Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. from decimal import Decimal as D
  2. import zlib
  3. from django.db import models
  4. from django.db.models import Sum
  5. from django.conf import settings
  6. from django.utils.encoding import python_2_unicode_compatible
  7. from django.utils.timezone import now
  8. from django.utils.translation import ugettext_lazy as _
  9. from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
  10. from oscar.apps.basket.managers import OpenBasketManager, SavedBasketManager
  11. from oscar.apps.offer import results
  12. from oscar.core.compat import AUTH_USER_MODEL
  13. from oscar.templatetags.currency_filters import currency
  14. @python_2_unicode_compatible
  15. class AbstractBasket(models.Model):
  16. """
  17. Basket object
  18. """
  19. # Baskets can be anonymously owned - hence this field is nullable. When a
  20. # anon user signs in, their two baskets are merged.
  21. owner = models.ForeignKey(
  22. AUTH_USER_MODEL, related_name='baskets', null=True,
  23. verbose_name=_("Owner"))
  24. # Basket statuses
  25. # - Frozen is for when a basket is in the process of being submitted
  26. # and we need to prevent any changes to it.
  27. OPEN, MERGED, SAVED, FROZEN, SUBMITTED = (
  28. "Open", "Merged", "Saved", "Frozen", "Submitted")
  29. STATUS_CHOICES = (
  30. (OPEN, _("Open - currently active")),
  31. (MERGED, _("Merged - superceded by another basket")),
  32. (SAVED, _("Saved - for items to be purchased later")),
  33. (FROZEN, _("Frozen - the basket cannot be modified")),
  34. (SUBMITTED, _("Submitted - has been ordered at the checkout")),
  35. )
  36. status = models.CharField(
  37. _("Status"), max_length=128, default=OPEN, choices=STATUS_CHOICES)
  38. # A basket can have many vouchers attached to it. However, it is common
  39. # for sites to only allow one voucher per basket - this will need to be
  40. # enforced in the project's codebase.
  41. vouchers = models.ManyToManyField(
  42. 'voucher.Voucher', null=True, verbose_name=_("Vouchers"), blank=True)
  43. date_created = models.DateTimeField(_("Date created"), auto_now_add=True)
  44. date_merged = models.DateTimeField(_("Date merged"), null=True, blank=True)
  45. date_submitted = models.DateTimeField(_("Date submitted"), null=True,
  46. blank=True)
  47. # Only if a basket is in one of these statuses can it be edited
  48. editable_statuses = (OPEN, SAVED)
  49. class Meta:
  50. abstract = True
  51. app_label = 'basket'
  52. verbose_name = _('Basket')
  53. verbose_name_plural = _('Baskets')
  54. objects = models.Manager()
  55. open = OpenBasketManager()
  56. saved = SavedBasketManager()
  57. def __init__(self, *args, **kwargs):
  58. super(AbstractBasket, self).__init__(*args, **kwargs)
  59. # We keep a cached copy of the basket lines as we refer to them often
  60. # within the same request cycle. Also, applying offers will append
  61. # discount data to the basket lines which isn't persisted to the DB and
  62. # so we want to avoid reloading them as this would drop the discount
  63. # information.
  64. self._lines = None
  65. self.offer_applications = results.OfferApplications()
  66. def __str__(self):
  67. return _(
  68. u"%(status)s basket (owner: %(owner)s, lines: %(num_lines)d)") \
  69. % {'status': self.status,
  70. 'owner': self.owner,
  71. 'num_lines': self.num_lines}
  72. # ========
  73. # Strategy
  74. # ========
  75. @property
  76. def has_strategy(self):
  77. return hasattr(self, '_strategy')
  78. def _get_strategy(self):
  79. if not self.has_strategy:
  80. raise RuntimeError(
  81. "No strategy class has been assigned to this basket. "
  82. "This is normally assigned to the incoming request in "
  83. "oscar.apps.basket.middleware.BasketMiddleware. "
  84. "Since it is missing, you must be doing something different. "
  85. "Ensure that a strategy instance is assigned to the basket!"
  86. )
  87. return self._strategy
  88. def _set_strategy(self, strategy):
  89. self._strategy = strategy
  90. strategy = property(_get_strategy, _set_strategy)
  91. def all_lines(self):
  92. """
  93. Return a cached set of basket lines.
  94. This is important for offers as they alter the line models and you
  95. don't want to reload them from the DB as that information would be
  96. lost.
  97. """
  98. if self.id is None:
  99. return self.lines.none()
  100. if self._lines is None:
  101. self._lines = (
  102. self.lines
  103. .select_related('product', 'stockrecord')
  104. .prefetch_related(
  105. 'attributes', 'product__images'))
  106. return self._lines
  107. def is_quantity_allowed(self, qty):
  108. """
  109. Test whether the passed quantity of items can be added to the basket
  110. """
  111. # We enfore a max threshold to prevent a DOS attack via the offers
  112. # system.
  113. basket_threshold = settings.OSCAR_MAX_BASKET_QUANTITY_THRESHOLD
  114. if basket_threshold:
  115. total_basket_quantity = self.num_items
  116. max_allowed = basket_threshold - total_basket_quantity
  117. if qty > max_allowed:
  118. return False, _(
  119. "Due to technical limitations we are not able "
  120. "to ship more than %(threshold)d items in one order.") \
  121. % {'threshold': basket_threshold}
  122. return True, None
  123. # ============
  124. # Manipulation
  125. # ============
  126. def flush(self):
  127. """
  128. Remove all lines from basket.
  129. """
  130. if self.status == self.FROZEN:
  131. raise PermissionDenied("A frozen basket cannot be flushed")
  132. self.lines.all().delete()
  133. self._lines = None
  134. def add_product(self, product, quantity=1, options=None):
  135. """
  136. Add a product to the basket
  137. 'stock_info' is the price and availability data returned from
  138. a partner strategy class.
  139. The 'options' list should contains dicts with keys 'option' and 'value'
  140. which link the relevant product.Option model and string value
  141. respectively.
  142. """
  143. if options is None:
  144. options = []
  145. if not self.id:
  146. self.save()
  147. # Ensure that all lines are the same currency
  148. price_currency = self.currency
  149. stock_info = self.strategy.fetch_for_product(product)
  150. if price_currency and stock_info.price.currency != price_currency:
  151. raise ValueError((
  152. "Basket lines must all have the same currency. Proposed "
  153. "line has currency %s, while basket has currency %s")
  154. % (stock_info.price.currency, price_currency))
  155. if stock_info.stockrecord is None:
  156. raise ValueError((
  157. "Basket lines must all have stock records. Strategy hasn't "
  158. "found any stock record for product %s") % product)
  159. # Line reference is used to distinguish between variations of the same
  160. # product (eg T-shirts with different personalisations)
  161. line_ref = self._create_line_reference(
  162. product, stock_info.stockrecord, options)
  163. # Determine price to store (if one exists). It is only stored for
  164. # audit and sometimes caching.
  165. defaults = {
  166. 'quantity': quantity,
  167. 'price_excl_tax': stock_info.price.excl_tax,
  168. 'price_currency': stock_info.price.currency,
  169. }
  170. if stock_info.price.is_tax_known:
  171. defaults['price_incl_tax'] = stock_info.price.incl_tax
  172. line, created = self.lines.get_or_create(
  173. line_reference=line_ref,
  174. product=product,
  175. stockrecord=stock_info.stockrecord,
  176. defaults=defaults)
  177. if created:
  178. for option_dict in options:
  179. line.attributes.create(option=option_dict['option'],
  180. value=option_dict['value'])
  181. else:
  182. line.quantity += quantity
  183. line.save()
  184. self.reset_offer_applications()
  185. add_product.alters_data = True
  186. add = add_product
  187. def applied_offers(self):
  188. """
  189. Return a dict of offers successfully applied to the basket.
  190. This is used to compare offers before and after a basket change to see
  191. if there is a difference.
  192. """
  193. return self.offer_applications.offers
  194. def reset_offer_applications(self):
  195. """
  196. Remove any discounts so they get recalculated
  197. """
  198. self.offer_applications = results.OfferApplications()
  199. self._lines = None
  200. def merge_line(self, line, add_quantities=True):
  201. """
  202. For transferring a line from another basket to this one.
  203. This is used with the "Saved" basket functionality.
  204. """
  205. try:
  206. existing_line = self.lines.get(line_reference=line.line_reference)
  207. except ObjectDoesNotExist:
  208. # Line does not already exist - reassign its basket
  209. line.basket = self
  210. line.save()
  211. else:
  212. # Line already exists - assume the max quantity is correct and
  213. # delete the old
  214. if add_quantities:
  215. existing_line.quantity += line.quantity
  216. else:
  217. existing_line.quantity = max(existing_line.quantity,
  218. line.quantity)
  219. existing_line.save()
  220. line.delete()
  221. finally:
  222. self._lines = None
  223. merge_line.alters_data = True
  224. def merge(self, basket, add_quantities=True):
  225. """
  226. Merges another basket with this one.
  227. :basket: The basket to merge into this one.
  228. :add_quantities: Whether to add line quantities when they are merged.
  229. """
  230. # Use basket.lines.all instead of all_lines as this function is called
  231. # before a strategy has been assigned.
  232. for line_to_merge in basket.lines.all():
  233. self.merge_line(line_to_merge, add_quantities)
  234. basket.status = self.MERGED
  235. basket.date_merged = now()
  236. basket._lines = None
  237. basket.save()
  238. # Ensure all vouchers are moved to the new basket
  239. for voucher in basket.vouchers.all():
  240. basket.vouchers.remove(voucher)
  241. self.vouchers.add(voucher)
  242. merge.alters_data = True
  243. def freeze(self):
  244. """
  245. Freezes the basket so it cannot be modified.
  246. """
  247. self.status = self.FROZEN
  248. self.save()
  249. freeze.alters_data = True
  250. def thaw(self):
  251. """
  252. Unfreezes a basket so it can be modified again
  253. """
  254. self.status = self.OPEN
  255. self.save()
  256. thaw.alters_data = True
  257. def submit(self):
  258. """
  259. Mark this basket as submitted
  260. """
  261. self.status = self.SUBMITTED
  262. self.date_submitted = now()
  263. self.save()
  264. submit.alters_data = True
  265. # Kept for backwards compatibility
  266. set_as_submitted = submit
  267. def is_shipping_required(self):
  268. """
  269. Test whether the basket contains physical products that require
  270. shipping.
  271. """
  272. for line in self.all_lines():
  273. if line.product.is_shipping_required:
  274. return True
  275. return False
  276. # =======
  277. # Helpers
  278. # =======
  279. def _create_line_reference(self, product, stockrecord, options):
  280. """
  281. Returns a reference string for a line based on the item
  282. and its options.
  283. """
  284. base = '%s_%s' % (product.id, stockrecord.id)
  285. if not options:
  286. return base
  287. return "%s_%s" % (base, zlib.crc32(repr(options).encode('utf8')))
  288. def _get_total(self, property):
  289. """
  290. For executing a named method on each line of the basket
  291. and returning the total.
  292. """
  293. total = D('0.00')
  294. for line in self.all_lines():
  295. try:
  296. total += getattr(line, property)
  297. except ObjectDoesNotExist:
  298. # Handle situation where the product may have been deleted
  299. pass
  300. return total
  301. # ==========
  302. # Properties
  303. # ==========
  304. @property
  305. def is_empty(self):
  306. """
  307. Test if this basket is empty
  308. """
  309. return self.id is None or self.num_lines == 0
  310. @property
  311. def is_tax_known(self):
  312. """
  313. Test if tax values are known for this basket
  314. """
  315. return all([line.is_tax_known for line in self.all_lines()])
  316. @property
  317. def total_excl_tax(self):
  318. """
  319. Return total line price excluding tax
  320. """
  321. return self._get_total('line_price_excl_tax_incl_discounts')
  322. @property
  323. def total_tax(self):
  324. """Return total tax for a line"""
  325. return self._get_total('line_tax')
  326. @property
  327. def total_incl_tax(self):
  328. """
  329. Return total price inclusive of tax and discounts
  330. """
  331. return self._get_total('line_price_incl_tax_incl_discounts')
  332. @property
  333. def total_incl_tax_excl_discounts(self):
  334. """
  335. Return total price inclusive of tax but exclusive discounts
  336. """
  337. return self._get_total('line_price_incl_tax')
  338. @property
  339. def total_discount(self):
  340. return self._get_total('discount_value')
  341. @property
  342. def offer_discounts(self):
  343. """
  344. Return basket discounts from non-voucher sources. Does not include
  345. shipping discounts.
  346. """
  347. return self.offer_applications.offer_discounts
  348. @property
  349. def voucher_discounts(self):
  350. """
  351. Return discounts from vouchers
  352. """
  353. return self.offer_applications.voucher_discounts
  354. @property
  355. def has_shipping_discounts(self):
  356. return len(self.shipping_discounts) > 0
  357. @property
  358. def shipping_discounts(self):
  359. """
  360. Return discounts from vouchers
  361. """
  362. return self.offer_applications.shipping_discounts
  363. @property
  364. def post_order_actions(self):
  365. """
  366. Return discounts from vouchers
  367. """
  368. return self.offer_applications.post_order_actions
  369. @property
  370. def grouped_voucher_discounts(self):
  371. """
  372. Return discounts from vouchers but grouped so that a voucher which
  373. links to multiple offers is aggregated into one object.
  374. """
  375. return self.offer_applications.grouped_voucher_discounts
  376. @property
  377. def total_excl_tax_excl_discounts(self):
  378. """
  379. Return total price excluding tax and discounts
  380. """
  381. return self._get_total('line_price_excl_tax')
  382. @property
  383. def num_lines(self):
  384. """Return number of lines"""
  385. return self.all_lines().count()
  386. @property
  387. def num_items(self):
  388. """Return number of items"""
  389. return sum(line.quantity for line in self.lines.all())
  390. @property
  391. def num_items_without_discount(self):
  392. num = 0
  393. for line in self.all_lines():
  394. num += line.quantity_without_discount
  395. return num
  396. @property
  397. def num_items_with_discount(self):
  398. num = 0
  399. for line in self.all_lines():
  400. num += line.quantity_with_discount
  401. return num
  402. @property
  403. def time_before_submit(self):
  404. if not self.date_submitted:
  405. return None
  406. return self.date_submitted - self.date_created
  407. @property
  408. def time_since_creation(self, test_datetime=None):
  409. if not test_datetime:
  410. test_datetime = now()
  411. return test_datetime - self.date_created
  412. @property
  413. def contains_a_voucher(self):
  414. if not self.id:
  415. return False
  416. return self.vouchers.exists()
  417. @property
  418. def is_submitted(self):
  419. return self.status == self.SUBMITTED
  420. @property
  421. def can_be_edited(self):
  422. """
  423. Test if a basket can be edited
  424. """
  425. return self.status in self.editable_statuses
  426. @property
  427. def currency(self):
  428. # Since all lines should have the same currency, return the currency of
  429. # the first one found.
  430. for line in self.all_lines():
  431. return line.price_currency
  432. # =============
  433. # Query methods
  434. # =============
  435. def contains_voucher(self, code):
  436. """
  437. Test whether the basket contains a voucher with a given code
  438. """
  439. if self.id is None:
  440. return False
  441. try:
  442. self.vouchers.get(code=code)
  443. except ObjectDoesNotExist:
  444. return False
  445. else:
  446. return True
  447. def product_quantity(self, product):
  448. """
  449. Return the quantity of a product in the basket
  450. The basket can contain multiple lines with the same product, but
  451. different options and stockrecords. Those quantities are summed up.
  452. """
  453. matching_lines = self.lines.filter(product=product)
  454. quantity = matching_lines.aggregate(Sum('quantity'))['quantity__sum']
  455. return quantity or 0
  456. def line_quantity(self, product, stockrecord, options=None):
  457. """
  458. Return the current quantity of a specific product and options
  459. """
  460. ref = self._create_line_reference(product, stockrecord, options)
  461. try:
  462. return self.lines.get(line_reference=ref).quantity
  463. except ObjectDoesNotExist:
  464. return 0
  465. @python_2_unicode_compatible
  466. class AbstractLine(models.Model):
  467. """
  468. A line of a basket (product and a quantity)
  469. """
  470. basket = models.ForeignKey('basket.Basket', related_name='lines',
  471. verbose_name=_("Basket"))
  472. # This is to determine which products belong to the same line
  473. # We can't just use product.id as you can have customised products
  474. # which should be treated as separate lines. Set as a
  475. # SlugField as it is included in the path for certain views.
  476. line_reference = models.SlugField(
  477. _("Line Reference"), max_length=128, db_index=True)
  478. product = models.ForeignKey(
  479. 'catalogue.Product', related_name='basket_lines',
  480. verbose_name=_("Product"))
  481. # We store the stockrecord that should be used to fulfil this line.
  482. stockrecord = models.ForeignKey(
  483. 'partner.StockRecord', related_name='basket_lines')
  484. quantity = models.PositiveIntegerField(_('Quantity'), default=1)
  485. # We store the unit price incl tax of the product when it is first added to
  486. # the basket. This allows us to tell if a product has changed price since
  487. # a person first added it to their basket.
  488. price_currency = models.CharField(
  489. _("Currency"), max_length=12, default=settings.OSCAR_DEFAULT_CURRENCY)
  490. price_excl_tax = models.DecimalField(
  491. _('Price excl. Tax'), decimal_places=2, max_digits=12,
  492. null=True)
  493. price_incl_tax = models.DecimalField(
  494. _('Price incl. Tax'), decimal_places=2, max_digits=12, null=True)
  495. # Track date of first addition
  496. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  497. def __init__(self, *args, **kwargs):
  498. super(AbstractLine, self).__init__(*args, **kwargs)
  499. # Instance variables used to persist discount information
  500. self._discount_excl_tax = D('0.00')
  501. self._discount_incl_tax = D('0.00')
  502. self._affected_quantity = 0
  503. class Meta:
  504. abstract = True
  505. app_label = 'basket'
  506. unique_together = ("basket", "line_reference")
  507. verbose_name = _('Basket line')
  508. verbose_name_plural = _('Basket lines')
  509. def __str__(self):
  510. return _(
  511. u"Basket #%(basket_id)d, Product #%(product_id)d, quantity"
  512. u" %(quantity)d") % {'basket_id': self.basket.pk,
  513. 'product_id': self.product.pk,
  514. 'quantity': self.quantity}
  515. def save(self, *args, **kwargs):
  516. if not self.basket.can_be_edited:
  517. raise PermissionDenied(
  518. _("You cannot modify a %s basket") % (
  519. self.basket.status.lower(),))
  520. return super(AbstractLine, self).save(*args, **kwargs)
  521. # =============
  522. # Offer methods
  523. # =============
  524. def clear_discount(self):
  525. """
  526. Remove any discounts from this line.
  527. """
  528. self._discount_excl_tax = D('0.00')
  529. self._discount_incl_tax = D('0.00')
  530. self._affected_quantity = 0
  531. def discount(self, discount_value, affected_quantity, incl_tax=True):
  532. """
  533. Apply a discount to this line
  534. """
  535. if incl_tax:
  536. if self._discount_excl_tax > 0:
  537. raise RuntimeError(
  538. "Attempting to discount the tax-inclusive price of a line "
  539. "when tax-exclusive discounts are already applied")
  540. self._discount_incl_tax += discount_value
  541. else:
  542. if self._discount_incl_tax > 0:
  543. raise RuntimeError(
  544. "Attempting to discount the tax-exclusive price of a line "
  545. "when tax-inclusive discounts are already applied")
  546. self._discount_excl_tax += discount_value
  547. self._affected_quantity += int(affected_quantity)
  548. def consume(self, quantity):
  549. """
  550. Mark all or part of the line as 'consumed'
  551. Consumed items are no longer available to be used in offers.
  552. """
  553. if quantity > self.quantity - self._affected_quantity:
  554. inc = self.quantity - self._affected_quantity
  555. else:
  556. inc = quantity
  557. self._affected_quantity += int(inc)
  558. def get_price_breakdown(self):
  559. """
  560. Return a breakdown of line prices after discounts have been applied.
  561. Returns a list of (unit_price_incl_tx, unit_price_excl_tax, quantity)
  562. tuples.
  563. """
  564. if not self.is_tax_known:
  565. raise RuntimeError("A price breakdown can only be determined "
  566. "when taxes are known")
  567. prices = []
  568. if not self.discount_value:
  569. prices.append((self.unit_price_incl_tax, self.unit_price_excl_tax,
  570. self.quantity))
  571. else:
  572. # Need to split the discount among the affected quantity
  573. # of products.
  574. item_incl_tax_discount = (
  575. self.discount_value / int(self._affected_quantity))
  576. item_excl_tax_discount = item_incl_tax_discount * self._tax_ratio
  577. item_excl_tax_discount = item_excl_tax_discount.quantize(D('0.01'))
  578. prices.append((self.unit_price_incl_tax - item_incl_tax_discount,
  579. self.unit_price_excl_tax - item_excl_tax_discount,
  580. self._affected_quantity))
  581. if self.quantity_without_discount:
  582. prices.append((self.unit_price_incl_tax,
  583. self.unit_price_excl_tax,
  584. self.quantity_without_discount))
  585. return prices
  586. # =======
  587. # Helpers
  588. # =======
  589. @property
  590. def _tax_ratio(self):
  591. if not self.unit_price_incl_tax:
  592. return 0
  593. return self.unit_price_excl_tax / self.unit_price_incl_tax
  594. # ==========
  595. # Properties
  596. # ==========
  597. @property
  598. def has_discount(self):
  599. return self.quantity > self.quantity_without_discount
  600. @property
  601. def quantity_with_discount(self):
  602. return self._affected_quantity
  603. @property
  604. def quantity_without_discount(self):
  605. return int(self.quantity - self._affected_quantity)
  606. @property
  607. def is_available_for_discount(self):
  608. return self.quantity_without_discount > 0
  609. @property
  610. def discount_value(self):
  611. # Only one of the incl- and excl- discounts should be non-zero
  612. return max(self._discount_incl_tax, self._discount_excl_tax)
  613. @property
  614. def purchase_info(self):
  615. """
  616. Return the stock/price info
  617. """
  618. if not hasattr(self, '_info'):
  619. # Cache the PurchaseInfo instance.
  620. self._info = self.basket.strategy.fetch_for_product(
  621. self.product, self.stockrecord)
  622. return self._info
  623. @property
  624. def is_tax_known(self):
  625. return self.purchase_info.price.is_tax_known
  626. @property
  627. def unit_effective_price(self):
  628. """
  629. The price to use for offer calculations
  630. """
  631. return self.purchase_info.price.effective_price
  632. @property
  633. def unit_price_excl_tax(self):
  634. return self.purchase_info.price.excl_tax
  635. @property
  636. def unit_price_incl_tax(self):
  637. return self.purchase_info.price.incl_tax
  638. @property
  639. def unit_tax(self):
  640. return self.purchase_info.price.tax
  641. @property
  642. def line_price_excl_tax(self):
  643. return self.quantity * self.unit_price_excl_tax
  644. @property
  645. def line_price_excl_tax_incl_discounts(self):
  646. if self._discount_excl_tax:
  647. return self.line_price_excl_tax - self._discount_excl_tax
  648. if self._discount_incl_tax:
  649. # This is a tricky situation. We know the discount as calculated
  650. # against tax inclusive prices but we need to guess how much of the
  651. # discount applies to tax-exclusive prices. We do this by
  652. # assuming a linear tax and scaling down the original discount.
  653. return self.line_price_excl_tax \
  654. - self._tax_ratio * self._discount_incl_tax
  655. return self.line_price_excl_tax
  656. @property
  657. def line_price_incl_tax_incl_discounts(self):
  658. # We use whichever discount value is set. If the discount value was
  659. # calculated against the tax-exclusive prices, then the line price
  660. # including tax
  661. return self.line_price_incl_tax - self.discount_value
  662. @property
  663. def line_tax(self):
  664. return self.quantity * self.unit_tax
  665. @property
  666. def line_price_incl_tax(self):
  667. return self.quantity * self.unit_price_incl_tax
  668. @property
  669. def description(self):
  670. d = str(self.product)
  671. ops = []
  672. for attribute in self.attributes.all():
  673. ops.append("%s = '%s'" % (attribute.option.name, attribute.value))
  674. if ops:
  675. d = "%s (%s)" % (d.decode('utf-8'), ", ".join(ops))
  676. return d
  677. def get_warning(self):
  678. """
  679. Return a warning message about this basket line if one is applicable
  680. This could be things like the price has changed
  681. """
  682. if not self.stockrecord:
  683. msg = u"'%(product)s' is no longer available"
  684. return _(msg) % {'product': self.product.get_title()}
  685. if not self.price_incl_tax:
  686. return
  687. if not self.purchase_info.price.is_tax_known:
  688. return
  689. # Compare current price to price when added to basket
  690. current_price_incl_tax = self.purchase_info.price.incl_tax
  691. if current_price_incl_tax != self.price_incl_tax:
  692. product_prices = {
  693. 'product': self.product.get_title(),
  694. 'old_price': currency(self.price_incl_tax),
  695. 'new_price': currency(current_price_incl_tax)
  696. }
  697. if current_price_incl_tax > self.price_incl_tax:
  698. warning = _("The price of '%(product)s' has increased from"
  699. " %(old_price)s to %(new_price)s since you added"
  700. " it to your basket")
  701. return warning % product_prices
  702. else:
  703. warning = _("The price of '%(product)s' has decreased from"
  704. " %(old_price)s to %(new_price)s since you added"
  705. " it to your basket")
  706. return warning % product_prices
  707. class AbstractLineAttribute(models.Model):
  708. """
  709. An attribute of a basket line
  710. """
  711. line = models.ForeignKey('basket.Line', related_name='attributes',
  712. verbose_name=_("Line"))
  713. option = models.ForeignKey('catalogue.Option', verbose_name=_("Option"))
  714. value = models.CharField(_("Value"), max_length=255)
  715. class Meta:
  716. abstract = True
  717. app_label = 'basket'
  718. verbose_name = _('Line attribute')
  719. verbose_name_plural = _('Line attributes')