cciw-website / cciw / bookings / models.py

  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
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
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
# -*- coding: utf-8 -*-
from datetime import datetime, date, timedelta
from decimal import Decimal
import os

from dateutil.relativedelta import relativedelta
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
from django.db import models
from django.utils.safestring import mark_safe

from cciw.cciwmain.common import get_thisyear
from cciw.cciwmain.models import Camp
from cciw.cciwmain.utils import Lock

from .signals import places_confirmed

# = Business rules =
#
# Business rules are implemented in relevant models and managers.
#
#


SEX_MALE, SEX_FEMALE = 'm', 'f'
SEXES = [
    (SEX_MALE, 'Male'),
    (SEX_FEMALE, 'Female'),
]

# Price types that can be selected for a booking
PRICE_FULL, PRICE_2ND_CHILD, PRICE_3RD_CHILD, PRICE_CUSTOM, PRICE_SOUTH_WALES_TRANSPORT, PRICE_DEPOSIT = range(0, 6)
PRICE_TYPES = [
    (PRICE_FULL,      'Full price'),
    (PRICE_2ND_CHILD, '2nd child discount'),
    (PRICE_3RD_CHILD, '3rd child discount'),
    (PRICE_CUSTOM,    'Custom discount'),
]

# Price types that are used by Price model
VALUED_PRICE_TYPES = [(v,d) for (v,d) in PRICE_TYPES if v is not PRICE_CUSTOM] + \
    [(PRICE_SOUTH_WALES_TRANSPORT, 'South wales transport surcharge'),
     (PRICE_DEPOSIT, 'Deposit'),
     ]

BOOKING_INFO_COMPLETE, BOOKING_APPROVED, BOOKING_BOOKED, BOOKING_CANCELLED, BOOKING_CANCELLED_FULL_REFUND = range(0, 5)
BOOKING_STATES = [
    (BOOKING_INFO_COMPLETE, 'Information complete'),
    (BOOKING_APPROVED, 'Manually approved'),
    (BOOKING_BOOKED, 'Booked'),
    (BOOKING_CANCELLED, 'Cancelled'),
    (BOOKING_CANCELLED_FULL_REFUND, 'Cancelled - full refund'),
]


class Price(models.Model):
    year = models.PositiveSmallIntegerField()
    price_type = models.PositiveSmallIntegerField(choices=VALUED_PRICE_TYPES)
    price = models.DecimalField(decimal_places=2, max_digits=10)

    class Meta:
        unique_together = ['year', 'price_type']

    def __unicode__(self):
        return u"%s %s - %s" % (self.get_price_type_display(), self.year, self.price)


