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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. from itertools import chain
  2. from django.db import models
  3. from django.contrib.auth.models import User
  4. from django.template.defaultfilters import slugify
  5. from django.utils.translation import ugettext_lazy as _
  6. from django.db.models import Sum
  7. class AbstractOrder(models.Model):
  8. u"""An order"""
  9. number = models.CharField(_("Order number"), max_length=128, db_index=True)
  10. # We track the site that each order is placed within
  11. site = models.ForeignKey('sites.Site')
  12. basket = models.ForeignKey('basket.Basket')
  13. # Orders can be anonymous so we don't always have a customer ID
  14. user = models.ForeignKey(User, related_name='orders', null=True, blank=True)
  15. # Billing address is not always required (eg paying by gift card)
  16. billing_address = models.ForeignKey('order.BillingAddress', null=True, blank=True)
  17. # Total price looks like it could be calculated by adding up the
  18. # prices of the associated lines, but in some circumstances extra
  19. # order-level charges are added and so we need to store it separately
  20. total_incl_tax = models.DecimalField(_("Order total (inc. tax)"), decimal_places=2, max_digits=12)
  21. total_excl_tax = models.DecimalField(_("Order total (excl. tax)"), decimal_places=2, max_digits=12)
  22. # Shipping charges
  23. shipping_incl_tax = models.DecimalField(_("Shipping charge (inc. tax)"), decimal_places=2, max_digits=12, default=0)
  24. shipping_excl_tax = models.DecimalField(_("Shipping charge (excl. tax)"), decimal_places=2, max_digits=12, default=0)
  25. # Not all lines are actually shipped (such as downloads), hence shipping address
  26. # is not mandatory.
  27. shipping_address = models.ForeignKey('order.ShippingAddress', null=True, blank=True)
  28. shipping_method = models.CharField(_("Shipping method"), max_length=128, null=True, blank=True)
  29. # Index added to this field for reporting
  30. date_placed = models.DateTimeField(auto_now_add=True, db_index=True)
  31. @property
  32. def basket_total_incl_tax(self):
  33. u"""Return basket total including tax"""
  34. return self.total_incl_tax - self.shipping_incl_tax
  35. @property
  36. def basket_total_excl_tax(self):
  37. u"""Return basket total excluding tax"""
  38. return self.total_excl_tax - self.shipping_excl_tax
  39. @property
  40. def num_lines(self):
  41. return self.lines.count()
  42. @property
  43. def num_items(self):
  44. u"""
  45. Returns the number of items in this order.
  46. """
  47. num_items = 0
  48. for line in self.lines.all():
  49. num_items += line.quantity
  50. return num_items
  51. @property
  52. def shipping_status(self):
  53. events = self.shipping_events.all()
  54. if not len(events):
  55. return ''
  56. # Collect all events by event-type
  57. map = {}
  58. for event in events:
  59. event_name = event.event_type.name
  60. if event_name not in map:
  61. map[event_name] = []
  62. map[event_name] = list(chain(map[event_name], event.line_quantities.all()))
  63. # Determine last complete event
  64. status = _("In progress")
  65. for event_name, event_line_quantities in map.items():
  66. if self._is_event_complete(event_line_quantities):
  67. status = event_name
  68. return status
  69. def _is_event_complete(self, event_quantites):
  70. # Form map of line to quantity
  71. map = {}
  72. for event_quantity in event_quantites:
  73. line_id = event_quantity.line_id
  74. map.setdefault(line_id, 0)
  75. map[line_id] += event_quantity.quantity
  76. for line in self.lines.all():
  77. if map[line.id] != line.quantity:
  78. return False
  79. return True
  80. class Meta:
  81. abstract = True
  82. ordering = ['-date_placed',]
  83. permissions = (
  84. ("can_view", "Can view orders (eg for reporting)"),
  85. )
  86. def __unicode__(self):
  87. return u"#%s" % (self.number,)
  88. class AbstractOrderNote(models.Model):
  89. u"""A note against an order."""
  90. order = models.ForeignKey('order.Order', related_name="notes")
  91. user = models.ForeignKey('auth.User')
  92. message = models.TextField()
  93. date = models.DateTimeField(auto_now_add=True)
  94. class Meta:
  95. abstract = True
  96. def __unicode__(self):
  97. return u"'%s' (%s)" % (self.message[0:50], self.user)
  98. class AbstractCommunicationEvent(models.Model):
  99. u"""
  100. An order-level event involving a communication to the customer, such
  101. as an confirmation email being sent."""
  102. order = models.ForeignKey('order.Order', related_name="communication_events")
  103. type = models.ForeignKey('order.CommunicationEventType')
  104. date = models.DateTimeField(auto_now_add=True)
  105. class Meta:
  106. abstract = True
  107. class AbstractCommunicationEventType(models.Model):
  108. u"""Communication events are things like 'OrderConfirmationEmailSent'"""
  109. # Code is used in forms
  110. code = models.SlugField(max_length=128)
  111. # Name is the friendly description of an event
  112. name = models.CharField(max_length=255)
  113. def save(self, *args, **kwargs):
  114. if not self.code:
  115. self.code = slugify(self.name)
  116. super(AbstractOrderEventType, self).save(*args, **kwargs)
  117. class Meta:
  118. abstract = True
  119. verbose_name_plural = _("Communication event types")
  120. def __unicode__(self):
  121. return self.name
  122. class AbstractLine(models.Model):
  123. u"""
  124. A order line (basically a product and a quantity)
  125. Not using a line model as it's difficult to capture and payment
  126. information when it splits across a line.
  127. """
  128. order = models.ForeignKey('order.Order', related_name='lines')
  129. # We store the partner, their SKU and the title for cases where the product has been
  130. # deleted from the catalogue.
  131. partner = models.ForeignKey('stock.Partner', related_name='order_lines')
  132. partner_reference = models.CharField(_("Partner reference"), max_length=128, blank=True, null=True)
  133. title = models.CharField(_("Title"), max_length=255)
  134. # We don't want any hard links between orders and the products table
  135. product = models.ForeignKey('product.Item', on_delete=models.SET_NULL, null=True)
  136. quantity = models.PositiveIntegerField(default=1)
  137. # Price information (these fields are actually redundant as the information
  138. # can be calculated from the LinePrice models
  139. line_price_incl_tax = models.DecimalField(decimal_places=2, max_digits=12)
  140. line_price_excl_tax = models.DecimalField(decimal_places=2, max_digits=12)
  141. # Cost price (the price charged by the fulfilment partner for this product). This
  142. # is useful for audit and financial reporting.
  143. cost_price = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True)
  144. # Partner information
  145. partner_line_reference = models.CharField(_("Partner reference"), max_length=128, blank=True, null=True,
  146. help_text=_("This is the item number that the partner uses within their system"))
  147. partner_line_notes = models.TextField(blank=True, null=True)
  148. # Estimated dispatch date - should be set at order time
  149. est_dispatch_date = models.DateField(blank=True, null=True)
  150. @property
  151. def description(self):
  152. u"""
  153. Returns a description of this line including details of any
  154. line attributes.
  155. """
  156. d = str(self.product)
  157. ops = []
  158. for attribute in self.attributes.all():
  159. ops.append("%s = '%s'" % (attribute.type, attribute.value))
  160. if ops:
  161. d = "%s (%s)" % (d, ", ".join(ops))
  162. return d
  163. @property
  164. def shipping_status(self):
  165. u"""Returns a string summary of the shipping status of this line"""
  166. status_map = self._shipping_event_history()
  167. if not status_map:
  168. return ''
  169. events = []
  170. last_complete_event_name = None
  171. for event_dict in status_map:
  172. if event_dict['quantity'] == self.quantity:
  173. events.append(event_dict['name'])
  174. last_complete_event_name = event_dict['name']
  175. else:
  176. events.append("%s (%d/%d items)" % (event_dict['name'],
  177. event_dict['quantity'], self.quantity))
  178. if last_complete_event_name == status_map[-1]['name']:
  179. return last_complete_event_name
  180. return ', '.join(events)
  181. def has_shipping_event_occurred(self, event_type):
  182. u"""Checks whether this line has passed a given shipping event"""
  183. for event_dict in self._shipping_event_history():
  184. if event_dict['name'] == event_type.name and event_dict['quantity'] == self.quantity:
  185. return True
  186. return False
  187. @property
  188. def is_product_deleted(self):
  189. return self.product == None
  190. def _shipping_event_history(self):
  191. u"""
  192. Returns a list of shipping events"""
  193. status_map = {}
  194. for event in self.shippingevent_set.all():
  195. event_name = event.event_type.name
  196. event_quantity = event.line_quantities.get(line=self).quantity
  197. if event_name in status_map:
  198. status_map[event_name]['quantity'] += event_quantity
  199. else:
  200. status_map[event_name] = {'name': event_name, 'quantity': event_quantity}
  201. return list(status_map.values())
  202. class Meta:
  203. abstract = True
  204. verbose_name_plural = _("Order lines")
  205. def __unicode__(self):
  206. return u"Product '%s', quantity '%s'" % (self.product, self.quantity)
  207. class AbstractLineAttribute(models.Model):
  208. u"""An attribute of a line."""
  209. line = models.ForeignKey('order.Line', related_name='attributes')
  210. type = models.CharField(_("Type"), max_length=128)
  211. value = models.CharField(_("Value"), max_length=255)
  212. class Meta:
  213. abstract = True
  214. def __unicode__(self):
  215. return "%s = %s" % (self.type, self.value)
  216. class AbstractLinePrice(models.Model):
  217. u"""
  218. For tracking the prices paid for each unit within a line.
  219. This is necessary as offers can lead to units within a line
  220. having different prices. For example, one product may be sold at
  221. 50% off as it's part of an offer while the remainder are full price.
  222. """
  223. order = models.ForeignKey('order.Order', related_name='line_prices')
  224. line = models.ForeignKey('order.Line', related_name='prices')
  225. quantity = models.PositiveIntegerField(default=1)
  226. price_incl_tax = models.DecimalField(decimal_places=2, max_digits=12)
  227. price_excl_tax = models.DecimalField(decimal_places=2, max_digits=12)
  228. shipping_incl_tax = models.DecimalField(decimal_places=2, max_digits=12, default=0)
  229. shipping_excl_tax = models.DecimalField(decimal_places=2, max_digits=12, default=0)
  230. class Meta:
  231. abstract = True
  232. def __unicode__(self):
  233. return u"Line '%s' (quantity %d) price %s" % (self.line, self.quantity, self.price_incl_tax)
  234. class AbstractPaymentEvent(models.Model):
  235. u"""
  236. An event is something which happens to a line such as
  237. payment being taken for 2 items, or 1 item being dispatched.
  238. """
  239. order = models.ForeignKey('order.Order', related_name='payment_events')
  240. line = models.ForeignKey('order.Line', related_name='payment_events')
  241. quantity = models.PositiveIntegerField(default=1)
  242. event_type = models.ForeignKey('order.PaymentEventType')
  243. date = models.DateTimeField(auto_now_add=True)
  244. class Meta:
  245. abstract = True
  246. verbose_name_plural = _("Payment events")
  247. def __unicode__(self):
  248. return u"Order #%d, line %s: %d items %s" % (
  249. self.line.order.number, self.line.line_id, self.quantity, self.event_type)
  250. class AbstractPaymentEventType(models.Model):
  251. u"""Payment events are things like 'Paid', 'Failed', 'Refunded'"""
  252. # Name is the friendly description of an event
  253. name = models.CharField(max_length=255)
  254. code = models.SlugField(max_length=128)
  255. # The normal order in which these shipping events take place
  256. sequence_number = models.PositiveIntegerField(default=0)
  257. def save(self, *args, **kwargs):
  258. if not self.code:
  259. self.code = slugify(self.name)
  260. super(AbstractPaymentEventType, self).save(*args, **kwargs)
  261. class Meta:
  262. abstract = True
  263. verbose_name_plural = _("Payment event types")
  264. ordering = ('sequence_number',)
  265. def __unicode__(self):
  266. return self.name
  267. class AbstractShippingEvent(models.Model):
  268. u"""
  269. An event is something which happens to a group of lines such as
  270. 1 item being dispatched.
  271. """
  272. order = models.ForeignKey('order.Order', related_name='shipping_events')
  273. lines = models.ManyToManyField('order.Line', through='ShippingEventQuantity')
  274. event_type = models.ForeignKey('order.ShippingEventType')
  275. notes = models.TextField(_("Event notes"), blank=True, null=True,
  276. help_text="This could be the dispatch reference, or a tracking number")
  277. date = models.DateTimeField(auto_now_add=True)
  278. class Meta:
  279. abstract = True
  280. verbose_name_plural = _("Shipping events")
  281. ordering = ['-date']
  282. def __unicode__(self):
  283. return u"Order #%s, type %s" % (
  284. self.order.number, self.event_type)
  285. def num_affected_lines(self):
  286. return self.lines.count()
  287. class ShippingEventQuantity(models.Model):
  288. u"""A "through" model linking lines to shipping events"""
  289. event = models.ForeignKey('order.ShippingEvent', related_name='line_quantities')
  290. line = models.ForeignKey('order.Line')
  291. quantity = models.PositiveIntegerField()
  292. def _check_previous_events_are_complete(self):
  293. u"""Checks whether previous shipping events have passed"""
  294. previous_events = ShippingEventQuantity._default_manager.filter(line=self.line,
  295. event__event_type__sequence_number__lt=self.event.event_type.sequence_number)
  296. self.quantity = int(self.quantity)
  297. for event_quantities in previous_events:
  298. if event_quantities.quantity < self.quantity:
  299. raise ValueError("Invalid quantity (%d) for event type (a previous event has not been fully passed)" % self.quantity)
  300. def _check_new_quantity(self):
  301. quantity_row = ShippingEventQuantity._default_manager.filter(line=self.line,
  302. event__event_type=self.event.event_type).aggregate(Sum('quantity'))
  303. previous_quantity = quantity_row['quantity__sum']
  304. if previous_quantity == None:
  305. previous_quantity = 0
  306. if previous_quantity + self.quantity > self.line.quantity:
  307. raise ValueError("Invalid quantity (%d) for event type (total exceeds line total)" % self.quantity)
  308. def save(self, *args, **kwargs):
  309. # Default quantity to full quantity of line
  310. if not self.quantity:
  311. self.quantity = self.line.quantity
  312. self._check_previous_events_are_complete()
  313. self._check_new_quantity()
  314. super(ShippingEventQuantity, self).save(*args, **kwargs)
  315. def __unicode__(self):
  316. return "%s - quantity %d" % (self.line.product, self.quantity)
  317. class AbstractShippingEventType(models.Model):
  318. u"""Shipping events are things like 'OrderPlaced', 'Acknowledged', 'Dispatched', 'Refunded'"""
  319. # Name is the friendly description of an event
  320. name = models.CharField(max_length=255)
  321. # Code is used in forms
  322. code = models.SlugField(max_length=128)
  323. is_required = models.BooleanField(default=True, help_text="This event must be passed before the next shipping event can take place")
  324. # The normal order in which these shipping events take place
  325. sequence_number = models.PositiveIntegerField(default=0)
  326. def save(self, *args, **kwargs):
  327. if not self.code:
  328. self.code = slugify(self.name)
  329. super(AbstractShippingEventType, self).save(*args, **kwargs)
  330. class Meta:
  331. abstract = True
  332. verbose_name_plural = _("Shipping event types")
  333. ordering = ('sequence_number',)
  334. def __unicode__(self):
  335. return self.name