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 34KB

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