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

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