Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

abstract_models.py 34KB

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