source: main/trunk/openPLM/plmapp/controllers/group.py @ 371

Revision 371, 7.3 KB checked in by pcosquer, 8 years ago (diff)

groups: add invitation

Line 
1############################################################################
2# openPLM - open source PLM
3# Copyright 2010 Philippe Joulaud, Pierre Cosquer
4#
5# This file is part of openPLM.
6#
7#    openPLM is free software: you can redistribute it and/or modify
8#    it under the terms of the GNU General Public License as published by
9#    the Free Software Foundation, either version 3 of the License, or
10#    (at your option) any later version.
11#
12#    openPLM is distributed in the hope that it will be useful,
13#    but WITHOUT ANY WARRANTY; without even the implied warranty of
14#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15#    GNU General Public License for more details.
16#
17#    You should have received a copy of the GNU General Public License
18#    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
19#
20# Contact :
21#    Philippe Joulaud : ninoo.fr@gmail.com
22#    Pierre Cosquer : pierre.cosquer@insa-rennes.fr
23################################################################################
24
25"""
26This module contains a class called :class:`GroupController` which
27provides a controller for :class:`~django.contrib.auth.models.Group`.
28This class is similar to :class:`.PLMObjectController` but some methods
29from :class:`.PLMObjectController` are not defined.
30"""
31
32import datetime
33
34import openPLM.plmapp.models as models
35from openPLM.plmapp.mail import send_mail
36from openPLM.plmapp.exceptions import PermissionError
37from openPLM.plmapp.controllers.base import Controller, permission_required
38
39class GroupController(Controller):
40    u"""
41    Object used to manage a :class:`~django.contrib.auth.models.Group` and store his
42    modification in an history
43   
44    :attributes:
45        .. attribute:: object
46
47            The :class:`~django.contrib.auth.models.Group` managed by the controller
48
49    :param obj: managed object
50    :type obj: an instance of :class:`~django.contrib.auth.models.Group`
51    :param user: user who modify *obj*
52    :type user: :class:`~django.contrib.auth.models.Group`
53
54    .. note::
55        This class does not inherit from :class:`.PLMObjectController`.
56
57    """
58
59    HISTORY = models.GroupHistory
60
61    def __init__(self, obj, user):
62        if hasattr(obj, "groupinfo"):
63            obj = obj.groupinfo
64        super(GroupController, self).__init__(obj, user)
65   
66    @classmethod
67    def create(cls, name, description, user, data={}):
68        obj = models.GroupInfo(name=name, description=description)
69        obj.creator = user
70        obj.owner = user
71        if data:
72            for key, value in data.iteritems():
73                if key not in ["name", "description"]:
74                    setattr(obj, key, value)
75        obj.save()
76        infos = {"name" : name, "description" : description}
77        infos.update(data)
78        details = ",".join("%s : %s" % (k, v) for k, v in infos.items())
79        res = cls(obj, user)
80        user.groups.add(obj)
81        res._save_histo("Create", details)
82        return res
83
84    @classmethod
85    def create_from_form(cls, form, user):
86        u"""
87        Creates a :class:`PLMObjectController` from *form* and associates *user*
88        as the creator/owner of the PLMObject.
89       
90        This method raises :exc:`ValueError` if *form* is invalid.
91
92        :param form: a django form associated to a model
93        :param user: user who creates/owns the object
94        :rtype: :class:`PLMObjectController`
95        """
96        if form.is_valid():
97            name = form.cleaned_data["name"]
98            desc = form.cleaned_data["description"]
99            obj = cls.create(name, desc, user)
100            return obj
101        else:
102            raise ValueError("form is invalid")
103
104
105    def has_permission(self, role):
106        if role == models.ROLE_OWNER:
107            return self.owner == self._user
108        return False
109
110    def update_users(self, formset):
111        u"""
112        Updates users with data from *formset*
113       
114        :param formset:
115        :type formset: a formset_factory of
116                        :class:`~plmapp.forms.ModifyUserForm`
117       
118        :raises: :exc:`.PermissionError` if :attr:`_user` is not the owner of
119            :attr:`object`.
120        """
121       
122        self.check_permission("owner")
123        users = []
124        if formset.is_valid():
125            for form in formset.forms:
126                group = form.cleaned_data["group"]
127                if group.pk != self.object.pk:
128                    raise ValueError("Bad group %s (%s expected)" % (group, self.object))
129                delete = form.cleaned_data["delete"]
130                user = form.cleaned_data["user"]
131                if user == self.owner:
132                    raise ValueError("Bad user %s" % user)
133                if delete:
134                    users.append(user)
135            for user in users:
136                user.groups.remove(group)
137            self._save_histo("User removed", ", ".join((u.username for u in users)))
138       
139    @permission_required(role=models.ROLE_OWNER)
140    def add_user(self, user):
141        """
142        Adds *user* to the group.
143        """
144        if not user.email:
145            raise ValueError("user's email is empty")
146        inv = models.Invitation.objects.create(group=self.object, owner=self._user,
147                guest=user, guest_asked=False)
148        ctx = { "group" : self.object,
149                "invitation" : inv,
150                }
151        subject = "[PLM] Invitation to join the group %s" % self.name
152        send_mail(subject, [user], ctx, "mails/invitation1")
153
154    def ask_to_join(self):
155        """
156        Adds *user* to the group.
157        """
158        if not self.owner.email:
159            raise ValueError("user's email is empty")
160        inv = models.Invitation.objects.create(group=self.object, owner=self.owner,
161                guest=self._user, guest_asked=True)
162        ctx = { "group" : self.object,
163                "invitation" : inv,
164                "guest" : self._user
165                }
166        subject = "[PLM] %s ask you to join the group %s" % (self._user, self.name)
167        send_mail(subject, [self.owner], ctx, "mails/invitation2")
168
169
170    def accept_invitation(self, invitation):
171        if invitation.state != models.Invitation.PENDING:
172            raise ValueError("Invalid invitation")
173        if invitation.guest_asked:
174            if self._user != invitation.owner:
175                raise PermissionError("You can not accept this invitation.")
176        else:
177            if self._user != invitation.guest:
178                raise PermissionError("You can not accept this invitation.")
179           
180        invitation.state = models.Invitation.ACCEPTED
181        invitation.validation_time = datetime.datetime.now()
182
183        user = invitation.guest
184        user.groups.add(self.object)
185        self._save_histo("User added", user.username, users=(user,))
186
187    def refuse_invitation(self, invitation):
188        if invitation.state != models.Invitation.PENDING:
189            raise ValueError("Invalid invitation")
190        if invitation.guest_asked:
191            if self._user != invitation.owner:
192                raise PermissionError("You can not refuse this invitation.")
193        else:
194            if self._user != invitation.guest:
195                raise PermissionError("You can not refuse this invitation.")
196        invitation.state = models.Invitation.REFUSED
197        invitation.validation_time = datetime.datetime.now()
198        # TODO mail
199
Note: See TracBrowser for help on using the repository browser.