您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

abstract_models.py 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  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. def get_discounts(self):
  131. if self.discounts is None:
  132. self.discounts = []
  133. return self.discounts
  134. def set_discounts(self, discounts):
  135. """
  136. Sets the discounts that apply to this basket.
  137. This should be a list of dictionaries
  138. """
  139. self.discounts = discounts
  140. def remove_discounts(self):
  141. """
  142. Remove any discounts so they get recalculated
  143. """
  144. self.discounts = []
  145. self._lines = None
  146. def merge_line(self, line, add_quantities=True):
  147. """
  148. For transferring a line from another basket to this one.
  149. This is used with the "Saved" basket functionality.
  150. """
  151. try:
  152. existing_line = self.lines.get(line_reference=line.line_reference)
  153. except ObjectDoesNotExist:
  154. # Line does not already exist - reassign its basket
  155. line.basket = self
  156. line.save()
  157. else:
  158. # Line already exists - assume the max quantity is correct and
  159. # delete the old
  160. if add_quantities:
  161. existing_line.quantity += line.quantity
  162. else:
  163. existing_line.quantity = max(existing_line.quantity,
  164. line.quantity)
  165. existing_line.save()
  166. line.delete()
  167. def merge(self, basket, add_quantities=True):
  168. """
  169. Merges another basket with this one.
  170. :basket: The basket to merge into this one
  171. :add_quantities: Whether to add line quantities when they are merged.
  172. """
  173. for line_to_merge in basket.all_lines():
  174. self.merge_line(line_to_merge, add_quantities)
  175. basket.status = self.MERGED
  176. basket.date_merged = now()
  177. basket.save()
  178. self._lines = None
  179. def freeze(self):
  180. """
  181. Freezes the basket so it cannot be modified.
  182. """
  183. self.status = self.FROZEN
  184. self.save()
  185. def thaw(self):
  186. """
  187. Unfreezes a basket so it can be modified again
  188. """
  189. self.status = self.OPEN
  190. self.save()
  191. def set_as_submitted(self):
  192. """Mark this basket as submitted."""
  193. self.status = self.SUBMITTED
  194. self.date_submitted = now()
  195. self.save()
  196. def set_as_tax_exempt(self):
  197. self.exempt_from_tax = True
  198. for line in self.all_lines():
  199. line.set_as_tax_exempt()
  200. def is_shipping_required(self):
  201. """
  202. Test whether the basket contains physical products that require
  203. shipping.
  204. """
  205. for line in self.all_lines():
  206. if line.product.is_shipping_required:
  207. return True
  208. return False
  209. # =======
  210. # Helpers
  211. # =======
  212. def _create_line_reference(self, item, options):
  213. """
  214. Returns a reference string for a line based on the item
  215. and its options.
  216. """
  217. if not options:
  218. return item.id
  219. return "%d_%s" % (item.id, zlib.crc32(str(options)))
  220. def _get_total(self, property):
  221. """
  222. For executing a named method on each line of the basket
  223. and returning the total.
  224. """
  225. total = Decimal('0.00')
  226. for line in self.all_lines():
  227. try:
  228. total += getattr(line, property)
  229. except ObjectDoesNotExist:
  230. # Handle situation where the product may have been deleted
  231. pass
  232. return total
  233. # ==========
  234. # Properties
  235. # ==========
  236. @property
  237. def is_empty(self):
  238. """
  239. Test if this basket is empty
  240. """
  241. return self.id is None or self.num_lines == 0
  242. @property
  243. def total_excl_tax(self):
  244. """Return total line price excluding tax"""
  245. return self._get_total('line_price_excl_tax_and_discounts')
  246. @property
  247. def total_tax(self):
  248. """Return total tax for a line"""
  249. return self._get_total('line_tax')
  250. @property
  251. def total_incl_tax(self):
  252. """
  253. Return total price inclusive of tax and discounts
  254. """
  255. return self._get_total('line_price_incl_tax_and_discounts')
  256. @property
  257. def total_incl_tax_excl_discounts(self):
  258. """
  259. Return total price inclusive of tax but exclusive discounts
  260. """
  261. return self._get_total('line_price_incl_tax')
  262. @property
  263. def total_discount(self):
  264. return self._get_total('discount_value')
  265. @property
  266. def offer_discounts(self):
  267. """
  268. Return discounts from non-voucher sources.
  269. """
  270. offer_discounts = []
  271. for discount in self.get_discounts():
  272. if not discount['voucher']:
  273. offer_discounts.append(discount)
  274. return offer_discounts
  275. @property
  276. def voucher_discounts(self):
  277. """
  278. Return discounts from vouchers
  279. """
  280. voucher_discounts = []
  281. for discount in self.get_discounts():
  282. if discount['voucher']:
  283. voucher_discounts.append(discount)
  284. return voucher_discounts
  285. @property
  286. def grouped_voucher_discounts(self):
  287. """
  288. Return discounts from vouchers but grouped so that a voucher which
  289. links to multiple offers is aggregated into one object.
  290. """
  291. voucher_discounts = {}
  292. for discount in self.voucher_discounts:
  293. voucher = discount['voucher']
  294. if voucher.code not in voucher_discounts:
  295. voucher_discounts[voucher.code] = {
  296. 'voucher': voucher,
  297. 'discount': discount['discount'],
  298. }
  299. else:
  300. voucher_discounts[voucher.code] += discount.discount
  301. return voucher_discounts.values()
  302. @property
  303. def total_excl_tax_excl_discounts(self):
  304. """
  305. Return total price excluding tax and discounts
  306. """
  307. return self._get_total('line_price_excl_tax')
  308. @property
  309. def num_lines(self):
  310. """Return number of lines"""
  311. return len(self.all_lines())
  312. @property
  313. def num_items(self):
  314. """Return number of items"""
  315. return reduce(
  316. lambda num, line: num + line.quantity, self.all_lines(), 0)
  317. @property
  318. def num_items_without_discount(self):
  319. num = 0
  320. for line in self.all_lines():
  321. num += line.quantity_without_discount
  322. return num
  323. @property
  324. def num_items_with_discount(self):
  325. num = 0
  326. for line in self.all_lines():
  327. num += line.quantity_with_discount
  328. return num
  329. @property
  330. def time_before_submit(self):
  331. if not self.date_submitted:
  332. return None
  333. return self.date_submitted - self.date_created
  334. @property
  335. def time_since_creation(self, test_datetime=None):
  336. if not test_datetime:
  337. test_datetime = now()
  338. return test_datetime - self.date_created
  339. @property
  340. def contains_a_voucher(self):
  341. return self.vouchers.all().count() > 0
  342. # =============
  343. # Query methods
  344. # =============
  345. def can_be_edited(self):
  346. """
  347. Test if a basket can be edited
  348. """
  349. return self.status in self.editable_statuses
  350. def contains_voucher(self, code):
  351. """
  352. Test whether the basket contains a voucher with a given code
  353. """
  354. try:
  355. self.vouchers.get(code=code)
  356. except ObjectDoesNotExist:
  357. return False
  358. else:
  359. return True
  360. def line_quantity(self, product, options=None):
  361. """
  362. Return the current quantity of a specific product and options
  363. """
  364. ref = self._create_line_reference(product, options)
  365. try:
  366. return self.lines.get(line_reference=ref).quantity
  367. except ObjectDoesNotExist:
  368. return 0
  369. def is_submitted(self):
  370. return self.status == self.SUBMITTED
  371. class AbstractLine(models.Model):
  372. """
  373. A line of a basket (product and a quantity)
  374. """
  375. basket = models.ForeignKey('basket.Basket', related_name='lines',
  376. verbose_name=_("Basket"))
  377. # This is to determine which products belong to the same line
  378. # We can't just use product.id as you can have customised products
  379. # which should be treated as separate lines. Set as a
  380. # SlugField as it is included in the path for certain views.
  381. line_reference = models.SlugField(_("Line Reference"), max_length=128,
  382. db_index=True)
  383. product = models.ForeignKey(
  384. 'catalogue.Product', related_name='basket_lines',
  385. verbose_name=_("Product"))
  386. quantity = models.PositiveIntegerField(_('Quantity'), default=1)
  387. # We store the unit price incl tax of the product when it is first added to
  388. # the basket. This allows us to tell if a product has changed price since
  389. # a person first added it to their basket.
  390. price_excl_tax = models.DecimalField(
  391. _('Price excl. Tax'), decimal_places=2, max_digits=12,
  392. null=True)
  393. price_incl_tax = models.DecimalField(
  394. _('Price incl. Tax'), decimal_places=2, max_digits=12, null=True)
  395. # Track date of first addition
  396. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  397. # Instance variables used to persist discount information
  398. _discount = Decimal('0.00')
  399. _affected_quantity = 0
  400. _charge_tax = True
  401. class Meta:
  402. abstract = True
  403. unique_together = ("basket", "line_reference")
  404. verbose_name = _('Basket line')
  405. verbose_name_plural = _('Basket lines')
  406. def __unicode__(self):
  407. return _(
  408. u"%(basket)s, Product '%(product)s', quantity %(quantity)d") % {
  409. 'basket': self.basket,
  410. 'product': self.product,
  411. 'quantity': self.quantity}
  412. def save(self, *args, **kwargs):
  413. """
  414. Saves a line or deletes if the quantity is 0
  415. """
  416. if not self.basket.can_be_edited():
  417. raise PermissionDenied(
  418. _("You cannot modify a %s basket") % (
  419. self.basket.status.lower(),))
  420. if self.quantity == 0:
  421. return self.delete(*args, **kwargs)
  422. return super(AbstractLine, self).save(*args, **kwargs)
  423. def set_as_tax_exempt(self):
  424. self._charge_tax = False
  425. # =============
  426. # Offer methods
  427. # =============
  428. def clear_discount(self):
  429. """
  430. Remove any discounts from this line.
  431. """
  432. self._discount = Decimal('0.00')
  433. self._affected_quantity = 0
  434. def discount(self, discount_value, affected_quantity):
  435. self._discount += discount_value
  436. self._affected_quantity += int(affected_quantity)
  437. def consume(self, quantity):
  438. if quantity > self.quantity - self._affected_quantity:
  439. inc = self.quantity - self._affected_quantity
  440. else:
  441. inc = quantity
  442. self._affected_quantity += int(inc)
  443. def get_price_breakdown(self):
  444. """
  445. Returns a breakdown of line prices after discounts have
  446. been applied.
  447. """
  448. prices = []
  449. if not self.has_discount:
  450. prices.append((self.unit_price_incl_tax, self.unit_price_excl_tax,
  451. self.quantity))
  452. else:
  453. # Need to split the discount among the affected quantity
  454. # of products.
  455. item_incl_tax_discount = (
  456. self._discount / int(self._affected_quantity))
  457. item_excl_tax_discount = item_incl_tax_discount * self._tax_ratio
  458. prices.append((self.unit_price_incl_tax - item_incl_tax_discount,
  459. self.unit_price_excl_tax - item_excl_tax_discount,
  460. self._affected_quantity))
  461. if self.quantity_without_discount:
  462. prices.append((self.unit_price_incl_tax,
  463. self.unit_price_excl_tax,
  464. self.quantity_without_discount))
  465. return prices
  466. # =======
  467. # Helpers
  468. # =======
  469. def _get_stockrecord_property(self, property):
  470. if not self.product.stockrecord:
  471. return Decimal('0.00')
  472. else:
  473. attr = getattr(self.product.stockrecord, property)
  474. if attr is None:
  475. attr = Decimal('0.00')
  476. return attr
  477. @property
  478. def _tax_ratio(self):
  479. if not self.unit_price_incl_tax:
  480. return 0
  481. return self.unit_price_excl_tax / self.unit_price_incl_tax
  482. # ==========
  483. # Properties
  484. # ==========
  485. @property
  486. def has_discount(self):
  487. return self.quantity > self.quantity_without_discount
  488. @property
  489. def quantity_with_discount(self):
  490. return self._affected_quantity
  491. @property
  492. def quantity_without_discount(self):
  493. return int(self.quantity - self._affected_quantity)
  494. @property
  495. def is_available_for_discount(self):
  496. return self.quantity_without_discount > 0
  497. @property
  498. def discount_value(self):
  499. return self._discount
  500. @property
  501. def unit_price_excl_tax(self):
  502. """Return unit price excluding tax"""
  503. return self._get_stockrecord_property('price_excl_tax')
  504. @property
  505. def unit_price_incl_tax(self):
  506. """Return unit price including tax"""
  507. if not self._charge_tax:
  508. return self.unit_price_excl_tax
  509. return self._get_stockrecord_property('price_incl_tax')
  510. @property
  511. def unit_tax(self):
  512. """Return tax of a unit"""
  513. if not self._charge_tax:
  514. return Decimal('0.00')
  515. return self._get_stockrecord_property('price_tax')
  516. @property
  517. def line_price_excl_tax(self):
  518. """Return line price excluding tax"""
  519. return self.quantity * self.unit_price_excl_tax
  520. @property
  521. def line_price_excl_tax_and_discounts(self):
  522. return self.line_price_excl_tax - self._discount * self._tax_ratio
  523. @property
  524. def line_tax(self):
  525. """Return line tax"""
  526. return self.quantity * self.unit_tax
  527. @property
  528. def line_price_incl_tax(self):
  529. """Return line price including tax"""
  530. return self.quantity * self.unit_price_incl_tax
  531. @property
  532. def line_price_incl_tax_and_discounts(self):
  533. return self.line_price_incl_tax - self._discount
  534. @property
  535. def description(self):
  536. """Return product description"""
  537. d = str(self.product)
  538. ops = []
  539. for attribute in self.attributes.all():
  540. ops.append("%s = '%s'" % (attribute.option.name, attribute.value))
  541. if ops:
  542. d = "%s (%s)" % (d.decode('utf-8'), ", ".join(ops))
  543. return d
  544. def get_warning(self):
  545. """
  546. Return a warning message about this basket line if one is applicable
  547. This could be things like the price has changed
  548. """
  549. if not self.price_incl_tax:
  550. return
  551. if not self.product.has_stockrecord:
  552. msg = u"'%(product)s' is no longer available"
  553. return _(msg) % {'product': self.product.get_title()}
  554. current_price_incl_tax = self.product.stockrecord.price_incl_tax
  555. if current_price_incl_tax > self.price_incl_tax:
  556. msg = (
  557. u"The price of '%(product)s' has increased from %(old_price)s "
  558. u"to %(new_price)s since you added it to your basket")
  559. return _(msg) % {'product': self.product.get_title(),
  560. 'old_price': currency(self.price_incl_tax),
  561. 'new_price': currency(current_price_incl_tax)}
  562. if current_price_incl_tax < self.price_incl_tax:
  563. msg = (
  564. u"The price of '%(product)s' has decreased from %(old_price)s "
  565. u"to %(new_price)s since you added it to your basket")
  566. return _(msg) % {'product': self.product.get_title(),
  567. 'old_price': currency(self.price_incl_tax),
  568. 'new_price': currency(current_price_incl_tax)}
  569. class AbstractLineAttribute(models.Model):
  570. """
  571. An attribute of a basket line
  572. """
  573. line = models.ForeignKey('basket.Line', related_name='attributes',
  574. verbose_name=_("Line"))
  575. option = models.ForeignKey('catalogue.Option', verbose_name=_("Option"))
  576. value = models.CharField(_("Value"), max_length=255)
  577. class Meta:
  578. abstract = True
  579. verbose_name = _('Line attribute')
  580. verbose_name_plural = _('Line attributes')