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

abstract_models.py 35KB

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