admin_views.py 12.4 KB
Newer Older
1
2
import csv

3
4
from django.contrib import messages
from django.contrib.admin import helpers
5
from django.contrib.admin.views.decorators import staff_member_required
6
from django.contrib.auth.mixins import PermissionRequiredMixin
7
8
9
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404
from django.urls import reverse
10
from django.utils import timezone
11
from django.utils.decorators import method_decorator
12
13
14
from django.utils.text import slugify
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
15
from django.views import View
16
from django.views.generic import DetailView, TemplateView, FormView
17

18
from events import services
19
from events.decorators import organiser_only
20
from events.exceptions import RegistrationError
21
22
from events.forms import FieldsForm, EventMessageForm
from pushnotifications.models import Message, Category
23
24
25
from .models import Event, Registration


26
@method_decorator(staff_member_required, name='dispatch')
27
@method_decorator(organiser_only, name='dispatch')
28
class EventAdminDetails(DetailView, PermissionRequiredMixin):
29
    """
30
    Renders an overview of registrations for the specified event
31
    """
32
33
34
    template_name = 'events/admin/details.html'
    model = Event
    context_object_name = 'event'
35
    permission_required = 'events.change_event'
36

37

38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
@method_decorator(staff_member_required, name='dispatch')
@method_decorator(organiser_only, name='dispatch')
class RegistrationAdminFields(FormView):
    """
    Renders a form that allows the user to change the details of their
    registration. The user should be authenticated.
    """
    form_class = FieldsForm
    template_name = 'admin/change_form.html'
    registration = None
    admin = None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            **self.admin.admin_site.each_context(self.request),
            'add': False,
            'change': True,
            'has_view_permission': True,
            'has_add_permission': False,
            'has_change_permission':
                self.request.user.has_perms('events.change_registration'),
            'has_delete_permission': False,
            'has_editable_inline_admin_formsets': False,
            'app_label': 'events',
            'opts': self.registration._meta,
            'is_popup': False,
            'save_as': False,
            'save_on_top': False,
            'original': self.registration,
            'obj_id': self.registration.pk,
            'title': _('Change registration fields'),
            'adminform': helpers.AdminForm(context['form'], (
                (None, {
                    'fields': [f for f in context['form'].fields.keys()]
                }),
            ), {})
        })
        return context

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs["fields"] = services.registration_fields(
            self.request, registration=self.registration)
        return kwargs

    def form_valid(self, form):
        values = form.field_values()
        try:
            services.update_registration(registration=self.registration,
                                         field_values=values)
            messages.success(self.request,
                             _("Registration successfully saved."))
            if '_save' in self.request.POST:
                return HttpResponseRedirect(reverse(
                    'admin:events_registration_change',
                    args=[str(self.registration.pk)]
                ))
        except RegistrationError as e:
            messages.error(self.request, e)
        return self.render_to_response(self.get_context_data(form=form))

    def dispatch(self, request, *args, **kwargs):
        self.registration = get_object_or_404(
102
            Registration, pk=self.kwargs['registration'])
103
104
105
106
107
108
109
110
111
112
113
        try:
            if self.registration.event.has_fields():
                return super().dispatch(request, *args, **kwargs)
        except RegistrationError:
            pass
        return HttpResponseRedirect(reverse(
            'admin:events_registration_change',
            args=[str(self.registration.pk)]
        ))


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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
@method_decorator(staff_member_required, name='dispatch')
@method_decorator(organiser_only, name='dispatch')
class EventMessage(FormView):
    """
    Renders a form that allows the user to create a push notification for all
    users registers to the event.
    """
    form_class = EventMessageForm
    template_name = 'events/admin/message_form.html'
    admin = None

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context.update({
            **self.admin.admin_site.each_context(self.request),
            'add': False,
            'change': True,
            'has_view_permission': True,
            'has_add_permission': False,
            'has_change_permission':
                self.request.user.has_perms('events.change_event'),
            'has_delete_permission': False,
            'has_editable_inline_admin_formsets': False,
            'app_label': 'events',
            'opts': self.event._meta,
            'is_popup': False,
            'save_as': False,
            'save_on_top': False,
            'original': self.event,
            'obj_id': self.event.pk,
            'title': _('Send push notification'),
            'adminform': helpers.AdminForm(context['form'], (
                (None, {
                    'fields': [f for f in context['form'].fields.keys()]
                }),
            ), {})
        })
        return context

    def form_valid(self, form):
        values = form.cleaned_data
        message = Message(
            title_nl=values['title_nl'],
            title_en=values['title_en'],
            body_nl=values['title_nl'],
            body_en=values['title_en'],
            url=values['url'],
            category=Category.objects.get(key='event')
        )
        message.save()
        message.users.set([r.member for r in self.event.participants
                           if r.member])
        message.send()
        print(message)

        messages.success(self.request,
                         _("Message sent successfully."))
        if '_save' in self.request.POST:
172
            return redirect(
173
174
                'admin:events_event_details',
                args=[str(self.event.pk)]
175
            )
