Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

abstract_models.py 22KB

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