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

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