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

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