summaryrefslogtreecommitdiff
path: root/postgresqleu/confreg/util.py
blob: 09baf4ebed03b00efc99c2a136b0aef11782ed5b (plain)
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
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
102
103
104
105
106
107
108
109
110
111
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
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
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
213
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
244
245
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
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
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from django.conf import settings
from django.core.exceptions import PermissionDenied
from django.utils import timezone

import os
from decimal import Decimal
from datetime import datetime, date, timedelta
import urllib.parse
from io import BytesIO
import re

from postgresqleu.mailqueue.util import send_simple_mail
from postgresqleu.util.middleware import RedirectException
from postgresqleu.util.time import today_conference
from postgresqleu.confreg.jinjafunc import JINJA_TEMPLATE_ROOT, render_jinja_conference_template
from postgresqleu.confreg.jinjapdf import render_jinja_ticket

from .models import PrepaidVoucher, DiscountCode, RegistrationWaitlistHistory
from .models import ConferenceRegistration, Conference
from .models import AttendeeMail
from .models import ConferenceRegistrationLog


def reglog(reg, txt, user=None):
    ConferenceRegistrationLog(reg=reg, txt=txt, user=user).save()


#
# Send an email using a conference template
#
def send_conference_mail(conference, receiver, subject, templatename, templateattr={}, attachments=None, bcc=None, receivername=None, sender=None, sendername=None):
    if not ((conference and conference.jinjadir) or os.path.exists(os.path.join(JINJA_TEMPLATE_ROOT, templatename))):
        raise Exception("Mail template not found")

    send_simple_mail(sender or conference.contactaddr,
                     receiver,
                     "[{0}] {1}".format(conference.conferencename, subject),
                     render_jinja_conference_template(conference, templatename, templateattr),
                     attachments,
                     bcc,
                     sendername or conference.conferencename,
                     receivername)


class InvoicerowsException(Exception):
    pass


def invoicerows_for_registration(reg, update_used_vouchers):
    # Return the rows that would be used to build an invoice for this
    # registration. Format is tuple of (description, num, cost)

    # Main conference registration
    r = [['%s - %s' % (reg.email, reg.regtype.regtype),
          1,
          reg.regtype.cost,
          reg.conference.vat_registrations,
          ]]

    # Any additional options
    for a in reg.additionaloptions.all():
        if a.cost > 0:
            r.append(['   %s' % a.name, 1, a.cost, reg.conference.vat_registrations])

    # Any voucher if present
    if reg.vouchercode:
        try:
            v = PrepaidVoucher.objects.get(vouchervalue=reg.vouchercode, conference=reg.conference)
            if v.usedate:
                # Find a way to raise an exception here if the voucher is
                # already used? For now, we just ignore it.
                raise InvoicerowsException("Prepaid voucher already used")
            else:
                # Valid voucher found!
                if update_used_vouchers:
                    v.usedate = timezone.now()
                    v.user = reg
                    v.save()
                # Add a row with the discount of the registration type
                r.append(['   Discount voucher %s...' % reg.vouchercode[:30], 1, -reg.regtype.cost, reg.conference.vat_registrations])
        except PrepaidVoucher.DoesNotExist:
            # Nonexistant voucher code means discount code was used
            try:
                d = DiscountCode.objects.get(code=reg.vouchercode, conference=reg.conference)
                if d.validuntil and d.validuntil < today_conference():
                    raise InvoicerowsException("Discount code is no longer valid")
                elif d.maxuses > 0 and d.registrations.count() >= d.maxuses:
                    raise InvoicerowsException("Discount code does not have enough remaining instances")
                elif d.is_invoiced:
                    raise InvoicerowsException("Discount code has already been invoiced and is no longer valid")
                else:
                    # Valid discount code found!
                    selected_options = reg.additionaloptions.all()
                    for o in d.requiresoption.all():
                        if o not in selected_options:
                            raise InvoicerowsException("Discount code requires option {0}".format(o.name))

                    required_regtypes = d.requiresregtype.all()
                    if required_regtypes:
                        if reg.regtype not in required_regtypes:
                            raise InvoicerowsException("Discount code requires registration types {0}".format(",".join(required_regtypes)))

                    if update_used_vouchers:
                        d.registrations.add(reg)
                        d.save()
                    # Add a row with the discount
                    current_total = sum([rr[2] for rr in r])
                    discount = 0
                    if d.discountamount:
                        # Fixed amount discount
                        discount = d.discountamount > current_total and current_total or d.discountamount
                    else:
                        # Percentage discount. Can be either off the total or just the reg
                        if d.regonly:
                            # regtype.cost is Decimal
                            discount = reg.regtype.cost * d.discountpercentage / 100
                        else:
                            discount = Decimal(current_total) * d.discountpercentage / 100
                    if discount > 0:
                        r.append(['   Discount code %s' % d.code, 1, -discount, reg.conference.vat_registrations])
            except DiscountCode.DoesNotExist:
                raise InvoicerowsException("Invalid voucher code")
    return r


