models.py 15.7 KB
Newer Older
Thom Wiggers's avatar
Thom Wiggers committed
1
2
3
4
from django.core import validators
from django.core.exceptions import ValidationError
from django.db import models
from django.db.models import Q
5
from django.urls import reverse
Thom Wiggers's avatar
Thom Wiggers committed
6
from django.utils import timezone
7
from django.utils.translation import ugettext_lazy as _
8
from django.utils.text import format_lazy
9
from tinymce.models import HTMLField
10

11
from thaliawebsite.settings import settings
12
from utils.translation import ModelTranslateMeta, MultilingualField
Thom Wiggers's avatar
Thom Wiggers committed
13
14


15
class Event(models.Model, metaclass=ModelTranslateMeta):
Thom Wiggers's avatar
Thom Wiggers committed
16
17
    """Represents events"""

18
19
20
21
22
23
24
25
    EVENT_CATEGORIES = (
        ('drinks', _('Drinks')),
        ('activity', _('Activity')),
        ('lunchlecture', _('Lunch Lecture')),
        ('generalmeeting', _('General Meeting')),
        ('workshop', _('Workshop')),
        ('other', _('Other')))

Thom Wiggers's avatar
Thom Wiggers committed
26
27
    DEFAULT_NO_REGISTRATION_MESSAGE = _('No registration required')

28
29
30
31
32
    title = MultilingualField(
        models.CharField,
        _("title"),
        max_length=100
    )
Thom Wiggers's avatar
Thom Wiggers committed
33

34
    description = MultilingualField(
35
        HTMLField,
36
37
        _("description")
    )
Thom Wiggers's avatar
Thom Wiggers committed
38
39
40
41
42
43

    start = models.DateTimeField(_("start time"))

    end = models.DateTimeField(_("end time"))

    organiser = models.ForeignKey(
44
        'activemembers.Committee',
Thom Wiggers's avatar
Thom Wiggers committed
45
        models.PROTECT,
46
        verbose_name=_("organiser")
Thom Wiggers's avatar
Thom Wiggers committed
47
48
    )

49
50
51
52
53
54
55
    category = models.CharField(
        max_length=40,
        choices=EVENT_CATEGORIES,
        verbose_name=_('category'),
        default='other'
    )

Thom Wiggers's avatar
Thom Wiggers committed
56
57
58
59
    registration_start = models.DateTimeField(
        _("registration start"),
        null=True,
        blank=True,
60
61
62
        help_text=_("If you set a registration period registration will be "
                    "required. If you don't set one, registration won't be "
                    "required.")
Thom Wiggers's avatar
Thom Wiggers committed
63
64
65
66
67
    )

    registration_end = models.DateTimeField(
        _("registration end"),
        null=True,
68
69
70
71
        blank=True,
        help_text=_("If you set a registration period registration will be "
                    "required. If you don't set one, registration won't be "
                    "required.")
72
73
74
75
76
    )

    cancel_deadline = models.DateTimeField(
        _("cancel deadline"),
        null=True,
Thom Wiggers's avatar
Thom Wiggers committed
77
78
79
        blank=True
    )

80
81
82
83
84
85
86
    send_cancel_email = models.BooleanField(
        _('send cancellation notifications'),
        default=True,
        help_text=_("Send an email to the organising party when a member "
                    "cancels their registration after the deadline."),
    )

87
88
89
90
91
    location = MultilingualField(
        models.CharField,
        _("location"),
        max_length=255,
    )
Thom Wiggers's avatar
Thom Wiggers committed
92
93
94
95
96

    map_location = models.CharField(
        _("location for minimap"),
        max_length=255,
        help_text=_('Location of Huygens: Heyendaalseweg 135, Nijmegen. '
97
                    'Location of Mercator 1: Toernooiveld 212, Nijmegen. '
Thom Wiggers's avatar
Thom Wiggers committed
98
99
100
101
102
103
104
105
106
107
108
                    'Not shown as text!!'),
    )

    price = models.DecimalField(
        _("price"),
        max_digits=5,
        decimal_places=2,
        default=0,
        validators=[validators.MinValueValidator(0)],
    )

109
110
    fine = models.DecimalField(
        _("fine"),
Thom Wiggers's avatar
Thom Wiggers committed
111
112
113
        max_digits=5,
        decimal_places=2,
        default=0,
114
115
        # Minimum fine is checked in this model's clean(), as it is only for
        # events that require registration.
116
        help_text=_("Fine if participant does not show up (at least €5)."),
117
        validators=[validators.MinValueValidator(0)],
Thom Wiggers's avatar
Thom Wiggers committed
118
119
120
121
122
123
124
125
    )

    max_participants = models.PositiveSmallIntegerField(
        _('maximum number of participants'),
        blank=True,
        null=True,
    )

