admin_views.py 7.12 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import csv
import json

from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import get_object_or_404, render
from django.utils import timezone
from django.utils.text import slugify
from django.utils.translation import pgettext_lazy
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.http import require_http_methods

from events.decorators import organiser_only
from .models import Event, Registration


@staff_member_required
@permission_required('events.change_event')
@organiser_only
def details(request, event_id):
22
23
24
25
26
27
    """
    Renders an overview of registration for the specified event
    :param request: the request object
    :param event_id: the primary key of the event
    :return: HttpResponse 200 with the page HTML
    """
28
29
30
31
32
33
34
35
36
37
38
39
    event = get_object_or_404(Event, pk=event_id)

    return render(request, 'events/admin/details.html', {
        'event': event,
    })


@staff_member_required
@permission_required('events.change_event')
@organiser_only
@require_http_methods(["POST"])
def change_registration(request, event_id, action=None):
40
41
42
43
44
45
46
    """
    JSON call to change the status of a registration
    :param request: the request object
    :param event_id: the primary key of the event
    :param action: specifies what should be changed
    :return: JsonResponse with a success status
    """
47
48
49
50
51
52
53
    data = {
        'success': True
    }

    try:
        id = request.POST.get("id", -1)
        obj = Registration.objects.get(event=event_id, pk=id)
54
55
56
        if action == 'present':
            checked = json.loads(request.POST.get("checked"))
            if checked is not None:
57
                obj.present = checked
58
59
60
61
62
63
                obj.save()
        elif action == 'payment':
            value = request.POST.get("value")
            if value is not None:
                obj.payment = value
                obj.save()
64
65
66
67
68
69
70
71
72
    except Registration.DoesNotExist:
        data['success'] = False

    return JsonResponse(data)


@staff_member_required
@permission_required('events.change_event')
def export(request, event_id):
73
74
75
76
77
78
    """
    Export the registration of a specified event
    :param request: the request object
    :param event_id: the primary key of the event
    :return: A CSV containing all registrations for the event
    """
79
80
81
82
83
    event = get_object_or_404(Event, pk=event_id)
    extra_fields = event.registrationinformationfield_set.all()
    registrations = event.registration_set.all()

    header_fields = (
84
85
        [_('Name'), _('Email'), _('Paid'), _('Present'),
         _('Status'), _('Phone number')] +
86
        [field.name for field in extra_fields] +
87
        [_('Date'), _('Date cancelled')])
88
89
90

    rows = []
    if event.price == 0:
91
        header_fields.remove(_('Paid'))
92
93
94
95
96
    for i, registration in enumerate(registrations):
        if registration.member:
            name = registration.member.get_full_name()
        else:
            name = registration.name
97
98
        status = pgettext_lazy('registration status',
                               'registered').capitalize()
99
100
101
102
103
        cancelled = None
        if registration.date_cancelled:

            if registration.is_late_cancellation():
                status = pgettext_lazy('registration status',
104
                                       'late cancellation').capitalize()
105
            else:
106
107
                status = pgettext_lazy('registration status',
                                       'cancelled').capitalize()
108
109
110
111
112
            cancelled = timezone.localtime(registration.date_cancelled)

        elif registration.queue_position:
            status = pgettext_lazy('registration status', 'waiting')
        data = {
113
114
115
116
            _('Name'): name,
            _('Date'): timezone.localtime(
                            registration.date).strftime("%Y-%m-%d %H:%m"),
            _('Present'): _('Yes') if registration.present else '',
117
            _('Phone number'): (registration.member.profile.phone_number
118
119
                                if registration.member
                                else ''),
120
            _('Email'): (registration.member.email
121
122
123
124
                                if registration.member
                                else ''),
            _('Status'): status,
            _('Date cancelled'): cancelled,
125
126
        }
        if event.price > 0:
127
            if registration.payment == registration.PAYMENT_CASH:
128
                data[_('Paid')] = _('Cash')
129
            elif registration.payment == registration.PAYMENT_CARD:
130
                data[_('Paid')] = _('Pin')
131
            else:
132
                data[_('Paid')] = _('No')
133
134
135
136
137
138
139
140
141
142
143

        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:
144
145
146
147
                  (row[_('Status')] == pgettext_lazy(
                        'registration status',
                        'late cancellation').capitalize(),
                   row[_('Date')]),
148
149
150
151
152
153
154
155
156
157
158
159
160
161
                  reverse=True,
                  )

    for row in rows:
        writer.writerow(row)

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


@staff_member_required
@permission_required('events.change_event')
def export_email(request, event_id):
162
163
164
165
166
167
168
    """
    Renders a page that outputs all email addresses of registered members
    for an event
    :param request: the request object
    :param event_id: the primary key of the event
    :return: HttpResponse 200 with the HTML of the page
    """
169
170
    event = get_object_or_404(Event, pk=event_id)
    registrations = event.registration_set.filter(
171
        date_cancelled=None)
172
    registrations = registrations[:event.max_participants]
173
    addresses = [r.member.email for r in registrations if r.member]
174
175
176
177
178
179
180
181
182
183
    no_addresses = [r.name for r in registrations if not r.member]
    return render(request, 'events/admin/email_export.html',
                  {'event': event, 'addresses': addresses,
                   'no_addresses': no_addresses})


@staff_member_required
@permission_required('events.change_event')
@organiser_only
def all_present(request, event_id):
184
185
186
187
188
189
    """
    Mark all registrations of an event as present
    :param request: the request object
    :param event_id: the primary key of the event
    :return: HttpResponse 302 to the event admin page
    """
190
191
192
193
194
195
196
197
198
199
200
    event = get_object_or_404(Event, pk=event_id)

    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])

    event.registration_set.filter(pk__in=registrations_query).update(
201
        present=True, payment=Registration.PAYMENT_CASH)
202
203

    return HttpResponseRedirect('/events/admin/{}'.format(event_id))