admin_views.py 5.99 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
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):
    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):
    data = {
        'success': True
    }

    try:
        id = request.POST.get("id", -1)
        obj = Registration.objects.get(event=event_id, pk=id)
41
42
43
        if action == 'present':
            checked = json.loads(request.POST.get("checked"))
            if checked is not None:
44
                obj.present = checked
45
46
47
48
49
50
                obj.save()
        elif action == 'payment':
            value = request.POST.get("value")
            if value is not None:
                obj.payment = value
                obj.save()
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    except Registration.DoesNotExist:
        data['success'] = False

    return JsonResponse(data)


@staff_member_required
@permission_required('events.change_event')
def export(request, event_id):
    event = get_object_or_404(Event, pk=event_id)
    extra_fields = event.registrationinformationfield_set.all()
    registrations = event.registration_set.all()

    header_fields = (
65
66
        [_('Name'), _('Email'), _('Paid'), _('Present'),
         _('Status'), _('Phone number')] +
67
        [field.name for field in extra_fields] +
68
        [_('Date'), _('Date cancelled')])
69
70
71

    rows = []
    if event.price == 0:
72
        header_fields.remove(_('Paid'))
73
74
75
76
77
    for i, registration in enumerate(registrations):
        if registration.member:
            name = registration.member.get_full_name()
        else:
            name = registration.name
78
79
        status = pgettext_lazy('registration status',
                               'registered').capitalize()
80
81
82
83
84
        cancelled = None
        if registration.date_cancelled:

            if registration.is_late_cancellation():
                status = pgettext_lazy('registration status',
85
                                       'late cancellation').capitalize()
86
            else:
87
88
                status = pgettext_lazy('registration status',
                                       'cancelled').capitalize()
89
90
91
92
93
            cancelled = timezone.localtime(registration.date_cancelled)

        elif registration.queue_position:
            status = pgettext_lazy('registration status', 'waiting')
        data = {
94
95
96
97
            _('Name'): name,
            _('Date'): timezone.localtime(
                            registration.date).strftime("%Y-%m-%d %H:%m"),
            _('Present'): _('Yes') if registration.present else '',
98
            _('Phone number'): (registration.member.profile.phone_number
99
100
                                if registration.member
                                else ''),
101
            _('Email'): (registration.member.email
102
103
104
105
                                if registration.member
                                else ''),
            _('Status'): status,
            _('Date cancelled'): cancelled,
106
107
        }
        if event.price > 0:
108
            if registration.payment == registration.PAYMENT_CASH:
109
                data[_('Paid')] = _('Cash')
110
            elif registration.payment == registration.PAYMENT_CARD:
111
                data[_('Paid')] = _('Pin')
112
            else:
113
                data[_('Paid')] = _('No')
114
115
116
117
118
119
120
121
122
123
124

        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:
125
126
127
128
                  (row[_('Status')] == pgettext_lazy(
                        'registration status',
                        'late cancellation').capitalize(),
                   row[_('Date')]),
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
                  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):
    event = get_object_or_404(Event, pk=event_id)
    registrations = event.registration_set.filter(
145
        date_cancelled=None)
146
    registrations = registrations[:event.max_participants]
147
    addresses = [r.member.email for r in registrations if r.member]
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
    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):
    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(
169
        present=True, payment=Registration.PAYMENT_CASH)
170
171

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