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

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