You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

abstract_models.py 35KB

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