126
127
    no_registration_message = MultilingualField(
        models.CharField,
Thom Wiggers's avatar
Thom Wiggers committed
128
129
130
131
        _('message when there is no registration'),
        max_length=200,
        blank=True,
        null=True,
132
133
        help_text=(format_lazy("{} {}", _("Default:"),
                               DEFAULT_NO_REGISTRATION_MESSAGE)),
Thom Wiggers's avatar
Thom Wiggers committed
134
135
136
137
    )

    published = models.BooleanField(_("published"), default=False)

138
    @property
139
    def after_cancel_deadline(self):
140
141
142
143
144
        return self.cancel_deadline and self.cancel_deadline <= timezone.now()

    @property
    def registration_started(self):
        return self.registration_start <= timezone.now()
145

146
    @property
147
148
149
    def registration_required(self):
        return bool(self.registration_start) or bool(self.registration_end)

150
151
152
153
    def has_fields(self):
        return self.registrationinformationfield_set.count() > 0

    def reached_participants_limit(self):
154
        return (self.max_participants is not None and
155
156
                self.max_participants <= self.registration_set.filter(
                    date_cancelled=None).count())
157

158
159
160
161
162
163
    @property
    def registrations(self):
        return self.registration_set.filter(date_cancelled=None)

    @property
    def participants(self):
164
165
166
        if self.max_participants is not None:
            return self.registrations.order_by('date')[:self.max_participants]
        return self.registrations.order_by('date')
167
168
169

    @property
    def queue(self):
170
171
172
        if self.max_participants is not None:
            return self.registrations.order_by('date')[self.max_participants:]
        return []
173

174
175
176
    @property
    def cancellations(self):
        return self.registration_set.exclude(date_cancelled=None)
177

178
    @property
179
    def registration_allowed(self):
180
        now = timezone.now()
181
182
183
184
185
186
187
188
        return ((self.registration_start or self.registration_end) and
                self.registration_end > now >= self.registration_start)

    @property
    def cancellation_allowed(self):
        now = timezone.now()
        return ((self.registration_start or self.registration_end)
                and now >= self.registration_start)
189

Thom Wiggers's avatar
Thom Wiggers committed
190
191
    def clean(self):
        super().clean()
Thom Wiggers's avatar
Thom Wiggers committed
192
        errors = {}
193
        if self.end is not None and self.start is not None and (
194
                self.end < self.start):
Thom Wiggers's avatar
Thom Wiggers committed
195
            errors.update({
196
                'end': _("Can't have an event travel back in time")})
197
        if self.registration_required:
198
199
200
201
202
            if self.fine < 5:
                errors.update({
                    'fine': _("The fine for this event is too low "
                              "(must be at least €5).")
                })
203
204
205
206
207
208
            for lang in settings.LANGUAGES:
                field = 'no_registration_message_' + lang[0]
                if getattr(self, field):
                    errors.update(
                        {field: _("Doesn't make sense to have this "
                                  "if you require registrations.")})
Thom Wiggers's avatar
Thom Wiggers committed
209
210
211
212
213
214
215
216
217
218
            if not self.registration_start:
                errors.update(
                    {'registration_start': _(
                        "If registration is required, you need a start of "
                        "registration")})
            if not self.registration_end:
                errors.update(
                    {'registration_end': _(
                        "If registration is required, you need an end of "
                        "registration")})
219
220
221
222
223
            if not self.cancel_deadline:
                errors.update(
                    {'cancel_deadline': _(
                        "If registration is required, you need a deadline for "
                        "the cancellation")})
224
225
226
227
228
            elif self.cancel_deadline > self.start:
                errors.update(
                    {'cancel_deadline': _(
                        "The cancel deadline should be"
                        " before the start of the event.")})
Thom Wiggers's avatar
Thom Wiggers committed
229
            if self.registration_start and self.registration_end and (
230
                    self.registration_start >= self.registration_end):
Thom Wiggers's avatar
Thom Wiggers committed
231
232
233
234
235
                message = _('Registration start should be before '
                            'registration end')
                errors.update({
                    'registration_start': message,
                    'registration_end': message})
236
237
238
239
240
241
242
        if (self.organiser is not None and
                self.send_cancel_email and
                self.organiser.contact_mailinglist is None):
            errors.update(
                {'send_cancel_email': _("This organiser does not "
                                        "have a contact mailinglist.")})

