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

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