Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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. # 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. # Cost price (the price charged by the fulfilment partner for this product). This
  145. # is useful for audit and financial reporting.
  146. cost_price = models.DecimalField(decimal_places=2, max_digits=12, blank=True, null=True)
  147. # Partner information
  148. partner_line_reference = models.CharField(_("Partner reference"), max_length=128, blank=True, null=True,
  149. help_text=_("This is the item number that the partner uses within their system"))
  150. partner_line_notes = models.TextField(blank=True, null=True)
  151. # Estimated dispatch date - should be set at order time
  152. est_dispatch_date = models.DateField(blank=True, null=True)
  153. @property
  154. def description(self):
  155. u"""
  156. Returns a description of this line including details of any
  157. line attributes.
  158. """
  159. d = str(self.product)
  160. ops = []
  161. for attribute in self.attributes.all():
  162. ops.append("%s = '%s'" % (attribute.type, attribute.value))
  163. if ops:
  164. d = "%s (%s)" % (d, ", ".join(ops))
  165. return d
  166. @property
  167. def shipping_status(self):
  168. u"""Returns a string summary of the shipping status of this line"""
  169. status_map = self._shipping_event_history()
  170. if not status_map:
  171. return ''
  172. events = []
  173. last_complete_event_name = None
  174. for event_dict in status_map:
  175. if event_dict['quantity'] == self.quantity:
  176. events.append(event_dict['name'])
  177. last_complete_event_name = event_dict['name']
  178. else:
  179. events.append("%s (%d/%d items)" % (event_dict['name'],
  180. event_dict['quantity'], self.quantity))
  181. if last_complete_event_name == status_map[-1]['name']:
  182. return last_complete_event_name
  183. return ', '.join(events)
  184. def has_shipping_event_occurred(self, event_type):
  185. u"""Checks whether this line has passed a given shipping event"""
  186. for event_dict in self._shipping_event_history():
  187. if event_dict['name'] == event_type.name and event_dict['quantity'] == self.quantity:
  188. return True
  189. return False
  190. @property
  191. def is_product_deleted(self):
  192. return self.product == None
  193. def _shipping_event_history(self):
  194. u"""
  195. Returns a list of shipping events"""
  196. status_map = {}
  197. for event in self.shippingevent_set.all():
  198. event_name = event.event_type.name
  199. event_quantity = event.line_quantities.get(line=self).quantity
  200. if event_name in status_map:
  201. status_map[event_name]['quantity'] += event_quantity
  202. else:
  203. status_map[event_name] = {'name': event_name, 'quantity': event_quantity}
  204. return list(status_map.values())
  205. class Meta:
  206. abstract = True
  207. verbose_name_plural = _("Order lines")
  208. def __unicode__(self):
  209. return u"Product '%s', quantity '%s'" % (self.product, self.quantity)
  210. class AbstractLineAttribute(models.Model):
  211. u"""An attribute of a line."""
  212. line = models.ForeignKey('order.Line', related_name='attributes')
  213. type = models.CharField(_("Type"), max_length=128)
  214. value = models.CharField(_("Value"), max_length=255)
  215. class Meta:
  216. abstract = True
  217. def __unicode__(self):
  218. return "%s = %s" % (self.type, self.value)
  219. class AbstractLinePrice(models.Model):
  220. u"""
  221. For tracking the prices paid for each unit within a line.
  222. This is necessary as offers can lead to units within a line
  223. having different prices. For example, one product may be sold at
  224. 50% off as it's part of an offer while the remainder are full price.
  225. """
  226. order = models.ForeignKey('order.Order', related_name='line_prices')
  227. line = models.ForeignKey('order.Line', related_name='prices')
  228. quantity = models.PositiveIntegerField(default=1)
  229. price_incl_tax = models.DecimalField(decimal_places=2, max_digits=12)
  230. price_excl_tax = models.DecimalField(decimal_places=2, max_digits=12)
  231. shipping_incl_tax = models.DecimalField(decimal_places=2, max_digits=12, default=0)
  232. shipping_excl_tax = models.DecimalField(decimal_places=2, max_digits=12, default=0)
  233. class Meta:
  234. abstract = True
  235. def __unicode__(self):
  236. return u"Line '%s' (quantity %d) price %s" % (self.line, self.quantity, self.price_incl_tax)
  237. class AbstractPaymentEvent(models.Model):
  238. u"""
  239. An event is something which happens to a line such as
  240. payment being taken for 2 items, or 1 item being dispatched.
  241. """
  242. order = models.ForeignKey('order.Order', related_name='payment_events')
  243. line = models.ForeignKey('order.Line', related_name='payment_events')
  244. quantity = models.PositiveIntegerField(default=1)
  245. event_type = models.ForeignKey('order.PaymentEventType')
  246. date = models.DateTimeField(auto_now_add=True)
  247. class Meta:
  248. abstract = True
  249. verbose_name_plural = _("Payment events")
  250. def __unicode__(self):
  251. return u"Order #%d, line %s: %d items %s" % (
  252. self.line.order.number, self.line.line_id, self.quantity, self.event_type)
  253. class AbstractPaymentEventType(models.Model):
  254. u"""Payment events are things like 'Paid', 'Failed', 'Refunded'"""
  255. # Name is the friendly description of an event
  256. name = models.CharField(max_length=255)
  257. code = models.SlugField(max_length=128)
  258. # The normal order in which these shipping events take place
  259. sequence_number = models.PositiveIntegerField(default=0)
  260. def save(self, *args, **kwargs):
  261. if not self.code:
  262. self.code = slugify(self.name)
  263. super(AbstractPaymentEventType, self).save(*args, **kwargs)
  264. class Meta:
  265. abstract = True
  266. verbose_name_plural = _("Payment event types")
  267. ordering = ('sequence_number',)
  268. def __unicode__(self):
  269. return self.name
  270. class AbstractShippingEvent(models.Model):
  271. u"""
  272. An event is something which happens to a group of lines such as
  273. 1 item being dispatched.
  274. """
  275. order = models.ForeignKey('order.Order', related_name='shipping_events')
  276. lines = models.ManyToManyField('order.Line', through='ShippingEventQuantity')
  277. event_type = models.ForeignKey('order.ShippingEventType')
  278. notes = models.TextField(_("Event notes"), blank=True, null=True,
  279. help_text="This could be the dispatch reference, or a tracking number")
  280. date = models.DateTimeField(auto_now_add=True)
  281. class Meta:
  282. abstract = True
  283. verbose_name_plural = _("Shipping events")
  284. ordering = ['-date']
  285. def __unicode__(self):
  286. return u"Order #%s, type %s" % (
  287. self.order.number, self.event_type)
  288. def num_affected_lines(self):
  289. return self.lines.count()
  290. class ShippingEventQuantity(models.Model):
  291. u"""A "through" model linking lines to shipping events"""
  292. event = models.ForeignKey('order.ShippingEvent', related_name='line_quantities')
  293. line = models.ForeignKey('order.Line')
  294. quantity = models.PositiveIntegerField()
  295. def _check_previous_events_are_complete(self):
  296. u"""Checks whether previous shipping events have passed"""
  297. previous_events = ShippingEventQuantity._default_manager.filter(line=self.line,
  298. event__event_type__sequence_number__lt=self.event.event_type.sequence_number)
  299. self.quantity = int(self.quantity)
  300. for event_quantities in previous_events:
  301. if event_quantities.quantity < self.quantity:
  302. raise ValueError("Invalid quantity (%d) for event type (a previous event has not been fully passed)" % self.quantity)
  303. def _check_new_quantity(self):
  304. quantity_row = ShippingEventQuantity._default_manager.filter(line=self.line,
  305. event__event_type=self.event.event_type).aggregate(Sum('quantity'))
  306. previous_quantity = quantity_row['quantity__sum']
  307. if previous_quantity == None:
  308. previous_quantity = 0
  309. if previous_quantity + self.quantity > self.line.quantity:
  310. raise ValueError("Invalid quantity (%d) for event type (total exceeds line total)" % self.quantity)
  311. def save(self, *args, **kwargs):
  312. # Default quantity to full quantity of line
  313. if not self.quantity:
  314. self.quantity = self.line.quantity
  315. self._check_previous_events_are_complete()
  316. self._check_new_quantity()
  317. super(ShippingEventQuantity, self).save(*args, **kwargs)
  318. def __unicode__(self):
  319. return "%s - quantity %d" % (self.line.product, self.quantity)
  320. class AbstractShippingEventType(models.Model):
  321. u"""Shipping events are things like 'OrderPlaced', 'Acknowledged', 'Dispatched', 'Refunded'"""
  322. # Name is the friendly description of an event
  323. name = models.CharField(max_length=255)
  324. # Code is used in forms
  325. code = models.SlugField(max_length=128)
  326. is_required = models.BooleanField(default=True, help_text="This event must be passed before the next shipping event can take place")
  327. # The normal order in which these shipping events take place
  328. sequence_number = models.PositiveIntegerField(default=0)
  329. def save(self, *args, **kwargs):
  330. if not self.code:
  331. self.code = slugify(self.name)
  332. super(AbstractShippingEventType, self).save(*args, **kwargs)
  333. class Meta:
  334. abstract = True
  335. verbose_name_plural = _("Shipping event types")
  336. ordering = ('sequence_number',)
  337. def __unicode__(self):
  338. return self.name
  339. class AbstractOrderDiscount(models.Model):
  340. order = models.ForeignKey('order.Order', related_name="discounts")
  341. offer = models.ForeignKey('offer.ConditionalOffer', null=True, on_delete=models.SET_NULL)
  342. voucher = models.ForeignKey('offer.Voucher', related_name="discount_vouchers", null=True, on_delete=models.SET_NULL)
  343. voucher_code = models.CharField(_("Code"), max_length=128, db_index=True)
  344. amount = models.DecimalField(decimal_places=2, max_digits=12, default=0)
  345. class Meta:
  346. abstract = True