class BookingAccount(models.Model):
    # For online bookings, email is required, but not for paper. Initially for online
    # process only email is filled in, so to ensure we can edit all BookingAccounts
    # in the admin, all the address fields have 'blank=True'.
    email = models.EmailField(blank=True, unique=True, null=True)
    name = models.CharField(blank=True, max_length=100, null=True)
    address = models.TextField(blank=True)
    post_code = models.CharField(blank=True, max_length=10, null=True)
    phone_number = models.CharField(blank=True, max_length=22)
    share_phone_number = models.BooleanField("Allow this phone number to be passed on "
                                             "to other parents to help organise transport",
                                             blank=True, default=False)
    total_received = models.DecimalField(default=Decimal('0.00'), decimal_places=2, max_digits=10)
    first_login = models.DateTimeField(null=True, blank=True)
    last_login = models.DateTimeField(null=True, blank=True)

    def has_account_details(self):
        return self.name != "" and self.address != "" and self.post_code != ""

    def __unicode__(self):
        out = []
        if self.name:
            out.append(self.name)
        if self.post_code:
            out.append(self.post_code)
        if self.email:
            out.append(u"<" + self.email + u">")
        if not out:
            out.append(u"(empty)")
        return u", ".join(out)

    class Meta:
        unique_together = [('name', 'post_code'),
                           ('name', 'email')]

    def save(self, **kwargs):
        # We have to ensure that only receive_payment touches the total_received
        # field when doing updates
        if self.id is None:
            return super(BookingAccount, self).save(**kwargs)
        else:
            update_fields = [f for f in self._meta.fields if
                             f.name != 'id' and f.name != 'total_received']
            update_kwargs = dict((f.attname, getattr(self, f.attname)) for
                                 f in update_fields)
            BookingAccount.objects.filter(id=self.id).update(**update_kwargs)

    # Business methods:

    def get_balance(self, confirmed_only=False):
        """
        Gets the balance to pay on the account.
        If confirmed_only=True, then only bookings that are confirmed
        (no expiration date) are included as 'received goods'
        """
        total = self.bookings.payable(confirmed_only).aggregate(models.Sum('amount_due'))['amount_due__sum']
        if total is None:
            total = Decimal('0.00')
        return total - self.total_received

    def receive_payment(self, amount):
        """
        Adds the amount to the account's total_received field.  This should only
        ever be called by the 'process_payments' management command. Client code
        should use the 'send_payment' function.
        """
        # = Receiving payments =
        #
        # This system needs to be robust, and cope with all kinds of user error, and
        # things not matching up. The essential philosophy of this code is to assume the
        # worst, most complicated scenario, and this will then easily handle the more
        # simple case where everything matches up as a special case.
        #
        # When a payment is received, django-paypal creates an object
        # and a signal handler calls BookingAccount.receive_payment, which must
        # update the 'total_received' field.
        #
        # We also need to set the 'Booking.booking_expires' field of relevant Booking
        # objects to null, so that the place is securely booked.
        #
        # There are a number of scenarios where the amount paid doesn't cover the total
        # amount due:
        # 1) user fiddles with the form client side and alters the amount
        # 2) user starts paying for one place, then books another place in a different
        # tab/window
        #
        # It is also possible for a place to be partially paid for, yet booked e.g. if a
        # user selects a discount for which they were not eligible, and pays. This is then
        # discovered, and the 'amount due' for that place is altered by an admin.
        #
        # So, we need a method to distribute any incoming payment so that we stop the
        # booked place from expiring. It is better to be too generous than too stingy in
        # stopping places from expiring, because:
        #
        # * on camp we can generally cope with one too many campers
        # * we don't want people slipping off the camp lists by accident
        # * we can always check whether people still have money outstanding by just checking
        #   the total amount paid against the total amount due.
        #
        # Therefore, we ignore the partially paid case, and for distributing payment treat
        # any place which is 'booked' with no 'booking_expires' as fully paid.
        #
        # When a payment is received, we don't know which place it is for, and
        # in general it could be for any combination of the places that need
        # payment. There could also be money in the account that is still
        # 'unclaimed'. So, for simplicity we simply go through all places which
        # are 'booked' and have a 'booking_expires' date, starting with the
        # earliest 'booking_expires', on the assumption that we will get payment
        # for that one first.
        #
        # Use update and F objects to avoid concurrency problems
        BookingAccount.objects.filter(id=self.id).update(total_received=models.F('total_received') + amount)

        # Need new data from DB:
        acc = BookingAccount.objects.get(id=self.id)
        self.total_received = acc.total_received

        self.distribute_balance()

    def distribute_balance(self):
        """
        Distribute any money in the account to mark unconfirmed places as
        confirmed.
        """
        # In order to distribute funds, need to take into account the total
        # amount in the account that is not covered by confirmed places
        existing_balance = self.get_balance(confirmed_only=True)
        # The 'pot' is the amount we have as excess and can use to mark places
        # as confirmed.
        pot = -existing_balance
        # Order by booking_expires ascending i.e. earliest first
        candidate_bookings = list(self.bookings.unconfirmed()
                                  .order_by('booking_expires'))
        i = 0
        confirmed_bookings = []
        while pot > 0 and i < len(candidate_bookings):
            b = candidate_bookings[i]
            if b.amount_due <= pot:
                b.confirm()
                b.save()
                confirmed_bookings.append(b)
                pot -= b.amount_due
            i += 1
        if confirmed_bookings:
            places_confirmed.send(confirmed_bookings, payment_received=True)



class BookingManager(models.Manager):
    use_for_related_fields = True
    def get_query_set(self):
        return super(BookingManager, self).get_query_set().select_related('camp', 'account')

    def basket(self, year):
        return self._ready_to_book(year, False)

    def shelf(self, year):
        return self._ready_to_book(year, True)

    def _ready_to_book(self, year, shelved):
        qs = self.get_query_set().filter(camp__year__exact=year, shelved=shelved)
        return qs.filter(state=BOOKING_INFO_COMPLETE) | qs.filter(state=BOOKING_APPROVED)

    def booked(self):
        return self.get_query_set().filter(state=BOOKING_BOOKED)

    def confirmed(self):
        return self.get_query_set().filter(state=BOOKING_BOOKED,
                                           booking_expires__isnull=True)

    def unconfirmed(self):
        return self.get_query_set().filter(state=BOOKING_BOOKED,
                                           booking_expires__isnull=False)

    def payable(self, confirmed_only):
        """
        Returns bookings for which payment is due.
        If confirmed_only is True, unconfirmed places are excluded.
        """
        # Cancelled bookings have payment due - the deposit
        cancelled = self.get_query_set().filter(state=BOOKING_CANCELLED)
        return cancelled | (self.confirmed() if confirmed_only else self.booked())

    def cancelled(self):
        return self.get_query_set().filter(state=BOOKING_CANCELLED)


