Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

abstract_models.py 18KB

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