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 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  1. from itertools import chain
  2. from decimal import Decimal as D
  3. import hashlib
  4. import datetime
  5. from django.db import models
  6. from django.contrib.auth.models import User
  7. from django.template.defaultfilters import slugify
  8. from django.utils.translation import ugettext_lazy as _
  9. from django.db.models import Sum
  10. from django.conf import settings
  11. from oscar.apps.order.exceptions import (InvalidOrderStatus, InvalidLineStatus,
  12. InvalidShippingEvent)
  13. class AbstractOrder(models.Model):
  14. """
  15. The main order model
  16. """
  17. number = models.CharField(_("Order number"), max_length=128, db_index=True)
  18. # We track the site that each order is placed within
  19. site = models.ForeignKey('sites.Site', verbose_name=_("Site"))
  20. basket_id = models.PositiveIntegerField(_("Basket ID"), null=True, blank=True)
  21. # Orders can be anonymous so we don't always have a customer ID
  22. user = models.ForeignKey(User, related_name='orders', null=True, blank=True, verbose_name=_("User"))
  23. # Billing address is not always required (eg paying by gift card)
  24. billing_address = models.ForeignKey('order.BillingAddress', null=True, blank=True,
  25. verbose_name=_("Billing Address"))
  26. # Total price looks like it could be calculated by adding up the
  27. # prices of the associated lines, but in some circumstances extra
  28. # order-level charges are added and so we need to store it separately
  29. total_incl_tax = models.DecimalField(_("Order total (inc. tax)"), decimal_places=2, max_digits=12)
  30. total_excl_tax = models.DecimalField(_("Order total (excl. tax)"), decimal_places=2, max_digits=12)
  31. # Shipping charges
  32. shipping_incl_tax = models.DecimalField(_("Shipping charge (inc. tax)"), decimal_places=2, max_digits=12, default=0)
  33. shipping_excl_tax = models.DecimalField(_("Shipping charge (excl. tax)"), decimal_places=2, max_digits=12, default=0)
  34. # Not all lines are actually shipped (such as downloads), hence shipping address
  35. # is not mandatory.
  36. shipping_address = models.ForeignKey('order.ShippingAddress', null=True, blank=True,
  37. verbose_name=_("Shipping Address"))
  38. shipping_method = models.CharField(_("Shipping method"), max_length=128, null=True, blank=True)
  39. # Use this field to indicate that an order is on hold / awaiting payment
  40. status = models.CharField(_("Status"), max_length=100, null=True, blank=True)
  41. guest_email = models.EmailField(_("Guest email address"), null=True, blank=True)
  42. # Index added to this field for reporting
  43. date_placed = models.DateTimeField(auto_now_add=True, db_index=True)
  44. # Dict of available status changes
  45. pipeline = getattr(settings, 'OSCAR_ORDER_STATUS_PIPELINE', {})
  46. cascade = getattr(settings, 'OSCAR_ORDER_STATUS_CASCADE', {})
  47. @classmethod
  48. def all_statuses(cls):
  49. return cls.pipeline.keys()
  50. def available_statuses(self):
  51. return self.pipeline.get(self.status, ())
  52. def set_status(self, new_status):
  53. if new_status == self.status:
  54. return
  55. if new_status not in self.available_statuses():
  56. raise InvalidOrderStatus(_("'%(new_status)s' is not a valid status for order %(number)s "
  57. "(current status: '%(status)s')") % {
  58. 'new_status': new_status,
  59. 'number': self.number,
  60. 'status': self.status})
  61. self.status = new_status
  62. if new_status in self.cascade:
  63. for line in self.lines.all():
  64. line.status = self.cascade[self.status]
  65. line.save()
  66. self.save()
  67. @property
  68. def is_anonymous(self):
  69. return self.user is None
  70. @property
  71. def basket_total_incl_tax(self):
  72. """
  73. Return basket total including tax
  74. """
  75. return self.total_incl_tax - self.shipping_incl_tax
  76. @property
  77. def basket_total_excl_tax(self):
  78. """
  79. Return basket total excluding tax
  80. """
  81. return self.total_excl_tax - self.shipping_excl_tax
  82. @property
  83. def total_before_discounts_incl_tax(self):
  84. total = D('0.00')
  85. for line in self.lines.all():
  86. total += line.line_price_before_discounts_incl_tax
  87. total += self.shipping_incl_tax
  88. return total
  89. @property
  90. def total_before_discounts_excl_tax(self):
  91. total = D('0.00')
  92. for line in self.lines.all():
  93. total += line.line_price_before_discounts_excl_tax
  94. total += self.shipping_excl_tax
  95. return total
  96. @property
  97. def total_discount_incl_tax(self):
  98. """
  99. The amount of discount this order received
  100. """
  101. discount = D('0.00')
  102. for line in self.lines.all():
  103. discount += line.discount_incl_tax
  104. return discount
  105. @property
  106. def total_discount_excl_tax(self):
  107. discount = D('0.00')
  108. for line in self.lines.all():
  109. discount += line.discount_excl_tax
  110. return discount
  111. @property
  112. def total_tax(self):
  113. return self.total_incl_tax - self.total_excl_tax
  114. @property
  115. def num_lines(self):
  116. return self.lines.count()
  117. @property
  118. def num_items(self):
  119. """
  120. Returns the number of items in this order.
  121. """
  122. num_items = 0
  123. for line in self.lines.all():
  124. num_items += line.quantity
  125. return num_items
  126. @property
  127. def shipping_status(self):
  128. events = self.shipping_events.all()
  129. if not len(events):
  130. return ''
  131. # Collect all events by event-type
  132. map = {}
  133. for event in events:
  134. event_name = event.event_type.name
  135. if event_name not in map:
  136. map[event_name] = []
  137. map[event_name] = list(chain(map[event_name], event.line_quantities.all()))
  138. # Determine last complete event
  139. status = _("In progress")
  140. for event_name, event_line_quantities in map.items():
  141. if self._is_event_complete(event_line_quantities):
  142. status = event_name
  143. return status
  144. def _is_event_complete(self, event_quantites):
  145. # Form map of line to quantity
  146. map = {}
  147. for event_quantity in event_quantites:
  148. line_id = event_quantity.line_id
  149. map.setdefault(line_id, 0)
  150. map[line_id] += event_quantity.quantity
  151. for line in self.lines.all():
  152. if map[line.id] != line.quantity:
  153. return False
  154. return True
  155. class Meta:
  156. abstract = True
  157. ordering = ['-date_placed',]
  158. permissions = (
  159. ("can_view", _("Can view orders (eg for reporting)")),
  160. )
  161. verbose_name = _("Order")
  162. verbose_name_plural = _("Orders")
  163. def __unicode__(self):
  164. return u"#%s" % (self.number,)
  165. def verification_hash(self):
  166. return hashlib.md5('%s%s' % (self.number, settings.SECRET_KEY)).hexdigest()
  167. @property
  168. def email(self):
  169. if not self.user:
  170. return self.guest_email
  171. return self.user.email
  172. class AbstractOrderNote(models.Model):
  173. """
  174. A note against an order.
  175. This are often used for audit purposes too. IE, whenever an admin
  176. makes a change to an order, we create a note to record what happened.
  177. """
  178. order = models.ForeignKey('order.Order', related_name="notes", verbose_name=_("Order"))
  179. # These are sometimes programatically generated so don't need a
  180. # user everytime
  181. user = models.ForeignKey('auth.User', null=True, verbose_name=_("User"))
  182. # We allow notes to be classified although this isn't always needed
  183. INFO, WARNING, ERROR, SYSTEM = 'Info', 'Warning', 'Error', 'System'
  184. note_type = models.CharField(_("Note Type"), max_length=128, null=True)
  185. message = models.TextField(_("Message"))
  186. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  187. date_updated = models.DateTimeField(_("Date Updated"), auto_now=True)
  188. # Notes can only be edited for 5 minutes after being created
  189. editable_lifetime = 300
  190. class Meta:
  191. abstract = True
  192. verbose_name = _("Order Note")
  193. verbose_name_plural = _("Order Notes")
  194. def __unicode__(self):
  195. return u"'%s' (%s)" % (self.message[0:50], self.user)
  196. def is_editable(self):
  197. if self.note_type == self.SYSTEM:
  198. return False
  199. return (datetime.datetime.now() - self.date_updated).seconds < self.editable_lifetime
  200. class AbstractCommunicationEvent(models.Model):
  201. """
  202. An order-level event involving a communication to the customer, such
  203. as an confirmation email being sent.
  204. """
  205. order = models.ForeignKey('order.Order', related_name="communication_events", verbose_name=_("Order"))
  206. event_type = models.ForeignKey('customer.CommunicationEventType', verbose_name=_("Event Type"))
  207. date = models.DateTimeField(_("Date"), auto_now_add=True)
  208. class Meta:
  209. abstract = True
  210. verbose_name = _("Communication Event")
  211. verbose_name_plural = _("Communication Events")
  212. def __unicode__(self):
  213. return _("'%(type)s' event for order #%(number)s") % {'type': self.type.name, 'number': self.order.number}
  214. class AbstractLine(models.Model):
  215. """
  216. A order line (basically a product and a quantity)
  217. Not using a line model as it's difficult to capture and payment
  218. information when it splits across a line.
  219. """
  220. order = models.ForeignKey('order.Order', related_name='lines', verbose_name=_("Order"))
  221. # We store the partner, their SKU and the title for cases where the product has been
  222. # deleted from the catalogue. We also store the partner name in case the partner
  223. # gets deleted at a later date.
  224. partner = models.ForeignKey('partner.Partner', related_name='order_lines', blank=True, null=True,
  225. on_delete=models.SET_NULL, verbose_name=_("Partner"))
  226. partner_name = models.CharField(_("Partner name"), max_length=128)
  227. partner_sku = models.CharField(_("Partner SKU"), max_length=128)
  228. title = models.CharField(_("Title"), max_length=255)
  229. upc = models.CharField(_("UPC"), max_length=128, blank=True, null=True)
  230. # We don't want any hard links between orders and the products table so we allow
  231. # this link to be NULLable.
  232. product = models.ForeignKey('catalogue.Product', on_delete=models.SET_NULL, blank=True, null=True,
  233. verbose_name=_("Product"))
  234. quantity = models.PositiveIntegerField(_("Quantity"), default=1)
  235. # Price information (these fields are actually redundant as the information
  236. # can be calculated from the LinePrice models
  237. line_price_incl_tax = models.DecimalField(_("Price (inc. tax)"), decimal_places=2, max_digits=12)
  238. line_price_excl_tax = models.DecimalField(_("Price (excl. tax)"), decimal_places=2, max_digits=12)
  239. # Price information before discounts are applied
  240. line_price_before_discounts_incl_tax = models.DecimalField(_("Price before discounts (inc. tax)"),
  241. decimal_places=2, max_digits=12)
  242. line_price_before_discounts_excl_tax = models.DecimalField(_("Price before discounts (excl. tax)"),
  243. decimal_places=2, max_digits=12)
  244. # REPORTING FIELDS
  245. # Cost price (the price charged by the fulfilment partner for this product).
  246. unit_cost_price = models.DecimalField(_("Unit Cost Price"), decimal_places=2, max_digits=12, blank=True, null=True)
  247. # Normal site price for item (without discounts)
  248. unit_price_incl_tax = models.DecimalField(_("Unit Price (inc. tax)"),decimal_places=2, max_digits=12,
  249. blank=True, null=True)
  250. unit_price_excl_tax = models.DecimalField(_("Unit Price (excl. tax)"), decimal_places=2, max_digits=12,
  251. blank=True, null=True)
  252. # Retail price at time of purchase
  253. unit_retail_price = models.DecimalField(_("Unit Retail Price"), decimal_places=2, max_digits=12,
  254. blank=True, null=True)
  255. # Partner information
  256. partner_line_reference = models.CharField(_("Partner reference"), max_length=128, blank=True, null=True,
  257. help_text=_("This is the item number that the partner uses within their system"))
  258. partner_line_notes = models.TextField(_("Partner Notes"), blank=True, null=True)
  259. # Partners often want to assign some status to each line to help with their own
  260. # business processes.
  261. status = models.CharField(_("Status"), max_length=255, null=True, blank=True)
  262. # Estimated dispatch date - should be set at order time
  263. est_dispatch_date = models.DateField(_("Estimated Dispatch Date"), blank=True, null=True)
  264. pipeline = getattr(settings, 'OSCAR_LINE_STATUS_PIPELINE', {})
  265. @classmethod
  266. def all_statuses(cls):
  267. return cls.pipeline.keys()
  268. def available_statuses(self):
  269. return self.pipeline.get(self.status, ())
  270. def set_status(self, new_status):
  271. if new_status == self.status:
  272. return
  273. if new_status not in self.available_statuses():
  274. raise InvalidLineStatus(_("'%(new_status)s' is not a valid status (current status: '%(status)s')") % {
  275. 'new_status': new_status, 'status': self.status})
  276. self.status = new_status
  277. self.save()
  278. @property
  279. def category(self):
  280. """
  281. Used by Google analytics tracking
  282. """
  283. return None
  284. @property
  285. def description(self):
  286. """
  287. Returns a description of this line including details of any
  288. line attributes.
  289. """
  290. desc = self.title
  291. ops = []
  292. for attribute in self.attributes.all():
  293. ops.append("%s = '%s'" % (attribute.type, attribute.value))
  294. if ops:
  295. desc = "%s (%s)" % (desc, ", ".join(ops))
  296. return desc
  297. @property
  298. def discount_incl_tax(self):
  299. return self.line_price_before_discounts_incl_tax - self.line_price_incl_tax
  300. @property
  301. def discount_excl_tax(self):
  302. return self.line_price_before_discounts_excl_tax - self.line_price_excl_tax
  303. @property
  304. def line_price_tax(self):
  305. return self.line_price_incl_tax - self.line_price_excl_tax
  306. @property
  307. def unit_price_tax(self):
  308. return self.unit_price_incl_tax - self.unit_price_excl_tax
  309. @property
  310. def shipping_status(self):
  311. """Returns a string summary of the shipping status of this line"""
  312. status_map = self.shipping_event_breakdown()
  313. if not status_map:
  314. return ''
  315. events = []
  316. last_complete_event_name = None
  317. for event_dict in status_map.values():
  318. if event_dict['quantity'] == self.quantity:
  319. events.append(event_dict['name'])
  320. last_complete_event_name = event_dict['name']
  321. else:
  322. events.append("%s (%d/%d items)" % (event_dict['name'],
  323. event_dict['quantity'], self.quantity))
  324. if last_complete_event_name == status_map.values()[-1]['name']:
  325. return last_complete_event_name
  326. return ', '.join(events)
  327. def has_shipping_event_occurred(self, event_type, quantity=None):
  328. """
  329. Check whether this line has passed a given shipping event
  330. """
  331. if not quantity:
  332. quantity = self.quantity
  333. for name, event_dict in self.shipping_event_breakdown().items():
  334. if name == event_type.name and event_dict['quantity'] == self.quantity:
  335. return True
  336. return False
  337. @property
  338. def is_product_deleted(self):
  339. return self.product == None
  340. def shipping_event_breakdown(self):
  341. """
  342. Returns a dict of shipping events that this line has been through
  343. """
  344. status_map = {}
  345. for event in self.shippingevent_set.all():
  346. event_type = event.event_type
  347. event_name = event_type.name
  348. event_quantity = event.line_quantities.get(line=self).quantity
  349. if event_name in status_map:
  350. status_map[event_name]['quantity'] += event_quantity
  351. else:
  352. status_map[event_name] = {'name': event_name,
  353. 'event_type': event.event_type,
  354. 'quantity': event_quantity}
  355. return status_map
  356. class Meta:
  357. abstract = True
  358. verbose_name = _("Order Line")
  359. verbose_name_plural = _("Order Lines")
  360. def __unicode__(self):
  361. if self.product:
  362. title = self.product.title
  363. else:
  364. title = _('<missing product>')
  365. return _("Product '%(name)s', quantity '%(qty)s'") % {'name': title, 'qty': self.quantity}
  366. class AbstractLineAttribute(models.Model):
  367. u"""An attribute of a line."""
  368. line = models.ForeignKey('order.Line', related_name='attributes', verbose_name=_("Line"))
  369. option = models.ForeignKey('catalogue.Option', null=True, on_delete=models.SET_NULL,
  370. related_name="line_attributes", verbose_name=_("Option"))
  371. type = models.CharField(_("Type"), max_length=128)
  372. value = models.CharField(_("Value"), max_length=255)
  373. class Meta:
  374. abstract = True
  375. verbose_name = _("Line Attribute")
  376. verbose_name_plural = _("Line Attributes")
  377. def __unicode__(self):
  378. return "%s = %s" % (self.type, self.value)
  379. class AbstractLinePrice(models.Model):
  380. u"""
  381. For tracking the prices paid for each unit within a line.
  382. This is necessary as offers can lead to units within a line
  383. having different prices. For example, one product may be sold at
  384. 50% off as it's part of an offer while the remainder are full price.
  385. """
  386. order = models.ForeignKey('order.Order', related_name='line_prices', verbose_name=_("Option"))
  387. line = models.ForeignKey('order.Line', related_name='prices', verbose_name=_("Line"))
  388. quantity = models.PositiveIntegerField(_("Quantity"), default=1)
  389. price_incl_tax = models.DecimalField(_("Price (inc. tax)"), decimal_places=2, max_digits=12)
  390. price_excl_tax = models.DecimalField(_("Price (excl. tax)"), decimal_places=2, max_digits=12)
  391. shipping_incl_tax = models.DecimalField(_("Shiping (inc. tax)"), decimal_places=2, max_digits=12, default=0)
  392. shipping_excl_tax = models.DecimalField(_("Shipping (excl. tax)"), decimal_places=2, max_digits=12, default=0)
  393. class Meta:
  394. abstract = True
  395. ordering = ('id',)
  396. verbose_name = _("Line Price")
  397. verbose_name_plural = _("Line Prices")
  398. def __unicode__(self):
  399. return _("Line '%(number)s' (quantity %(qty)d) price %(price)s") % {
  400. 'number': self.line, 'qty': self.quantity, 'price': self.price_incl_tax}
  401. # PAYMENT EVENTS
  402. class AbstractPaymentEventType(models.Model):
  403. """
  404. Payment events are things like 'Paid', 'Failed', 'Refunded'
  405. """
  406. name = models.CharField(_("Name"), max_length=128, unique=True)
  407. code = models.SlugField(_("Code"), max_length=128, unique=True)
  408. sequence_number = models.PositiveIntegerField(_("Sequence"), default=0)
  409. def save(self, *args, **kwargs):
  410. if not self.code:
  411. self.code = slugify(self.name)
  412. super(AbstractPaymentEventType, self).save(*args, **kwargs)
  413. class Meta:
  414. abstract = True
  415. verbose_name = _("Payment Event Type")
  416. verbose_name_plural = _("Payment Event Types")
  417. ordering = ('sequence_number',)
  418. def __unicode__(self):
  419. return self.name
  420. class AbstractPaymentEvent(models.Model):
  421. """
  422. An event is something which happens to a line such as
  423. payment being taken for 2 items, or 1 item being dispatched.
  424. """
  425. order = models.ForeignKey('order.Order', related_name='payment_events', verbose_name=_("Order"))
  426. amount = models.DecimalField(_("Amount"), decimal_places=2, max_digits=12)
  427. lines = models.ManyToManyField('order.Line', through='PaymentEventQuantity', verbose_name=_("Lines"))
  428. event_type = models.ForeignKey('order.PaymentEventType', verbose_name=_("Event Type"))
  429. date = models.DateTimeField(_("Date Created"), auto_now_add=True)
  430. class Meta:
  431. abstract = True
  432. verbose_name = _("Payment Event")
  433. verbose_name_plural = _("Payment Events")
  434. def __unicode__(self):
  435. return _("Payment event for order %s") % self.order
  436. def num_affected_lines(self):
  437. return self.lines.all().count()
  438. class PaymentEventQuantity(models.Model):
  439. """
  440. A "through" model linking lines to payment events
  441. """
  442. event = models.ForeignKey('order.PaymentEvent', related_name='line_quantities', verbose_name=_("Event"))
  443. line = models.ForeignKey('order.Line', verbose_name=_("Line"))
  444. quantity = models.PositiveIntegerField(_("Quantity"))
  445. class Meta:
  446. verbose_name = _("Payment Event Quantity")
  447. verbose_name_plural = _("Payment Event Quantities")
  448. # SHIPPING EVENTS
  449. class AbstractShippingEvent(models.Model):
  450. """
  451. An event is something which happens to a group of lines such as
  452. 1 item being dispatched.
  453. """
  454. order = models.ForeignKey('order.Order', related_name='shipping_events', verbose_name=_("Order"))
  455. lines = models.ManyToManyField('order.Line', through='ShippingEventQuantity', verbose_name=_("Lines"))
  456. event_type = models.ForeignKey('order.ShippingEventType', verbose_name=_("Event Type"))
  457. notes = models.TextField(_("Event notes"), blank=True, null=True,
  458. help_text=_("This could be the dispatch reference, or a tracking number"))
  459. date = models.DateTimeField(_("Date Created"), auto_now_add=True)
  460. class Meta:
  461. abstract = True
  462. verbose_name = _("Shipping Event")
  463. verbose_name_plural = _("Shipping Events")
  464. ordering = ['-date']
  465. def __unicode__(self):
  466. return _("Order #%(number)s, type %(type)s") % {
  467. 'number': self.order.number, 'type': self.event_type}
  468. def num_affected_lines(self):
  469. return self.lines.count()
  470. class ShippingEventQuantity(models.Model):
  471. """
  472. A "through" model linking lines to shipping events
  473. """
  474. event = models.ForeignKey('order.ShippingEvent', related_name='line_quantities', verbose_name=_("Event"))
  475. line = models.ForeignKey('order.Line', verbose_name=_("Line"))
  476. quantity = models.PositiveIntegerField(_("Quantity"))
  477. class Meta:
  478. verbose_name = _("Shipping Event Quantity")
  479. verbose_name_plural = _("Shipping Event Quantities")
  480. def _check_previous_events_are_complete(self):
  481. """
  482. Checks whether previous shipping events have passed
  483. """
  484. # Quantity of the proposd event must have occurred for
  485. # the previous events in the sequence.
  486. previous_event_types = self.event.event_type.get_prerequisites()
  487. for event_type in previous_event_types:
  488. quantity = ShippingEventQuantity._default_manager.filter(
  489. line=self.line,
  490. event__event_type=event_type).aggregate(Sum('quantity'))['quantity__sum']
  491. if quantity is None or quantity < int(self.quantity):
  492. raise InvalidShippingEvent(_("This shipping event is not permitted"))
  493. def _check_new_quantity(self):
  494. quantity_row = ShippingEventQuantity._default_manager.filter(line=self.line,
  495. event__event_type=self.event.event_type).aggregate(Sum('quantity'))
  496. previous_quantity = quantity_row['quantity__sum']
  497. if previous_quantity == None:
  498. previous_quantity = 0
  499. if previous_quantity + self.quantity > self.line.quantity:
  500. raise ValueError(_("Invalid quantity (%d) for event type (total exceeds line total)") % self.quantity)
  501. def save(self, *args, **kwargs):
  502. # Default quantity to full quantity of line
  503. if not self.quantity:
  504. self.quantity = self.line.quantity
  505. self.quantity = int(self.quantity)
  506. self._check_previous_events_are_complete()
  507. self._check_new_quantity()
  508. super(ShippingEventQuantity, self).save(*args, **kwargs)
  509. def __unicode__(self):
  510. return _("%(product)s - quantity %(qty)d") % {'product': self.line.product, 'qty': self.quantity}
  511. class AbstractShippingEventType(models.Model):
  512. """
  513. Shipping events are things like 'OrderPlaced', 'Acknowledged', 'Dispatched', 'Refunded'
  514. """
  515. # Name is the friendly description of an event
  516. name = models.CharField(_("Name"), max_length=255, unique=True)
  517. # Code is used in forms
  518. code = models.SlugField(_("Code"), max_length=128, unique=True)
  519. is_required = models.BooleanField(_("Is Required"), default=True,
  520. help_text=_("This event must be passed before the next shipping event can take place"))
  521. # The normal order in which these shipping events take place
  522. sequence_number = models.PositiveIntegerField(_("Sequence"), default=0)
  523. def save(self, *args, **kwargs):
  524. if not self.code:
  525. self.code = slugify(self.name)
  526. super(AbstractShippingEventType, self).save(*args, **kwargs)
  527. class Meta:
  528. abstract = True
  529. verbose_name = _("Shipping Event Type")
  530. verbose_name_plural = _("Shipping Event Types")
  531. ordering = ('sequence_number',)
  532. def __unicode__(self):
  533. return self.name
  534. def get_prerequisites(self):
  535. return self.__class__._default_manager.filter(
  536. is_required=True,
  537. sequence_number__lt=self.sequence_number).order_by('sequence_number')
  538. class AbstractOrderDiscount(models.Model):
  539. """
  540. A discount against an order.
  541. Normally only used for display purposes so an order can be listed with discounts displayed
  542. separately even though in reality, the discounts are applied at the line level.
  543. """
  544. order = models.ForeignKey('order.Order', related_name="discounts", verbose_name=_("Order"))
  545. offer_id = models.PositiveIntegerField(_("Offer ID"), blank=True, null=True)
  546. voucher_id = models.PositiveIntegerField(_("Voucher ID"), blank=True, null=True)
  547. voucher_code = models.CharField(_("Code"), max_length=128, db_index=True, null=True)
  548. amount = models.DecimalField(_("Amount"), decimal_places=2, max_digits=12, default=0)
  549. class Meta:
  550. abstract = True
  551. verbose_name = _("Order Discount")
  552. verbose_name_plural = _("Order Discounts")
  553. def __unicode__(self):
  554. return _("Discount of %(amount)r from order %(order)s") % {'amount': self.amount, 'order': self.order}
  555. @property
  556. def offer(self):
  557. Offer = models.get_model('offer', 'ConditionalOffer')
  558. try:
  559. return Offer.objects.get(id=self.offer_id)
  560. except Offer.DoesNotExist:
  561. return None
  562. @property
  563. def voucher(self):
  564. Voucher = models.get_model('voucher', 'Voucher')
  565. try:
  566. return Voucher.objects.get(id=self.offer_id)
  567. except Voucher.DoesNotExist:
  568. return None
  569. def description(self):
  570. if self.voucher_code:
  571. return self.voucher_code
  572. return self.offer.name