Debian Codegraph @

addons/website_sale_loyalty/models/sale_order.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from collections import defaultdict
4 from datetime import timedelta
5
6 from odoo import api, fields, models
7 from odoo.exceptions import UserError
8 from odoo.fields import Domain
9 from odoo.http import request
10
11
12 class SaleOrder(models.Model):
13 _inherit = 'sale.order'
14
15 # List of disabled rewards for automatic claim
16 disabled_auto_rewards = fields.Many2many("loyalty.reward", relation="sale_order_disabled_auto_rewards_rel")
17
18 def _get_program_domain(self):
19 res = super()._get_program_domain()
20 # Replace `sale_ok` leaf with `ecommerce_ok` if order is linked to a website
21 if self.website_id:
22 for idx, leaf in enumerate(res):
23 if leaf[0] != 'sale_ok':
24 continue
25 res[idx] = ('ecommerce_ok', '=', True)
26 return Domain.AND([res, [('website_id', 'in', (self.website_id.id, False))]])
27 return res
28
29 def _get_trigger_domain(self):
30 res = super()._get_trigger_domain()
31 # Replace `sale_ok` leaf with `ecommerce_ok` if order is linked to a website
32 if self.website_id:
33 for idx, leaf in enumerate(res):
34 if leaf[0] != 'program_id.sale_ok':
35 continue
36 res[idx] = ('program_id.ecommerce_ok', '=', True)
37 return Domain.AND([res, [('program_id.website_id', 'in', (self.website_id.id, False))]])
38 return res
39
40 def _get_program_timezone(self):
41 return self.website_id.salesperson_id.tz or super()._get_program_timezone()
42
43 def _try_pending_coupon(self):
44 if not request:
45 return False
46
47 pending_coupon_code = request.session.get('pending_coupon_code')
48 if pending_coupon_code:
49 status = self._try_apply_code(pending_coupon_code)
50 if 'error' not in status: # Returns an array if everything went right
51 request.session.pop('pending_coupon_code')
52 if len(status) == 1:
53 coupon, rewards = next(iter(status.items()))
54 if len(rewards) == 1 and not rewards.multi_product:
55 self._apply_program_reward(rewards, coupon)
56 return status
57 return True
58
59 def _update_programs_and_rewards(self):
60 for order in self:
61 order._try_pending_coupon()
62 return super()._update_programs_and_rewards()
63
64 def _auto_apply_rewards(self):
65 """
66 Tries to auto apply claimable rewards.
67
68 It must answer to the following rules:
69 - Must not be from a nominative program
70 - The reward must be the only reward of the program
71 - The reward may not be a multi product reward
72
73 Returns True if any reward was claimed else False
74 """
75 self.ensure_one()
76
77 claimed_reward_count = 0
78 claimable_rewards = self._get_claimable_rewards()
79 for coupon, rewards in claimable_rewards.items():
80 if (
81 len(coupon.program_id.reward_ids) != 1
82 or coupon.program_id.is_nominative
83 or (rewards.reward_type == 'product' and rewards.multi_product)
84 or rewards in self.disabled_auto_rewards
85 or rewards in self.order_line.reward_id
86 ):
87 continue
88
89 try:
90 res = self._apply_program_reward(rewards, coupon)
91 if 'error' not in res:
92 claimed_reward_count += 1
93 except UserError:
94 pass
95
96 return bool(claimed_reward_count)
97
98 def _compute_website_order_line(self):
99 """ This method will merge multiple discount lines generated by a same program
100 into a single one (temporary line with `new()`).
101 This case will only occur when the program is a discount applied on multiple
102 products with different taxes.
103 In this case, each taxes will have their own discount line. This is required
104 to have correct amount of taxes according to the discount.
105 But we want these lines to be `visually` merged into a single one in the
106 e-commerce since the end user should only see one discount line.
107 This is only possible since we don't show taxes in cart.
108 eg:
109 line 1: 10% discount on product with tax `A` - $15
110 line 2: 10% discount on product with tax `B` - $11.5
111 line 3: 10% discount on product with tax `C` - $10
112 would be `hidden` and `replaced` by
113 line 1: 10% discount - $36.5
114
115 Note: The line will be created without tax(es) and the amount will be computed
116 depending if B2B or B2C is enabled.
117 """
118 super()._compute_website_order_line()
119 for order in self:
120 grouped_order_lines = defaultdict(lambda: self.env['sale.order.line'])
121 for line in order.order_line:
122 if line.reward_id and line.coupon_id:
123 grouped_order_lines[(line.reward_id, line.coupon_id, line.reward_identifier_code)] |= line
124 new_lines = self.env['sale.order.line']
125 for lines in grouped_order_lines.values():
126 if lines.reward_id.reward_type != 'discount':
127 continue
128 new_lines += self.env['sale.order.line'].new({
129 'product_id': lines[0].product_id.id,
130 'tax_ids': False,
131 'price_unit': sum(lines.mapped('price_unit')),
132 'price_subtotal': sum(lines.mapped('price_subtotal')),
133 'price_total': sum(lines.mapped('price_total')),
134 'discount': 0.0,
135 'name': lines[0].name_short if lines.reward_id.reward_type != 'product' else lines[0].name,
136 'product_uom_qty': 1,
137 'product_uom_id': lines[0].product_uom_id.id,
138 'order_id': order.id,
139 'is_reward_line': True,
140 'coupon_id': lines.coupon_id,
141 'reward_id': lines.reward_id,
142 })
143 if new_lines:
144 order.website_order_line += new_lines
145
146 def _compute_cart_info(self):
147 super(SaleOrder, self)._compute_cart_info()
148 for order in self:
149 reward_lines = order.website_order_line.filtered(lambda line: line.is_reward_line)
150 order.cart_quantity -= int(sum(reward_lines.mapped('product_uom_qty')))
151
152 def get_promo_code_error(self, delete=True):
153 error = request.session.get('error_promo_code')
154 if error and delete:
155 request.session.pop('error_promo_code')
156 return error
157
158 def get_promo_code_success_message(self, delete=True):
159 if not request.session.get('successful_code'):
160 return False
161 code = request.session.get('successful_code')
162 if delete:
163 request.session.pop('successful_code')
164 return code
165
166 def _set_delivery_method(self, *args, **kwargs):
167 super()._set_delivery_method(*args, **kwargs)
168 self._update_programs_and_rewards()
169
170 def _remove_delivery_line(self):
171 super()._remove_delivery_line()
172 self._update_programs_and_rewards()
173
174 def _cart_update_order_line(self, order_line, quantity, **kwargs):
175 if (
176 quantity <= 0
177 and order_line.coupon_id
178 and order_line.reward_id
179 and order_line.reward_id.reward_type == 'discount'
180 ):
181 # When a reward line is deleted we remove it from the auto claimable rewards
182 order_line = order_line.with_context(website_sale_loyalty_delete=True)
183
184 return super()._cart_update_order_line(order_line, quantity, **kwargs)
185
186 def _verify_cart_after_update(self):
187 super()._verify_cart_after_update()
188 self._update_programs_and_rewards()
189 self._auto_apply_rewards()
190 if request: # In case the rewards application modifies the cart quantity
191 request.session['website_sale_cart_quantity'] = self.cart_quantity
192
193 def _get_non_delivery_lines(self):
194 """Override of `website_sale` to exclude delivery reward lines."""
195 return super()._get_non_delivery_lines() - self._get_free_shipping_lines()
196
197 def _get_free_shipping_lines(self):
198 self.ensure_one()
199 return self.order_line.filtered(lambda l: l.reward_id.reward_type == 'shipping')
200
201 def _allow_nominative_programs(self):
202 if not request or not hasattr(request, 'website'):
203 return super()._allow_nominative_programs()
204 return not request.website.is_public_user() and super()._allow_nominative_programs()
205
206 @api.autovacuum
207 def _gc_abandoned_coupons(self, *args, **kwargs):
208 """Remove coupons from abandonned ecommerce order."""
209 ICP = self.env['ir.config_parameter']
210 validity = ICP.get_param('website_sale_coupon.abandonned_coupon_validity', 4)
211 validity = fields.Datetime.to_string(fields.Datetime.now() - timedelta(days=int(validity)))
212 so_to_reset = self.env['sale.order'].search([
213 ('state', '=', 'draft'),
214 ('write_date', '<', validity),
215 ('website_id', '!=', False),
216 ('applied_coupon_ids', '!=', False),
217 ])
218 so_to_reset.applied_coupon_ids = False
219 for so in so_to_reset:
220 so._update_programs_and_rewards()
221
222 def _get_claimable_and_showable_rewards(self):
223 self.ensure_one()
224 res = self._get_claimable_rewards()
225 loyality_cards = self.env['loyalty.card'].search([
226 ('partner_id', '=', self.partner_id.id),
227 ('program_id', 'any', self._get_program_domain()),
228 '|',
229 ('program_id.trigger', '=', 'with_code'),
230 '&', ('program_id.trigger', '=', 'auto'), ('program_id.applies_on', '=', 'future'),
231 ])
232 total_is_zero = self.currency_id.is_zero(self.amount_total)
233 global_discount_reward = self._get_applied_global_discount()
234 for coupon in loyality_cards:
235 points = self._get_real_points_for_coupon(coupon)
236 for reward in coupon.program_id.reward_ids - self.order_line.reward_id:
237 if (
238 reward.is_global_discount
239 and global_discount_reward
240 and self._best_global_discount_already_applied(global_discount_reward, reward)
241 ):
242 continue
243 if reward.reward_type == 'discount' and total_is_zero:
244 continue
245 if coupon.expiration_date and coupon.expiration_date < fields.Date.today():
246 continue
247 if points >= reward.required_points:
248 if coupon in res:
249 res[coupon] |= reward
250 else:
251 res[coupon] = reward
252 return res
253
254 def _cart_find_product_line(self, *args, **kwargs):
255 # Filter out reward lines, they shouldn't be modified by standard _cart_add logic.
256 # This kind of lines is handled by _update_programs_and_rewards and _auto_apply_rewards.
257 return super()._cart_find_product_line(*args, **kwargs).filtered(
258 lambda sol: not sol.is_reward_line
259 )
260
261 def _recompute_cart(self):
262 """Recompute cart with loyalty programs and rewards applied."""
263 self._update_programs_and_rewards()
264 self._auto_apply_rewards()
265 super()._recompute_cart()