819d4e42dd877d4afc6796aed7c7af9c352224cc
[plcapi.git] / PLC / Methods / AddPersonTag.py
1 #
2 # Thierry Parmentelat - INRIA
3 #
4 from PLC.Faults import *
5 from PLC.Method import Method
6 from PLC.Parameter import Parameter, Mixed
7 from PLC.Auth import Auth
8
9 from PLC.Persons import Person, Persons
10 from PLC.TagTypes import TagType, TagTypes
11 from PLC.PersonTags import PersonTag, PersonTags
12
13
14 class AddPersonTag(Method):
15     """
16     Sets the specified setting for the specified person
17     to the specified value.
18
19     Admins have full access.  Non-admins can change their own tags.
20
21     Returns the new person_tag_id (> 0) if successful, faults
22     otherwise.
23     """
24
25     roles = ['admin', 'pi', 'tech', 'user']
26
27     accepts = [
28         Auth(),
29         # no other way to refer to a person
30         PersonTag.fields['person_id'],
31         Mixed(TagType.fields['tag_type_id'],
32               TagType.fields['tagname']),
33         PersonTag.fields['value'],
34         ]
35
36     returns = Parameter(int, 'New person_tag_id (> 0) if successful')
37
38     def call(self, auth, person_id, tag_type_id_or_name, value):
39         persons = Persons(self.api, [person_id])
40         if not persons:
41             raise PLCInvalidArgument, "No such person %r"%person_id
42         person = persons[0]
43
44         tag_types = TagTypes(self.api, [tag_type_id_or_name])
45         if not tag_types:
46             raise PLCInvalidArgument, "No such tag type %r"%tag_type_id_or_name
47         tag_type = tag_types[0]
48
49         # checks for existence - does not allow several different settings
50         conflicts = PersonTags(self.api, {'person_id':person['person_id'],
51                                           'tag_type_id':tag_type['tag_type_id']})
52
53         if len(conflicts) :
54             raise PLCInvalidArgument, "Person %d (%s) already has setting %d"% \
55                 (person['person_id'],person['email'], tag_type['tag_type_id'])
56
57         # check authorizations
58         person.caller_may_write_tag (self.api,self.caller,tag_type)
59
60         person_tag = PersonTag(self.api)
61         person_tag['person_id'] = person['person_id']
62         person_tag['tag_type_id'] = tag_type['tag_type_id']
63         person_tag['value'] = value
64
65         person_tag.sync()
66         self.object_ids = [person_tag['person_tag_id']]
67
68         return person_tag['person_tag_id']