Debian Codegraph @

addons/sale_loyalty/tests/test_program_rules.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from datetime import date, timedelta
4
5 from freezegun import freeze_time
6 from pytz import timezone
7
8 from odoo.exceptions import ValidationError
9 from odoo.fields import Command, Datetime
10
11 from odoo.addons.payment.tests.common import PaymentCommon
12 from odoo.addons.sale_loyalty.tests.common import TestSaleCouponCommon
13
14
15 class TestProgramRules(TestSaleCouponCommon, PaymentCommon):
16 # Test all the validity rules to allow a customer to have a reward.
17 # The check based on the products is already done in the basic operations test
18
19 def test_program_rules_minimum_purchased_amount(self):
20 # Test case: Based on the minimum purchased
21
22 self.immediate_promotion_program.rule_ids.write({
23 'product_ids': False,
24 'minimum_amount': 1006,
25 'minimum_amount_tax_mode': 'excl'
26 })
27
28 order = self.empty_order
29 order.write({'order_line': [
30 (0, False, {
31 'product_id': self.product_A.id,
32 'name': '1 Product A',
33 'product_uom_qty': 1.0,
34 }),
35 (0, False, {
36 'product_id': self.product_B.id,
37 'name': '2 Product B',
38 'product_uom_qty': 1.0,
39 })
40 ]})
41 order._update_programs_and_rewards()
42 self._claim_reward(order, self.immediate_promotion_program)
43 self.assertEqual(len(order.order_line.ids), 2, "The promo offer shouldn't have been applied as the purchased amount is not enough")
44
45 order = self.env['sale.order'].create({'partner_id': self.partner.id})
46 order.write({'order_line': [
47 (0, False, {
48 'product_id': self.product_A.id,
49 'name': '10 Product A',
50 'product_uom_qty': 10.0,
51 }),
52 (0, False, {
53 'product_id': self.product_B.id,
54 'name': '2 Product B',
55 'product_uom_qty': 1.0,
56 })
57 ]})
58 order._update_programs_and_rewards()
59 self._claim_reward(order, self.immediate_promotion_program)
60 # 10*100 + 5 = 1005
61 self.assertEqual(len(order.order_line.ids), 2, "The promo offer should not be applied as the purchased amount is not enough")
62
63 self.immediate_promotion_program.rule_ids.minimum_amount = 1005
64 order._update_programs_and_rewards()
65 self._claim_reward(order, self.immediate_promotion_program)
66 self.assertEqual(len(order.order_line.ids), 3, "The promo offer should be applied as the purchased amount is now enough")
67
68 # 10*(100*1.15) + (5*1.15) = 10*115 + 5.75 = 1155.75
69 self.immediate_promotion_program.rule_ids.minimum_amount = 1006
70 self.immediate_promotion_program.rule_ids.minimum_amount_tax_mode = 'incl'
71 order._update_programs_and_rewards()
72 self._claim_reward(order, self.immediate_promotion_program)
73 self.assertEqual(len(order.order_line.ids), 3, "The promo offer should be applied as the initial amount required is now tax included")
74
75 def test_program_rules_min_amount_not_reached_and_specific_product(self):
76 """
77 Test that the discount isn't applied if the min amount isn't reached for the specified
78 product.
79 """
80 self.env['loyalty.program'].search([]).active = False
81 order = self.empty_order
82 program = self.env['loyalty.program'].create({
83 'name': "Discount on Product A",
84 'program_type': 'promotion',
85 'trigger': 'auto',
86 'applies_on': 'current',
87 'rule_ids': [Command.create({
88 'minimum_amount': 110,
89 'minimum_amount_tax_mode': 'excl',
90 'product_ids': [Command.set(self.product_A.ids)],
91 })],
92 'reward_ids': [Command.create({
93 'reward_type': 'discount',
94 'discount': 10,
95 'discount_mode': 'percent',
96 'discount_applicability': 'specific',
97 'discount_product_ids': [Command.set(self.product_A.ids)],
98 })],
99 })
100 self.env['sale.order.line'].create([{
101 'product_id': self.product_A.id,
102 'product_uom_qty': 1.0,
103 'order_id': order.id,
104 }, {
105 'product_id': self.product_B.id,
106 'product_uom_qty': 40.0,
107 'order_id': order.id,
108 }])
109 self.assertEqual(len(order.order_line), 2)
110 self.assertEqual(order.amount_untaxed, 300)
111
112 order._update_programs_and_rewards()
113 self._claim_reward(order, program)
114
115 self.assertEqual(len(order.order_line), 2)
116 self.assertEqual(order.amount_untaxed, 300)
117
118 def test_program_rules_min_amount_reached_and_specific_product(self):
119 """
120 Test that the discount is applied if the min amount is reached for the specified product.
121 """
122 self.env['loyalty.program'].search([]).active = False
123 order = self.empty_order
124 program = self.env['loyalty.program'].create({
125 'name': "Discount on Product A",
126 'program_type': 'promotion',
127 'trigger': 'auto',
128 'applies_on': 'current',
129 'rule_ids': [Command.create({
130 'minimum_amount': 110,
131 'minimum_amount_tax_mode': 'excl',
132 'product_ids': [Command.set(self.product_A.ids)],
133 })],
134 'reward_ids': [Command.create({
135 'reward_type': 'discount',
136 'discount': 10,
137 'discount_mode': 'percent',
138 'discount_applicability': 'specific',
139 'discount_product_ids': [Command.set(self.product_A.ids)],
140 })],
141 })
142 self.env['sale.order.line'].create([{
143 'product_id': self.product_A.id,
144 'product_uom_qty': 2.0,
145 'order_id': order.id,
146 }, {
147 'product_id': self.product_B.id,
148 'product_uom_qty': 20.0,
149 'order_id': order.id,
150 }])
151 self.assertEqual(len(order.order_line), 2)
152 self.assertEqual(order.amount_untaxed, 300)
153
154 order._update_programs_and_rewards()
155 self._claim_reward(order, program)
156
157 self.assertEqual(len(order.order_line), 3)
158 self.assertEqual(order.amount_untaxed, 280)
159
160 def test_program_rules_coupon_qty_and_amount_remove_not_eligible(self):
161 ''' This test will:
162 * Check quantity and amount requirements works as expected (since it's slightly different from a promotion_program)
163 * Ensure that if a reward from a coupon_program was allowed and the conditions are not met anymore,
164 the reward will be removed on recompute.
165 '''
166 self.immediate_promotion_program.active = False # Avoid having this program to add rewards on this test
167 order = self.empty_order
168
169 program = self.env['loyalty.program'].create({
170 'name': 'Get 10% discount if buy at least 4 Product A and $320',
171 'program_type': 'coupons',
172 'applies_on': 'current',
173 'trigger': 'with_code',
174 'rule_ids': [(0, 0, {
175 'product_ids': self.product_A,
176 'minimum_qty': 3,
177 'minimum_amount': 320,
178 })],
179 'reward_ids': [(0, 0, {
180 'reward_type': 'discount',
181 'discount_mode': 'percent',
182 'discount': 10,
183 'discount_applicability': 'order',
184 })],
185 })
186
187 sol1 = self.env['sale.order.line'].create({
188 'product_id': self.product_A.id,
189 'name': 'Product A',
190 'product_uom_qty': 2.0,
191 'order_id': order.id,
192 })
193
194 sol2 = self.env['sale.order.line'].create({
195 'product_id': self.product_B.id,
196 'name': 'Product B',
197 'product_uom_qty': 4.0,
198 'order_id': order.id,
199 })
200
201 # Default value for coupon generate wizard is generate by quantity and generate only one coupon
202 self.env['loyalty.generate.wizard'].with_context(active_id=program.id).create({'coupon_qty': 1, 'points_granted': 1}).generate_coupons()
203 coupon = program.coupon_ids[0]
204
205 # Not enough amount since we only have 220 (100*2 + 5*4)
206 with self.assertRaises(ValidationError):
207 self._apply_promo_code(order, coupon.code)
208
209 sol2.product_uom_qty = 24
210
211 # Not enough qty since we only have 3 Product A (Amount is ok: 100*2 + 5*24 = 320)
212 with self.assertRaises(ValidationError):
213 self._apply_promo_code(order, coupon.code)
214
215 sol1.product_uom_qty = 3
216
217 self._apply_promo_code(order, coupon.code)
218 self._claim_reward(order, program, coupon)
219
220 self.assertEqual(len(order.order_line.ids), 3, "The order should contain the Product A line, the Product B line and the discount line")
221
222 sol1.product_uom_qty = 2
223 order._update_programs_and_rewards()
224
225 self.assertEqual(len(order.order_line.ids), 2, "The discount line should have been removed as we don't meet the program requirements")
226
227 def test_program_rules_promotion_use_best(self):
228 ''' This test verifies that only the best global discount is applied.
229 '''
230 self.immediate_promotion_program.active = False # Avoid having this program to add rewards on this test
231 order = self.empty_order
232
233 p1 = self.env['loyalty.program'].create({
234 'name': 'Get 5% discount if buy at least 2 Product',
235 'trigger': 'auto',
236 'program_type': 'promotion',
237 'applies_on': 'current',
238 'rule_ids': [(0, 0, {
239 'reward_point_mode': 'order',
240 'minimum_qty': 2,
241 })],
242 'reward_ids': [(0, 0, {
243 'reward_type': 'discount',
244 'discount': 5,
245 'discount_mode': 'percent',
246 'discount_applicability': 'order',
247 'required_points': 1,
248 })],
249 })
250 p2 = self.env['loyalty.program'].create({
251 'name': 'Get 10% discount if buy at least 4 Product',
252 'trigger': 'auto',
253 'program_type': 'promotion',
254 'applies_on': 'current',
255 'rule_ids': [(0, 0, {
256 'reward_point_mode': 'order',
257 'minimum_qty': 4,
258 })],
259 'reward_ids': [(0, 0, {
260 'reward_type': 'discount',
261 'discount': 10,
262 'discount_mode': 'percent',
263 'discount_applicability': 'order',
264 'required_points': 1,
265 })],
266 })
267 sol = self.env['sale.order.line'].create({
268 'product_id': self.product_A.id,
269 'name': 'Product A',
270 'product_uom_qty': 1.0,
271 'order_id': order.id,
272 })
273
274 order._update_programs_and_rewards()
275 self._claim_reward(order, p1)
276 self._claim_reward(order, p2)
277 self.assertEqual(len(order.order_line.ids), 1, "The order should only contains the Product A line")
278
279 sol.product_uom_qty = 3
280 order._update_programs_and_rewards()
281 self._claim_reward(order, p1)
282 self._claim_reward(order, p2)
283 discounts = set(order.order_line.mapped('name')) - {'Product A'}
284 self.assertEqual(len(discounts), 1, "The order should contains the Product A line and a discount")
285 # The name of the discount is dynamically changed to smth looking like:
286 # "Discount Get 5% discount if buy at least 2 Product - On product with following tax: Tax 15.00%"
287 self.assertTrue('Discount 5% on your order' in discounts.pop(), "The discount should be a 5% discount")
288
289 sol.product_uom_qty = 5
290 order._update_programs_and_rewards()
291 self._claim_reward(order, p1)
292 self._claim_reward(order, p2)
293 discounts = set(order.order_line.mapped('name')) - {'Product A'}
294 self.assertEqual(len(discounts), 1, "The order should contains the Product A line and a discount")
295 self.assertTrue('Discount 10% on your order' in discounts.pop(), "The discount should be a 10% discount")
296
297 @freeze_time('2011-11-02 09:00:21')
298 def test_program_rules_validity_dates(self):
299 # Test date_to (no date_from)
300 today = date.today()
301 past_day = today - timedelta(days=2)
302 future_day = today + timedelta(days=2)
303 self.immediate_promotion_program.write({'date_to': past_day})
304 order = self.empty_order
305 order.write({'order_line': [
306 Command.create({
307 'product_id': self.product_A.id,
308 'name': '1 Product A',
309 'product_uom_qty': 1.0,
310 }),
311 Command.create({
312 'product_id': self.product_B.id,
313 'name': '2 Product B',
314 'product_uom_qty': 1.0,
315 })
316 ]})
317 self._auto_rewards(order, self.immediate_promotion_program)
318 msg = "The promo shouldn't have been applied as it is expired."
319 self.assertEqual(len(order.order_line.ids), 2, msg)
320
321 self.immediate_promotion_program.write({'date_to': future_day})
322 self._auto_rewards(order, self.immediate_promotion_program)
323 msg = "The promo should have been applied we're between the validity dates."
324 self.assertEqual(len(order.order_line.ids), 3, msg)
325
326 # Test date_from (no date_to)
327 self.immediate_promotion_program.write({
328 'date_from': future_day, 'date_to': False,
329 })
330 self._auto_rewards(order, self.immediate_promotion_program)
331 msg = "The promo shouldn't have been applied as it is not active yet."
332 self.assertEqual(len(order.order_line.ids), 2, msg)
333
334 self.immediate_promotion_program.write({'date_from': past_day})
335 self._auto_rewards(order, self.immediate_promotion_program)
336 msg = "The promo should have been applied we're between the validity dates."
337 self.assertEqual(len(order.order_line.ids), 3, msg)
338
339 # Test date_from and date_to
340 self.immediate_promotion_program.write({'date_from': past_day, 'date_to': future_day})
341 self._auto_rewards(order, self.immediate_promotion_program)
342 msg = "The promo should have been applied as we're between the validity dates"
343 self.assertEqual(len(order.order_line.ids), 3, msg)
344
345 self.immediate_promotion_program.write({
346 'date_from': today + timedelta(days=1),
347 'date_to': future_day,
348 })
349 self._auto_rewards(order, self.immediate_promotion_program)
350 msg = "The promo offer shouldn't have been applied as it is not active yet."
351 self.assertEqual(len(order.order_line.ids), 2, msg)
352
353 self.immediate_promotion_program.write({
354 'date_from': past_day,
355 'date_to': today - timedelta(days=1),
356 })
357 self._auto_rewards(order, self.immediate_promotion_program)
358 msg = "The promo offer shouldn't have been applied as it is expired."
359 self.assertEqual(len(order.order_line.ids), 2, msg)
360
361 self.immediate_promotion_program.write({'date_from': today, 'date_to': today})
362 self._auto_rewards(order, self.immediate_promotion_program)
363 msg = "The promo should have been applied as today is a valid starting and ending date."
364 self.assertEqual(len(order.order_line.ids), 3, msg)
365
366 def test_program_rules_number_of_uses(self):
367 # Test case: Based on the number of allowed uses
368 self.immediate_promotion_program.write({
369 'limit_usage': True,
370 'max_usage': 1,
371 })
372 order = self.empty_order
373 order.write({'order_line': [
374 Command.create({
375 'product_id': self.product_A.id,
376 'name': '1 Product A',
377 'product_uom_qty': 1.0,
378 })
379 ]})
380 self._auto_rewards(order, self.immediate_promotion_program)
381 self.assertEqual(len(order.order_line.ids), 2, "The promo offer should have been applied")
382
383 order = self.env['sale.order'].create({
384 'partner_id': self.env['res.partner'].create({'name': 'My Partner'}).id
385 })
386
387 order.write({'order_line': [
388 Command.create({
389 'product_id': self.product_B.id,
390 'name': '2 Product B',
391 'product_uom_qty': 1.0,
392 })
393 ]})
394 # Invalidate total_order_count
395 self.immediate_promotion_program.invalidate_recordset(['order_count', 'total_order_count'])
396 self._auto_rewards(order, self.immediate_promotion_program)
397 msg = "The promo offer shouldn't have been applied as the number of uses is exceeded"
398 self.assertEqual(len(order.order_line.ids), 1, msg)
399
400 def test_program_rules_validity_date_timezones(self):
401 """Test that the validity dates are checked according to the company's time zone"""
402 self.env.company.partner_id.tz = 'Europe/London'
403 self.partner.tz = 'America/Los_Angeles'
404 midnight = Datetime.today()
405 yesterday = (midnight - timedelta(days=1)).date()
406 self.immediate_promotion_program.update({
407 'date_to': yesterday,
408 'limit_usage': True,
409 'max_usage': 1,
410 })
411 order = self.empty_order.with_context(tz=self.partner.tz)
412 order.order_line = [
413 Command.create({'product_id': self.product_A.id}),
414 Command.create({'product_id': self.product_B.id}),
415 ]
416
417 with freeze_time(midnight):
418 # Try apply reward at UTC midnight with LA time zone in context (expired)
419 self._auto_rewards(order, self.immediate_promotion_program)
420 self.assertFalse(
421 order.order_line.filtered('is_reward_line'),
422 "Promo should not be applied if only valid in the customer's time zone",
423 )
424
425 with freeze_time(timezone(self.env.company.partner_id.tz).localize(midnight)):
426 # Try apply reward at London midnight (expired)
427 self._auto_rewards(order, self.immediate_promotion_program)
428 self.assertFalse(
429 order.order_line.filtered('is_reward_line'),
430 "Promo should not be applied if only valid in the customer's time zone",
431 )
432
433 self.partner.tz = 'Europe/Brussels'
434 with freeze_time(timezone(self.partner.tz).localize(midnight)):
435 # Apply reward at Brussels midnight (still valid in company's time zone)
436 self._auto_rewards(order, self.immediate_promotion_program)
437 self.assertTrue(
438 order.order_line.filtered('is_reward_line'),
439 "Promo should be applied if valid in the company's time zone",
440 )
441
442 def test_program_rules_validity_date_transactions(self):
443 """Test that the validity dates are checked according to the time of transaction."""
444 today = Datetime.today()
445 tomorrow = today + timedelta(days=1)
446 self.immediate_promotion_program.update({
447 'date_to': today,
448 'limit_usage': True,
449 'max_usage': 1,
450 'reward_ids': [Command.set(self.program_gift_card.reward_ids.ids)],
451 })
452 order = self.empty_order
453 order.order_line = [
454 Command.create({'product_id': self.product_A.id}),
455 Command.create({'product_id': self.product_B.id}),
456 ]
457
458 intial_amount = order.amount_total
459 self._auto_rewards(order, self.immediate_promotion_program)
460 self.assertLess(order.amount_total, intial_amount, "A discount should be applied")
461
462 tx = order.transaction_ids = self._create_transaction(
463 flow='redirect',
464 sale_order_ids=[order.id],
465 state='pending',
466 reference=order.name,
467 amount=order.amount_total,
468 )
469 # Our slow provider only gets around to confirming the transaction the next day
470 with freeze_time(tomorrow):
471 tx._set_done()
472 tx._post_process()
473 self.assertAlmostEqual(
474 order.amount_total, tx.amount,
475 msg="Discount should still apply if transaction gets confirmed post-expiration",
476 )