forms.py 10.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# -*- coding:utf-8 -*
#
# Copyright 2016,2017
# - Skia <skia@libskia.so>
# - Sli <antoine@bartuccio.fr>
#
# Ce fichier fait partie du site de l'Association des Étudiants de l'UTBM,
# http://ae.utbm.fr.
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License a published by the Free Software
# Foundation; either version 3 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Sofware Foundation, Inc., 59 Temple
# Place - Suite 330, Boston, MA 02111-1307, USA.
#
#

from django.conf import settings
from django import forms
from django.utils.translation import ugettext_lazy as _

from ajax_select.fields import AutoCompleteSelectField, AutoCompleteSelectMultipleField

from club.models import Mailing, MailingSubscription, Club, Membership

from core.models import User
from core.views.forms import SelectDate, SelectDateTime
from counter.models import Counter


class ClubEditForm(forms.ModelForm):
    class Meta:
        model = Club
        fields = ["address", "logo", "short_description"]

    def __init__(self, *args, **kwargs):
        super(ClubEditForm, self).__init__(*args, **kwargs)
        self.fields["short_description"].widget = forms.Textarea()


49
50
51
52
53
54
55
class MailingForm(forms.Form):
    """
    Form handling mailing lists right
    """

    ACTION_NEW_MAILING = 1
    ACTION_NEW_SUBSCRIPTION = 2
56
    ACTION_REMOVE_SUBSCRIPTION = 3
57
58
59
60
61
62
63

    subscription_users = AutoCompleteSelectMultipleField(
        "users",
        label=_("Users to add"),
        help_text=_("Search users to add (one or more)."),
        required=False,
    )
64

65
    def __init__(self, club_id, user_id, mailings, *args, **kwargs):
66
67
        super(MailingForm, self).__init__(*args, **kwargs)

68
69
70
71
        self.fields["action"] = forms.TypedChoiceField(
            (
                (self.ACTION_NEW_MAILING, _("New Mailing")),
                (self.ACTION_NEW_SUBSCRIPTION, _("Subscribe")),
72
                (self.ACTION_REMOVE_SUBSCRIPTION, _("Remove")),
73
74
75
76
77
78
79
80
            ),
            coerce=int,
            label=_("Action"),
            initial=1,
            required=True,
            widget=forms.HiddenInput(),
        )

81
82
83
84
85
86
87
88
89
        # Generate bulk removal forms, they are never required
        for mailing in mailings:
            self.fields["removal_" + str(mailing.id)] = forms.ModelMultipleChoiceField(
                mailing.subscriptions.all(),
                label=_("Remove"),
                required=False,
                widget=forms.CheckboxSelectMultiple,
            )

90
        # Include fields for handling mailing creation
91
        mailing_fields = ("email",)
92
93
94
95
96
97
98
99
100
101
102
103
104
        self.fields.update(forms.fields_for_model(Mailing, fields=mailing_fields))
        for field in mailing_fields:
            self.fields["mailing_" + field] = self.fields.pop(field)
            self.fields["mailing_" + field].required = False

        # Include fields for handling subscription creation
        subscription_fields = ("mailing", "email")
        self.fields.update(
            forms.fields_for_model(MailingSubscription, fields=subscription_fields)
        )
        for field in subscription_fields:
            self.fields["subscription_" + field] = self.fields.pop(field)
            self.fields["subscription_" + field].required = False
105

106
107
108
109
        self.fields["subscription_mailing"].queryset = Mailing.objects.filter(
            club__id=club_id, is_moderated=True
        )

110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
    def check_required(self, cleaned_data, field):
        """
        If the given field doesn't exist or has no value, add a required error on it
        """
        if not cleaned_data.get(field, None):
            self.add_error(field, _("This field is required"))

    def clean_subscription_users(self):
        """
        Convert given users into real users and check their validity
        """
        cleaned_data = super(MailingForm, self).clean()
        users = []
        for user in cleaned_data["subscription_users"]:
            user = User.objects.filter(id=user).first()
            if not user:
                raise forms.ValidationError(
                    _("One of the selected users doesn't exist"), code="invalid"
                )
            if not user.email:
                raise forms.ValidationError(
                    _("One of the selected users doesn't have an email address"),
                    code="invalid",
                )
            users.append(user)
        return users

    def clean(self):
        cleaned_data = super(MailingForm, self).clean()

        if not "action" in cleaned_data:
            # If there is no action provided, we can stop here
            raise forms.ValidationError(_("An action is required"), code="invalid")

        if cleaned_data["action"] == self.ACTION_NEW_MAILING:
            self.check_required(cleaned_data, "mailing_email")

        if cleaned_data["action"] == self.ACTION_NEW_SUBSCRIPTION:
            self.check_required(cleaned_data, "subscription_mailing")
            if not cleaned_data.get(
                "subscription_users", None
            ) and not cleaned_data.get("subscription_email", None):
                raise forms.ValidationError(
                    _("You must specify at least an user or an email address"),
                    code="invalid",
                )

        return cleaned_data
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291


