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