176
177
178
179
180
181

    def dispatch(self, request, *args, **kwargs):
        self.event = get_object_or_404(Event, pk=self.kwargs['pk'])
        return super().dispatch(request, *args, **kwargs)


182
@method_decorator(staff_member_required, name='dispatch')
183
@method_decorator(organiser_only, name='dispatch')
184
class EventRegistrationsExport(View, PermissionRequiredMixin):
185
    """
186
    View to export registrations
187
    """
188
    template_name = 'events/admin/details.html'
189
    permission_required = 'events.change_event'
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

    def get(self, request, pk):
        """
        Export the registration of a specified event

        :param request: the request object
        :param pk: the primary key of the event
        :return: A CSV containing all registrations for the event
        """
        event = get_object_or_404(Event, pk=pk)
        extra_fields = event.registrationinformationfield_set.all()
        registrations = event.registration_set.all()

        header_fields = (
            [_('Name'), _('Email'), _('Paid'), _('Present'),
             _('Status'), _('Phone number')] +
            [field.name for field in extra_fields] +
            [_('Date'), _('Date cancelled')])

        rows = []
        if event.price == 0:
            header_fields.remove(_('Paid'))
        for i, registration in enumerate(registrations):
            if registration.member:
                name = registration.member.get_full_name()
215
            else:
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
                name = registration.name
            status = pgettext_lazy('registration status',
                                   'registered').capitalize()
            cancelled = None
            if registration.date_cancelled:

                if registration.is_late_cancellation():
                    status = pgettext_lazy('registration status',
                                           'late cancellation').capitalize()
                else:
                    status = pgettext_lazy('registration status',
                                           'cancelled').capitalize()
                cancelled = timezone.localtime(registration.date_cancelled)

            elif registration.queue_position:
                status = pgettext_lazy('registration status', 'waiting')
            data = {
                _('Name'): name,
                _('Date'): timezone.localtime(registration.date),
                _('Present'): _('Yes') if registration.present else '',
                _('Phone number'): (registration.member.profile.phone_number
                                    if registration.member
                                    else ''),
                _('Email'): (registration.member.email
                             if registration.member
                             else ''),
                _('Status'): status,
                _('Date cancelled'): cancelled,
            }
            if event.price > 0:
246
247
                if registration.is_paid():
                    data[_('Paid')] = registration.payment.get_type_display()
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
                else:
                    data[_('Paid')] = _('No')

            data.update({field['field'].name: field['value'] for field in
                         registration.information_fields})
            rows.append(data)

        response = HttpResponse(content_type='text/csv')
        writer = csv.DictWriter(response, header_fields)
        writer.writeheader()

        rows = sorted(rows,
                      key=lambda row:
                      (row[_('Status')] == pgettext_lazy(
                          'registration status',
                          'late cancellation').capitalize(),
                       row[_('Date')]),
                      reverse=True,
                      )

        for row in rows:
            writer.writerow(row)

        response['Content-Disposition'] = (
            'attachment; filename="{}.csv"'.format(slugify(event.title)))
        return response


276
@method_decorator(staff_member_required, name='dispatch')
277
@method_decorator(organiser_only, name='dispatch')
278
class EventRegistrationEmailsExport(TemplateView, PermissionRequiredMixin):
279
280
281
    """
    Renders a page that outputs all email addresses of registered members
    for an event
282
283
    """
    template_name = 'events/admin/email_export.html'
284
    permission_required = 'events.view_event'
285

286
287
288
289
290
291
292
293
294
295
296
297
298
299
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        event = get_object_or_404(Event, pk=kwargs['pk'])
        registrations = event.registration_set.filter(
            date_cancelled=None)
        registrations = registrations[:event.max_participants]
        addresses = [r.member.email for r in registrations if r.member]
        no_addresses = [r.name for r in registrations if not r.member]
        context['event'] = event
        context['addresses'] = addresses
        context['no_addresses'] = no_addresses
        return context


300
@method_decorator(staff_member_required, name='dispatch')
301
@method_decorator(organiser_only, name='dispatch')
302
class EventRegistrationsMarkPresent(View, PermissionRequiredMixin):
303
    """
304
305
    Renders a page that outputs all email addresses of registered members
    for an event
306
    """
307
    template_name = 'events/admin/email_export.html'
308
    permission_required = 'events.change_registration'
309

310
311
312
    def get(self, request, pk):
        """
        Mark all registrations of an event as present
313

314
315
316
317
318
319
320
321
322
323
324
325
326
        :param request: the request object
        :param pk: the primary key of the event
        :return: HttpResponse 302 to the event admin page
        """
        event = get_object_or_404(Event, pk=pk)

        if event.max_participants is None:
            registrations_query = event.registration_set.filter(
                date_cancelled=None)
        else:
            registrations_query = (event.registration_set
                                   .filter(date_cancelled=None)
                                   .order_by('date')[:event.max_participants])
327

328
329
        event.registration_set.filter(pk__in=registrations_query).update(
            present=True, payment=Registration.PAYMENT_CASH)
330

331
332
        return HttpResponseRedirect(reverse('admin:events_event_details',
                                            args=[str(event.pk)]))