Thom Wiggers's avatar
Thom Wiggers committed
243
244
        if errors:
            raise ValidationError(errors)
Thom Wiggers's avatar
Thom Wiggers committed
245
246

    def get_absolute_url(self):
247
        return reverse('events:event', args=[str(self.pk)])
Thom Wiggers's avatar
Thom Wiggers committed
248
249
250
251
252
253
254
255

    def __str__(self):
        return '{}: {}'.format(
            self.title,
            timezone.localtime(self.start).strftime('%Y-%m-%d %H:%M'))

    class Meta:
        ordering = ('-start',)
256
257
258
        permissions = (
            ("override_organiser", "Can access events as if organizing"),
        )
Thom Wiggers's avatar
Thom Wiggers committed
259
260


261
262
263
264
265
def registration_member_choices_limit():
    return (Q(membership__until__isnull=True) |
            Q(membership__until__gt=timezone.now().date()))


Thom Wiggers's avatar
Thom Wiggers committed
266
267
268
class Registration(models.Model):
    """Event registrations"""

269
270
271
272
    PAYMENT_CARD = 'card_payment'
    PAYMENT_CASH = 'cash_payment'
    PAYMENT_NONE = 'no_payment'

273
    PAYMENT_TYPES = (
274
275
276
        (PAYMENT_NONE, _('No payment')),
        (PAYMENT_CASH, _('Paid with cash')),
        (PAYMENT_CARD, _('Paid with card')))
277

Thom Wiggers's avatar
Thom Wiggers committed
278
279
280
    event = models.ForeignKey(Event, models.CASCADE)

    member = models.ForeignKey(
281
        'members.Member', models.CASCADE,
Thom Wiggers's avatar
Thom Wiggers committed
282
283
        blank=True,
        null=True,
284
        limit_choices_to=registration_member_choices_limit
Thom Wiggers's avatar
Thom Wiggers committed
285
286
287
288
289
290
291
292
293
294
    )

    name = models.CharField(
        _('name'),
        max_length=50,
        help_text=_('Use this for non-members'),
        null=True,
        blank=True
    )

295
296
    date = models.DateTimeField(_('registration date'),
                                default=timezone.now)
Thom Wiggers's avatar
Thom Wiggers committed
297
298
299
300
301
    date_cancelled = models.DateTimeField(_('cancellation date'),
                                          null=True,
                                          blank=True)

    present = models.BooleanField(
302
        _('present'),
Thom Wiggers's avatar
Thom Wiggers committed
303
304
        default=False,
    )
305
306
307
308
309
310

    payment = models.CharField(
        choices=PAYMENT_TYPES,
        default='no_payment',
        verbose_name=_('payment'),
        max_length=20,
Thom Wiggers's avatar
Thom Wiggers committed
311
312
    )

313
314
    @property
    def information_fields(self):
Thom Wiggers's avatar
Thom Wiggers committed
315
316
317
318
        fields = self.event.registrationinformationfield_set.all()
        return [{'field': field, 'value': field.get_value_for(self)}
                for field in fields]

319
320
321
322
323
324
325
326
327
328
329
330
331
    @property
    def is_registered(self):
        return self.date_cancelled is None

    @property
    def queue_position(self):
        if self.event.max_participants is not None:
            try:
                return list(self.event.queue).index(self) + 1
            except ValueError:
                pass
        return 0

332
333
334
    def is_external(self):
        return bool(self.name)

Luuk Scholten's avatar
Luuk Scholten committed
335
    def is_late_cancellation(self):
336
337
        # First check whether or not the user cancelled
        # If the user cancelled then check if this was after the deadline
338
339
        # And if there is a max participants number:
        # do a complex check to calculate if this user was on
340
341
342
        # the waiting list at the time of cancellation, since
        # you shouldn't need to pay the costs of something
        # you weren't even able to go to.
Luuk Scholten's avatar
Luuk Scholten committed
343
        return (self.date_cancelled and
344
                self.event.cancel_deadline and
345
                self.date_cancelled > self.event.cancel_deadline and
346
347
                (self.event.max_participants is None or
                 self.event.registration_set.filter(
348
349
350
                     (Q(date_cancelled__gte=self.date_cancelled) |
                      Q(date_cancelled=None)) &
                     Q(date__lte=self.date)
351
                 ).count() < self.event.max_participants))
Luuk Scholten's avatar
Luuk Scholten committed
352

353
    def would_cancel_after_deadline(self):
