Files @ 1c239c361f00
Branch filter:

Location: symposion_app/registrasion/controllers/cart.py - annotation

Christopher Neugebauer
Propagates the per_user_limit category error to the products, rather than the category.

Fixes #79.
  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
64ca477cb89a
64ca477cb89a
64ca477cb89a
64ca477cb89a
64ca477cb89a
64ca477cb89a
576dddcaad19
d9e433659d01
a69d3f051e6b
312fffd137c2
d9e433659d01
d9e433659d01
d9e433659d01
39021cd3dd3e
760996588372
6d52a4c18ff8
d9e433659d01
d9e433659d01
a4d684f444e7
875f736d67c5
875f736d67c5
875f736d67c5
d9e433659d01
d9e433659d01
a69d3f051e6b
a69d3f051e6b
587e6e20b284
587e6e20b284
587e6e20b284
587e6e20b284
587e6e20b284
a69d3f051e6b
a69d3f051e6b
a69d3f051e6b
a69d3f051e6b
587e6e20b284
3d635521ebf6
3d635521ebf6
3d635521ebf6
3d635521ebf6
587e6e20b284
a69d3f051e6b
a69d3f051e6b
a69d3f051e6b
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
eab1deff7776
3d635521ebf6
eab1deff7776
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
63dfd353c16e
63dfd353c16e
63dfd353c16e
63dfd353c16e
d9e433659d01
875f736d67c5
d9e433659d01
d9e433659d01
d9e433659d01
63dfd353c16e
eab1deff7776
d9e433659d01
a69d3f051e6b
a69d3f051e6b
a69d3f051e6b
a69d3f051e6b
a69d3f051e6b
587e6e20b284
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
875f736d67c5
d9e433659d01
d9e433659d01
875f736d67c5
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
3d635521ebf6
3d635521ebf6
3d635521ebf6
64ca477cb89a
3d635521ebf6
3d635521ebf6
587e6e20b284
c51be4d30aff
39021cd3dd3e
587e6e20b284
587e6e20b284
587e6e20b284
587e6e20b284
587e6e20b284
39021cd3dd3e
39021cd3dd3e
587e6e20b284
587e6e20b284
587e6e20b284
587e6e20b284
587e6e20b284
c51be4d30aff
c51be4d30aff
d9e433659d01
a69d3f051e6b
39021cd3dd3e
312fffd137c2
312fffd137c2
312fffd137c2
312fffd137c2
39021cd3dd3e
875f736d67c5
53413388e016
53413388e016
53413388e016
53413388e016
53413388e016
312fffd137c2
576dddcaad19
312fffd137c2
312fffd137c2
312fffd137c2
312fffd137c2
312fffd137c2
312fffd137c2
39021cd3dd3e
312fffd137c2
e3ec12814779
e3ec12814779
6d52a4c18ff8
6d52a4c18ff8
e3ec12814779
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
6d52a4c18ff8
e3ec12814779
e3ec12814779
312fffd137c2
c24b9ee213b9
312fffd137c2
a4d684f444e7
a4d684f444e7
a79ad3520e60
941caa30d9f4
a79ad3520e60
312fffd137c2
312fffd137c2
312fffd137c2
a4d684f444e7
312fffd137c2
941caa30d9f4
312fffd137c2
312fffd137c2
a4d684f444e7
a4d684f444e7
312fffd137c2
a4d684f444e7
312fffd137c2
a4d684f444e7
312fffd137c2
576dddcaad19
576dddcaad19
576dddcaad19
576dddcaad19
576dddcaad19
a79ad3520e60
c6fdfa496e84
a79ad3520e60
576dddcaad19
a4d684f444e7
c6fdfa496e84
576dddcaad19
576dddcaad19
a4d684f444e7
576dddcaad19
e3ec12814779
1c239c361f00
1c239c361f00
1c239c361f00
1c239c361f00
1c239c361f00
576dddcaad19
c24b9ee213b9
145fd057aca0
1e7a2abc7f92
e3ec12814779
1e7a2abc7f92
1e7a2abc7f92
1e7a2abc7f92
40bc5985f4b8
40bc5985f4b8
a4d684f444e7
a4d684f444e7
a4d684f444e7
39021cd3dd3e
a69d3f051e6b
cc4249083219
cc4249083219
d9e433659d01
cc4249083219
875f736d67c5
cc4249083219
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
6f28c20b706f
6f28c20b706f
6f28c20b706f
6f28c20b706f
6f28c20b706f
6f28c20b706f
6f28c20b706f
6f28c20b706f
6f28c20b706f
6f28c20b706f
875f736d67c5
6f28c20b706f
2d5cd622c517
d9e433659d01
0d57da8d6f66
c8c16072ba87
8e95bb746990
8e95bb746990
d9e433659d01
2d5cd622c517
0d57da8d6f66
2d5cd622c517
2d5cd622c517
0d57da8d6f66
c8c16072ba87
2d5cd622c517
2d5cd622c517
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
d9e433659d01
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
f5d9458d1a9c
f5d9458d1a9c
f5d9458d1a9c
f5d9458d1a9c
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
0d57da8d6f66
d9e433659d01
875f736d67c5
4fb569d9353d
d9e433659d01
e3ec12814779
f5d9458d1a9c
f5d9458d1a9c
f5d9458d1a9c
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
b709da97f1bf
d9e433659d01
d9e433659d01
3f1be0e14e06
3f1be0e14e06
d9e433659d01
135f2fb47b13
135f2fb47b13
135f2fb47b13
135f2fb47b13
135f2fb47b13
135f2fb47b13
135f2fb47b13
135f2fb47b13
135f2fb47b13
135f2fb47b13
135f2fb47b13
d9e433659d01
d9e433659d01
d9e433659d01
135f2fb47b13
f5d9458d1a9c
f5d9458d1a9c
f5d9458d1a9c
d9e433659d01
f5d9458d1a9c
f5d9458d1a9c
f5d9458d1a9c
a69d3f051e6b
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
c8c16072ba87
c8c16072ba87
c8c16072ba87
c8c16072ba87
c8c16072ba87
8e95bb746990
c8c16072ba87
c8c16072ba87
c8c16072ba87
c8c16072ba87
7d97d2d2dea1
7d97d2d2dea1
875f736d67c5
53413388e016
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
7d97d2d2dea1
f5d9458d1a9c
587e6e20b284
587e6e20b284
d9e433659d01
d9e433659d01
875f736d67c5
d9e433659d01
53413388e016
c0b0ae780d07
53413388e016
c41a9cadffb9
c41a9cadffb9
162db2481781
162db2481781
162db2481781
162db2481781
162db2481781
c41a9cadffb9
0182a32f0347
0182a32f0347
0182a32f0347
0182a32f0347
c41a9cadffb9
d9e433659d01
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
d9e433659d01
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
875f736d67c5
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
d9e433659d01
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
c41a9cadffb9
d9e433659d01
d9e433659d01
c41a9cadffb9
c41a9cadffb9
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
875f736d67c5
d9e433659d01
d9e433659d01
c41a9cadffb9
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
c41a9cadffb9
d9e433659d01
d9e433659d01
63dfd353c16e
d9e433659d01
d9e433659d01
d9e433659d01
d9e433659d01
c2400c4695ae
c41a9cadffb9
from .batch import BatchController
from .category import CategoryController
from .discount import DiscountController
from .flag import FlagController
from .product import ProductController

