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

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