Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478
  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 as date_filter
  5. from django.db import models
  6. from django.utils.timezone import now, get_current_timezone
  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 render_currency as 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 hide_time_if_zero(dt):
  282. # Only show hours/minutes if they have been specified
  283. localtime = dt.astimezone(get_current_timezone())
  284. if localtime.hour == 0 and localtime.minute == 0:
  285. return date_filter(localtime, settings.DATE_FORMAT)
  286. return date_filter(localtime, settings.DATETIME_FORMAT)
  287. if self.start_datetime or self.end_datetime:
  288. today = now()
  289. if self.start_datetime and self.end_datetime:
  290. desc = _("Available between %(start)s and %(end)s") % {
  291. 'start': hide_time_if_zero(self.start_datetime),
  292. 'end': hide_time_if_zero(self.end_datetime)}
  293. is_satisfied = self.start_datetime <= today <= self.end_datetime
  294. elif self.start_datetime:
  295. desc = _("Available from %(start)s") % {
  296. 'start': hide_time_if_zero(self.start_datetime)}
  297. is_satisfied = today >= self.start_datetime
  298. elif self.end_datetime:
  299. desc = _("Available until %(end)s") % {
  300. 'end': hide_time_if_zero(self.end_datetime)}
  301. is_satisfied = today <= self.end_datetime
  302. restrictions.append({
  303. 'description': desc,
  304. 'is_satisfied': is_satisfied})
  305. if self.max_discount:
  306. desc = _("Limited to a cost of %(max)s") % {
  307. 'max': currency(self.max_discount)}
  308. restrictions.append({
  309. 'description': desc,
  310. 'is_satisfied': self.total_discount < self.max_discount})
  311. return restrictions
  312. @property
  313. def has_products(self):
  314. return self.condition.range is not None
  315. def products(self):
  316. """
  317. Return a queryset of products in this offer
  318. """
  319. Product = get_model('catalogue', 'Product')
  320. if not self.has_products:
  321. return Product.objects.none()
  322. cond_range = self.condition.range
  323. if cond_range.includes_all_products:
  324. # Return ALL the products
  325. return Product.browsable.select_related(
  326. 'product_class', 'stockrecord').filter(
  327. is_discountable=True).prefetch_related(
  328. 'variants', 'images', 'product_class__options',
  329. 'product_options')
  330. return cond_range.included_products.filter(is_discountable=True)
  331. class Condition(models.Model):
  332. COUNT, VALUE, COVERAGE = ("Count", "Value", "Coverage")
  333. TYPE_CHOICES = (
  334. (COUNT, _("Depends on number of items in basket that are in "
  335. "condition range")),
  336. (VALUE, _("Depends on value of items in basket that are in "
  337. "condition range")),
  338. (COVERAGE, _("Needs to contain a set number of DISTINCT items "
  339. "from the condition range")))
  340. range = models.ForeignKey(
  341. 'offer.Range', verbose_name=_("Range"), null=True, blank=True)
  342. type = models.CharField(_('Type'), max_length=128, choices=TYPE_CHOICES,
  343. null=True, blank=True)
  344. value = PositiveDecimalField(_('Value'), decimal_places=2, max_digits=12,
  345. null=True, blank=True)
  346. proxy_class = models.CharField(_("Custom class"), null=True, blank=True,
  347. max_length=255, unique=True, default=None)
  348. class Meta:
  349. verbose_name = _("Condition")
  350. verbose_name_plural = _("Conditions")
  351. def proxy(self):
  352. """
  353. Return the proxy model
  354. """
  355. field_dict = dict(self.__dict__)
  356. for field in field_dict.keys():
  357. if field.startswith('_'):
  358. del field_dict[field]
  359. if self.proxy_class:
  360. klass = load_proxy(self.proxy_class)
  361. return klass(**field_dict)
  362. klassmap = {
  363. self.COUNT: CountCondition,
  364. self.VALUE: ValueCondition,
  365. self.COVERAGE: CoverageCondition}
  366. if self.type in klassmap:
  367. return klassmap[self.type](**field_dict)
  368. return self
  369. def __unicode__(self):
  370. return self.proxy().name
  371. @property
  372. def name(self):
  373. return self.description
  374. @property
  375. def description(self):
  376. return self.proxy().description
  377. def consume_items(self, basket, affected_lines):
  378. pass
  379. def is_satisfied(self, basket):
  380. """
  381. Determines whether a given basket meets this condition. This is
  382. stubbed in this top-class object. The subclassing proxies are
  383. responsible for implementing it correctly.
  384. """
  385. return False
  386. def is_partially_satisfied(self, basket):
  387. """
  388. Determine if the basket partially meets the condition. This is useful
  389. for up-selling messages to entice customers to buy something more in
  390. order to qualify for an offer.
  391. """
  392. return False
  393. def get_upsell_message(self, basket):
  394. return None
  395. def can_apply_condition(self, line):
  396. """
  397. Determines whether the condition can be applied to a given basket line
  398. """
  399. if not line.stockrecord:
  400. return False
  401. product = line.product
  402. return self.range.contains_product(product) and product.is_discountable
  403. def get_applicable_lines(self, basket, most_expensive_first=True):
  404. """
  405. Return line data for the lines that can be consumed by this condition
  406. """
  407. line_tuples = []
  408. for line in basket.all_lines():
  409. if not self.can_apply_condition(line):
  410. continue
  411. # We only include products where we know the tax charged
  412. if not line.stockinfo.price.is_tax_known:
  413. continue
  414. price = line.unit_price_incl_tax
  415. if not price:
  416. continue
  417. line_tuples.append((price, line))
  418. if most_expensive_first:
  419. return sorted(line_tuples, reverse=True)
  420. return sorted(line_tuples)
  421. class Benefit(models.Model):
  422. range = models.ForeignKey(
  423. 'offer.Range', null=True, blank=True, verbose_name=_("Range"))
  424. # Benefit types
  425. PERCENTAGE, FIXED, MULTIBUY, FIXED_PRICE = (
  426. "Percentage", "Absolute", "Multibuy", "Fixed price")
  427. SHIPPING_PERCENTAGE, SHIPPING_ABSOLUTE, SHIPPING_FIXED_PRICE = (
  428. 'Shipping percentage', 'Shipping absolute', 'Shipping fixed price')
  429. TYPE_CHOICES = (
  430. (PERCENTAGE, _("Discount is a percentage off of the product's value")),
  431. (FIXED, _("Discount is a fixed amount off of the product's value")),
  432. (MULTIBUY, _("Discount is to give the cheapest product for free")),
  433. (FIXED_PRICE,
  434. _("Get the products that meet the condition for a fixed price")),
  435. (SHIPPING_ABSOLUTE,
  436. _("Discount is a fixed amount of the shipping cost")),
  437. (SHIPPING_FIXED_PRICE, _("Get shipping for a fixed price")),
  438. (SHIPPING_PERCENTAGE, _("Discount is a percentage off of the shipping cost")),
  439. )
  440. type = models.CharField(
  441. _("Type"), max_length=128, choices=TYPE_CHOICES, blank=True)
  442. # The value to use with the designated type. This can be either an integer
  443. # (eg for multibuy) or a decimal (eg an amount) which is slightly
  444. # confusing.
  445. value = PositiveDecimalField(
  446. _("Value"), decimal_places=2, max_digits=12, null=True, blank=True)
  447. # If this is not set, then there is no upper limit on how many products
  448. # can be discounted by this benefit.
  449. max_affected_items = models.PositiveIntegerField(
  450. _("Max Affected Items"), blank=True, null=True,
  451. help_text=_("Set this to prevent the discount consuming all items "
  452. "within the range that are in the basket."))
  453. # A custom benefit class can be used instead. This means the
  454. # type/value/max_affected_items fields should all be None.
  455. proxy_class = models.CharField(_("Custom class"), null=True, blank=True,
  456. max_length=255, unique=True, default=None)
  457. class Meta:
  458. verbose_name = _("Benefit")
  459. verbose_name_plural = _("Benefits")
  460. def proxy(self):
  461. field_dict = dict(self.__dict__)
  462. for field in field_dict.keys():
  463. if field.startswith('_'):
  464. del field_dict[field]
  465. if self.proxy_class:
  466. klass = load_proxy(self.proxy_class)
  467. return klass(**field_dict)
  468. klassmap = {
  469. self.PERCENTAGE: PercentageDiscountBenefit,
  470. self.FIXED: AbsoluteDiscountBenefit,
  471. self.MULTIBUY: MultibuyDiscountBenefit,
  472. self.FIXED_PRICE: FixedPriceBenefit,
  473. self.SHIPPING_ABSOLUTE: ShippingAbsoluteDiscountBenefit,
  474. self.SHIPPING_FIXED_PRICE: ShippingFixedPriceBenefit,
  475. self.SHIPPING_PERCENTAGE: ShippingPercentageDiscountBenefit}
  476. if self.type in klassmap:
  477. return klassmap[self.type](**field_dict)
  478. raise RuntimeError("Unrecognised benefit type (%s)" % self.type)
  479. def __unicode__(self):
  480. name = self.proxy().name
  481. if self.max_affected_items:
  482. name += ungettext(
  483. " (max %d item)",
  484. " (max %d items)",
  485. self.max_affected_items) % self.max_affected_items
  486. return name
  487. @property
  488. def name(self):
  489. return self.description
  490. @property
  491. def description(self):
  492. return self.proxy().description
  493. def apply(self, basket, condition, offer=None):
  494. return ZERO_DISCOUNT
  495. def apply_deferred(self, basket):
  496. return None
  497. def clean(self):
  498. if not self.type:
  499. return
  500. method_name = 'clean_%s' % self.type.lower().replace(' ', '_')
  501. if hasattr(self, method_name):
  502. getattr(self, method_name)()
  503. def clean_multibuy(self):
  504. if not self.range:
  505. raise ValidationError(
  506. _("Multibuy benefits require a product range"))
  507. if self.value:
  508. raise ValidationError(
  509. _("Multibuy benefits don't require a value"))
  510. if self.max_affected_items:
  511. raise ValidationError(
  512. _("Multibuy benefits don't require a 'max affected items' "
  513. "attribute"))
  514. def clean_percentage(self):
  515. if not self.range:
  516. raise ValidationError(
  517. _("Percentage benefits require a product range"))
  518. if self.value > 100:
  519. raise ValidationError(
  520. _("Percentage discount cannot be greater than 100"))
  521. def clean_shipping_absolute(self):
  522. if not self.value:
  523. raise ValidationError(
  524. _("A discount value is required"))
  525. if self.range:
  526. raise ValidationError(
  527. _("No range should be selected as this benefit does not "
  528. "apply to products"))
  529. if self.max_affected_items:
  530. raise ValidationError(
  531. _("Shipping discounts don't require a 'max affected items' "
  532. "attribute"))
  533. def clean_shipping_percentage(self):
  534. if self.value > 100:
  535. raise ValidationError(
  536. _("Percentage discount cannot be greater than 100"))
  537. if self.range:
  538. raise ValidationError(
  539. _("No range should be selected as this benefit does not "
  540. "apply to products"))
  541. if self.max_affected_items:
  542. raise ValidationError(
  543. _("Shipping discounts don't require a 'max affected items' "
  544. "attribute"))
  545. def clean_shipping_fixed_price(self):
  546. if self.range:
  547. raise ValidationError(
  548. _("No range should be selected as this benefit does not "
  549. "apply to products"))
  550. if self.max_affected_items:
  551. raise ValidationError(
  552. _("Shipping discounts don't require a 'max affected items' "
  553. "attribute"))
  554. def clean_fixed_price(self):
  555. if self.range:
  556. raise ValidationError(
  557. _("No range should be selected as the condition range will "
  558. "be used instead."))
  559. def clean_absolute(self):
  560. if not self.range:
  561. raise ValidationError(
  562. _("Fixed discount benefits require a product range"))
  563. if not self.value:
  564. raise ValidationError(
  565. _("Fixed discount benefits require a value"))
  566. def round(self, amount):
  567. """
  568. Apply rounding to discount amount
  569. """
  570. if hasattr(settings, 'OSCAR_OFFER_ROUNDING_FUNCTION'):
  571. return settings.OSCAR_OFFER_ROUNDING_FUNCTION(amount)
  572. return amount.quantize(D('.01'), ROUND_DOWN)
  573. def _effective_max_affected_items(self):
  574. """
  575. Return the maximum number of items that can have a discount applied
  576. during the application of this benefit
  577. """
  578. return self.max_affected_items if self.max_affected_items else 10000
  579. def can_apply_benefit(self, line):
  580. """
  581. Determines whether the benefit can be applied to a given basket line
  582. """
  583. return line.stockrecord and line.product.is_discountable
  584. def get_applicable_lines(self, basket, range=None):
  585. """
  586. Return the basket lines that are available to be discounted
  587. :basket: The basket
  588. :range: The range of products to use for filtering. The fixed-price
  589. benefit ignores its range and uses the condition range
  590. """
  591. if range is None:
  592. range = self.range
  593. line_tuples = []
  594. for line in basket.all_lines():
  595. product = line.product
  596. # We only include products where we know the tax charged
  597. if not line.stockinfo.price.is_tax_known:
  598. continue
  599. if (not range.contains(product) or
  600. not self.can_apply_benefit(line)):
  601. continue
  602. price = line.unit_price_incl_tax
  603. if not price:
  604. # Avoid zero price products
  605. continue
  606. if line.quantity_without_discount == 0:
  607. continue
  608. line_tuples.append((price, line))
  609. # We sort lines to be cheapest first to ensure consistent applications
  610. return sorted(line_tuples)
  611. def shipping_discount(self, charge):
  612. return D('0.00')
  613. class Range(models.Model):
  614. """
  615. Represents a range of products that can be used within an offer
  616. """
  617. name = models.CharField(_("Name"), max_length=128, unique=True)
  618. includes_all_products = models.BooleanField(
  619. _('Includes All Products'), default=False)
  620. included_products = models.ManyToManyField(
  621. 'catalogue.Product', related_name='includes', blank=True,
  622. verbose_name=_("Included Products"))
  623. excluded_products = models.ManyToManyField(
  624. 'catalogue.Product', related_name='excludes', blank=True,
  625. verbose_name=_("Excluded Products"))
  626. classes = models.ManyToManyField(
  627. 'catalogue.ProductClass', related_name='classes', blank=True,
  628. verbose_name=_("Product Classes"))
  629. included_categories = models.ManyToManyField(
  630. 'catalogue.Category', related_name='includes', blank=True,
  631. verbose_name=_("Included Categories"))
  632. # Allow a custom range instance to be specified
  633. proxy_class = models.CharField(
  634. _("Custom class"), null=True, blank=True, max_length=255,
  635. default=None, unique=True)
  636. date_created = models.DateTimeField(_("Date Created"), auto_now_add=True)
  637. __included_product_ids = None
  638. __excluded_product_ids = None
  639. __class_ids = None
  640. class Meta:
  641. verbose_name = _("Range")
  642. verbose_name_plural = _("Ranges")
  643. def __unicode__(self):
  644. return self.name
  645. def contains_product(self, product):
  646. """
  647. Check whether the passed product is part of this range
  648. """
  649. # We look for shortcircuit checks first before
  650. # the tests that require more database queries.
  651. if settings.OSCAR_OFFER_BLACKLIST_PRODUCT and \
  652. settings.OSCAR_OFFER_BLACKLIST_PRODUCT(product):
  653. return False
  654. # Delegate to a proxy class if one is provided
  655. if self.proxy_class:
  656. return load_proxy(self.proxy_class)().contains_product(product)
  657. excluded_product_ids = self._excluded_product_ids()
  658. if product.id in excluded_product_ids:
  659. return False
  660. if self.includes_all_products:
  661. return True
  662. if product.product_class_id in self._class_ids():
  663. return True
  664. included_product_ids = self._included_product_ids()
  665. if product.id in included_product_ids:
  666. return True
  667. test_categories = self.included_categories.all()
  668. if test_categories:
  669. for category in product.categories.all():
  670. for test_category in test_categories:
  671. if category == test_category or category.is_descendant_of(test_category):
  672. return True
  673. return False
  674. # Shorter alias
  675. contains = contains_product
  676. def _included_product_ids(self):
  677. if self.__included_product_ids is None:
  678. self.__included_product_ids = [row['id'] for row in self.included_products.values('id')]
  679. return self.__included_product_ids
  680. def _excluded_product_ids(self):
  681. if not self.id:
  682. return []
  683. if self.__excluded_product_ids is None:
  684. self.__excluded_product_ids = [row['id'] for row in self.excluded_products.values('id')]
  685. return self.__excluded_product_ids
  686. def _class_ids(self):
  687. if None == self.__class_ids:
  688. self.__class_ids = [row['id'] for row in self.classes.values('id')]
  689. return self.__class_ids
  690. def num_products(self):
  691. if self.includes_all_products:
  692. return None
  693. return self.included_products.all().count()
  694. @property
  695. def is_editable(self):
  696. """
  697. Test whether this product can be edited in the dashboard
  698. """
  699. return self.proxy_class is None
  700. # ==========
  701. # Conditions
  702. # ==========
  703. class CountCondition(Condition):
  704. """
  705. An offer condition dependent on the NUMBER of matching items from the
  706. basket.
  707. """
  708. _description = _("Basket includes %(count)d item(s) from %(range)s")
  709. @property
  710. def name(self):
  711. return self._description % {
  712. 'count': self.value,
  713. 'range': unicode(self.range).lower()}
  714. @property
  715. def description(self):
  716. return self._description % {
  717. 'count': self.value,
  718. 'range': range_anchor(self.range)}
  719. class Meta:
  720. proxy = True
  721. verbose_name = _("Count Condition")
  722. verbose_name_plural = _("Count Conditions")
  723. def is_satisfied(self, basket):
  724. """
  725. Determines whether a given basket meets this condition
  726. """
  727. num_matches = 0
  728. for line in basket.all_lines():
  729. if (self.can_apply_condition(line)
  730. and line.quantity_without_discount > 0):
  731. num_matches += line.quantity_without_discount
  732. if num_matches >= self.value:
  733. return True
  734. return False
  735. def _get_num_matches(self, basket):
  736. if hasattr(self, '_num_matches'):
  737. return getattr(self, '_num_matches')
  738. num_matches = 0
  739. for line in basket.all_lines():
  740. if (self.can_apply_condition(line)
  741. and line.quantity_without_discount > 0):
  742. num_matches += line.quantity_without_discount
  743. self._num_matches = num_matches
  744. return num_matches
  745. def is_partially_satisfied(self, basket):
  746. num_matches = self._get_num_matches(basket)
  747. return 0 < num_matches < self.value
  748. def get_upsell_message(self, basket):
  749. num_matches = self._get_num_matches(basket)
  750. delta = self.value - num_matches
  751. return ungettext('Buy %(delta)d more product from %(range)s',
  752. 'Buy %(delta)d more products from %(range)s', delta) % {
  753. 'delta': delta, 'range': self.range}
  754. def consume_items(self, basket, affected_lines):
  755. """
  756. Marks items within the basket lines as consumed so they
  757. can't be reused in other offers.
  758. :basket: The basket
  759. :affected_lines: The lines that have been affected by the discount.
  760. This should be list of tuples (line, discount, qty)
  761. """
  762. # We need to count how many items have already been consumed as part of
  763. # applying the benefit, so we don't consume too many items.
  764. num_consumed = 0
  765. for line, __, quantity in affected_lines:
  766. num_consumed += quantity
  767. to_consume = max(0, self.value - num_consumed)
  768. if to_consume == 0:
  769. return
  770. for __, line in self.get_applicable_lines(basket,
  771. most_expensive_first=True):
  772. quantity_to_consume = min(line.quantity_without_discount,
  773. to_consume)
  774. line.consume(quantity_to_consume)
  775. to_consume -= quantity_to_consume
  776. if to_consume == 0:
  777. break
  778. class CoverageCondition(Condition):
  779. """
  780. An offer condition dependent on the number of DISTINCT matching items from the basket.
  781. """
  782. _description = _("Basket includes %(count)d distinct item(s) from %(range)s")
  783. @property
  784. def name(self):
  785. return self._description % {
  786. 'count': self.value,
  787. 'range': unicode(self.range).lower()}
  788. @property
  789. def description(self):
  790. return self._description % {
  791. 'count': self.value,
  792. 'range': range_anchor(self.range)}
  793. class Meta:
  794. proxy = True
  795. verbose_name = _("Coverage Condition")
  796. verbose_name_plural = _("Coverage Conditions")
  797. def is_satisfied(self, basket):
  798. """
  799. Determines whether a given basket meets this condition
  800. """
  801. covered_ids = []
  802. for line in basket.all_lines():
  803. if not line.is_available_for_discount:
  804. continue
  805. product = line.product
  806. if (self.can_apply_condition(line) and product.id not in covered_ids):
  807. covered_ids.append(product.id)
  808. if len(covered_ids) >= self.value:
  809. return True
  810. return False
  811. def _get_num_covered_products(self, basket):
  812. covered_ids = []
  813. for line in basket.all_lines():
  814. if not line.is_available_for_discount:
  815. continue
  816. product = line.product
  817. if (self.can_apply_condition(line) and product.id not in covered_ids):
  818. covered_ids.append(product.id)
  819. return len(covered_ids)
  820. def get_upsell_message(self, basket):
  821. delta = self.value - self._get_num_covered_products(basket)
  822. return ungettext('Buy %(delta)d more product from %(range)s',
  823. 'Buy %(delta)d more products from %(range)s', delta) % {
  824. 'delta': delta, 'range': self.range}
  825. def is_partially_satisfied(self, basket):
  826. return 0 < self._get_num_covered_products(basket) < self.value
  827. def consume_items(self, basket, affected_lines):
  828. """
  829. Marks items within the basket lines as consumed so they
  830. can't be reused in other offers.
  831. """
  832. # Determine products that have already been consumed by applying the
  833. # benefit
  834. consumed_products = []
  835. for line, __, quantity in affected_lines:
  836. consumed_products.append(line.product)
  837. to_consume = max(0, self.value - len(consumed_products))
  838. if to_consume == 0:
  839. return
  840. for line in basket.all_lines():
  841. product = line.product
  842. if not self.can_apply_condition(line):
  843. continue
  844. if product in consumed_products:
  845. continue
  846. if not line.is_available_for_discount:
  847. continue
  848. # Only consume a quantity of 1 from each line
  849. line.consume(1)
  850. consumed_products.append(product)
  851. to_consume -= 1
  852. if to_consume == 0:
  853. break
  854. def get_value_of_satisfying_items(self, basket):
  855. covered_ids = []
  856. value = D('0.00')
  857. for line in basket.all_lines():
  858. if (self.can_apply_condition(line) and line.product.id not in covered_ids):
  859. covered_ids.append(line.product.id)
  860. value += line.unit_price_incl_tax
  861. if len(covered_ids) >= self.value:
  862. return value
  863. return value
  864. class ValueCondition(Condition):
  865. """
  866. An offer condition dependent on the VALUE of matching items from the
  867. basket.
  868. """
  869. _description = _("Basket includes %(amount)s from %(range)s")
  870. @property
  871. def name(self):
  872. return self._description % {
  873. 'amount': currency(self.value),
  874. 'range': unicode(self.range).lower()}
  875. @property
  876. def description(self):
  877. return self._description % {
  878. 'amount': currency(self.value),
  879. 'range': range_anchor(self.range)}
  880. class Meta:
  881. proxy = True
  882. verbose_name = _("Value Condition")
  883. verbose_name_plural = _("Value Conditions")
  884. def is_satisfied(self, basket):
  885. """
  886. Determine whether a given basket meets this condition
  887. """
  888. value_of_matches = D('0.00')
  889. for line in basket.all_lines():
  890. if (self.can_apply_condition(line) and line.quantity_without_discount > 0):
  891. price = line.unit_price_incl_tax
  892. value_of_matches += price * int(line.quantity_without_discount)
  893. if value_of_matches >= self.value:
  894. return True
  895. return False
  896. def _get_value_of_matches(self, basket):
  897. if hasattr(self, '_value_of_matches'):
  898. return getattr(self, '_value_of_matches')
  899. value_of_matches = D('0.00')
  900. for line in basket.all_lines():
  901. if (self.can_apply_condition(line) and line.quantity_without_discount > 0):
  902. price = line.unit_price_incl_tax
  903. value_of_matches += price * int(line.quantity_without_discount)
  904. self._value_of_matches = value_of_matches
  905. return value_of_matches
  906. def is_partially_satisfied(self, basket):
  907. value_of_matches = self._get_value_of_matches(basket)
  908. return D('0.00') < value_of_matches < self.value
  909. def get_upsell_message(self, basket):
  910. value_of_matches = self._get_value_of_matches(basket)
  911. return _('Spend %(value)s more from %(range)s') % {
  912. 'value': currency(self.value - value_of_matches),
  913. 'range': self.range}
  914. def consume_items(self, basket, affected_lines):
  915. """
  916. Marks items within the basket lines as consumed so they
  917. can't be reused in other offers.
  918. We allow lines to be passed in as sometimes we want them sorted
  919. in a specific order.
  920. """
  921. # Determine value of items already consumed as part of discount
  922. value_consumed = D('0.00')
  923. for line, __, qty in affected_lines:
  924. price = line.unit_price_incl_tax
  925. value_consumed += price * qty
  926. to_consume = max(0, self.value - value_consumed)
  927. if to_consume == 0:
  928. return
  929. for price, line in self.get_applicable_lines(
  930. basket, most_expensive_first=True):
  931. quantity_to_consume = min(
  932. line.quantity_without_discount,
  933. (to_consume / price).quantize(D(1), ROUND_UP))
  934. line.consume(quantity_to_consume)
  935. to_consume -= price * quantity_to_consume
  936. if to_consume <= 0:
  937. break
  938. # ============
  939. # Result types
  940. # ============
  941. class ApplicationResult(object):
  942. is_final = is_successful = False
  943. # Basket discount
  944. discount = D('0.00')
  945. description = None
  946. # Offer applications can affect 3 distinct things
  947. # (a) Give a discount off the BASKET total
  948. # (b) Give a discount off the SHIPPING total
  949. # (a) Trigger a post-order action
  950. BASKET, SHIPPING, POST_ORDER = range(0, 3)
  951. affects = None
  952. @property
  953. def affects_basket(self):
  954. return self.affects == self.BASKET
  955. @property
  956. def affects_shipping(self):
  957. return self.affects == self.SHIPPING
  958. @property
  959. def affects_post_order(self):
  960. return self.affects == self.POST_ORDER
  961. class BasketDiscount(ApplicationResult):
  962. """
  963. For when an offer application leads to a simple discount off the basket's
  964. total
  965. """
  966. affects = ApplicationResult.BASKET
  967. def __init__(self, amount):
  968. self.discount = amount
  969. @property
  970. def is_successful(self):
  971. return self.discount > 0
  972. # Helper global as returning zero discount is quite common
  973. ZERO_DISCOUNT = BasketDiscount(D('0.00'))
  974. class ShippingDiscount(ApplicationResult):
  975. """
  976. For when an offer application leads to a discount from the shipping cost
  977. """
  978. is_successful = is_final = True
  979. affects = ApplicationResult.SHIPPING
  980. SHIPPING_DISCOUNT = ShippingDiscount()
  981. class PostOrderAction(ApplicationResult):
  982. """
  983. For when an offer condition is met but the benefit is deferred until after
  984. the order has been placed. Eg buy 2 books and get 100 loyalty points.
  985. """
  986. is_final = is_successful = True
  987. affects = ApplicationResult.POST_ORDER
  988. def __init__(self, description):
  989. self.description = description
  990. # ========
  991. # Benefits
  992. # ========
  993. class PercentageDiscountBenefit(Benefit):
  994. """
  995. An offer benefit that gives a percentage discount
  996. """
  997. _description = _("%(value)s%% discount on %(range)s")
  998. @property
  999. def name(self):
  1000. return self._description % {
  1001. 'value': self.value,
  1002. 'range': self.range.name.lower()}
  1003. @property
  1004. def description(self):
  1005. return self._description % {
  1006. 'value': self.value,
  1007. 'range': range_anchor(self.range)}
  1008. class Meta:
  1009. proxy = True
  1010. verbose_name = _("Percentage discount benefit")
  1011. verbose_name_plural = _("Percentage discount benefits")
  1012. def apply(self, basket, condition, offer=None):
  1013. line_tuples = self.get_applicable_lines(basket)
  1014. discount = D('0.00')
  1015. affected_items = 0
  1016. max_affected_items = self._effective_max_affected_items()
  1017. affected_lines = []
  1018. for price, line in line_tuples:
  1019. if affected_items >= max_affected_items:
  1020. break
  1021. quantity_affected = min(line.quantity_without_discount,
  1022. max_affected_items - affected_items)
  1023. line_discount = self.round(self.value / D('100.0') * price
  1024. * int(quantity_affected))
  1025. line.discount(line_discount, quantity_affected)
  1026. affected_lines.append((line, line_discount, quantity_affected))
  1027. affected_items += quantity_affected
  1028. discount += line_discount
  1029. if discount > 0:
  1030. condition.consume_items(basket, affected_lines)
  1031. return BasketDiscount(discount)
  1032. class AbsoluteDiscountBenefit(Benefit):
  1033. """
  1034. An offer benefit that gives an absolute discount
  1035. """
  1036. _description = _("%(value)s discount on %(range)s")
  1037. @property
  1038. def name(self):
  1039. return self._description % {
  1040. 'value': currency(self.value),
  1041. 'range': self.range.name.lower()}
  1042. @property
  1043. def description(self):
  1044. return self._description % {
  1045. 'value': currency(self.value),
  1046. 'range': range_anchor(self.range)}
  1047. class Meta:
  1048. proxy = True
  1049. verbose_name = _("Absolute discount benefit")
  1050. verbose_name_plural = _("Absolute discount benefits")
  1051. def apply(self, basket, condition, offer=None):
  1052. # Fetch basket lines that are in the range and available to be used in
  1053. # an offer.
  1054. line_tuples = self.get_applicable_lines(basket)
  1055. if not line_tuples:
  1056. return ZERO_DISCOUNT
  1057. # Determine which lines can have the discount applied to them
  1058. max_affected_items = self._effective_max_affected_items()
  1059. num_affected_items = 0
  1060. affected_items_total = D('0.00')
  1061. lines_to_discount = []
  1062. for price, line in line_tuples:
  1063. if num_affected_items >= max_affected_items:
  1064. break
  1065. qty = min(line.quantity_without_discount,
  1066. max_affected_items - num_affected_items)
  1067. lines_to_discount.append((line, price, qty))
  1068. num_affected_items += qty
  1069. affected_items_total += qty * price
  1070. # Guard against zero price products causing problems
  1071. if not affected_items_total:
  1072. return ZERO_DISCOUNT
  1073. # Ensure we don't try to apply a discount larger than the total of the
  1074. # matching items.
  1075. discount = min(self.value, affected_items_total)
  1076. # Apply discount equally amongst them
  1077. affected_lines = []
  1078. applied_discount = D('0.00')
  1079. for i, (line, price, qty) in enumerate(lines_to_discount):
  1080. if i == len(lines_to_discount) - 1:
  1081. # If last line, then take the delta as the discount to ensure
  1082. # the total discount is correct and doesn't mismatch due to
  1083. # rounding.
  1084. line_discount = discount - applied_discount
  1085. else:
  1086. # Calculate a weighted discount for the line
  1087. line_discount = self.round(
  1088. ((price * qty) / affected_items_total) * discount)
  1089. line.discount(line_discount, qty)
  1090. affected_lines.append((line, line_discount, qty))
  1091. applied_discount += line_discount
  1092. condition.consume_items(basket, affected_lines)
  1093. return BasketDiscount(discount)
  1094. class FixedPriceBenefit(Benefit):
  1095. """
  1096. An offer benefit that gives the items in the condition for a
  1097. fixed price. This is useful for "bundle" offers.
  1098. Note that we ignore the benefit range here and only give a fixed price
  1099. for the products in the condition range. The condition cannot be a value
  1100. condition.
  1101. We also ignore the max_affected_items setting.
  1102. """
  1103. _description = _("The products that meet the condition are sold "
  1104. "for %(amount)s")
  1105. def __unicode__(self):
  1106. return self._description % {
  1107. 'amount': currency(self.value)}
  1108. @property
  1109. def description(self):
  1110. return self.__unicode__()
  1111. class Meta:
  1112. proxy = True
  1113. verbose_name = _("Fixed price benefit")
  1114. verbose_name_plural = _("Fixed price benefits")
  1115. def apply(self, basket, condition, offer=None):
  1116. if isinstance(condition, ValueCondition):
  1117. return ZERO_DISCOUNT
  1118. # Fetch basket lines that are in the range and available to be used in
  1119. # an offer.
  1120. line_tuples = self.get_applicable_lines(basket, range=condition.range)
  1121. if not line_tuples:
  1122. return ZERO_DISCOUNT
  1123. # Determine the lines to consume
  1124. num_permitted = int(condition.value)
  1125. num_affected = 0
  1126. value_affected = D('0.00')
  1127. covered_lines = []
  1128. for price, line in line_tuples:
  1129. if isinstance(condition, CoverageCondition):
  1130. quantity_affected = 1
  1131. else:
  1132. quantity_affected = min(
  1133. line.quantity_without_discount,
  1134. num_permitted - num_affected)
  1135. num_affected += quantity_affected
  1136. value_affected += quantity_affected * price
  1137. covered_lines.append((price, line, quantity_affected))
  1138. if num_affected >= num_permitted:
  1139. break
  1140. discount = max(value_affected - self.value, D('0.00'))
  1141. if not discount:
  1142. return ZERO_DISCOUNT
  1143. # Apply discount to the affected lines
  1144. discount_applied = D('0.00')
  1145. last_line = covered_lines[-1][1]
  1146. for price, line, quantity in covered_lines:
  1147. if line == last_line:
  1148. # If last line, we just take the difference to ensure that
  1149. # rounding doesn't lead to an off-by-one error
  1150. line_discount = discount - discount_applied
  1151. else:
  1152. line_discount = self.round(
  1153. discount * (price * quantity) / value_affected)
  1154. line.discount(line_discount, quantity)
  1155. discount_applied += line_discount
  1156. return BasketDiscount(discount)
  1157. class MultibuyDiscountBenefit(Benefit):
  1158. _description = _("Cheapest product from %(range)s is free")
  1159. @property
  1160. def name(self):
  1161. return self._description % {
  1162. 'range': self.range.name.lower()}
  1163. @property
  1164. def description(self):
  1165. return self._description % {
  1166. 'range': range_anchor(self.range)}
  1167. class Meta:
  1168. proxy = True
  1169. verbose_name = _("Multibuy discount benefit")
  1170. verbose_name_plural = _("Multibuy discount benefits")
  1171. def apply(self, basket, condition, offer=None):
  1172. line_tuples = self.get_applicable_lines(basket)
  1173. if not line_tuples:
  1174. return ZERO_DISCOUNT
  1175. # Cheapest line gives free product
  1176. discount, line = line_tuples[0]
  1177. line.discount(discount, 1)
  1178. affected_lines = [(line, discount, 1)]
  1179. condition.consume_items(basket, affected_lines)
  1180. return BasketDiscount(discount)
  1181. # =================
  1182. # Shipping benefits
  1183. # =================
  1184. class ShippingBenefit(Benefit):
  1185. def apply(self, basket, condition, offer=None):
  1186. condition.consume_items(basket, affected_lines=())
  1187. return SHIPPING_DISCOUNT
  1188. class Meta:
  1189. proxy = True
  1190. class ShippingAbsoluteDiscountBenefit(ShippingBenefit):
  1191. _description = _("%(amount)s off shipping cost")
  1192. @property
  1193. def description(self):
  1194. return self._description % {
  1195. 'amount': currency(self.value)}
  1196. class Meta:
  1197. proxy = True
  1198. verbose_name = _("Shipping absolute discount benefit")
  1199. verbose_name_plural = _("Shipping absolute discount benefits")
  1200. def shipping_discount(self, charge):
  1201. return min(charge, self.value)
  1202. class ShippingFixedPriceBenefit(ShippingBenefit):
  1203. _description = _("Get shipping for %(amount)s")
  1204. @property
  1205. def description(self):
  1206. return self._description % {
  1207. 'amount': currency(self.value)}
  1208. class Meta:
  1209. proxy = True
  1210. verbose_name = _("Fixed price shipping benefit")
  1211. verbose_name_plural = _("Fixed price shipping benefits")
  1212. def shipping_discount(self, charge):
  1213. if charge < self.value:
  1214. return D('0.00')
  1215. return charge - self.value
  1216. class ShippingPercentageDiscountBenefit(ShippingBenefit):
  1217. _description = _("%(value)s%% off of shipping cost")
  1218. @property
  1219. def description(self):
  1220. return self._description % {
  1221. 'value': self.value}
  1222. class Meta:
  1223. proxy = True
  1224. verbose_name = _("Shipping percentage discount benefit")
  1225. verbose_name_plural = _("Shipping percentage discount benefits")
  1226. def shipping_discount(self, charge):
  1227. return charge * self.value / D('100.0')