summaryrefslogtreecommitdiff
path: root/postgresqleu/confreg/invoicehandler.py
blob: 6b6ad325d7c753ac1bb0e1fdcc00c51723731839 (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
from django.utils import timezone
from django.conf import settings

from .models import ConferenceRegistration, BulkPayment, PendingAdditionalOrder
from .models import RegistrationWaitlistHistory, PrepaidVoucher
from .models import RegistrationTransferPending
from .util import notify_reg_confirmed
from .util import send_conference_mail, send_conference_notification
from .util import reglog
from .util import make_registration_transfer


class InvoiceProcessor(object):
    # Process invoices once they're getting paid
    #
    # In the case of conference registration, this means that we
    # flag the conference registration as confirmed.
    #
    # Since we lock the registration when the invoice is generated,
    # we don't actually need to verify that nothing has changed.
    #
    # All modifications are already wrapped in a django transaction
    def process_invoice_payment(self, invoice):
        # The processorid field contains our registration id
        try:
            reg = ConferenceRegistration.objects.get(pk=invoice.processorid)
        except ConferenceRegistration.DoesNotExist:
            raise Exception("Could not find conference registration %s" % invoice.processorid)

        if reg.payconfirmedat:
            raise Exception("Registration already paid")

        reg.payconfirmedat = timezone.now()
        reg.payconfirmedby = "Invoice paid"
        reg.save(update_fields=['payconfirmedat', 'payconfirmedby'])
        reglog(reg, "Confirmed registration by invoice")
        notify_reg_confirmed(reg)

    # Process an invoice being canceled. This means we need to unlink
    # it from the registration. We don't actually remove the registration,
    # but it will automatically become "unlocked" for further edits.
    def process_invoice_cancellation(self, invoice):
        try:
            reg = ConferenceRegistration.objects.get(pk=invoice.processorid)
        except ConferenceRegistration.DoesNotExist:
            raise Exception("Could not find conference registration %s" % invoice.processorid)

        if reg.payconfirmedat:
            raise Exception("Registration already paid")

        if reg.canceledat:
            raise Exception("Registration already canceled")

        # Unlink this invoice from the registration. This will automatically
        # "unlock" the registration
        reg.invoice = None
        reglog(reg, "Invoice #{} canceled, unlinking from reg".format(invoice.id))

        # If this registration holds any additional options that are about to expire, release
        # them for others to use at this point.
        for ao in reg.additionaloptions.filter(invoice_autocancel_hours__isnull=False, invoice_autocancel_hours__gt=0):
            reglog(reg, "Expired additional option {}".format(ao.name))
            reg.additionaloptions.remove(ao)

        reg.save(update_fields=['invoice'])

        # If the registration was on the waitlist, put it back in the
        # queue.
        if hasattr(reg, 'registrationwaitlistentry'):
            wl = reg.registrationwaitlistentry
            RegistrationWaitlistHistory(waitlist=wl,
                                        text="Invoice was cancelled, moving back to waitlist").save()
            wl.offeredon = None
            wl.offerexpires = None
            wl.enteredon = timezone.now()
            wl.save()

            send_conference_notification(
                reg.conference,
                'Waitlist invoice canceled',
                'Invoice for user {0} {1} <{2}> was canceled, and the offer has expired.'.format(reg.firstname, reg.lastname, reg.email),
            )

        # If the registration was attached to a discount code, remove it so that it is no
        # longer counted against it. Also clear out the field, in case others want to use
        # that discount code.
        if reg.discountcode_set.exists():
            reg.discountcode_set.clear()
        if reg.vouchercode:
            try:
                vc = PrepaidVoucher.objects.get(vouchervalue=reg.vouchercode)
                vc.usedate = None
                vc.user = None
                vc.save(update_fields=['usedate', 'user'])
            except PrepaidVoucher.DoesNotExist:
                # Vouchercode is set even if it's a discount code, since we use the same field.
                # And in this case, there is no matching prepaid voucher.
                pass

            reg.vouchercode = ''
            reg.save(update_fields=['vouchercode'])

    # Return the user to a page showing what happened as a result
    # of their payment. In our case, we just return the user directly
    # to the registration page.
    def get_return_url(self, invoice):
        # The processorid field contains our registration id
        try:
            reg = ConferenceRegistration.objects.get(pk=invoice.processorid)
        except ConferenceRegistration.DoesNotExist:
            raise Exception("Could not find conference registration %s" % invoice.processorid)
        return "%s/events/%s/register/" % (settings.SITEBASE, reg.conference.urlname)

    # Admin access to the registration
    def get_admin_url(self, invoice):
        try:
            reg = ConferenceRegistration.objects.get(pk=invoice.processorid)
        except ConferenceRegistration.DoesNotExist:
            return None
        return "/events/admin/{0}/regdashboard/list/{1}/".format(reg.conference.urlname, reg.pk)


class BulkInvoiceProcessor(object):
    # Process invoices once they're getting paid
    #
    # In the case of conference bulk registrations, this means that we
    # flag all the related conference registrations as confirmed.
    #
    # Since we lock the registration when the invoice is generated,
    # we don't actually need to verify that nothing has changed.
    #
    # All modifications are already wrapped in a django transaction
    def process_invoice_payment(self, invoice):
        # The processorid field contains our bulkpayment id
        try:
            bp = BulkPayment.objects.get(pk=invoice.processorid)
        except ConferenceRegistration.DoesNotExist:
            raise Exception("Could not find bulk payment %s" % invoice.processorid)

        if bp.paidat:
            raise Exception("Bulk payment already paid")

        bp.paidat = timezone.now()

        # Confirm all related ones
        for r in bp.conferenceregistration_set.all():
            r.payconfirmedat = timezone.now()
            r.payconfirmedby = "Bulk paid"
            r.save(update_fields=['payconfirmedat', 'payconfirmedby'])
            reglog(r, "Confirmed registration by bulk paid")
            notify_reg_confirmed(r)

        bp.save(update_fields=['paidat'])

    # Process an invoice being canceled. This means we need to unlink
    # it from the registration. We don't actually remove the registration,
    # but it will automatically become "unlocked" for further edits.
    def process_invoice_cancellation(self, invoice):
        try:
            bp = BulkPayment.objects.get(pk=invoice.processorid)
        except ConferenceRegistration.DoesNotExist:
            raise Exception("Could not find bulk payment %s" % invoice.processor)
        if bp.paidat:
            raise Exception("Bulk registration already paid")

        # Unlink this bulk payment from all registrations. This will
        # automatically unlock the registrations. Also notify the
        # attendees that this happened.
        for r in bp.conferenceregistration_set.all():
            r.bulkpayment = None
            r.save(update_fields=['bulkpayment'])
            reglog(r, "Unlinked from bulk payment by cancel")

            if r.attendee:
                # Only notify if this attendee actually knows about the
                # registration.
                send_conference_mail(bp.conference,
                                     r.email,
                                     "Your multi-registration canceled",
                                     'confreg/mail/bulkpay_canceled.txt',
                                     {
                                         'conference': bp.conference,
                                         'reg': r,
                                         'bulk': bp,
                                     },
                                     receivername=r.fullname,
                )

            # If this registration holds any additional options that are about to expire, release
            # them for others to use at this point.
            for ao in r.additionaloptions.filter(invoice_autocancel_hours__isnull=False, invoice_autocancel_hours__gt=0):
                reglog(r, "Expired additional option {}".format(ao.name))
                r.additionaloptions.remove(ao)

            # If the registration was attached to a discount code, remove it so that it is no
            # longer counted against it. Also clear out the field, in case others want to use
            # that discount code.
            if r.discountcode_set.exists():
                # If this discountcode is in the vouchercode field, clear it.
                dcodes = r.discountcode_set.all()
                if len(dcodes) != 1:
                    raise Exception("Matched {} discount codes, not 1!".format(len(dcodes)))
                if dcodes[0].code == r.vouchercode:
                    r.vouchercode = ''
                r.discountcode_set.clear()
                r.save(update_fields=['vouchercode'])

            # If there is still a voucher code, it must be referring to a regular voucher
            # and not a discount code.
            if r.vouchercode:
                # Also mark the voucher code as not used anymore
                try:
                    vc = PrepaidVoucher.objects.get(vouchervalue=r.vouchercode)
                    vc.usedate = None
                    vc.user = None
                    vc.save(update_fields=['usedate', 'user'])
                except PrepaidVoucher.DoesNotExist:
                    # Vouchercode is set even if it's a discount code, since we use the same field.
                    # And in this case, there is no matching prepaid voucher.
                    pass

                r.vouchercode = ''
                r.save(update_fields=['vouchercode'])

        # Now actually *remove* the bulk payment record completely,
        # since it no longer contains anything interesting.
        bp.delete()

    # Return the user to a page showing what happened as a result
    # of their payment. In our case, we just return the user directly
    # to the bulk payment page.
    def get_return_url(self, invoice):
        try:
            bp = BulkPayment.objects.get(pk=invoice.processorid)
        except ConferenceRegistration.DoesNotExist:
            raise Exception("Could not find bulk payment %s" % invoice.processor)
        return "%s/events/%s/register/other/" % (settings.SITEBASE, bp.conference.urlname)

    # Admin access to the bulk payment we just send to the dashboard
    def get_admin_url(self, invoice):
        try:
            bp = BulkPayment.objects.get(pk=invoice.processorid)
        except BulkPayment.DoesNotExist:
            return None
        return "/events/admin/{0}/multiregs/?b={1}".format(bp.conference.urlname, bp.id)


class AddonInvoiceProcessor(object):
    can_refund = False
    # Process invoices for additional options added to an existing
    # registration.
    #
    # Since we lock the registration when the invoice is generated,
    # we don't actually need to verify that nothing has changed.
    #
    # All modifications are already wrapped in a django transaction

    def process_invoice_payment(self, invoice):
        try:
            order = PendingAdditionalOrder.objects.get(pk=invoice.processorid)
        except PendingAdditionalOrder.DoesNotExist:
            raise Exception("Could not find additional options order %s!" % invoice.processorid)

        if order.payconfirmedat:
            raise Exception("Additional options already paid")

        order.payconfirmedat = timezone.now()
        if order.newregtype:
            order.reg.regtype = order.newregtype

        for o in order.options.all():
            order.reg.additionaloptions.add(o)

        order.reg.save(update_fields=['regtype'])
        order.save()

    def process_invoice_cancellation(self, invoice):
        try:
            order = PendingAdditionalOrder.objects.get(pk=invoice.processorid)
        except PendingAdditionalOrder.DoesNotExist:
            raise Exception("Could not find additional options order %s!" % invoice.processorid)

        # We just remove the entry completely, as there is no "unlocking"
        # here.
        order.delete()

    # Return the user to their dashboard
    def get_return_url(self, invoice):
        try:
            order = PendingAdditionalOrder.objects.get(pk=invoice.processorid)
        except PendingAdditionalOrder.DoesNotExist:
            raise Exception("Could not find additional options order %s!" % invoice.processorid)

        return "%s/events/%s/register/" % (settings.SITEBASE, order.reg.conference.urlname)

    # Admin access to the registration
    def get_admin_url(self, invoice):
        try:
            order = PendingAdditionalOrder.objects.get(pk=invoice.processorid)
        except PendingAdditionalOrder.DoesNotExist:
            return None
        return "/events/admin/{0}/regdashboard/list/{1}/".format(order.reg.conference.urlname, order.reg.pk)


class TransferInvoiceProcessor(object):
    can_refund = False
    # Process invoices for registration transfers.
    #
    # All modifications are already wrapped in a django transaction

    def process_invoice_payment(self, invoice):
        try:
            pending = RegistrationTransferPending.objects.get(pk=invoice.processorid)
        except RegistrationTransferPending.DoesNotExist:
            raise Exception("Could not find pending transfer: %s!" % invoice.processorid)

        reglog(pending.fromreg, 'Paid invoice for pending transfer')
        dummy = list(make_registration_transfer(pending.fromreg, pending.toreg, None, True))

        pending.delete()

    def process_invoice_cancellation(self, invoice):
        try:
            pending = RegistrationTransferPending.objects.get(pk=invoice.processorid)
        except RegistrationTransferPending.DoesNotExist:
            raise Exception("Could not find pending transfer: %s!" % invoice.processorid)

        reglog(pending.fromreg, 'Canceled invoice for pending transfer')
        pending.delete()

    # Return the user to their dashboard
    def get_return_url(self, invoice):
        try:
            pending = RegistrationTransferPending.objects.get(pk=invoice.processorid)
        except RegistrationTransferPending.DoesNotExist:
            # We can't find the transfer - that could be because it's successfully completed,
            # at which point the reservation may be canceled. So in this case, we just redirect
            # the user back to their invoice, because we have to send them somewhere.
            return "{}/invoices/{}/".format(settings.SITEBASE, invoice.recipient_secret)

        return "{}/events/{}/".format(settings.SITEBASE, pending.conference.urlname)

    def get_admin_url(self, invoice):
        try:
            pending = RegistrationTransferPending.objects.get(pk=invoice.processorid)
        except RegistrationTransferPending.DoesNotExist:
            return None

        return "/events/admin/{0}/transfer/".format(pending.conference.urlname)