-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
abstract_models.py
1069 lines (892 loc) · 35.9 KB
/
abstract_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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from itertools import chain
from decimal import Decimal as D
import hashlib
from django.conf import settings
from django.db import models
from django.db.models import Sum
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _, pgettext_lazy
from django.utils.datastructures import SortedDict
from django.utils.timezone import now
from oscar.core.utils import get_default_currency
from oscar.core.compat import AUTH_USER_MODEL
from oscar.models.fields import AutoSlugField
from . import exceptions
@python_2_unicode_compatible
class AbstractOrder(models.Model):
"""
The main order model
"""
number = models.CharField(
_("Order number"), max_length=128, db_index=True, unique=True)
# We track the site that each order is placed within
site = models.ForeignKey(
'sites.Site', verbose_name=_("Site"), null=True,
on_delete=models.SET_NULL)
basket = models.ForeignKey(
'basket.Basket', verbose_name=_("Basket"),
null=True, blank=True, on_delete=models.SET_NULL)
# Orders can be placed without the user authenticating so we don't always
# have a customer ID.
user = models.ForeignKey(
AUTH_USER_MODEL, related_name='orders', null=True, blank=True,
verbose_name=_("User"), on_delete=models.SET_NULL)
# Billing address is not always required (eg paying by gift card)
billing_address = models.ForeignKey(
'order.BillingAddress', null=True, blank=True,
verbose_name=_("Billing Address"),
on_delete=models.SET_NULL)
# Total price looks like it could be calculated by adding up the
# prices of the associated lines, but in some circumstances extra
# order-level charges are added and so we need to store it separately
currency = models.CharField(
_("Currency"), max_length=12, default=get_default_currency)
total_incl_tax = models.DecimalField(
_("Order total (inc. tax)"), decimal_places=2, max_digits=12)
total_excl_tax = models.DecimalField(
_("Order total (excl. tax)"), decimal_places=2, max_digits=12)
# Shipping charges
shipping_incl_tax = models.DecimalField(
_("Shipping charge (inc. tax)"), decimal_places=2, max_digits=12,
default=0)
shipping_excl_tax = models.DecimalField(
_("Shipping charge (excl. tax)"), decimal_places=2, max_digits=12,
default=0)
# Not all lines are actually shipped (such as downloads), hence shipping
# address is not mandatory.
shipping_address = models.ForeignKey(
'order.ShippingAddress', null=True, blank=True,
verbose_name=_("Shipping Address"),
on_delete=models.SET_NULL)
shipping_method = models.CharField(
_("Shipping method"), max_length=128, blank=True)
# Identifies shipping code
shipping_code = models.CharField(blank=True, max_length=128, default="")
# Use this field to indicate that an order is on hold / awaiting payment
status = models.CharField(_("Status"), max_length=100, blank=True)
guest_email = models.EmailField(_("Guest email address"), blank=True)
# Index added to this field for reporting
date_placed = models.DateTimeField(db_index=True)
#: Order status pipeline. This should be a dict where each (key, value) #:
#: corresponds to a status and a list of possible statuses that can follow
#: that one.
pipeline = getattr(settings, 'OSCAR_ORDER_STATUS_PIPELINE', {})
#: Order status cascade pipeline. This should be a dict where each (key,
#: value) pair corresponds to an *order* status and the corresponding
#: *line* status that needs to be set when the order is set to the new
#: status
cascade = getattr(settings, 'OSCAR_ORDER_STATUS_CASCADE', {})
@classmethod
def all_statuses(cls):
"""
Return all possible statuses for an order
"""
return list(cls.pipeline.keys())
def available_statuses(self):
"""
Return all possible statuses that this order can move to
"""
return self.pipeline.get(self.status, ())
def set_status(self, new_status):
"""
Set a new status for this order.
If the requested status is not valid, then ``InvalidOrderStatus`` is
raised.
"""
if new_status == self.status:
return
if new_status not in self.available_statuses():
raise exceptions.InvalidOrderStatus(
_("'%(new_status)s' is not a valid status for order %(number)s"
" (current status: '%(status)s')")
% {'new_status': new_status,
'number': self.number,
'status': self.status})
self.status = new_status
if new_status in self.cascade:
for line in self.lines.all():
line.status = self.cascade[self.status]
line.save()
self.save()
set_status.alters_data = True
@property
def is_anonymous(self):
# It's possible for an order to be placed by a customer who then
# deletes their profile. Hence, we need to check that a guest email is
# set.
return self.user is None and bool(self.guest_email)
@property
def basket_total_before_discounts_incl_tax(self):
"""
Return basket total including tax but before discounts are applied
"""
total = D('0.00')
for line in self.lines.all():
total += line.line_price_before_discounts_incl_tax
return total
@property
def basket_total_before_discounts_excl_tax(self):
"""
Return basket total excluding tax but before discounts are applied
"""
total = D('0.00')
for line in self.lines.all():
total += line.line_price_before_discounts_excl_tax
return total
@property
def basket_total_incl_tax(self):
"""
Return basket total including tax
"""
return self.total_incl_tax - self.shipping_incl_tax
@property
def basket_total_excl_tax(self):
"""
Return basket total excluding tax
"""
return self.total_excl_tax - self.shipping_excl_tax
@property
def total_before_discounts_incl_tax(self):
return (self.basket_total_before_discounts_incl_tax +
self.shipping_incl_tax)
@property
def total_before_discounts_excl_tax(self):
return (self.basket_total_before_discounts_excl_tax +
self.shipping_excl_tax)
@property
def total_discount_incl_tax(self):
"""
The amount of discount this order received
"""
discount = D('0.00')
for line in self.lines.all():
discount += line.discount_incl_tax
return discount
@property
def total_discount_excl_tax(self):
discount = D('0.00')
for line in self.lines.all():
discount += line.discount_excl_tax
return discount
@property
def total_tax(self):
return self.total_incl_tax - self.total_excl_tax
@property
def num_lines(self):
return self.lines.count()
@property
def num_items(self):
"""
Returns the number of items in this order.
"""
num_items = 0
for line in self.lines.all():
num_items += line.quantity
return num_items
@property
def shipping_tax(self):
return self.shipping_incl_tax - self.shipping_excl_tax
@property
def shipping_status(self):
events = self.shipping_events.all()
if not len(events):
return ''
# Collect all events by event-type
map = {}
for event in events:
event_name = event.event_type.name
if event_name not in map:
map[event_name] = []
map[event_name] = list(chain(map[event_name],
event.line_quantities.all()))
# Determine last complete event
status = _("In progress")
for event_name, event_line_quantities in map.items():
if self._is_event_complete(event_line_quantities):
status = event_name
return status
@property
def has_shipping_discounts(self):
return len(self.shipping_discounts) > 0
@property
def shipping_before_discounts_incl_tax(self):
# We can construct what shipping would have been before discounts by
# adding the discounts back onto the final shipping charge.
total = D('0.00')
for discount in self.shipping_discounts:
total += discount.amount
return self.shipping_incl_tax + total
def _is_event_complete(self, event_quantities):
# Form map of line to quantity
map = {}
for event_quantity in event_quantities:
line_id = event_quantity.line_id
map.setdefault(line_id, 0)
map[line_id] += event_quantity.quantity
for line in self.lines.all():
if map[line.id] != line.quantity:
return False
return True
class Meta:
abstract = True
app_label = 'order'
ordering = ['-date_placed']
verbose_name = _("Order")
verbose_name_plural = _("Orders")
def __str__(self):
return u"#%s" % (self.number,)
def verification_hash(self):
key = '%s%s' % (self.number, settings.SECRET_KEY)
hash = hashlib.md5(key.encode('utf8'))
return hash.hexdigest()
@property
def email(self):
if not self.user:
return self.guest_email
return self.user.email
@property
def basket_discounts(self):
# This includes both offer- and voucher- discounts. For orders we
# don't need to treat them differently like we do for baskets.
return self.discounts.filter(
category=AbstractOrderDiscount.BASKET)
@property
def shipping_discounts(self):
return self.discounts.filter(
category=AbstractOrderDiscount.SHIPPING)
@property
def post_order_actions(self):
return self.discounts.filter(
category=AbstractOrderDiscount.DEFERRED)
def set_date_placed_default(self):
if self.date_placed is None:
self.date_placed = now()
def save(self, *args, **kwargs):
# Ensure the date_placed field works as it auto_now_add was set. But
# this gives us the ability to set the date_placed explicitly (which is
# useful when importing orders from another system).
self.set_date_placed_default()
super(AbstractOrder, self).save(*args, **kwargs)
@python_2_unicode_compatible
class AbstractOrderNote(models.Model):
"""
A note against an order.
This are often used for audit purposes too. IE, whenever an admin
makes a change to an order, we create a note to record what happened.
"""
order = models.ForeignKey('order.Order', related_name="notes",
verbose_name=_("Order"))
# These are sometimes programatically generated so don't need a
# user everytime
user = models.ForeignKey(AUTH_USER_MODEL, null=True,
verbose_name=_("User"))
# We allow notes to be classified although this isn't always needed
INFO, WARNING, ERROR, SYSTEM = 'Info', 'Warning', 'Error', 'System'
note_type = models.CharField(_("Note Type"), max_length=128, blank=True)
message = models.TextField(_("Message"))
date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
date_updated = models.DateTimeField(_("Date Updated"), auto_now=True)
# Notes can only be edited for 5 minutes after being created
editable_lifetime = 300
class Meta:
abstract = True
app_label = 'order'
verbose_name = _("Order Note")
verbose_name_plural = _("Order Notes")
def __str__(self):
return u"'%s' (%s)" % (self.message[0:50], self.user)
def is_editable(self):
if self.note_type == self.SYSTEM:
return False
delta = timezone.now() - self.date_updated
return delta.seconds < self.editable_lifetime
@python_2_unicode_compatible
class AbstractCommunicationEvent(models.Model):
"""
An order-level event involving a communication to the customer, such
as an confirmation email being sent.
"""
order = models.ForeignKey(
'order.Order', related_name="communication_events",
verbose_name=_("Order"))
event_type = models.ForeignKey(
'customer.CommunicationEventType', verbose_name=_("Event Type"))
date_created = models.DateTimeField(_("Date"), auto_now_add=True)
class Meta:
abstract = True
app_label = 'order'
verbose_name = _("Communication Event")
verbose_name_plural = _("Communication Events")
ordering = ['-date_created']
def __str__(self):
return _("'%(type)s' event for order #%(number)s") \
% {'type': self.event_type.name, 'number': self.order.number}
# LINES
@python_2_unicode_compatible
class AbstractLine(models.Model):
"""
An order line
"""
order = models.ForeignKey(
'order.Order', related_name='lines', verbose_name=_("Order"))
# PARTNER INFORMATION
# -------------------
# We store the partner and various detail their SKU and the title for cases
# where the product has been deleted from the catalogue (but we still need
# the data for reporting). We also store the partner name in case the
# partner gets deleted at a later date.
partner = models.ForeignKey(
'partner.Partner', related_name='order_lines', blank=True, null=True,
on_delete=models.SET_NULL, verbose_name=_("Partner"))
partner_name = models.CharField(
_("Partner name"), max_length=128, blank=True)
partner_sku = models.CharField(_("Partner SKU"), max_length=128)
# A line reference is the ID that a partner uses to represent this
# particular line (it's not the same as a SKU).
partner_line_reference = models.CharField(
_("Partner reference"), max_length=128, blank=True,
help_text=_("This is the item number that the partner uses "
"within their system"))
partner_line_notes = models.TextField(
_("Partner Notes"), blank=True)
# We keep a link to the stockrecord used for this line which allows us to
# update stocklevels when it ships
stockrecord = models.ForeignKey(
'partner.StockRecord', on_delete=models.SET_NULL, blank=True,
null=True, verbose_name=_("Stock record"))
# PRODUCT INFORMATION
# -------------------
# We don't want any hard links between orders and the products table so we
# allow this link to be NULLable.
product = models.ForeignKey(
'catalogue.Product', on_delete=models.SET_NULL, blank=True, null=True,
verbose_name=_("Product"))
title = models.CharField(
pgettext_lazy(u"Product title", u"Title"), max_length=255)
# UPC can be null because it's usually set as the product's UPC, and that
# can be null as well
upc = models.CharField(_("UPC"), max_length=128, blank=True, null=True)
quantity = models.PositiveIntegerField(_("Quantity"), default=1)
# REPORTING INFORMATION
# ---------------------
# Price information (these fields are actually redundant as the information
# can be calculated from the LinePrice models
line_price_incl_tax = models.DecimalField(
_("Price (inc. tax)"), decimal_places=2, max_digits=12)
line_price_excl_tax = models.DecimalField(
_("Price (excl. tax)"), decimal_places=2, max_digits=12)
# Price information before discounts are applied
line_price_before_discounts_incl_tax = models.DecimalField(
_("Price before discounts (inc. tax)"),
decimal_places=2, max_digits=12)
line_price_before_discounts_excl_tax = models.DecimalField(
_("Price before discounts (excl. tax)"),
decimal_places=2, max_digits=12)
# Cost price (the price charged by the fulfilment partner for this
# product).
unit_cost_price = models.DecimalField(
_("Unit Cost Price"), decimal_places=2, max_digits=12, blank=True,
null=True)
# Normal site price for item (without discounts)
unit_price_incl_tax = models.DecimalField(
_("Unit Price (inc. tax)"), decimal_places=2, max_digits=12,
blank=True, null=True)
unit_price_excl_tax = models.DecimalField(
_("Unit Price (excl. tax)"), decimal_places=2, max_digits=12,
blank=True, null=True)
# Retail price at time of purchase
unit_retail_price = models.DecimalField(
_("Unit Retail Price"), decimal_places=2, max_digits=12,
blank=True, null=True)
# Partners often want to assign some status to each line to help with their
# own business processes.
status = models.CharField(_("Status"), max_length=255, blank=True)
# Estimated dispatch date - should be set at order time
est_dispatch_date = models.DateField(
_("Estimated Dispatch Date"), blank=True, null=True)
#: Order status pipeline. This should be a dict where each (key, value)
#: corresponds to a status and the possible statuses that can follow that
#: one.
pipeline = getattr(settings, 'OSCAR_LINE_STATUS_PIPELINE', {})
class Meta:
abstract = True
app_label = 'order'
verbose_name = _("Order Line")
verbose_name_plural = _("Order Lines")
def __str__(self):
if self.product:
title = self.product.title
else:
title = _('<missing product>')
return _("Product '%(name)s', quantity '%(qty)s'") % {
'name': title, 'qty': self.quantity}
@classmethod
def all_statuses(cls):
"""
Return all possible statuses for an order line
"""
return list(cls.pipeline.keys())
def available_statuses(self):
"""
Return all possible statuses that this order line can move to
"""
return self.pipeline.get(self.status, ())
def set_status(self, new_status):
"""
Set a new status for this line
If the requested status is not valid, then ``InvalidLineStatus`` is
raised.
"""
if new_status == self.status:
return
if new_status not in self.available_statuses():
raise exceptions.InvalidLineStatus(
_("'%(new_status)s' is not a valid status (current status:"
" '%(status)s')")
% {'new_status': new_status, 'status': self.status})
self.status = new_status
self.save()
set_status.alters_data = True
@property
def category(self):
"""
Used by Google analytics tracking
"""
return None
@property
def description(self):
"""
Returns a description of this line including details of any
line attributes.
"""
desc = self.title
ops = []
for attribute in self.attributes.all():
ops.append("%s = '%s'" % (attribute.type, attribute.value))
if ops:
desc = "%s (%s)" % (desc, ", ".join(ops))
return desc
@property
def discount_incl_tax(self):
return self.line_price_before_discounts_incl_tax \
- self.line_price_incl_tax
@property
def discount_excl_tax(self):
return self.line_price_before_discounts_excl_tax \
- self.line_price_excl_tax
@property
def line_price_tax(self):
return self.line_price_incl_tax - self.line_price_excl_tax
@property
def unit_price_tax(self):
return self.unit_price_incl_tax - self.unit_price_excl_tax
# Shipping status helpers
@property
def shipping_status(self):
"""
Returns a string summary of the shipping status of this line
"""
status_map = self.shipping_event_breakdown
if not status_map:
return ''
events = []
last_complete_event_name = None
for event_dict in reversed(list(status_map.values())):
if event_dict['quantity'] == self.quantity:
events.append(event_dict['name'])
last_complete_event_name = event_dict['name']
else:
events.append("%s (%d/%d items)" % (
event_dict['name'], event_dict['quantity'],
self.quantity))
if last_complete_event_name == list(status_map.values())[0]['name']:
return last_complete_event_name
return ', '.join(events)
def is_shipping_event_permitted(self, event_type, quantity):
"""
Test whether a shipping event with the given quantity is permitted
This method should normally be overriden to ensure that the
prerequisite shipping events have been passed for this line.
"""
# Note, this calculation is simplistic - normally, you will also need
# to check if previous shipping events have occurred. Eg, you can't
# return lines until they have been shipped.
current_qty = self.shipping_event_quantity(event_type)
return (current_qty + quantity) <= self.quantity
def shipping_event_quantity(self, event_type):
"""
Return the quantity of this line that has been involved in a shipping
event of the passed type.
"""
result = self.shipping_event_quantities.filter(
event__event_type=event_type).aggregate(Sum('quantity'))
if result['quantity__sum'] is None:
return 0
else:
return result['quantity__sum']
def has_shipping_event_occurred(self, event_type, quantity=None):
"""
Test whether this line has passed a given shipping event
"""
if not quantity:
quantity = self.quantity
return self.shipping_event_quantity(event_type) == quantity
def get_event_quantity(self, event):
"""
Fetches the ShippingEventQuantity instance for this line
Exists as a separate method so it can be overridden to avoid
the DB query that's caused by get().
"""
return event.line_quantities.get(line=self)
@property
def shipping_event_breakdown(self):
"""
Returns a dict of shipping events that this line has been through
"""
status_map = SortedDict()
for event in self.shipping_events.all():
event_type = event.event_type
event_name = event_type.name
event_quantity = self.get_event_quantity(event).quantity
if event_name in status_map:
status_map[event_name]['quantity'] += event_quantity
else:
status_map[event_name] = {
'event_type': event_type,
'name': event_name,
'quantity': event_quantity
}
return status_map
# Payment event helpers
def is_payment_event_permitted(self, event_type, quantity):
"""
Test whether a payment event with the given quantity is permitted.
Allow each payment event type to occur only once per quantity.
"""
current_qty = self.payment_event_quantity(event_type)
return (current_qty + quantity) <= self.quantity
def payment_event_quantity(self, event_type):
"""
Return the quantity of this line that has been involved in a payment
event of the passed type.
"""
result = self.payment_event_quantities.filter(
event__event_type=event_type).aggregate(Sum('quantity'))
if result['quantity__sum'] is None:
return 0
else:
return result['quantity__sum']
@property
def is_product_deleted(self):
return self.product is None
def is_available_to_reorder(self, basket, strategy):
"""
Test if this line can be re-ordered using the passed strategy and
basket
"""
if not self.product:
return False, (_("'%(title)s' is no longer available") %
{'title': self.title})
try:
basket_line = basket.lines.get(product=self.product)
except basket.lines.model.DoesNotExist:
desired_qty = self.quantity
else:
desired_qty = basket_line.quantity + self.quantity
result = strategy.fetch_for_product(self.product)
is_available, reason = result.availability.is_purchase_permitted(
quantity=desired_qty)
if not is_available:
return False, reason
return True, None
@python_2_unicode_compatible
class AbstractLineAttribute(models.Model):
"""
An attribute of a line
"""
line = models.ForeignKey(
'order.Line', related_name='attributes',
verbose_name=_("Line"))
option = models.ForeignKey(
'catalogue.Option', null=True, on_delete=models.SET_NULL,
related_name="line_attributes", verbose_name=_("Option"))
type = models.CharField(_("Type"), max_length=128)
value = models.CharField(_("Value"), max_length=255)
class Meta:
abstract = True
app_label = 'order'
verbose_name = _("Line Attribute")
verbose_name_plural = _("Line Attributes")
def __str__(self):
return "%s = %s" % (self.type, self.value)
@python_2_unicode_compatible
class AbstractLinePrice(models.Model):
"""
For tracking the prices paid for each unit within a line.
This is necessary as offers can lead to units within a line
having different prices. For example, one product may be sold at
50% off as it's part of an offer while the remainder are full price.
"""
order = models.ForeignKey(
'order.Order', related_name='line_prices', verbose_name=_("Option"))
line = models.ForeignKey(
'order.Line', related_name='prices', verbose_name=_("Line"))
quantity = models.PositiveIntegerField(_("Quantity"), default=1)
price_incl_tax = models.DecimalField(
_("Price (inc. tax)"), decimal_places=2, max_digits=12)
price_excl_tax = models.DecimalField(
_("Price (excl. tax)"), decimal_places=2, max_digits=12)
shipping_incl_tax = models.DecimalField(
_("Shiping (inc. tax)"), decimal_places=2, max_digits=12, default=0)
shipping_excl_tax = models.DecimalField(
_("Shipping (excl. tax)"), decimal_places=2, max_digits=12, default=0)
class Meta:
abstract = True
app_label = 'order'
ordering = ('id',)
verbose_name = _("Line Price")
verbose_name_plural = _("Line Prices")
def __str__(self):
return _("Line '%(number)s' (quantity %(qty)d) price %(price)s") % {
'number': self.line,
'qty': self.quantity,
'price': self.price_incl_tax}
# PAYMENT EVENTS
@python_2_unicode_compatible
class AbstractPaymentEventType(models.Model):
"""
Payment event types are things like 'Paid', 'Failed', 'Refunded'.
These are effectively the transaction types.
"""
name = models.CharField(_("Name"), max_length=128, unique=True)
code = AutoSlugField(_("Code"), max_length=128, unique=True,
populate_from='name')
class Meta:
abstract = True
app_label = 'order'
verbose_name = _("Payment Event Type")
verbose_name_plural = _("Payment Event Types")
ordering = ('name', )
def __str__(self):
return self.name
@python_2_unicode_compatible
class AbstractPaymentEvent(models.Model):
"""
A payment event for an order
For example:
* All lines have been paid for
* 2 lines have been refunded
"""
order = models.ForeignKey(
'order.Order', related_name='payment_events',
verbose_name=_("Order"))
amount = models.DecimalField(
_("Amount"), decimal_places=2, max_digits=12)
# The reference should refer to the transaction ID of the payment gateway
# that was used for this event.
reference = models.CharField(
_("Reference"), max_length=128, blank=True)
lines = models.ManyToManyField(
'order.Line', through='PaymentEventQuantity',
verbose_name=_("Lines"))
event_type = models.ForeignKey(
'order.PaymentEventType', verbose_name=_("Event Type"))
# Allow payment events to be linked to shipping events. Often a shipping
# event will trigger a payment event and so we can use this FK to capture
# the relationship.
shipping_event = models.ForeignKey(
'order.ShippingEvent', related_name='payment_events',
null=True)
date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
class Meta:
abstract = True
app_label = 'order'
verbose_name = _("Payment Event")
verbose_name_plural = _("Payment Events")
ordering = ['-date_created']
def __str__(self):
return _("Payment event for order %s") % self.order
def num_affected_lines(self):
return self.lines.all().count()
class PaymentEventQuantity(models.Model):
"""
A "through" model linking lines to payment events
"""
event = models.ForeignKey(
'order.PaymentEvent', related_name='line_quantities',
verbose_name=_("Event"))
line = models.ForeignKey(
'order.Line', related_name="payment_event_quantities",
verbose_name=_("Line"))
quantity = models.PositiveIntegerField(_("Quantity"))
class Meta:
app_label = 'order'
verbose_name = _("Payment Event Quantity")
verbose_name_plural = _("Payment Event Quantities")
unique_together = ('event', 'line')
# SHIPPING EVENTS
@python_2_unicode_compatible
class AbstractShippingEvent(models.Model):
"""
An event is something which happens to a group of lines such as
1 item being dispatched.
"""
order = models.ForeignKey(
'order.Order', related_name='shipping_events', verbose_name=_("Order"))
lines = models.ManyToManyField(
'order.Line', related_name='shipping_events',
through='ShippingEventQuantity', verbose_name=_("Lines"))
event_type = models.ForeignKey(
'order.ShippingEventType', verbose_name=_("Event Type"))
notes = models.TextField(
_("Event notes"), blank=True,
help_text=_("This could be the dispatch reference, or a "
"tracking number"))
date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
class Meta:
abstract = True
app_label = 'order'
verbose_name = _("Shipping Event")
verbose_name_plural = _("Shipping Events")
ordering = ['-date_created']
def __str__(self):
return _("Order #%(number)s, type %(type)s") % {
'number': self.order.number,
'type': self.event_type}
def num_affected_lines(self):
return self.lines.count()
@python_2_unicode_compatible
class ShippingEventQuantity(models.Model):
"""
A "through" model linking lines to shipping events.
This exists to track the quantity of a line that is involved in a
particular shipping event.
"""
event = models.ForeignKey(
'order.ShippingEvent', related_name='line_quantities',
verbose_name=_("Event"))
line = models.ForeignKey(
'order.Line', related_name="shipping_event_quantities",
verbose_name=_("Line"))
quantity = models.PositiveIntegerField(_("Quantity"))
class Meta:
app_label = 'order'
verbose_name = _("Shipping Event Quantity")
verbose_name_plural = _("Shipping Event Quantities")
unique_together = ('event', 'line')
def save(self, *args, **kwargs):
# Default quantity to full quantity of line
if not self.quantity:
self.quantity = self.line.quantity
# Ensure we don't violate quantities constraint
if not self.line.is_shipping_event_permitted(
self.event.event_type, self.quantity):
raise exceptions.InvalidShippingEvent
super(ShippingEventQuantity, self).save(*args, **kwargs)
def __str__(self):
return _("%(product)s - quantity %(qty)d") % {
'product': self.line.product,
'qty': self.quantity}
@python_2_unicode_compatible
class AbstractShippingEventType(models.Model):
"""
A type of shipping/fulfillment event
Eg: 'Shipped', 'Cancelled', 'Returned'
"""
# Name is the friendly description of an event
name = models.CharField(_("Name"), max_length=255, unique=True)
# Code is used in forms
code = AutoSlugField(_("Code"), max_length=128, unique=True,
populate_from='name')
class Meta:
abstract = True
app_label = 'order'
verbose_name = _("Shipping Event Type")
verbose_name_plural = _("Shipping Event Types")
ordering = ('name', )
def __str__(self):
return self.name
# DISCOUNTS
@python_2_unicode_compatible
class AbstractOrderDiscount(models.Model):
"""
A discount against an order.
Normally only used for display purposes so an order can be listed with
discounts displayed separately even though in reality, the discounts are
applied at the line level.
This has evolved to be a slightly misleading class name as this really
track benefit applications which aren't necessarily discounts.
"""
order = models.ForeignKey(
'order.Order', related_name="discounts", verbose_name=_("Order"))
# We need to distinguish between basket discounts, shipping discounts and
# 'deferred' discounts.
BASKET, SHIPPING, DEFERRED = "Basket", "Shipping", "Deferred"
CATEGORY_CHOICES = (
(BASKET, _(BASKET)),
(SHIPPING, _(SHIPPING)),
(DEFERRED, _(DEFERRED)),
)
category = models.CharField(
_("Discount category"), default=BASKET, max_length=64,
choices=CATEGORY_CHOICES)
offer_id = models.PositiveIntegerField(
_("Offer ID"), blank=True, null=True)