views.py 22.8 KB
Newer Older
1
2
3
4
# -*- coding:utf-8 -*
#
# Copyright 2016,2017
# - Skia <skia@libskia.so>
Sli's avatar
Sli committed
5
# - Sli <antoine@bartuccio.fr>
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#
# 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.
#
#

26
27

from django.conf import settings
Skia's avatar
Skia committed
28
from django import forms
Sli's avatar
Sli committed
29
from django.views.generic import ListView, DetailView, TemplateView, View
Sli's avatar
Sli committed
30
from django.views.generic.edit import DeleteView
Sli's avatar
Sli committed
31
from django.views.generic.detail import SingleObjectMixin
Skia's avatar
Skia committed
32
from django.views.generic.edit import UpdateView, CreateView
33
from django.http import HttpResponseRedirect, HttpResponse, Http404
Sli's avatar
Sli committed
34
from django.core.urlresolvers import reverse, reverse_lazy
Skia's avatar
Skia committed
35
from django.utils import timezone
Skia's avatar
Skia committed
36
from django.utils.translation import ugettext_lazy as _
Sli's avatar
Sli committed
37
from django.utils.translation import ugettext as _t
38
from django.core.exceptions import PermissionDenied, ValidationError, NON_FIELD_ERRORS
Sli's avatar
Sli committed
39
from django.shortcuts import get_object_or_404, redirect
Skia's avatar
Skia committed
40

Sli's avatar
Sli committed
41
42
43
44
45
46
47
from core.views import (
    CanCreateMixin,
    CanViewMixin,
    CanEditMixin,
    CanEditPropMixin,
    TabedViewMixin,
    PageEditViewBase,
48
    DetailFormView,
Sli's avatar
Sli committed
49
)
50
51
52
53
from core.models import PageRev

from counter.models import Selling

Sli's avatar
Sli committed
54
55
56
57
58
59
from com.views import (
    PosterListBaseView,
    PosterCreateBaseView,
    PosterEditBaseView,
    PosterDeleteBaseView,
)
Sli's avatar
Sli committed
60

61
from club.models import Club, Membership, Mailing, MailingSubscription
62
from club.forms import MailingForm, ClubEditForm, ClubMemberForm
Sli's avatar
Sli committed
63

64

65
66
class ClubTabsMixin(TabedViewMixin):
    def get_tabs_title(self):
67
68
69
        obj = self.get_object()
        if isinstance(obj, PageRev):
            self.object = obj.page.club
70
71
72
73
        return self.object.get_display_name()

    def get_list_of_tabs(self):
        tab_list = []
Sli's avatar
Sli committed
74
75
76
77
78
79
80
        tab_list.append(
            {
                "url": reverse("club:club_view", kwargs={"club_id": self.object.id}),
                "slug": "infos",
                "name": _("Infos"),
            }
        )
81
        if self.request.user.can_view(self.object):
Sli's avatar
Sli committed
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
            tab_list.append(
                {
                    "url": reverse(
                        "club:club_members", kwargs={"club_id": self.object.id}
                    ),
                    "slug": "members",
                    "name": _("Members"),
                }
            )
            tab_list.append(
                {
                    "url": reverse(
                        "club:club_old_members", kwargs={"club_id": self.object.id}
                    ),
                    "slug": "elderlies",
                    "name": _("Old members"),
                }
            )
100
        if self.object.page:
Sli's avatar
Sli committed
101
102
103
104
105
106
107
108
109
            tab_list.append(
                {
                    "url": reverse(
                        "club:club_hist", kwargs={"club_id": self.object.id}
                    ),
                    "slug": "history",
                    "name": _("History"),
                }
            )
110
        if self.request.user.can_edit(self.object):
Sli's avatar
Sli committed
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
            tab_list.append(
                {
                    "url": reverse("club:tools", kwargs={"club_id": self.object.id}),
                    "slug": "tools",
                    "name": _("Tools"),
                }
            )
            tab_list.append(
                {
                    "url": reverse(
                        "club:club_edit", kwargs={"club_id": self.object.id}
                    ),
                    "slug": "edit",
                    "name": _("Edit"),
                }
            )
127
            if self.object.page and self.request.user.can_edit(self.object.page):