class Booking(models.Model):
    account = models.ForeignKey(BookingAccount, related_name='bookings')

    # Booking details - from user
    camp = models.ForeignKey(Camp, related_name='bookings')
    name = models.CharField(max_length=100)
    sex = models.CharField(max_length=1, choices=SEXES)
    date_of_birth = models.DateField()
    address = models.TextField()
    post_code = models.CharField(max_length=10)
    phone_number = models.CharField(blank=True, max_length=22)
    email = models.EmailField(blank=True)
    church = models.CharField("name of church", max_length=100, blank=True)
    south_wales_transport = models.BooleanField("require transport from South Wales",
                                                blank=True, default=False)

    # Contact - from user
    contact_name = models.CharField(max_length=100)
    contact_phone_number = models.CharField(max_length=22)

    # Diet - from user
    dietary_requirements = models.TextField(blank=True)

    # GP details - from user
    gp_name = models.CharField("GP name", max_length=100)
    gp_address = models.TextField("GP address")
    gp_phone_number = models.CharField("GP phone number", max_length=22)

    # Medical details - from user
    medical_card_number = models.CharField(max_length=100) # no idea how long it should be
    last_tetanus_injection = models.DateField(null=True, blank=True)
    allergies = models.TextField(blank=True)
    regular_medication_required = models.TextField(blank=True)
    illnesses = models.TextField(blank=True)
    learning_difficulties = models.TextField(blank=True)
    serious_illness = models.BooleanField(blank=True, default=False)

    # Agreement - from user
    agreement = models.BooleanField(default=False)

    # Price - partly from user (must fit business rules)
    price_type = models.PositiveSmallIntegerField(choices=PRICE_TYPES)
    amount_due = models.DecimalField(decimal_places=2, max_digits=10)

    # State - user driven
    shelved = models.BooleanField(default=False, help_text=
                                  u"Used by user to put on 'shelf'")

    # State - internal
    state = models.IntegerField(choices=BOOKING_STATES,
                                help_text=mark_safe(
            u"<ul>"
            u"<li>To book, set to 'Booked' <b>and</b> ensure 'Booking expires' is empty</li>"
            u"<li>For people paying online and needing custom discounts, set to 'Manually approved' to allow them to book and pay</li>"
            u"<li>If there are queries before it can be booked, set to 'Information complete'</li>"
            u"</ul>"))

    created = models.DateTimeField(default=datetime.now)
    booking_expires = models.DateTimeField(null=True, blank=True)


    objects = BookingManager()

    # Methods

    def __unicode__(self):
        return u"%s, %s-%s, %s" % (self.name, self.camp.year, self.camp.number,
                                  self.account)

    ### Main business rules here ###

    def confirmed_booking(self):
        return self.state == BOOKING_BOOKED and self.booking_expires is None
    confirmed_booking.boolean = True

    def expected_amount_due(self):
        if self.state == BOOKING_CANCELLED:
            return Price.objects.get(year=self.camp.year,
                                     price_type=PRICE_DEPOSIT).price
        elif self.state == BOOKING_CANCELLED_FULL_REFUND:
            return Decimal('0.00')
        else:
            amount = Price.objects.get(year=self.camp.year,
                                       price_type=self.price_type).price
            if self.south_wales_transport:
                amount += Price.objects.get(price_type=PRICE_SOUTH_WALES_TRANSPORT,
                                            year=self.camp.year).price
            return amount

    def auto_set_amount_due(self):
        if self.price_type == PRICE_CUSTOM:
            if self.amount_due is None:
                self.amount_due = Decimal('0.00')
        else:
            self.amount_due = self.expected_amount_due()

    def get_booking_problems(self, booking_sec=False):
        """
        Returns a two tuple (errors, warnings), where 'errors' is a list of
        reasons why booking cannot be done. If empty list, then it can be.
        'warnings' is a list of possible problems that don't stop booking.

        If 'booking_sec', it shows the problems as they should be seen by the
        booking secretary.
        """
        if self.state == BOOKING_APPROVED and not booking_sec:
            return ([], [])

        return (self.get_booking_errors(booking_sec=booking_sec),
                self.get_booking_warnings(booking_sec=booking_sec))

    def get_booking_errors(self, booking_sec=False):
        errors = []

        # Custom price - not auto bookable
        if self.price_type == PRICE_CUSTOM:
            errors.append(u"A custom discount needs to be arranged by the booking secretary")

        # 2nd/3rd child discounts
        if self.price_type == PRICE_2ND_CHILD:
            qs = self.account.bookings.basket(self.camp.year)
            if not qs.filter(price_type=PRICE_FULL).exists():
                errors.append(u"You cannot use a 2nd child discount unless you have "
                              u"a child at full price. Please edit the place details "
                              u"and choose an appropriate price type.")

        if self.price_type == PRICE_3RD_CHILD:
            qs = self.account.bookings.basket(self.camp.year)
            qs = qs.filter(price_type=PRICE_FULL) | qs.filter(price_type=PRICE_2ND_CHILD)
            if qs.count() < 2:
                errors.append(u"You cannot use a 3rd child discount unless you have "
                              u"two other places without this discount. Please edit the "
                              u"place details and choose an appropriate price type.")

        # serious illness
        if self.serious_illness:
            errors.append(u"Must be approved by leader due to serious illness/condition")

        # Check age.
        # Age is calculated based on shool years, i.e. age on 31st August
        camper_age = relativedelta(date(self.camp.year, 8, 31), self.date_of_birth)
        if camper_age.years < self.camp.minimum_age:
            errors.append(u"Camper will be below the minimum age (%d) on the 31st August %d"
                          % (self.camp.minimum_age, self.camp.year))

        if camper_age.years > self.camp.maximum_age:
            errors.append(u"Camper will be above the maximum age (%d) on the 31st August %d"
                          % (self.camp.maximum_age, self.camp.year))

        # Check place availability
        places_left, places_left_male, places_left_female = self.camp.get_places_left()

        # We only want one message about places not being available, and the
        # order here is important - if there are no places full stop, we don't
        # want to display message about there being no places for boys etc.
        places_available = True

        # Simple - no places left
        if places_left <= 0:
            errors.append(u"There are no places left on this camp.")
            places_available = False

        if places_available and self.sex == SEX_MALE:
            if places_left_male <= 0:
                errors.append(u"There are no places left for boys on this camp.")
                places_available = False

        if places_available and self.sex == SEX_FEMALE:
            if places_left_female <= 0:
                errors.append(u"There are no places left for girls on this camp.")
                places_available = False

        if places_available:
            # Complex - need to check the other places that are about to be booked.
            # (if there is one place left, and two campers for it, we can't say that
            # there are enough places)
            same_camp_bookings = self.account.bookings.basket(self.camp.year).filter(camp=self.camp)
            places_to_be_booked = same_camp_bookings.count()
            places_to_be_booked_male = same_camp_bookings.filter(sex=SEX_MALE).count()
            places_to_be_booked_female = same_camp_bookings.filter(sex=SEX_FEMALE).count()

            if places_left < places_to_be_booked:
                errors.append(u"There are not enough places left on this camp "
                              u"for the campers in this set of bookings.")
                places_available = False

            if places_available and self.sex == SEX_MALE:
                if places_left_male < places_to_be_booked_male:
                    errors.append(u"There are not enough places for boys left on this camp "
                                  u"for the campers in this set of bookings.")
                    places_available = False

            if places_available and self.sex == SEX_FEMALE:
                if places_left_female < places_to_be_booked_female:
                    errors.append(u"There are not enough places for girls left on this camp "
                                  u"for the campers in this set of bookings.")
                    places_available = False

        if booking_sec and self.price_type != PRICE_CUSTOM:
            expected_amount = self.expected_amount_due()
            if self.amount_due != expected_amount:
                errors.append(u"The 'amount due' is not the expected value of £%s." % expected_amount)
        return errors

    def get_booking_warnings(self, booking_sec=False):
        warnings = []

        if self.account.bookings.filter(name=self.name, camp=self.camp).exclude(id=self.id):
            warnings.append(u"You have entered another set of place details for a camper "
                            u"called '%s' on camp %d. Please ensure you don't book multiple "
                            u"places for the same camper!" % (self.name, self.camp.number))


        if self.price_type == PRICE_FULL:
            full_pricers = self.account.bookings.basket(self.camp.year)\
                .filter(price_type=PRICE_FULL).order_by('name')
            if len(full_pricers) > 1:
                names = [b.name for b in full_pricers]
                pretty_names = u', '.join(names[1:]) + u" and " + names[0]
                warning = u"You have multiple places at 'Full price'. "
                if len(names) == 2:
                    warning += (u"If %s are from the same family, one is eligible "
                                u"for the 2nd child discount." % pretty_names)
                else:
                    warning += (u"If %s are from the same family, one or more is eligible "
                                u"for the 2nd or 3rd child discounts." % pretty_names)

                warnings.append(warning)

        if self.price_type == PRICE_2ND_CHILD:
            second_childers = self.account.bookings.basket(self.camp.year)\
                .filter(price_type=PRICE_2ND_CHILD).order_by('name')
            if len(second_childers) > 1:
                names = [b.name for b in second_childers]
                pretty_names = u', '.join(names[1:]) + u" and " + names[0]
                warning = u"You have multiple places at '2nd child discount'. "
                if len(names) == 2:
                    warning += (u"If %s are from the same family, one is eligible "
                                u"for the 3rd child discount." % pretty_names)
                else:
                    warning += (u"If %s are from the same family, %d are eligible "
                                u"for the 3rd child discount." % (pretty_names,
                                                                 len(names) - 1))

                warnings.append(warning)

        return warnings

    def confirm(self):
        self.booking_expires = None

    def expire(self):
        self.booking_expires = None
        self.state = BOOKING_INFO_COMPLETE

    def is_user_editable(self):
        return self.state == BOOKING_INFO_COMPLETE

    class Meta:
        ordering = ['-created']


