admin_views.py 12.3 KB
Newer Older
1
2
import csv

3
from django.conf import settings
4
5
from django.contrib import messages
from django.contrib.admin import helpers
6
from django.contrib.admin.views.decorators import staff_member_required
7
from django.contrib.auth.mixins import PermissionRequiredMixin
8
from django.http import HttpResponse
9
from django.shortcuts import get_object_or_404, redirect
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
@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:
92
                return redirect(
93
                    'admin:events_registration_change',
94
95
                    self.registration.pk
                )
96
97
98
99
100
101
        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
        try:
            if self.registration.event.has_fields():
                return super().dispatch(request, *args, **kwargs)
        except RegistrationError:
            pass
108
        return redirect(
109
            'admin:events_registration_change',
110
111
            self.registration.pk
        )
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
@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
155
156
        if not values['url']:
            values['url'] = settings.BASE_URL + self.event.get_absolute_url()
157
158
159
160
161
        message = Message(
            title_nl=values['title_nl'],
            title_en=values['title_en'],
            body_nl=values['title_nl'],
            body_en=values['title_en'],
162
            url=values['url'],
163
164
165
166
167
168
169
170
171
172
            category=Category.objects.get(key='event')
        )
        message.save()
        message.users.set([r.member for r in self.event.participants
                           if r.member])
        message.send()

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

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


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

    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()
213
            else:
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
                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:
244
245
                if registration.is_paid():
                    data[_('Paid')] = registration.payment.get_type_display()
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
                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


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

284
285
286
287
288
289
290
291
292
293
294
295
296
297
    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


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

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

312
313
314
315
316
317
318
319
320
321
322
323
324
        :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])
325

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

329
        return redirect('admin:events_event_details', event.pk)