Sli's avatar
Sli committed
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
158
159
160
161
162
                tab_list.append(
                    {
                        "url": reverse(
                            "core:page_edit",
                            kwargs={"page_name": self.object.page.get_full_name()},
                        ),
                        "slug": "page_edit",
                        "name": _("Edit club page"),
                    }
                )
            tab_list.append(
                {
                    "url": reverse(
                        "club:club_sellings", kwargs={"club_id": self.object.id}
                    ),
                    "slug": "sellings",
                    "name": _("Sellings"),
                }
            )
            tab_list.append(
                {
                    "url": reverse("club:mailing", kwargs={"club_id": self.object.id}),
                    "slug": "mailing",
                    "name": _("Mailing list"),
                }
            )
            tab_list.append(
                {
                    "url": reverse(
                        "club:poster_list", kwargs={"club_id": self.object.id}
                    ),
                    "slug": "posters",
                    "name": _("Posters list"),
                }
            )
163
        if self.request.user.is_owner(self.object):
Sli's avatar
Sli committed
164
165
166
167
168
169
170
171
172
            tab_list.append(
                {
                    "url": reverse(
                        "club:club_prop", kwargs={"club_id": self.object.id}
                    ),
                    "slug": "props",
                    "name": _("Props"),
                }
            )
173
174
        return tab_list

Krophil's avatar
Krophil committed
175

Skia's avatar
Skia committed
176
class ClubListView(ListView):
Skia's avatar
Skia committed
177
178
179
    """
    List the Clubs
    """
Sli's avatar
Sli committed
180

181
    model = Club
Sli's avatar
Sli committed
182
    template_name = "club/club_list.jinja"
183

Krophil's avatar
Krophil committed
184

185
class ClubView(ClubTabsMixin, DetailView):
Skia's avatar
Skia committed
186
187
188
    """
    Front page of a Club
    """
Sli's avatar
Sli committed
189

190
191
    model = Club
    pk_url_kwarg = "club_id"
Sli's avatar
Sli committed
192
    template_name = "club/club_detail.jinja"
193
    current_tab = "infos"
194

195
196
197
    def get_context_data(self, **kwargs):
        kwargs = super(ClubView, self).get_context_data(**kwargs)
        if self.object.page and self.object.page.revisions.exists():
Sli's avatar
Sli committed
198
            kwargs["page_revision"] = self.object.page.revisions.last().content
199
200
201
202
203
204
205
        return kwargs


class ClubRevView(ClubView):
    """
    Display a specific page revision
    """
Sli's avatar
Sli committed
206

207
208
    def dispatch(self, request, *args, **kwargs):
        obj = self.get_object()
Sli's avatar
Sli committed
209
        self.revision = get_object_or_404(PageRev, pk=kwargs["rev_id"], page__club=obj)
210
211
212
213
        return super(ClubRevView, self).dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        kwargs = super(ClubRevView, self).get_context_data(**kwargs)
Sli's avatar
Sli committed
214
        kwargs["page_revision"] = self.revision.content
215
216
217
218
        return kwargs


class ClubPageEditView(ClubTabsMixin, PageEditViewBase):
Sli's avatar
Sli committed
219
    template_name = "club/pagerev_edit.jinja"
220
221
222
    current_tab = "page_edit"

    def dispatch(self, request, *args, **kwargs):
Sli's avatar
Sli committed
223
        self.club = get_object_or_404(Club, pk=kwargs["club_id"])
224
225
226
227
228
229
230
231
232
        if not self.club.page:
            raise Http404
        return super(ClubPageEditView, self).dispatch(request, *args, **kwargs)

    def get_object(self):
        self.page = self.club.page
        return self._get_revision()

    def get_success_url(self, **kwargs):
Sli's avatar
Sli committed
233
        return reverse_lazy("club:club_view", kwargs={"club_id": self.club.id})
234
235
236
237
238
239


class ClubPageHistView(ClubTabsMixin, CanViewMixin, DetailView):
    """
    Modification hostory of the page
    """
Sli's avatar
Sli committed
240

241
242
    model = Club
    pk_url_kwarg = "club_id"
Sli's avatar
Sli committed
243
    template_name = "club/page_history.jinja"
244
245
    current_tab = "history"

Krophil's avatar
Krophil committed
246

247
class ClubToolsView(ClubTabsMixin, CanEditMixin, DetailView):
Skia's avatar
Skia committed
248
249
250
    """
    Tools page of a Club
    """
Sli's avatar
Sli committed
251

