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

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