def attendee_cost_from_bulk_payment(reg):
    re_email_dash = re.compile(r"^[^\s]+@[^\s]+ - [^\s]")
    if not reg.bulkpayment:
        raise Exception("Not called with bulk payment!")

    # We need to find the individual rows and sum it up, since it's possible that we have been
    # using discount codes for example.
    # We have no better key to work with than the email address...
    found = False
    totalnovat = totalvat = 0
    for r in reg.bulkpayment.invoice.invoicerow_set.all().order_by('id'):
        if r.rowtext.startswith(reg.email + ' - '):
            # Found the beginning!
            if found:
                raise Exception("Found the same registration more than once!")
            found = True
            totalnovat = r.totalrow
            totalvat = r.totalvat
        elif r.rowtext.startswith("  "):
            # Something to do with this reg
            if found:
                totalnovat += r.totalrow
                totalvat += r.totalvat
        elif re_email_dash.match(r.rowtext):
            # Matched a different reg
            found = False
        else:
            raise Exception("Unknown invoice row '%s'" % r.rowtext)

    return (totalnovat, totalvat)


def send_welcome_email(reg):
    # Do we need to send the welcome email?
    if not reg.conference.sendwelcomemail:
        return

    if reg.conference.tickets:
        buf = BytesIO()
        render_jinja_ticket(reg, buf, systemroot=JINJA_TEMPLATE_ROOT)
        attachments = [
            ('{0}_ticket.pdf'.format(reg.conference.urlname), 'application/pdf', buf.getvalue()),
        ]
    else:
        attachments = None

    # Ok, this attendee needs a notification. For now we don't support
    # any string replacements in it, maybe in the future.
    send_conference_mail(reg.conference,
                         reg.email,
                         "Registration complete",
                         'confreg/mail/welcomemail.txt',
                         {
                             'reg': reg,
                         },
                         receivername=reg.fullname,
                         attachments=attachments,
    )


def notify_reg_confirmed(reg, updatewaitlist=True):
    reglog(reg, "Registration confirmed")

    # This one was off the waitlist, so generate a history entry
    if updatewaitlist and hasattr(reg, 'registrationwaitlistentry'):
        RegistrationWaitlistHistory(waitlist=reg.registrationwaitlistentry,
                                    text="Completed registration from the waitlist").save()

    # If this registration has no user attached to it, it means that
    # it was a "register for somebody else". In this case we need to
    # send the user an email with information that otherwise would not
    # be available. This means that the user will get two separate
    # emails in case welcome emails is enabled, but that is necessary
    # since we need to include links and things in this email.
    if not reg.attendee:
        # First we see if we can just find a user match on email, this
        # being a user that has not already registered for this
        # conference.
        found = False
        try:
            u = User.objects.get(email=reg.email)
            if not ConferenceRegistration.objects.filter(conference=reg.conference, attendee=u).exists():
                # Found user by this id, not used yet, so attach it
                # to their account.
                reg.attendee = u
                reg.save()
                found = True
        except User.DoesNotExist:
            pass

        if not found:
            # User not found, so we use the random token and send it
            # to ask them to attach their account to this registration.
            send_conference_mail(reg.conference,
                                 reg.email,
                                 "Your registration",
                                 'confreg/mail/regmulti_attach.txt',
                                 {
                                     'conference': reg.conference,
                                     'reg': reg,
                                 },
                                 receivername=reg.fullname,
            )

    # If the registration has a user account, we may have email to connect
    # to this registration.
    if reg.attendee:
        for m in AttendeeMail.objects.filter(conference=reg.conference,
                                             pending_regs=reg.attendee):
            m.pending_regs.remove(reg.attendee)
            m.registrations.add(reg)

    if reg.conference.notifyregs:
        send_conference_mail(reg.conference,
                             reg.conference.notifyaddr,
                             "New registration",
                             'confreg/mail/admin_notify_reg.txt',
                             {
                                 'reg': reg,
                             },
                             sender=reg.conference.notifyaddr,
                             receivername=reg.conference.conferencename,
        )

    send_welcome_email(reg)


