Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

abstract_models.py 40KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. import logging
  2. from collections import OrderedDict
  3. from decimal import Decimal as D
  4. from django.conf import settings
  5. from django.core.signing import BadSignature, Signer
  6. from django.db import models
  7. from django.db.models import Sum
  8. from django.utils import timezone
  9. from django.utils.crypto import constant_time_compare
  10. from django.utils.timezone import now
  11. from django.utils.translation import gettext_lazy as _
  12. from django.utils.translation import pgettext_lazy
  13. from oscar.apps.order.signals import (
  14. order_line_status_changed, order_status_changed)
  15. from oscar.core.compat import AUTH_USER_MODEL
  16. from oscar.core.loading import get_model
  17. from oscar.core.utils import get_default_currency
  18. from oscar.models.fields import AutoSlugField
  19. from . import exceptions
  20. logger = logging.getLogger('oscar.order')
  21. class AbstractOrder(models.Model):
  22. """
  23. The main order model
  24. """
  25. number = models.CharField(
  26. _("Order number"), max_length=128, db_index=True, unique=True)
  27. # We track the site that each order is placed within
  28. site = models.ForeignKey(
  29. 'sites.Site', verbose_name=_("Site"), null=True,
  30. on_delete=models.SET_NULL)
  31. basket = models.ForeignKey(
  32. 'basket.Basket', verbose_name=_("Basket"),
  33. null=True, blank=True, on_delete=models.SET_NULL)
  34. # Orders can be placed without the user authenticating so we don't always
  35. # have a customer ID.
  36. user = models.ForeignKey(
  37. AUTH_USER_MODEL, related_name='orders', null=True, blank=True,
  38. verbose_name=_("User"), on_delete=models.SET_NULL)
  39. # Billing address is not always required (eg paying by gift card)
  40. billing_address = models.ForeignKey(
  41. 'order.BillingAddress', null=True, blank=True,
  42. verbose_name=_("Billing Address"),
  43. on_delete=models.SET_NULL)
  44. # Total price looks like it could be calculated by adding up the
  45. # prices of the associated lines, but in some circumstances extra
  46. # order-level charges are added and so we need to store it separately
  47. currency = models.CharField(
  48. _("Currency"), max_length=12, default=get_default_currency)
  49. total_incl_tax = models.DecimalField(
  50. _("Order total (inc. tax)"), decimal_places=2, max_digits=12)
  51. total_excl_tax = models.DecimalField(
  52. _("Order total (excl. tax)"), decimal_places=2, max_digits=12)
  53. # Shipping charges
  54. shipping_incl_tax = models.DecimalField(
  55. _("Shipping charge (inc. tax)"), decimal_places=2, max_digits=12,
  56. default=0)
  57. shipping_excl_tax = models.DecimalField(
  58. _("Shipping charge (excl. tax)"), decimal_places=2, max_digits=12,
  59. default=0)
  60. # Not all lines are actually shipped (such as downloads), hence shipping
  61. # address is not mandatory.
  62. shipping_address = models.ForeignKey(
  63. 'order.ShippingAddress', null=True, blank=True,
  64. verbose_name=_("Shipping Address"),
  65. on_delete=models.SET_NULL)
  66. shipping_method = models.CharField(
  67. _("Shipping method"), max_length=128, blank=True)
  68. # Identifies shipping code
  69. shipping_code = models.CharField(blank=True, max_length=128, default="")
  70. # Use this field to indicate that an order is on hold / awaiting payment
  71. status = models.CharField(_("Status"), max_length=100, blank=True)
  72. guest_email = models.EmailField(_("Guest email address"), blank=True)
  73. # Index added to this field for reporting
  74. date_placed = models.DateTimeField(db_index=True)
  75. #: Order status pipeline. This should be a dict where each (key, value) #:
  76. #: corresponds to a status and a list of possible statuses that can follow
  77. #: that one.
  78. pipeline = getattr(settings, 'OSCAR_ORDER_STATUS_PIPELINE', {})
  79. #: Order status cascade pipeline. This should be a dict where each (key,
  80. #: value) pair corresponds to an *order* status and the corresponding
  81. #: *line* status that needs to be set when the order is set to the new
  82. #: status
  83. cascade = getattr(settings, 'OSCAR_ORDER_STATUS_CASCADE', {})
  84. @classmethod
  85. def all_statuses(cls):
  86. """
  87. Return all possible statuses for an order
  88. """
  89. return list(cls.pipeline.keys())
  90. def available_statuses(self):
  91. """
  92. Return all possible statuses that this order can move to
  93. """
  94. return self.pipeline.get(self.status, ())
  95. def set_status(self, new_status):
  96. """
  97. Set a new status for this order.
  98. If the requested status is not valid, then ``InvalidOrderStatus`` is
  99. raised.
  100. """
  101. if new_status == self.status:
  102. return
  103. old_status = self.status
  104. if new_status not in self.available_statuses():
  105. raise exceptions.InvalidOrderStatus(
  106. _("'%(new_status)s' is not a valid status for order %(number)s"
  107. " (current status: '%(status)s')")
  108. % {'new_status': new_status,
  109. 'number': self.number,
  110. 'status': self.status})
  111. self.status = new_status
  112. if new_status in self.cascade:
  113. for line in self.lines.all():
  114. line.status = self.cascade[self.status]
  115. line.save()
  116. self.save()
  117. # Send signal for handling status changed
  118. order_status_changed.send(sender=self,
  119. order=self,
  120. old_status=old_status,
  121. new_status=new_status,
  122. )
  123. self._create_order_status_change(old_status, new_status)
  124. set_status.alters_data = True
  125. def _create_order_status_change(self, old_status, new_status):
  126. # Not setting the status on the order as that should be handled before
  127. self.status_changes.create(old_status=old_status, new_status=new_status)
  128. @property
  129. def is_anonymous(self):
  130. # It's possible for an order to be placed by a customer who then
  131. # deletes their profile. Hence, we need to check that a guest email is
  132. # set.
  133. return self.user is None and bool(self.guest_email)
  134. @property
  135. def basket_total_before_discounts_incl_tax(self):
  136. """
  137. Return basket total including tax but before discounts are applied
  138. """
  139. result = self.lines.aggregate(total=Sum('line_price_before_discounts_incl_tax'))
  140. return result['total']
  141. @property
  142. def basket_total_before_discounts_excl_tax(self):
  143. """
  144. Return basket total excluding tax but before discounts are applied
  145. """
  146. result = self.lines.aggregate(total=Sum('line_price_before_discounts_excl_tax'))
  147. return result['total']
  148. @property
  149. def basket_total_incl_tax(self):
  150. """
  151. Return basket total including tax
  152. """
  153. return self.total_incl_tax - self.shipping_incl_tax - self.surcharge_incl_tax
  154. @property
  155. def basket_total_excl_tax(self):
  156. """
  157. Return basket total excluding tax
  158. """
  159. return self.total_excl_tax - self.shipping_excl_tax - self.surcharge_excl_tax
  160. @property
  161. def total_before_discounts_incl_tax(self):
  162. return (self.basket_total_before_discounts_incl_tax
  163. + self.shipping_incl_tax)
  164. @property
  165. def total_before_discounts_excl_tax(self):
  166. return (self.basket_total_before_discounts_excl_tax
  167. + self.shipping_excl_tax)
  168. @property
  169. def total_discount_incl_tax(self):
  170. """
  171. The amount of discount this order received
  172. """
  173. discount = D('0.00')
  174. for line in self.lines.all():
  175. discount += line.discount_incl_tax
  176. return discount
  177. @property
  178. def total_discount_excl_tax(self):
  179. discount = D('0.00')
  180. for line in self.lines.all():
  181. discount += line.discount_excl_tax
  182. return discount
  183. @property
  184. def total_tax(self):
  185. return self.total_incl_tax - self.total_excl_tax
  186. @property
  187. def surcharge_excl_tax(self):
  188. return sum(charge.excl_tax for charge in self.surcharges.all())
  189. @property
  190. def surcharge_incl_tax(self):
  191. return sum(charge.incl_tax for charge in self.surcharges.all())
  192. @property
  193. def num_lines(self):
  194. return self.lines.count()
  195. @property
  196. def num_items(self):
  197. """
  198. Returns the number of items in this order.
  199. """
  200. num_items = 0
  201. for line in self.lines.all():
  202. num_items += line.quantity
  203. return num_items
  204. @property
  205. def shipping_tax(self):
  206. return self.shipping_incl_tax - self.shipping_excl_tax
  207. @property
  208. def shipping_status(self):
  209. """Return the last complete shipping event for this order."""
  210. # As safeguard against identical timestamps, also sort by the primary
  211. # key. It's not recommended to rely on this behaviour, but in practice
  212. # reasonably safe if PKs are not manually set.
  213. events = self.shipping_events.order_by('-date_created', '-pk').all()
  214. if not len(events):
  215. return ''
  216. # Collect all events by event-type
  217. event_map = OrderedDict()
  218. for event in events:
  219. event_name = event.event_type.name
  220. if event_name not in event_map:
  221. event_map[event_name] = []
  222. event_map[event_name].extend(list(event.line_quantities.all()))
  223. # Determine last complete event
  224. status = _("In progress")
  225. for event_name, event_line_quantities in event_map.items():
  226. if self._is_event_complete(event_line_quantities):
  227. return event_name
  228. return status
  229. @property
  230. def has_shipping_discounts(self):
  231. return len(self.shipping_discounts) > 0
  232. @property
  233. def shipping_before_discounts_incl_tax(self):
  234. # We can construct what shipping would have been before discounts by
  235. # adding the discounts back onto the final shipping charge.
  236. total = D('0.00')
  237. for discount in self.shipping_discounts:
  238. total += discount.amount
  239. return self.shipping_incl_tax + total
  240. def _is_event_complete(self, event_quantities):
  241. # Form map of line to quantity
  242. event_map = {}
  243. for event_quantity in event_quantities:
  244. line_id = event_quantity.line_id
  245. event_map.setdefault(line_id, 0)
  246. event_map[line_id] += event_quantity.quantity
  247. for line in self.lines.all():
  248. if event_map.get(line.pk, 0) != line.quantity:
  249. return False
  250. return True
  251. class Meta:
  252. abstract = True
  253. app_label = 'order'
  254. ordering = ['-date_placed']
  255. verbose_name = _("Order")
  256. verbose_name_plural = _("Orders")
  257. def __str__(self):
  258. return "#%s" % (self.number,)
  259. def verification_hash(self):
  260. signer = Signer(salt='oscar.apps.order.Order')
  261. return signer.sign(self.number)
  262. def check_verification_hash(self, hash_to_check):
  263. """
  264. Checks the received verification hash against this order number.
  265. Returns False if the verification failed, True otherwise.
  266. """
  267. signer = Signer(salt='oscar.apps.order.Order')
  268. try:
  269. signed_number = signer.unsign(hash_to_check)
  270. except BadSignature:
  271. return False
  272. return constant_time_compare(signed_number, self.number)
  273. @property
  274. def email(self):
  275. if not self.user:
  276. return self.guest_email
  277. return self.user.email
  278. @property
  279. def basket_discounts(self):
  280. # This includes both offer- and voucher- discounts. For orders we
  281. # don't need to treat them differently like we do for baskets.
  282. return self.discounts.filter(
  283. category=AbstractOrderDiscount.BASKET)
  284. @property
  285. def shipping_discounts(self):
  286. return self.discounts.filter(
  287. category=AbstractOrderDiscount.SHIPPING)
  288. @property
  289. def post_order_actions(self):
  290. return self.discounts.filter(
  291. category=AbstractOrderDiscount.DEFERRED)
  292. def set_date_placed_default(self):
  293. if self.date_placed is None:
  294. self.date_placed = now()
  295. def save(self, *args, **kwargs):
  296. # Ensure the date_placed field works as it auto_now_add was set. But
  297. # this gives us the ability to set the date_placed explicitly (which is
  298. # useful when importing orders from another system).
  299. self.set_date_placed_default()
  300. super().save(*args, **kwargs)
  301. class AbstractOrderNote(models.Model):
  302. """
  303. A note against an order.
  304. This are often used for audit purposes too. IE, whenever an admin
  305. makes a change to an order, we create a note to record what happened.
  306. """
  307. order = models.ForeignKey(
  308. 'order.Order',
  309. on_delete=models.CASCADE,
  310. related_name="notes",
  311. verbose_name=_("Order"))
  312. # These are sometimes programatically generated so don't need a
  313. # user everytime
  314. user = models.ForeignKey(
  315. AUTH_USER_MODEL,
  316. on_delete=models.CASCADE,
  317. null=True,
  318. verbose_name=_("User"))
  319. # We allow notes to be classified although this isn't always needed
  320. INFO, WARNING, ERROR, SYSTEM = 'Info', 'Warning', 'Error', 'System'
  321. note_type = models.CharField(_("Note Type"), max_length=128, blank=True)
  322. message = models.TextField(_("Message"))
  323. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  324. date_updated = models.DateTimeField(_("Date Updated"), auto_now=True)
  325. # Notes can only be edited for 5 minutes after being created
  326. editable_lifetime = 300
  327. class Meta:
  328. abstract = True
  329. app_label = 'order'
  330. ordering = ['-date_updated']
  331. verbose_name = _("Order Note")
  332. verbose_name_plural = _("Order Notes")
  333. def __str__(self):
  334. return "'%s' (%s)" % (self.message[0:50], self.user)
  335. def is_editable(self):
  336. if self.note_type == self.SYSTEM:
  337. return False
  338. delta = timezone.now() - self.date_updated
  339. return delta.seconds < self.editable_lifetime
  340. class AbstractOrderStatusChange(models.Model):
  341. order = models.ForeignKey(
  342. 'order.Order',
  343. on_delete=models.CASCADE,
  344. related_name='status_changes',
  345. verbose_name=_('Order Status Changes')
  346. )
  347. old_status = models.CharField(_('Old Status'), max_length=100, blank=True)
  348. new_status = models.CharField(_('New Status'), max_length=100, blank=True)
  349. date_created = models.DateTimeField(_('Date Created'), auto_now_add=True, db_index=True)
  350. class Meta:
  351. abstract = True
  352. app_label = 'order'
  353. verbose_name = _('Order Status Change')
  354. verbose_name_plural = _('Order Status Changes')
  355. ordering = ['-date_created']
  356. def __str__(self):
  357. return _("%(order)s has changed status from %(old_status)s to %(new_status)s") \
  358. % {'order': self.order, 'old_status': self.old_status, 'new_status': self.new_status, }
  359. class AbstractCommunicationEvent(models.Model):
  360. """
  361. An order-level event involving a communication to the customer, such
  362. as an confirmation email being sent.
  363. """
  364. order = models.ForeignKey(
  365. 'order.Order',
  366. on_delete=models.CASCADE,
  367. related_name="communication_events",
  368. verbose_name=_("Order"))
  369. event_type = models.ForeignKey(
  370. 'communication.CommunicationEventType',
  371. on_delete=models.CASCADE,
  372. verbose_name=_("Event Type"))
  373. date_created = models.DateTimeField(_("Date"), auto_now_add=True, db_index=True)
  374. class Meta:
  375. abstract = True
  376. app_label = 'order'
  377. verbose_name = _("Communication Event")
  378. verbose_name_plural = _("Communication Events")
  379. ordering = ['-date_created']
  380. def __str__(self):
  381. return _("'%(type)s' event for order #%(number)s") \
  382. % {'type': self.event_type.name, 'number': self.order.number}
  383. # LINES
  384. class AbstractLine(models.Model):
  385. """
  386. An order line
  387. """
  388. order = models.ForeignKey(
  389. 'order.Order',
  390. on_delete=models.CASCADE,
  391. related_name='lines',
  392. verbose_name=_("Order"))
  393. # PARTNER INFORMATION
  394. # -------------------
  395. # We store the partner and various detail their SKU and the title for cases
  396. # where the product has been deleted from the catalogue (but we still need
  397. # the data for reporting). We also store the partner name in case the
  398. # partner gets deleted at a later date.
  399. partner = models.ForeignKey(
  400. 'partner.Partner', related_name='order_lines', blank=True, null=True,
  401. on_delete=models.SET_NULL, verbose_name=_("Partner"))
  402. partner_name = models.CharField(
  403. _("Partner name"), max_length=128, blank=True)
  404. partner_sku = models.CharField(_("Partner SKU"), max_length=128)
  405. # A line reference is the ID that a partner uses to represent this
  406. # particular line (it's not the same as a SKU).
  407. partner_line_reference = models.CharField(
  408. _("Partner reference"), max_length=128, blank=True,
  409. help_text=_("This is the item number that the partner uses "
  410. "within their system"))
  411. partner_line_notes = models.TextField(
  412. _("Partner Notes"), blank=True)
  413. # We keep a link to the stockrecord used for this line which allows us to
  414. # update stocklevels when it ships
  415. stockrecord = models.ForeignKey(
  416. 'partner.StockRecord', on_delete=models.SET_NULL, blank=True,
  417. null=True, verbose_name=_("Stock record"))
  418. # PRODUCT INFORMATION
  419. # -------------------
  420. # We don't want any hard links between orders and the products table so we
  421. # allow this link to be NULLable.
  422. product = models.ForeignKey(
  423. 'catalogue.Product', on_delete=models.SET_NULL, blank=True, null=True,
  424. verbose_name=_("Product"))
  425. title = models.CharField(
  426. pgettext_lazy("Product title", "Title"), max_length=255)
  427. # UPC can be null because it's usually set as the product's UPC, and that
  428. # can be null as well
  429. upc = models.CharField(_("UPC"), max_length=128, blank=True, null=True)
  430. quantity = models.PositiveIntegerField(_("Quantity"), default=1)
  431. # REPORTING INFORMATION
  432. # ---------------------
  433. # Price information (these fields are actually redundant as the information
  434. # can be calculated from the LinePrice models
  435. # Deprecated - will be removed in Oscar 2.1
  436. line_price_incl_tax = models.DecimalField(
  437. _("Price (inc. tax)"), decimal_places=2, max_digits=12)
  438. # Deprecated - will be removed in Oscar 2.1
  439. line_price_excl_tax = models.DecimalField(
  440. _("Price (excl. tax)"), decimal_places=2, max_digits=12)
  441. # Price information before discounts are applied
  442. line_price_before_discounts_incl_tax = models.DecimalField(
  443. _("Price before discounts (inc. tax)"),
  444. decimal_places=2, max_digits=12)
  445. line_price_before_discounts_excl_tax = models.DecimalField(
  446. _("Price before discounts (excl. tax)"),
  447. decimal_places=2, max_digits=12)
  448. # Normal site price for item (without discounts)
  449. unit_price_incl_tax = models.DecimalField(
  450. _("Unit Price (inc. tax)"), decimal_places=2, max_digits=12,
  451. blank=True, null=True)
  452. unit_price_excl_tax = models.DecimalField(
  453. _("Unit Price (excl. tax)"), decimal_places=2, max_digits=12,
  454. blank=True, null=True)
  455. # Partners often want to assign some status to each line to help with their
  456. # own business processes.
  457. status = models.CharField(_("Status"), max_length=255, blank=True)
  458. #: Order status pipeline. This should be a dict where each (key, value)
  459. #: corresponds to a status and the possible statuses that can follow that
  460. #: one.
  461. pipeline = getattr(settings, 'OSCAR_LINE_STATUS_PIPELINE', {})
  462. class Meta:
  463. abstract = True
  464. app_label = 'order'
  465. # Enforce sorting in order of creation.
  466. ordering = ['pk']
  467. verbose_name = _("Order Line")
  468. verbose_name_plural = _("Order Lines")
  469. def __str__(self):
  470. if self.product:
  471. title = self.product.title
  472. else:
  473. title = _('<missing product>')
  474. return _("Product '%(name)s', quantity '%(qty)s'") % {
  475. 'name': title, 'qty': self.quantity}
  476. @classmethod
  477. def all_statuses(cls):
  478. """
  479. Return all possible statuses for an order line
  480. """
  481. return list(cls.pipeline.keys())
  482. def available_statuses(self):
  483. """
  484. Return all possible statuses that this order line can move to
  485. """
  486. return self.pipeline.get(self.status, ())
  487. def set_status(self, new_status):
  488. """
  489. Set a new status for this line
  490. If the requested status is not valid, then ``InvalidLineStatus`` is
  491. raised.
  492. """
  493. if new_status == self.status:
  494. return
  495. old_status = self.status
  496. if new_status not in self.available_statuses():
  497. raise exceptions.InvalidLineStatus(
  498. _("'%(new_status)s' is not a valid status (current status:"
  499. " '%(status)s')")
  500. % {'new_status': new_status, 'status': self.status})
  501. self.status = new_status
  502. self.save()
  503. # Send signal for handling status changed
  504. order_line_status_changed.send(sender=self,
  505. line=self,
  506. old_status=old_status,
  507. new_status=new_status,
  508. )
  509. set_status.alters_data = True
  510. @property
  511. def description(self):
  512. """
  513. Returns a description of this line including details of any
  514. line attributes.
  515. """
  516. desc = self.title
  517. ops = []
  518. for attribute in self.attributes.all():
  519. ops.append("%s = '%s'" % (attribute.type, attribute.value))
  520. if ops:
  521. desc = "%s (%s)" % (desc, ", ".join(ops))
  522. return desc
  523. @property
  524. def discount_incl_tax(self):
  525. return self.line_price_before_discounts_incl_tax \
  526. - self.line_price_incl_tax
  527. @property
  528. def discount_excl_tax(self):
  529. return self.line_price_before_discounts_excl_tax \
  530. - self.line_price_excl_tax
  531. @property
  532. def line_price_tax(self):
  533. return self.line_price_incl_tax - self.line_price_excl_tax
  534. @property
  535. def unit_price_tax(self):
  536. return self.unit_price_incl_tax - self.unit_price_excl_tax
  537. # Shipping status helpers
  538. @property
  539. def shipping_status(self):
  540. """
  541. Returns a string summary of the shipping status of this line
  542. """
  543. status_map = self.shipping_event_breakdown
  544. if not status_map:
  545. return ''
  546. events = []
  547. last_complete_event_name = None
  548. for event_dict in reversed(list(status_map.values())):
  549. if event_dict['quantity'] == self.quantity:
  550. events.append(event_dict['name'])
  551. last_complete_event_name = event_dict['name']
  552. else:
  553. events.append("%s (%d/%d items)" % (
  554. event_dict['name'], event_dict['quantity'],
  555. self.quantity))
  556. if last_complete_event_name == list(status_map.values())[0]['name']:
  557. return last_complete_event_name
  558. return ', '.join(events)
  559. def is_shipping_event_permitted(self, event_type, quantity):
  560. """
  561. Test whether a shipping event with the given quantity is permitted
  562. This method should normally be overridden to ensure that the
  563. prerequisite shipping events have been passed for this line.
  564. """
  565. # Note, this calculation is simplistic - normally, you will also need
  566. # to check if previous shipping events have occurred. Eg, you can't
  567. # return lines until they have been shipped.
  568. current_qty = self.shipping_event_quantity(event_type)
  569. return (current_qty + quantity) <= self.quantity
  570. def shipping_event_quantity(self, event_type):
  571. """
  572. Return the quantity of this line that has been involved in a shipping
  573. event of the passed type.
  574. """
  575. result = self.shipping_event_quantities.filter(
  576. event__event_type=event_type).aggregate(Sum('quantity'))
  577. if result['quantity__sum'] is None:
  578. return 0
  579. else:
  580. return result['quantity__sum']
  581. def has_shipping_event_occurred(self, event_type, quantity=None):
  582. """
  583. Test whether this line has passed a given shipping event
  584. """
  585. if not quantity:
  586. quantity = self.quantity
  587. return self.shipping_event_quantity(event_type) == quantity
  588. def get_event_quantity(self, event):
  589. """
  590. Fetches the ShippingEventQuantity instance for this line
  591. Exists as a separate method so it can be overridden to avoid
  592. the DB query that's caused by get().
  593. """
  594. return event.line_quantities.get(line=self)
  595. @property
  596. def shipping_event_breakdown(self):
  597. """
  598. Returns a dict of shipping events that this line has been through
  599. """
  600. status_map = OrderedDict()
  601. for event in self.shipping_events.all():
  602. event_type = event.event_type
  603. event_name = event_type.name
  604. event_quantity = self.get_event_quantity(event).quantity
  605. if event_name in status_map:
  606. status_map[event_name]['quantity'] += event_quantity
  607. else:
  608. status_map[event_name] = {
  609. 'event_type': event_type,
  610. 'name': event_name,
  611. 'quantity': event_quantity
  612. }
  613. return status_map
  614. # Payment event helpers
  615. def is_payment_event_permitted(self, event_type, quantity):
  616. """
  617. Test whether a payment event with the given quantity is permitted.
  618. Allow each payment event type to occur only once per quantity.
  619. """
  620. current_qty = self.payment_event_quantity(event_type)
  621. return (current_qty + quantity) <= self.quantity
  622. def payment_event_quantity(self, event_type):
  623. """
  624. Return the quantity of this line that has been involved in a payment
  625. event of the passed type.
  626. """
  627. result = self.payment_event_quantities.filter(
  628. event__event_type=event_type).aggregate(Sum('quantity'))
  629. if result['quantity__sum'] is None:
  630. return 0
  631. else:
  632. return result['quantity__sum']
  633. @property
  634. def is_product_deleted(self):
  635. return self.product is None
  636. def is_available_to_reorder(self, basket, strategy):
  637. """
  638. Test if this line can be re-ordered using the passed strategy and
  639. basket
  640. """
  641. if not self.product:
  642. return False, (_("'%(title)s' is no longer available") %
  643. {'title': self.title})
  644. try:
  645. basket_line = basket.lines.get(product=self.product)
  646. except basket.lines.model.DoesNotExist:
  647. desired_qty = self.quantity
  648. else:
  649. desired_qty = basket_line.quantity + self.quantity
  650. result = strategy.fetch_for_product(self.product)
  651. is_available, reason = result.availability.is_purchase_permitted(
  652. quantity=desired_qty)
  653. if not is_available:
  654. return False, reason
  655. return True, None
  656. class AbstractLineAttribute(models.Model):
  657. """
  658. An attribute of a line
  659. """
  660. line = models.ForeignKey(
  661. 'order.Line',
  662. on_delete=models.CASCADE,
  663. related_name='attributes',
  664. verbose_name=_("Line"))
  665. option = models.ForeignKey(
  666. 'catalogue.Option', null=True, on_delete=models.SET_NULL,
  667. related_name="line_attributes", verbose_name=_("Option"))
  668. type = models.CharField(_("Type"), max_length=128)
  669. value = models.CharField(_("Value"), max_length=255)
  670. class Meta:
  671. abstract = True
  672. app_label = 'order'
  673. verbose_name = _("Line Attribute")
  674. verbose_name_plural = _("Line Attributes")
  675. def __str__(self):
  676. return "%s = %s" % (self.type, self.value)
  677. class AbstractLinePrice(models.Model):
  678. """
  679. For tracking the prices paid for each unit within a line.
  680. This is necessary as offers can lead to units within a line
  681. having different prices. For example, one product may be sold at
  682. 50% off as it's part of an offer while the remainder are full price.
  683. """
  684. order = models.ForeignKey(
  685. 'order.Order',
  686. on_delete=models.CASCADE,
  687. related_name='line_prices',
  688. verbose_name=_("Option"))
  689. line = models.ForeignKey(
  690. 'order.Line',
  691. on_delete=models.CASCADE,
  692. related_name='prices',
  693. verbose_name=_("Line"))
  694. quantity = models.PositiveIntegerField(_("Quantity"), default=1)
  695. price_incl_tax = models.DecimalField(
  696. _("Price (inc. tax)"), decimal_places=2, max_digits=12)
  697. price_excl_tax = models.DecimalField(
  698. _("Price (excl. tax)"), decimal_places=2, max_digits=12)
  699. shipping_incl_tax = models.DecimalField(
  700. _("Shiping (inc. tax)"), decimal_places=2, max_digits=12, default=0)
  701. shipping_excl_tax = models.DecimalField(
  702. _("Shipping (excl. tax)"), decimal_places=2, max_digits=12, default=0)
  703. class Meta:
  704. abstract = True
  705. app_label = 'order'
  706. ordering = ('id',)
  707. verbose_name = _("Line Price")
  708. verbose_name_plural = _("Line Prices")
  709. def __str__(self):
  710. return _("Line '%(number)s' (quantity %(qty)d) price %(price)s") % {
  711. 'number': self.line,
  712. 'qty': self.quantity,
  713. 'price': self.price_incl_tax}
  714. # PAYMENT EVENTS
  715. class AbstractPaymentEventType(models.Model):
  716. """
  717. Payment event types are things like 'Paid', 'Failed', 'Refunded'.
  718. These are effectively the transaction types.
  719. """
  720. name = models.CharField(_("Name"), max_length=128, unique=True)
  721. code = AutoSlugField(_("Code"), max_length=128, unique=True,
  722. populate_from='name')
  723. class Meta:
  724. abstract = True
  725. app_label = 'order'
  726. verbose_name = _("Payment Event Type")
  727. verbose_name_plural = _("Payment Event Types")
  728. ordering = ('name', )
  729. def __str__(self):
  730. return self.name
  731. class AbstractPaymentEvent(models.Model):
  732. """
  733. A payment event for an order
  734. For example:
  735. * All lines have been paid for
  736. * 2 lines have been refunded
  737. """
  738. order = models.ForeignKey(
  739. 'order.Order',
  740. on_delete=models.CASCADE,
  741. related_name='payment_events',
  742. verbose_name=_("Order"))
  743. amount = models.DecimalField(
  744. _("Amount"), decimal_places=2, max_digits=12)
  745. # The reference should refer to the transaction ID of the payment gateway
  746. # that was used for this event.
  747. reference = models.CharField(
  748. _("Reference"), max_length=128, blank=True)
  749. lines = models.ManyToManyField(
  750. 'order.Line', through='PaymentEventQuantity',
  751. verbose_name=_("Lines"))
  752. event_type = models.ForeignKey(
  753. 'order.PaymentEventType',
  754. on_delete=models.CASCADE,
  755. verbose_name=_("Event Type"))
  756. # Allow payment events to be linked to shipping events. Often a shipping
  757. # event will trigger a payment event and so we can use this FK to capture
  758. # the relationship.
  759. shipping_event = models.ForeignKey(
  760. 'order.ShippingEvent',
  761. null=True,
  762. on_delete=models.CASCADE,
  763. related_name='payment_events')
  764. date_created = models.DateTimeField(_("Date created"), auto_now_add=True, db_index=True)
  765. class Meta:
  766. abstract = True
  767. app_label = 'order'
  768. verbose_name = _("Payment Event")
  769. verbose_name_plural = _("Payment Events")
  770. ordering = ['-date_created']
  771. def __str__(self):
  772. return _("Payment event for order %s") % self.order
  773. def num_affected_lines(self):
  774. return self.lines.all().count()
  775. class PaymentEventQuantity(models.Model):
  776. """
  777. A "through" model linking lines to payment events
  778. """
  779. event = models.ForeignKey(
  780. 'order.PaymentEvent',
  781. on_delete=models.CASCADE,
  782. related_name='line_quantities',
  783. verbose_name=_("Event"))
  784. line = models.ForeignKey(
  785. 'order.Line',
  786. on_delete=models.CASCADE,
  787. related_name="payment_event_quantities",
  788. verbose_name=_("Line"))
  789. quantity = models.PositiveIntegerField(_("Quantity"))
  790. class Meta:
  791. app_label = 'order'
  792. verbose_name = _("Payment Event Quantity")
  793. verbose_name_plural = _("Payment Event Quantities")
  794. unique_together = ('event', 'line')
  795. # SHIPPING EVENTS
  796. class AbstractShippingEvent(models.Model):
  797. """
  798. An event is something which happens to a group of lines such as
  799. 1 item being dispatched.
  800. """
  801. order = models.ForeignKey(
  802. 'order.Order',
  803. on_delete=models.CASCADE,
  804. related_name='shipping_events',
  805. verbose_name=_("Order"))
  806. lines = models.ManyToManyField(
  807. 'order.Line', related_name='shipping_events',
  808. through='ShippingEventQuantity', verbose_name=_("Lines"))
  809. event_type = models.ForeignKey(
  810. 'order.ShippingEventType',
  811. on_delete=models.CASCADE,
  812. verbose_name=_("Event Type"))
  813. notes = models.TextField(
  814. _("Event notes"), blank=True,
  815. help_text=_("This could be the dispatch reference, or a "
  816. "tracking number"))
  817. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True, db_index=True)
  818. class Meta:
  819. abstract = True
  820. app_label = 'order'
  821. verbose_name = _("Shipping Event")
  822. verbose_name_plural = _("Shipping Events")
  823. ordering = ['-date_created']
  824. def __str__(self):
  825. return _("Order #%(number)s, type %(type)s") % {
  826. 'number': self.order.number,
  827. 'type': self.event_type}
  828. def num_affected_lines(self):
  829. return self.lines.count()
  830. class ShippingEventQuantity(models.Model):
  831. """
  832. A "through" model linking lines to shipping events.
  833. This exists to track the quantity of a line that is involved in a
  834. particular shipping event.
  835. """
  836. event = models.ForeignKey(
  837. 'order.ShippingEvent',
  838. on_delete=models.CASCADE,
  839. related_name='line_quantities',
  840. verbose_name=_("Event"))
  841. line = models.ForeignKey(
  842. 'order.Line',
  843. on_delete=models.CASCADE,
  844. related_name="shipping_event_quantities",
  845. verbose_name=_("Line"))
  846. quantity = models.PositiveIntegerField(_("Quantity"))
  847. class Meta:
  848. app_label = 'order'
  849. verbose_name = _("Shipping Event Quantity")
  850. verbose_name_plural = _("Shipping Event Quantities")
  851. unique_together = ('event', 'line')
  852. def save(self, *args, **kwargs):
  853. # Default quantity to full quantity of line
  854. if not self.quantity:
  855. self.quantity = self.line.quantity
  856. # Ensure we don't violate quantities constraint
  857. if not self.line.is_shipping_event_permitted(
  858. self.event.event_type, self.quantity):
  859. raise exceptions.InvalidShippingEvent
  860. super().save(*args, **kwargs)
  861. def __str__(self):
  862. return _("%(product)s - quantity %(qty)d") % {
  863. 'product': self.line.product,
  864. 'qty': self.quantity}
  865. class AbstractShippingEventType(models.Model):
  866. """
  867. A type of shipping/fulfilment event
  868. E.g.: 'Shipped', 'Cancelled', 'Returned'
  869. """
  870. # Name is the friendly description of an event
  871. name = models.CharField(_("Name"), max_length=255, unique=True)
  872. # Code is used in forms
  873. code = AutoSlugField(_("Code"), max_length=128, unique=True,
  874. populate_from='name')
  875. class Meta:
  876. abstract = True
  877. app_label = 'order'
  878. verbose_name = _("Shipping Event Type")
  879. verbose_name_plural = _("Shipping Event Types")
  880. ordering = ('name', )
  881. def __str__(self):
  882. return self.name
  883. # DISCOUNTS
  884. class AbstractOrderDiscount(models.Model):
  885. """
  886. A discount against an order.
  887. Normally only used for display purposes so an order can be listed with
  888. discounts displayed separately even though in reality, the discounts are
  889. applied at the line level.
  890. This has evolved to be a slightly misleading class name as this really
  891. track benefit applications which aren't necessarily discounts.
  892. """
  893. order = models.ForeignKey(
  894. 'order.Order',
  895. on_delete=models.CASCADE,
  896. related_name="discounts",
  897. verbose_name=_("Order"))
  898. # We need to distinguish between basket discounts, shipping discounts and
  899. # 'deferred' discounts.
  900. BASKET, SHIPPING, DEFERRED = "Basket", "Shipping", "Deferred"
  901. CATEGORY_CHOICES = (
  902. (BASKET, _(BASKET)),
  903. (SHIPPING, _(SHIPPING)),
  904. (DEFERRED, _(DEFERRED)),
  905. )
  906. category = models.CharField(
  907. _("Discount category"), default=BASKET, max_length=64,
  908. choices=CATEGORY_CHOICES)
  909. offer_id = models.PositiveIntegerField(
  910. _("Offer ID"), blank=True, null=True)
  911. offer_name = models.CharField(
  912. _("Offer name"), max_length=128, db_index=True, blank=True)
  913. voucher_id = models.PositiveIntegerField(
  914. _("Voucher ID"), blank=True, null=True)
  915. voucher_code = models.CharField(
  916. _("Code"), max_length=128, db_index=True, blank=True)
  917. frequency = models.PositiveIntegerField(_("Frequency"), null=True)
  918. amount = models.DecimalField(
  919. _("Amount"), decimal_places=2, max_digits=12, default=0)
  920. # Post-order offer applications can return a message to indicate what
  921. # action was taken after the order was placed.
  922. message = models.TextField(blank=True)
  923. @property
  924. def is_basket_discount(self):
  925. return self.category == self.BASKET
  926. @property
  927. def is_shipping_discount(self):
  928. return self.category == self.SHIPPING
  929. @property
  930. def is_post_order_action(self):
  931. return self.category == self.DEFERRED
  932. class Meta:
  933. abstract = True
  934. app_label = 'order'
  935. ordering = ['pk']
  936. verbose_name = _("Order Discount")
  937. verbose_name_plural = _("Order Discounts")
  938. def save(self, **kwargs):
  939. if self.offer_id and not self.offer_name:
  940. offer = self.offer
  941. if offer:
  942. self.offer_name = offer.name
  943. if self.voucher_id and not self.voucher_code:
  944. voucher = self.voucher
  945. if voucher:
  946. self.voucher_code = voucher.code
  947. super().save(**kwargs)
  948. def __str__(self):
  949. return _("Discount of %(amount)r from order %(order)s") % {
  950. 'amount': self.amount, 'order': self.order}
  951. @property
  952. def offer(self):
  953. Offer = get_model('offer', 'ConditionalOffer')
  954. try:
  955. return Offer.objects.get(id=self.offer_id)
  956. except Offer.DoesNotExist:
  957. return None
  958. @property
  959. def voucher(self):
  960. Voucher = get_model('voucher', 'Voucher')
  961. try:
  962. return Voucher.objects.get(id=self.voucher_id)
  963. except Voucher.DoesNotExist:
  964. return None
  965. def description(self):
  966. if self.voucher_code:
  967. return self.voucher_code
  968. return self.offer_name or ""
  969. class AbstractSurcharge(models.Model):
  970. order = models.ForeignKey(
  971. 'order.Order',
  972. on_delete=models.CASCADE,
  973. related_name="surcharges",
  974. verbose_name=_("Surcharges"))
  975. name = models.CharField(
  976. _("Surcharge"), max_length=128
  977. )
  978. code = models.CharField(
  979. _("Surcharge code"), max_length=128
  980. )
  981. incl_tax = models.DecimalField(
  982. _("Surcharge (inc. tax)"), decimal_places=2, max_digits=12,
  983. default=0)
  984. excl_tax = models.DecimalField(
  985. _("Surcharge (excl. tax)"), decimal_places=2, max_digits=12,
  986. default=0)
  987. @property
  988. def tax(self):
  989. return self.incl_tax - self.excl_tax
  990. class Meta:
  991. abstract = True
  992. app_label = 'order'
  993. ordering = ['pk']