Skia's avatar
Skia committed
252
253
    model = Club
    pk_url_kwarg = "club_id"
Sli's avatar
Sli committed
254
    template_name = "club/club_tools.jinja"
255
    current_tab = "tools"
Skia's avatar
Skia committed
256

Krophil's avatar
Krophil committed
257

258
class ClubMembersView(ClubTabsMixin, CanViewMixin, DetailFormView):
Skia's avatar
Skia committed
259
260
261
    """
    View of a club's members
    """
Sli's avatar
Sli committed
262

263
264
    model = Club
    pk_url_kwarg = "club_id"
Skia's avatar
Skia committed
265
    form_class = ClubMemberForm
Sli's avatar
Sli committed
266
    template_name = "club/club_members.jinja"
267
    current_tab = "members"
268

269
270
    def get_form_kwargs(self):
        kwargs = super(ClubMembersView, self).get_form_kwargs()
271
        kwargs["request_user"] = self.request.user
272
        kwargs["club"] = self.get_object()
Sli's avatar
Sli committed
273
        kwargs["club_members"] = self.members
274
275
276
277
        return kwargs

    def get_context_data(self, *args, **kwargs):
        kwargs = super(ClubMembersView, self).get_context_data(*args, **kwargs)
Sli's avatar
Sli committed
278
        kwargs["members"] = self.members
279
        return kwargs
Skia's avatar
Skia committed
280

281
    def form_valid(self, form):
Sli's avatar
Sli committed
282
283
284
        """
            Check user rights
        """
285
286
287
288
        resp = super(ClubMembersView, self).form_valid(form)

        data = form.clean()
        users = data.pop("users", [])
Sli's avatar
Sli committed
289
        users_old = data.pop("users_old", [])
290
291
        for user in users:
            Membership(club=self.get_object(), user=user, **data).save()
Sli's avatar
Sli committed
292
293
294
295
        for user in users_old:
            membership = self.get_object().get_membership_for(user)
            membership.end_date = timezone.now()
            membership.save()
296
        return resp
Sli's avatar
Sli committed
297

298
    def dispatch(self, request, *args, **kwargs):
Sli's avatar
Sli committed
299
300
301
        self.members = (
            self.get_object().members.filter(end_date=None).order_by("-role").all()
        )
302
303
304
        return super(ClubMembersView, self).dispatch(request, *args, **kwargs)

    def get_success_url(self, **kwargs):
305
306
307
        return reverse_lazy(
            "club:club_members", kwargs={"club_id": self.get_object().id}
        )
308

Krophil's avatar
Krophil committed
309

310
class ClubOldMembersView(ClubTabsMixin, CanViewMixin, DetailView):
Skia's avatar
Skia committed
311
312
313
    """
    Old members of a club
    """
Sli's avatar
Sli committed
314

Skia's avatar
Skia committed
315
316
    model = Club
    pk_url_kwarg = "club_id"
Sli's avatar
Sli committed
317
    template_name = "club/club_old_members.jinja"
318
    current_tab = "elderlies"
Skia's avatar
Skia committed
319

Krophil's avatar
Krophil committed
320

Skia's avatar
Skia committed
321
322
323
324
class ClubSellingView(ClubTabsMixin, CanEditMixin, DetailView):
    """
    Sellings of a club
    """
Sli's avatar
Sli committed
325

Skia's avatar
Skia committed
326
327
    model = Club
    pk_url_kwarg = "club_id"
Sli's avatar
Sli committed
328
    template_name = "club/club_sellings.jinja"
Skia's avatar
Skia committed
329
330
331
332
    current_tab = "sellings"

    def get_form_class(self):
        kwargs = {
Sli's avatar
Sli committed
333
334
335
336
337
            "product": forms.ModelChoiceField(
                self.object.products.order_by("name").all(),
                label=_("Product"),
                required=False,
            )
Krophil's avatar
Krophil committed
338
        }
Sli's avatar
Sli committed
339
        return type("SellingsForm", (SellingsFormBase,), kwargs)
Skia's avatar
Skia committed
340
341
342

    def get_context_data(self, **kwargs):
        kwargs = super(ClubSellingView, self).get_context_data(**kwargs)
Skia's avatar
Skia committed
343
        form = self.get_form_class()(self.request.GET)
Skia's avatar
Skia committed
344
345
        qs = Selling.objects.filter(club=self.object)
        if form.is_valid():
