Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

abstract_models.py 20KB

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