svn keywords
[plcapi.git] / PLC / Methods / AddSiteAddress.py
1 # $Id$
2 # $URL$
3 from PLC.Faults import *
4 from PLC.Method import Method
5 from PLC.Parameter import Parameter, Mixed
6 from PLC.Addresses import Address, Addresses
7 from PLC.Auth import Auth
8 from PLC.Sites import Site, Sites
9
10 can_update = lambda (field, value): field in \
11              ['line1', 'line2', 'line3',
12               'city', 'state', 'postalcode', 'country']
13
14 class AddSiteAddress(Method):
15     """
16     Adds a new address to a site. Fields specified in
17     address_fields are used; some are not optional.
18
19     PIs may only add addresses to their own sites.
20
21     Returns the new address_id (> 0) if successful, faults otherwise.
22     """
23
24     roles = ['admin', 'pi']
25
26     address_fields = dict(filter(can_update, Address.fields.items()))
27
28     accepts = [
29         Auth(),
30         Mixed(Site.fields['site_id'],
31               Site.fields['login_base']),
32         address_fields
33         ]
34
35     returns = Parameter(int, 'New address_id (> 0) if successful')
36
37     def call(self, auth, site_id_or_login_base, address_fields):
38         address_fields = dict(filter(can_update, address_fields.items()))
39
40         # Get associated site details
41         sites = Sites(self.api, [site_id_or_login_base])
42         if not sites:
43             raise PLCInvalidArgument, "No such site"
44         site = sites[0]
45
46         if 'admin' not in self.caller['roles']:
47             if site['site_id'] not in self.caller['site_ids']:
48                 raise PLCPermissionDenied, "Address must be associated with one of your sites"
49
50         address = Address(self.api, address_fields)
51         address.sync(commit = False)
52         site.add_address(address, commit = True)
53
54         # Logging variables
55         self.event_objects = {'Site': [site['site_id']], 
56                               'Address': [address['address_id']]}
57         self.message = 'Address %d assigned to Site %d' % \
58                 (address['address_id'], site['site_id'])
59
60         return address['address_id']