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

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