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

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