Skia's avatar
Skia committed
346
347
            if not len([v for v in form.cleaned_data.values() if v is not None]):
                qs = Selling.objects.filter(id=-1)
Sli's avatar
Sli committed
348
349
350
351
352
353
354
355
356
357
358
359
360
361
            if form.cleaned_data["begin_date"]:
                qs = qs.filter(date__gte=form.cleaned_data["begin_date"])
            if form.cleaned_data["end_date"]:
                qs = qs.filter(date__lte=form.cleaned_data["end_date"])
            if form.cleaned_data["counter"]:
                qs = qs.filter(counter=form.cleaned_data["counter"])
            if form.cleaned_data["product"]:
                qs = qs.filter(product__id=form.cleaned_data["product"].id)
            kwargs["result"] = qs.all().order_by("-id")
            kwargs["total"] = sum([s.quantity * s.unit_price for s in qs.all()])
            kwargs["total_quantity"] = sum([s.quantity for s in qs.all()])
            kwargs["benefit"] = kwargs["total"] - sum(
                [s.product.purchase_price for s in qs.exclude(product=None)]
            )
Skia's avatar
Skia committed
362
        else:
Sli's avatar
Sli committed
363
364
            kwargs["result"] = qs[:0]
        kwargs["form"] = form
Skia's avatar
Skia committed
365
366
        return kwargs

Krophil's avatar
Krophil committed
367

Sli's avatar
Sli committed
368
369
370
371
372
373
374
class ClubSellingCSVView(ClubSellingView):
    """
    Generate sellings in csv for a given period
    """

    def get(self, request, *args, **kwargs):
        import csv
Sli's avatar
Sli committed
375
376

        response = HttpResponse(content_type="text/csv")
Sli's avatar
Sli committed
377
378
        self.object = self.get_object()
        name = _("Sellings") + "_" + self.object.name + ".csv"
Sli's avatar
Sli committed
379
        response["Content-Disposition"] = "filename=" + name
Sli's avatar
Sli committed
380
        kwargs = self.get_context_data(**kwargs)
Sli's avatar
Sli committed
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
        writer = csv.writer(
            response, delimiter=";", lineterminator="\n", quoting=csv.QUOTE_ALL
        )

        writer.writerow([_t("Quantity"), kwargs["total_quantity"]])
        writer.writerow([_t("Total"), kwargs["total"]])
        writer.writerow([_t("Benefit"), kwargs["benefit"]])
        writer.writerow(
            [
                _t("Date"),
                _t("Counter"),
                _t("Barman"),
                _t("Customer"),
                _t("Label"),
                _t("Quantity"),
                _t("Total"),
                _t("Payment method"),
                _t("Selling price"),
                _t("Purchase price"),
                _t("Benefit"),
            ]
        )
        for o in kwargs["result"]:
Sli's avatar
Sli committed
404
405
406
            row = [o.date, o.counter]
            if o.seller:
                row.append(o.seller.get_display_name())
Krophil's avatar
Krophil committed
407
            else:
Sli's avatar
Sli committed
408
                row.append("")
Sli's avatar
Sli committed
409
410
            if o.customer:
                row.append(o.customer.user.get_display_name())
Krophil's avatar
Krophil committed
411
            else:
Sli's avatar
Sli committed
412
413
414
415
416
417
418
                row.append("")
            row = row + [
                o.label,
                o.quantity,
                o.quantity * o.unit_price,
                o.get_payment_method_display(),
            ]
Sli's avatar
Sli committed
419
420
421
422
            if o.product:
                row.append(o.product.selling_price)
                row.append(o.product.purchase_price)
                row.append(o.product.selling_price - o.product.purchase_price)
Krophil's avatar
Krophil committed
423
            else:
Sli's avatar
Sli committed
424
                row = row + ["", "", ""]
Sli's avatar
Sli committed
425
426
427
428
            writer.writerow(row)

        return response

Krophil's avatar
Krophil committed
429

430
class ClubEditView(ClubTabsMixin, CanEditMixin, UpdateView):
Skia's avatar
Skia committed
431
432
433
    """
    Edit a Club's main informations (for the club's members)
    """
Sli's avatar
Sli committed
434

Skia's avatar
Skia committed
435
436
    model = Club
    pk_url_kwarg = "club_id"
437
    form_class = ClubEditForm
