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.

models.py 51KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469
  1. from decimal import Decimal as D, ROUND_DOWN, ROUND_UP
  2. from django.core import exceptions
  3. from django.db.models import get_model
  4. from django.template.defaultfilters import date
  5. from django.db import models
  6. from django.utils.timezone import now
  7. from django.utils.translation import ungettext, ugettext as _
  8. from django.utils.importlib import import_module
  9. from django.core.exceptions import ValidationError
  10. from django.core.urlresolvers import reverse
  11. from django.conf import settings
  12. from oscar.core.utils import slugify
  13. from oscar.apps.offer.managers import ActiveOfferManager
  14. from oscar.templatetags.currency_filters import currency
  15. from oscar.models.fields import PositiveDecimalField, ExtendedURLField
  16. def load_proxy(proxy_class):
  17. module, classname = proxy_class.rsplit('.', 1)
  18. try:
  19. mod = import_module(module)
  20. except ImportError, e:
  21. raise exceptions.ImproperlyConfigured(
  22. "Error importing module %s: %s" % (module, e))
  23. try:
  24. return getattr(mod, classname)
  25. except AttributeError:
  26. raise exceptions.ImproperlyConfigured(
  27. "Module %s does not define a %s" % (module, classname))
  28. def range_anchor(range):
  29. return '<a href="%s">%s</a>' % (
  30. reverse('dashboard:range-update', kwargs={'pk': range.pk}),
  31. range.name)
  32. class ConditionalOffer(models.Model):
  33. """
  34. A conditional offer (eg buy 1, get 10% off)
  35. """
  36. name = models.CharField(
  37. _("Name"), max_length=128, unique=True,
  38. help_text=_("This is displayed within the customer's basket"))
  39. slug = models.SlugField(_("Slug"), max_length=128, unique=True, null=True)
  40. description = models.TextField(_("Description"), blank=True,
  41. help_text=_("This is displayed on the offer browsing page"))
  42. # Offers come in a few different types:
  43. # (a) Offers that are available to all customers on the site. Eg a
  44. # 3-for-2 offer.
  45. # (b) Offers that are linked to a voucher, and only become available once
  46. # that voucher has been applied to the basket
  47. # (c) Offers that are linked to a user. Eg, all students get 10% off. The
  48. # code to apply this offer needs to be coded
  49. # (d) Session offers - these are temporarily available to a user after some
  50. # trigger event. Eg, users coming from some affiliate site get 10%
  51. # off.
  52. SITE, VOUCHER, USER, SESSION = ("Site", "Voucher", "User", "Session")
  53. TYPE_CHOICES = (
  54. (SITE, _("Site offer - available to all users")),
  55. (VOUCHER, _("Voucher offer - only available after entering "
  56. "the appropriate voucher code")),
  57. (USER, _("User offer - available to certain types of user")),
  58. (SESSION, _("Session offer - temporary offer, available for "
  59. "a user for the duration of their session")),
  60. )
  61. offer_type = models.CharField(
  62. _("Type"), choices=TYPE_CHOICES, default=SITE, max_length=128)
  63. # We track a status variable so it's easier to load offers that are
  64. # 'available' in some sense.
  65. OPEN, SUSPENDED, CONSUMED = "Open", "Suspended", "Consumed"
  66. status = models.CharField(_("Status"), max_length=64, default=OPEN)
  67. condition = models.ForeignKey(
  68. 'offer.Condition', verbose_name=_("Condition"))
  69. benefit = models.ForeignKey('offer.Benefit', verbose_name=_("Benefit"))
  70. # Some complicated situations require offers to be applied in a set order.
  71. priority = models.IntegerField(_("Priority"), default=0,
  72. help_text=_("The highest priority offers are applied first"))
  73. # AVAILABILITY
  74. # Range of availability. Note that if this is a voucher offer, then these
  75. # dates are ignored and only the dates from the voucher are used to
  76. # determine availability.
  77. start_datetime = models.DateTimeField(_("Start date"), blank=True, null=True)
  78. end_datetime = models.DateTimeField(
  79. _("End date"), blank=True, null=True,
  80. help_text=_("Offers are active until the end of the 'end date'"))
  81. # Use this field to limit the number of times this offer can be applied in
  82. # total. Note that a single order can apply an offer multiple times so
  83. # this is not the same as the number of orders that can use it.
  84. max_global_applications = models.PositiveIntegerField(
  85. _("Max global applications"),
  86. help_text=_("The number of times this offer can be used before it "
  87. "is unavailable"), blank=True, null=True)
  88. # Use this field to limit the number of times this offer can be used by a
  89. # single user. This only works for signed-in users - it doesn't really
  90. # make sense for sites that allow anonymous checkout.
  91. max_user_applications = models.PositiveIntegerField(
  92. _("Max user applications"),
  93. help_text=_("The number of times a single user can use this offer"),
  94. blank=True, null=True)
  95. # Use this field to limit the number of times this offer can be applied to
  96. # a basket (and hence a single order).
  97. max_basket_applications = models.PositiveIntegerField(
  98. _("Max basket applications"),
  99. blank=True, null=True,
  100. help_text=_("The number of times this offer can be applied to a "
  101. "basket (and order)"))
  102. # Use this field to limit the amount of discount an offer can lead to.
  103. # This can be helpful with budgeting.
  104. max_discount = models.DecimalField(
  105. _("Max discount"), decimal_places=2, max_digits=12, null=True,
  106. blank=True,
  107. help_text=_("When an offer has given more discount to orders "
  108. "than this threshold, then the offer becomes "
  109. "unavailable"))
  110. # TRACKING
  111. total_discount = models.DecimalField(
  112. _("Total Discount"), decimal_places=2, max_digits=12,
  113. default=D('0.00'))
  114. num_applications = models.PositiveIntegerField(
  115. _("Number of applications"), default=0)
  116. num_orders = models.PositiveIntegerField(
  117. _("Number of Orders"), default=0)
  118. redirect_url = ExtendedURLField(_("URL redirect (optional)"), blank=True)
  119. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  120. objects = models.Manager()
  121. active = ActiveOfferManager()
  122. # We need to track the voucher that this offer came from (if it is a
  123. # voucher offer)
  124. _voucher = None
  125. class Meta:
  126. ordering = ['-priority']
  127. verbose_name = _("Conditional offer")
  128. verbose_name_plural = _("Conditional offers")
  129. # The way offers are looked up involves the fields (offer_type, status,
  130. # start_datetime, end_datetime). Ideally, you want a DB index that
  131. # covers these 4 fields (will add support for this in Django 1.5)
  132. def save(self, *args, **kwargs):
  133. if not self.slug:
  134. self.slug = slugify(self.name)
  135. # Check to see if consumption thresholds have been broken
  136. if not self.is_suspended:
  137. if self.get_max_applications() == 0:
  138. self.status = self.CONSUMED
  139. else:
  140. self.status = self.OPEN
  141. return super(ConditionalOffer, self).save(*args, **kwargs)
  142. def get_absolute_url(self):
  143. return reverse('offer:detail', kwargs={'slug': self.slug})
  144. def __unicode__(self):
  145. return self.name
  146. def clean(self):
  147. if (self.start_datetime and self.end_datetime and
  148. self.start_datetime > self.end_datetime):
  149. raise exceptions.ValidationError(
  150. _('End date should be later than start date'))
  151. @property
  152. def is_open(self):
  153. return self.status == self.OPEN
  154. @property
  155. def is_suspended(self):
  156. return self.status == self.SUSPENDED
  157. def suspend(self):
  158. self.status = self.SUSPENDED
  159. self.save()
  160. suspend.alters_data = True
  161. def unsuspend(self):
  162. self.status = self.OPEN
  163. self.save()
  164. suspend.alters_data = True
  165. def is_available(self, user=None, test_date=None):
  166. """
  167. Test whether this offer is available to be used
  168. """
  169. if self.is_suspended:
  170. return False
  171. if test_date is None:
  172. test_date = now()
  173. predicates = []
  174. if self.start_datetime:
  175. predicates.append(self.start_datetime > test_date)
  176. if self.end_datetime:
  177. predicates.append(test_date > self.end_datetime)
  178. if any(predicates):
  179. return 0
  180. return self.get_max_applications(user) > 0
  181. def is_condition_satisfied(self, basket):
  182. return self.condition.proxy().is_satisfied(basket)
  183. def is_condition_partially_satisfied(self, basket):
  184. return self.condition.proxy().is_partially_satisfied(basket)
  185. def get_upsell_message(self, basket):
  186. return self.condition.proxy().get_upsell_message(basket)
  187. def apply_benefit(self, basket):
  188. """
  189. Applies the benefit to the given basket and returns the discount.
  190. """
  191. if not self.is_condition_satisfied(basket):
  192. return ZERO_DISCOUNT
  193. return self.benefit.proxy().apply(
  194. basket, self.condition.proxy(), self)
  195. def apply_deferred_benefit(self, basket):
  196. """
  197. Applies any deferred benefits. These are things like adding loyalty
  198. points to somone's account.
  199. """
  200. return self.benefit.proxy().apply_deferred(basket)
  201. def set_voucher(self, voucher):
  202. self._voucher = voucher
  203. def get_voucher(self):
  204. return self._voucher
  205. def get_max_applications(self, user=None):
  206. """
  207. Return the number of times this offer can be applied to a basket for a
  208. given user.
  209. """
  210. if self.max_discount and self.total_discount >= self.max_discount:
  211. return 0
  212. # Hard-code a maximum value as we need some sensible upper limit for
  213. # when there are not other caps.
  214. limits = [10000]
  215. if self.max_user_applications and user:
  216. limits.append(max(0, self.max_user_applications -
  217. self.get_num_user_applications(user)))
  218. if self.max_basket_applications:
  219. limits.append(self.max_basket_applications)
  220. if self.max_global_applications:
  221. limits.append(
  222. max(0, self.max_global_applications - self.num_applications))
  223. return min(limits)
  224. def get_num_user_applications(self, user):
  225. OrderDiscount = models.get_model('order', 'OrderDiscount')
  226. aggregates = OrderDiscount.objects.filter(
  227. offer_id=self.id, order__user=user).aggregate(
  228. total=models.Sum('frequency'))
  229. return aggregates['total'] if aggregates['total'] is not None else 0
  230. def shipping_discount(self, charge):
  231. return self.benefit.proxy().shipping_discount(charge)
  232. def record_usage(self, discount):
  233. self.num_applications += discount['freq']
  234. self.total_discount += discount['discount']
  235. self.num_orders += 1
  236. self.save()
  237. record_usage.alters_data = True
  238. def availability_description(self):
  239. """
  240. Return a description of when this offer is available
  241. """
  242. restrictions = self.availability_restrictions()
  243. descriptions = [r['description'] for r in restrictions]
  244. return "<br/>".join(descriptions)
  245. def availability_restrictions(self):
  246. restrictions = []
  247. if self.is_suspended:
  248. restrictions.append({
  249. 'description': _("Offer is suspended"),
  250. 'is_satisfied': False})
  251. if self.max_global_applications:
  252. remaining = self.max_global_applications - self.num_applications
  253. desc = _(
  254. "Limited to %(total)d uses "
  255. "(%(remainder)d remaining)") % {
  256. 'total': self.max_global_applications,
  257. 'remainder': remaining}
  258. restrictions.append({
  259. 'description': desc,
  260. 'is_satisfied': remaining > 0})
  261. if self.max_user_applications:
  262. if self.max_user_applications == 1:
  263. desc = _("Limited to 1 use per user")
  264. else:
  265. desc = _(
  266. "Limited to %(total)d uses per user") % {
  267. 'total': self.max_user_applications}
  268. restrictions.append({
  269. 'description': desc,
  270. 'is_satisfied': True})
  271. if self.max_basket_applications:
  272. if self.max_user_applications == 1:
  273. desc = _("Limited to 1 use per basket")
  274. else:
  275. desc = _(
  276. "Limited to %(total)d uses per basket") % {
  277. 'total': self.max_basket_applications}
  278. restrictions.append({
  279. 'description': desc,
  280. 'is_satisfied': True})
  281. def format_datetime(dt):
  282. # Only show hours/minutes if they have been specified
  283. if dt.hour == 0 and dt.minute == 0:
  284. return date(dt, settings.DATE_FORMAT)
  285. return date(dt, settings.DATETIME_FORMAT)
  286. if self.start_datetime or self.end_datetime:
  287. today = now()
  288. if self.start_datetime and self.end_datetime:
  289. desc = _("Available between %(start)s and %(end)s") % {
  290. 'start': format_datetime(self.start_datetime),
  291. 'end': format_datetime(self.end_datetime)}
  292. is_satisfied = self.start_datetime <= today <= self.end_datetime
  293. elif self.start_datetime:
  294. desc = _("Available from %(start)s") % {
  295. 'start': format_datetime(self.start_datetime)}
  296. is_satisfied = today >= self.start_datetime
  297. elif self.end_datetime:
  298. desc = _("Available until %(end)s") % {
  299. 'end': format_datetime(self.end_datetime)}
  300. is_satisfied = today <= self.end_datetime
  301. restrictions.append({
  302. 'description': desc,
  303. 'is_satisfied': is_satisfied})
  304. if self.max_discount:
  305. desc = _("Limited to a cost of %(max)s") % {
  306. 'max': currency(self.max_discount)}
  307. restrictions.append({
  308. 'description': desc,
  309. 'is_satisfied': self.total_discount < self.max_discount})
  310. return restrictions
  311. @property
  312. def has_products(self):
  313. return self.condition.range is not None
  314. def products(self):
  315. """
  316. Return a queryset of products in this offer
  317. """
  318. Product = get_model('catalogue', 'Product')
  319. if not self.has_products:
  320. return Product.objects.none()
  321. cond_range = self.condition.range
  322. if cond_range.includes_all_products:
  323. # Return ALL the products
  324. return Product.browsable.select_related(
  325. 'product_class', 'stockrecord').filter(
  326. is_discountable=True).prefetch_related(
  327. 'variants', 'images', 'product_class__options',
  328. 'product_options')
  329. return cond_range.included_products.filter(is_discountable=True)
  330. class Condition(models.Model):
  331. COUNT, VALUE, COVERAGE = ("Count", "Value", "Coverage")
  332. TYPE_CHOICES = (
  333. (COUNT, _("Depends on number of items in basket that are in "
  334. "condition range")),
  335. (VALUE, _("Depends on value of items in basket that are in "
  336. "condition range")),
  337. (COVERAGE, _("Needs to contain a set number of DISTINCT items "
  338. "from the condition range")))
  339. range = models.ForeignKey(
  340. 'offer.Range', verbose_name=_("Range"), null=True, blank=True)
  341. type = models.CharField(_('Type'), max_length=128, choices=TYPE_CHOICES,
  342. null=True, blank=True)
  343. value = PositiveDecimalField(_('Value'), decimal_places=2, max_digits=12,
  344. null=True, blank=True)
  345. proxy_class = models.CharField(_("Custom class"), null=True, blank=True,
  346. max_length=255, unique=True, default=None)
  347. class Meta:
  348. verbose_name = _("Condition")
  349. verbose_name_plural = _("Conditions")
  350. def proxy(self):
  351. """
  352. Return the proxy model
  353. """
  354. field_dict = dict(self.__dict__)
  355. for field in field_dict.keys():
  356. if field.startswith('_'):
  357. del field_dict[field]
  358. if self.proxy_class:
  359. klass = load_proxy(self.proxy_class)
  360. return klass(**field_dict)
  361. klassmap = {
  362. self.COUNT: CountCondition,
  363. self.VALUE: ValueCondition,
  364. self.COVERAGE: CoverageCondition}
  365. if self.type in klassmap:
  366. return klassmap[self.type](**field_dict)
  367. return self
  368. def __unicode__(self):
  369. return self.proxy().name
  370. @property
  371. def name(self):
  372. return self.description
  373. @property
  374. def description(self):
  375. return self.proxy().description
  376. def consume_items(self, basket, affected_lines):
  377. pass
  378. def is_satisfied(self, basket):
  379. """
  380. Determines whether a given basket meets this condition. This is
  381. stubbed in this top-class object. The subclassing proxies are
  382. responsible for implementing it correctly.
  383. """
  384. return False
  385. def is_partially_satisfied(self, basket):
  386. """
  387. Determine if the basket partially meets the condition. This is useful
  388. for up-selling messages to entice customers to buy something more in
  389. order to qualify for an offer.
  390. """
  391. return False
  392. def get_upsell_message(self, basket):
  393. return None
  394. def can_apply_condition(self, product):
  395. """
  396. Determines whether the condition can be applied to a given product
  397. """
  398. return (self.range.contains_product(product)
  399. and product.is_discountable and product.has_stockrecord)
  400. def get_applicable_lines(self, basket, most_expensive_first=True):
  401. """
  402. Return line data for the lines that can be consumed by this condition
  403. """
  404. line_tuples = []
  405. for line in basket.all_lines():
  406. product = line.product
  407. if not self.can_apply_condition(product):
  408. continue
  409. price = line.unit_price_incl_tax
  410. if not price:
  411. continue
  412. line_tuples.append((price, line))
  413. if most_expensive_first:
  414. return sorted(line_tuples, reverse=True)
  415. return sorted(line_tuples)
  416. class Benefit(models.Model):
  417. range = models.ForeignKey(
  418. 'offer.Range', null=True, blank=True, verbose_name=_("Range"))
  419. # Benefit types
  420. PERCENTAGE, FIXED, MULTIBUY, FIXED_PRICE = (
  421. "Percentage", "Absolute", "Multibuy", "Fixed price")
  422. SHIPPING_PERCENTAGE, SHIPPING_ABSOLUTE, SHIPPING_FIXED_PRICE = (
  423. 'Shipping percentage', 'Shipping absolute', 'Shipping fixed price')
  424. TYPE_CHOICES = (
  425. (PERCENTAGE, _("Discount is a percentage off of the product's value")),
  426. (FIXED, _("Discount is a fixed amount off of the product's value")),
  427. (MULTIBUY, _("Discount is to give the cheapest product for free")),
  428. (FIXED_PRICE,
  429. _("Get the products that meet the condition for a fixed price")),
  430. (SHIPPING_ABSOLUTE,
  431. _("Discount is a fixed amount of the shipping cost")),
  432. (SHIPPING_FIXED_PRICE, _("Get shipping for a fixed price")),
  433. (SHIPPING_PERCENTAGE, _("Discount is a percentage off of the shipping cost")),
  434. )
  435. type = models.CharField(
  436. _("Type"), max_length=128, choices=TYPE_CHOICES, blank=True)
  437. # The value to use with the designated type. This can be either an integer
  438. # (eg for multibuy) or a decimal (eg an amount) which is slightly
  439. # confusing.
  440. value = PositiveDecimalField(
  441. _("Value"), decimal_places=2, max_digits=12, null=True, blank=True)
  442. # If this is not set, then there is no upper limit on how many products
  443. # can be discounted by this benefit.
  444. max_affected_items = models.PositiveIntegerField(
  445. _("Max Affected Items"), blank=True, null=True,
  446. help_text=_("Set this to prevent the discount consuming all items "
  447. "within the range that are in the basket."))
  448. # A custom benefit class can be used instead. This means the
  449. # type/value/max_affected_items fields should all be None.
  450. proxy_class = models.CharField(_("Custom class"), null=True, blank=True,
  451. max_length=255, unique=True, default=None)
  452. class Meta:
  453. verbose_name = _("Benefit")
  454. verbose_name_plural = _("Benefits")
  455. def proxy(self):
  456. field_dict = dict(self.__dict__)
  457. for field in field_dict.keys():
  458. if field.startswith('_'):
  459. del field_dict[field]
  460. if self.proxy_class:
  461. klass = load_proxy(self.proxy_class)
  462. return klass(**field_dict)
  463. klassmap = {
  464. self.PERCENTAGE: PercentageDiscountBenefit,
  465. self.FIXED: AbsoluteDiscountBenefit,
  466. self.MULTIBUY: MultibuyDiscountBenefit,
  467. self.FIXED_PRICE: FixedPriceBenefit,
  468. self.SHIPPING_ABSOLUTE: ShippingAbsoluteDiscountBenefit,
  469. self.SHIPPING_FIXED_PRICE: ShippingFixedPriceBenefit,
  470. self.SHIPPING_PERCENTAGE: ShippingPercentageDiscountBenefit}
  471. if self.type in klassmap:
  472. return klassmap[self.type](**field_dict)
  473. raise RuntimeError("Unrecognised benefit type (%s)" % self.type)
  474. def __unicode__(self):
  475. name = self.proxy().name
  476. if self.max_affected_items:
  477. name += ungettext(
  478. " (max %d item)",
  479. " (max %d items)",
  480. self.max_affected_items) % self.max_affected_items
  481. return name
  482. @property
  483. def name(self):
  484. return self.description
  485. @property
  486. def description(self):
  487. return self.proxy().description
  488. def apply(self, basket, condition, offer=None):
  489. return ZERO_DISCOUNT
  490. def apply_deferred(self, basket):
  491. return None
  492. def clean(self):
  493. if not self.type:
  494. return
  495. method_name = 'clean_%s' % self.type.lower().replace(' ', '_')
  496. if hasattr(self, method_name):
  497. getattr(self, method_name)()
  498. def clean_multibuy(self):
  499. if not self.range:
  500. raise ValidationError(
  501. _("Multibuy benefits require a product range"))
  502. if self.value:
  503. raise ValidationError(
  504. _("Multibuy benefits don't require a value"))
  505. if self.max_affected_items:
  506. raise ValidationError(
  507. _("Multibuy benefits don't require a 'max affected items' "
  508. "attribute"))
  509. def clean_percentage(self):
  510. if not self.range:
  511. raise ValidationError(
  512. _("Percentage benefits require a product range"))
  513. if self.value > 100:
  514. raise ValidationError(
  515. _("Percentage discount cannot be greater than 100"))
  516. def clean_shipping_absolute(self):
  517. if not self.value:
  518. raise ValidationError(
  519. _("A discount value is required"))
  520. if self.range:
  521. raise ValidationError(
  522. _("No range should be selected as this benefit does not "
  523. "apply to products"))
  524. if self.max_affected_items:
  525. raise ValidationError(
  526. _("Shipping discounts don't require a 'max affected items' "
  527. "attribute"))
  528. def clean_shipping_percentage(self):
  529. if self.value > 100:
  530. raise ValidationError(
  531. _("Percentage discount cannot be greater than 100"))
  532. if self.range:
  533. raise ValidationError(
  534. _("No range should be selected as this benefit does not "
  535. "apply to products"))
  536. if self.max_affected_items:
  537. raise ValidationError(
  538. _("Shipping discounts don't require a 'max affected items' "
  539. "attribute"))
  540. def clean_shipping_fixed_price(self):
  541. if self.range:
  542. raise ValidationError(
  543. _("No range should be selected as this benefit does not "
  544. "apply to products"))
  545. if self.max_affected_items:
  546. raise ValidationError(
  547. _("Shipping discounts don't require a 'max affected items' "
  548. "attribute"))
  549. def clean_fixed_price(self):
  550. if self.range:
  551. raise ValidationError(
  552. _("No range should be selected as the condition range will "
  553. "be used instead."))
  554. def clean_absolute(self):
  555. if not self.range:
  556. raise ValidationError(
  557. _("Fixed discount benefits require a product range"))
  558. if not self.value:
  559. raise ValidationError(
  560. _("Fixed discount benefits require a value"))
  561. def round(self, amount):
  562. """
  563. Apply rounding to discount amount
  564. """
  565. if hasattr(settings, 'OSCAR_OFFER_ROUNDING_FUNCTION'):
  566. return settings.OSCAR_OFFER_ROUNDING_FUNCTION(amount)
  567. return amount.quantize(D('.01'), ROUND_DOWN)
  568. def _effective_max_affected_items(self):
  569. """
  570. Return the maximum number of items that can have a discount applied
  571. during the application of this benefit
  572. """
  573. return self.max_affected_items if self.max_affected_items else 10000
  574. def can_apply_benefit(self, product):
  575. """
  576. Determines whether the benefit can be applied to a given product
  577. """
  578. return product.has_stockrecord and product.is_discountable
  579. def get_applicable_lines(self, basket, range=None):
  580. """
  581. Return the basket lines that are available to be discounted
  582. :basket: The basket
  583. :range: The range of products to use for filtering. The fixed-price
  584. benefit ignores its range and uses the condition range
  585. """
  586. if range is None:
  587. range = self.range
  588. line_tuples = []
  589. for line in basket.all_lines():
  590. product = line.product
  591. if (not range.contains(product) or
  592. not self.can_apply_benefit(product)):
  593. continue
  594. price = line.unit_price_incl_tax
  595. if not price:
  596. # Avoid zero price products
  597. continue
  598. if line.quantity_without_discount == 0:
  599. continue
  600. line_tuples.append((price, line))
  601. # We sort lines to be cheapest first to ensure consistent applications
  602. return sorted(line_tuples)
  603. def shipping_discount(self, charge):
  604. return D('0.00')
  605. class Range(models.Model):
  606. """
  607. Represents a range of products that can be used within an offer
  608. """
  609. name = models.CharField(_("Name"), max_length=128, unique=True)
  610. includes_all_products = models.BooleanField(
  611. _('Includes All Products'), default=False)
  612. included_products = models.ManyToManyField(
  613. 'catalogue.Product', related_name='includes', blank=True,
  614. verbose_name=_("Included Products"))
  615. excluded_products = models.ManyToManyField(
  616. 'catalogue.Product', related_name='excludes', blank=True,
  617. verbose_name=_("Excluded Products"))
  618. classes = models.ManyToManyField(
  619. 'catalogue.ProductClass', related_name='classes', blank=True,
  620. verbose_name=_("Product Classes"))
  621. included_categories = models.ManyToManyField(
  622. 'catalogue.Category', related_name='includes', blank=True,
  623. verbose_name=_("Included Categories"))
  624. # Allow a custom range instance to be specified
  625. proxy_class = models.CharField(
  626. _("Custom class"), null=True, blank=True, max_length=255,
  627. default=None, unique=True)
  628. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  629. __included_product_ids = None
  630. __excluded_product_ids = None
  631. __class_ids = None
  632. class Meta:
  633. verbose_name = _("Range")
  634. verbose_name_plural = _("Ranges")
  635. def __unicode__(self):
  636. return self.name
  637. def contains_product(self, product):
  638. """
  639. Check whether the passed product is part of this range
  640. """
  641. # We look for shortcircuit checks first before
  642. # the tests that require more database queries.
  643. if settings.OSCAR_OFFER_BLACKLIST_PRODUCT and \
  644. settings.OSCAR_OFFER_BLACKLIST_PRODUCT(product):
  645. return False
  646. # Delegate to a proxy class if one is provided
  647. if self.proxy_class:
  648. return load_proxy(self.proxy_class)().contains_product(product)
  649. excluded_product_ids = self._excluded_product_ids()
  650. if product.id in excluded_product_ids:
  651. return False
  652. if self.includes_all_products:
  653. return True
  654. if product.product_class_id in self._class_ids():
  655. return True
  656. included_product_ids = self._included_product_ids()
  657. if product.id in included_product_ids:
  658. return True
  659. test_categories = self.included_categories.all()
  660. if test_categories:
  661. for category in product.categories.all():
  662. for test_category in test_categories:
  663. if category == test_category or category.is_descendant_of(test_category):
  664. return True
  665. return False
  666. # Shorter alias
  667. contains = contains_product
  668. def _included_product_ids(self):
  669. if self.__included_product_ids is None:
  670. self.__included_product_ids = [row['id'] for row in self.included_products.values('id')]
  671. return self.__included_product_ids
  672. def _excluded_product_ids(self):
  673. if not self.id:
  674. return []
  675. if self.__excluded_product_ids is None:
  676. self.__excluded_product_ids = [row['id'] for row in self.excluded_products.values('id')]
  677. return self.__excluded_product_ids
  678. def _class_ids(self):
  679. if None == self.__class_ids:
  680. self.__class_ids = [row['id'] for row in self.classes.values('id')]
  681. return self.__class_ids
  682. def num_products(self):
  683. if self.includes_all_products:
  684. return None
  685. return self.included_products.all().count()
  686. @property
  687. def is_editable(self):
  688. """
  689. Test whether this product can be edited in the dashboard
  690. """
  691. return self.proxy_class is None
  692. # ==========
  693. # Conditions
  694. # ==========
  695. class CountCondition(Condition):
  696. """
  697. An offer condition dependent on the NUMBER of matching items from the
  698. basket.
  699. """
  700. _description = _("Basket includes %(count)d item(s) from %(range)s")
  701. @property
  702. def name(self):
  703. return self._description % {
  704. 'count': self.value,
  705. 'range': unicode(self.range).lower()}
  706. @property
  707. def description(self):
  708. return self._description % {
  709. 'count': self.value,
  710. 'range': range_anchor(self.range)}
  711. class Meta:
  712. proxy = True
  713. verbose_name = _("Count Condition")
  714. verbose_name_plural = _("Count Conditions")
  715. def is_satisfied(self, basket):
  716. """
  717. Determines whether a given basket meets this condition
  718. """
  719. num_matches = 0
  720. for line in basket.all_lines():
  721. if (self.can_apply_condition(line.product)
  722. and line.quantity_without_discount > 0):
  723. num_matches += line.quantity_without_discount
  724. if num_matches >= self.value:
  725. return True
  726. return False
  727. def _get_num_matches(self, basket):
  728. if hasattr(self, '_num_matches'):
  729. return getattr(self, '_num_matches')
  730. num_matches = 0
  731. for line in basket.all_lines():
  732. if (self.can_apply_condition(line.product)
  733. and line.quantity_without_discount > 0):
  734. num_matches += line.quantity_without_discount
  735. self._num_matches = num_matches
  736. return num_matches
  737. def is_partially_satisfied(self, basket):
  738. num_matches = self._get_num_matches(basket)
  739. return 0 < num_matches < self.value
  740. def get_upsell_message(self, basket):
  741. num_matches = self._get_num_matches(basket)
  742. delta = self.value - num_matches
  743. return ungettext('Buy %(delta)d more product from %(range)s',
  744. 'Buy %(delta)d more products from %(range)s', delta) % {
  745. 'delta': delta, 'range': self.range}
  746. def consume_items(self, basket, affected_lines):
  747. """
  748. Marks items within the basket lines as consumed so they
  749. can't be reused in other offers.
  750. :basket: The basket
  751. :affected_lines: The lines that have been affected by the discount.
  752. This should be list of tuples (line, discount, qty)
  753. """
  754. # We need to count how many items have already been consumed as part of
  755. # applying the benefit, so we don't consume too many items.
  756. num_consumed = 0
  757. for line, __, quantity in affected_lines:
  758. num_consumed += quantity
  759. to_consume = max(0, self.value - num_consumed)
  760. if to_consume == 0:
  761. return
  762. for __, line in self.get_applicable_lines(basket,
  763. most_expensive_first=True):
  764. quantity_to_consume = min(line.quantity_without_discount,
  765. to_consume)
  766. line.consume(quantity_to_consume)
  767. to_consume -= quantity_to_consume
  768. if to_consume == 0:
  769. break
  770. class CoverageCondition(Condition):
  771. """
  772. An offer condition dependent on the number of DISTINCT matching items from the basket.
  773. """
  774. _description = _("Basket includes %(count)d distinct item(s) from %(range)s")
  775. @property
  776. def name(self):
  777. return self._description % {
  778. 'count': self.value,
  779. 'range': unicode(self.range).lower()}
  780. @property
  781. def description(self):
  782. return self._description % {
  783. 'count': self.value,
  784. 'range': range_anchor(self.range)}
  785. class Meta:
  786. proxy = True
  787. verbose_name = _("Coverage Condition")
  788. verbose_name_plural = _("Coverage Conditions")
  789. def is_satisfied(self, basket):
  790. """
  791. Determines whether a given basket meets this condition
  792. """
  793. covered_ids = []
  794. for line in basket.all_lines():
  795. if not line.is_available_for_discount:
  796. continue
  797. product = line.product
  798. if (self.can_apply_condition(product) and product.id not in covered_ids):
  799. covered_ids.append(product.id)
  800. if len(covered_ids) >= self.value:
  801. return True
  802. return False
  803. def _get_num_covered_products(self, basket):
  804. covered_ids = []
  805. for line in basket.all_lines():
  806. if not line.is_available_for_discount:
  807. continue
  808. product = line.product
  809. if (self.can_apply_condition(product) and product.id not in covered_ids):
  810. covered_ids.append(product.id)
  811. return len(covered_ids)
  812. def get_upsell_message(self, basket):
  813. delta = self.value - self._get_num_covered_products(basket)
  814. return ungettext('Buy %(delta)d more product from %(range)s',
  815. 'Buy %(delta)d more products from %(range)s', delta) % {
  816. 'delta': delta, 'range': self.range}
  817. def is_partially_satisfied(self, basket):
  818. return 0 < self._get_num_covered_products(basket) < self.value
  819. def consume_items(self, basket, affected_lines):
  820. """
  821. Marks items within the basket lines as consumed so they
  822. can't be reused in other offers.
  823. """
  824. # Determine products that have already been consumed by applying the
  825. # benefit
  826. consumed_products = []
  827. for line, __, quantity in affected_lines:
  828. consumed_products.append(line.product)
  829. to_consume = max(0, self.value - len(consumed_products))
  830. if to_consume == 0:
  831. return
  832. for line in basket.all_lines():
  833. product = line.product
  834. if not self.can_apply_condition(product):
  835. continue
  836. if product in consumed_products:
  837. continue
  838. if not line.is_available_for_discount:
  839. continue
  840. # Only consume a quantity of 1 from each line
  841. line.consume(1)
  842. consumed_products.append(product)
  843. to_consume -= 1
  844. if to_consume == 0:
  845. break
  846. def get_value_of_satisfying_items(self, basket):
  847. covered_ids = []
  848. value = D('0.00')
  849. for line in basket.all_lines():
  850. if (self.can_apply_condition(line.product) and line.product.id not in covered_ids):
  851. covered_ids.append(line.product.id)
  852. value += line.unit_price_incl_tax
  853. if len(covered_ids) >= self.value:
  854. return value
  855. return value
  856. class ValueCondition(Condition):
  857. """
  858. An offer condition dependent on the VALUE of matching items from the
  859. basket.
  860. """
  861. _description = _("Basket includes %(amount)s from %(range)s")
  862. @property
  863. def name(self):
  864. return self._description % {
  865. 'amount': currency(self.value),
  866. 'range': unicode(self.range).lower()}
  867. @property
  868. def description(self):
  869. return self._description % {
  870. 'amount': currency(self.value),
  871. 'range': range_anchor(self.range)}
  872. class Meta:
  873. proxy = True
  874. verbose_name = _("Value Condition")
  875. verbose_name_plural = _("Value Conditions")
  876. def is_satisfied(self, basket):
  877. """
  878. Determine whether a given basket meets this condition
  879. """
  880. value_of_matches = D('0.00')
  881. for line in basket.all_lines():
  882. product = line.product
  883. if (self.can_apply_condition(product) and product.has_stockrecord
  884. and line.quantity_without_discount > 0):
  885. price = line.unit_price_incl_tax
  886. value_of_matches += price * int(line.quantity_without_discount)
  887. if value_of_matches >= self.value:
  888. return True
  889. return False
  890. def _get_value_of_matches(self, basket):
  891. if hasattr(self, '_value_of_matches'):
  892. return getattr(self, '_value_of_matches')
  893. value_of_matches = D('0.00')
  894. for line in basket.all_lines():
  895. product = line.product
  896. if (self.can_apply_condition(product) and product.has_stockrecord
  897. and line.quantity_without_discount > 0):
  898. price = line.unit_price_incl_tax
  899. value_of_matches += price * int(line.quantity_without_discount)
  900. self._value_of_matches = value_of_matches
  901. return value_of_matches
  902. def is_partially_satisfied(self, basket):
  903. value_of_matches = self._get_value_of_matches(basket)
  904. return D('0.00') < value_of_matches < self.value
  905. def get_upsell_message(self, basket):
  906. value_of_matches = self._get_value_of_matches(basket)
  907. return _('Spend %(value)s more from %(range)s') % {
  908. 'value': currency(self.value - value_of_matches),
  909. 'range': self.range}
  910. def consume_items(self, basket, affected_lines):
  911. """
  912. Marks items within the basket lines as consumed so they
  913. can't be reused in other offers.
  914. We allow lines to be passed in as sometimes we want them sorted
  915. in a specific order.
  916. """
  917. # Determine value of items already consumed as part of discount
  918. value_consumed = D('0.00')
  919. for line, __, qty in affected_lines:
  920. price = line.unit_price_incl_tax
  921. value_consumed += price * qty
  922. to_consume = max(0, self.value - value_consumed)
  923. if to_consume == 0:
  924. return
  925. for price, line in self.get_applicable_lines(
  926. basket, most_expensive_first=True):
  927. quantity_to_consume = min(
  928. line.quantity_without_discount,
  929. (to_consume / price).quantize(D(1), ROUND_UP))
  930. line.consume(quantity_to_consume)
  931. to_consume -= price * quantity_to_consume
  932. if to_consume <= 0:
  933. break
  934. # ============
  935. # Result types
  936. # ============
  937. class ApplicationResult(object):
  938. is_final = is_successful = False
  939. # Basket discount
  940. discount = D('0.00')
  941. description = None
  942. # Offer applications can affect 3 distinct things
  943. # (a) Give a discount off the BASKET total
  944. # (b) Give a discount off the SHIPPING total
  945. # (a) Trigger a post-order action
  946. BASKET, SHIPPING, POST_ORDER = range(0, 3)
  947. affects = None
  948. @property
  949. def affects_basket(self):
  950. return self.affects == self.BASKET
  951. @property
  952. def affects_shipping(self):
  953. return self.affects == self.SHIPPING
  954. @property
  955. def affects_post_order(self):
  956. return self.affects == self.POST_ORDER
  957. class BasketDiscount(ApplicationResult):
  958. """
  959. For when an offer application leads to a simple discount off the basket's
  960. total
  961. """
  962. affects = ApplicationResult.BASKET
  963. def __init__(self, amount):
  964. self.discount = amount
  965. @property
  966. def is_successful(self):
  967. return self.discount > 0
  968. # Helper global as returning zero discount is quite common
  969. ZERO_DISCOUNT = BasketDiscount(D('0.00'))
  970. class ShippingDiscount(ApplicationResult):
  971. """
  972. For when an offer application leads to a discount from the shipping cost
  973. """
  974. is_successful = is_final = True
  975. affects = ApplicationResult.SHIPPING
  976. SHIPPING_DISCOUNT = ShippingDiscount()
  977. class PostOrderAction(ApplicationResult):
  978. """
  979. For when an offer condition is met but the benefit is deferred until after
  980. the order has been placed. Eg buy 2 books and get 100 loyalty points.
  981. """
  982. is_final = is_successful = True
  983. affects = ApplicationResult.POST_ORDER
  984. def __init__(self, description):
  985. self.description = description
  986. # ========
  987. # Benefits
  988. # ========
  989. class PercentageDiscountBenefit(Benefit):
  990. """
  991. An offer benefit that gives a percentage discount
  992. """
  993. _description = _("%(value)s%% discount on %(range)s")
  994. @property
  995. def name(self):
  996. return self._description % {
  997. 'value': self.value,
  998. 'range': self.range.name.lower()}
  999. @property
  1000. def description(self):
  1001. return self._description % {
  1002. 'value': self.value,
  1003. 'range': range_anchor(self.range)}
  1004. class Meta:
  1005. proxy = True
  1006. verbose_name = _("Percentage discount benefit")
  1007. verbose_name_plural = _("Percentage discount benefits")
  1008. def apply(self, basket, condition, offer=None):
  1009. line_tuples = self.get_applicable_lines(basket)
  1010. discount = D('0.00')
  1011. affected_items = 0
  1012. max_affected_items = self._effective_max_affected_items()
  1013. affected_lines = []
  1014. for price, line in line_tuples:
  1015. if affected_items >= max_affected_items:
  1016. break
  1017. quantity_affected = min(line.quantity_without_discount,
  1018. max_affected_items - affected_items)
  1019. line_discount = self.round(self.value / D('100.0') * price
  1020. * int(quantity_affected))
  1021. line.discount(line_discount, quantity_affected)
  1022. affected_lines.append((line, line_discount, quantity_affected))
  1023. affected_items += quantity_affected
  1024. discount += line_discount
  1025. if discount > 0:
  1026. condition.consume_items(basket, affected_lines)
  1027. return BasketDiscount(discount)
  1028. class AbsoluteDiscountBenefit(Benefit):
  1029. """
  1030. An offer benefit that gives an absolute discount
  1031. """
  1032. _description = _("%(value)s discount on %(range)s")
  1033. @property
  1034. def name(self):
  1035. return self._description % {
  1036. 'value': currency(self.value),
  1037. 'range': self.range.name.lower()}
  1038. @property
  1039. def description(self):
  1040. return self._description % {
  1041. 'value': currency(self.value),
  1042. 'range': range_anchor(self.range)}
  1043. class Meta:
  1044. proxy = True
  1045. verbose_name = _("Absolute discount benefit")
  1046. verbose_name_plural = _("Absolute discount benefits")
  1047. def apply(self, basket, condition, offer=None):
  1048. # Fetch basket lines that are in the range and available to be used in
  1049. # an offer.
  1050. line_tuples = self.get_applicable_lines(basket)
  1051. if not line_tuples:
  1052. return ZERO_DISCOUNT
  1053. # Determine which lines can have the discount applied to them
  1054. max_affected_items = self._effective_max_affected_items()
  1055. num_affected_items = 0
  1056. affected_items_total = D('0.00')
  1057. lines_to_discount = []
  1058. for price, line in line_tuples:
  1059. if num_affected_items >= max_affected_items:
  1060. break
  1061. qty = min(line.quantity_without_discount,
  1062. max_affected_items - num_affected_items)
  1063. lines_to_discount.append((line, price, qty))
  1064. num_affected_items += qty
  1065. affected_items_total += qty * price
  1066. # Guard against zero price products causing problems
  1067. if not affected_items_total:
  1068. return ZERO_DISCOUNT
  1069. # Ensure we don't try to apply a discount larger than the total of the
  1070. # matching items.
  1071. discount = min(self.value, affected_items_total)
  1072. # Apply discount equally amongst them
  1073. affected_lines = []
  1074. applied_discount = D('0.00')
  1075. for i, (line, price, qty) in enumerate(lines_to_discount):
  1076. if i == len(lines_to_discount) - 1:
  1077. # If last line, then take the delta as the discount to ensure
  1078. # the total discount is correct and doesn't mismatch due to
  1079. # rounding.
  1080. line_discount = discount - applied_discount
  1081. else:
  1082. # Calculate a weighted discount for the line
  1083. line_discount = self.round(
  1084. ((price * qty) / affected_items_total) * discount)
  1085. line.discount(line_discount, qty)
  1086. affected_lines.append((line, line_discount, qty))
  1087. applied_discount += line_discount
  1088. condition.consume_items(basket, affected_lines)
  1089. return BasketDiscount(discount)
  1090. class FixedPriceBenefit(Benefit):
  1091. """
  1092. An offer benefit that gives the items in the condition for a
  1093. fixed price. This is useful for "bundle" offers.
  1094. Note that we ignore the benefit range here and only give a fixed price
  1095. for the products in the condition range. The condition cannot be a value
  1096. condition.
  1097. We also ignore the max_affected_items setting.
  1098. """
  1099. _description = _("The products that meet the condition are sold "
  1100. "for %(amount)s")
  1101. def __unicode__(self):
  1102. return self._description % {
  1103. 'amount': currency(self.value)}
  1104. @property
  1105. def description(self):
  1106. return self.__unicode__()
  1107. class Meta:
  1108. proxy = True
  1109. verbose_name = _("Fixed price benefit")
  1110. verbose_name_plural = _("Fixed price benefits")
  1111. def apply(self, basket, condition, offer=None):
  1112. if isinstance(condition, ValueCondition):
  1113. return ZERO_DISCOUNT
  1114. # Fetch basket lines that are in the range and available to be used in
  1115. # an offer.
  1116. line_tuples = self.get_applicable_lines(basket, range=condition.range)
  1117. if not line_tuples:
  1118. return ZERO_DISCOUNT
  1119. # Determine the lines to consume
  1120. num_permitted = int(condition.value)
  1121. num_affected = 0
  1122. value_affected = D('0.00')
  1123. covered_lines = []
  1124. for price, line in line_tuples:
  1125. if isinstance(condition, CoverageCondition):
  1126. quantity_affected = 1
  1127. else:
  1128. quantity_affected = min(
  1129. line.quantity_without_discount,
  1130. num_permitted - num_affected)
  1131. num_affected += quantity_affected
  1132. value_affected += quantity_affected * price
  1133. covered_lines.append((price, line, quantity_affected))
  1134. if num_affected >= num_permitted:
  1135. break
  1136. discount = max(value_affected - self.value, D('0.00'))
  1137. if not discount:
  1138. return ZERO_DISCOUNT
  1139. # Apply discount to the affected lines
  1140. discount_applied = D('0.00')
  1141. last_line = covered_lines[-1][0]
  1142. for price, line, quantity in covered_lines:
  1143. if line == last_line:
  1144. # If last line, we just take the difference to ensure that
  1145. # rounding doesn't lead to an off-by-one error
  1146. line_discount = discount - discount_applied
  1147. else:
  1148. line_discount = self.round(
  1149. discount * (price * quantity) / value_affected)
  1150. line.discount(line_discount, quantity)
  1151. discount_applied += line_discount
  1152. return BasketDiscount(discount)
  1153. class MultibuyDiscountBenefit(Benefit):
  1154. _description = _("Cheapest product from %(range)s is free")
  1155. @property
  1156. def name(self):
  1157. return self._description % {
  1158. 'range': self.range.name.lower()}
  1159. @property
  1160. def description(self):
  1161. return self._description % {
  1162. 'range': range_anchor(self.range)}
  1163. class Meta:
  1164. proxy = True
  1165. verbose_name = _("Multibuy discount benefit")
  1166. verbose_name_plural = _("Multibuy discount benefits")
  1167. def apply(self, basket, condition, offer=None):
  1168. line_tuples = self.get_applicable_lines(basket)
  1169. if not line_tuples:
  1170. return ZERO_DISCOUNT
  1171. # Cheapest line gives free product
  1172. discount, line = line_tuples[0]
  1173. line.discount(discount, 1)
  1174. affected_lines = [(line, discount, 1)]
  1175. condition.consume_items(basket, affected_lines)
  1176. return BasketDiscount(discount)
  1177. # =================
  1178. # Shipping benefits
  1179. # =================
  1180. class ShippingBenefit(Benefit):
  1181. def apply(self, basket, condition, offer=None):
  1182. condition.consume_items(basket, affected_lines=())
  1183. return SHIPPING_DISCOUNT
  1184. class Meta:
  1185. proxy = True
  1186. class ShippingAbsoluteDiscountBenefit(ShippingBenefit):
  1187. _description = _("%(amount)s off shipping cost")
  1188. @property
  1189. def description(self):
  1190. return self._description % {
  1191. 'amount': currency(self.value)}
  1192. class Meta:
  1193. proxy = True
  1194. verbose_name = _("Shipping absolute discount benefit")
  1195. verbose_name_plural = _("Shipping absolute discount benefits")
  1196. def shipping_discount(self, charge):
  1197. return min(charge, self.value)
  1198. class ShippingFixedPriceBenefit(ShippingBenefit):
  1199. _description = _("Get shipping for %(amount)s")
  1200. @property
  1201. def description(self):
  1202. return self._description % {
  1203. 'amount': currency(self.value)}
  1204. class Meta:
  1205. proxy = True
  1206. verbose_name = _("Fixed price shipping benefit")
  1207. verbose_name_plural = _("Fixed price shipping benefits")
  1208. def shipping_discount(self, charge):
  1209. if charge < self.value:
  1210. return D('0.00')
  1211. return charge - self.value
  1212. class ShippingPercentageDiscountBenefit(ShippingBenefit):
  1213. _description = _("%(value)s%% off of shipping cost")
  1214. @property
  1215. def description(self):
  1216. return self._description % {
  1217. 'value': self.value}
  1218. class Meta:
  1219. proxy = True
  1220. verbose_name = _("Shipping percentage discount benefit")
  1221. verbose_name_plural = _("Shipping percentage discount benefits")
  1222. def shipping_discount(self, charge):
  1223. return charge * self.value / D('100.0')