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

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