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

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