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