Sli's avatar
Sli committed
438
    template_name = "core/edit.jinja"
439
    current_tab = "edit"
Skia's avatar
Skia committed
440

Krophil's avatar
Krophil committed
441

442
class ClubEditPropView(ClubTabsMixin, CanEditPropMixin, UpdateView):
Skia's avatar
Skia committed
443
444
445
    """
    Edit the properties of a Club object (for the Sith admins)
    """
Sli's avatar
Sli committed
446

447
448
    model = Club
    pk_url_kwarg = "club_id"
Sli's avatar
Sli committed
449
450
    fields = ["name", "unix_name", "parent", "is_active"]
    template_name = "core/edit.jinja"
451
    current_tab = "props"
Skia's avatar
Skia committed
452

Krophil's avatar
Krophil committed
453

Skia's avatar
Skia committed
454
455
456
457
class ClubCreateView(CanEditPropMixin, CreateView):
    """
    Create a club (for the Sith admin)
    """
Sli's avatar
Sli committed
458

Skia's avatar
Skia committed
459
460
    model = Club
    pk_url_kwarg = "club_id"
Sli's avatar
Sli committed
461
462
    fields = ["name", "unix_name", "parent"]
    template_name = "core/edit.jinja"
Skia's avatar
Skia committed
463

Krophil's avatar
Krophil committed
464

Skia's avatar
Skia committed
465
466
467
468
class MembershipSetOldView(CanEditMixin, DetailView):
    """
    Set a membership as beeing old
    """
Sli's avatar
Sli committed
469

Skia's avatar
Skia committed
470
471
472
473
474
475
476
    model = Membership
    pk_url_kwarg = "membership_id"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.end_date = timezone.now()
        self.object.save()
Sli's avatar
Sli committed
477
478
479
480
481
482
483
        return HttpResponseRedirect(
            reverse(
                "club:club_members",
                args=self.args,
                kwargs={"club_id": self.object.club.id},
            )
        )
Skia's avatar
Skia committed
484
485
486

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
Sli's avatar
Sli committed
487
488
489
490
491
492
493
        return HttpResponseRedirect(
            reverse(
                "club:club_members",
                args=self.args,
                kwargs={"club_id": self.object.club.id},
            )
        )
Skia's avatar
Skia committed
494

Krophil's avatar
Krophil committed
495

Skia's avatar
Skia committed
496
class ClubStatView(TemplateView):
Krophil's avatar
Krophil committed
497
    template_name = "club/stats.jinja"
Skia's avatar
Skia committed
498
499
500

    def get_context_data(self, **kwargs):
        kwargs = super(ClubStatView, self).get_context_data(**kwargs)
Sli's avatar
Sli committed
501
        kwargs["club_list"] = Club.objects.all()
Skia's avatar
Skia committed
502
        return kwargs
Sli's avatar
Sli committed
503
504


505
class ClubMailingView(ClubTabsMixin, CanEditMixin, DetailFormView):
Sli's avatar
Sli committed
506
507
508
    """
    A list of mailing for a given club
    """
Sli's avatar
Sli committed
509

510
511
512
    model = Club
    form_class = MailingForm
    pk_url_kwarg = "club_id"
Sli's avatar
Sli committed
513
    template_name = "club/mailing.jinja"
Sli's avatar
Sli committed
514
    current_tab = "mailing"
Sli's avatar
Sli committed
515

516
517
    def get_form_kwargs(self):
        kwargs = super(ClubMailingView, self).get_form_kwargs()
518
519
        kwargs["club_id"] = self.get_object().id
        kwargs["user_id"] = self.request.user.id
520
        kwargs["mailings"] = self.mailings
521
522
        return kwargs

523
524
525
526
    def dispatch(self, request, *args, **kwargs):
        self.mailings = Mailing.objects.filter(club_id=self.get_object().id).all()
        return super(ClubMailingView, self).dispatch(request, *args, **kwargs)

Sli's avatar
Sli committed
527
528
    def get_context_data(self, **kwargs):
        kwargs = super(ClubMailingView, self).get_context_data(**kwargs)
529
530
        kwargs["club"] = self.get_object()
        kwargs["user"] = self.request.user
531
        kwargs["mailings"] = self.mailings
532
533
534
        kwargs["mailings_moderated"] = (
            kwargs["mailings"].exclude(is_moderated=False).all()
        )
