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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. from decimal import Decimal
  2. import zlib
  3. import datetime
  4. from django.db import models
  5. from django.utils.translation import ugettext as _
  6. from django.core.exceptions import ObjectDoesNotExist, PermissionDenied
  7. from oscar.apps.basket.managers import OpenBasketManager, SavedBasketManager
  8. # Basket statuses
  9. # - Frozen is for when a basket is in the process of being submitted
  10. # and we need to prevent any changes to it.
  11. OPEN, MERGED, SAVED, FROZEN, SUBMITTED = ("Open", "Merged", "Saved", "Frozen", "Submitted")
  12. class AbstractBasket(models.Model):
  13. u"""Basket object"""
  14. # Baskets can be anonymously owned (which are merged if the user signs in)
  15. owner = models.ForeignKey('auth.User', related_name='baskets', null=True)
  16. STATUS_CHOICES = (
  17. (OPEN, _("Open - currently active")),
  18. (MERGED, _("Merged - superceded by another basket")),
  19. (SAVED, _("Saved - for items to be purchased later")),
  20. (FROZEN, _("Frozen - the basket cannot be modified")),
  21. (SUBMITTED, _("Submitted - has been ordered at the checkout")),
  22. )
  23. status = models.CharField(_("Status"), max_length=128, default=OPEN, choices=STATUS_CHOICES)
  24. vouchers = models.ManyToManyField('offer.Voucher')
  25. date_created = models.DateTimeField(auto_now_add=True)
  26. date_merged = models.DateTimeField(null=True, blank=True)
  27. date_submitted = models.DateTimeField(null=True, blank=True)
  28. # Cached queryset of lines
  29. _lines = None
  30. discounts = []
  31. class Meta:
  32. abstract = True
  33. objects = models.Manager()
  34. open = OpenBasketManager()
  35. saved = SavedBasketManager()
  36. def __unicode__(self):
  37. return u"%s basket (owner: %s, lines: %d)" % (self.status, self.owner, self.num_lines)
  38. def all_lines(self):
  39. if not self._lines:
  40. self._lines = self.lines.all()
  41. return self._lines
  42. # ============
  43. # Manipulation
  44. # ============
  45. def flush(self):
  46. u"""Remove all lines from basket."""
  47. if self.status == FROZEN:
  48. raise PermissionDenied("A frozen basket cannot be flushed")
  49. self.lines_all().delete()
  50. def add_product(self, item, quantity=1, options=[]):
  51. u"""
  52. Convenience method for adding products to a basket
  53. The 'options' list should contains dicts with keys 'option' and 'value'
  54. which link the relevant product.Option model and string value respectively.
  55. """
  56. if not self.id:
  57. self.save()
  58. line_ref = self._create_line_reference(item, options)
  59. try:
  60. line = self.lines.get(line_reference=line_ref)
  61. line.quantity += quantity
  62. line.save()
  63. except ObjectDoesNotExist:
  64. line = self.lines.create(basket=self, line_reference=line_ref, product=item, quantity=quantity)
  65. for option_dict in options:
  66. line.attributes.create(line=line, option=option_dict['option'], value=option_dict['value'])
  67. def set_discounts(self, discounts):
  68. u"""
  69. Sets the discounts that apply to this basket.
  70. This should be a list of dictionaries
  71. """
  72. self.discounts = discounts
  73. def merge_line(self, line):
  74. u"""
  75. For transferring a line from another basket to this one.
  76. This is used with the "Saved" basket functionality.
  77. """
  78. try:
  79. existing_line = self.lines.get(line_reference=line.line_reference)
  80. # Line already exists - bump its quantity and delete the old
  81. existing_line.quantity += line.quantity
  82. existing_line.save()
  83. line.delete()
  84. except ObjectDoesNotExist:
  85. # Line does not already exist - reassign its basket
  86. line.basket = self
  87. line.save()
  88. def merge(self, basket):
  89. """
  90. Merges another basket with this one.
  91. """
  92. for line_to_merge in basket.all_lines():
  93. self.merge_line(line_to_merge)
  94. basket.status = MERGED
  95. basket.date_merged = datetime.datetime.now()
  96. basket.save()
  97. def freeze(self):
  98. """
  99. Freezes the basket so it cannot be modified.
  100. """
  101. self.status = FROZEN
  102. self.save()
  103. def set_as_submitted(self):
  104. u"""Mark this basket as submitted."""
  105. self.status = SUBMITTED
  106. self.date_submitted = datetime.datetime.now()
  107. self.save()
  108. # =======
  109. # Helpers
  110. # =======
  111. def _create_line_reference(self, item, options):
  112. u"""
  113. Returns a reference string for a line based on the item
  114. and its options.
  115. """
  116. if not options:
  117. return item.id
  118. return "%d_%s" % (item.id, zlib.crc32(str(options)))
  119. def _get_total(self, property):
  120. u"""
  121. For executing a named method on each line of the basket
  122. and returning the total.
  123. """
  124. total = Decimal('0.00')
  125. for line in self.all_lines():
  126. total += getattr(line, property)
  127. return total
  128. # ==========
  129. # Properties
  130. # ==========
  131. @property
  132. def is_empty(self):
  133. u"""Return bool based on basket having 0 lines"""
  134. return self.num_lines == 0
  135. @property
  136. def total_excl_tax(self):
  137. u"""Return total line price excluding tax"""
  138. return self._get_total('line_price_excl_tax_and_discounts')
  139. @property
  140. def total_tax(self):
  141. u"""Return total tax for a line"""
  142. return self._get_total('line_tax')
  143. @property
  144. def total_incl_tax(self):
  145. u"""Return total price for a line including tax"""
  146. return self._get_total('line_price_incl_tax_and_discounts')
  147. @property
  148. def num_lines(self):
  149. u"""Return number of lines"""
  150. return self.all_lines().count()
  151. @property
  152. def num_items(self):
  153. u"""Return number of items"""
  154. return reduce(lambda num,line: num+line.quantity, self.all_lines(), 0)
  155. @property
  156. def num_items_without_discount(self):
  157. u"""Return number of items"""
  158. num = 0
  159. for line in self.all_lines():
  160. num += line.quantity_without_discount
  161. return num
  162. @property
  163. def time_before_submit(self):
  164. if not self.date_submitted:
  165. return None
  166. return self.date_submitted - self.date_created
  167. @property
  168. def time_since_creation(self, test_datetime=None):
  169. if not test_datetime:
  170. test_datetime = datetime.datetime.now()
  171. return test_datetime - self.date_created
  172. class AbstractLine(models.Model):
  173. u"""A line of a basket (product and a quantity)"""
  174. basket = models.ForeignKey('basket.Basket', related_name='lines')
  175. # This is to determine which products belong to the same line
  176. # We can't just use product.id as you can have customised products
  177. # which should be treated as separate lines. Set as a
  178. # SlugField as it is included in the path for certain views.
  179. line_reference = models.SlugField(max_length=128, db_index=True)
  180. product = models.ForeignKey('product.Item', related_name='basket_lines')
  181. quantity = models.PositiveIntegerField(default=1)
  182. # Instance variables used to persist discount information
  183. _discount_field = 'price_excl_tax'
  184. _discount = Decimal('0.00')
  185. _affected_quantity = 0
  186. class Meta:
  187. abstract = True
  188. unique_together = ("basket", "line_reference")
  189. def __unicode__(self):
  190. return u"%s, Product '%s', quantity %d" % (self.basket, self.product, self.quantity)
  191. def save(self, *args, **kwargs):
  192. u"""Saves a line or deletes if it's quanity is 0"""
  193. if self.basket.status not in (OPEN, SAVED):
  194. raise PermissionDenied("You cannot modify a %s basket" % self.basket.status.lower())
  195. if self.quantity == 0:
  196. return self.delete(*args, **kwargs)
  197. super(AbstractLine, self).save(*args, **kwargs)
  198. # =============
  199. # Offer methods
  200. # =============
  201. def discount(self, discount_value, affected_quantity):
  202. self._discount += discount_value
  203. self._affected_quantity += affected_quantity
  204. def consume(self, quantity):
  205. self._affected_quantity += quantity
  206. def get_price_breakdown(self):
  207. u"""
  208. Returns a breakdown of line prices after discounts have
  209. been applied.
  210. """
  211. prices = []
  212. if not self.has_discount:
  213. prices.append((self.unit_price_incl_tax, self.unit_price_excl_tax, self.quantity))
  214. else:
  215. # Need to split the discount among the affected quantity
  216. # of products.
  217. item_incl_tax_discount = self._discount / self._affected_quantity
  218. item_excl_tax_discount = item_incl_tax_discount * self._tax_ratio
  219. prices.append((self.unit_price_incl_tax - item_incl_tax_discount,
  220. self.unit_price_excl_tax - item_excl_tax_discount,
  221. self._affected_quantity))
  222. if self.quantity_without_discount:
  223. prices.append((self.unit_price_incl_tax, self.unit_price_excl_tax, self.quantity_without_discount))
  224. return prices
  225. # =======
  226. # Helpers
  227. # =======
  228. def _get_stockrecord_property(self, property):
  229. if not self.product.stockrecord:
  230. return None
  231. else:
  232. return getattr(self.product.stockrecord, property)
  233. @property
  234. def _tax_ratio(self):
  235. return self.unit_price_excl_tax / self.unit_price_incl_tax
  236. # ==========
  237. # Properties
  238. # ==========
  239. @property
  240. def has_discount(self):
  241. return self.quantity > self.quantity_without_discount
  242. @property
  243. def quantity_without_discount(self):
  244. return self.quantity - self._affected_quantity
  245. @property
  246. def is_available_for_discount(self):
  247. return self.quantity_without_discount > 0
  248. @property
  249. def discount_value(self):
  250. return self._discount
  251. @property
  252. def unit_price_excl_tax(self):
  253. u"""Return unit price excluding tax"""
  254. return self._get_stockrecord_property('price_excl_tax')
  255. @property
  256. def unit_tax(self):
  257. u"""Return tax of a unit"""
  258. return self._get_stockrecord_property('price_tax')
  259. @property
  260. def unit_price_incl_tax(self):
  261. u"""Return unit price including tax"""
  262. return self._get_stockrecord_property('price_incl_tax')
  263. @property
  264. def line_price_excl_tax(self):
  265. u"""Return line price excluding tax"""
  266. return self.quantity * self.unit_price_excl_tax
  267. @property
  268. def line_price_excl_tax_and_discounts(self):
  269. return self.line_price_excl_tax - self._discount * self._tax_ratio
  270. @property
  271. def line_tax(self):
  272. u"""Return line tax"""
  273. return self.quantity * self.unit_tax
  274. @property
  275. def line_price_incl_tax(self):
  276. u"""Return line price including tax"""
  277. return self.quantity * self.unit_price_incl_tax
  278. @property
  279. def line_price_incl_tax_and_discounts(self):
  280. return self.line_price_incl_tax - self._discount
  281. @property
  282. def description(self):
  283. u"""Return product description"""
  284. d = str(self.product)
  285. ops = []
  286. for attribute in self.attributes.all():
  287. ops.append("%s = '%s'" % (attribute.option.name, attribute.value))
  288. if ops:
  289. d = "%s (%s)" % (d, ", ".join(ops))
  290. return d
  291. class AbstractLineAttribute(models.Model):
  292. u"""An attribute of a basket line"""
  293. line = models.ForeignKey('basket.Line', related_name='attributes')
  294. option = models.ForeignKey('product.option')
  295. value = models.CharField(_("Value"), max_length=255)
  296. class Meta:
  297. abstract = True