Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

models.py 59KB

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