Debian Codegraph @

addons/point_of_sale/tests/test_point_of_sale_flow.py

raw symbols SCIP
1 import odoo
2
3 from freezegun import freeze_time
4 from unittest.mock import patch
5 from odoo import fields
6 from odoo.fields import Command
7 from odoo.tests import Form
8 from datetime import datetime, timedelta
9 from odoo.addons.point_of_sale.tests.common import CommonPosTest
10 from odoo.exceptions import ValidationError, UserError
11
12
13 @odoo.tests.tagged('post_install', '-at_install')
14 class TestPointOfSaleFlow(CommonPosTest):
15
16 def setup_tags(self):
17 tags = self.env['account.account.tag'].create([
18 {
19 'name': f"tag{i}",
20 'applicability': 'taxes',
21 'country_id': self.company_data['company'].country_id.id,
22 }
23 for i in range(1, 5)
24 ])
25 self.twenty_dollars_with_15_excl.taxes_id = [Command.set(self.tax_sale_a.ids)]
26 self.tax_sale_a.invoice_repartition_line_ids.filtered(
27 lambda l: l.repartition_type == 'base').write({'tag_ids': tags[0].ids})
28 self.tax_sale_a.invoice_repartition_line_ids.filtered(
29 lambda l: l.repartition_type == 'tax').write({'tag_ids': tags[1].ids})
30 self.tax_sale_a.refund_repartition_line_ids.filtered(
31 lambda l: l.repartition_type == 'base').write({'tag_ids': tags[2].ids})
32 self.tax_sale_a.refund_repartition_line_ids.filtered(
33 lambda l: l.repartition_type == 'tax').write({'tag_ids': tags[3].ids})
34
35 return tags
36
37 def test_order_refund(self):
38 self.pos_config_usd.open_ui()
39
40 # The amount_total will be 30 with 3.52 taxes included
41 order, refund = self.create_backend_pos_order({
42 'line_data': [
43 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
44 {'product_id': self.twenty_dollars_with_10_incl.product_variant_id.id},
45 ],
46 'payment_data': [
47 {'payment_method_id': self.cash_payment_method.id, 'amount': 10},
48 {'payment_method_id': self.bank_payment_method.id, 'amount': 20},
49 ],
50 'refund_data': [
51 {'payment_method_id': self.cash_payment_method.id, 'amount': -30},
52 ]
53 })
54
55 self.assertAlmostEqual(order.amount_total, order.amount_paid)
56 self.assertEqual(refund.state, 'paid', "The refund is not marked as paid")
57 self.assertTrue(refund.payment_ids.payment_method_id.is_cash_count)
58
59 current_session = self.pos_config_usd.current_session_id
60 total_cash_payment = sum(current_session.mapped('order_ids.payment_ids').filtered(
61 lambda payment: payment.payment_method_id.type == 'cash').mapped('amount')
62 )
63 current_session.post_closing_cash_details(total_cash_payment)
64 current_session.close_session_from_ui()
65 self.assertEqual(current_session.state, 'closed')
66
67 def test_refund_multiple_payment_rounding(self):
68 """
69 This test makes sure that the refund amount always correspond to what
70 has been paid in the original order. In this example we have a
71 rounding, so we pay 5 in bank that is not rounded, then we pay the
72 rest in cash that is rounded. This sum up to 10 paid, so the refund
73 should be 10.
74 """
75 self.account_cash_rounding_down.rounding = 5.0
76 self.pos_config_usd.write({
77 'rounding_method': self.account_cash_rounding_down.id,
78 'cash_rounding': True,
79 })
80
81 self.pos_config_usd.open_ui()
82 # order total will be 11.5 with 1.5 taxes excluded, with rounding 10 should be paid
83 order, refund = self.create_backend_pos_order({
84 'line_data': [
85 {'product_id': self.ten_dollars_with_15_excl.product_variant_id.id},
86 ],
87 'payment_data': [
88 {'payment_method_id': self.bank_payment_method.id, 'amount': 5},
89 {'payment_method_id': self.cash_payment_method.id},
90 ],
91 'refund_data': [
92 {'payment_method_id': self.cash_payment_method.id, 'amount': -10},
93 ]
94 })
95
96 self.assertEqual(order.amount_paid, 10.0)
97 self.assertEqual(order.state, 'paid')
98 self.assertEqual(refund.amount_paid, -10.0)
99 self.assertEqual(refund.state, 'paid')
100
101 def test_order_partial_refund_rounding(self):
102 """ This test ensures that the refund amound of a partial order corresponds to
103 the price of the item, without rounding. """
104 self.account_cash_rounding_down.rounding = 5.0
105 self.pos_config_usd.write({
106 'rounding_method': self.account_cash_rounding_down.id,
107 'cash_rounding': True,
108 })
109
110 self.pos_config_usd.open_ui()
111 current_session = self.pos_config_usd.current_session_id
112
113 # order total will be 34.5 with 4.5 taxes excluded, with rounding 10 should be paid
114 order, _ = self.create_backend_pos_order({
115 'line_data': [
116 {'product_id': self.ten_dollars_with_15_excl.product_variant_id.id, 'qty': 3},
117 ],
118 'payment_data': [
119 {'payment_method_id': self.bank_payment_method.id, 'amount': 34.5},
120 ],
121 })
122
123 self.assertEqual(order._get_rounded_amount(order.amount_total), order.amount_paid)
124 refund_action = order.refund()
125 refund = self.env['pos.order'].browse(refund_action['res_id'])
126
127 with Form(refund) as refund_form:
128 with refund_form.lines.edit(0) as line:
129 line.qty = 1
130 refund = refund_form.save()
131
132 self.assertEqual(refund.amount_total, 10.0)
133 payment_context = {"active_ids": refund.ids, "active_id": refund.id}
134 refund_payment = self.env['pos.make.payment'].with_context(**payment_context).create({
135 'amount': refund.amount_total,
136 'payment_method_id': self.cash_payment_method.id,
137 })
138 refund_payment.with_context(**payment_context).check()
139 self.assertEqual(refund.state, 'paid')
140 current_session.action_pos_session_closing_control()
141 self.assertEqual(current_session.state, 'closed')
142
143 def test_order_partial_refund(self):
144 """ The purpose of this test is to make a partial refund of a pos order.
145 The amount to refund should depend on the article returned and once the
146 payment made, the refund order should be marked as paid."""
147 self.pos_config_usd.open_ui()
148 current_session = self.pos_config_usd.current_session_id
149
150 # order total will be 30 with 3.52 taxes included
151 order, _ = self.create_backend_pos_order({
152 'line_data': [
153 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
154 {'product_id': self.twenty_dollars_with_15_incl.product_variant_id.id},
155 ],
156 'payment_data': [
157 {'payment_method_id': self.cash_payment_method.id, 'amount': 10},
158 {'payment_method_id': self.bank_payment_method.id, 'amount': 20},
159 ]
160 })
161
162 refund_action = order.refund()
163 refund = self.env['pos.order'].browse(refund_action['res_id'])
164
165 with Form(refund) as refund_form:
166 with refund_form.lines.edit(0) as line:
167 line.qty = 0
168 refund = refund_form.save()
169
170 self.assertEqual(refund.amount_total, -20.0)
171
172 payment_context = {"active_ids": refund.ids, "active_id": refund.id}
173 refund_payment = self.env['pos.make.payment'].with_context(**payment_context).create({
174 'amount': refund.amount_total,
175 'payment_method_id': self.cash_payment_method.id,
176 })
177 refund_payment.with_context(**payment_context).check()
178
179 self.assertEqual(refund.state, 'paid')
180
181 refund_action = order.refund()
182 remaining_refund = self.env['pos.order'].browse(refund_action['res_id'])
183 self.assertEqual(remaining_refund.amount_total, -10.0)
184
185 payment_context = {"active_ids": remaining_refund.ids, "active_id": remaining_refund.id}
186 refund_payment = self.env['pos.make.payment'].with_context(**payment_context).create({
187 'amount': remaining_refund.amount_total,
188 'payment_method_id': self.cash_payment_method.id,
189 })
190 refund_payment.with_context(**payment_context).check()
191
192 self.assertEqual(remaining_refund.state, 'paid')
193
194 current_session.action_pos_session_closing_control()
195 self.assertEqual(current_session.state, 'closed')
196
197 def test_order_to_picking(self):
198 """
199 In order to test the Point of Sale in module, I will do three orders
200 from the sale to the payment, invoicing + picking, but will only
201 check the picking consistency in the end.
202
203 TODO: Check the negative picking after changing the picking relation
204 to One2many (also for a mixed use case), check the quantity, the
205 locations and return picking logic
206 """
207 order_1, _ = self.create_backend_pos_order({
208 'order_data': {
209 'partner_id': self.partner_jcb.id,
210 'pricelist_id': self.partner_jcb.property_product_pricelist.id,
211 },
212 'line_data': [
213 {'product_id': self.twenty_dollars_with_15_incl.product_variant_id.id},
214 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
215 ],
216 'payment_data': [
217 {'payment_method_id': self.credit_payment_method.id, 'amount': 30},
218 ],
219 })
220 order_2, _ = self.create_backend_pos_order({
221 'order_data': {
222 'partner_id': self.partner_lowe.id,
223 'pricelist_id': self.partner_lowe.property_product_pricelist.id,
224 },
225 'line_data': [
226 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
227 {'product_id': self.twenty_dollars_with_15_incl.product_variant_id.id},
228 ],
229 'payment_data': [
230 {'payment_method_id': self.credit_payment_method.id, 'amount': 30},
231 ],
232 })
233 order_3, order_refund_3 = self.create_backend_pos_order({
234 'order_data': {
235 'partner_id': self.partner_vlst.id,
236 'pricelist_id': self.partner_vlst.property_product_pricelist.id,
237 },
238 'line_data': [
239 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
240 {'product_id': self.twenty_dollars_with_15_incl.product_variant_id.id},
241 ],
242 'payment_data': [
243 {'payment_method_id': self.cash_payment_method.id, 'amount': 30},
244 ],
245 'refund_data': [
246 {'payment_method_id': self.cash_payment_method.id, 'amount': -30},
247 ],
248 })
249
250 self.assertEqual(order_1.state, 'paid', 'Order should be in paid state.')
251 self.assertEqual(order_1.picking_ids[0].state, 'done')
252 self.assertEqual(order_1.picking_ids[0].move_ids.mapped('state'), ['done', 'done'])
253 self.assertEqual(order_2.state, 'paid', 'Order should be in paid state.')
254 self.assertEqual(order_2.picking_ids[0].state, 'done')
255 self.assertEqual(order_2.picking_ids[0].move_ids.mapped('state'), ['done', 'done'])
256 self.assertEqual(order_3.state, 'paid', 'Order should be in paid state.')
257 self.assertEqual(order_3.picking_ids[0].state, 'done')
258 self.assertEqual(order_3.picking_ids[0].move_ids.mapped('state'), ['done', 'done'])
259
260 order_refund_3.action_pos_order_invoice()
261 invoice_pdf_content = str(order_refund_3.account_move._get_invoice_legal_documents(
262 'pdf', allow_fallback=True).get('content'))
263 self.assertTrue("using Cash" in invoice_pdf_content)
264 self.assertEqual(order_refund_3.picking_count, 1)
265 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
266
267 def test_order_to_picking02(self):
268 """
269 This test is similar to test_order_to_picking except that this time,
270 there are two products:
271 - One tracked by lot (ten_dollars_with_10_incl)
272 - One untracked (twenty_dollars_with_15_incl)
273 - Both are in a sublocation of the main warehouse
274 """
275 wh_location = self.company_data['default_warehouse'].lot_stock_id
276 shelf1_location = self.env['stock.location'].create({
277 'name': 'shelf1',
278 'usage': 'internal',
279 'location_id': wh_location.id,
280 })
281 self.ten_dollars_with_10_incl.product_variant_id.write({
282 'tracking': 'lot',
283 'is_storable': True,
284 })
285 self.twenty_dollars_with_15_incl.product_variant_id.write({
286 'tracking': 'none',
287 'is_storable': True,
288 })
289 lot = self.env['stock.lot'].create({
290 'name': 'SuperLot',
291 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
292 })
293
294 quantity_1 = self.env['stock.quant']._update_available_quantity(
295 self.ten_dollars_with_10_incl.product_variant_id, shelf1_location, 2, lot_id=lot)
296 quantity_2 = self.env['stock.quant']._update_available_quantity(
297 self.twenty_dollars_with_15_incl.product_variant_id, shelf1_location, 2)
298
299 self.assertEqual(quantity_1[0], 2)
300 self.assertEqual(quantity_2[0], 2)
301 self.pos_config_usd.open_ui()
302 self.pos_config_usd.current_session_id.update_stock_at_closing = False
303 order, _ = self.create_backend_pos_order({
304 'order_data': {
305 'partner_id': self.partner_manv.id,
306 'pricelist_id': self.partner_manv.property_product_pricelist.id,
307 },
308 'line_data': [
309 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
310 {'product_id': self.twenty_dollars_with_15_incl.product_variant_id.id},
311 ],
312 'payment_data': [
313 {'payment_method_id': self.cash_payment_method.id, 'amount': 30},
314 ],
315 })
316
317 self.assertEqual(order.state, 'paid')
318 tracked_line = self.env['stock.move.line'].search(
319 [('product_id', '=', self.ten_dollars_with_10_incl.product_variant_id.id)])
320 untracked_line = order.picking_ids.move_line_ids - tracked_line
321 self.assertEqual(tracked_line.lot_id, lot)
322 self.assertFalse(untracked_line.lot_id)
323 self.assertEqual(tracked_line.location_id, shelf1_location)
324 self.assertEqual(untracked_line.location_id, shelf1_location)
325
326 res = order.action_pos_order_invoice()
327 invoice_test = self.env['account.move'].browse(res['res_id'])
328 self.assertEqual(invoice_test.ref, invoice_test.pos_order_ids.display_name)
329
330 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
331
332 def test_order_to_payment_currency(self):
333 """
334 In order to test the Point of Sale in module, I will do a full flow
335 from the sale to the payment and invoicing. I will use two products,
336 one with price including a 10% tax, the other one with 5% tax
337 excluded from the price.
338
339 The order will be in a different currency than the company currency.
340 """
341 self.env.cr.execute(
342 "UPDATE res_company SET currency_id = %s WHERE id = %s",
343 [self.env.ref('base.USD').id, self.env.company.id])
344
345 # Demo data are crappy, clean-up the rates
346 self.env['res.currency.rate'].search([]).unlink()
347 self.env['res.currency.rate'].create({
348 'name': '2010-01-01',
349 'rate': 2.0,
350 'currency_id': self.env.ref('base.EUR').id,
351 })
352
353 order, _ = self.create_backend_pos_order({
354 'order_data': {
355 'partner_id': self.partner_mobt.id,
356 'pricelist_id': self.partner_mobt.property_product_pricelist.id,
357 },
358 'line_data': [
359 {'product_id': self.ten_dollars_no_tax.product_variant_id.id},
360 {'product_id': self.twenty_dollars_no_tax.product_variant_id.id},
361 ],
362 'payment_data': [
363 {'payment_method_id': self.bank_payment_method.id, 'amount': 10},
364 {'payment_method_id': self.bank_payment_method.id},
365 ],
366 'pos_config': self.pos_config_eur,
367 })
368
369 self.assertEqual(order.amount_total, 30)
370 self.assertEqual(order.amount_paid, 30)
371 self.assertEqual(order.state, 'paid')
372 current_session = self.pos_config_eur.current_session_id
373 current_session.action_pos_session_validate()
374 self.assertTrue(current_session.move_id)
375 debit_lines = current_session.move_id.mapped('line_ids.debit')
376 credit_lines = current_session.move_id.mapped('line_ids.credit')
377 amount_currency_lines = current_session.move_id.mapped('line_ids.amount_currency')
378 for a, b in zip(sorted(debit_lines), [0.0, 15.0]):
379 self.assertAlmostEqual(a, b)
380 for a, b in zip(sorted(credit_lines), [0.0, 15.0]):
381 self.assertAlmostEqual(a, b)
382 for a, b in zip(sorted(amount_currency_lines), [-30, 30]):
383 self.assertAlmostEqual(a, b)
384
385 def test_order_to_invoice_no_tax(self):
386 order, _ = self.create_backend_pos_order({
387 'order_data': {
388 'partner_id': self.partner_mobt.id,
389 'pricelist_id': self.partner_mobt.property_product_pricelist.id,
390 },
391 'line_data': [
392 {'product_id': self.ten_dollars_no_tax.product_variant_id.id},
393 {'product_id': self.twenty_dollars_no_tax.product_variant_id.id},
394 ],
395 'payment_data': [
396 {'payment_method_id': self.bank_payment_method.id, 'amount': 30},
397 ],
398 })
399 self.assertEqual(order.state, 'paid', "Order should be in paid state.")
400 self.assertFalse(order.account_move, 'Invoice should not be attached to order yet.')
401
402 res = order.action_pos_order_invoice()
403 self.assertIn('res_id', res, "No invoice created")
404
405 # I test that the total of the attached invoice is correct
406 invoice = self.env['account.move'].browse(res['res_id'])
407 if invoice.state != 'posted':
408 invoice.action_post()
409
410 # Making the invoice draft should send a warning notification to the user
411 with patch.object(self.env.registry['bus.bus'], '_sendone') as mock_send:
412 invoice.button_draft()
413 mock_send.assert_called_with(self.env.user.partner_id, 'simple_notification', {
414 'type': 'danger',
415 'message': "You can't reset this invoice to draft because the POS session is still open. Please close the ongoing session first, then try again.",
416 'sticky': True,
417 })
418
419 self.assertEqual(invoice.state, 'posted')
420
421 self.assertAlmostEqual(invoice.amount_total, order.amount_total, places=2)
422
423 for iline in invoice.invoice_line_ids:
424 self.assertFalse(iline.tax_ids)
425
426 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
427
428 def test_order_to_invoice_uses_correct_shipping_address(self):
429 """
430 Test that invoice created from POS uses the correct shipping address
431 same as selected in the POS order.
432 """
433 _, delivery2 = self.env["res.partner"].create([{
434 'name': f"Delivery Address {i + 1}",
435 'type': 'delivery',
436 'parent_id': self.partner.id,
437 } for i in range(2)]
438 )
439
440 self.pos_config_eur.open_ui()
441 current_session = self.pos_config_eur.current_session_id
442 untax, tax = self.compute_tax(self.product, 100, 1)
443
444 pos_order = self.env['pos.order'].create({
445 'company_id': self.env.company.id,
446 'session_id': current_session.id,
447 'partner_id': delivery2.id,
448 'pricelist_id': self.partner.property_product_pricelist.id,
449 'lines': [(0, 0, {
450 'name': "OL/0001",
451 'product_id': self.product.id,
452 'price_unit': 100,
453 'qty': 1.0,
454 'tax_ids': [(6, 0, self.product.taxes_id.ids)],
455 'price_subtotal': untax,
456 'price_subtotal_incl': untax + tax,
457 })],
458 'amount_tax': tax,
459 'amount_total': untax + tax,
460 'amount_paid': 0.0,
461 'amount_return': 0.0,
462 'last_order_preparation_change': '{}'
463 })
464
465 pos_order.action_pos_order_invoice()
466 invoice = pos_order.account_move
467
468 self.assertEqual(
469 invoice.partner_shipping_id.id,
470 delivery2.id,
471 "The shipping address should be 'Delivery Address 2' as selected in the POS order."
472 )
473
474 def test_order_with_deleted_tax(self):
475 order, _ = self.create_backend_pos_order({
476 'line_data': [
477 {'product_id': self.ten_dollars_with_10_excl.product_variant_id.id},
478 ],
479 })
480
481 untax, atax = self.compute_tax(self.ten_dollars_with_10_excl.product_variant_id, 10.0)
482 self.ten_dollars_with_10_excl.taxes_id.unlink()
483 current_session = self.pos_config_usd.current_session_id
484 payment = self.env['pos.make.payment'].create({
485 'config_id': self.pos_config_usd.id,
486 'amount': untax + atax,
487 'payment_method_id': self.cash_payment_method.id,
488 })
489 payment.with_context(active_ids=order.ids, active_id=order.id).check()
490 self.assertEqual(order.state, 'paid', "Order should be in paid state.")
491
492 total_cash_payment = sum(current_session.mapped('order_ids.payment_ids').filtered(
493 lambda payment: payment.payment_method_id.type == 'cash').mapped('amount'))
494 current_session.post_closing_cash_details(total_cash_payment)
495
496 # close session (should not fail here)
497 # We don't call `action_pos_session_closing_control` to force the failed
498 # closing which will return the action because the internal rollback call messes
499 # with the rollback of the test runner. So instead, we directly call the method
500 # that returns the action by specifying the imbalance amount.
501 action = current_session._close_session_action(1.0)
502 wizard = self.env['pos.close.session.wizard'].browse(action['res_id'])
503 wizard.with_context(action['context']).close_session()
504
505 diff_line = current_session.move_id.line_ids.filtered(
506 lambda line: line.name == 'Difference at closing PoS session')
507 self.assertAlmostEqual(diff_line.credit, 1.0, msg="Missing amount of 1.0")
508
509 def test_order_multi_step_route(self):
510 """
511 Test that orders in sessions with "Ship Later" enabled and
512 "Specific Route" set to a multi-step (2/3) route can be validated.
513 This config implies multiple picking types and multiple move_lines.
514 """
515 self.ten_dollars_with_10_incl.product_variant_id.write({
516 'tracking': 'lot',
517 'is_storable': True,
518 })
519 self.twenty_dollars_with_10_incl.product_variant_id.write({
520 'tracking': 'lot',
521 'is_storable': True,
522 })
523 twenty_dollars_lot = self.env['stock.lot'].create({
524 'name': '80085',
525 'product_id': self.twenty_dollars_with_10_incl.product_variant_id.id,
526 })
527 stock_location = self.company_data['default_warehouse'].lot_stock_id
528 stock_quantity = self.env['stock.quant'].with_context(inventory_mode=True).create({
529 'product_id': self.twenty_dollars_with_10_incl.product_variant_id.id,
530 'inventory_quantity': 1,
531 'location_id': stock_location.id,
532 'lot_id': twenty_dollars_lot.id
533 })
534 stock_quantity.action_apply_inventory()
535 warehouse_id = self.company_data['default_warehouse']
536 warehouse_id.delivery_steps = 'pick_ship'
537
538 self.pos_config_usd.write({
539 'ship_later': True,
540 'warehouse_id': warehouse_id.id,
541 'route_id': warehouse_id.route_ids[-1].id,
542 })
543
544 self.pos_config_usd.open_ui()
545 self.pos_config_usd.current_session_id.update_stock_at_closing = False
546 order, _ = self.create_backend_pos_order({
547 'order_data': {
548 'shipping_date': fields.Date.today(),
549 'partner_id': self.partner_mobt.id,
550 'pricelist_id': self.partner_mobt.property_product_pricelist.id,
551 },
552 'line_data': [
553 {
554 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
555 'pack_lot_ids': [[0, 0, {'lot_name': '80085'}]],
556 },
557 {
558 'product_id': self.twenty_dollars_with_10_incl.product_variant_id.id,
559 'pack_lot_ids': [[0, 0, {'lot_name': '80085'}]],
560 },
561 ],
562 'payment_data': [
563 {'payment_method_id': self.bank_payment_method.id, 'amount': 30},
564 ],
565 })
566 picking_mls_no_stock = order.picking_ids.move_line_ids.filtered(
567 lambda l: l.product_id.id == self.ten_dollars_with_10_incl.product_variant_id.id)
568 picking_mls_stock = order.picking_ids.move_line_ids.filtered(
569 lambda l: l.product_id.id == self.twenty_dollars_with_10_incl.product_variant_id.id)
570 self.assertEqual(order.state, 'paid')
571 self.assertEqual(len(picking_mls_no_stock), 0)
572 self.assertEqual(len(picking_mls_stock), 1)
573 self.assertEqual(len(order.picking_ids.picking_type_id), 1)
574
575 def test_pos_order_invoice_payment_term(self):
576 """ Test that when invoicing a POS order paid with customer account, the partner's payment term is then applied to the invoice. """
577 self.customer_account_payment_method = self.env['pos.payment.method'].create({
578 'name': 'Customer Account',
579 'split_transactions': True,
580 })
581 payment_methods = self.pos_config_usd.payment_method_ids | self.customer_account_payment_method
582 self.pos_config_usd.write({'payment_method_ids': [Command.set(payment_methods.ids)]})
583
584 pay_term_30 = self.env.ref('account.account_payment_term_30days')
585 partner_a = self.env["res.partner"].create({
586 'name': 'APartner',
587 'property_payment_term_id': pay_term_30.id,
588 })
589
590 self.pos_config_usd.open_ui()
591 current_session = self.pos_config_usd.current_session_id
592 order = self.env['pos.order'].create({
593 'company_id': self.env.company.id,
594 'session_id': current_session.id,
595 'partner_id': partner_a.id,
596 'lines': [Command.create({
597 'product_id': self.product_a.id,
598 'price_unit': 10,
599 'discount': 0,
600 'qty': 1,
601 'price_subtotal': 10,
602 'price_subtotal_incl': 10,
603 })],
604 'amount_paid': 10.0,
605 'amount_total': 10.0,
606 'amount_tax': 0.0,
607 'amount_return': 0.0,
608 'to_invoice': True,
609 'last_order_preparation_change': '{}'
610 })
611 payment_context = {"active_ids": order.ids, "active_id": order.id}
612 order_payment = self.env['pos.make.payment'].with_context(**payment_context).create({
613 'amount': 10.0,
614 'payment_method_id': self.customer_account_payment_method.id
615 })
616 order_payment.with_context(**payment_context).check()
617
618 self.assertEqual(order.account_move.invoice_date_due, (datetime.now() + timedelta(days=30)).date())
619
620 def test_order_with_different_payments_and_refund(self):
621 """
622 Test that all the payments are correctly taken into account when the order
623 contains multiple payments and money refund.
624 In this example, we create an order with two payments for a product of 750$:
625 - one payment of $300 with customer account
626 - one payment of $460 with cash
627 Then, we refund the order with $10, and check that the amount still due is 300$.
628 """
629 self.twenty_dollars_no_tax.product_variant_id.write({
630 'is_storable': True,
631 })
632 order, _ = self.create_backend_pos_order({
633 'order_data': {
634 'partner_id': self.partner_adgu.id,
635 'to_invoice': True,
636 },
637 'line_data': [
638 {'product_id': self.twenty_dollars_no_tax.product_variant_id.id},
639 ],
640 'payment_data': [
641 {'payment_method_id': self.cash_payment_method.id, 'amount': 10},
642 {'payment_method_id': self.credit_payment_method.id, 'amount': 20},
643 {'payment_method_id': self.cash_payment_method.id, 'amount': -10},
644 ],
645 })
646 self.assertEqual(order.account_move.amount_residual, 20)
647
648 def test_sale_order_postponed_invoicing(self):
649 """
650 Test the flow of creating an invoice later, after the POS session
651 has been closed and everything has been processed. Process should:
652 - Create a new misc entry, that will revert part of the POS
653 closing entry.
654 - Create the move and associating payment(s) entry, as it would
655 do when closing with invoice.
656 - Reconcile the receivable lines from the created misc entry
657 with the ones from the created payment(s)
658 """
659 tags = self.setup_tags()
660 with freeze_time('2020-01-01'):
661 order, _ = self.create_backend_pos_order({
662 'line_data': [
663 {'product_id': self.twenty_dollars_with_15_excl.product_variant_id.id},
664 ],
665 'payment_data': [
666 {'payment_method_id': self.bank_payment_method.id, 'amount': 23.0},
667 ],
668 })
669 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
670
671 # Check the closing entry.
672 closing_entry = order.session_move_id
673 self.assertRecordValues(closing_entry.line_ids.sorted(), [{
674 'balance': -3.0,
675 'account_id': self.company_data['default_account_tax_sale'].id,
676 'tax_ids': [],
677 'tax_tag_ids': tags[1].ids,
678 'reconciled': False
679 }, {
680 'balance': -20.0,
681 'account_id': self.company_data['default_account_revenue'].id,
682 'tax_ids': self.tax_sale_a.ids,
683 'tax_tag_ids': tags[0].ids,
684 'reconciled': False
685 }, {
686 'balance': 23.0,
687 'account_id': self.company_data['default_account_receivable'].id,
688 'tax_ids': [],
689 'tax_tag_ids': [],
690 'reconciled': True
691 }])
692
693 with freeze_time('2020-01-03'):
694 order.partner_id = self.partner_adgu.id
695 order.action_pos_order_invoice()
696
697 # Check the reverse moves, one for the closing entry, one for the statement lines.
698 reverse_closing_entries = self.env['account.move'].search([
699 ('id', '!=', closing_entry.id),
700 ('company_id', '=', self.env.company.id),
701 ('statement_line_id', '=', False),
702 ('move_type', '=', 'entry'),
703 ('state', '=', 'posted'),
704 ])
705 self.assertRecordValues(reverse_closing_entries[0].line_ids.sorted(), [{
706 'balance': 3.0,
707 'account_id': self.company_data['default_account_tax_sale'].id,
708 'tax_ids': [],
709 'tax_tag_ids': tags[1].ids,
710 'reconciled': False
711 }, {
712 'balance': 20.0,
713 'account_id': self.company_data['default_account_revenue'].id,
714 'tax_ids': self.tax_sale_a.ids,
715 'tax_tag_ids': tags[0].ids,
716 'reconciled': False
717 }, {
718 'balance': -23.0,
719 'account_id': self.company_data['default_account_receivable'].id,
720 'tax_ids': [],
721 'tax_tag_ids': [],
722 'reconciled': True
723 }])
724 self.assertRecordValues(reverse_closing_entries[2].line_ids.sorted(), [{
725 'balance': -23.0,
726 'account_id': self.company_data['default_account_receivable'].id,
727 'tax_ids': [],
728 'tax_tag_ids': [],
729 'reconciled': True
730 }, {
731 'balance': 23.0,
732 'account_id': self.company_data['default_account_receivable'].id,
733 'tax_ids': [],
734 'tax_tag_ids': [],
735 'reconciled': True
736 }])
737
738 def test_sale_order_postponed_invoicing_storno(self):
739 """
740 Test the flow of creating an invoice later, after the POS session
741 has been closed and everything has been processed. Process should:
742 - Create a new misc entry, that will revert part of the POS
743 closing entry.
744 - Create the move and associating payment(s) entry, as it would
745 do when closing with invoice.
746 - Reconcile the receivable lines from the created misc entry
747 with the ones from the created payment(s)
748 This test is the same as test_sale_order_postponed_invoicing but
749 with the storno feature enabled.
750 """
751 self.env.company.account_storno = True
752
753 tags = self.setup_tags()
754 with freeze_time('2020-01-01'):
755 order, _ = self.create_backend_pos_order({
756 'line_data': [
757 {'product_id': self.twenty_dollars_with_15_excl.product_variant_id.id},
758 ],
759 'payment_data': [
760 {'payment_method_id': self.bank_payment_method.id, 'amount': 23.0},
761 ],
762 })
763 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
764
765 # Check the closing entry.
766 closing_entry = order.session_move_id
767 self.assertRecordValues(closing_entry.line_ids.sorted(), [{
768 'balance': -3.0,
769 'debit': 0.0,
770 'credit': 3.0,
771 'account_id': self.company_data['default_account_tax_sale'].id,
772 'tax_ids': [],
773 'tax_tag_ids': tags[1].ids,
774 'reconciled': False,
775 }, {
776 'balance': -20.0,
777 'debit': 0.0,
778 'credit': 20.0,
779 'account_id': self.company_data['default_account_revenue'].id,
780 'tax_ids': self.tax_sale_a.ids,
781 'tax_tag_ids': tags[0].ids,
782 'reconciled': False,
783 }, {
784 'balance': 23.0,
785 'debit': 23.0,
786 'credit': 0.0,
787 'account_id': self.company_data['default_account_receivable'].id,
788 'tax_ids': [],
789 'tax_tag_ids': [],
790 'reconciled': True,
791 }])
792
793 with freeze_time('2020-01-03'):
794 order.partner_id = self.partner_adgu.id
795 order.action_pos_order_invoice()
796
797 # Check the reverse moves, one for the closing entry, one for the statement lines.
798 reverse_closing_entries = self.env['account.move'].search([
799 ('id', '!=', closing_entry.id),
800 ('company_id', '=', self.env.company.id),
801 ('statement_line_id', '=', False),
802 ('move_type', '=', 'entry'),
803 ('state', '=', 'posted'),
804 ])
805 self.assertRecordValues(reverse_closing_entries[0].line_ids.sorted(), [{
806 'balance': 3.0,
807 'debit': 0.0,
808 'credit': -3.0,
809 'account_id': self.company_data['default_account_tax_sale'].id,
810 'tax_ids': [],
811 'tax_tag_ids': tags[1].ids,
812 'reconciled': False,
813 }, {
814 'balance': 20.0,
815 'debit': 0.0,
816 'credit': -20.0,
817 'account_id': self.company_data['default_account_revenue'].id,
818 'tax_ids': self.tax_sale_a.ids,
819 'tax_tag_ids': tags[0].ids,
820 'reconciled': False,
821 }, {
822 'balance': -23.0,
823 'debit': -23.0,
824 'credit': 0.0,
825 'account_id': self.company_data['default_account_receivable'].id,
826 'tax_ids': [],
827 'tax_tag_ids': [],
828 'reconciled': True,
829 }])
830 self.assertTrue(all(amount >= 0 for amount in reverse_closing_entries[1:].line_ids.mapped('debit') + reverse_closing_entries[1:].line_ids.mapped('credit')),
831 "Non-reverse entries should have positive debit or credit amounts.")
832
833 def test_sale_order_postponed_invoicing_anglosaxon(self):
834 """ Test the flow of creating an invoice later, after the POS session has been closed and everything has been processed
835 in the case of anglo-saxon accounting.
836 """
837 self.env.company.anglo_saxon_accounting = True
838 self.env.company.point_of_sale_update_stock_quantities = 'closing'
839 order, _ = self.create_backend_pos_order({
840 'line_data': [
841 {'product_id': self.twenty_dollars_with_15_incl.product_variant_id.id},
842 ],
843 'payment_data': [
844 {'payment_method_id': self.bank_payment_method.id, 'amount': 20.0},
845 ],
846 })
847 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
848 with freeze_time('2020-01-03'):
849 order.partner_id = self.partner_stva.id
850 order.action_pos_order_invoice()
851
852 picking_ids = order.session_id.picking_ids
853 self.assertEqual(sum(picking_ids.move_line_ids.mapped('quantity')), 1)
854
855 def test_order_pos_tax_same_as_company(self):
856 """
857 Test that when the default_pos_receivable_account and the partner
858 account_receivable are the same, payment are correctly reconciled
859 and the invoice is correctly marked as paid.
860 """
861 self.pos_config_usd.open_ui()
862 current_session = self.pos_config_usd.current_session_id
863 account = self.partner_jcb.property_account_receivable_id
864 current_session.company_id.account_default_pos_receivable_account_id = account
865
866 order, _ = self.create_backend_pos_order({
867 'order_data': {
868 'partner_id': self.partner_jcb.id,
869 'to_invoice': True,
870 'pricelist_id': self.partner_jcb.property_product_pricelist.id,
871 },
872 'line_data': [
873 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
874 {'product_id': self.twenty_dollars_with_10_incl.product_variant_id.id},
875 ],
876 'payment_data': [
877 {'payment_method_id': self.cash_payment_method.id, 'amount': 30},
878 ],
879 })
880
881 self.assertEqual(order.account_move.amount_residual, 0)
882
883 def test_journal_entries_category_without_account(self):
884 # Set company's default accounts to false
885 self.env.company.income_account_id = False
886 self.env.company.expense_account_id = False
887 self.twenty_dollars_with_10_incl.write({
888 'property_account_income_id': False,
889 'property_account_expense_id': False,
890 })
891 account = self.env['account.account'].create({
892 'name': 'Account for category without account',
893 'code': 'X1111',
894 })
895
896 self.pos_config_usd.journal_id.default_account_id = account.id
897 self.create_backend_pos_order({
898 'line_data': [
899 {'product_id': self.twenty_dollars_with_10_incl.product_variant_id.id},
900 ],
901 'payment_data': [
902 {'payment_method_id': self.cash_payment_method.id, 'amount': 20},
903 ],
904 })
905 current_session = self.pos_config_usd.current_session_id
906 current_session.action_pos_session_closing_control()
907 self.assertEqual(current_session.move_id.line_ids[0].account_id.id, account.id)
908
909 def test_tracked_product_with_owner(self):
910 self.stock_location = self.company_data['default_warehouse'].lot_stock_id
911 self.ten_dollars_with_10_incl.product_variant_id.write({
912 'tracking': 'serial',
913 'is_storable': True,
914 })
915 lot1 = self.env['stock.lot'].create({
916 'name': '1001',
917 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
918 })
919 self.env['stock.quant']._update_available_quantity(
920 self.ten_dollars_with_10_incl.product_variant_id,
921 self.stock_location,
922 1, lot_id=lot1, owner_id=self.partner_adgu)
923
924
925 # create pos order with the two SN created before
926 self.create_backend_pos_order({
927 'order_data': {
928 'partner_id': self.partner_adgu.id,
929 'pricelist_id': self.pos_config_usd.pricelist_id.id,
930 },
931 'line_data': [
932 {
933 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
934 'pack_lot_ids': [[0, 0, {'lot_name': lot1.name}]],
935 },
936 ],
937 'payment_data': [
938 {'payment_method_id': self.cash_payment_method.id, 'amount': 10},
939 ],
940 })
941 current_session = self.pos_config_usd.current_session_id
942 current_session.action_pos_session_closing_control()
943 self.assertEqual(current_session.picking_ids.move_line_ids.owner_id.id, self.partner_adgu.id)
944
945 def test_order_refund_with_invoice(self):
946 """This test make sure that credit notes of pos orders are correctly
947 linked to the original invoice."""
948 self.pos_config_usd.open_ui()
949 current_session = self.pos_config_usd.current_session_id
950 self.create_backend_pos_order({
951 'order_data': {
952 'partner_id': self.partner_adgu.id,
953 'to_invoice': True,
954 },
955 'line_data': [
956 {'product_id': self.twenty_dollars_with_15_incl.product_variant_id.id}
957 ],
958 'payment_data': [
959 {'payment_method_id': self.bank_payment_method.id, 'amount': 20}
960 ],
961 'refund_data': [
962 {'payment_method_id': self.bank_payment_method.id, 'amount': -20}
963 ]
964 })
965
966 current_session.action_pos_session_closing_control()
967 invoices = self.env['account.move'].search([('move_type', '=', 'out_invoice')], order='id desc', limit=1)
968 credit_notes = self.env['account.move'].search([('move_type', '=', 'out_refund')], order='id desc', limit=1)
969 self.assertEqual(credit_notes.ref, "Reversal of: "+invoices.name)
970 self.assertEqual(credit_notes.reversed_entry_id.id, invoices.id)
971
972 def test_multi_exp_account_real_time(self):
973 self.real_time_categ = self.env['product.category'].create({
974 'name': 'test category',
975 'parent_id': False,
976 'property_cost_method': 'fifo',
977 'property_valuation': 'real_time',
978 })
979 self.account1 = self.env['account.account'].create({
980 'name': 'Account 1',
981 'code': 'AC1',
982 'reconcile': True,
983 'account_type': 'expense',
984 })
985 self.account2 = self.env['account.account'].create({
986 'name': 'Account 2',
987 'code': 'AC2',
988 'reconcile': True,
989 'account_type': 'expense',
990 })
991 self.ten_dollars_with_15_incl.write({
992 'is_storable': True,
993 'categ_id': self.real_time_categ.id,
994 'property_account_expense_id': self.account1.id,
995 'property_account_income_id': self.account1.id,
996 })
997 self.twenty_dollars_with_15_incl.write({
998 'is_storable': True,
999 'categ_id': self.real_time_categ.id,
1000 'property_account_expense_id': self.account2.id,
1001 'property_account_income_id': self.account2.id,
1002 })
1003 order, _ = self.create_backend_pos_order({
1004 'order_data': {
1005 'pricelist_id': self.pos_config_usd.pricelist_id.id,
1006 'partner_id': self.partner_adgu.id,
1007 'shipping_date': fields.Date.today(),
1008 },
1009 'line_data': [
1010 {'product_id': self.ten_dollars_with_15_incl.product_variant_id.id},
1011 {'product_id': self.twenty_dollars_with_15_incl.product_variant_id.id},
1012 ],
1013 'payment_data': [
1014 {'payment_method_id': self.cash_payment_method.id, 'amount': 30},
1015 ],
1016 })
1017
1018 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
1019 order.picking_ids._action_done()
1020 self.assertEqual(len(order.picking_ids.move_ids), 2)
1021
1022 def test_no_default_pricelist(self):
1023 """Should not have default_pricelist if use_pricelist is false."""
1024
1025 pricelist = self.env['product.pricelist'].create({
1026 'name': 'Test Pricelist',
1027 })
1028 self.pos_config_usd.write({
1029 'pricelist_id': pricelist.id,
1030 'use_pricelist': False,
1031 })
1032 self.pos_config_usd.open_ui()
1033 loaded_data = self.pos_config_usd.current_session_id.load_data([])
1034
1035 self.assertFalse(loaded_data['pos.config'][0]['pricelist_id'], False)
1036
1037 def test_refund_rounding_backend(self):
1038 self.account_cash_rounding_up.rounding = 5.0
1039 self.pos_config_usd.write({
1040 'rounding_method': self.account_cash_rounding_up.id,
1041 'cash_rounding': True,
1042 'only_round_cash_method': True,
1043 })
1044 _, refund = self.create_backend_pos_order({
1045 'line_data': [
1046 {'product_id': self.twenty_dollars_with_15_excl.product_variant_id.id},
1047 ],
1048 'payment_data': [
1049 {'payment_method_id': self.cash_payment_method.id, 'amount': 23.0}
1050 ],
1051 'refund_data': [
1052 {'payment_method_id': self.cash_payment_method.id}
1053 ]
1054 })
1055
1056 current_session = self.pos_config_usd.current_session_id
1057 current_session.action_pos_session_closing_control()
1058 refund_payment = refund.payment_ids[0]
1059 self.assertEqual(refund_payment.amount, -25.0)
1060 self.assertEqual(refund.amount_total, -23.00)
1061 self.assertEqual(refund.amount_paid, -25.0)
1062 self.assertEqual(current_session.state, 'closed')
1063
1064 def test_order_different_lots(self):
1065 self.pos_config_usd.open_ui()
1066 self.stock_location = self.company_data['default_warehouse'].lot_stock_id
1067 self.ten_dollars_with_10_incl.product_variant_id.write({
1068 'tracking': 'lot',
1069 'is_storable': True,
1070 })
1071
1072 lot_1 = self.env['stock.lot'].create({
1073 'name': '1001',
1074 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
1075 })
1076 lot_2 = self.env['stock.lot'].create({
1077 'name': '1002',
1078 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
1079 })
1080
1081 stock_quant_1 = self.env['stock.quant'].with_context(inventory_mode=True).create({
1082 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
1083 'inventory_quantity': 5,
1084 'location_id': self.stock_location.id,
1085 'lot_id': lot_1.id
1086 })
1087 stock_quant_1.action_apply_inventory()
1088 stock_quant_2 = self.env['stock.quant'].with_context(inventory_mode=True).create({
1089 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
1090 'inventory_quantity': 5,
1091 'location_id': self.stock_location.id,
1092 'lot_id': lot_2.id
1093 })
1094 stock_quant_2.action_apply_inventory()
1095 self.assertEqual(stock_quant_1.quantity, 5)
1096 self.assertEqual(stock_quant_2.quantity, 5)
1097 order, _ = self.create_backend_pos_order({
1098 'order_data': {
1099 'partner_id': self.partner_adgu.id,
1100 'pricelist_id': self.pos_config_usd.pricelist_id.id,
1101 },
1102 'line_data': [{
1103 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
1104 'pack_lot_ids': [[0, 0, {'lot_name': '1001'}]],
1105 'qty': 1,
1106 }, {
1107 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
1108 'pack_lot_ids': [[0, 0, {'lot_name': '1002'}]],
1109 'qty': 2,
1110 },
1111 ],
1112 'payment_data': [
1113 {'payment_method_id': self.cash_payment_method.id, 'amount': 30},
1114 ],
1115 })
1116 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
1117 self.assertEqual(order.state, 'done')
1118
1119 # Quantity decreased because from the same location
1120 self.assertEqual(stock_quant_1.quantity, 4)
1121 self.assertEqual(stock_quant_2.quantity, 3)
1122
1123 def test_pos_branch_account(self):
1124 branch = self.env['res.company'].create({
1125 'name': 'Sub Company',
1126 'parent_id': self.env.company.id,
1127 'chart_template': self.env.company.chart_template,
1128 'country_id': self.env.company.country_id.id,
1129 })
1130 self.env.cr.precommit.run()
1131 self.env.user.group_ids += self.env.ref('point_of_sale.group_pos_manager')
1132 bank_payment_method = self.bank_payment_method.copy()
1133 bank_payment_method.company_id = branch.id
1134 sub_pos_config = self.env['pos.config'].with_company(branch).create({
1135 'name': 'Main',
1136 'journal_id': self.company_data['default_journal_sale'].id,
1137 'invoice_journal_id': self.company_data['default_journal_sale'].id,
1138 'payment_method_ids': [(4, bank_payment_method.id)],
1139 })
1140
1141 sub_pos_config.open_ui()
1142 current_session = sub_pos_config.current_session_id
1143 self.create_backend_pos_order({
1144 'order_data': {
1145 'partner_id': self.partner_moda.id,
1146 'pricelist_id': sub_pos_config.pricelist_id.id,
1147 },
1148 'line_data': [
1149 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
1150 ],
1151 'payment_data': [
1152 {'payment_method_id': bank_payment_method.id},
1153 ],
1154 'pos_config': sub_pos_config,
1155 })
1156
1157 current_session = sub_pos_config.current_session_id
1158 sub_pos_config.current_session_id.action_pos_session_closing_control()
1159 self.assertEqual(current_session.state, 'closed', msg='State of current session should be closed.')
1160
1161 def test_order_unexisting_lots(self):
1162 self.ten_dollars_with_10_incl.product_variant_id.write({
1163 'tracking': 'lot',
1164 'is_storable': True,
1165 })
1166
1167 order, _ = self.create_backend_pos_order({
1168 'line_data': [{
1169 'product_id': self.ten_dollars_with_10_incl.product_variant_id.id,
1170 'pack_lot_ids': [[0, 0, {'lot_name': '1001'}]],
1171 }],
1172 'payment_data': [
1173 {'payment_method_id': self.cash_payment_method.id, 'amount': 10},
1174 ],
1175 })
1176
1177 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
1178 order_lot_id = order.picking_ids.move_line_ids.lot_id
1179 self.assertEqual(order_lot_id.name, '1001')
1180 self.assertTrue(all(
1181 quant.lot_id == order_lot_id
1182 for quant in self.env['stock.quant'].search([
1183 ('product_id', '=', self.ten_dollars_with_10_incl.product_variant_id.id)
1184 ])
1185 ))
1186
1187 def test_pos_creation_in_branch(self):
1188 branch = self.env['res.company'].create({
1189 'name': 'Branch 1',
1190 'parent_id': self.env.company.id,
1191 'chart_template': self.env.company.chart_template,
1192 })
1193
1194 self.env["pos.config"].with_company(branch).create({
1195 "name": "Branch Point of Sale"
1196 })
1197
1198 def test_reordering_rules_triggered_closing_pos(self):
1199 if self.env['ir.module.module']._get('purchase').state != 'installed':
1200 self.skipTest("Purchase module is required for this test to run")
1201
1202 self.env['stock.route'].search([('name', '=', 'Buy')]).warehouse_ids = self.env['stock.warehouse'].search([])
1203 self.ten_dollars_with_15_incl.write({
1204 'seller_ids': [Command.create({
1205 'partner_id': self.partner_stva.id,
1206 'min_qty': 1.0,
1207 'price': 10.0,
1208 })]
1209 })
1210
1211 self.env['stock.warehouse.orderpoint'].create({
1212 'product_id': self.ten_dollars_with_15_incl.product_variant_id.id,
1213 'location_id': self.pos_config_usd.picking_type_id.default_location_src_id.id,
1214 'product_min_qty': 1.0,
1215 'product_max_qty': 1.0,
1216 })
1217
1218 self.create_backend_pos_order({
1219 'order_data': {
1220 'partner_id': self.partner_stva.id,
1221 'pricelist_id': self.pos_config_usd.pricelist_id.id,
1222 },
1223 'line_data': [
1224 {'product_id': self.ten_dollars_with_15_incl.product_variant_id.id},
1225 ],
1226 'payment_data': [
1227 {'payment_method_id': self.bank_payment_method.id, 'amount': 10},
1228 ],
1229 })
1230 self.pos_config_usd.current_session_id.action_pos_session_closing_control()
1231 purchase_order = self.env['purchase.order'].search([], limit=1)
1232 self.assertEqual(purchase_order.order_line.product_qty, 1)
1233 self.assertEqual(purchase_order.order_line.product_id.id,
1234 self.ten_dollars_with_15_incl.product_variant_id.id)
1235
1236 def test_state_when_closing_register(self):
1237 self.create_backend_pos_order({
1238 'line_data': [
1239 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
1240 ],
1241 'payment_data': [
1242 {'payment_method_id': self.bank_payment_method.id, 'amount': 10},
1243 ],
1244 })
1245 current_session = self.pos_config_usd.current_session_id
1246 current_session.action_pos_session_closing_control(bank_payment_method_diffs={self.bank_payment_method.id: 5.00})
1247 self.assertEqual(current_session.state, 'closed')
1248
1249 def test_refund_qty_refund_cancel(self):
1250 """
1251 Test the refunded qty of an order, when the refund order has been cancelled
1252 """
1253
1254 product1 = self.env['product.product'].create({
1255 'name': 'Test Product',
1256 'lst_price': 100,
1257 'type': 'consu',
1258 })
1259
1260 self.pos_config_usd.open_ui()
1261 current_session = self.pos_config_usd.current_session_id
1262
1263 pos_order_data = {
1264 'amount_paid': 100,
1265 'amount_return': 0,
1266 'amount_tax': 0,
1267 'amount_total': 100,
1268 'date_order': fields.Datetime.to_string(fields.Datetime.now()),
1269 'fiscal_position_id': False,
1270 'lines': [(0, 0, {
1271 'discount': 0,
1272 'pack_lot_ids': [],
1273 'price_unit': 100.0,
1274 'product_id': product1.id,
1275 'price_subtotal': 100.0,
1276 'price_subtotal_incl': 100.0,
1277 'qty': 1,
1278 'tax_ids': []
1279 })],
1280 'name': 'Order 12345-123-1234',
1281 'partner_id': False,
1282 'session_id': current_session.id,
1283 'sequence_number': 2,
1284 'payment_ids': [(0, 0, {
1285 'amount': 100,
1286 'name': fields.Datetime.now(),
1287 'payment_method_id': self.cash_payment_method.id
1288 })],
1289 'uuid': '12345-123-1234',
1290 'last_order_preparation_change': '{}',
1291 'user_id': self.env.uid
1292 }
1293
1294 self.env['pos.order'].sync_from_ui([pos_order_data])
1295 order = current_session.order_ids[0]
1296 refund_action = order.refund()
1297 refund = self.env['pos.order'].browse(refund_action['res_id'])
1298 self.assertEqual(order.lines[0].refunded_qty, 1)
1299 refund.action_pos_order_cancel()
1300 self.assertEqual(order.lines[0].refunded_qty, 0)
1301
1302 def test_pos_order_refund_ship_delay_totalcost(self):
1303 # test that the total cost is computed for refund with a shipping delay and an avco/fifo product
1304 self.pos_config_usd.open_ui()
1305 current_session = self.pos_config_usd.current_session_id
1306 self.pos_config_usd.write({'ship_later': True})
1307 categ = self.env['product.category'].create({
1308 'name': 'test',
1309 'property_cost_method': 'average',
1310 'property_valuation': 'real_time',
1311 })
1312 product = self.env['product.product'].create({
1313 'name': 'Product A',
1314 'categ_id': categ.id,
1315 'lst_price': 10,
1316 'standard_price': 10,
1317 'is_storable': True,
1318 })
1319 productB = self.env['product.product'].create({
1320 'name': 'Product B',
1321 'categ_id': categ.id,
1322 'lst_price': 10,
1323 'standard_price': 10,
1324 'is_storable': True,
1325 })
1326
1327 order_data = {
1328 'company_id': self.env.company.id,
1329 'session_id': current_session.id,
1330 'partner_id': self.partner.id,
1331 'lines': [[0, 0, {
1332 'name': "OL/0001",
1333 'product_id': product.id,
1334 'price_unit': 10,
1335 'discount': 0,
1336 'qty': 2,
1337 'tax_ids': [[6, False, []]],
1338 'price_subtotal': 20,
1339 'price_subtotal_incl': 20,
1340 'total_cost': 20,
1341 }], [0, 0, {
1342 'name': "OL/0001",
1343 'product_id': productB.id,
1344 'price_unit': 10,
1345 'discount': 0,
1346 'qty': 2,
1347 'tax_ids': [[6, False, []]],
1348 'price_subtotal': 20,
1349 'price_subtotal_incl': 20,
1350 'total_cost': 20,
1351 }]],
1352 'payment_ids': [(0, 0, {
1353 'amount': 20,
1354 'name': fields.Datetime.now(),
1355 'payment_method_id': self.cash_payment_method.id
1356 })],
1357 'amount_paid': 20.0,
1358 'amount_total': 20.0,
1359 'amount_tax': 0.0,
1360 'amount_return': 0.0,
1361 'to_invoice': True,
1362 'last_order_preparation_change': '{}'
1363 }
1364 self.env['pos.order'].sync_from_ui([order_data])
1365 order = current_session.order_ids[0]
1366 refund_values = [{
1367 'name': 'a new test refund order',
1368 'company_id': self.env.company.id,
1369 'user_id': self.env.user.id,
1370 'session_id': current_session.id,
1371 'partner_id': self.partner.id,
1372 'amount_paid': -10,
1373 'amount_tax': 0,
1374 'amount_return': 0,
1375 'amount_total': -10,
1376 'fiscal_position_id': False,
1377 'lines': [[0, 0, {
1378 'product_id': product.id,
1379 'price_unit': 10,
1380 'discount': 0,
1381 'qty': -2,
1382 'tax_ids': [[6, False, []]],
1383 'price_subtotal': -20,
1384 'price_subtotal_incl': -20,
1385 'refunded_orderline_id': order.lines[0].id,
1386 'price_type': 'automatic'
1387 }], [0, 0, {
1388 'product_id': productB.id,
1389 'price_unit': 10,
1390 'discount': 0,
1391 'qty': -2,
1392 'tax_ids': [[6, False, []]],
1393 'price_subtotal': -20,
1394 'price_subtotal_incl': -20,
1395 'refunded_orderline_id': order.lines[1].id,
1396 'price_type': 'automatic'
1397 }]],
1398 'shipping_date': fields.Date.today(),
1399 'sequence_number': 2,
1400 'to_invoice': True,
1401 'date_order': fields.Datetime.to_string(fields.Datetime.now()),
1402 'uuid': '12345-123-1234',
1403 'payment_ids': [[0, 0, {
1404 'amount': -10,
1405 'name': fields.Datetime.now(),
1406 'payment_method_id': self.cash_payment_method.id
1407 }]],
1408 }]
1409 self.env['pos.order'].sync_from_ui(refund_values)
1410 refunded_order_line = self.env['pos.order.line'].search([('product_id', '=', product.id), ('qty', '=', -2)])
1411 self.assertEqual(refunded_order_line.total_cost, -20)
1412
1413 def test_cancel_order_with_past_preset(self):
1414 # Test that cancelling an order with a past preset does not raise an error and does cancel the order.
1415 preset_takeaway = self.env['pos.preset'].create({
1416 'name': 'Takeaway',
1417 })
1418 self.pos_config_usd.write({
1419 'use_presets': True,
1420 'default_preset_id': preset_takeaway.id,
1421 'available_preset_ids': [(6, 0, [preset_takeaway.id])],
1422 })
1423 resource_calendar = self.env['resource.calendar'].create({
1424 'name': 'Takeaway',
1425 'attendance_ids': [(0, 0, {
1426 'name': 'Takeaway',
1427 'dayofweek': str(day),
1428 'hour_from': 0,
1429 'hour_to': 24,
1430 'day_period': 'morning',
1431 }) for day in range(7)],
1432 })
1433 preset_takeaway.write({
1434 'use_timing': True,
1435 'resource_calendar_id': resource_calendar
1436 })
1437 self.pos_config_usd.open_ui()
1438 current_session = self.pos_config_usd.current_session_id
1439
1440 order = self.env['pos.order'].create({
1441 'company_id': self.env.company.id,
1442 'session_id': current_session.id,
1443 'partner_id': False,
1444 'lines': [(0, 0, {
1445 'name': "OL/0001",
1446 'product_id': self.env['product.product'].search([('available_in_pos', '=', True)], limit=1).id,
1447 'price_unit': 49.99,
1448 'discount': 0,
1449 'qty': 1,
1450 'tax_ids': [],
1451 'price_subtotal': 49.99,
1452 'price_subtotal_incl': 49.99,
1453 })],
1454 'pricelist_id': False,
1455 'amount_paid': 49.99,
1456 'amount_total': 49.99,
1457 'amount_tax': 0.0,
1458 'amount_return': 0.0,
1459 'to_invoice': False,
1460 'last_order_preparation_change': '{}',
1461 'preset_id': preset_takeaway.id,
1462 'preset_time': fields.Datetime.to_string(fields.Datetime.now() + timedelta(days=-2)),
1463 })
1464 order.action_pos_order_cancel()
1465 self.assertEqual(order.state, 'cancel')
1466
1467 def test_sum_only_pos_locations(self):
1468 """Test that quantities are summed only from POS source locations"""
1469
1470 self.product = self.env['product.product'].create({
1471 'name': 'Test Product',
1472 'tracking': 'lot',
1473 'is_storable': True,
1474 })
1475
1476 self.warehouse = self.env['stock.warehouse'].create({
1477 'name': 'Test Warehouse',
1478 'code': 'TWH',
1479 })
1480
1481 self.pos_child_location = self.env['stock.location'].create({
1482 'name': 'POS Child Location',
1483 'usage': 'internal',
1484 'location_id': self.warehouse.lot_stock_id.id,
1485 })
1486
1487 self.other_location = self.env['stock.location'].create({
1488 'name': 'Other Location',
1489 'usage': 'internal',
1490 })
1491
1492 picking_type = self.env['stock.picking.type'].create({
1493 'name': 'POS Operations',
1494 'code': 'outgoing',
1495 'sequence_code': 'POS',
1496 'warehouse_id': self.warehouse.id,
1497 'default_location_src_id': self.warehouse.lot_stock_id.id,
1498 })
1499
1500 self.pos_config = self.env['pos.config'].create({
1501 'name': 'Test POS Config',
1502 'picking_type_id': picking_type.id,
1503 })
1504
1505 self.lot = self.env['stock.lot'].create({
1506 'name': 'TEST_LOT',
1507 'product_id': self.product.id,
1508 })
1509
1510 # Create quants in different locations for the same lot
1511 self.env['stock.quant'].create([{
1512 'product_id': self.product.id,
1513 'location_id': self.warehouse.lot_stock_id.id,
1514 'lot_id': self.lot.id,
1515 'quantity': 10.0,
1516 }, {
1517 'product_id': self.product.id,
1518 'location_id': self.pos_child_location.id,
1519 'lot_id': self.lot.id,
1520 'quantity': 5.0,
1521 }, {
1522 'product_id': self.product.id,
1523 'location_id': self.other_location.id,
1524 'lot_id': self.lot.id,
1525 'quantity': 20.0,
1526 }])
1527
1528 result = self.env['pos.order.line'].get_existing_lots(self.env.company.id, self.pos_config.id, self.product.id)
1529
1530 self.assertEqual(len(result), 1, "Should return exactly one lot")
1531 self.assertEqual(result[0]['name'], 'TEST_LOT')
1532 self.assertEqual(result[0]['product_qty'], 15.0, "Should sum only quantities from POS source locations")
1533
1534 def test_order_invoiced_after_session_closed(self):
1535 """Test that an order can be invoiced after its session is closed.
1536 Scenario:
1537 1. Create a POS session and two orders:
1538 - Order A: Not to be invoiced immediately.
1539 - Order B: To be invoiced immediately.
1540 2. Close the POS session.
1541 3. Ensure:
1542 - Both orders have `reversed_move_ids` unset.
1543 4. Assign a partner to Order A and invoice it AFTER the session is closed.
1544 - Confirm that `reversed_move_ids` is set accordingly.
1545 """
1546 order_data = {
1547 'line_data': [
1548 {'product_id': self.ten_dollars_with_10_incl.product_variant_id.id},
1549 {'product_id': self.twenty_dollars_with_10_incl.product_variant_id.id},
1550 ],
1551 'payment_data': [
1552 {'payment_method_id': self.bank_payment_method.id, 'amount': 30},
1553 ],
1554 }
1555
1556 self.pos_config_usd.open_ui()
1557 current_session = self.pos_config_usd.current_session_id
1558
1559 order_no_invoice, _ = self.create_backend_pos_order({**order_data, 'to_invoice': False, 'partner_id': False})
1560 order_invoiced_immediate, _ = self.create_backend_pos_order({**order_data, 'to_invoice': True, 'partner_id': self.partner.id})
1561
1562 total_cash_payment = sum(
1563 current_session.mapped('order_ids.payment_ids')
1564 .filtered(lambda p: p.payment_method_id.type == 'cash')
1565 .mapped('amount')
1566 )
1567 current_session.post_closing_cash_details(total_cash_payment)
1568 current_session.close_session_from_ui()
1569
1570 # Ensure the session is closed
1571 self.assertEqual(current_session.state, 'closed')
1572
1573 # Initial state: no reversal moves for both orders
1574 self.assertFalse(order_no_invoice.reversed_move_ids,
1575 "Order with 'to_invoice' = False should have no reversal moves after session is closed.")
1576 self.assertFalse(order_invoiced_immediate.reversed_move_ids,
1577 "Immediate invoiced order should have no reversal moves after session is closed.")
1578
1579 # Now, set a partner and invoice the order after the session is closed
1580 order_no_invoice.partner_id = self.partner
1581 order_no_invoice.action_pos_order_invoice()
1582
1583 # Confirm that reversal move(s) are now set
1584 reversal_moves = self.env['account.move'].search([('reversed_pos_order_id', '=', order_no_invoice.id)])
1585 self.assertEqual(order_no_invoice.reversed_move_ids, reversal_moves,
1586 "Reversal move should be set for the order invoiced after the session is closed.")
1587
1588 def test_payment_difference_accounting_items(self):
1589 """Verify that the amount of the accounting items are correct when closing a session with a payment difference."""
1590 self.product1 = self.env['product.product'].create({
1591 'name': 'Test Product',
1592 'lst_price': 100,
1593 })
1594 # Make a sale paid by bank
1595 self.pos_config_usd.open_ui()
1596 session_id = self.pos_config_usd.current_session_id
1597 order = self.env['pos.order'].create({
1598 'company_id': self.env.company.id,
1599 'session_id': session_id.id,
1600 'partner_id': False,
1601 'lines': [Command.create({
1602 'name': 'OL/0001',
1603 'product_id': self.product1.id,
1604 'price_unit': 100.00,
1605 'discount': 0,
1606 'qty': 1,
1607 'tax_ids': False,
1608 'price_subtotal': 100.00,
1609 'price_subtotal_incl': 100.00,
1610 })],
1611 'pricelist_id': self.pos_config_usd.pricelist_id.id,
1612 'amount_paid': 100.00,
1613 'amount_total': 100.00,
1614 'amount_tax': 0.0,
1615 'amount_return': 0.0,
1616 'to_invoice': False,
1617 })
1618
1619 # Make payment
1620 payment_context = {"active_ids": order.ids, "active_id": order.id}
1621 order_payment = self.env['pos.make.payment'].with_context(**payment_context).create({
1622 'amount': order.amount_total,
1623 'payment_method_id': self.bank_payment_method.id
1624 })
1625 order_payment.with_context(**payment_context).check()
1626
1627 session_id.action_pos_session_closing_control(bank_payment_method_diffs={self.bank_payment_method.id: -10.00})
1628 self.bank_payment_move = session_id._get_related_account_moves().filtered(lambda move: 'Combine Bank' in move.ref)
1629 self.assertRecordValues(self.bank_payment_move.line_ids.sorted('balance'), [{
1630 'balance': -100.0,
1631 'account_id': self.bank_payment_method.receivable_account_id.id,
1632 },
1633 {
1634 'balance': 10.0,
1635 'account_id': self.bank_payment_method.journal_id.loss_account_id.id,
1636 },
1637 {
1638 'balance': 90.0,
1639 'account_id': self.bank_payment_move.payment_ids.outstanding_account_id.id,
1640 }])
1641
1642 def test_pos_order_partner_bank_id(self):
1643 # Setup a running session, with a paid pos order that is not invoiced
1644 self.pos_config_usd.open_ui()
1645 self.cash_payment_method.journal_id.bank_account_id = self.env['res.partner.bank'].create({
1646 'acc_number': 'FR7612345678901234567890123',
1647 'partner_id': self.company.partner_id.id,
1648 'bank_name': 'Test Bank',
1649 })
1650 current_session = self.pos_config_usd.current_session_id
1651 self.order = self.env['pos.order'].create({
1652 'company_id': self.env.company.id,
1653 'session_id': current_session.id,
1654 'partner_id': self.partner.id,
1655 'lines': [[0, 0, {
1656 'name': "OL/0001",
1657 'product_id': self.product_a.id,
1658 'price_unit': 10,
1659 'discount': 0,
1660 'qty': 1,
1661 'tax_ids': [],
1662 'price_subtotal': 10,
1663 'price_subtotal_incl': 10,
1664 'total_cost': 10,
1665 }]],
1666 'amount_paid': 10.0,
1667 'amount_total': 10.0,
1668 'amount_tax': 0.0,
1669 'amount_return': 0.0,
1670 'to_invoice': True,
1671 'last_order_preparation_change': '{}'
1672 })
1673 context_make_payment = {"active_ids": [self.order.id], "active_id": self.order.id}
1674 self.pos_make_payment_0 = self.env['pos.make.payment'].with_context(context_make_payment).create({
1675 'amount': 10.0,
1676 'payment_method_id': self.cash_payment_method.id,
1677 })
1678 context_payment = {'active_id': self.order.id}
1679 self.pos_make_payment_0.with_context(context_payment).check()
1680 res = self.order.action_pos_order_invoice()
1681 invoice = self.env['account.move'].browse(res['res_id'])
1682 self.assertEqual(invoice.partner_bank_id, self.cash_payment_method.journal_id.bank_account_id, "The invoice should have the partner's bank account set.")
1683
1684 def test_invoice_rounding_overpaid_backend(self):
1685 rouding_method = self.env['account.cash.rounding'].create({
1686 'name': 'Rounding up',
1687 'rounding': 0.05,
1688 'rounding_method': 'UP',
1689 'profit_account_id': self.company_data['default_account_revenue'].id,
1690 'loss_account_id': self.company_data['default_account_expense'].id,
1691 })
1692
1693 self.product_a.write({
1694 'name': 'Product Test',
1695 'list_price': 149.99,
1696 'taxes_id': False,
1697 })
1698
1699 self.pos_config_usd.write({
1700 'rounding_method': rouding_method.id,
1701 'cash_rounding': True,
1702 'only_round_cash_method': True,
1703 })
1704
1705 self.pos_config_usd.open_ui()
1706 current_session = self.pos_config_usd.current_session_id
1707
1708 pos_order_data = {
1709 'amount_paid': 149.99,
1710 'amount_tax': 0,
1711 'amount_return': 0.01,
1712 'amount_total': 149.99,
1713 'date_order': fields.Datetime.to_string(fields.Datetime.now()),
1714 'fiscal_position_id': False,
1715 'lines': [[0, 0, {
1716 'discount': 0,
1717 'pack_lot_ids': [],
1718 'price_unit': 149.99,
1719 'product_id': self.product_a.id,
1720 'price_subtotal': 149.99,
1721 'price_subtotal_incl': 149.99,
1722 'tax_ids': [[6, False, []]],
1723 'qty': 1,
1724 }]],
1725 'name': 'Order 12345-123-1234',
1726 'partner_id': self.partner.id,
1727 'session_id': current_session.id,
1728 'sequence_number': 2,
1729 'payment_ids': [[0, 0, {
1730 'amount': 100,
1731 'name': fields.Datetime.now(),
1732 'payment_method_id': self.cash_payment_method.id
1733 }], [0, 0, {
1734 'amount': 50,
1735 'name': fields.Datetime.now(),
1736 'payment_method_id': self.bank_payment_method.id
1737 }]],
1738 'uuid': '12345-123-1234',
1739 'user_id': self.env.uid,
1740 'to_invoice': False,
1741 }
1742 self.env['pos.order'].sync_from_ui([pos_order_data])
1743
1744 total_cash_payment = sum(current_session.mapped('order_ids.payment_ids').filtered(lambda payment: payment.payment_method_id.type == 'cash').mapped('amount'))
1745 current_session.post_closing_cash_details(total_cash_payment)
1746 current_session.close_session_from_ui()
1747
1748 pos_order = self.env['pos.order'].search([])
1749 pos_order.action_pos_order_invoice()
1750 self.assertEqual(pos_order.state, 'done')
1751
1752 def test_order_refund_lot_valuated(self):
1753 product2 = self.env['product.product'].create({
1754 'name': 'Product B',
1755 'is_storable': True,
1756 'tracking': 'lot',
1757 'available_in_pos': True,
1758 'lot_valuated': True,
1759 'lst_price': 500.0
1760 })
1761 self.env['stock.quant'].with_context(inventory_mode=True).create({
1762 'product_id': product2.id,
1763 'inventory_quantity': 10,
1764 'location_id': self.env.user._get_default_warehouse_id().lot_stock_id.id,
1765 'lot_id': self.env['stock.lot'].create({'name': '1001', 'product_id': product2.id}).id,
1766 }).sudo().action_apply_inventory()
1767
1768 self.pos_config_usd.open_ui()
1769 current_session = self.pos_config_usd.current_session_id
1770 # I create a new PoS order with 2 lines
1771 order = self.env['pos.order'].create({
1772 'company_id': self.env.company.id,
1773 'session_id': current_session.id,
1774 'partner_id': self.partner.id,
1775 'pricelist_id': self.partner.property_product_pricelist.id,
1776 'lines': [(0, 0, {
1777 'name': "OL/0001",
1778 'product_id': product2.id,
1779 'price_unit': 500,
1780 'discount': 0,
1781 'qty': 1.0,
1782 'tax_ids': [],
1783 'price_subtotal': 500,
1784 'price_subtotal_incl': 500,
1785 'pack_lot_ids': [Command.create({'lot_name': '1001'})]
1786 })],
1787 'amount_total': 500.0,
1788 'amount_tax': 0.0,
1789 'amount_paid': 0.0,
1790 'amount_return': 0.0,
1791 'last_order_preparation_change': '{}'
1792 })
1793
1794 payment_context = {"active_ids": order.ids, "active_id": order.id}
1795 order_payment = self.env['pos.make.payment'].with_context(**payment_context).create({
1796 'amount': order.amount_total,
1797 'payment_method_id': self.cash_payment_method.id
1798 })
1799 order_payment.with_context(**payment_context).check()
1800 self.assertAlmostEqual(order.amount_total, order.amount_paid, msg='Order should be fully paid.')
1801
1802 # I create a refund
1803 refund_action = order.refund()
1804 refund = self.env['pos.order'].browse(refund_action['res_id'])
1805
1806 payment_context = {"active_ids": refund.ids, "active_id": refund.id}
1807 refund_payment = self.env['pos.make.payment'].with_context(**payment_context).create({
1808 'amount': refund.amount_total,
1809 'payment_method_id': self.cash_payment_method.id,
1810 })
1811
1812 # I click on the validate button to register the payment.
1813 refund_payment.with_context(**payment_context).check()
1814 current_session.close_session_from_ui()
1815 self.assertEqual(current_session.picking_ids.mapped('state'), ['done', 'done'])
1816
1817 def test_search_paid_order_ids(self):
1818 """ Test if the orders from other configs are excluded in search_paid_order_ids """
1819 other_pos_config = self.env['pos.config'].create({
1820 'name': 'Other POS',
1821 'picking_type_id': self.env['stock.picking.type'].search([('code', '=', 'outgoing')], limit=1).id,
1822 })
1823 self.pos_config_usd.open_ui()
1824 other_pos_config.open_ui()
1825 current_session = self.pos_config_usd.current_session_id
1826 other_session = other_pos_config.current_session_id
1827
1828 paid_order_1, paid_order_2 = self.env['pos.order'].create([{
1829 'company_id': self.env.company.id,
1830 'session_id': session_id,
1831 'partner_id': self.partner.id,
1832 'lines': [
1833 Command.create({
1834 'product_id': self.product_a.id,
1835 'qty': 1,
1836 'price_subtotal': 134.38,
1837 'price_subtotal_incl': 134.38,
1838 }),
1839 ],
1840 'amount_tax': 0.0,
1841 'amount_total': 134.38,
1842 'amount_paid': 134.38,
1843 'amount_return': 0.0,
1844 'state': 'paid',
1845 } for session_id in (current_session.id, other_session.id)])
1846
1847 order_ids = [oi[0] for oi in self.env['pos.order'].search_paid_order_ids(other_pos_config.id, [], 80, 0)['ordersInfo']]
1848 self.assertNotIn(paid_order_1.id, order_ids)
1849 self.assertIn(paid_order_2.id, order_ids)
1850
1851 order_ids = [oi[0] for oi in self.env['pos.order'].search_paid_order_ids(other_pos_config.id, [('partner_id.complete_name', 'ilike', self.partner.complete_name)], 80, 0)['ordersInfo']]
1852 self.assertNotIn(paid_order_1.id, order_ids)
1853 self.assertIn(paid_order_2.id, order_ids)
1854
1855 def test_session_name_gap(self):
1856 self.pos_config_usd.open_ui()
1857 session = self.pos_config_usd.current_session_id
1858 session.set_opening_control(0, None)
1859 current_session_name = session.name
1860 session.action_pos_session_closing_control()
1861
1862 self.pos_config_usd.open_ui()
1863 session = self.pos_config_usd.current_session_id
1864
1865 def _post_cash_details_message_patch(*_args, **_kwargs):
1866 raise UserError('Test Error')
1867
1868 with patch.object(self.env.registry.models['pos.session'], "_post_cash_details_message", _post_cash_details_message_patch):
1869 with self.assertRaises(UserError):
1870 session.set_opening_control(0, None)
1871
1872 session.set_opening_control(0, None)
1873 self.assertEqual(int(session.name.split('/')[1]), int(current_session_name.split('/')[1]) + 1)
1874
1875 def test_open_ui_missing_country(self):
1876 """ Test that a POS can not be opened if it has no country """
1877 self.pos_config_usd.company_id.account_fiscal_country_id = False
1878 with self.assertRaises(ValidationError, msg="The company must have a fiscal country set."):
1879 self.pos_config_usd.open_ui()
1880
1881 def test_branch_company_access_cost_currency_id(self):
1882 branch = self.env['res.company'].create({
1883 'name': 'Branch 1',
1884 'parent_id': self.env.company.id,
1885 'chart_template': self.env.company.chart_template,
1886 'country_id': self.env.company.country_id.id,
1887 })
1888 user = self.env['res.users'].create({
1889 'name': 'Branch user',
1890 'login': 'branch_user',
1891 'email': '[email protected]',
1892 'group_ids': [(6, 0, [self.ref('base.group_user'), self.ref('point_of_sale.group_pos_user')])],
1893 'company_ids': [(4, branch.id)],
1894 'company_id': branch.id,
1895 })
1896 product = self.env['product.product'].create({
1897 'name': 'Product A',
1898 'is_storable': True,
1899 'company_id': self.env.company.id,
1900 })
1901 config = self.env['pos.config'].with_company(branch).create({
1902 'name': 'Main',
1903 'company_id': branch.id,
1904 })
1905 config.payment_method_ids.filtered(lambda pm: pm.is_cash_count).unlink()
1906
1907 config.open_ui()
1908 current_session = config.current_session_id
1909
1910 order = self.env['pos.order'].with_user(user).with_company(branch).create({
1911 'session_id': current_session.id,
1912 'partner_id': self.partner.id,
1913 'company_id': branch.id,
1914 'lines': [(0, 0, {
1915 'name': "OL/0001",
1916 'product_id': product.id,
1917 'price_unit': 6,
1918 'discount': 0,
1919 'qty': 1,
1920 'tax_ids': [[6, False, []]],
1921 'price_subtotal': 6,
1922 'price_subtotal_incl': 6,
1923 })],
1924 'amount_paid': 6.0,
1925 'amount_total': 6.0,
1926 'amount_tax': 0.0,
1927 'amount_return': 0.0,
1928 'to_invoice': False,
1929 'last_order_preparation_change': '{}'
1930 })
1931
1932 order_line = order.lines[0]
1933 self.env.invalidate_all()
1934 order_line.with_user(user).with_company(branch)._compute_total_cost(None)
1935
1936 def test_delete_res_partner_linked_to_pos_order(self):
1937 """ Test that a partner linked to a pos order cannot be deleted. """
1938 partner = self.env['res.partner'].create({
1939 'name': 'Partner test',
1940 })
1941 self.pos_config_usd.open_ui()
1942 current_session = self.pos_config_usd.current_session_id
1943
1944 self.env['pos.order'].create({
1945 'company_id': self.env.company.id,
1946 'session_id': current_session.id,
1947 'partner_id': partner.id,
1948 'lines': [(0, 0, {
1949 'name': "OL/0001",
1950 'product_id': self.product.id,
1951 'price_unit': 450,
1952 'discount': 0,
1953 'qty': 1,
1954 'tax_ids': [[6, False, []]],
1955 'price_subtotal': 450,
1956 'price_subtotal_incl': 450,
1957 })],
1958 'pricelist_id': self.pos_config_usd.pricelist_id.id,
1959 'amount_paid': 450.0,
1960 'amount_total': 450.0,
1961 'amount_tax': 0.0,
1962 'amount_return': 0.0,
1963 'to_invoice': False,
1964 'last_order_preparation_change': '{}'
1965 })
1966
1967 with self.assertRaises(ValidationError, msg='You cannot delete a customer that has point of sales orders. You can archive it instead.'):
1968 partner.unlink()
1969
1970 def test_split_payment_linked_to_accounting_partner(self):
1971 self.bank_payment_method.write({'split_transactions': True})
1972 self.pos_config_usd.open_ui()
1973 current_session = self.pos_config_usd.current_session_id
1974
1975 child_partner = self.env['res.partner'].create({
1976 'name': 'partner1 child',
1977 'parent_id': self.partner.id
1978 })
1979 product_order = {
1980 'amount_paid': 750,
1981 'amount_tax': 0,
1982 'amount_return': 0,
1983 'amount_total': 750,
1984 'date_order': fields.Datetime.to_string(fields.Datetime.now()),
1985 'fiscal_position_id': False,
1986 'lines': [[0, 0, {
1987 'discount': 0,
1988 'pack_lot_ids': [],
1989 'price_unit': 750.0,
1990 'product_id': self.product.id,
1991 'price_subtotal': 750.0,
1992 'price_subtotal_incl': 750.0,
1993 'tax_ids': [[6, False, []]],
1994 'qty': 1,
1995 }]],
1996 'name': 'Order 12345-123-1234',
1997 'partner_id': child_partner.id,
1998 'session_id': current_session.id,
1999 'sequence_number': 2,
2000 'payment_ids': [[0, 0, {
2001 'amount': 750,
2002 'name': fields.Datetime.now(),
2003 'payment_method_id': self.bank_payment_method.id
2004 }]],
2005 'uuid': '12345-123-1234',
2006 'user_id': self.env.uid,
2007 'to_invoice': False}
2008
2009 self.env['pos.order'].sync_from_ui([product_order])
2010 current_session.close_session_from_ui()
2011 order_balance = current_session.move_id.line_ids.filtered(
2012 lambda l: l.account_id.account_type == "asset_receivable"
2013 and l.partner_id == self.partner
2014 ).balance
2015 payment_balance = current_session.bank_payment_ids.move_id.line_ids.filtered(
2016 lambda l: l.account_id.account_type == "asset_receivable"
2017 and l.partner_id == self.partner
2018 ).balance
2019 self.assertEqual(order_balance + payment_balance, 0)
2020
2021 def test_draft_orders_products_loading(self):
2022 """ Test that products are correctly loaded when limited product loading is enabled and there are draft orders. """
2023 self.env['ir.config_parameter'].sudo().set_param('point_of_sale.limited_product_count', 1)
2024 self.pos_config_usd.open_ui()
2025 current_session = self.pos_config_usd.current_session_id
2026 self.env['pos.order'].create([{
2027 'company_id': self.env.company.id,
2028 'session_id': current_session.id,
2029 'partner_id': self.partner.id,
2030 'lines': [
2031 Command.create({
2032 'product_id': product.id,
2033 'qty': 1,
2034 'price_subtotal': 1,
2035 'price_subtotal_incl': 1,
2036 }),
2037 ],
2038 'amount_tax': 0.0,
2039 'amount_total': 1,
2040 'amount_paid': 1,
2041 'amount_return': 0.0,
2042 'state': 'draft',
2043 } for product in (self.product_a, self.product_b)])
2044
2045 data = current_session.with_context(pos_limited_loading=True).load_data([])
2046 loaded_product_ids = [p['id'] for p in data['product.product']]
2047 self.assertIn(self.product_a.id, loaded_product_ids)
2048 self.assertIn(self.product_b.id, loaded_product_ids)
2049
2050 def test_filter_local_data_no_errors(self):
2051 new_company = self.env['res.company'].create({
2052 'name': 'New Company',
2053 'country_id': self.env.company.country_id.id,
2054 'currency_id': self.env.company.currency_id.id,
2055 })
2056 self.pos_config_usd.open_ui()
2057 current_session = self.pos_config_usd.current_session_id
2058 product = self.env['product.product'].create({
2059 'name': 'Product A',
2060 'is_storable': True,
2061 'available_in_pos': True,
2062 'lst_price': 200.0,
2063 'company_id': new_company.id,
2064 })
2065 self.env.clear()
2066 data = current_session.with_company(self.env.company).filter_local_data({'product.product': [product.id]})
2067 self.assertIn(product.id, data['product.product'])
2068
2069 def test_string_sequence_number(self):
2070 self.pos_config_usd.open_ui()
2071 current_session = self.pos_config_usd.current_session_id
2072 current_session.config_id.order_seq_id.prefix = '/AA'
2073 current_session.config_id.order_seq_id.suffix = '1.B'
2074 product_order = {
2075 'amount_paid': 750,
2076 'amount_tax': 0,
2077 'amount_return': 0,
2078 'amount_total': 750,
2079 'date_order': fields.Datetime.to_string(fields.Datetime.now()),
2080 'lines': [[0, 0, {
2081 'price_unit': 750.0,
2082 'product_id': self.product.id,
2083 'price_subtotal': 750.0,
2084 'price_subtotal_incl': 750.0,
2085 'tax_ids': [[6, False, []]],
2086 'qty': 1,
2087 }]],
2088 'name': 'Order 12345-123-1234',
2089 'partner_id': False,
2090 'session_id': current_session.id,
2091 'payment_ids': [[0, 0, {
2092 'amount': 750,
2093 'name': fields.Datetime.now(),
2094 'payment_method_id': self.bank_payment_method.id
2095 }]],
2096 'uuid': '12345-123-1234',
2097 'user_id': self.env.uid,
2098 'to_invoice': False}
2099
2100 self.env['pos.order'].sync_from_ui([product_order])
2101 order = self.env['pos.order'].search([])
2102 self.assertEqual(order.name, f"/AA - {order.pos_reference.split('-')[-1]} - 1.B")