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

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