Debian Codegraph @

addons/website_sale_loyalty/tests/test_shop_sale_coupon.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2
3 from datetime import timedelta
4
5 from odoo import fields, http
6 from odoo.exceptions import ValidationError
7 from odoo.fields import Command
8 from odoo.tests import HttpCase, tagged
9
10 from odoo.addons.sale.tests.common import TestSaleCommon
11 from odoo.addons.website_sale.tests.common import MockRequest, WebsiteSaleCommon
12 from odoo.addons.website_sale_loyalty.controllers.cart import Cart
13 from odoo.addons.website_sale_loyalty.controllers.main import WebsiteSale
14
15
16 @tagged('post_install', '-at_install')
17 class WebsiteSaleLoyaltyTestUi(TestSaleCommon, HttpCase):
18
19 @classmethod
20 def setUpClass(cls):
21 super().setUpClass()
22 cls.env.ref('base.user_admin').write({
23 'company_id': cls.env.company.id,
24 'company_ids': [(4, cls.env.company.id)],
25 'name': 'Mitchell Admin',
26 'email': '[email protected]',
27 'street': '215 Vine St',
28 'phone': '+1 555-555-5555',
29 'city': 'Scranton',
30 'zip': '18503',
31 'country_id': cls.env.ref('base.us').id,
32 'state_id': cls.env.ref('base.state_us_39').id,
33 })
34 cls.env.ref('base.user_admin').sudo().partner_id.company_id = cls.env.company
35 cls.env.ref('website.default_website').company_id = cls.env.company
36 cls.public_category = cls.env['product.public.category'].create({'name': 'Public Category'})
37
38 def test_01_admin_shop_sale_loyalty_tour(self):
39 if self.env['ir.module.module']._get('payment_custom').state != 'installed':
40 self.skipTest("Transfer provider is not installed")
41
42 transfer_provider = self.env.ref('payment.payment_provider_transfer')
43 transfer_provider.sudo().write({
44 'state': 'enabled',
45 'is_published': True,
46 'company_id': self.env.company.id,
47 })
48 transfer_provider._transfer_ensure_pending_msg_is_set()
49
50 large_cabinet = self.env['product.product'].create({
51 'name': 'Small Cabinet',
52 'list_price': 320.0,
53 'type': 'consu',
54 'is_published': True,
55 'sale_ok': True,
56 'public_categ_ids': [(4, self.public_category.id)],
57 'taxes_id': False,
58 })
59
60 free_large_cabinet = self.env['product.product'].create({
61 'name': 'Free Product - Small Cabinet',
62 'type': 'service',
63 'supplier_taxes_id': False,
64 'sale_ok': False,
65 'purchase_ok': False,
66 'invoice_policy': 'order',
67 'default_code': 'FREELARGECABINET',
68 'taxes_id': False,
69 })
70
71 ten_percent = self.env['product.product'].create({
72 'name': '10.0% discount on total amount',
73 'type': 'service',
74 'supplier_taxes_id': False,
75 'sale_ok': False,
76 'purchase_ok': False,
77 'invoice_policy': 'order',
78 'default_code': '10PERCENTDISC',
79 'taxes_id': False,
80 })
81
82 self.env['loyalty.program'].search([]).write({'active': False})
83
84 self.env['loyalty.program'].create({
85 'name': 'Buy 4 Small Cabinets, get one for free',
86 'trigger': 'auto',
87 'rule_ids': [(0, 0, {
88 'minimum_qty': 4,
89 'product_ids': large_cabinet,
90 })],
91 'reward_ids': [(0, 0, {
92 'reward_type': 'product',
93 'reward_product_id': large_cabinet.id,
94 'discount_line_product_id': free_large_cabinet.id,
95 })]
96 })
97
98 self.env['loyalty.program'].create({
99 'name': 'Code for 10% on orders',
100 'trigger': 'with_code',
101 'rule_ids': [(0, 0, {
102 'mode': 'with_code',
103 'code': 'testcode',
104 })],
105 'reward_ids': [(0, 0, {
106 'reward_type': 'discount',
107 'discount': 10,
108 'discount_mode': 'percent',
109 'discount_applicability': 'order',
110 'discount_line_product_id': ten_percent.id,
111 })],
112 })
113
114 vip_program = self.env['loyalty.program'].create({
115 'name': 'VIP',
116 'trigger': 'auto',
117 'program_type': 'loyalty',
118 'portal_visible': True,
119 'applies_on': 'both',
120 'rule_ids': [(0, 0, {
121 'mode': 'auto',
122 })],
123 'reward_ids': [(0, 0, {
124 'reward_type': 'discount',
125 'discount': 21,
126 'discount_mode': 'percent',
127 'discount_applicability': 'order',
128 'required_points': 50,
129 })],
130 })
131
132 self.env['loyalty.card'].create({
133 'partner_id': self.env.ref('base.partner_admin').id,
134 'program_id': vip_program.id,
135 'point_name': "Points",
136 'points': 371.03,
137 })
138
139 self.env.ref("website_sale.reduction_code").write({"active": True})
140 self.start_tour("/", 'shop_sale_loyalty', login="admin")
141
142 def test_02_admin_shop_gift_card_tour(self):
143 gift_card = self.env['product.product'].create({
144 'name': 'TEST - Gift Card',
145 'list_price': 50,
146 'type': 'service',
147 'is_published': True,
148 'sale_ok': True,
149 'public_categ_ids': [(4, self.public_category.id)],
150 'taxes_id': False,
151 })
152 self.env['product.product'].create({
153 'name': 'TEST - Small Drawer',
154 'list_price': 50,
155 'type': 'consu',
156 'is_published': True,
157 'sale_ok': True,
158 'public_categ_ids': [(4, self.public_category.id)],
159 'taxes_id': False,
160 })
161 # Disable any other program
162 self.env['loyalty.program'].search([]).write({'active': False})
163
164 gift_card_program = self.env['loyalty.program'].create({
165 'name': 'Gift Cards',
166 'program_type': 'gift_card',
167 'applies_on': 'future',
168 'trigger': 'auto',
169 'rule_ids': [(0, 0, {
170 'reward_point_amount': 1,
171 'reward_point_mode': 'money',
172 'reward_point_split': True,
173 'product_ids': gift_card,
174 })],
175 'reward_ids': [(0, 0, {
176 'reward_type': 'discount',
177 'discount_mode': 'per_point',
178 'discount': 1,
179 'discount_applicability': 'order',
180 'required_points': 1,
181 'description': 'PAY WITH GIFT CARD',
182 })],
183 })
184 # Another program for good measure
185 self.env['loyalty.program'].create({
186 'name': '10% Discount',
187 'applies_on': 'current',
188 'trigger': 'with_code',
189 'program_type': 'promotion',
190 'rule_ids': [(0, 0, {
191 'mode': 'with_code',
192 'code': '10PERCENT',
193 })],
194 'reward_ids': [(0, 0, {
195 'reward_type': 'discount',
196 'discount': 10,
197 'discount_mode': 'percent',
198 'discount_applicability': 'order',
199 })],
200 })
201 # Create a gift card to be used
202 self.env['loyalty.card'].create({
203 'program_id': gift_card_program.id,
204 'points': 50,
205 'code': 'GIFT_CARD',
206 })
207
208 self.env.ref("website_sale.reduction_code").write({"active": True})
209 self.start_tour('/', 'shop_sale_gift_card', login='admin')
210
211 self.assertEqual(len(gift_card_program.coupon_ids), 2, 'There should be two coupons, one with points, one without')
212 self.assertEqual(len(gift_card_program.coupon_ids.filtered('points')), 1, 'There should be two coupons, one with points, one without')
213
214 def test_03_admin_shop_ewallet_tour(self):
215 self.env['product.product'].create({
216 'name': "TEST - Gift Card",
217 'list_price': 50,
218 'type': 'service',
219 'is_published': True,
220 'sale_ok': True,
221 'public_categ_ids': [(4, self.public_category.id)],
222 'taxes_id': False,
223 })
224 # Disable any other program
225 self.env['loyalty.program'].search([]).write({'active': False})
226 ewallet_programs = self.env['loyalty.program'].create([{
227 'name': f"ewallet - test - {ecommerce_ok=}",
228 'applies_on': 'future',
229 'trigger': 'auto',
230 'program_type': 'ewallet',
231 'ecommerce_ok': ecommerce_ok,
232 'reward_ids': [Command.create({
233 'reward_type': 'discount',
234 'discount_mode': 'per_point',
235 'discount': 1,
236 })],
237 } for ecommerce_ok in (True, False)])
238 self.env['loyalty.card'].create([{
239 'partner_id': self.env.ref('base.partner_admin').id,
240 'program_id': program_id,
241 'points': 1000,
242 } for program_id in ewallet_programs.ids])
243 self.start_tour('/', 'shop_sale_ewallet', login='admin')
244
245
246 @tagged('post_install', '-at_install')
247 class TestWebsiteSaleCoupon(HttpCase, WebsiteSaleCommon):
248
249 @classmethod
250 def setUpClass(cls):
251 super().setUpClass()
252 program = cls.env['loyalty.program'].create({
253 'name': '10% TEST Discount',
254 'trigger': 'with_code',
255 'applies_on': 'current',
256 'rule_ids': [(0, 0, {})],
257 'reward_ids': [(0, 0, {
258 'reward_type': 'discount',
259 'discount': 10,
260 'discount_mode': 'percent',
261 })],
262 })
263
264 cls.env['loyalty.generate.wizard'].with_context(active_id=program.id).create({
265 'coupon_qty': 1,
266 'points_granted': 1
267 }).generate_coupons()
268 cls.coupon = program.coupon_ids[0]
269
270 def _apply_promo_code(self, order, code, no_reward_fail=True):
271 status = order._try_apply_code(code)
272 if 'error' in status:
273 raise ValidationError(status['error'])
274 if not status and no_reward_fail:
275 # Can happen if global discount got filtered out in `_get_claimable_rewards`
276 raise ValidationError('No reward to claim with this coupon')
277 coupons = self.env['loyalty.card']
278 rewards = self.env['loyalty.reward']
279 for coupon, coupon_rewards in status.items():
280 coupons |= coupon
281 rewards |= coupon_rewards
282 if len(coupons) == 1 and len(rewards) == 1:
283 status = order._apply_program_reward(rewards, coupons)
284 if 'error' in status:
285 raise ValidationError(status['error'])
286
287 def test_01_gc_coupon(self):
288 # 1. Simulate a frontend order (website, product)
289 order = self.empty_cart
290 order.order_line = [
291 Command.create({
292 'product_id': self.env['product.product'].create({
293 'name': 'Product A',
294 'list_price': 100,
295 'sale_ok': True,
296 }).id,
297 'product_uom_qty': 2.0,
298 })
299 ]
300
301 # 2. Apply the coupon
302 self._apply_promo_code(order, self.coupon.code)
303
304 self.assertEqual(len(order.applied_coupon_ids), 1, "The coupon should've been applied on the order")
305 self.assertEqual(self.coupon, order.applied_coupon_ids)
306
307 # 3. Test recent order -> Should not be removed
308 order._gc_abandoned_coupons()
309
310 self.assertEqual(len(order.applied_coupon_ids), 1, "The coupon shouldn't have been removed from the order no more than 4 days")
311
312 # 4. Test order not older than ICP validity -> Should not be removed
313 ICP = self.env['ir.config_parameter']
314 icp_validity = ICP.create({'key': 'website_sale_coupon.abandonned_coupon_validity', 'value': 5})
315 self.env.flush_all()
316 query = """UPDATE %s SET write_date = %%s WHERE id = %%s""" % (order._table,)
317 self.env.cr.execute(query, (fields.Datetime.to_string(fields.Datetime.now() - timedelta(days=4, hours=2)), order.id))
318 order._gc_abandoned_coupons()
319
320 self.assertEqual(len(order.applied_coupon_ids), 1, "The coupon shouldn't have been removed from the order the order is 4 days old but icp validity is 5 days")
321
322 # 5. Test order with no ICP and older then 4 default days -> Should be removed
323 icp_validity.unlink()
324 order._gc_abandoned_coupons()
325
326 self.assertEqual(len(order.applied_coupon_ids), 0, "The coupon should've been removed from the order as more than 4 days")
327
328 def test_02_apply_discount_code_program_multi_rewards(self):
329 """
330 Check the triggering of a promotion program based on a promo code with multiple rewards
331 """
332 self.env['loyalty.program'].search([]).write({'active': False})
333 chair = self.env['product.product'].create({
334 'name': 'Super Chair', 'list_price': 1000, 'website_published': True
335 })
336 self.discount_code_program_multi_rewards = self.env['loyalty.program'].create({
337 'name': 'Discount code program',
338 'program_type': 'promo_code',
339 'applies_on': 'current',
340 'trigger': 'with_code',
341 'rule_ids': [(0, 0, {
342 'code': '12345',
343 'reward_point_amount': 1,
344 'reward_point_mode': 'order',
345 })],
346 'reward_ids': [
347 (0, 0, {
348 'reward_type': 'discount',
349 'discount': 10,
350 'discount_applicability': 'specific',
351 'required_points': 1,
352 'discount_product_ids': chair,
353 }),
354 (0, 0, {
355 'reward_type': 'discount',
356 'discount': 50,
357 'discount_applicability': 'order',
358 'required_points': 1,
359 }),
360 ],
361 })
362 self.start_tour('/', 'apply_discount_code_program_multi_rewards', login='admin')
363
364 def test_03_remove_coupon(self):
365 # 1. Simulate a frontend order (website, product)
366 order = self.empty_cart
367 order.order_line = [
368 Command.create({
369 'product_id': self.env['product.product'].create({
370 'name': 'Product A', 'list_price': 100, 'sale_ok': True
371 }).id,
372 })
373 ]
374
375 # 2. Apply the coupon
376 self._apply_promo_code(order, self.coupon.code)
377
378 # 3. Remove the coupon
379 coupon_line = order.website_order_line.filtered(
380 lambda l: l.coupon_id and l.coupon_id.id == self.coupon.id
381 )
382
383 website = self.website
384 with MockRequest(website.env, website=self.website, sale_order_id=order.id):
385 Cart().update_cart(
386 line_id=None, quantity=0.0, product_id=coupon_line.product_id.id,
387 )
388
389 msg = "The coupon should've been removed from the order"
390 self.assertEqual(len(order.applied_coupon_ids), 0, msg=msg)
391
392 def test_04_apply_coupon_code_twice(self):
393 """This test ensures that applying a coupon with code twice will:
394 1. Raise an error
395 2. Not delete the coupon
396 """
397 # Create product
398 product = self.env['product.product'].create({
399 'name': 'Product',
400 'list_price': 100,
401 'sale_ok': True,
402 'taxes_id': [],
403 })
404
405 order = self.empty_cart
406 order.order_line = [Command.create({'product_id': product.id})]
407
408 WebsiteSaleController = WebsiteSale()
409
410 installed_modules = set(self.env['ir.module.module'].search([
411 ('state', '=', 'installed'),
412 ]).mapped('name'))
413 for _ in http._generate_routing_rules(installed_modules, nodb_only=False):
414 pass
415
416 with MockRequest(self.env, website=self.website, sale_order_id=order.id) as request:
417 # Check the base cart value
418 self.assertEqual(order.amount_total, 100.0, "The base cart value is incorrect.")
419
420 # Apply coupon for the first time
421 WebsiteSaleController.pricelist(promo=self.coupon.code)
422
423 # Check that the coupon has been applied
424 self.assertEqual(order.amount_total, 90.0, "The coupon is not applied.")
425
426 # Apply the coupon again
427 WebsiteSaleController.pricelist(promo=self.coupon.code)
428 Cart().cart()
429 error_msg = request.session.get('error_promo_code')
430
431 # Check that the coupon stay applied
432 self.assertEqual(bool(error_msg), True, "Apply a coupon twice should display an error message")
433 self.assertEqual(order.amount_total, 90.0, "Apply a coupon twice shouldn't delete it")
434
435 def test_03_remove_coupon_with_different_taxes_on_products(self):
436 """
437 Tests the removal of a coupon from an order containing products with various tax rates,
438 ensuring that the system correctly handles multiple coupon lines created
439 for each unique tax scenario.
440
441 Background:
442 An order may include products with different tax implications,
443 such as non-taxed products, products with a single tax rate,
444 and products with multiple tax rates. When a coupon is applied,
445 it creates separate coupon lines for each distinct tax situation
446 (non-taxed, individual taxes, and combinations of taxes).
447 This test verifies that the coupon deletion process accurately removes
448 all associated coupon lines, maintaining the financial accuracy of the order.
449
450 Steps:
451 1. Create an order with products subject to different tax scenarios:
452 - Non-taxed product 'Product A'
453 - Product 'Product B' with Tax A
454 - Product 'Product C' with Tax B
455 - Product 'Product D' subject to both Tax A and Tax B
456 2. Apply a coupon, which generates four distinct coupon lines
457 to reflect each tax scenario.
458 3. Remove the coupon and verify that all coupon lines are removed and
459 that no coupons remain applied.
460 """
461 # Create 2 Taxes
462 tax_a = self.env['account.tax'].create({
463 'name': 'Tax A',
464 'type_tax_use': 'sale',
465 'amount_type': 'percent',
466 'amount': 15,
467 })
468 tax_b = tax_a.copy({'name': 'Tax B'})
469
470 # Create 4 products subject to different tax
471 products_data = [
472 ('Product A', []),
473 ('Product B', [tax_a.id]),
474 ('Product C', [tax_b.id]),
475 ('Product D', [tax_a.id, tax_b.id]),
476 ]
477
478 products = self.env['product.product'].create(
479 [{
480 'name': name,
481 'list_price': 100,
482 'sale_ok': True,
483 'taxes_id': [Command.set(taxes_id)],
484 } for name, taxes_id in products_data]
485 )
486
487 order = self.empty_cart
488 order.order_line = [Command.create({'product_id': product.id}) for product in products]
489
490 msg = "There should only be 4 lines for the 4 products."
491 self.assertEqual(len(order.order_line), 4, msg=msg)
492
493 # 2. Apply the coupon
494 self._apply_promo_code(order, self.coupon.code)
495
496 msg = (
497 "4 additional lines should have been added to the sale orders"
498 "after application of the coupon for each separate tax situation."
499 )
500 self.assertEqual(len(order.order_line), 8, msg=msg)
501
502 # 3. Remove the coupon
503 coupon_line = order.website_order_line.filtered(
504 lambda line: line.coupon_id and line.coupon_id.id == self.coupon.id
505 )
506 website = self.website
507 with MockRequest(website.env, website=self.website, sale_order_id=order.id):
508 Cart().update_cart(
509 line_id=None, quantity=0.0, product_id=coupon_line.product_id.id,
510 )
511
512 msg = "All coupon lines should have been removed from the order."
513 self.assertEqual(len(order.applied_coupon_ids), 0, msg=msg)
514 self.assertEqual(len(order.order_line), 4, msg=msg)
515
516 def test_confirm_points_as_public_user(self):
517 test_product = self.env['product.product'].create({
518 'name': "Test Product",
519 'list_price': 100,
520 'sale_ok': True,
521 })
522 test_partner = self.env['res.partner'].create({
523 'name': 'Test Partner'
524 })
525
526 loyalty_program = self.env['loyalty.program'].create({
527 'name': "Loyalty Program",
528 'program_type': 'loyalty',
529 'trigger': 'auto',
530 'applies_on': 'both',
531 'rule_ids': [Command.create({
532 'reward_point_mode': 'unit',
533 'reward_point_amount': 1,
534 'product_ids': [test_product.id],
535 })],
536 'reward_ids': [Command.create({
537 'reward_type': 'discount',
538 'discount': 1.5,
539 'discount_mode': 'per_point',
540 'discount_applicability': 'order',
541 'required_points': 3,
542 })],
543 })
544
545 order = self.env['sale.order'].create({
546 'partner_id': test_partner.id,
547 'order_line': [Command.create({
548 'product_id': test_product.id,
549 'product_uom_qty': 1,
550 })]
551 })
552
553 loyalty_card = self.env['loyalty.card'].create({
554 'program_id': loyalty_program.id,
555 'partner_id': test_partner.id,
556 'points': 0,
557 })
558 public_user = self.env.ref('base.public_user')
559 order.action_quotation_send()
560 order.with_context(access_token=order.access_token, user=public_user).action_confirm()
561 self.assertEqual(loyalty_card.points, 1)