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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939
  1. from itertools import chain
  2. from decimal import Decimal as D
  3. import hashlib
  4. from django.db import models
  5. from django.utils import timezone
  6. from oscar.core.compat import AUTH_USER_MODEL
  7. from oscar.core.utils 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 . import exceptions
  12. class AbstractOrder(models.Model):
  13. """
  14. The main order model
  15. """
  16. number = models.CharField(_("Order number"), max_length=128, db_index=True)
  17. # We track the site that each order is placed within
  18. site = models.ForeignKey('sites.Site', verbose_name=_("Site"))
  19. basket_id = models.PositiveIntegerField(_("Basket ID"), null=True, blank=True)
  20. # Orders can be anonymous so we don't always have a customer ID
  21. user = models.ForeignKey(AUTH_USER_MODEL, related_name='orders', null=True, blank=True, verbose_name=_("User"))
  22. # Billing address is not always required (eg paying by gift card)
  23. billing_address = models.ForeignKey('order.BillingAddress', null=True, blank=True,
  24. verbose_name=_("Billing Address"))
  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(
  32. _("Shipping charge (inc. tax)"), decimal_places=2, max_digits=12,
  33. default=0)
  34. shipping_excl_tax = models.DecimalField(
  35. _("Shipping charge (excl. tax)"), decimal_places=2, max_digits=12,
  36. default=0)
  37. # Not all lines are actually shipped (such as downloads), hence shipping address
  38. # is not mandatory.
  39. shipping_address = models.ForeignKey(
  40. 'order.ShippingAddress', null=True, blank=True,
  41. verbose_name=_("Shipping Address"))
  42. shipping_method = models.CharField(
  43. _("Shipping method"), max_length=128, null=True, blank=True)
  44. # Use this field to indicate that an order is on hold / awaiting payment
  45. status = models.CharField(_("Status"), max_length=100, null=True, blank=True)
  46. guest_email = models.EmailField(_("Guest email address"), null=True, blank=True)
  47. # Index added to this field for reporting
  48. date_placed = models.DateTimeField(auto_now_add=True, db_index=True)
  49. # Dict of available status changes
  50. pipeline = getattr(settings, 'OSCAR_ORDER_STATUS_PIPELINE', {})
  51. cascade = getattr(settings, 'OSCAR_ORDER_STATUS_CASCADE', {})
  52. @classmethod
  53. def all_statuses(cls):
  54. return cls.pipeline.keys()
  55. def available_statuses(self):
  56. return self.pipeline.get(self.status, ())
  57. def set_status(self, new_status):
  58. if new_status == self.status:
  59. return
  60. if new_status not in self.available_statuses():
  61. raise exceptions.InvalidOrderStatus(_("'%(new_status)s' is not a valid status for order %(number)s "
  62. "(current status: '%(status)s')") % {
  63. 'new_status': new_status,
  64. 'number': self.number,
  65. 'status': self.status})
  66. self.status = new_status
  67. if new_status in self.cascade:
  68. for line in self.lines.all():
  69. line.status = self.cascade[self.status]
  70. line.save()
  71. self.save()
  72. set_status.alters_data = True
  73. @property
  74. def is_anonymous(self):
  75. return self.user is None
  76. @property
  77. def basket_total_before_discounts_incl_tax(self):
  78. """
  79. Return basket total including tax but before discounts are applied
  80. """
  81. total = D('0.00')
  82. for line in self.lines.all():
  83. total += line.line_price_before_discounts_incl_tax
  84. return total
  85. @property
  86. def basket_total_before_discounts_excl_tax(self):
  87. """
  88. Return basket total excluding tax but before discounts are applied
  89. """
  90. total = D('0.00')
  91. for line in self.lines.all():
  92. total += line.line_price_before_discounts_excl_tax
  93. return total
  94. @property
  95. def basket_total_incl_tax(self):
  96. """
  97. Return basket total including tax
  98. """
  99. return self.total_incl_tax - self.shipping_incl_tax
  100. @property
  101. def basket_total_excl_tax(self):
  102. """
  103. Return basket total excluding tax
  104. """
  105. return self.total_excl_tax - self.shipping_excl_tax
  106. @property
  107. def total_before_discounts_incl_tax(self):
  108. return (self.basket_total_before_discounts_incl_tax +
  109. self.shipping_incl_tax)
  110. @property
  111. def total_before_discounts_excl_tax(self):
  112. return (self.basket_total_before_discounts_excl_tax +
  113. self.shipping_excl_tax)
  114. @property
  115. def total_discount_incl_tax(self):
  116. """
  117. The amount of discount this order received
  118. """
  119. discount = D('0.00')
  120. for line in self.lines.all():
  121. discount += line.discount_incl_tax
  122. return discount
  123. @property
  124. def total_discount_excl_tax(self):
  125. discount = D('0.00')
  126. for line in self.lines.all():
  127. discount += line.discount_excl_tax
  128. return discount
  129. @property
  130. def total_tax(self):
  131. return self.total_incl_tax - self.total_excl_tax
  132. @property
  133. def num_lines(self):
  134. return self.lines.count()
  135. @property
  136. def num_items(self):
  137. """
  138. Returns the number of items in this order.
  139. """
  140. num_items = 0
  141. for line in self.lines.all():
  142. num_items += line.quantity
  143. return num_items
  144. @property
  145. def shipping_status(self):
  146. events = self.shipping_events.all()
  147. if not len(events):
  148. return ''
  149. # Collect all events by event-type
  150. map = {}
  151. for event in events:
  152. event_name = event.event_type.name
  153. if event_name not in map:
  154. map[event_name] = []
  155. map[event_name] = list(chain(map[event_name], event.line_quantities.all()))
  156. # Determine last complete event
  157. status = _("In progress")
  158. for event_name, event_line_quantities in map.items():
  159. if self._is_event_complete(event_line_quantities):
  160. status = event_name
  161. return status
  162. @property
  163. def has_shipping_discounts(self):
  164. return len(self.shipping_discounts) > 0
  165. @property
  166. def shipping_before_discounts_incl_tax(self):
  167. # We can construct what shipping would have been before discounts by
  168. # adding the discounts back onto the final shipping charge.
  169. total = D('0.00')
  170. for discount in self.shipping_discounts:
  171. total += discount.amount
  172. return self.shipping_incl_tax + total
  173. def _is_event_complete(self, event_quantities):
  174. # Form map of line to quantity
  175. map = {}
  176. for event_quantity in event_quantities:
  177. line_id = event_quantity.line_id
  178. map.setdefault(line_id, 0)
  179. map[line_id] += event_quantity.quantity
  180. for line in self.lines.all():
  181. if map[line.id] != line.quantity:
  182. return False
  183. return True
  184. class Meta:
  185. abstract = True
  186. ordering = ['-date_placed',]
  187. permissions = (
  188. ("can_view", _("Can view orders (eg for reporting)")),
  189. )
  190. verbose_name = _("Order")
  191. verbose_name_plural = _("Orders")
  192. def __unicode__(self):
  193. return u"#%s" % (self.number,)
  194. def verification_hash(self):
  195. return hashlib.md5('%s%s' % (self.number, settings.SECRET_KEY)).hexdigest()
  196. @property
  197. def email(self):
  198. if not self.user:
  199. return self.guest_email
  200. return self.user.email
  201. @property
  202. def basket_discounts(self):
  203. # This includes both offer- and voucher- discounts. For orders we
  204. # don't need to treat them differently like we do for baskets.
  205. return self.discounts.filter(
  206. category=AbstractOrderDiscount.BASKET)
  207. @property
  208. def shipping_discounts(self):
  209. return self.discounts.filter(
  210. category=AbstractOrderDiscount.SHIPPING)
  211. @property
  212. def post_order_actions(self):
  213. return self.discounts.filter(
  214. category=AbstractOrderDiscount.DEFERRED)
  215. class AbstractOrderNote(models.Model):
  216. """
  217. A note against an order.
  218. This are often used for audit purposes too. IE, whenever an admin
  219. makes a change to an order, we create a note to record what happened.
  220. """
  221. order = models.ForeignKey('order.Order', related_name="notes", verbose_name=_("Order"))
  222. # These are sometimes programatically generated so don't need a
  223. # user everytime
  224. user = models.ForeignKey(AUTH_USER_MODEL, null=True, verbose_name=_("User"))
  225. # We allow notes to be classified although this isn't always needed
  226. INFO, WARNING, ERROR, SYSTEM = 'Info', 'Warning', 'Error', 'System'
  227. note_type = models.CharField(_("Note Type"), max_length=128, null=True)
  228. message = models.TextField(_("Message"))
  229. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  230. date_updated = models.DateTimeField(_("Date Updated"), auto_now=True)
  231. # Notes can only be edited for 5 minutes after being created
  232. editable_lifetime = 300
  233. class Meta:
  234. abstract = True
  235. verbose_name = _("Order Note")
  236. verbose_name_plural = _("Order Notes")
  237. def __unicode__(self):
  238. return u"'%s' (%s)" % (self.message[0:50], self.user)
  239. def is_editable(self):
  240. if self.note_type == self.SYSTEM:
  241. return False
  242. delta = timezone.now() - self.date_updated
  243. return delta.seconds < self.editable_lifetime
  244. class AbstractCommunicationEvent(models.Model):
  245. """
  246. An order-level event involving a communication to the customer, such
  247. as an confirmation email being sent.
  248. """
  249. order = models.ForeignKey(
  250. 'order.Order', related_name="communication_events",
  251. verbose_name=_("Order"))
  252. event_type = models.ForeignKey(
  253. 'customer.CommunicationEventType', verbose_name=_("Event Type"))
  254. date_created = models.DateTimeField(_("Date"), auto_now_add=True)
  255. class Meta:
  256. abstract = True
  257. verbose_name = _("Communication Event")
  258. verbose_name_plural = _("Communication Events")
  259. ordering = ['-date_created']
  260. def __unicode__(self):
  261. return _("'%(type)s' event for order #%(number)s") % {'type': self.event_type.name, 'number': self.order.number}
  262. # LINES
  263. class AbstractLine(models.Model):
  264. """
  265. A order line (basically a product and a quantity)
  266. Not using a line model as it's difficult to capture and payment
  267. information when it splits across a line.
  268. """
  269. order = models.ForeignKey(
  270. 'order.Order', related_name='lines', verbose_name=_("Order"))
  271. # We store the partner, their SKU and the title for cases where the product
  272. # has been deleted from the catalogue. We also store the partner name in
  273. # case the partner gets deleted at a later date.
  274. partner = models.ForeignKey(
  275. 'partner.Partner', related_name='order_lines', blank=True, null=True,
  276. on_delete=models.SET_NULL, verbose_name=_("Partner"))
  277. partner_name = models.CharField(_("Partner name"), max_length=128)
  278. partner_sku = models.CharField(_("Partner SKU"), max_length=128)
  279. title = models.CharField(_("Title"), max_length=255)
  280. upc = models.CharField(_("UPC"), max_length=128, blank=True, null=True)
  281. # We don't want any hard links between orders and the products table so we
  282. # allow this link to be NULLable.
  283. product = models.ForeignKey(
  284. 'catalogue.Product', on_delete=models.SET_NULL, blank=True, null=True,
  285. verbose_name=_("Product"))
  286. quantity = models.PositiveIntegerField(_("Quantity"), default=1)
  287. # Price information (these fields are actually redundant as the information
  288. # can be calculated from the LinePrice models
  289. line_price_incl_tax = models.DecimalField(
  290. _("Price (inc. tax)"), decimal_places=2, max_digits=12)
  291. line_price_excl_tax = models.DecimalField(
  292. _("Price (excl. tax)"), decimal_places=2, max_digits=12)
  293. # Price information before discounts are applied
  294. line_price_before_discounts_incl_tax = models.DecimalField(
  295. _("Price before discounts (inc. tax)"),
  296. decimal_places=2, max_digits=12)
  297. line_price_before_discounts_excl_tax = models.DecimalField(
  298. _("Price before discounts (excl. tax)"),
  299. decimal_places=2, max_digits=12)
  300. # REPORTING FIELDS
  301. # Cost price (the price charged by the fulfilment partner for this
  302. # product).
  303. unit_cost_price = models.DecimalField(
  304. _("Unit Cost Price"), decimal_places=2, max_digits=12, blank=True,
  305. null=True)
  306. # Normal site price for item (without discounts)
  307. unit_price_incl_tax = models.DecimalField(
  308. _("Unit Price (inc. tax)"), decimal_places=2, max_digits=12,
  309. blank=True, null=True)
  310. unit_price_excl_tax = models.DecimalField(
  311. _("Unit Price (excl. tax)"), decimal_places=2, max_digits=12,
  312. blank=True, null=True)
  313. # Retail price at time of purchase
  314. unit_retail_price = models.DecimalField(
  315. _("Unit Retail Price"), decimal_places=2, max_digits=12,
  316. blank=True, null=True)
  317. # Partner information
  318. partner_line_reference = models.CharField(
  319. _("Partner reference"), max_length=128, blank=True, null=True,
  320. help_text=_("This is the item number that the partner uses "
  321. "within their system"))
  322. partner_line_notes = models.TextField(
  323. _("Partner Notes"), blank=True, null=True)
  324. # Partners often want to assign some status to each line to help with their
  325. # own business processes.
  326. status = models.CharField(_("Status"), max_length=255,
  327. null=True, blank=True)
  328. # Estimated dispatch date - should be set at order time
  329. est_dispatch_date = models.DateField(
  330. _("Estimated Dispatch Date"), blank=True, null=True)
  331. pipeline = getattr(settings, 'OSCAR_LINE_STATUS_PIPELINE', {})
  332. class Meta:
  333. abstract = True
  334. verbose_name = _("Order Line")
  335. verbose_name_plural = _("Order Lines")
  336. def __unicode__(self):
  337. if self.product:
  338. title = self.product.title
  339. else:
  340. title = _('<missing product>')
  341. return _("Product '%(name)s', quantity '%(qty)s'") % {
  342. 'name': title, 'qty': self.quantity}
  343. @classmethod
  344. def all_statuses(cls):
  345. return cls.pipeline.keys()
  346. def available_statuses(self):
  347. return self.pipeline.get(self.status, ())
  348. def set_status(self, new_status):
  349. if new_status == self.status:
  350. return
  351. if new_status not in self.available_statuses():
  352. raise exceptions.InvalidLineStatus(_("'%(new_status)s' is not a valid status (current status: '%(status)s')") % {
  353. 'new_status': new_status, 'status': self.status})
  354. self.status = new_status
  355. self.save()
  356. set_status.alters_data = True
  357. @property
  358. def category(self):
  359. """
  360. Used by Google analytics tracking
  361. """
  362. return None
  363. @property
  364. def description(self):
  365. """
  366. Returns a description of this line including details of any
  367. line attributes.
  368. """
  369. desc = self.title
  370. ops = []
  371. for attribute in self.attributes.all():
  372. ops.append("%s = '%s'" % (attribute.type, attribute.value))
  373. if ops:
  374. desc = "%s (%s)" % (desc, ", ".join(ops))
  375. return desc
  376. @property
  377. def discount_incl_tax(self):
  378. return self.line_price_before_discounts_incl_tax - self.line_price_incl_tax
  379. @property
  380. def discount_excl_tax(self):
  381. return self.line_price_before_discounts_excl_tax - self.line_price_excl_tax
  382. @property
  383. def line_price_tax(self):
  384. return self.line_price_incl_tax - self.line_price_excl_tax
  385. @property
  386. def unit_price_tax(self):
  387. return self.unit_price_incl_tax - self.unit_price_excl_tax
  388. # Shipping status helpers
  389. @property
  390. def shipping_status(self):
  391. """
  392. Returns a string summary of the shipping status of this line
  393. """
  394. status_map = self.shipping_event_breakdown
  395. if not status_map:
  396. return ''
  397. events = []
  398. last_complete_event_name = None
  399. for event_dict in status_map.values():
  400. if event_dict['quantity'] == self.quantity:
  401. events.append(event_dict['name'])
  402. last_complete_event_name = event_dict['name']
  403. else:
  404. events.append("%s (%d/%d items)" % (
  405. event_dict['name'], event_dict['quantity'],
  406. self.quantity))
  407. if last_complete_event_name == status_map.values()[-1]['name']:
  408. return last_complete_event_name
  409. return ', '.join(events)
  410. def is_shipping_event_permitted(self, event_type, quantity):
  411. """
  412. Test whether a shipping event with the given quantity is permitted
  413. This method should normally be overriden to ensure that the
  414. prerequisite shipping events have been passed for this line.
  415. """
  416. # Note, this calculation is simplistic - normally, you will also need
  417. # to check if previous shipping events have occurred. Eg, you can't
  418. # return lines until they have been shipped.
  419. current_qty = self.shipping_event_quantity(event_type)
  420. return (current_qty + quantity) <= self.quantity
  421. def shipping_event_quantity(self, event_type):
  422. """
  423. Return the quantity of this line that has been involved in a shipping
  424. event of the passed type.
  425. """
  426. result = self.shipping_event_quantities.filter(
  427. event__event_type=event_type).aggregate(
  428. Sum('quantity'))
  429. if result['quantity__sum'] is None:
  430. return 0
  431. else:
  432. return result['quantity__sum']
  433. def has_shipping_event_occurred(self, event_type, quantity=None):
  434. """
  435. Test whether this line has passed a given shipping event
  436. """
  437. if not quantity:
  438. quantity = self.quantity
  439. return self.shipping_event_quantity(event_type) == quantity
  440. @property
  441. def shipping_event_breakdown(self):
  442. """
  443. Returns a dict of shipping events that this line has been through
  444. """
  445. status_map = {}
  446. for event in self.shipping_events.all():
  447. event_type = event.event_type
  448. event_name = event_type.name
  449. event_quantity = event.line_quantities.get(line=self).quantity
  450. if event_name in status_map:
  451. status_map[event_name]['quantity'] += event_quantity
  452. else:
  453. status_map[event_name] = {'event_type': event_type,
  454. 'name': event_name,
  455. 'quantity': event_quantity}
  456. return status_map
  457. # Payment event helpers
  458. def is_payment_event_permitted(self, event_type, quantity):
  459. """
  460. Test whether a payment event with the given quantity is permitted
  461. """
  462. current_qty = self.payment_event_quantity(event_type)
  463. return (current_qty + quantity) <= self.quantity
  464. def payment_event_quantity(self, event_type):
  465. """
  466. Return the quantity of this line that has been involved in a payment
  467. event of the passed type.
  468. """
  469. result = self.payment_event_quantities.filter(
  470. event__event_type=event_type).aggregate(
  471. Sum('quantity'))
  472. if result['quantity__sum'] is None:
  473. return 0
  474. else:
  475. return result['quantity__sum']
  476. @property
  477. def is_product_deleted(self):
  478. return self.product is None
  479. def is_available_to_reorder(self, basket, user):
  480. """
  481. Test if this line can be re-ordered by the passed user, using the
  482. passed basket.
  483. """
  484. if not self.product:
  485. return False, (_("'%(title)s' is no longer available") %
  486. {'title': self.title})
  487. Line = models.get_model('basket', 'Line')
  488. try:
  489. basket_line = basket.lines.get(product=self.product)
  490. except Line.DoesNotExist:
  491. desired_qty = self.quantity
  492. else:
  493. desired_qty = basket_line.quantity + self.quantity
  494. is_available, reason = self.product.is_purchase_permitted(
  495. user=user,
  496. quantity=desired_qty)
  497. if not is_available:
  498. return False, reason
  499. return True, None
  500. class AbstractLineAttribute(models.Model):
  501. """
  502. An attribute of a line
  503. """
  504. line = models.ForeignKey(
  505. 'order.Line', related_name='attributes',
  506. verbose_name=_("Line"))
  507. option = models.ForeignKey(
  508. 'catalogue.Option', null=True, on_delete=models.SET_NULL,
  509. related_name="line_attributes", verbose_name=_("Option"))
  510. type = models.CharField(_("Type"), max_length=128)
  511. value = models.CharField(_("Value"), max_length=255)
  512. class Meta:
  513. abstract = True
  514. verbose_name = _("Line Attribute")
  515. verbose_name_plural = _("Line Attributes")
  516. def __unicode__(self):
  517. return "%s = %s" % (self.type, self.value)
  518. class AbstractLinePrice(models.Model):
  519. """
  520. For tracking the prices paid for each unit within a line.
  521. This is necessary as offers can lead to units within a line
  522. having different prices. For example, one product may be sold at
  523. 50% off as it's part of an offer while the remainder are full price.
  524. """
  525. order = models.ForeignKey(
  526. 'order.Order', related_name='line_prices', verbose_name=_("Option"))
  527. line = models.ForeignKey(
  528. 'order.Line', related_name='prices', verbose_name=_("Line"))
  529. quantity = models.PositiveIntegerField(_("Quantity"), default=1)
  530. price_incl_tax = models.DecimalField(
  531. _("Price (inc. tax)"), decimal_places=2, max_digits=12)
  532. price_excl_tax = models.DecimalField(
  533. _("Price (excl. tax)"), decimal_places=2, max_digits=12)
  534. shipping_incl_tax = models.DecimalField(
  535. _("Shiping (inc. tax)"), decimal_places=2, max_digits=12, default=0)
  536. shipping_excl_tax = models.DecimalField(
  537. _("Shipping (excl. tax)"), decimal_places=2, max_digits=12, default=0)
  538. class Meta:
  539. abstract = True
  540. ordering = ('id',)
  541. verbose_name = _("Line Price")
  542. verbose_name_plural = _("Line Prices")
  543. def __unicode__(self):
  544. return _("Line '%(number)s' (quantity %(qty)d) price %(price)s") % {
  545. 'number': self.line,
  546. 'qty': self.quantity,
  547. 'price': self.price_incl_tax}
  548. # PAYMENT EVENTS
  549. class AbstractPaymentEventType(models.Model):
  550. """
  551. Payment event types are things like 'Paid', 'Failed', 'Refunded'.
  552. These are effectively the transaction types.
  553. """
  554. name = models.CharField(_("Name"), max_length=128, unique=True)
  555. code = models.SlugField(_("Code"), max_length=128, unique=True)
  556. def save(self, *args, **kwargs):
  557. if not self.code:
  558. self.code = slugify(self.name)
  559. super(AbstractPaymentEventType, self).save(*args, **kwargs)
  560. class Meta:
  561. abstract = True
  562. verbose_name = _("Payment Event Type")
  563. verbose_name_plural = _("Payment Event Types")
  564. ordering = ('name', )
  565. def __unicode__(self):
  566. return self.name
  567. class AbstractPaymentEvent(models.Model):
  568. """
  569. A payment event for an order
  570. For example:
  571. * All lines have been paid for
  572. * 2 lines have been refunded
  573. """
  574. order = models.ForeignKey(
  575. 'order.Order', related_name='payment_events',
  576. verbose_name=_("Order"))
  577. amount = models.DecimalField(
  578. _("Amount"), decimal_places=2, max_digits=12)
  579. # The reference should refer to the transaction ID of the payment gateway
  580. # that was used for this event.
  581. reference = models.CharField(
  582. _("Reference"), max_length=128, blank=True)
  583. lines = models.ManyToManyField(
  584. 'order.Line', through='PaymentEventQuantity',
  585. verbose_name=_("Lines"))
  586. event_type = models.ForeignKey(
  587. 'order.PaymentEventType', verbose_name=_("Event Type"))
  588. # Allow payment events to be linked to shipping events. Often a shipping
  589. # event will trigger a payment event and so we can use this FK to capture
  590. # the relationship.
  591. shipping_event = models.ForeignKey(
  592. 'order.ShippingEvent', related_name='payment_events',
  593. null=True)
  594. date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
  595. class Meta:
  596. abstract = True
  597. verbose_name = _("Payment Event")
  598. verbose_name_plural = _("Payment Events")
  599. ordering = ['-date_created']
  600. def __unicode__(self):
  601. return _("Payment event for order %s") % self.order
  602. def num_affected_lines(self):
  603. return self.lines.all().count()
  604. class PaymentEventQuantity(models.Model):
  605. """
  606. A "through" model linking lines to payment events
  607. """
  608. event = models.ForeignKey(
  609. 'order.PaymentEvent', related_name='line_quantities',
  610. verbose_name=_("Event"))
  611. line = models.ForeignKey(
  612. 'order.Line', related_name="payment_event_quantities",
  613. verbose_name=_("Line"))
  614. quantity = models.PositiveIntegerField(_("Quantity"))
  615. class Meta:
  616. verbose_name = _("Payment Event Quantity")
  617. verbose_name_plural = _("Payment Event Quantities")
  618. # SHIPPING EVENTS
  619. class AbstractShippingEvent(models.Model):
  620. """
  621. An event is something which happens to a group of lines such as
  622. 1 item being dispatched.
  623. """
  624. order = models.ForeignKey(
  625. 'order.Order', related_name='shipping_events', verbose_name=_("Order"))
  626. lines = models.ManyToManyField(
  627. 'order.Line', related_name='shipping_events',
  628. through='ShippingEventQuantity', verbose_name=_("Lines"))
  629. event_type = models.ForeignKey(
  630. 'order.ShippingEventType', verbose_name=_("Event Type"))
  631. notes = models.TextField(
  632. _("Event notes"), blank=True, null=True,
  633. help_text=_("This could be the dispatch reference, or a "
  634. "tracking number"))
  635. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  636. class Meta:
  637. abstract = True
  638. verbose_name = _("Shipping Event")
  639. verbose_name_plural = _("Shipping Events")
  640. ordering = ['-date_created']
  641. def __unicode__(self):
  642. return _("Order #%(number)s, type %(type)s") % {
  643. 'number': self.order.number,
  644. 'type': self.event_type}
  645. def num_affected_lines(self):
  646. return self.lines.count()
  647. class ShippingEventQuantity(models.Model):
  648. """
  649. A "through" model linking lines to shipping events.
  650. This exists to track the quantity of a line that is involved in a
  651. particular shipping event.
  652. """
  653. event = models.ForeignKey(
  654. 'order.ShippingEvent', related_name='line_quantities',
  655. verbose_name=_("Event"))
  656. line = models.ForeignKey(
  657. 'order.Line', related_name="shipping_event_quantities",
  658. verbose_name=_("Line"))
  659. quantity = models.PositiveIntegerField(_("Quantity"))
  660. class Meta:
  661. verbose_name = _("Shipping Event Quantity")
  662. verbose_name_plural = _("Shipping Event Quantities")
  663. def save(self, *args, **kwargs):
  664. # Default quantity to full quantity of line
  665. if not self.quantity:
  666. self.quantity = self.line.quantity
  667. # Ensure we don't violate quantities constraint
  668. if not self.line.is_shipping_event_permitted(
  669. self.event.event_type, self.quantity):
  670. raise exceptions.InvalidShippingEvent
  671. super(ShippingEventQuantity, self).save(*args, **kwargs)
  672. def __unicode__(self):
  673. return _("%(product)s - quantity %(qty)d") % {
  674. 'product': self.line.product,
  675. 'qty': self.quantity}
  676. class AbstractShippingEventType(models.Model):
  677. """
  678. A type of shipping/fulfillment event
  679. Eg: 'Shipped', 'Cancelled', 'Returned'
  680. """
  681. # Name is the friendly description of an event
  682. name = models.CharField(_("Name"), max_length=255, unique=True)
  683. # Code is used in forms
  684. code = models.SlugField(_("Code"), max_length=128, unique=True)
  685. def save(self, *args, **kwargs):
  686. if not self.code:
  687. self.code = slugify(self.name)
  688. super(AbstractShippingEventType, self).save(*args, **kwargs)
  689. class Meta:
  690. abstract = True
  691. verbose_name = _("Shipping Event Type")
  692. verbose_name_plural = _("Shipping Event Types")
  693. ordering = ('name', )
  694. def __unicode__(self):
  695. return self.name
  696. # DISCOUNTS
  697. class AbstractOrderDiscount(models.Model):
  698. """
  699. A discount against an order.
  700. Normally only used for display purposes so an order can be listed with
  701. discounts displayed separately even though in reality, the discounts are
  702. applied at the line level.
  703. This has evolved to be a slightly misleading class name as this really
  704. track benefit applications which aren't necessarily discounts.
  705. """
  706. order = models.ForeignKey(
  707. 'order.Order', related_name="discounts", verbose_name=_("Order"))
  708. # We need to distinguish between basket discounts, shipping discounts and
  709. # 'deferred' discounts.
  710. BASKET, SHIPPING, DEFERRED = "Basket", "Shipping", "Deferred"
  711. CATEGORY_CHOICES = (
  712. (BASKET, _(BASKET)),
  713. (SHIPPING, _(SHIPPING)),
  714. (DEFERRED, _(DEFERRED)),
  715. )
  716. category = models.CharField(
  717. _("Discount category"), default=BASKET, max_length=64,
  718. choices=CATEGORY_CHOICES)
  719. offer_id = models.PositiveIntegerField(
  720. _("Offer ID"), blank=True, null=True)
  721. offer_name = models.CharField(
  722. _("Offer name"), max_length=128, db_index=True, null=True)
  723. voucher_id = models.PositiveIntegerField(
  724. _("Voucher ID"), blank=True, null=True)
  725. voucher_code = models.CharField(
  726. _("Code"), max_length=128, db_index=True, null=True)
  727. frequency = models.PositiveIntegerField(_("Frequency"), null=True)
  728. amount = models.DecimalField(
  729. _("Amount"), decimal_places=2, max_digits=12, default=0)
  730. # Post-order offer applications can return a message to indicate what
  731. # action was taken after the order was placed.
  732. message = models.TextField(blank=True, null=True)
  733. @property
  734. def is_basket_discount(self):
  735. return self.category == self.BASKET
  736. @property
  737. def is_shipping_discount(self):
  738. return self.category == self.SHIPPING
  739. @property
  740. def is_post_order_action(self):
  741. return self.category == self.DEFERRED
  742. class Meta:
  743. abstract = True
  744. verbose_name = _("Order Discount")
  745. verbose_name_plural = _("Order Discounts")
  746. def save(self, **kwargs):
  747. if self.offer_id and not self.offer_name:
  748. offer = self.offer
  749. if offer:
  750. self.offer_name = offer.name
  751. if self.voucher_id and not self.voucher_code:
  752. voucher = self.voucher
  753. if voucher:
  754. self.voucher_code = voucher.code
  755. super(AbstractOrderDiscount, self).save(**kwargs)
  756. def __unicode__(self):
  757. return _("Discount of %(amount)r from order %(order)s") % {
  758. 'amount': self.amount, 'order': self.order}
  759. @property
  760. def offer(self):
  761. Offer = models.get_model('offer', 'ConditionalOffer')
  762. try:
  763. return Offer.objects.get(id=self.offer_id)
  764. except Offer.DoesNotExist:
  765. return None
  766. @property
  767. def voucher(self):
  768. Voucher = models.get_model('voucher', 'Voucher')
  769. try:
  770. return Voucher.objects.get(id=self.voucher_id)
  771. except Voucher.DoesNotExist:
  772. return None
  773. def description(self):
  774. if self.voucher_code:
  775. return self.voucher_code
  776. return self.offer_name or u""