535
536
537
        kwargs["mailings_not_moderated"] = (
            kwargs["mailings"].exclude(is_moderated=True).all()
        )
538
539
540
        kwargs["form_actions"] = {
            "NEW_MALING": self.form_class.ACTION_NEW_MAILING,
            "NEW_SUBSCRIPTION": self.form_class.ACTION_NEW_SUBSCRIPTION,
541
            "REMOVE_SUBSCRIPTION": self.form_class.ACTION_REMOVE_SUBSCRIPTION,
542
        }
Sli's avatar
Sli committed
543
544
        return kwargs

545
    def add_new_mailing(self, cleaned_data) -> ValidationError:
546
547
548
549
        """
        Create a new mailing list from the form
        """
        mailing = Mailing(
550
            club=self.get_object(),
551
            email=cleaned_data["mailing_email"],
552
            moderator=self.request.user,
553
554
            is_moderated=False,
        )
555
556
557
558
        try:
            mailing.clean()
        except ValidationError as validation_error:
            return validation_error
559
        mailing.save()
560
        return None
Sli's avatar
Sli committed
561

562
    def add_new_subscription(self, cleaned_data) -> ValidationError:
563
564
565
        """
        Add mailing subscriptions for each user given and/or for the specified email in form
        """
Sli's avatar
Sli committed
566
567
        users_to_save = []

568
569
570
571
        for user in cleaned_data["subscription_users"]:
            sub = MailingSubscription(
                mailing=cleaned_data["subscription_mailing"], user=user
            )
Sli's avatar
Sli committed
572
573
574
575
576
577
            try:
                sub.clean()
            except ValidationError as validation_error:
                return validation_error

            users_to_save.append(sub.save())
Sli's avatar
Sli committed
578

579
580
581
582
583
        if cleaned_data["subscription_email"]:
            sub = MailingSubscription(
                mailing=cleaned_data["subscription_mailing"],
                email=cleaned_data["subscription_email"],
            )
584
585

        try:
586
            sub.clean()
587
588
589
590
        except ValidationError as validation_error:
            return validation_error
        sub.save()

Sli's avatar
Sli committed
591
592
593
594
        # Save users after we are sure there is no error
        for user in users_to_save:
            user.save()

595
        return None
Sli's avatar
Sli committed
596

597
598
599
600
601
602
603
604
605
606
607
608
609
    def remove_subscription(self, cleaned_data):
        """
        Remove specified users from a mailing list
        """
        fields = [
            cleaned_data[key]
            for key in cleaned_data.keys()
            if key.startswith("removal_")
        ]
        for field in fields:
            for sub in field:
                sub.delete()

610
611
    def form_valid(self, form):
        resp = super(ClubMailingView, self).form_valid(form)
Sli's avatar
Sli committed
612

613
        cleaned_data = form.clean()
614
        error = None
Sli's avatar
Sli committed
615

616
        if cleaned_data["action"] == self.form_class.ACTION_NEW_MAILING:
617
            error = self.add_new_mailing(cleaned_data)
Sli's avatar
Sli committed
618

619
        if cleaned_data["action"] == self.form_class.ACTION_NEW_SUBSCRIPTION:
620
            error = self.add_new_subscription(cleaned_data)
621

622
623
624
        if cleaned_data["action"] == self.form_class.ACTION_REMOVE_SUBSCRIPTION:
            self.remove_subscription(cleaned_data)

625
626
627
628
        if error:
            form.add_error(NON_FIELD_ERRORS, error)
            return self.form_invalid(form)

629
        return resp
Sli's avatar
Sli committed
630
631

    def get_success_url(self, **kwargs):
632
        return reverse_lazy("club:mailing", kwargs={"club_id": self.get_object().id})
Sli's avatar
Sli committed
633
634
635
636
637


class MailingDeleteView(CanEditMixin, DeleteView):

    model = Mailing
Sli's avatar
Sli committed
638
    template_name = "core/delete_confirm.jinja"
Sli's avatar
Sli committed
639
    pk_url_kwarg = "mailing_id"
Sli's avatar
Sli committed
640
    redirect_page = None
Sli's avatar
Sli committed
641
642
643
644
645
646

    def dispatch(self, request, *args, **kwargs):
        self.club_id = self.get_object().club.id
        return super(MailingDeleteView, self).dispatch(request, *args, **kwargs)

    def get_success_url(self, **kwargs):