import collections
import datetime
import functools
import itertools

from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import Max
from django.db.models import Q
from django.utils import timezone

from registrasion.exceptions import CartValidationError
from registrasion.models import commerce
from registrasion.models import conditions
from registrasion.models import inventory


def _modifies_cart(func):
    ''' Decorator that makes the wrapped function raise ValidationError
    if we're doing something that could modify the cart.

    It also wraps the execution of this function in a database transaction,
    and marks the boundaries of a cart operations batch.
    '''

    @functools.wraps(func)
    def inner(self, *a, **k):
        self._fail_if_cart_is_not_active()
        with transaction.atomic():
            with BatchController.batch(self.cart.user):
                # Mark the version of self in the batch cache as modified
                memoised = self.for_user(self.cart.user)
                memoised._modified_by_batch = True
                return func(self, *a, **k)
    return inner


class CartController(object):

    def __init__(self, cart):
        self.cart = cart

    @classmethod
    @BatchController.memoise
    def for_user(cls, user):
        ''' Returns the user's current cart, or creates a new cart
        if there isn't one ready yet. '''

        try:
            existing = commerce.Cart.objects.get(
                user=user,
                status=commerce.Cart.STATUS_ACTIVE,
            )
        except ObjectDoesNotExist:
            existing = commerce.Cart.objects.create(
                user=user,
                time_last_updated=timezone.now(),
                reservation_duration=datetime.timedelta(),
            )
        return cls(existing)

    def _fail_if_cart_is_not_active(self):
        self.cart.refresh_from_db()
        if self.cart.status != commerce.Cart.STATUS_ACTIVE:
            raise ValidationError("You can only amend active carts.")

    def _autoextend_reservation(self):
        ''' Updates the cart's time last updated value, which is used to
        determine whether the cart has reserved the items and discounts it
        holds. '''

        reservations = [datetime.timedelta()]

        # If we have vouchers, we're entitled to an hour at minimum.
        if len(self.cart.vouchers.all()) >= 1:
            reservations.append(inventory.Voucher.RESERVATION_DURATION)

        # Else, it's the maximum of the included products
        items = commerce.ProductItem.objects.filter(cart=self.cart)
        agg = items.aggregate(Max("product__reservation_duration"))
        product_max = agg["product__reservation_duration__max"]

        if product_max is not None:
            reservations.append(product_max)

        self.cart.time_last_updated = timezone.now()
        self.cart.reservation_duration = max(reservations)

    def end_batch(self):
        ''' Calls ``_end_batch`` if a modification has been performed in the
        previous batch. '''
        if hasattr(self, '_modified_by_batch'):
            self._end_batch()

    def _end_batch(self):
        ''' Performs operations that occur occur at the end of a batch of
        product changes/voucher applications etc.

        You need to call this after you've finished modifying the user's cart.
        This is normally done by wrapping a block of code using
        ``operations_batch``.

        '''

        self.cart.refresh_from_db()

        self._recalculate_discounts()

        self._autoextend_reservation()
        self.cart.revision += 1
        self.cart.save()

    @_modifies_cart
    def set_quantities(self, product_quantities):
        ''' Sets the quantities on each of the products on each of the
        products specified. Raises an exception (ValidationError) if a limit
        is violated. `product_quantities` is an iterable of (product, quantity)
        pairs. '''

        items_in_cart = commerce.ProductItem.objects.filter(cart=self.cart)
        items_in_cart = items_in_cart.select_related(
            "product",
            "product__category",
        )

        product_quantities = list(product_quantities)

        # n.b need to add have the existing items first so that the new
        # items override the old ones.
        all_product_quantities = dict(itertools.chain(
            ((i.product, i.quantity) for i in items_in_cart.all()),
            product_quantities,
        )).items()

        # Validate that the limits we're adding are OK
        self._test_limits(all_product_quantities)

        new_items = []
        products = []
        for product, quantity in product_quantities:
            products.append(product)

            if quantity == 0:
                continue

            item = commerce.ProductItem(
                cart=self.cart,
                product=product,
                quantity=quantity,
            )
            new_items.append(item)

        to_delete = (
            Q(quantity=0) |
            Q(product__in=products)
        )

        items_in_cart.filter(to_delete).delete()
        commerce.ProductItem.objects.bulk_create(new_items)

    def _test_limits(self, product_quantities):
        ''' Tests that the quantity changes we intend to make do not violate
        the limits and flag conditions imposed on the products. '''

        errors = []

        # Pre-annotate products
        remainders = ProductController.user_remainders(self.cart.user)

        # Test each product limit here
        for product, quantity in product_quantities:
            if quantity < 0:
                errors.append((product, "Value must be zero or greater."))

            limit = remainders[product.id]

            if quantity > limit:
                errors.append((
                    product,
                    "You may only have %d of product: %s" % (
                        limit, product,
                    )
                ))

        # Collect by category
        by_cat = collections.defaultdict(list)
        for product, quantity in product_quantities:
            by_cat[product.category].append((product, quantity))

        # Pre-annotate categories
        remainders = CategoryController.user_remainders(self.cart.user)

        # Test each category limit here
        for category in by_cat:
            limit = remainders[category.id]

            # Get the amount so far in the cart
            to_add = sum(i[1] for i in by_cat[category])

            if to_add > limit:
                message = "You may only have %d items in category: %s" % (
                    limit, category.name,
                )
                for product, quantity in by_cat[category]:
                    errors.append((product, message))

        # Test the flag conditions
        errs = FlagController.test_flags(
            self.cart.user,
            product_quantities=product_quantities,
        )

        if errs:
            for error in errs:
                errors.append(error)

        if errors:
            raise CartValidationError(errors)

    @_modifies_cart
    def apply_voucher(self, voucher_code):
        ''' Applies the voucher with the given code to this cart. '''

        # Try and find the voucher
        voucher = inventory.Voucher.objects.get(code=voucher_code.upper())

        # Re-applying vouchers should be idempotent
        if voucher in self.cart.vouchers.all():
            return

        self._test_voucher(voucher)

        # If successful...
        self.cart.vouchers.add(voucher)

    def _test_voucher(self, voucher):
        ''' Tests whether this voucher is allowed to be applied to this cart.
        Raises ValidationError if not. '''

        # Is voucher exhausted?
        active_carts = commerce.Cart.reserved_carts()

        # It's invalid for a user to enter a voucher that's exhausted
        carts_with_voucher = active_carts.filter(vouchers=voucher)
        carts_with_voucher = carts_with_voucher.exclude(pk=self.cart.id)
        if carts_with_voucher.count() >= voucher.limit:
            raise ValidationError(
                "Voucher %s is no longer available" % voucher.code)

        # It's not valid for users to re-enter a voucher they already have
        user_carts_with_voucher = carts_with_voucher.filter(
            user=self.cart.user,
        )

        if user_carts_with_voucher.count() > 0:
            raise ValidationError("You have already entered this voucher.")

    def _test_vouchers(self, vouchers):
        ''' Tests each of the vouchers against self._test_voucher() and raises
        the collective ValidationError.
        Future work will refactor _test_voucher in terms of this, and save some
        queries. '''
        errors = []
        for voucher in vouchers:
            try:
                self._test_voucher(voucher)
            except ValidationError as ve:
                errors.append(ve)

        if errors:
            raise(ValidationError(ve))

    def _test_required_categories(self):
        ''' Makes sure that the owner of this cart has satisfied all of the
        required category constraints in the inventory (be it in this cart
        or others). '''

        required = set(inventory.Category.objects.filter(required=True))

        items = commerce.ProductItem.objects.filter(
            product__category__required=True,
            cart__user=self.cart.user,
        ).exclude(
            cart__status=commerce.Cart.STATUS_RELEASED,
        )

        for item in items:
            required.remove(item.product.category)

        errors = []
        for category in required:
            msg = "You must have at least one item from: %s" % category
            errors.append((None, msg))

        if errors:
            raise ValidationError(errors)

    def _append_errors(self, errors, ve):
        for error in ve.error_list:
            errors.append(error.message[1])

    def validate_cart(self):
        ''' Determines whether the status of the current cart is valid;
        this is normally called before generating or paying an invoice '''

        cart = self.cart
        user = self.cart.user
        errors = []

        try:
            self._test_vouchers(self.cart.vouchers.all())
        except ValidationError as ve:
            errors.append(ve)

        items = commerce.ProductItem.objects.filter(cart=cart)
        items = items.select_related("product", "product__category")

        product_quantities = list((i.product, i.quantity) for i in items)
        try:
            self._test_limits(product_quantities)
        except ValidationError as ve:
            self._append_errors(errors, ve)

        try:
            self._test_required_categories()
        except ValidationError as ve:
            self._append_errors(errors, ve)

        # Validate the discounts
        # TODO: refactor in terms of available_discounts
        # why aren't we doing that here?!

        #     def available_discounts(cls, user, categories, products):

        products = [i.product for i in items]
        discounts_with_quantity = DiscountController.available_discounts(
            user,
            [],
            products,
        )
        discounts = set(i.discount.id for i in discounts_with_quantity)

        discount_items = commerce.DiscountItem.objects.filter(cart=cart)
        for discount_item in discount_items:
            discount = discount_item.discount

            if discount.id not in discounts:
                errors.append(
                    ValidationError("Discounts are no longer available")
                )

        if errors:
            raise ValidationError(errors)

    @_modifies_cart
    def fix_simple_errors(self):
        ''' This attempts to fix the easy errors raised by ValidationError.
        This includes removing items from the cart that are no longer
        available, recalculating all of the discounts, and removing voucher
        codes that are no longer available. '''

        # Fix vouchers first (this affects available discounts)
        to_remove = []
        for voucher in self.cart.vouchers.all():
            try:
                self._test_voucher(voucher)
            except ValidationError:
                to_remove.append(voucher)

        for voucher in to_remove:
            self.cart.vouchers.remove(voucher)

        # Fix products and discounts
        items = commerce.ProductItem.objects.filter(cart=self.cart)
        items = items.select_related("product")
        products = set(i.product for i in items)
        available = set(ProductController.available_products(
            self.cart.user,
            products=products,
        ))

        not_available = products - available
        zeros = [(product, 0) for product in not_available]

        self.set_quantities(zeros)

    @transaction.atomic
    def _recalculate_discounts(self):
        ''' Calculates all of the discounts available for this product.'''

        # Delete the existing entries.
        commerce.DiscountItem.objects.filter(cart=self.cart).delete()

        product_items = self.cart.productitem_set.all().select_related(
            "product", "product__category", "product__price"
        )

        products = [i.product for i in product_items]
        discounts = DiscountController.available_discounts(
            self.cart.user,
            [],
            products,
        )

        # The highest-value discounts will apply to the highest-value
        # products first.
        product_items = reversed(product_items)
        for item in product_items:
            self._add_discount(item.product, item.quantity, discounts)

    def _add_discount(self, product, quantity, discounts):
        ''' Applies the best discounts on the given product, from the given
        discounts.'''

        def matches(discount):
            ''' Returns True if and only if the given discount apples to
            our product. '''
            if isinstance(discount.clause, conditions.DiscountForCategory):
                return discount.clause.category == product.category
            else:
                return discount.clause.product == product

        def value(discount):
            ''' Returns the value of this discount clause
            as applied to this product '''
            if discount.clause.percentage is not None:
                return discount.clause.percentage * product.price
            else:
                return discount.clause.price

        discounts = [i for i in discounts if matches(i)]
        discounts.sort(key=value)

        for candidate in reversed(discounts):
            if quantity == 0:
                break
            elif candidate.quantity == 0:
                # This discount clause has been exhausted by this cart
                continue

            # Get a provisional instance for this DiscountItem
            # with the quantity set to as much as we have in the cart
            discount_item = commerce.DiscountItem.objects.create(
                product=product,
                cart=self.cart,
                discount=candidate.discount,
                quantity=quantity,
            )

            # Truncate the quantity for this DiscountItem if we exceed quantity
            ours = discount_item.quantity
            allowed = candidate.quantity
            if ours > allowed:
                discount_item.quantity = allowed
                discount_item.save()
                # Update the remaining quantity.
                quantity = ours - allowed
            else:
                quantity = 0

            candidate.quantity -= discount_item.quantity