class SellingsFormBase(forms.Form):
    begin_date = forms.DateTimeField(
        ["%Y-%m-%d %H:%M:%S"],
        label=_("Begin date"),
        required=False,
        widget=SelectDateTime,
    )
    end_date = forms.DateTimeField(
        ["%Y-%m-%d %H:%M:%S"],
        label=_("End date"),
        required=False,
        widget=SelectDateTime,
    )
    counter = forms.ModelChoiceField(
        Counter.objects.order_by("name").all(), label=_("Counter"), required=False
    )


class ClubMemberForm(forms.Form):
    """
    Form handling the members of a club
    """

    error_css_class = "error"
    required_css_class = "required"

    users = AutoCompleteSelectMultipleField(
        "users",
        label=_("Users to add"),
        help_text=_("Search users to add (one or more)."),
        required=False,
    )

    def __init__(self, *args, **kwargs):
        self.club = kwargs.pop("club")
        self.request_user = kwargs.pop("request_user")
        self.club_members = kwargs.pop("club_members", None)
        if not self.club_members:
            self.club_members = (
                self.club.members.filter(end_date=None).order_by("-role").all()
            )
        self.request_user_membership = self.club.get_membership_for(self.request_user)
        super(ClubMemberForm, self).__init__(*args, **kwargs)

        # Using a ModelForm binds too much the form with the model and we don't want that
        # We want the view to process the model creation since they are multiple users
        # We also want the form to handle bulk deletion
        self.fields.update(
            forms.fields_for_model(
                Membership,
                fields=("role", "start_date", "description"),
                widgets={"start_date": SelectDate},
            )
        )

        # Role is required only if users is specified
        self.fields["role"].required = False

        # Start date and description are never really required
        self.fields["start_date"].required = False
        self.fields["description"].required = False

        self.fields["users_old"] = forms.ModelMultipleChoiceField(
            User.objects.filter(
                id__in=[
                    ms.user.id
                    for ms in self.club_members
                    if ms.can_be_edited_by(
                        self.request_user, self.request_user_membership
                    )
                ]
            ).all(),
            label=_("Mark as old"),
            required=False,
            widget=forms.CheckboxSelectMultiple,
        )
        if not self.request_user.is_root:
            self.fields.pop("start_date")

    def clean_users(self):
        """
            Check that the user is not trying to add an user already in the club
            Also check that the user is valid and has a valid subscription
        """
        cleaned_data = super(ClubMemberForm, self).clean()
        users = []
        for user_id in cleaned_data["users"]:
            user = User.objects.filter(id=user_id).first()
            if not user:
                raise forms.ValidationError(
                    _("One of the selected users doesn't exist"), code="invalid"
                )
            if not user.is_subscribed:
                raise forms.ValidationError(
                    _("User must be subscriber to take part to a club"), code="invalid"
                )
            if self.club.get_membership_for(user):
                raise forms.ValidationError(
                    _("You can not add the same user twice"), code="invalid"
                )
            users.append(user)
        return users

    def clean(self):
        """
            Check user rights for adding an user
        """
        cleaned_data = super(ClubMemberForm, self).clean()

        if "start_date" in cleaned_data and not cleaned_data["start_date"]:
            # Drop start_date if allowed to edition but not specified
            cleaned_data.pop("start_date")

        if not cleaned_data.get("users"):
            # No user to add equals no check needed
            return cleaned_data

        if cleaned_data.get("role", "") == "":
            # Role is required if users exists
            self.add_error("role", _("You should specify a role"))
            return cleaned_data

        request_user = self.request_user
        membership = self.request_user_membership
        if not (
            cleaned_data["role"] <= settings.SITH_MAXIMUM_FREE_ROLE
            or (membership is not None and membership.role >= cleaned_data["role"])
            or request_user.is_board_member
            or request_user.is_root
        ):
            raise forms.ValidationError(_("You do not have the permission to do that"))
        return cleaned_data