Sli's avatar
Sli committed
647
648
649
        if self.redirect_page:
            return reverse_lazy(self.redirect_page)
        else:
Sli's avatar
Sli committed
650
            return reverse_lazy("club:mailing", kwargs={"club_id": self.club_id})
Sli's avatar
Sli committed
651
652
653
654
655


class MailingSubscriptionDeleteView(CanEditMixin, DeleteView):

    model = MailingSubscription
Sli's avatar
Sli committed
656
    template_name = "core/delete_confirm.jinja"
Sli's avatar
Sli committed
657
658
659
660
    pk_url_kwarg = "mailing_subscription_id"

    def dispatch(self, request, *args, **kwargs):
        self.club_id = self.get_object().mailing.club.id
Sli's avatar
Sli committed
661
662
663
        return super(MailingSubscriptionDeleteView, self).dispatch(
            request, *args, **kwargs
        )
Sli's avatar
Sli committed
664
665

    def get_success_url(self, **kwargs):
Sli's avatar
Sli committed
666
        return reverse_lazy("club:mailing", kwargs={"club_id": self.club_id})
Sli's avatar
Sli committed
667

668

Sli's avatar
Sli committed
669
670
class MailingAutoGenerationView(View):
    def dispatch(self, request, *args, **kwargs):
Sli's avatar
Sli committed
671
        self.mailing = get_object_or_404(Mailing, pk=kwargs["mailing_id"])
Sli's avatar
Sli committed
672
673
674
675
676
677
        if not request.user.can_edit(self.mailing):
            raise PermissionDenied
        return super(MailingAutoGenerationView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        club = self.mailing.club
678
        self.mailing.subscriptions.all().delete()
Sli's avatar
Sli committed
679
680
681
        members = club.members.filter(
            role__gte=settings.SITH_CLUB_ROLES_ID["Board member"]
        ).exclude(end_date__lte=timezone.now())
Sli's avatar
Sli committed
682
683
        for member in members.all():
            MailingSubscription(user=member.user, mailing=self.mailing).save()
Sli's avatar
Sli committed
684
        return redirect("club:mailing", club_id=club.id)
Sli's avatar
Sli committed
685

686

687
class PosterListView(ClubTabsMixin, PosterListBaseView, CanViewMixin):
688
689
    """List communication posters"""

Sli's avatar
Sli committed
690
691
    def get_object(self):
        return self.club
Nicolas Ballet's avatar
Nicolas Ballet committed
692

693
694
    def get_context_data(self, **kwargs):
        kwargs = super(PosterListView, self).get_context_data(**kwargs)
Sli's avatar
Sli committed
695
696
        kwargs["app"] = "club"
        kwargs["club"] = self.club
697
698
699
        return kwargs


Nicolas Ballet's avatar
Nicolas Ballet committed
700
class PosterCreateView(PosterCreateBaseView, CanCreateMixin):
701
702
    """Create communication poster"""

703
    pk_url_kwarg = "club_id"
704

705
706
707
708
709
710
711
    def get_object(self):
        obj = super(PosterCreateView, self).get_object()
        if not obj:
            return self.club
        return obj

    def get_success_url(self, **kwargs):
Sli's avatar
Sli committed
712
        return reverse_lazy("club:poster_list", kwargs={"club_id": self.club.id})
713

Nicolas Ballet's avatar
Nicolas Ballet committed
714
715

class PosterEditView(ClubTabsMixin, PosterEditBaseView, CanEditMixin):
716
717
    """Edit communication poster"""

Nicolas Ballet's avatar
Nicolas Ballet committed
718
    def get_success_url(self):
Sli's avatar
Sli committed
719
        return reverse_lazy("club:poster_list", kwargs={"club_id": self.club.id})
720
721
722

    def get_context_data(self, **kwargs):
        kwargs = super(PosterEditView, self).get_context_data(**kwargs)
Sli's avatar
Sli committed
723
        kwargs["app"] = "club"
724
725
        return kwargs

Nicolas Ballet's avatar
Nicolas Ballet committed
726
727
728
729
730

class PosterDeleteView(PosterDeleteBaseView, ClubTabsMixin, CanEditMixin):
    """Delete communication poster"""

    def get_success_url(self):
Sli's avatar
Sli committed
731
        return reverse_lazy("club:poster_list", kwargs={"club_id": self.club.id})