def book_basket_now(bookings):
    """
    Book a basket of bookings, returning True if successful,
    False otherwise.
    """
    try:
        lock = Lock(os.path.join(os.environ['HOME'], '.cciw_booking_lock'))
        lock.acquire()
        bookings = list(bookings)
        now = datetime.now()
        for b in bookings:
            if len(b.get_booking_problems()[0]) > 0:
                return False

        for b in bookings:
            b.state = BOOKING_BOOKED
            b.booking_expires = now + timedelta(1) # 24 hours
            b.save()

        # In some cases we may have enough money to pay for places from money in
        # account. Since a payment will not be needed or received, we need to
        # make sure these don't expire.
        seen_accounts = set()
        for b in bookings:
            if b.account_id in seen_accounts:
                continue
            b.account.distribute_balance()
            seen_accounts.add(b.account_id)

        return True
    finally:
        lock.release()


# See process_payments management command for explanation

class PaymentManager(models.Manager):
    use_for_related_fields = True

    def get_query_set(self):
        return super(PaymentManager, self).get_query_set().select_related('account')


class Payment(models.Model):
    amount = models.DecimalField(decimal_places=2, max_digits=10)
    account = models.ForeignKey(BookingAccount)
    origin_id = models.PositiveIntegerField()
    origin_type = models.ForeignKey(ContentType)
    origin = generic.GenericForeignKey('origin_type', 'origin_id')
    processed = models.DateTimeField(null=True)
    created = models.DateTimeField()

    objects = PaymentManager()

    def __unicode__(self):
        return u"<Payment: %s to %s from %s>" % (self.amount, self.account, self.origin)


