Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

abstract_models.py 26KB

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