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

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