class ChequePaymentManager(models.Manager):
    use_for_related_fields = True

    def get_query_set(self):
        return super(ChequePaymentManager, self).get_query_set().select_related('account')


class ChequePaymentBase(models.Model):
    amount = models.DecimalField(decimal_places=2, max_digits=10)
    account = models.ForeignKey(BookingAccount)
    created = models.DateTimeField(default=datetime.now)

    objects = ChequePaymentManager()

    def save(self, **kwargs):
        if self.id is not None:
            raise Exception("%s cannot be edited after it has been saved to DB" %
                            self.__class__.__name__)
        else:
            return super(ChequePaymentBase, self).save(**kwargs)

    class Meta:
        abstract = True


class ChequePayment(ChequePaymentBase):

    def __unicode__(self):
        return u"Cheque payment of £%s from %s" % (self.amount, self.account)


class RefundPayment(ChequePaymentBase):

    def __unicode__(self):
        return u"Refund payment of £%s to %s" % (self.amount, self.account)


def trigger_payment_processing():
    # NB - this is always called from a web request, for which the virtualenv
    # has been set up in os.environ, so this is passed on and the correct python
    # runs manage.py.
    manage_py = os.path.join(settings.BASE_DIR, 'manage.py')
    os.spawnl(os.P_NOWAIT, manage_py, 'manage.py', 'process_payments')


def send_payment(amount, to_account, from_obj):
    Payment.objects.create(amount=amount,
                           account=to_account,
                           origin=from_obj,
                           processed=None,
                           created=datetime.now())
    trigger_payment_processing()


# Very important that the setup done in .hooks happens:
from .hooks import *
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.