354
355
356
        now = timezone.now()
        return (self.queue_position == 0 and
                now >= self.event.cancel_deadline)
357

Thom Wiggers's avatar
Thom Wiggers committed
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
    def clean(self):
        if ((self.member is None and not self.name) or
                (self.member and self.name)):
            raise ValidationError({
                'member': _('Either specify a member or a name'),
                'name': _('Either specify a member or a name'),
            })

    def validate_unique(self, exclude=None):
        super().validate_unique(exclude)

    def __str__(self):
        if self.member:
            return '{}: {}'.format(self.member.get_full_name(), self.event)
        else:
            return '{}: {}'.format(self.name, self.event)

    class Meta:
        ordering = ('date',)
        unique_together = (('member', 'event', 'name', 'date_cancelled'),)


380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
class RegistrationInformationField(models.Model, metaclass=ModelTranslateMeta):
    """Field description to ask for when registering"""
    BOOLEAN_FIELD = 'boolean'
    INTEGER_FIELD = 'integer'
    TEXT_FIELD = 'text'

    FIELD_TYPES = ((BOOLEAN_FIELD, _('Checkbox')),
                   (TEXT_FIELD, _('Text')),
                   (INTEGER_FIELD, _('Integer')),)

    event = models.ForeignKey(Event, models.CASCADE)

    type = models.CharField(
        _('field type'),
        choices=FIELD_TYPES,
        max_length=10,
    )

    name = MultilingualField(
        models.CharField,
        _('field name'),
        max_length=100,
    )

    description = MultilingualField(
        models.TextField,
        _('description'),
        null=True,
        blank=True,
    )

    required = models.BooleanField(
        _('required'),
    )

    def get_value_for(self, registration):
        if self.type == self.TEXT_FIELD:
            value_set = self.textregistrationinformation_set
        elif self.type == self.BOOLEAN_FIELD:
            value_set = self.booleanregistrationinformation_set
        elif self.type == self.INTEGER_FIELD:
            value_set = self.integerregistrationinformation_set

        try:
            return value_set.get(registration=registration).value
        except (TextRegistrationInformation.DoesNotExist,
                BooleanRegistrationInformation.DoesNotExist,
                IntegerRegistrationInformation.DoesNotExist):
            return None

    def set_value_for(self, registration, value):
        if self.type == self.TEXT_FIELD:
            value_set = self.textregistrationinformation_set
        elif self.type == self.BOOLEAN_FIELD:
            value_set = self.booleanregistrationinformation_set
        elif self.type == self.INTEGER_FIELD:
            value_set = self.integerregistrationinformation_set

        try:
            field_value = value_set.get(registration=registration)
        except BooleanRegistrationInformation.DoesNotExist:
            field_value = BooleanRegistrationInformation()
        except TextRegistrationInformation.DoesNotExist:
            field_value = TextRegistrationInformation()
        except IntegerRegistrationInformation.DoesNotExist:
            field_value = IntegerRegistrationInformation()

        field_value.registration = registration
        field_value.field = self
        field_value.value = value
        field_value.save()

    def __str__(self):
        return "{} ({})".format(self.name, dict(self.FIELD_TYPES)[self.type])

    class Meta:
        order_with_respect_to = 'event'


Thom Wiggers's avatar
Thom Wiggers committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
class AbstractRegistrationInformation(models.Model):
    """Abstract to contain common things for registration information"""

    registration = models.ForeignKey(Registration, models.CASCADE)
    field = models.ForeignKey(RegistrationInformationField, models.CASCADE)
    changed = models.DateTimeField(_('last changed'), auto_now=True)

    def __str__(self):
        return '{} - {}: {}'.format(self.registration, self.field, self.value)

    class Meta:
        abstract = True


class BooleanRegistrationInformation(AbstractRegistrationInformation):
Joren Vrancken's avatar
Joren Vrancken committed
474
    """Checkbox information filled in by members when registering"""
Thom Wiggers's avatar
Thom Wiggers committed
475
476
477
478
479

    value = models.BooleanField()


class TextRegistrationInformation(AbstractRegistrationInformation):
Joren Vrancken's avatar
Joren Vrancken committed
480
    """Checkbox information filled in by members when registering"""
Thom Wiggers's avatar
Thom Wiggers committed
481
482
483
484
    value = models.TextField()


class IntegerRegistrationInformation(AbstractRegistrationInformation):
Joren Vrancken's avatar
Joren Vrancken committed
485
    """Checkbox information filled in by members when registering"""
Thom Wiggers's avatar
Thom Wiggers committed
486
    value = models.IntegerField()