def cancel_registration(reg, is_unconfirmed=False, reason=None, user=None):
    if reg.canceledat:
        raise Exception("Registration is already canceled")

    # Verify that we're only canceling a real registration
    if not reg.payconfirmedat:
        # If we don't allow canceling an unpaid registration, and the registration
        # actually is unpaid, then boom.
        if not is_unconfirmed:
            raise Exception("Registration not paid, data is out of sync!")

    # If we sent a welcome mail, also send a goodbye mail. Except when this is an
    # unfinished part of a multiregistration, in which case it would probably just
    # be confusing to the user.
    if reg.conference.sendwelcomemail and not (reg.attendee != reg.registrator and not reg.payconfirmedat):
        send_conference_mail(reg.conference,
                             reg.email,
                             "Registration canceled",
                             'confreg/mail/reg_canceled.txt',
                             {
                                 'conference': reg.conference,
                                 'reg': reg,
                                 'unconfirmed': is_unconfirmed,
                             },
                             receivername=reg.fullname,
        )

    # Now actually cancel the reg.

    # If the reg used a voucher or a discount code, return it to the pool.
    if reg.vouchercode:
        if PrepaidVoucher.objects.filter(user=reg).exists():
            v = PrepaidVoucher.objects.get(user=reg)
            v.user = None
            v.usedate = None
            v.save()
        elif DiscountCode.objects.filter(registrations=reg).exists():
            d = DiscountCode.objects.get(registrations=reg)
            d.registrations.remove(reg)
            d.save()
        reg.vouchercode = ""

    # If the registration has any additional options, remove them
    reg.additionaloptions.clear()

    # Volunteer assignments are simply deleted
    reg.volunteerassignment_set.all().delete()

    # If this registration was never paid, we're done now - just delete
    # the record completely. We don't care about keeping registrations
    # that never completed around in history.
    if not reg.payconfirmedat:
        reg.delete()
        return

    # Else, flag canceled and save
    reg.canceledat = timezone.now()
    reg.save()

    reglog(reg, "Canceled registration", user)

    if reg.conference.notifyregs and not is_unconfirmed:
        send_conference_mail(reg.conference,
                             reg.conference.notifyaddr,
                             "Canceled registration",
                             'confreg/mail/admin_notify_cancel.txt',
                             {
                                 'reg': reg,
                                 'reason': reason,
                             },
                             sender=reg.conference.notifyaddr,
                             receivername=reg.conference.conferencename,
        )


def get_invoice_autocancel(*args):
    # Each argument is expected to be an integer with number of hours,
    # or None if there is no limit
    hours = [a for a in args if a is not None]
    if hours:
        return timezone.now() + timedelta(hours=min(hours))
    else:
        return None


def expire_additional_options(reg):
    # If there are any additional options on this registrations that are untouched for
    # longer than the invoice autocancel period, expire them. Send an email to the user
    # being expired (expects to run within a transaction).
    # Returns the list of options expired for this particular user.

    hours = int(round((timezone.now() - reg.lastmodified).total_seconds() / 3600))
    expireset = list(reg.additionaloptions.filter(invoice_autocancel_hours__isnull=False,
                                                  invoice_autocancel_hours__lt=hours))

    expired_names = []
    if expireset:
        # We have something expired. Step one is to send an email about it, based on a
        # template. (It's a bit inefficient to re-parse the template every time, but
        # we don't expire these things very often, so we don't care)

        if reg.attendee:
            send_conference_mail(reg.conference,
                                 reg.email,
                                 'Your pending registration',
                                 'confreg/mail/additionaloption_expired.txt',
                                 {
                                     'conference': reg.conference,
                                     'reg': reg,
                                     'options': expireset,
                                     'optionscount': len(expireset),
                                 },
                                 receivername=reg.fullname,
            )

        for ao in expireset:
            # Notify caller that this one is being expired
            expired_names.append(ao.name)
            # And actually expire it
            reg.additionaloptions.remove(ao)

        # And finally - save
        reg.save()

    return expired_names


def get_authenticated_conference(request, urlname=None, confid=None):
    if not request.user.is_authenticated:
        raise RedirectException("{0}?{1}".format(settings.LOGIN_URL, urllib.parse.urlencode({'next': request.build_absolute_uri()})))

    if confid:
        c = get_object_or_404(Conference, pk=confid)
    else:
        c = get_object_or_404(Conference, urlname=urlname)

    timezone.activate(c.tzname)

    if request.user.is_superuser:
        return c
    else:
        if c.administrators.filter(pk=request.user.id).exists():
            return c
        if c.series.administrators.filter(pk=request.user.id).exists():
            return c
        raise PermissionDenied()


def get_conference_or_404(urlname):
    conference = get_object_or_404(Conference, urlname=urlname)

    timezone.activate(conference.tzname)

    return conference