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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. from decimal import Decimal
  2. import zlib
  3. from django.db import models
  4. from django.db.models import query
  5. from django.conf import settings
  6. from django.utils.timezone import now
  7. from django.utils.translation import ugettext as _
  8. from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
  9. from oscar.apps.basket.managers import OpenBasketManager, SavedBasketManager
  10. from oscar.templatetags.currency_filters import currency
  11. # Basket statuses
  12. # - Frozen is for when a basket is in the process of being submitted
  13. # and we need to prevent any changes to it.
  14. OPEN, MERGED, SAVED, FROZEN, SUBMITTED = (
  15. "Open", "Merged", "Saved", "Frozen", "Submitted")
  16. class AbstractBasket(models.Model):
  17. """
  18. Basket object
  19. """
  20. # Baskets can be anonymously owned (which are merged if the user signs in)
  21. owner = models.ForeignKey('auth.User', related_name='baskets',
  22. null=True, verbose_name=_("Owner"))
  23. STATUS_CHOICES = (
  24. (OPEN, _("Open - currently active")),
  25. (MERGED, _("Merged - superceded by another basket")),
  26. (SAVED, _("Saved - for items to be purchased later")),
  27. (FROZEN, _("Frozen - the basket cannot be modified")),
  28. (SUBMITTED, _("Submitted - has been ordered at the checkout")),
  29. )
  30. status = models.CharField(_("Status"), max_length=128, default=OPEN,
  31. choices=STATUS_CHOICES)
  32. vouchers = models.ManyToManyField('voucher.Voucher', null=True,
  33. verbose_name=_("Vouchers"))
  34. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  35. date_merged = models.DateTimeField(_("Date Merged"), null=True, blank=True)
  36. date_submitted = models.DateTimeField(_("Date Submitted"), null=True,
  37. blank=True)
  38. class Meta:
  39. abstract = True
  40. verbose_name = _('Basket')
  41. verbose_name_plural = _('Baskets')
  42. objects = models.Manager()
  43. open = OpenBasketManager()
  44. saved = SavedBasketManager()
  45. _lines = None
  46. def __init__(self, *args, **kwargs):
  47. super(AbstractBasket, self).__init__(*args, **kwargs)
  48. self._lines = None # Cached queryset of lines
  49. self.discounts = None # Dictionary of discounts
  50. self.exempt_from_tax = False
  51. def __unicode__(self):
  52. return _(
  53. u"%(status)s basket (owner: %(owner)s, lines: %(num_lines)d)") % {
  54. 'status': self.status,
  55. 'owner': self.owner,
  56. 'num_lines': self.num_lines}
  57. def all_lines(self):
  58. """
  59. Return a cached set of basket lines.
  60. This is important for offers as they alter the line models and you
  61. don't want to reload them from the DB.
  62. """
  63. if self.id is None:
  64. return query.EmptyQuerySet(model=self.__class__)
  65. if self._lines is None:
  66. self._lines = self.lines.all()
  67. return self._lines
  68. def is_quantity_allowed(self, qty):
  69. basket_threshold = settings.OSCAR_MAX_BASKET_QUANTITY_THRESHOLD
  70. if basket_threshold:
  71. total_basket_quantity = self.num_items
  72. max_allowed = basket_threshold - total_basket_quantity
  73. if qty > max_allowed:
  74. return False, _(
  75. "Due to technical limitations we are not able "
  76. "to ship more than %(threshold)d items in one order."
  77. " Your basket currently has %(basket)d items.") % {
  78. 'threshold': basket_threshold,
  79. 'basket': total_basket_quantity,
  80. }
  81. return True, None
  82. # ============
  83. # Manipulation
  84. # ============
  85. def flush(self):
  86. """Remove all lines from basket."""
  87. if self.status == FROZEN:
  88. raise PermissionDenied("A frozen basket cannot be flushed")
  89. self.lines.all().delete()
  90. self._lines = None
  91. def add_product(self, product, quantity=1, options=None):
  92. """
  93. Add a product to the basket
  94. The 'options' list should contains dicts with keys 'option' and 'value'
  95. which link the relevant product.Option model and string value
  96. respectively.
  97. """
  98. if options is None:
  99. options = []
  100. if not self.id:
  101. self.save()
  102. # Line reference is used to distinguish between variations of the same
  103. # product (eg T-shirts with different personalisations)
  104. line_ref = self._create_line_reference(product, options)
  105. # Determine price to store (if one exists). It is only stored for
  106. # audit and sometimes caching.
  107. price_excl_tax, price_incl_tax = None, None
  108. if product.has_stockrecord:
  109. stockrecord = product.stockrecord
  110. if stockrecord:
  111. price_excl_tax = getattr(stockrecord, 'price_excl_tax', None)
  112. price_incl_tax = getattr(stockrecord, 'price_incl_tax', None)
  113. line, created = self.lines.get_or_create(
  114. line_reference=line_ref,
  115. product=product,
  116. defaults={'quantity': quantity,
  117. 'price_excl_tax': price_excl_tax,
  118. 'price_incl_tax': price_incl_tax})
  119. if created:
  120. for option_dict in options:
  121. line.attributes.create(option=option_dict['option'],
  122. value=option_dict['value'])
  123. else:
  124. line.quantity += quantity
  125. line.save()
  126. self._lines = None
  127. def get_discounts(self):
  128. if self.discounts is None:
  129. self.discounts = []
  130. return self.discounts
  131. def set_discounts(self, discounts):
  132. """
  133. Sets the discounts that apply to this basket.
  134. This should be a list of dictionaries
  135. """
  136. self.discounts = discounts
  137. def remove_discounts(self):
  138. """
  139. Remove any discounts so they get recalculated
  140. """
  141. self.discounts = []
  142. self._lines = None
  143. def merge_line(self, line, add_quantities=True):
  144. """
  145. For transferring a line from another basket to this one.
  146. This is used with the "Saved" basket functionality.
  147. """
  148. try:
  149. existing_line = self.lines.get(line_reference=line.line_reference)
  150. except ObjectDoesNotExist:
  151. # Line does not already exist - reassign its basket
  152. line.basket = self
  153. line.save()
  154. else:
  155. # Line already exists - assume the max quantity is correct and
  156. # delete the old
  157. if add_quantities:
  158. existing_line.quantity += line.quantity
  159. else:
  160. existing_line.quantity = max(existing_line.quantity,
  161. line.quantity)
  162. existing_line.save()
  163. line.delete()
  164. def merge(self, basket, add_quantities=True):
  165. """
  166. Merges another basket with this one.
  167. :basket: The basket to merge into this one
  168. :add_quantities: Whether to add line quantities when they are merged.
  169. """
  170. for line_to_merge in basket.all_lines():
  171. self.merge_line(line_to_merge, add_quantities)
  172. basket.status = MERGED
  173. basket.date_merged = now()
  174. basket.save()
  175. self._lines = None
  176. def freeze(self):
  177. """
  178. Freezes the basket so it cannot be modified.
  179. """
  180. self.status = FROZEN
  181. self.save()
  182. def thaw(self):
  183. """
  184. Unfreezes a basket so it can be modified again
  185. """
  186. self.status = OPEN
  187. self.save()
  188. def set_as_submitted(self):
  189. """Mark this basket as submitted."""
  190. self.status = SUBMITTED
  191. self.date_submitted = now()
  192. self.save()
  193. def set_as_tax_exempt(self):
  194. self.exempt_from_tax = True
  195. for line in self.all_lines():
  196. line.set_as_tax_exempt()
  197. def is_shipping_required(self):
  198. """
  199. Test whether the basket contains physical products that require
  200. shipping.
  201. """
  202. for line in self.all_lines():
  203. if line.product.is_shipping_required:
  204. return True
  205. return False
  206. # =======
  207. # Helpers
  208. # =======
  209. def _create_line_reference(self, item, options):
  210. """
  211. Returns a reference string for a line based on the item
  212. and its options.
  213. """
  214. if not options:
  215. return item.id
  216. return "%d_%s" % (item.id, zlib.crc32(str(options)))
  217. def _get_total(self, property):
  218. """
  219. For executing a named method on each line of the basket
  220. and returning the total.
  221. """
  222. total = Decimal('0.00')
  223. for line in self.all_lines():
  224. try:
  225. total += getattr(line, property)
  226. except ObjectDoesNotExist:
  227. # Handle situation where the product may have been deleted
  228. pass
  229. return total
  230. # ==========
  231. # Properties
  232. # ==========
  233. @property
  234. def is_empty(self):
  235. """
  236. Test if this basket is empty
  237. """
  238. return self.id is None or self.num_lines == 0
  239. @property
  240. def total_excl_tax(self):
  241. """Return total line price excluding tax"""
  242. return self._get_total('line_price_excl_tax_and_discounts')
  243. @property
  244. def total_tax(self):
  245. """Return total tax for a line"""
  246. return self._get_total('line_tax')
  247. @property
  248. def total_incl_tax(self):
  249. """
  250. Return total price inclusive of tax and discounts
  251. """
  252. return self._get_total('line_price_incl_tax_and_discounts')
  253. @property
  254. def total_incl_tax_excl_discounts(self):
  255. """
  256. Return total price inclusive of tax but exclusive discounts
  257. """
  258. return self._get_total('line_price_incl_tax')
  259. @property
  260. def total_discount(self):
  261. return self._get_total('discount_value')
  262. @property
  263. def offer_discounts(self):
  264. """
  265. Return discounts from non-voucher sources.
  266. """
  267. offer_discounts = []
  268. for discount in self.get_discounts():
  269. if not discount['voucher']:
  270. offer_discounts.append(discount)
  271. return offer_discounts
  272. @property
  273. def voucher_discounts(self):
  274. """
  275. Return discounts from vouchers
  276. """
  277. voucher_discounts = []
  278. for discount in self.get_discounts():
  279. if discount['voucher']:
  280. voucher_discounts.append(discount)
  281. return voucher_discounts
  282. @property
  283. def grouped_voucher_discounts(self):
  284. """
  285. Return discounts from vouchers but grouped so that a voucher which
  286. links to multiple offers is aggregated into one object.
  287. """
  288. voucher_discounts = {}
  289. for discount in self.voucher_discounts:
  290. voucher = discount['voucher']
  291. if voucher.code not in voucher_discounts:
  292. voucher_discounts[voucher.code] = {
  293. 'voucher': voucher,
  294. 'discount': discount['discount'],
  295. }
  296. else:
  297. voucher_discounts[voucher.code] += discount.discount
  298. return voucher_discounts.values()
  299. @property
  300. def total_excl_tax_excl_discounts(self):
  301. """
  302. Return total price excluding tax and discounts
  303. """
  304. return self._get_total('line_price_excl_tax')
  305. @property
  306. def num_lines(self):
  307. """Return number of lines"""
  308. return len(self.all_lines())
  309. @property
  310. def num_items(self):
  311. """Return number of items"""
  312. return reduce(
  313. lambda num, line: num + line.quantity, self.all_lines(), 0)
  314. @property
  315. def num_items_without_discount(self):
  316. num = 0
  317. for line in self.all_lines():
  318. num += line.quantity_without_discount
  319. return num
  320. @property
  321. def num_items_with_discount(self):
  322. num = 0
  323. for line in self.all_lines():
  324. num += line.quantity_with_discount
  325. return num
  326. @property
  327. def time_before_submit(self):
  328. if not self.date_submitted:
  329. return None
  330. return self.date_submitted - self.date_created
  331. @property
  332. def time_since_creation(self, test_datetime=None):
  333. if not test_datetime:
  334. test_datetime = now()
  335. return test_datetime - self.date_created
  336. @property
  337. def contains_a_voucher(self):
  338. return self.vouchers.all().count() > 0
  339. def contains_voucher(self, code):
  340. """
  341. Test whether the basket contains a voucher with a given code
  342. """
  343. try:
  344. self.vouchers.get(code=code)
  345. except ObjectDoesNotExist:
  346. return False
  347. else:
  348. return True
  349. class AbstractLine(models.Model):
  350. """
  351. A line of a basket (product and a quantity)
  352. """
  353. basket = models.ForeignKey('basket.Basket', related_name='lines',
  354. verbose_name=_("Basket"))
  355. # This is to determine which products belong to the same line
  356. # We can't just use product.id as you can have customised products
  357. # which should be treated as separate lines. Set as a
  358. # SlugField as it is included in the path for certain views.
  359. line_reference = models.SlugField(_("Line Reference"), max_length=128,
  360. db_index=True)
  361. product = models.ForeignKey(
  362. 'catalogue.Product', related_name='basket_lines',
  363. verbose_name=_("Product"))
  364. quantity = models.PositiveIntegerField(_('Quantity'), default=1)
  365. # We store the unit price incl tax of the product when it is first added to
  366. # the basket. This allows us to tell if a product has changed price since
  367. # a person first added it to their basket.
  368. price_excl_tax = models.DecimalField(
  369. _('Price excl. Tax'), decimal_places=2, max_digits=12,
  370. null=True)
  371. price_incl_tax = models.DecimalField(
  372. _('Price incl. Tax'), decimal_places=2, max_digits=12, null=True)
  373. # Track date of first addition
  374. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  375. # Instance variables used to persist discount information
  376. _discount = Decimal('0.00')
  377. _affected_quantity = 0
  378. _charge_tax = True
  379. class Meta:
  380. abstract = True
  381. unique_together = ("basket", "line_reference")
  382. verbose_name = _('Basket line')
  383. verbose_name_plural = _('Basket lines')
  384. def __unicode__(self):
  385. return _(
  386. u"%(basket)s, Product '%(product)s', quantity %(quantity)d") % {
  387. 'basket': self.basket,
  388. 'product': self.product,
  389. 'quantity': self.quantity}
  390. def save(self, *args, **kwargs):
  391. """Saves a line or deletes if it's quanity is 0"""
  392. if self.basket.status not in (OPEN, SAVED):
  393. raise PermissionDenied(
  394. _("You cannot modify a %s basket") % (
  395. self.basket.status.lower(),))
  396. if self.quantity == 0:
  397. return self.delete(*args, **kwargs)
  398. super(AbstractLine, self).save(*args, **kwargs)
  399. def set_as_tax_exempt(self):
  400. self._charge_tax = False
  401. # =============
  402. # Offer methods
  403. # =============
  404. def clear_discount(self):
  405. """
  406. Remove any discounts from this line.
  407. """
  408. self._discount = Decimal('0.00')
  409. self._affected_quantity = 0
  410. def discount(self, discount_value, affected_quantity):
  411. self._discount += discount_value
  412. self._affected_quantity += int(affected_quantity)
  413. def consume(self, quantity):
  414. if quantity > self.quantity - self._affected_quantity:
  415. inc = self.quantity - self._affected_quantity
  416. else:
  417. inc = quantity
  418. self._affected_quantity += int(inc)
  419. def get_price_breakdown(self):
  420. """
  421. Returns a breakdown of line prices after discounts have
  422. been applied.
  423. """
  424. prices = []
  425. if not self.has_discount:
  426. prices.append((self.unit_price_incl_tax, self.unit_price_excl_tax,
  427. self.quantity))
  428. else:
  429. # Need to split the discount among the affected quantity
  430. # of products.
  431. item_incl_tax_discount = (
  432. self._discount / int(self._affected_quantity))
  433. item_excl_tax_discount = item_incl_tax_discount * self._tax_ratio
  434. prices.append((self.unit_price_incl_tax - item_incl_tax_discount,
  435. self.unit_price_excl_tax - item_excl_tax_discount,
  436. self._affected_quantity))
  437. if self.quantity_without_discount:
  438. prices.append((self.unit_price_incl_tax,
  439. self.unit_price_excl_tax,
  440. self.quantity_without_discount))
  441. return prices
  442. # =======
  443. # Helpers
  444. # =======
  445. def _get_stockrecord_property(self, property):
  446. if not self.product.stockrecord:
  447. return Decimal('0.00')
  448. else:
  449. attr = getattr(self.product.stockrecord, property)
  450. if attr is None:
  451. attr = Decimal('0.00')
  452. return attr
  453. @property
  454. def _tax_ratio(self):
  455. if not self.unit_price_incl_tax:
  456. return 0
  457. return self.unit_price_excl_tax / self.unit_price_incl_tax
  458. # ==========
  459. # Properties
  460. # ==========
  461. @property
  462. def has_discount(self):
  463. return self.quantity > self.quantity_without_discount
  464. @property
  465. def quantity_with_discount(self):
  466. return self._affected_quantity
  467. @property
  468. def quantity_without_discount(self):
  469. return int(self.quantity - self._affected_quantity)
  470. @property
  471. def is_available_for_discount(self):
  472. return self.quantity_without_discount > 0
  473. @property
  474. def discount_value(self):
  475. return self._discount
  476. @property
  477. def unit_price_excl_tax(self):
  478. """Return unit price excluding tax"""
  479. return self._get_stockrecord_property('price_excl_tax')
  480. @property
  481. def unit_price_incl_tax(self):
  482. """Return unit price including tax"""
  483. if not self._charge_tax:
  484. return self.unit_price_excl_tax
  485. return self._get_stockrecord_property('price_incl_tax')
  486. @property
  487. def unit_tax(self):
  488. """Return tax of a unit"""
  489. if not self._charge_tax:
  490. return Decimal('0.00')
  491. return self._get_stockrecord_property('price_tax')
  492. @property
  493. def line_price_excl_tax(self):
  494. """Return line price excluding tax"""
  495. return self.quantity * self.unit_price_excl_tax
  496. @property
  497. def line_price_excl_tax_and_discounts(self):
  498. return self.line_price_excl_tax - self._discount * self._tax_ratio
  499. @property
  500. def line_tax(self):
  501. """Return line tax"""
  502. return self.quantity * self.unit_tax
  503. @property
  504. def line_price_incl_tax(self):
  505. """Return line price including tax"""
  506. return self.quantity * self.unit_price_incl_tax
  507. @property
  508. def line_price_incl_tax_and_discounts(self):
  509. return self.line_price_incl_tax - self._discount
  510. @property
  511. def description(self):
  512. """Return product description"""
  513. d = str(self.product)
  514. ops = []
  515. for attribute in self.attributes.all():
  516. ops.append("%s = '%s'" % (attribute.option.name, attribute.value))
  517. if ops:
  518. d = "%s (%s)" % (d.decode('utf-8'), ", ".join(ops))
  519. return d
  520. def get_warning(self):
  521. """
  522. Return a warning message about this basket line if one is applicable
  523. This could be things like the price has changed
  524. """
  525. if not self.price_incl_tax:
  526. return
  527. if not self.product.has_stockrecord:
  528. msg = u"'%(product)s' is no longer available"
  529. return _(msg) % {'product': self.product.get_title()}
  530. current_price_incl_tax = self.product.stockrecord.price_incl_tax
  531. if current_price_incl_tax > self.price_incl_tax:
  532. msg = (
  533. u"The price of '%(product)s' has increased from %(old_price)s "
  534. u"to %(new_price)s since you added it to your basket")
  535. return _(msg) % {'product': self.product.get_title(),
  536. 'old_price': currency(self.price_incl_tax),
  537. 'new_price': currency(current_price_incl_tax)}
  538. if current_price_incl_tax < self.price_incl_tax:
  539. msg = (
  540. u"The price of '%(product)s' has decreased from %(old_price)s "
  541. u"to %(new_price)s since you added it to your basket")
  542. return _(msg) % {'product': self.product.get_title(),
  543. 'old_price': currency(self.price_incl_tax),
  544. 'new_price': currency(current_price_incl_tax)}
  545. class AbstractLineAttribute(models.Model):
  546. """
  547. An attribute of a basket line
  548. """
  549. line = models.ForeignKey('basket.Line', related_name='attributes',
  550. verbose_name=_("Line"))
  551. option = models.ForeignKey('catalogue.Option', verbose_name=_("Option"))
  552. value = models.CharField(_("Value"), max_length=255)
  553. class Meta:
  554. abstract = True
  555. verbose_name = _('Line attribute')
  556. verbose_name_plural = _('Line attributes')