Debian Codegraph @

addons/sale_loyalty/models/sale_order.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 import itertools
4 import random
5 from collections import defaultdict
6 from functools import partial
7
8 from pytz import timezone
9
10 from odoo import _, api, fields, models
11 from odoo.exceptions import UserError, ValidationError
12 from odoo.fields import Command, Domain
13 from odoo.tools import float_round, lazy, str2bool
14
15
16 def _generate_random_reward_code():
17 return str(random.getrandbits(32))
18
19
20 class SaleOrder(models.Model):
21 _inherit = 'sale.order'
22
23 # Contains how much points should be given to a coupon upon validating the order
24 applied_coupon_ids = fields.Many2many(
25 string="Manually Applied Coupons", comodel_name='loyalty.card', copy=False
26 )
27 code_enabled_rule_ids = fields.Many2many(
28 string="Manually Triggered Rules", comodel_name='loyalty.rule', copy=False
29 )
30 coupon_point_ids = fields.One2many(
31 comodel_name='sale.order.coupon.points', inverse_name='order_id', copy=False
32 )
33 reward_amount = fields.Float(compute='_compute_reward_total')
34
35 # Display Fields
36 gift_card_count = fields.Integer(compute='_compute_gift_card_count')
37 loyalty_data = fields.Json(compute='_compute_loyalty_data')
38
39 @api.depends('order_line')
40 def _compute_reward_total(self):
41 for order in self:
42 reward_amount = 0
43 for line in order.order_line:
44 if not line.reward_id:
45 continue
46 if line.reward_id.reward_type != 'product':
47 reward_amount += line.price_subtotal
48 else:
49 # Free product are 'regular' product lines with a price_unit of 0
50 reward_amount -= line.product_id.lst_price * line.product_uom_qty
51 order.reward_amount = reward_amount
52
53 def _compute_loyalty_data(self):
54 self.loyalty_data = {}
55
56 confirmed_so = self.filtered(lambda order: order.state == 'sale' and bool(order.id))
57 if not confirmed_so:
58 return
59
60 loyalty_history_data = self.env['loyalty.history'].sudo()._read_group(
61 domain=[
62 ('order_id', 'in', confirmed_so.ids),
63 ('order_model', '=', self._name),
64 ],
65 groupby=['order_id'],
66 aggregates=['issued:sum', 'used:sum'],
67 )
68 loyalty_history_data_per_order = {
69 order_id: {
70 'total_issued': issued,
71 'total_cost': cost,
72 }
73 for order_id, issued, cost in loyalty_history_data
74 }
75 for order in confirmed_so:
76 if order.id not in loyalty_history_data_per_order:
77 continue
78 coupons = order.coupon_point_ids.coupon_id
79 coupon_point_name = (len(coupons) == 1 and coupons.point_name) or _("Points")
80 order.loyalty_data = {
81 'point_name': coupon_point_name,
82 'issued': loyalty_history_data_per_order[order.id]['total_issued'],
83 'cost': loyalty_history_data_per_order[order.id]['total_cost'],
84 }
85
86 def _compute_gift_card_count(self):
87 gift_card_data = dict(
88 self.env['loyalty.card']._read_group(
89 domain=[
90 ('order_id', 'in', self.ids),
91 ('program_type', '=', 'gift_card'),
92 ],
93 groupby=['order_id'],
94 aggregates=['__count'],
95 )
96 )
97 for order in self:
98 order.gift_card_count = gift_card_data.get(order, 0)
99
100 def _add_loyalty_history_lines(self):
101 self.ensure_one()
102 points_per_coupon = defaultdict(partial(defaultdict, int))
103 for coupon_point in self.coupon_point_ids:
104 points_per_coupon[coupon_point.coupon_id]['issued'] = coupon_point.points
105 for line in self.order_line:
106 if not line.coupon_id:
107 continue
108 points_per_coupon[line.coupon_id]['cost'] += line.points_cost
109
110 create_values = []
111 base_values = {
112 'order_id': self.id,
113 'order_model': self._name,
114 'description': _("Order %s", self.display_name),
115 }
116 for coupon, point_dict in points_per_coupon.items():
117 cost = point_dict.get('cost', 0.0)
118 issued = point_dict.get('issued', 0.0)
119 create_values.append({
120 **base_values,
121 'card_id': coupon.id,
122 'used': cost,
123 'issued': issued,
124 })
125
126 self.env['loyalty.history'].create(create_values)
127
128 def _get_no_effect_on_threshold_lines(self):
129 """Return the lines that have no effect on the minimum amount to reach."""
130 self.ensure_one()
131 return self.env['sale.order.line']
132
133 def copy(self, default=None):
134 new_orders = super().copy(default)
135 reward_lines = new_orders.order_line.filtered('is_reward_line')
136 if reward_lines:
137 reward_lines.unlink()
138 return new_orders
139
140 def action_confirm(self):
141 """
142 Override to validate and update coupon rewards.
143
144 If called with one SO, checks if there exists rewards that are available but not claimed,
145 and if so returns a notification action.
146
147 :raises ValidationError: A coupon gave a negative amount of points.
148 :return: True or a notification action
149 :rtype: bool | dict
150 """
151 for order in self:
152 all_coupons = order.applied_coupon_ids | order.coupon_point_ids.coupon_id | order.order_line.coupon_id
153 if any(order._get_real_points_for_coupon(coupon) < 0 for coupon in all_coupons):
154 raise ValidationError(_("One or more rewards on the sale order is invalid. Please check them."))
155 order._update_programs_and_rewards()
156 order._add_loyalty_history_lines()
157 has_claimable_rewards = len(self) == 1 and bool(self._get_claimable_rewards())
158
159 # Remove any coupon from 'current' program that don't claim any reward.
160 # This is to avoid ghost coupons that are lost forever.
161 # Claiming a reward for that program will require either an automated check or a manual input again.
162 reward_coupons = self.order_line.coupon_id
163 self.coupon_point_ids.filtered(
164 lambda pe: pe.coupon_id.program_id.applies_on == 'current' and pe.coupon_id not in reward_coupons
165 ).coupon_id.sudo().unlink()
166 # Add/remove the points to our coupons
167 for coupon, change in self.filtered(lambda s: s.state != 'sale')._get_point_changes().items():
168 coupon.points += change
169 res = super().action_confirm()
170 # Prioritize any action from super()
171 if isinstance(res, bool) and has_claimable_rewards:
172 res = {
173 'type': 'ir.actions.client',
174 'tag': 'display_notification',
175 'params': {
176 'type': 'info',
177 'title': _("Rewards Available"),
178 'message': _("There are available rewards not added to this order."),
179 'next': {'type': 'ir.actions.act_window_close'},
180 },
181 }
182 self._send_reward_coupon_mail()
183 return res
184
185 def _action_cancel(self):
186 previously_confirmed = self.filtered(lambda s: s.state == 'sale')
187 res = super()._action_cancel()
188
189 order_history_lines = self.env['loyalty.history'].search([
190 ('order_model', '=', self._name),
191 ('order_id', 'in', previously_confirmed.ids),
192 ])
193 if order_history_lines:
194 order_history_lines.sudo().unlink()
195
196 # Add/remove the points to our coupons
197 for coupon, changes in previously_confirmed.filtered(
198 lambda s: s.state != 'sale'
199 )._get_point_changes().items():
200 coupon.points -= changes
201 # Remove any rewards
202 self.order_line.filtered(lambda l: l.is_reward_line).unlink()
203 self.coupon_point_ids.coupon_id.sudo().filtered(
204 lambda c: not c.program_id.is_nominative and c.order_id in self and not c.use_count)\
205 .unlink()
206 self.coupon_point_ids.unlink()
207 return res
208
209 def action_open_reward_wizard(self):
210 self.ensure_one()
211 self._update_programs_and_rewards()
212 claimable_rewards = self._get_claimable_rewards()
213 if len(claimable_rewards) == 1:
214 coupon = next(iter(claimable_rewards))
215 rewards = claimable_rewards[coupon]
216 if len(rewards) == 1 and not rewards.multi_product:
217 self._apply_program_reward(claimable_rewards[coupon], coupon)
218 return True
219 elif not claimable_rewards:
220 return True
221 return self.env['ir.actions.actions']._for_xml_id('sale_loyalty.sale_loyalty_reward_wizard_action')
222
223 def action_view_gift_cards(self):
224 self.ensure_one()
225 return {
226 'name': _("Gift Cards"),
227 'type': 'ir.actions.act_window',
228 'view_mode': 'list,form',
229 'res_model': 'loyalty.card',
230 'domain': [('order_id', '=', self.id), ('program_type', '=', 'gift_card')],
231 'context': {'create': False},
232 }
233
234 def _send_reward_coupon_mail(self):
235 coupons = self.env['loyalty.card']
236 for order in self:
237 coupons |= order._get_reward_coupons()
238 if coupons:
239 coupons._send_creation_communication(force_send=True)
240
241 def _get_applied_global_discount_lines(self):
242 """
243 Returns the first line of the currently applied global discount or False
244 """
245 self.ensure_one()
246 return self.order_line.filtered(lambda l: l.reward_id.is_global_discount)
247
248 def _get_applied_global_discount(self):
249 """
250 Returns the currently applied global discount reward or False
251 """
252 return self._get_applied_global_discount_lines().reward_id
253
254 def _get_reward_values_product(self, reward, coupon, product=None, **kwargs):
255 """
256 Returns an array of dict containing the values required for the reward lines
257 """
258 self.ensure_one()
259 assert reward.reward_type == 'product'
260
261 reward_products = reward.reward_product_ids
262 product = product or reward_products[:1]
263 if not product or product not in reward_products:
264 raise UserError(_("Invalid product to claim."))
265 taxes = self.fiscal_position_id.map_tax(product.taxes_id._filter_taxes_by_company(self.company_id))
266 points = self._get_real_points_for_coupon(coupon)
267 claimable_count = float_round(points / reward.required_points, precision_rounding=1, rounding_method='DOWN') if not reward.clear_wallet else 1
268 cost = points if reward.clear_wallet else claimable_count * reward.required_points
269 return [{
270 'name': reward.description,
271 'product_id': product.id,
272 'discount': 100,
273 'product_uom_qty': reward.reward_product_qty * claimable_count,
274 'reward_id': reward.id,
275 'coupon_id': coupon.id,
276 'points_cost': cost,
277 'reward_identifier_code': _generate_random_reward_code(),
278 'sequence': max(self.order_line.filtered(lambda x: not x.is_reward_line).mapped('sequence'), default=10) + 1,
279 'tax_ids': [Command.clear()] + [Command.link(tax.id) for tax in taxes],
280 }]
281
282 def _discountable_amount(self, rewards_to_ignore):
283 """Compute the `discountable` amount for the current order, ignoring the provided rewards.
284
285 :param rewards_to_ignore: the rewards to ignore from the total amount (if they were already
286 applied on the order)
287 :type rewards_to_ignore: `loyalty.reward` recordset
288
289 :return: The discountable amount
290 :rtype: float
291 """
292 self.ensure_one()
293
294 discountable = 0
295
296 for line in self.order_line - self._get_no_effect_on_threshold_lines():
297 if rewards_to_ignore and line.reward_id in rewards_to_ignore:
298 # Ignore the existing reward line if it was already applied
299 continue
300 if not line.product_uom_qty or not line.price_unit:
301 # Ignore lines whose amount will be 0 (bc of empty qty or 0 price)
302 continue
303 tax_data = line.tax_ids.compute_all(
304 line.price_unit,
305 quantity=line.product_uom_qty,
306 product=line.product_id,
307 partner=line.order_partner_id,
308 )
309 # To compute the discountable amount we get the subtotal and add
310 # non-fixed tax totals. This way fixed taxes will not be discounted
311 taxes = line.tax_ids.filtered(lambda t: t.amount_type != 'fixed')
312 discountable += tax_data['total_excluded'] + sum(
313 tax['amount'] for tax in tax_data['taxes'] if tax['id'] in taxes.ids
314 )
315 return discountable
316
317 def _discountable_order(self, reward):
318 """Compute the `discountable` amount (and amounts per tax group) for the current order.
319
320 :param reward: if provided, the reward whose discountable amounts must be computed.
321 It must be applicable at the order level.
322 :type reward: `loyalty.reward` record, can be empty to compute the amounts regardless of the
323 program configuration
324
325 :return: A tuple with the first element being the total discountable amount of the order,
326 and the second a dictionary mapping each non-fixed taxes group to its corresponding
327 total untaxed amount of the eligible order lines.
328 :rtype: tuple(float, dict(account.tax: float))
329 """
330 self.ensure_one()
331 reward.ensure_one()
332 assert reward.discount_applicability == 'order'
333
334 lines = self.order_line.filtered(lambda line: not line.display_type)
335 if not reward.program_id.is_payment_program:
336 # Gift cards and eWallets are applied on the total order amount
337 # Other types of programs are not expected to apply on delivery lines
338 lines -= self._get_no_effect_on_threshold_lines()
339
340 discountable = 0
341 discountable_per_tax = defaultdict(float)
342
343 AccountTax = self.env['account.tax']
344 base_lines = []
345 for line in lines:
346 base_line = line._prepare_base_line_for_taxes_computation()
347 taxes = base_line['tax_ids'].flatten_taxes_hierarchy()
348 if not reward.program_id.is_payment_program:
349 # To compute the discountable amount we get the subtotal and add
350 # non-fixed tax totals. This way fixed taxes will not be discounted
351 # This does not apply to Gift Cards and e-Wallet, where the total
352 # order amount may be paid with the card balance
353 taxes = taxes.filtered(lambda t: t.amount_type != 'fixed')
354 base_line['discount_taxes'] = taxes
355 base_lines.append(base_line)
356 AccountTax._add_tax_details_in_base_lines(base_lines, self.company_id)
357 AccountTax._round_base_lines_tax_details(base_lines, self.company_id)
358
359 def grouping_function(base_line, tax_data):
360 if not tax_data:
361 return None
362 return {
363 'taxes': base_line['discount_taxes'],
364 'skip': (
365 tax_data['tax'] not in base_line['discount_taxes']
366 or base_line['record'] not in lines
367 ),
368 }
369
370 base_lines_aggregated_values = AccountTax._aggregate_base_lines_tax_details(base_lines, grouping_function)
371 values_per_grouping_key = AccountTax._aggregate_base_lines_aggregated_values(base_lines_aggregated_values)
372 for grouping_key, values in values_per_grouping_key.items():
373 if grouping_key and grouping_key['skip']:
374 continue
375
376 taxes = grouping_key['taxes'] if grouping_key else self.env['account.tax']
377 discountable += values['raw_base_amount_currency'] + values['raw_tax_amount_currency']
378 discountable_per_tax[taxes] += (
379 values['raw_base_amount_currency']
380 + sum(
381 tax_data['raw_tax_amount_currency']
382 for base_line, taxes_data in values['base_line_x_taxes_data']
383 for tax_data in taxes_data
384 if tax_data['tax'].price_include
385 )
386 )
387 return discountable, discountable_per_tax
388
389 def _cheapest_line(self, reward):
390 self.ensure_one()
391 cheapest_line = False
392 cheapest_line_price_unit = False
393 domain = reward._get_discount_product_domain()
394 for line in (self.order_line - self._get_no_effect_on_threshold_lines()):
395 line_price_unit = self._get_order_line_price(line, 'price_unit')
396 if (
397 line.reward_id
398 or line.combo_item_id
399 or not line.product_uom_qty
400 or not line_price_unit
401 or not line.product_id.filtered_domain(domain)
402 ):
403 continue
404 if not cheapest_line or cheapest_line_price_unit > line_price_unit:
405 cheapest_line = line._get_lines_with_price()
406 cheapest_line_price_unit = line_price_unit
407 return cheapest_line
408
409 def _discountable_cheapest(self, reward):
410 """
411 Returns the discountable and discountable_per_tax for a discount that applies to the cheapest line
412 """
413 self.ensure_one()
414 assert reward.discount_applicability == 'cheapest'
415
416 cheapest_line = self._cheapest_line(reward)
417 if not cheapest_line:
418 return False, False
419
420 discountable = 0
421 discountable_per_tax = defaultdict(int)
422 for line in cheapest_line:
423 discountable += line.price_total / line.product_uom_qty
424 taxes = line.tax_ids.filtered(lambda t: t.amount_type != 'fixed')
425 discountable_per_tax[taxes] += line.price_unit * (1 - (line.discount or 0) / 100)
426
427 return discountable, discountable_per_tax
428
429 def _get_specific_discountable_lines(self, reward):
430 """
431 Returns all lines to which `reward` can apply
432 """
433 self.ensure_one()
434 assert reward.discount_applicability == 'specific'
435
436 discountable_lines = self.env['sale.order.line']
437 for line in (self.order_line - self._get_no_effect_on_threshold_lines()):
438 domain = reward._get_discount_product_domain()
439 if (
440 not line.reward_id
441 and not line.combo_item_id
442 and line.product_id.filtered_domain(domain)
443 ):
444 discountable_lines |= line._get_lines_with_price()
445 return discountable_lines
446
447 def _discountable_specific(self, reward):
448 """
449 Special function to compute the discountable for 'specific' types of discount.
450 The goal of this function is to make sure that applying a 5$ discount on an order with a
451 5$ product and a 5% discount does not make the order go below 0.
452
453 Returns the discountable and discountable_per_tax for a discount that only applies to specific products.
454 """
455 self.ensure_one()
456 assert reward.discount_applicability == 'specific'
457
458 lines_to_discount = self._get_specific_discountable_lines(reward).filtered(
459 lambda line: bool(line.product_uom_qty and line.price_total)
460 )
461 discount_lines = defaultdict(lambda: self.env['sale.order.line'])
462 order_lines = self.order_line - self._get_no_effect_on_threshold_lines()
463 remaining_amount_per_line = defaultdict(int)
464 for line in order_lines:
465 if not line.product_uom_qty or not line.price_total:
466 continue
467 remaining_amount_per_line[line] = line.price_total
468 if line.reward_id.reward_type == 'discount':
469 discount_lines[line.reward_identifier_code] |= line
470
471 order_lines -= self.order_line.filtered('reward_id')
472 cheapest_line = False
473 for lines in discount_lines.values():
474 line_reward = lines.reward_id
475 discounted_lines = order_lines
476 if line_reward.discount_applicability == 'cheapest':
477 # get the discounted cheapest line applicable for given reward domain
478 cheapest_line = cheapest_line or self._cheapest_line(line_reward)
479 discounted_lines = cheapest_line
480 elif line_reward.discount_applicability == 'specific':
481 discounted_lines = self._get_specific_discountable_lines(line_reward)
482 if not discounted_lines:
483 continue
484 common_lines = discounted_lines & lines_to_discount
485 if line_reward.discount_mode == 'percent':
486 for line in discounted_lines:
487 if line_reward.discount_applicability == 'cheapest':
488 remaining_amount_per_line[line] *= (1 - line_reward.discount / 100 / line.product_uom_qty)
489 else:
490 remaining_amount_per_line[line] *= (1 - line_reward.discount / 100)
491 else:
492 non_common_lines = discounted_lines - lines_to_discount
493 # Fixed prices are per tax
494 discounted_amounts = defaultdict(int, {
495 sol.tax_ids.filtered(lambda t: t.amount_type != 'fixed'): abs(sol.price_total)
496 for sol in lines
497 })
498 for line in itertools.chain(non_common_lines, common_lines):
499 # For gift card and eWallet programs we have no tax but we can consume the amount completely
500 if lines.reward_id.program_id.is_payment_program:
501 discounted_amount = discounted_amounts[lines.tax_ids.filtered(lambda t: t.amount_type != 'fixed')]
502 else:
503 discounted_amount = discounted_amounts[line.tax_ids.filtered(lambda t: t.amount_type != 'fixed')]
504 if discounted_amount == 0:
505 continue
506 remaining = remaining_amount_per_line[line]
507 consumed = min(remaining, discounted_amount)
508 if lines.reward_id.program_id.is_payment_program:
509 discounted_amounts[lines.tax_ids.filtered(lambda t: t.amount_type != 'fixed')] -= consumed
510 else:
511 discounted_amounts[line.tax_ids.filtered(lambda t: t.amount_type != 'fixed')] -= consumed
512 remaining_amount_per_line[line] -= consumed
513
514 discountable = 0
515 discountable_per_tax = defaultdict(int)
516 for line in lines_to_discount:
517 discountable += remaining_amount_per_line[line]
518 line_discountable = line.price_unit * line.product_uom_qty * (1 - (line.discount or 0.0) / 100.0)
519 # line_discountable is the same as in a 'order' discount
520 # but first multiplied by a factor for the taxes to apply
521 # and then multiplied by another factor coming from the discountable
522 taxes = line.tax_ids.filtered(lambda t: t.amount_type != 'fixed')
523 discountable_per_tax[taxes] += line_discountable *\
524 (remaining_amount_per_line[line] / line.price_total)
525 return discountable, discountable_per_tax
526
527 def _get_reward_values_discount(self, reward, coupon, **kwargs):
528 self.ensure_one()
529 assert reward.reward_type == 'discount'
530
531 reward_applies_on = reward.discount_applicability
532 reward_product = reward.discount_line_product_id
533 reward_program = reward.program_id
534 reward_currency = reward.currency_id
535 sequence = max(
536 self.order_line.filtered(lambda x: not x.is_reward_line).mapped('sequence'),
537 default=10
538 ) + 1
539 base_reward_line_values = {
540 'product_id': reward_product.id,
541 'product_uom_qty': 1.0,
542 'tax_ids': [Command.clear()],
543 'name': reward.description,
544 'reward_id': reward.id,
545 'coupon_id': coupon.id,
546 'sequence': sequence,
547 'reward_identifier_code': _generate_random_reward_code(),
548 }
549
550 discountable = 0
551 discountable_per_tax = defaultdict(int)
552 if reward_applies_on == 'order':
553 discountable, discountable_per_tax = self._discountable_order(reward)
554 elif reward_applies_on == 'specific':
555 discountable, discountable_per_tax = self._discountable_specific(reward)
556 elif reward_applies_on == 'cheapest':
557 discountable, discountable_per_tax = self._discountable_cheapest(reward)
558
559 if not discountable:
560 if not reward_program.is_payment_program and any(line.reward_id.program_id.is_payment_program for line in self.order_line):
561 return [{
562 **base_reward_line_values,
563 'name': _("TEMPORARY DISCOUNT LINE"),
564 'price_unit': 0,
565 'product_uom_qty': 0,
566 'points_cost': 0,
567 }]
568 raise UserError(_("There is nothing to discount"))
569
570 max_discount = reward_currency._convert(reward.discount_max_amount, self.currency_id, self.company_id, fields.Date.today()) or float('inf')
571 # discount should never surpass the order's current total amount
572 max_discount = min(self.amount_total, max_discount)
573 if reward.discount_mode == 'per_point':
574 points = self._get_real_points_for_coupon(coupon)
575 if not reward_program.is_payment_program:
576 # Rewards cannot be partially offered to customers
577 points = points // reward.required_points * reward.required_points
578 max_discount = min(max_discount,
579 reward_currency._convert(reward.discount * points,
580 self.currency_id, self.company_id, fields.Date.today()))
581 elif reward.discount_mode == 'per_order':
582 max_discount = min(max_discount,
583 reward_currency._convert(reward.discount, self.currency_id, self.company_id, fields.Date.today()))
584 elif reward.discount_mode == 'percent':
585 max_discount = min(max_discount, discountable * (reward.discount / 100))
586
587 # Discount per taxes
588 point_cost = reward.required_points if not reward.clear_wallet else self._get_real_points_for_coupon(coupon)
589 if reward.discount_mode == 'per_point' and not reward.clear_wallet:
590 # Calculate the actual point cost if the cost is per point
591 converted_discount = self.currency_id._convert(min(max_discount, discountable), reward_currency, self.company_id, fields.Date.today())
592 point_cost = coupon.currency_id.round(converted_discount / reward.discount)
593
594 if reward_program.is_payment_program: # Gift card / eWallet
595 reward_line_values = {
596 **base_reward_line_values,
597 'price_unit': -min(max_discount, discountable),
598 'points_cost': point_cost,
599 }
600
601 if reward_program.program_type == 'gift_card':
602 # For gift cards, the SOL should consider the discount product taxes
603 taxes_to_apply = reward_product.taxes_id._filter_taxes_by_company(self.company_id)
604 if taxes_to_apply:
605 mapped_taxes = self.fiscal_position_id.map_tax(taxes_to_apply)
606 price_incl_taxes = mapped_taxes.filtered('price_include')
607 tax_res = mapped_taxes.with_context(
608 force_price_include=True,
609 round=False,
610 round_base=False,
611 ).compute_all(
612 reward_line_values['price_unit'],
613 currency=self.currency_id,
614 )
615 new_price = tax_res['total_excluded']
616 new_price += sum(
617 tax_data['amount']
618 for tax_data in tax_res['taxes']
619 if tax_data['id'] in price_incl_taxes.ids
620 )
621 reward_line_values.update({
622 'price_unit': new_price,
623 'tax_ids': [Command.set(mapped_taxes.ids)],
624 })
625 return [reward_line_values]
626
627 discount_factor = min(1, (max_discount / discountable)) if discountable else 1
628 reward_dict = {}
629 for tax, price in discountable_per_tax.items():
630 if not price:
631 continue
632 mapped_taxes = self.fiscal_position_id.map_tax(tax)
633 tax_desc = ''
634 if len(discountable_per_tax) > 1 and any(t.name for t in mapped_taxes):
635 tax_desc = _(
636 " - On products with the following taxes: %(taxes)s",
637 taxes=", ".join(mapped_taxes.mapped('name')),
638 )
639 reward_dict[tax] = {
640 **base_reward_line_values,
641 'name': _(
642 "Discount %(desc)s%(tax_str)s",
643 desc=reward.description,
644 tax_str=tax_desc,
645 ) if mapped_taxes else reward.description,
646 'price_unit': -(price * discount_factor),
647 'points_cost': 0,
648 'tax_ids': [Command.clear()] + [Command.link(tax.id) for tax in mapped_taxes]
649 }
650 # We only assign the point cost to one line to avoid counting the cost multiple times
651 if reward_dict:
652 reward_dict[next(iter(reward_dict))]['points_cost'] = point_cost
653 # Returning .values() directly does not return a subscribable list
654 return list(reward_dict.values())
655
656 def _get_program_domain(self):
657 """
658 Returns the base domain that all programs have to comply to.
659 """
660 self.ensure_one()
661 today = self._get_confirmed_tx_create_date()
662 return [('active', '=', True), ('sale_ok', '=', True),
663 *self.env['loyalty.program']._check_company_domain([self.company_id.id, self.company_id.parent_id.id]),
664 '|', ('pricelist_ids', '=', False), ('pricelist_ids', 'in', [self.pricelist_id.id]),
665 '|', ('date_from', '=', False), ('date_from', '<=', today),
666 '|', ('date_to', '=', False), ('date_to', '>=', today)]
667
668 def _get_trigger_domain(self):
669 """
670 Returns the base domain that all triggers have to comply to.
671 """
672 self.ensure_one()
673 today = self._get_confirmed_tx_create_date()
674 return [('active', '=', True), ('program_id.sale_ok', '=', True),
675 *self.env['loyalty.program']._check_company_domain([self.company_id.id, self.company_id.parent_id.id]),
676 '|', ('program_id.pricelist_ids', '=', False),
677 ('program_id.pricelist_ids', 'in', [self.pricelist_id.id]),
678 '|', ('program_id.date_from', '=', False), ('program_id.date_from', '<=', today),
679 '|', ('program_id.date_to', '=', False), ('program_id.date_to', '>=', today)]
680
681 def _get_program_timezone(self):
682 """Get the timezone to be used for loyalty date checking on the current order."""
683 self.ensure_one()
684 return (
685 self.company_id.partner_id.tz
686 or self.env['ir.config_parameter'].sudo().get_param('loyalty.timezone', 'UTC')
687 )
688
689 def _get_confirmed_tx_create_date(self):
690 """Return the creation date of the earliest confirmed transaction to check which loyalty
691 programs are applicable. If no transactions are confirmed, return the current day, using
692 the company's time zone.
693 """
694 self.ensure_one()
695 order_tz = self._get_program_timezone()
696 confirmed_txs_dates = self.sudo().transaction_ids.filtered(
697 lambda tx: tx.state in ('done', 'authorized'),
698 ).mapped('create_date')
699 if confirmed_txs_dates:
700 # If order is getting confirmed, use the earliest finalized transaction's create date
701 tx_date = min(confirmed_txs_dates)
702 return tx_date.astimezone(timezone(order_tz)).date()
703 return fields.Date.context_today(self.with_context(tz=order_tz))
704
705 def _get_applicable_program_points(self, domain=None):
706 """
707 Returns a dict with the points per program for each (automatic) program that is applicable
708 """
709 self.ensure_one()
710 if not domain:
711 domain = [('trigger', '=', 'auto')]
712 # Make sure domain always complies with the order's domain rules
713 domain = Domain.AND([self._get_program_domain(), domain])
714 # No other way than to test all programs to the order
715 programs = self.env['loyalty.program'].search(domain)
716 all_status = self._program_check_compute_points(programs)
717 program_points = {p: status['points'][0] for p, status in all_status.items() if 'points' in status}
718 return program_points
719
720 def _get_points_programs(self):
721 """
722 Returns all programs that give points on the current order.
723 """
724 self.ensure_one()
725 return self.coupon_point_ids.filtered('points').coupon_id.program_id
726
727 def _get_reward_programs(self):
728 """
729 Returns all programs that are being used for rewards.
730 """
731 self.ensure_one()
732 return self.order_line.reward_id.program_id
733
734 def _get_reward_coupons(self):
735 """
736 Returns all coupons that are a reward.
737 """
738 self.ensure_one()
739 return self.coupon_point_ids.filtered('points').coupon_id.filtered(
740 lambda c: c.program_id.applies_on == 'future',
741 )
742
743 def _get_applied_programs(self):
744 """
745 Returns all applied programs on current order.
746
747 Applied programs is the combination of both new points for your order and the programs linked to rewards.
748 """
749 self.ensure_one()
750 return self._get_points_programs() | self._get_reward_programs()
751
752 def _recompute_prices(self):
753 """Recompute coupons/promotions after pricelist prices reset."""
754 super()._recompute_prices()
755 for order in self:
756 if any(line.is_reward_line for line in order.order_line):
757 order._update_programs_and_rewards()
758
759 def _get_point_changes(self):
760 """
761 Returns the changes in points per coupon as a dict.
762
763 Used when validating/cancelling an order
764 """
765 points_per_coupon = defaultdict(lambda: 0)
766 for coupon_point in self.coupon_point_ids:
767 points_per_coupon[coupon_point.coupon_id] += coupon_point.points
768 for line in self.order_line:
769 if not line.reward_id or not line.coupon_id:
770 continue
771 points_per_coupon[line.coupon_id] -= line.points_cost
772 return points_per_coupon
773
774 def _get_real_points_for_coupon(self, coupon, post_confirm=False):
775 """
776 Returns the actual points usable for this coupon for this order. Set pos_confirm to True to include points for future orders.
777
778 This is calculated by taking the points on the coupon, the points the order will give to the coupon (if applicable) and removing the points taken by already applied rewards.
779 """
780 self.ensure_one()
781 points = coupon.points
782 if self.state not in ('sale', 'done'):
783 if coupon.program_id.applies_on != 'future':
784 # Points that will be given by the order upon confirming the order
785 points += self.coupon_point_ids.filtered(lambda p: p.coupon_id == coupon).points
786 # Points already used by rewards
787 points -= sum(self.order_line.filtered(lambda l: l.coupon_id == coupon).mapped('points_cost'))
788 points = coupon.currency_id.round(points)
789 return points
790
791 def _add_points_for_coupon(self, coupon_points):
792 """
793 Updates (or creates) an entry in coupon_point_ids for the given coupons.
794 """
795 self.ensure_one()
796 if self.state == 'sale':
797 for coupon, points in coupon_points.items():
798 coupon.sudo().points += points
799 for pe in self.coupon_point_ids.sudo():
800 if pe.coupon_id in coupon_points:
801 pe.points = coupon_points.pop(pe.coupon_id)
802 if coupon_points:
803 self.sudo().with_context(tracking_disable=True).write({
804 'coupon_point_ids': [(0, 0, {
805 'coupon_id': coupon.id,
806 'points': points,
807 }) for coupon, points in coupon_points.items()]
808 })
809
810 def _update_loyalty_history(self, coupon_id, points):
811 self.ensure_one()
812 order_coupon_history = self.env['loyalty.history'].search([
813 ('card_id', '=', coupon_id.id),
814 ('order_model', '=', self._name),
815 ('order_id', '=', self.id),
816 ], limit=1)
817 order_coupon_history.update({
818 'used': order_coupon_history.used + points,
819 })
820
821 def _remove_program_from_points(self, programs):
822 self.coupon_point_ids.filtered(lambda p: p.coupon_id.program_id in programs).sudo().unlink()
823
824 def _get_reward_line_values(self, reward, coupon, **kwargs):
825 self.ensure_one()
826 self = self.with_context(lang=self._get_lang())
827 reward = reward.with_context(lang=self._get_lang())
828 if reward.reward_type == 'discount':
829 return self._get_reward_values_discount(reward, coupon, **kwargs)
830 elif reward.reward_type == 'product':
831 return self._get_reward_values_product(reward, coupon, **kwargs)
832
833 def _write_vals_from_reward_vals(self, reward_vals, old_lines, delete=True):
834 """
835 Update, create new reward line and delete old lines in one write on `order_line`
836
837 Returns the untouched old lines.
838 """
839 self.ensure_one()
840 command_list = []
841 for vals, line in zip(reward_vals, old_lines):
842 if vals['product_id'] == line.product_id.id:
843 vals['name'] = line.name # Preserve custom description
844 command_list.append((Command.UPDATE, line.id, vals))
845 if len(reward_vals) > len(old_lines):
846 command_list.extend((Command.CREATE, 0, vals) for vals in reward_vals[len(old_lines):])
847 elif len(reward_vals) < len(old_lines) and delete:
848 command_list.extend((Command.DELETE, line.id) for line in old_lines[len(reward_vals):])
849 self.write({'order_line': command_list})
850 return self.env['sale.order.line'] if delete else old_lines[len(reward_vals):]
851
852 def _best_global_discount_already_applied(self, current_reward, new_reward, discountable=None):
853 """Determine whether current_reward is better than new_reward.
854
855 This function compares the discount amount of two rewards to determine whether the current
856 one is better than another one.
857
858 Notes
859 -----
860
861 If the discount amounts of both the current and the new rewards exceed the order total,
862 the reward with the smaller discount amount is considered the best.
863 This is to ensure that the most advantageous discount is applied for the customer,
864 who will keep the most important voucher, having saved the same amount in the end.
865
866 :param loyalty.reward current_reward: The reward currently applied on the sale order.
867 :param loyalty.reward new_reward: The reward to compare with.
868 :param float discountable: The total discountable amount of the sale order.
869 If not provided, it will be calculated on the fly.
870 :return: True if current_reward is considered better than new_reward.
871 :rtype: bool
872 """
873 self.ensure_one()
874 current_reward.ensure_one()
875 new_reward.ensure_one()
876
877 if current_reward == new_reward:
878 return True
879
880 if discountable is None: # Only recompute if discountable is not given, not if its zero
881 discountable = self._discountable_amount(current_reward)
882
883 discount_current_reward = self._get_discount_amount(current_reward, discountable)
884 discount_new_reward = self._get_discount_amount(new_reward, discountable)
885
886 discount_current_bigger_than_discountable = self.currency_id.compare_amounts(
887 amount1=discount_current_reward,
888 amount2=discountable,
889 ) >= 0
890 discount_new_bigger_than_discountable = self.currency_id.compare_amounts(
891 amount1=discount_new_reward,
892 amount2=discountable,
893 ) >= 0
894 compare_current_and_new_reward = self.currency_id.compare_amounts(
895 amount1=discount_current_reward,
896 amount2=discount_new_reward,
897 )
898
899 if discount_current_bigger_than_discountable and discount_new_bigger_than_discountable:
900 # If both discounts are greater than the discountable amount, the lower discount
901 # is better as it reduces the discount amount 'spent' by the customer.
902 return compare_current_and_new_reward <= 0
903
904 # Return True only if the discount of the new reward is greater than the current reward
905 # discount.
906 return compare_current_and_new_reward >= 0
907
908 def _get_discount_amount(self, reward, discountable):
909 """Compute the discount amount for the given reward, w.r.t. the discountable amount.
910
911 :param loyalty.reward reward: The reward for which to calculate the maximum discount.
912 :param float discountable: The total discountable amount of the sale order.
913 :return: The maximum discount amount.
914 :rtype: float
915 """
916 if reward.discount_mode == 'per_order':
917 return reward.currency_id._convert(
918 from_amount=reward.discount,
919 to_currency=self.currency_id,
920 company=self.company_id,
921 date=fields.Date.today(),
922 )
923 elif reward.discount_mode == 'percent':
924 return discountable * (reward.discount / 100)
925
926 def _apply_program_reward(self, reward, coupon, **kwargs):
927 """
928 Applies the reward to the order provided the given coupon has enough points.
929 This method does not check for program rules.
930
931 This method also assumes the points added by the program triggers have already been computed.
932 The temporary points are used if the program is applicable to the current order.
933
934 Returns a dict containing the error message or empty if everything went correctly.
935 NOTE: A call to `_update_programs_and_rewards` is expected to reorder the discounts.
936 """
937 self.ensure_one()
938 # Use the old lines before creating new ones. These should already be in a 'reset' state.
939 old_reward_lines = kwargs.get('old_lines', self.env['sale.order.line'])
940 if reward.is_global_discount:
941 global_discount_reward_lines = self._get_applied_global_discount_lines()
942 global_discount_reward = global_discount_reward_lines.reward_id
943 if (
944 global_discount_reward
945 and global_discount_reward != reward
946 and self._best_global_discount_already_applied(global_discount_reward, reward)
947 ):
948 return {'error': _("A better global discount is already applied.")}
949 elif global_discount_reward and global_discount_reward != reward:
950 # Invalidate the old global discount as it may impact the new discount to apply
951 global_discount_reward_lines._reset_loyalty(True)
952 old_reward_lines |= global_discount_reward_lines
953 if not reward.program_id.is_nominative and reward.program_id.applies_on == 'future' and coupon in self.coupon_point_ids.coupon_id:
954 return {'error': _("The coupon can only be claimed on future orders.")}
955 elif self._get_real_points_for_coupon(coupon) < reward.required_points:
956 return {'error': _("The coupon does not have enough points for the selected reward.")}
957 reward_vals = self._get_reward_line_values(reward, coupon, **kwargs)
958 self._write_vals_from_reward_vals(reward_vals, old_reward_lines)
959 return {}
960
961 def _get_claimable_rewards(self, forced_coupons=None):
962 """
963 Fetch all rewards that are currently claimable from all concerned coupons,
964 meaning coupons from applied programs and applied rewards or the coupons given as parameter.
965
966 Returns a dict containing the all the claimable rewards grouped by coupon.
967 Coupons that can not claim any reward are not contained in the result.
968 """
969 self.ensure_one()
970 result = defaultdict(lambda: self.env['loyalty.reward'])
971
972 all_coupons = forced_coupons or (self.coupon_point_ids.coupon_id | self.order_line.coupon_id | self.applied_coupon_ids)
973 if not all_coupons:
974 return result
975
976 has_payment_reward = any(line.reward_id.program_id.is_payment_program for line in self.order_line)
977 global_discount_reward = self._get_applied_global_discount()
978 active_products_domain = self.env['loyalty.reward']._get_active_products_domain()
979
980 # Only evaluate discountable amount if needed
981 discountable = lazy(lambda: self._discountable_amount(global_discount_reward))
982 total_is_zero = lazy(lambda: self.currency_id.is_zero(discountable))
983
984 for coupon in all_coupons:
985 # Skip coupons generated by this order that only apply on future orders
986 if coupon.program_id.applies_on == 'future' and coupon.order_id == self:
987 continue
988 points = self._get_real_points_for_coupon(coupon)
989 for reward in coupon.program_id.reward_ids:
990 if (
991 reward.is_global_discount
992 and global_discount_reward
993 and self._best_global_discount_already_applied(
994 global_discount_reward, reward, discountable
995 )
996 ):
997 continue
998 # Discounts are not allowed if the total is zero unless there is a payment reward, in which case we allow discounts.
999 # If the total is 0 again without the payment reward it will be removed.
1000 is_discount = reward.reward_type == 'discount'
1001 is_payment_program = reward.program_id.is_payment_program
1002 if is_discount and total_is_zero and (not has_payment_reward or is_payment_program):
1003 continue
1004 # Skip discount that has already been applied if not part of a payment program
1005 if is_discount and not is_payment_program and reward in self.order_line.reward_id:
1006 continue
1007 if reward.reward_type == 'product' and not reward.filtered_domain(
1008 active_products_domain
1009 ):
1010 continue
1011 if points >= reward.required_points:
1012 result[coupon] |= reward
1013 return result
1014
1015 def _allow_nominative_programs(self):
1016 """
1017 Whether or not this order may use nominative programs.
1018 """
1019 self.ensure_one()
1020 return True
1021
1022 def _update_programs_and_rewards(self):
1023 """
1024 Updates applied programs's given points with the current state of the order.
1025 Checks automatic programs for applicability.
1026 Updates applied rewards using the new points and the current state of the order (for example with % discounts).
1027 """
1028 self.ensure_one()
1029
1030 # +===================================================+
1031 # | STEP 1: Retrieve all applicable programs |
1032 # +===================================================+
1033
1034 # Automatically load in eWallet and loyalty cards coupons with previously received points
1035 if self._allow_nominative_programs():
1036 loyalty_card = self.env['loyalty.card'].search([
1037 ('id', 'not in', self.applied_coupon_ids.ids),
1038 ('partner_id', '=', self.partner_id.id),
1039 ('points', '>', 0),
1040 '|', ('program_id.program_type', '=', 'ewallet'),
1041 '&', ('program_id.program_type', '=', 'loyalty'),
1042 ('program_id.applies_on', '!=', 'current'),
1043 ])
1044 if loyalty_card:
1045 self.applied_coupon_ids += loyalty_card
1046 # Programs that are applied to the order and count points
1047 points_programs = self._get_points_programs()
1048 # Coupon programs that require the program's rules to match but do not count for points
1049 coupon_programs = self.applied_coupon_ids.program_id
1050 # Programs that are automatic and not yet applied
1051 program_domain = self._get_program_domain()
1052 domain = Domain.AND([program_domain, [('id', 'not in', points_programs.ids), ('trigger', '=', 'auto'), ('rule_ids.mode', '=', 'auto')]])
1053 automatic_programs = self.env['loyalty.program'].search(domain).filtered(lambda p:
1054 not p.limit_usage or p.total_order_count < p.max_usage)
1055
1056 all_programs_to_check = points_programs | coupon_programs | automatic_programs
1057 all_coupons = self.coupon_point_ids.coupon_id | self.applied_coupon_ids
1058 # First basic check using the program_domain -> for example if a program gets archived mid quotation
1059 domain_matching_programs = all_programs_to_check.filtered_domain(program_domain)
1060 all_programs_status = {p: {'error': 'error'} for p in all_programs_to_check - domain_matching_programs}
1061 # Compute applicability and points given for all programs that passed the domain check
1062 # Note that points are computed with reward lines present
1063 all_programs_status.update(self._program_check_compute_points(domain_matching_programs))
1064 # Delay any unlink to the end of the function since they cause a full cache invalidation
1065 lines_to_unlink = self.env['sale.order.line']
1066 coupons_to_unlink = self.env['loyalty.card']
1067 point_entries_to_unlink = self.env['sale.order.coupon.points']
1068 # Remove any coupons that are expired
1069 if initial_coupons := self.applied_coupon_ids:
1070 check_date = self._get_confirmed_tx_create_date()
1071 self.applied_coupon_ids = initial_coupons.filtered(
1072 lambda c: not c.expiration_date or c.expiration_date >= check_date,
1073 )
1074 removed = initial_coupons - self.applied_coupon_ids
1075 lines_to_unlink |= self.order_line.filtered(lambda sol: sol.coupon_id in removed)
1076 point_ids_per_program = defaultdict(lambda: self.env['sale.order.coupon.points'])
1077 for pe in self.coupon_point_ids:
1078 # Update coupons that were created for Public User
1079 if pe.coupon_id.partner_id.is_public and not self.partner_id.is_public:
1080 pe.coupon_id.partner_id = self.partner_id
1081 # Remove any point entry for a coupon that does not belong to the customer
1082 if pe.coupon_id.partner_id and pe.coupon_id.partner_id != self.partner_id:
1083 pe.points = 0
1084 point_entries_to_unlink |= pe
1085 else:
1086 point_ids_per_program[pe.coupon_id.program_id] |= pe
1087
1088 # +==========================================+
1089 # | STEP 2: Update applied programs |
1090 # +==========================================+
1091
1092 # Programs that were not applied via a coupon
1093 for program in points_programs:
1094 status = all_programs_status[program]
1095 program_point_entries = point_ids_per_program[program]
1096 if 'error' in status:
1097 # Program is not applicable anymore
1098 coupons_from_order = program_point_entries.coupon_id.filtered(lambda c: c.order_id == self)
1099 all_coupons -= coupons_from_order
1100 # Invalidate those lines so that they don't impact anything further down the line
1101 program_reward_lines = self.order_line.filtered(lambda l: l.coupon_id in coupons_from_order)
1102 program_reward_lines._reset_loyalty(True)
1103 lines_to_unlink |= program_reward_lines
1104 # Delete coupon created by this order for this program if it is not nominative
1105 if not program.is_nominative:
1106 coupons_to_unlink |= coupons_from_order
1107 else:
1108 # Only remove the coupon_point_id
1109 point_entries_to_unlink |= program_point_entries
1110 point_entries_to_unlink.points = 0
1111 # Remove the code activated rules
1112 self.code_enabled_rule_ids -= program.rule_ids
1113 else:
1114 # Program stays applicable, update our points
1115 all_point_changes = [p for p in status['points'] if p]
1116 if not all_point_changes and program.is_nominative:
1117 all_point_changes = [0]
1118 for pe, points in zip(program_point_entries.sudo(), all_point_changes):
1119 pe.points = points
1120 if len(program_point_entries) < len(all_point_changes):
1121 new_coupon_points = all_point_changes[len(program_point_entries):]
1122 # next_order_coupons should be linked to the order's partner
1123 partner_id = program.program_type == 'next_order_coupons' and self.partner_id.id
1124 # NOTE: Maybe we could batch the creation of coupons across multiple programs but this really only applies to gift cards
1125 new_coupons = self.env['loyalty.card'].with_context(loyalty_no_mail=True, tracking_disable=True).create([{
1126 'program_id': program.id,
1127 'partner_id': partner_id,
1128 'points': 0,
1129 'order_id': self.id,
1130 } for _ in new_coupon_points])
1131 self._add_points_for_coupon({coupon: x for coupon, x in zip(new_coupons, new_coupon_points)})
1132 elif len(program_point_entries) > len(all_point_changes):
1133 point_ids_to_unlink = program_point_entries[len(all_point_changes):]
1134 all_coupons -= point_ids_to_unlink.coupon_id
1135 coupons_to_unlink |= point_ids_to_unlink.coupon_id
1136 point_ids_to_unlink.points = 0
1137
1138 # Programs applied using a coupon
1139 applied_coupon_per_program = defaultdict(lambda: self.env['loyalty.card'])
1140 for coupon in self.applied_coupon_ids:
1141 applied_coupon_per_program[coupon.program_id] |= coupon
1142 for program in coupon_programs:
1143 if program not in domain_matching_programs or\
1144 (program.applies_on == 'current' and 'error' in all_programs_status[program]):
1145 program_reward_lines = self.order_line.filtered(lambda l: l.coupon_id in applied_coupon_per_program[program])
1146 program_reward_lines._reset_loyalty(True)
1147 lines_to_unlink |= program_reward_lines
1148 self.applied_coupon_ids -= applied_coupon_per_program[program]
1149 all_coupons -= applied_coupon_per_program[program]
1150
1151 # +==========================================+
1152 # | STEP 3: Update reward lines |
1153 # +==========================================+
1154
1155 # We will reuse these lines as much as possible, this resets the order in a reward-less state
1156 reward_line_pool = self.order_line.filtered(lambda l: l.reward_id and l.coupon_id)._reset_loyalty()
1157 seen_rewards = set()
1158 line_rewards = []
1159 payment_rewards = [] # gift_card and ewallet are considered as payments and should always be applied last
1160 for line in self.order_line:
1161 if line.reward_identifier_code in seen_rewards or not line.reward_id or\
1162 not line.coupon_id:
1163 continue
1164 seen_rewards.add(line.reward_identifier_code)
1165 if line.reward_id.program_id.is_payment_program:
1166 payment_rewards.append((line.reward_id, line.coupon_id, line.reward_identifier_code, line.product_id))
1167 else:
1168 line_rewards.append((line.reward_id, line.coupon_id, line.reward_identifier_code, line.product_id))
1169
1170 for reward_key in itertools.chain(line_rewards, payment_rewards):
1171 coupon = reward_key[1]
1172 reward = reward_key[0]
1173 program = reward.program_id
1174 points = self._get_real_points_for_coupon(coupon)
1175 if coupon not in all_coupons or points < reward.required_points or program not in domain_matching_programs:
1176 # Reward is not applicable anymore, the reward lines will simply be removed at the end of this function
1177 continue
1178 try:
1179 values_list = self._get_reward_line_values(reward, coupon, product=reward_key[3])
1180 except UserError:
1181 # It could happen that we have nothing to discount after changing the order.
1182 values_list = []
1183 reward_line_pool = self._write_vals_from_reward_vals(values_list, reward_line_pool, delete=False)
1184
1185 lines_to_unlink |= reward_line_pool
1186
1187 # +==========================================+
1188 # | STEP 4: Apply new programs |
1189 # +==========================================+
1190
1191 for program in automatic_programs:
1192 program_status = all_programs_status[program]
1193 if 'error' in program_status:
1194 continue
1195 self.__try_apply_program(program, False, program_status)
1196
1197 # +==========================================+
1198 # | STEP 5: Cleanup |
1199 # +==========================================+
1200
1201 order_line_update = [(Command.DELETE, line.id) for line in lines_to_unlink]
1202 if order_line_update:
1203 self.write({'order_line': order_line_update})
1204 if coupons_to_unlink:
1205 coupons_to_unlink.sudo().unlink()
1206 if point_entries_to_unlink:
1207 point_entries_to_unlink.sudo().unlink()
1208
1209 def _get_not_rewarded_order_lines(self):
1210 return self.order_line.filtered(lambda line: line.product_id and not line.reward_id)
1211
1212 def _get_order_line_price(self, order_line, price_type):
1213 return sum(order_line._get_lines_with_price().mapped(price_type))
1214
1215 def _program_check_compute_points(self, programs):
1216 """
1217 Checks the program validity from the order lines aswell as computing the number of points to add.
1218
1219 Returns a dict containing the error message or the points that will be given with the keys 'points'.
1220 """
1221 self.ensure_one()
1222
1223 # Prepare quantities
1224 order_lines = self._get_not_rewarded_order_lines().filtered(
1225 lambda line: not line.combo_item_id
1226 )
1227 products = order_lines.product_id
1228 products_qties = dict.fromkeys(products, 0)
1229 for line in order_lines:
1230 products_qties[line.product_id] += line.product_uom_qty
1231 # Contains the products that can be applied per rule
1232 products_per_rule = programs._get_valid_products(products)
1233
1234 # Prepare amounts
1235 so_products_per_rule = programs._get_valid_products(self.order_line.product_id)
1236 lines_per_rule = defaultdict(lambda: self.env['sale.order.line'])
1237 # Skip lines that have no effect on the minimum amount to reach.
1238 for line in self.order_line - self._get_no_effect_on_threshold_lines():
1239 is_discount = line.reward_id.reward_type == 'discount'
1240 reward_program = line.reward_id.program_id
1241 # Skip lines for automatic discounts, as well as combo item lines.
1242 if (is_discount and reward_program.trigger == 'auto') or line.combo_item_id:
1243 continue
1244 for program in programs:
1245 # Skip lines for the current program's discounts.
1246 if is_discount and reward_program == program:
1247 continue
1248 for rule in program.rule_ids:
1249 # Skip lines to which the rule doesn't apply.
1250 if line.product_id in so_products_per_rule.get(rule, []):
1251 lines_per_rule[rule] |= line._get_lines_with_price()
1252
1253 result = {}
1254 for program in programs:
1255 # Used for error messages
1256 # By default False, but True if no rules and applies_on current -> misconfigured coupons program
1257 code_matched = not bool(program.rule_ids) and program.applies_on == 'current' # Stays false if all triggers have code and none have been activated
1258 minimum_amount_matched = code_matched
1259 product_qty_matched = code_matched
1260 points = 0
1261 # Some rules may split their points per unit / money spent
1262 # (i.e. gift cards 2x50$ must result in two 50$ codes)
1263 rule_points = []
1264 program_result = result.setdefault(program, dict())
1265 for rule in program.rule_ids:
1266 # prevent bottomless ewallet spending
1267 if program.program_type == 'ewallet' and not program.trigger_product_ids:
1268 break
1269 if rule.mode == 'with_code' and rule not in self.code_enabled_rule_ids:
1270 continue
1271 code_matched = True
1272 rule_amount = rule._compute_amount(self.currency_id)
1273 untaxed_amount = sum(lines_per_rule[rule].mapped('price_subtotal'))
1274 tax_amount = sum(lines_per_rule[rule].mapped('price_tax'))
1275 if rule_amount > (rule.minimum_amount_tax_mode == 'incl' and (untaxed_amount + tax_amount) or untaxed_amount):
1276 continue
1277 minimum_amount_matched = True
1278 if not products_per_rule.get(rule):
1279 continue
1280 rule_products = products_per_rule[rule]
1281 ordered_rule_products_qty = sum(products_qties[product] for product in rule_products)
1282 if ordered_rule_products_qty < rule.minimum_qty or not rule_products:
1283 continue
1284 product_qty_matched = True
1285 if not rule.reward_point_amount:
1286 continue
1287 # Count all points separately if the order is for the future and the split option is enabled
1288 if program.applies_on == 'future' and rule.reward_point_split and rule.reward_point_mode != 'order':
1289 if rule.reward_point_mode == 'unit':
1290 rule_points.extend(rule.reward_point_amount for _ in range(int(ordered_rule_products_qty)))
1291 elif rule.reward_point_mode == 'money':
1292 for line in self.order_line:
1293 if (
1294 line.is_reward_line
1295 or line.combo_item_id
1296 or line.product_id not in rule_products
1297 or line.product_uom_qty <= 0
1298 ):
1299 continue
1300 line_price_total = self._get_order_line_price(line, 'price_total')
1301 points_per_unit = float_round(
1302 (rule.reward_point_amount * line_price_total / line.product_uom_qty),
1303 precision_digits=2, rounding_method='DOWN')
1304 if not points_per_unit:
1305 continue
1306 rule_points.extend([points_per_unit] * int(line.product_uom_qty))
1307 else:
1308 # All checks have been passed we can now compute the points to give
1309 if rule.reward_point_mode == 'order':
1310 points += rule.reward_point_amount
1311 elif rule.reward_point_mode == 'money':
1312 # Compute amount paid for rule
1313 # NOTE: this accounts for discounts -> 1 point per $ * (100$ - 30%) will
1314 # result in 70 points
1315 amount_paid = 0.0
1316 rule_products = so_products_per_rule.get(rule, [])
1317 for line in self.order_line - self._get_no_effect_on_threshold_lines():
1318 if line.combo_item_id or line.reward_id.program_id.program_type in [
1319 'ewallet', 'gift_card', program.program_type
1320 ]:
1321 continue
1322 line_price_total = self._get_order_line_price(line, 'price_total')
1323 amount_paid += (
1324 line_price_total if line.product_id in rule_products
1325 else 0.0
1326 )
1327
1328 points += float_round(rule.reward_point_amount * amount_paid, precision_digits=2, rounding_method='DOWN')
1329 elif rule.reward_point_mode == 'unit':
1330 points += rule.reward_point_amount * ordered_rule_products_qty
1331 # NOTE: for programs that are nominative we always allow the program to be 'applied' on the order
1332 # with 0 points so that `_get_claimable_rewards` returns the rewards associated with those programs
1333 if not program.is_nominative:
1334 if not code_matched:
1335 program_result['error'] = _("This program requires a code to be applied.")
1336 elif not minimum_amount_matched:
1337 program_result['error'] = _(
1338 "A minimum of %(amount)s %(currency)s should be purchased to get the reward",
1339 amount=min(program.rule_ids.mapped('minimum_amount')),
1340 currency=program.currency_id.name,
1341 )
1342 elif not product_qty_matched:
1343 program_result['error'] = _("You don't have the required product quantities on your sales order.")
1344 elif self.partner_id.is_public and not self._allow_nominative_programs():
1345 program_result['error'] = _("This program is not available for public users.")
1346 if 'error' not in program_result:
1347 points_result = [points] + rule_points
1348 program_result['points'] = points_result
1349 return result
1350
1351 def __try_apply_program(self, program, coupon, status):
1352 self.ensure_one()
1353 all_points = status['points']
1354 points = all_points[0]
1355 coupons = coupon or self.env['loyalty.card']
1356 if coupon:
1357 if program.is_nominative:
1358 self._add_points_for_coupon({coupon: points})
1359 elif not coupon:
1360 # If the program only applies on the current order it does not make sense to fetch already existing coupons
1361 if program.is_nominative:
1362 coupon = self.env['loyalty.card'].search(
1363 [('partner_id', '=', self.partner_id.id), ('program_id', '=', program.id)], limit=1)
1364 # Do not apply 'nominative' programs if no point is given and no coupon exists
1365 if not points and not coupon:
1366 return {'error': _("No card found for this loyalty program and no points will be given with this order.")}
1367 elif coupon:
1368 self._add_points_for_coupon({coupon: points})
1369 coupons = coupon
1370 if not coupon:
1371 all_points = [p for p in all_points if p]
1372 partner = False
1373 # Loyalty programs and ewallets are nominative
1374 if program.is_nominative or program.program_type == 'next_order_coupons':
1375 partner = self.partner_id.id
1376 coupons = self.env['loyalty.card'].sudo().with_context(loyalty_no_mail=True, tracking_disable=True).create([{
1377 'program_id': program.id,
1378 'partner_id': partner,
1379 'points': 0,
1380 'order_id': self.id,
1381 } for _ in all_points])
1382 self._add_points_for_coupon({coupon: x for coupon, x in zip(coupons, all_points)})
1383 return {'coupon': coupons}
1384
1385 def _try_apply_program(self, program, coupon=None):
1386 """
1387 Tries to apply a program using the coupon if provided.
1388
1389 This function provides the full routine to apply a program, it will check for applicability
1390 aswell as creating the necessary coupons and co-models to give the points to the customer.
1391
1392 This function does not apply any reward to the order, rewards have to be given manually.
1393
1394 Returns a dict containing the error message or containing the associated coupon(s).
1395 """
1396 self.ensure_one()
1397 # Basic checks
1398 if not program.filtered_domain(self._get_program_domain()):
1399 return {'error': _("The program is not available for this order.")}
1400 elif program in self._get_applied_programs():
1401 return {'error': _("This program is already applied to this order."), 'already_applied': True}
1402 elif program.reward_ids:
1403 global_rewards = program.reward_ids.filtered('is_global_discount')
1404 applied_global_reward = self._get_applied_global_discount()
1405 best_global_rewards = max(
1406 global_rewards,
1407 key=lambda reward: self._get_discount_amount(
1408 reward, self._discountable_amount(applied_global_reward)
1409 )
1410 ) if len(global_rewards) > 1 else global_rewards
1411 if (
1412 best_global_rewards
1413 and applied_global_reward
1414 and self._best_global_discount_already_applied(applied_global_reward, best_global_rewards)
1415 ):
1416 return {'error': _(
1417 "This discount (%(discount)s) is not compatible with \"%(other_discount)s\". "
1418 "Please remove it in order to apply this one.",
1419 discount=best_global_rewards.description,
1420 other_discount=applied_global_reward.description
1421 )}
1422 # Check for applicability from the program's triggers/rules.
1423 # This step should also compute the amount of points to give for that program on that order.
1424 status = self._program_check_compute_points(program)[program]
1425 if 'error' in status:
1426 return status
1427 return self.__try_apply_program(program, coupon, status)
1428
1429 def _try_apply_code(self, code):
1430 """
1431 Tries to apply a promotional code to the sales order.
1432 It can be either from a coupon or a program rule.
1433
1434 Returns a dict with the following possible keys:
1435 - 'not_found': Populated with True if the code did not yield any result.
1436 - 'error': Any error message that could occur.
1437 OR The result of `_get_claimable_rewards` with the found or newly created coupon, it will be empty if the coupon was consumed completely.
1438 """
1439 self.ensure_one()
1440
1441 base_domain = self._get_trigger_domain()
1442 domain = Domain.AND([base_domain, [('mode', '=', 'with_code'), ('code', '=', code)]])
1443 rule = self.env['loyalty.rule'].search(domain)
1444 program = rule.program_id
1445 coupon = False
1446 check_date = self._get_confirmed_tx_create_date()
1447
1448 if rule in self.code_enabled_rule_ids:
1449 return {'error': _("This promo code is already applied.")}
1450
1451 # No trigger was found from the code, try to find a coupon
1452 if not program:
1453 coupon = self.env['loyalty.card'].search([('code', '=', code)])
1454 if not coupon or\
1455 not coupon.program_id.active or\
1456 not coupon.program_id.reward_ids or\
1457 not coupon.program_id.filtered_domain(self._get_program_domain()):
1458 return {'error': _("This code is invalid (%s).", code), 'not_found': True}
1459 if coupon.expiration_date and coupon.expiration_date < check_date:
1460 return {'error': _("This coupon is expired.")}
1461 elif coupon.points < min(coupon.program_id.reward_ids.mapped('required_points')):
1462 return {'error': _("This coupon has already been used.")}
1463 program = coupon.program_id
1464
1465 if not program or not program.active:
1466 return {'error': _("This code is invalid (%s).", code), 'not_found': True}
1467 elif program.program_type in ('loyalty', 'ewallet'):
1468 return {'error': _("This program cannot be applied with code.")}
1469
1470 # Lock the loyalty program row to block several processes that try to
1471 # read it at the same time. We also use NOWAIT to make sure we trigger a
1472 # serialization error when the processes don't have the lock and thus,
1473 # trigger a retry of the transaction.
1474 self.env.cr.execute("""
1475 SELECT id FROM loyalty_program WHERE id=%s FOR UPDATE NOWAIT
1476 """, (program.id,))
1477
1478 if (program.limit_usage and program.total_order_count >= program.max_usage):
1479 return {'error': _("This code is expired (%s).", code)}
1480
1481 # Rule will count the next time the points are updated
1482 if rule:
1483 self.code_enabled_rule_ids |= rule
1484 program_is_applied = program in self._get_points_programs()
1485 # Condition that need to apply program (if not applied yet):
1486 # current -> always
1487 # future -> if no coupon
1488 # nominative -> non blocking if card exists with points
1489 if coupon:
1490 self.applied_coupon_ids += coupon
1491 if program_is_applied:
1492 # Update the points for our programs, this will take the new trigger in account
1493 self._update_programs_and_rewards()
1494 elif program.applies_on != 'future' or not coupon:
1495 apply_result = self._try_apply_program(program, coupon)
1496 if 'error' in apply_result and (not program.is_nominative or (program.is_nominative and not coupon)):
1497 if rule:
1498 self.code_enabled_rule_ids -= rule
1499 if coupon and not apply_result.get('already_applied', False):
1500 self.applied_coupon_ids -= coupon
1501 return apply_result
1502 coupon = apply_result.get('coupon', self.env['loyalty.card'])
1503 return self._get_claimable_rewards(forced_coupons=coupon)
1504
1505 def _validate_order(self):
1506 """
1507 Override of sale to create invoice for zero amount order. If the order total is zero and
1508 automatic invoicing is enabled, it creates and posts an invoice.
1509
1510 :return: None
1511 """
1512 super()._validate_order()
1513 if self.amount_total or not self.reward_amount:
1514 return
1515 auto_invoice = self.env['ir.config_parameter'].get_param('sale.automatic_invoice')
1516 if str2bool(auto_invoice):
1517 # create an invoice for order with zero total amount and automatic invoice enabled
1518 self._force_lines_to_invoice_policy_order()
1519 invoice = self._create_invoices(final=True)
1520 invoice.action_post()