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. from django.db import models
  5. from django.utils import timezone
  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. delta = timezone.now() - self.date_updated
  200. return delta.seconds < self.editable_lifetime
  201. class AbstractCommunicationEvent(models.Model):
  202. """
  203. An order-level event involving a communication to the customer, such
  204. as an confirmation email being sent.
  205. """
  206. order = models.ForeignKey('order.Order', related_name="communication_events", verbose_name=_("Order"))
  207. event_type = models.ForeignKey('customer.CommunicationEventType', verbose_name=_("Event Type"))
  208. date = models.DateTimeField(_("Date"), auto_now_add=True)
  209. class Meta:
  210. abstract = True
  211. verbose_name = _("Communication Event")
  212. verbose_name_plural = _("Communication Events")
  213. def __unicode__(self):
  214. return _("'%(type)s' event for order #%(number)s") % {'type': self.type.name, 'number': self.order.number}
  215. class AbstractLine(models.Model):
  216. """
  217. A order line (basically a product and a quantity)
  218. Not using a line model as it's difficult to capture and payment
  219. information when it splits across a line.
  220. """
  221. order = models.ForeignKey('order.Order', related_name='lines', verbose_name=_("Order"))
  222. # We store the partner, their SKU and the title for cases where the product has been
  223. # deleted from the catalogue. We also store the partner name in case the partner
  224. # gets deleted at a later date.
  225. partner = models.ForeignKey('partner.Partner', related_name='order_lines', blank=True, null=True,
  226. on_delete=models.SET_NULL, verbose_name=_("Partner"))
  227. partner_name = models.CharField(_("Partner name"), max_length=128)
  228. partner_sku = models.CharField(_("Partner SKU"), max_length=128)
  229. title = models.CharField(_("Title"), max_length=255)
  230. upc = models.CharField(_("UPC"), max_length=128, blank=True, null=True)
  231. # We don't want any hard links between orders and the products table so we allow
  232. # this link to be NULLable.
  233. product = models.ForeignKey('catalogue.Product', on_delete=models.SET_NULL, blank=True, null=True,
  234. verbose_name=_("Product"))
  235. quantity = models.PositiveIntegerField(_("Quantity"), default=1)
  236. # Price information (these fields are actually redundant as the information
  237. # can be calculated from the LinePrice models
  238. line_price_incl_tax = models.DecimalField(_("Price (inc. tax)"), decimal_places=2, max_digits=12)
  239. line_price_excl_tax = models.DecimalField(_("Price (excl. tax)"), decimal_places=2, max_digits=12)
  240. # Price information before discounts are applied
  241. line_price_before_discounts_incl_tax = models.DecimalField(_("Price before discounts (inc. tax)"),
  242. decimal_places=2, max_digits=12)
  243. line_price_before_discounts_excl_tax = models.DecimalField(_("Price before discounts (excl. tax)"),
  244. decimal_places=2, max_digits=12)
  245. # REPORTING FIELDS
  246. # Cost price (the price charged by the fulfilment partner for this product).
  247. unit_cost_price = models.DecimalField(_("Unit Cost Price"), decimal_places=2, max_digits=12, blank=True, null=True)
  248. # Normal site price for item (without discounts)
  249. unit_price_incl_tax = models.DecimalField(_("Unit Price (inc. tax)"),decimal_places=2, max_digits=12,
  250. blank=True, null=True)
  251. unit_price_excl_tax = models.DecimalField(_("Unit Price (excl. tax)"), decimal_places=2, max_digits=12,
  252. blank=True, null=True)
  253. # Retail price at time of purchase
  254. unit_retail_price = models.DecimalField(_("Unit Retail Price"), decimal_places=2, max_digits=12,
  255. blank=True, null=True)
  256. # Partner information
  257. partner_line_reference = models.CharField(_("Partner reference"), max_length=128, blank=True, null=True,
  258. help_text=_("This is the item number that the partner uses within their system"))
  259. partner_line_notes = models.TextField(_("Partner Notes"), blank=True, null=True)
  260. # Partners often want to assign some status to each line to help with their own
  261. # business processes.
  262. status = models.CharField(_("Status"), max_length=255, null=True, blank=True)
  263. # Estimated dispatch date - should be set at order time
  264. est_dispatch_date = models.DateField(_("Estimated Dispatch Date"), blank=True, null=True)
  265. pipeline = getattr(settings, 'OSCAR_LINE_STATUS_PIPELINE', {})
  266. @classmethod
  267. def all_statuses(cls):
  268. return cls.pipeline.keys()
  269. def available_statuses(self):
  270. return self.pipeline.get(self.status, ())
  271. def set_status(self, new_status):
  272. if new_status == self.status:
  273. return
  274. if new_status not in self.available_statuses():
  275. raise InvalidLineStatus(_("'%(new_status)s' is not a valid status (current status: '%(status)s')") % {
  276. 'new_status': new_status, 'status': self.status})
  277. self.status = new_status
  278. self.save()
  279. @property
  280. def category(self):
  281. """
  282. Used by Google analytics tracking
  283. """
  284. return None
  285. @property
  286. def description(self):
  287. """
  288. Returns a description of this line including details of any
  289. line attributes.
  290. """
  291. desc = self.title
  292. ops = []
  293. for attribute in self.attributes.all():
  294. ops.append("%s = '%s'" % (attribute.type, attribute.value))
  295. if ops:
  296. desc = "%s (%s)" % (desc, ", ".join(ops))
  297. return desc
  298. @property
  299. def discount_incl_tax(self):
  300. return self.line_price_before_discounts_incl_tax - self.line_price_incl_tax
  301. @property
  302. def discount_excl_tax(self):
  303. return self.line_price_before_discounts_excl_tax - self.line_price_excl_tax
  304. @property
  305. def line_price_tax(self):
  306. return self.line_price_incl_tax - self.line_price_excl_tax
  307. @property
  308. def unit_price_tax(self):
  309. return self.unit_price_incl_tax - self.unit_price_excl_tax
  310. @property
  311. def shipping_status(self):
  312. """Returns a string summary of the shipping status of this line"""
  313. status_map = self.shipping_event_breakdown()
  314. if not status_map:
  315. return ''
  316. events = []
  317. last_complete_event_name = None
  318. for event_dict in status_map.values():
  319. if event_dict['quantity'] == self.quantity:
  320. events.append(event_dict['name'])
  321. last_complete_event_name = event_dict['name']
  322. else:
  323. events.append("%s (%d/%d items)" % (event_dict['name'],
  324. event_dict['quantity'], self.quantity))
  325. if last_complete_event_name == status_map.values()[-1]['name']:
  326. return last_complete_event_name
  327. return ', '.join(events)
  328. def has_shipping_event_occurred(self, event_type, quantity=None):
  329. """
  330. Check whether this line has passed a given shipping event
  331. """
  332. if not quantity:
  333. quantity = self.quantity
  334. for name, event_dict in self.shipping_event_breakdown().items():
  335. if name == event_type.name and event_dict['quantity'] == self.quantity:
  336. return True
  337. return False
  338. @property
  339. def is_product_deleted(self):
  340. return self.product == None
  341. def shipping_event_breakdown(self):
  342. """
  343. Returns a dict of shipping events that this line has been through
  344. """
  345. status_map = {}
  346. for event in self.shippingevent_set.all():
  347. event_type = event.event_type
  348. event_name = event_type.name
  349. event_quantity = event.line_quantities.get(line=self).quantity
  350. if event_name in status_map:
  351. status_map[event_name]['quantity'] += event_quantity
  352. else:
  353. status_map[event_name] = {'name': event_name,
  354. 'event_type': event.event_type,
  355. 'quantity': event_quantity}
  356. return status_map
  357. class Meta:
  358. abstract = True
  359. verbose_name = _("Order Line")
  360. verbose_name_plural = _("Order Lines")
  361. def __unicode__(self):
  362. if self.product:
  363. title = self.product.title
  364. else:
  365. title = _('<missing product>')
  366. return _("Product '%(name)s', quantity '%(qty)s'") % {'name': title, 'qty': self.quantity}
  367. class AbstractLineAttribute(models.Model):
  368. u"""An attribute of a line."""
  369. line = models.ForeignKey('order.Line', related_name='attributes', verbose_name=_("Line"))
  370. option = models.ForeignKey('catalogue.Option', null=True, on_delete=models.SET_NULL,
  371. related_name="line_attributes", verbose_name=_("Option"))
  372. type = models.CharField(_("Type"), max_length=128)
  373. value = models.CharField(_("Value"), max_length=255)
  374. class Meta:
  375. abstract = True
  376. verbose_name = _("Line Attribute")
  377. verbose_name_plural = _("Line Attributes")
  378. def __unicode__(self):
  379. return "%s = %s" % (self.type, self.value)
  380. class AbstractLinePrice(models.Model):
  381. u"""
  382. For tracking the prices paid for each unit within a line.
  383. This is necessary as offers can lead to units within a line
  384. having different prices. For example, one product may be sold at
  385. 50% off as it's part of an offer while the remainder are full price.
  386. """
  387. order = models.ForeignKey('order.Order', related_name='line_prices', verbose_name=_("Option"))
  388. line = models.ForeignKey('order.Line', related_name='prices', verbose_name=_("Line"))
  389. quantity = models.PositiveIntegerField(_("Quantity"), default=1)
  390. price_incl_tax = models.DecimalField(_("Price (inc. tax)"), decimal_places=2, max_digits=12)
  391. price_excl_tax = models.DecimalField(_("Price (excl. tax)"), decimal_places=2, max_digits=12)
  392. shipping_incl_tax = models.DecimalField(_("Shiping (inc. tax)"), decimal_places=2, max_digits=12, default=0)
  393. shipping_excl_tax = models.DecimalField(_("Shipping (excl. tax)"), decimal_places=2, max_digits=12, default=0)
  394. class Meta:
  395. abstract = True
  396. ordering = ('id',)
  397. verbose_name = _("Line Price")
  398. verbose_name_plural = _("Line Prices")
  399. def __unicode__(self):
  400. return _("Line '%(number)s' (quantity %(qty)d) price %(price)s") % {
  401. 'number': self.line, 'qty': self.quantity, 'price': self.price_incl_tax}
  402. # PAYMENT EVENTS
  403. class AbstractPaymentEventType(models.Model):
  404. """
  405. Payment events are things like 'Paid', 'Failed', 'Refunded'
  406. """
  407. name = models.CharField(_("Name"), max_length=128, unique=True)
  408. code = models.SlugField(_("Code"), max_length=128, unique=True)
  409. sequence_number = models.PositiveIntegerField(_("Sequence"), default=0)
  410. def save(self, *args, **kwargs):
  411. if not self.code:
  412. self.code = slugify(self.name)
  413. super(AbstractPaymentEventType, self).save(*args, **kwargs)
  414. class Meta:
  415. abstract = True
  416. verbose_name = _("Payment Event Type")
  417. verbose_name_plural = _("Payment Event Types")
  418. ordering = ('sequence_number',)
  419. def __unicode__(self):
  420. return self.name
  421. class AbstractPaymentEvent(models.Model):
  422. """
  423. An event is something which happens to a line such as
  424. payment being taken for 2 items, or 1 item being dispatched.
  425. """
  426. order = models.ForeignKey('order.Order', related_name='payment_events', verbose_name=_("Order"))
  427. amount = models.DecimalField(_("Amount"), decimal_places=2, max_digits=12)
  428. lines = models.ManyToManyField('order.Line', through='PaymentEventQuantity', verbose_name=_("Lines"))
  429. event_type = models.ForeignKey('order.PaymentEventType', verbose_name=_("Event Type"))
  430. date = models.DateTimeField(_("Date Created"), auto_now_add=True)
  431. class Meta:
  432. abstract = True
  433. verbose_name = _("Payment Event")
  434. verbose_name_plural = _("Payment Events")
  435. def __unicode__(self):
  436. return _("Payment event for order %s") % self.order
  437. def num_affected_lines(self):
  438. return self.lines.all().count()
  439. class PaymentEventQuantity(models.Model):
  440. """
  441. A "through" model linking lines to payment events
  442. """
  443. event = models.ForeignKey('order.PaymentEvent', related_name='line_quantities', verbose_name=_("Event"))
  444. line = models.ForeignKey('order.Line', verbose_name=_("Line"))
  445. quantity = models.PositiveIntegerField(_("Quantity"))
  446. class Meta:
  447. verbose_name = _("Payment Event Quantity")
  448. verbose_name_plural = _("Payment Event Quantities")
  449. # SHIPPING EVENTS
  450. class AbstractShippingEvent(models.Model):
  451. """
  452. An event is something which happens to a group of lines such as
  453. 1 item being dispatched.
  454. """
  455. order = models.ForeignKey('order.Order', related_name='shipping_events', verbose_name=_("Order"))
  456. lines = models.ManyToManyField('order.Line', through='ShippingEventQuantity', verbose_name=_("Lines"))
  457. event_type = models.ForeignKey('order.ShippingEventType', verbose_name=_("Event Type"))
  458. notes = models.TextField(_("Event notes"), blank=True, null=True,
  459. help_text=_("This could be the dispatch reference, or a tracking number"))
  460. date = models.DateTimeField(_("Date Created"), auto_now_add=True)
  461. class Meta:
  462. abstract = True
  463. verbose_name = _("Shipping Event")
  464. verbose_name_plural = _("Shipping Events")
  465. ordering = ['-date']
  466. def __unicode__(self):
  467. return _("Order #%(number)s, type %(type)s") % {
  468. 'number': self.order.number, 'type': self.event_type}
  469. def num_affected_lines(self):
  470. return self.lines.count()
  471. class ShippingEventQuantity(models.Model):
  472. """
  473. A "through" model linking lines to shipping events
  474. """
  475. event = models.ForeignKey('order.ShippingEvent', related_name='line_quantities', verbose_name=_("Event"))
  476. line = models.ForeignKey('order.Line', verbose_name=_("Line"))
  477. quantity = models.PositiveIntegerField(_("Quantity"))
  478. class Meta:
  479. verbose_name = _("Shipping Event Quantity")
  480. verbose_name_plural = _("Shipping Event Quantities")
  481. def _check_previous_events_are_complete(self):
  482. """
  483. Checks whether previous shipping events have passed
  484. """
  485. # Quantity of the proposd event must have occurred for
  486. # the previous events in the sequence.
  487. previous_event_types = self.event.event_type.get_prerequisites()
  488. for event_type in previous_event_types:
  489. quantity = ShippingEventQuantity._default_manager.filter(
  490. line=self.line,
  491. event__event_type=event_type).aggregate(Sum('quantity'))['quantity__sum']
  492. if quantity is None or quantity < int(self.quantity):
  493. raise InvalidShippingEvent(_("This shipping event is not permitted"))
  494. def _check_new_quantity(self):
  495. quantity_row = ShippingEventQuantity._default_manager.filter(line=self.line,
  496. event__event_type=self.event.event_type).aggregate(Sum('quantity'))
  497. previous_quantity = quantity_row['quantity__sum']
  498. if previous_quantity == None:
  499. previous_quantity = 0
  500. if previous_quantity + self.quantity > self.line.quantity:
  501. raise ValueError(_("Invalid quantity (%d) for event type (total exceeds line total)") % self.quantity)
  502. def save(self, *args, **kwargs):
  503. # Default quantity to full quantity of line
  504. if not self.quantity:
  505. self.quantity = self.line.quantity
  506. self.quantity = int(self.quantity)
  507. self._check_previous_events_are_complete()
  508. self._check_new_quantity()
  509. super(ShippingEventQuantity, self).save(*args, **kwargs)
  510. def __unicode__(self):
  511. return _("%(product)s - quantity %(qty)d") % {'product': self.line.product, 'qty': self.quantity}
  512. class AbstractShippingEventType(models.Model):
  513. """
  514. Shipping events are things like 'OrderPlaced', 'Acknowledged', 'Dispatched', 'Refunded'
  515. """
  516. # Name is the friendly description of an event
  517. name = models.CharField(_("Name"), max_length=255, unique=True)
  518. # Code is used in forms
  519. code = models.SlugField(_("Code"), max_length=128, unique=True)
  520. is_required = models.BooleanField(_("Is Required"), default=True,
  521. help_text=_("This event must be passed before the next shipping event can take place"))
  522. # The normal order in which these shipping events take place
  523. sequence_number = models.PositiveIntegerField(_("Sequence"), default=0)
  524. def save(self, *args, **kwargs):
  525. if not self.code:
  526. self.code = slugify(self.name)
  527. super(AbstractShippingEventType, self).save(*args, **kwargs)
  528. class Meta:
  529. abstract = True
  530. verbose_name = _("Shipping Event Type")
  531. verbose_name_plural = _("Shipping Event Types")
  532. ordering = ('sequence_number',)
  533. def __unicode__(self):
  534. return self.name
  535. def get_prerequisites(self):
  536. return self.__class__._default_manager.filter(
  537. is_required=True,
  538. sequence_number__lt=self.sequence_number).order_by('sequence_number')
  539. class AbstractOrderDiscount(models.Model):
  540. """
  541. A discount against an order.
  542. Normally only used for display purposes so an order can be listed with discounts displayed
  543. separately even though in reality, the discounts are applied at the line level.
  544. """
  545. order = models.ForeignKey('order.Order', related_name="discounts", verbose_name=_("Order"))
  546. offer_id = models.PositiveIntegerField(_("Offer ID"), blank=True, null=True)
  547. voucher_id = models.PositiveIntegerField(_("Voucher ID"), blank=True, null=True)
  548. voucher_code = models.CharField(_("Code"), max_length=128, db_index=True, null=True)
  549. amount = models.DecimalField(_("Amount"), decimal_places=2, max_digits=12, default=0)
  550. class Meta:
  551. abstract = True
  552. verbose_name = _("Order Discount")
  553. verbose_name_plural = _("Order Discounts")
  554. def __unicode__(self):
  555. return _("Discount of %(amount)r from order %(order)s") % {'amount': self.amount, 'order': self.order}
  556. @property
  557. def offer(self):
  558. Offer = models.get_model('offer', 'ConditionalOffer')
  559. try:
  560. return Offer.objects.get(id=self.offer_id)
  561. except Offer.DoesNotExist:
  562. return None
  563. @property
  564. def voucher(self):
  565. Voucher = models.get_model('voucher', 'Voucher')
  566. try:
  567. return Voucher.objects.get(id=self.offer_id)
  568. except Voucher.DoesNotExist:
  569. return None
  570. def description(self):
  571. if self.voucher_code:
  572. return self.voucher_code
  573. return self.offer.name