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

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