You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

models.py 51KB

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