Debian Codegraph @

addons/point_of_sale/tests/common.py

raw
1 import logging
2
3 from random import randint
4 from datetime import datetime
5 from odoo import fields, tools
6 from odoo.fields import Command
7 from odoo.tests import Form
8 from odoo.addons.stock_account.tests.test_anglo_saxon_valuation_reconciliation_common import ValuationReconciliationTestCommon
9
10 _logger = logging.getLogger(__name__)
11
12 def archive_products(env):
13 # Archive all existing product to avoid noise during the tours
14 all_pos_product = env['product.template'].search([('available_in_pos', '=', True)])
15 tip = env.ref('point_of_sale.product_product_tip').product_tmpl_id
16 (all_pos_product - tip)._write({'active': False})
17
18
19 class CommonPosTest(ValuationReconciliationTestCommon):
20 @classmethod
21 def setUpClass(self):
22 super().setUpClass()
23 archive_products(self.env)
24
25 self.env.user.group_ids += self.env.ref('point_of_sale.group_pos_manager')
26 self.env.ref('base.EUR').active = True
27 self.env.ref('base.USD').active = True
28
29 self.create_res_partners(self)
30 self.create_account_cash_rounding(self)
31 self.create_pos_categories(self)
32 self.create_account_taxes(self)
33 self.create_product_templates(self)
34 self.create_payment_methods(self)
35 self.create_pos_configs(self)
36
37 def create_pos_configs(self):
38 sale_journal_eur = self.env['account.journal'].create({
39 'name': 'PoS Sale EUR',
40 'type': 'sale',
41 'code': 'POSE',
42 'company_id': self.company.id,
43 'sequence': 12,
44 'currency_id': self.env.ref('base.EUR').id,
45 })
46 self.pricelist_eur = self.env['product.pricelist'].create({
47 'name': 'Test EUR Pricelist',
48 'currency_id': self.env.ref('base.EUR').id
49 })
50 self.pos_config_eur = self.env['pos.config'].create({
51 'name': 'PoS Config EUR',
52 'journal_id': sale_journal_eur.id,
53 'use_pricelist': True,
54 'available_pricelist_ids': [(6, 0, self.pricelist_eur.ids)],
55 'pricelist_id': self.pricelist_eur.id,
56 'payment_method_ids': [(6, 0, self.bank_payment_method.ids)]
57 })
58 self.pos_config_usd = self.env['pos.config'].create({
59 'name': 'PoS Config USD',
60 'journal_id': self.company_data['default_journal_sale'].id,
61 'invoice_journal_id': self.company_data['default_journal_sale'].id,
62 'payment_method_ids': [
63 (4, self.credit_payment_method.id),
64 (4, self.bank_payment_method.id),
65 (4, self.cash_payment_method.id),
66 ]
67 })
68
69 def create_res_partners(self):
70 self.partner_mobt = self.env['res.partner'].create({
71 'name': 'MOBT',
72 })
73 self.partner_adgu = self.env['res.partner'].create({
74 'name': 'ADGU',
75 })
76 self.partner_lowe = self.env['res.partner'].create({
77 'name': 'LOWE',
78 })
79 self.partner_jcb = self.env['res.partner'].create({
80 'name': 'JCB',
81 })
82 self.partner_moda = self.env['res.partner'].create({
83 'name': 'MODA',
84 })
85 self.partner_stva = self.env['res.partner'].create({
86 'name': 'STVA',
87 })
88 self.partner_manv = self.env['res.partner'].create({
89 'name': 'MANV',
90 })
91 self.partner_vlst = self.env['res.partner'].create({
92 'name': 'VLST',
93 })
94
95 def create_account_cash_rounding(self):
96 self.account_cash_rounding_down = self.env['account.cash.rounding'].create({
97 'name': 'Rounding down',
98 'rounding': 0.05,
99 'rounding_method': 'DOWN',
100 'profit_account_id': self.company_data['default_account_revenue'].id,
101 'loss_account_id': self.company_data['default_account_expense'].id,
102 })
103 self.account_cash_rounding_up = self.env['account.cash.rounding'].create({
104 'name': 'Rounding up',
105 'rounding': 0.05,
106 'rounding_method': 'UP',
107 'profit_account_id': self.company_data['default_account_revenue'].id,
108 'loss_account_id': self.company_data['default_account_expense'].id,
109 })
110 self.account_cash_rounding_half = self.env['account.cash.rounding'].create({
111 'name': 'Rounding half',
112 'rounding': 0.05,
113 'profit_account_id': self.company_data['default_account_revenue'].id,
114 'loss_account_id': self.company_data['default_account_expense'].id,
115 })
116
117 def create_payment_methods(self):
118 self.cash_payment_method = self.env['pos.payment.method'].create({
119 'name': 'Cash',
120 'receivable_account_id': self.company_data['default_account_receivable'].id,
121 'journal_id': self.company_data['default_journal_cash'].id,
122 })
123 self.bank_payment_method = self.env['pos.payment.method'].create({
124 'name': 'Bank',
125 'journal_id': self.company_data['default_journal_bank'].id,
126 'receivable_account_id': self.company_data['default_account_receivable'].id,
127 })
128 self.credit_payment_method = self.env['pos.payment.method'].create({
129 'name': 'Credit',
130 'receivable_account_id': self.company_data['default_account_receivable'].id,
131 'split_transactions': True,
132 })
133
134 def create_pos_categories(self):
135 self.cat_no_tax = self.env['pos.category'].create({
136 'name': 'No tax',
137 'sequence': 0,
138 })
139 self.cat_tax_five_incl = self.env['pos.category'].create({
140 'name': 'Tax five incl',
141 'sequence': 1,
142 })
143 self.cat_tax_ten_incl = self.env['pos.category'].create({
144 'name': 'Tax ten incl',
145 'sequence': 2,
146 })
147 self.cat_tax_fiften_incl = self.env['pos.category'].create({
148 'name': 'Tax fifteen incl',
149 'sequence': 3,
150 })
151 self.cat_tax_five_excl = self.env['pos.category'].create({
152 'name': 'Tax five excl',
153 'sequence': 4,
154 })
155 self.cat_tax_ten_excl = self.env['pos.category'].create({
156 'name': 'Tax ten excl',
157 'sequence': 5,
158 })
159 self.cat_tax_fiften_excl = self.env['pos.category'].create({
160 'name': 'Tax fifteen excl',
161 'sequence': 6,
162 })
163
164 def create_account_taxes(self):
165 self.tax_five_incl = self.env['account.tax'].create({
166 'name': 'Tax five incl',
167 'amount': 5,
168 'price_include_override': 'tax_included',
169 })
170 self.tax_ten_incl = self.env['account.tax'].create({
171 'name': 'Tax ten incl',
172 'amount': 10,
173 'price_include_override': 'tax_included',
174 })
175 self.tax_fiften_incl = self.env['account.tax'].create({
176 'name': 'Tax fifteen incl',
177 'amount': 15,
178 'price_include_override': 'tax_included',
179 })
180 self.tax_five_excl = self.env['account.tax'].create({
181 'name': 'Tax five excl',
182 'amount': 5,
183 })
184 self.tax_ten_excl = self.env['account.tax'].create({
185 'name': 'Tax ten excl',
186 'amount': 10,
187 })
188 self.tax_fiften_excl = self.env['account.tax'].create({
189 'name': 'Tax fifteen excl',
190 'amount': 15,
191 })
192
193 def create_product_templates(self):
194 self.ten_dollars_no_tax = self.env['product.template'].create({
195 'available_in_pos': True,
196 'name': 'Ten dollars no tax',
197 'list_price': 10.0,
198 'pos_categ_ids': [(6, 0, [self.cat_no_tax.id])],
199 'taxes_id': [(5, 0)],
200 })
201 self.twenty_dollars_no_tax = self.env['product.template'].create({
202 'available_in_pos': True,
203 'name': 'Twenty dollars no tax',
204 'list_price': 20.0,
205 'pos_categ_ids': [(6, 0, [self.cat_no_tax.id])],
206 'taxes_id': [(5, 0)],
207 })
208 self.ten_dollars_with_5_incl = self.env['product.template'].create({
209 'available_in_pos': True,
210 'name': 'Ten dollars with 5 included',
211 'list_price': 10.0,
212 'taxes_id': [(6, 0, [self.tax_five_incl.id])],
213 'pos_categ_ids': [(6, 0, [self.cat_tax_five_incl.id])],
214 })
215 self.twenty_dollars_with_5_incl = self.env['product.template'].create({
216 'available_in_pos': True,
217 'name': 'Twenty dollars with 5 included',
218 'list_price': 20.0,
219 'taxes_id': [(6, 0, [self.tax_five_incl.id])],
220 'pos_categ_ids': [(6, 0, [self.cat_tax_five_incl.id])],
221 })
222 self.ten_dollars_with_10_incl = self.env['product.template'].create({
223 'available_in_pos': True,
224 'name': 'Ten dollars with 10 included',
225 'list_price': 10.0,
226 'taxes_id': [(6, 0, [self.tax_ten_incl.id])],
227 'pos_categ_ids': [(6, 0, [self.cat_tax_ten_incl.id])],
228 })
229 self.twenty_dollars_with_10_incl = self.env['product.template'].create({
230 'available_in_pos': True,
231 'name': 'Twenty dollars with 10 included',
232 'list_price': 20.0,
233 'taxes_id': [(6, 0, [self.tax_ten_incl.id])],
234 'pos_categ_ids': [(6, 0, [self.cat_tax_ten_incl.id])],
235 })
236 self.ten_dollars_with_15_incl = self.env['product.template'].create({
237 'available_in_pos': True,
238 'name': 'Ten dollars with 15 included',
239 'list_price': 10.0,
240 'taxes_id': [(6, 0, [self.tax_fiften_incl.id])],
241 'pos_categ_ids': [(6, 0, [self.cat_tax_fiften_incl.id])],
242 })
243 self.twenty_dollars_with_15_incl = self.env['product.template'].create({
244 'available_in_pos': True,
245 'name': 'Twenty dollars with 15 included',
246 'list_price': 20.0,
247 'taxes_id': [(6, 0, [self.tax_fiften_incl.id])],
248 'pos_categ_ids': [(6, 0, [self.cat_tax_fiften_incl.id])],
249 })
250 self.ten_dollars_with_5_excl = self.env['product.template'].create({
251 'available_in_pos': True,
252 'name': 'Ten dollars with 5 excluded',
253 'list_price': 10.0,
254 'taxes_id': [(6, 0, [self.tax_five_excl.id])],
255 'pos_categ_ids': [(6, 0, [self.cat_tax_five_excl.id])],
256 })
257 self.twenty_dollars_with_5_excl = self.env['product.template'].create({
258 'available_in_pos': True,
259 'name': 'Twenty dollars with 5 excluded',
260 'list_price': 20.0,
261 'taxes_id': [(6, 0, [self.tax_five_excl.id])],
262 'pos_categ_ids': [(6, 0, [self.cat_tax_five_excl.id])],
263 })
264 self.ten_dollars_with_10_excl = self.env['product.template'].create({
265 'available_in_pos': True,
266 'name': 'Ten dollars with 10 excluded',
267 'list_price': 10.0,
268 'taxes_id': [(6, 0, [self.tax_ten_excl.id])],
269 'pos_categ_ids': [(6, 0, [self.cat_tax_ten_excl.id])],
270 })
271 self.twenty_dollars_with_10_excl = self.env['product.template'].create({
272 'available_in_pos': True,
273 'name': 'Twenty dollars with 10 excluded',
274 'list_price': 20.0,
275 'taxes_id': [(6, 0, [self.tax_ten_excl.id])],
276 'pos_categ_ids': [(6, 0, [self.cat_tax_ten_excl.id])],
277 })
278 self.ten_dollars_with_15_excl = self.env['product.template'].create({
279 'available_in_pos': True,
280 'name': 'Ten dollars with 15 excluded',
281 'list_price': 10.0,
282 'taxes_id': [(6, 0, [self.tax_fiften_excl.id])],
283 'pos_categ_ids': [(6, 0, [self.cat_tax_fiften_excl.id])],
284 })
285 self.twenty_dollars_with_15_excl = self.env['product.template'].create({
286 'available_in_pos': True,
287 'name': 'Twenty dollars with 15 excluded',
288 'list_price': 20.0,
289 'taxes_id': [(6, 0, [self.tax_fiften_excl.id])],
290 'pos_categ_ids': [(6, 0, [self.cat_tax_fiften_excl.id])],
291 })
292
293 def create_backend_pos_order(self, data):
294 pos_config = data.get('pos_config', self.pos_config_usd)
295 order_data = data.get('order_data', {})
296 line_product_ids = [line_data['product_id'] for line_data in data.get('line_data', [])]
297 product_by_id = {p.id: p for p in self.env['product.product'].browse(line_product_ids)}
298 refund = False
299
300 if not pos_config.current_session_id:
301 pos_config.open_ui()
302
303 order = self.env['pos.order'].create({
304 'amount_total': 0,
305 'amount_paid': 0,
306 'amount_tax': 0,
307 'amount_return': 0,
308 'date_order': fields.Datetime.to_string(fields.Datetime.now()),
309 'company_id': self.env.company.id,
310 'session_id': pos_config.current_session_id.id,
311 'lines': [
312 Command.create({
313 'price_unit': product_by_id[line_data['product_id']].lst_price,
314 'price_subtotal': product_by_id[line_data['product_id']].lst_price,
315 'tax_ids': [(6, 0, product_by_id[line_data['product_id']].taxes_id.ids)],
316 'price_subtotal_incl': 0,
317 **line_data,
318 }) for line_data in data.get('line_data', [])
319 ],
320 **order_data,
321 })
322
323 # Re-trigger prices computation
324 order.lines._onchange_amount_line_all()
325 order._compute_prices()
326
327 if data.get('payment_data'):
328 payment_context = {"active_ids": order.ids, "active_id": order.id}
329 for payment in data['payment_data']:
330 make_payment = {'payment_method_id': payment['payment_method_id']}
331 if payment.get('amount'):
332 make_payment['amount'] = payment['amount']
333 order_payment = self.env['pos.make.payment'].with_context(**payment_context).create(make_payment)
334 order_payment.with_context(**payment_context).check()
335
336 if data.get('refund_data'):
337 refund_action = order.refund()
338 refund = self.env['pos.order'].browse(refund_action['res_id'])
339 payment_context = {"active_ids": refund.ids, "active_id": refund.id}
340
341 if data.get('order_data') and data['order_data'].get('to_invoice', False):
342 refund.to_invoice = True
343
344 for refund_data in data['refund_data']:
345 make_refund = {'payment_method_id': refund_data['payment_method_id']}
346 if refund_data.get('amount'):
347 make_refund['amount'] = refund_data['amount']
348 refund_payment = self.env['pos.make.payment'].with_context(**payment_context).create(make_refund)
349 refund_payment.with_context(**payment_context).check()
350
351 return order, refund
352
353 def compute_tax(self, product, price, qty=1, taxes=None, pos_config=None):
354 config = pos_config or self.pos_config_usd
355 if not taxes:
356 taxes = product.taxes_id.filtered(lambda t: t.company_id.id == self.env.company.id)
357 currency = config.currency_id
358 res = taxes.compute_all(price, currency, qty, product=product)
359 untax = res['total_excluded']
360 return untax, sum(tax.get('amount', 0.0) for tax in res['taxes'])
361
362
363 class TestPoSCommon(ValuationReconciliationTestCommon):
364 """ Set common values for different special test cases.
365
366 The idea is to set up common values here for the tests
367 and implement different special scenarios by inheriting
368 this class.
369 """
370
371 @classmethod
372 def setUpClass(cls):
373 super().setUpClass()
374 cls.env.user.group_ids |= cls.env.ref('point_of_sale.group_pos_manager')
375
376 cls.company_data['company'].write({
377 'point_of_sale_update_stock_quantities': 'real',
378 'country_id': cls.env['res.country'].create({
379 'name': 'PoS Land',
380 'code': 'WOW',
381 }),
382 })
383
384 # Set basic defaults
385 cls.account_tax_return_journal = cls.company_data['default_tax_return_journal']
386 cls.sales_account = cls.company_data['default_account_revenue']
387 cls.invoice_journal = cls.company_data['default_journal_sale']
388 cls.receivable_account = cls.company_data['default_account_receivable']
389 cls.tax_received_account = cls.company_data['default_account_tax_sale']
390 cls.company.account_default_pos_receivable_account_id = cls.env['account.account'].create({
391 'code': 'X1012.POS',
392 'name': 'Debtors - (POS)',
393 'reconcile': True,
394 'account_type': 'asset_receivable',
395 })
396 cls.pos_receivable_account = cls.company.account_default_pos_receivable_account_id
397 cls.pos_receivable_cash = cls.copy_account(cls.company.account_default_pos_receivable_account_id, {'name': 'POS Receivable Cash'})
398 cls.pos_receivable_bank = cls.copy_account(cls.company.account_default_pos_receivable_account_id, {'name': 'POS Receivable Bank'})
399 cls.outstanding_bank = cls.copy_account(cls.inbound_payment_method_line.payment_account_id, {'name': 'Outstanding Bank'})
400 cls.c1_receivable = cls.copy_account(cls.receivable_account, {'name': 'Customer 1 Receivable'})
401 cls.other_receivable_account = cls.env['account.account'].create({
402 'name': 'Other Receivable',
403 'code': 'RCV00',
404 'account_type': 'asset_receivable',
405 'internal_group': 'asset',
406 'reconcile': True,
407 })
408
409 # company_currency can be different from `base.USD` depending on the localization installed
410 cls.company_currency = cls.company.currency_id
411 # other_currency is a currency different from the company_currency
412 # sometimes company_currency is different from USD, so handle appropriately.
413 cls.other_currency = cls.setup_other_currency("EUR", rounding=0.001)
414
415 cls.currency_pricelist = cls.env['product.pricelist'].create({
416 'name': 'Public Pricelist',
417 'currency_id': cls.company_currency.id,
418 })
419 # Set Point of Sale configurations
420 # basic_config
421 # - derived from 'point_of_sale.pos_config_main' with added invoice_journal_id and credit payment method.
422 # other_currency_config
423 # - pos.config set to have currency different from company currency.
424 cls.basic_config = cls._create_basic_config()
425 cls.other_currency_config = cls._create_other_currency_config()
426
427 # Set product categories
428 # categ_basic
429 # - just the plain 'product.product_category_services'
430 # categ_anglo
431 # - product category with fifo and real_time valuations
432 # - used for checking anglo saxon accounting behavior
433 cls.categ_basic = cls.env.ref('product.product_category_services')
434 cls.env.company.anglo_saxon_accounting = True
435 cls.categ_anglo = cls._create_categ_anglo()
436
437 # other basics
438 cls.sale_account = cls.company.income_account_id
439 cls.other_sale_account = cls.env['account.account'].search([
440 ('company_ids', '=', cls.company.id),
441 ('account_type', '=', 'income'),
442 ('id', '!=', cls.sale_account.id)
443 ], limit=1)
444
445 # Set customers
446 cls.customer = cls.env['res.partner'].create({'name': 'Customer 1', 'property_account_receivable_id': cls.c1_receivable.id})
447 cls.other_customer = cls.env['res.partner'].create({'name': 'Other Customer', 'property_account_receivable_id': cls.other_receivable_account.id})
448
449 # Set taxes
450 # cls.taxes => dict
451 # keys: 'tax7', 'tax10'(price_include=True), 'tax_group_7_10'
452 cls.taxes = cls._create_taxes()
453
454 cls.stock_location_components = cls.env["stock.location"].create({
455 'name': 'Shelf 1',
456 'location_id': cls.company_data['default_warehouse'].lot_stock_id.id,
457 })
458
459
460 #####################
461 ## private methods ##
462 #####################
463
464 @classmethod
465 def _create_basic_config(cls):
466 config = cls.env['pos.config'].create({
467 'name': 'PoS Shop Test',
468 'invoice_journal_id': cls.invoice_journal.id,
469 'available_pricelist_ids': cls.currency_pricelist.ids,
470 'pricelist_id': cls.currency_pricelist.id,
471 })
472 cls.company_data['default_journal_cash'].pos_payment_method_ids.unlink()
473 cls.cash_pm1 = config.payment_method_ids.filtered(lambda c: c.journal_id.type == 'cash')
474 if cls.cash_pm1:
475 cls.cash_pm1.write({'receivable_account_id': cls.pos_receivable_cash.id})
476 else:
477 cls.cash_pm1 = cls.env['pos.payment.method'].create({
478 'name': 'Cash',
479 'journal_id': cls.company_data['default_journal_cash'].id,
480 'receivable_account_id': cls.pos_receivable_cash.id,
481 'company_id': cls.env.company.id,
482 })
483 cls.bank_pm1 = cls.env['pos.payment.method'].create({
484 'name': 'Bank',
485 'journal_id': cls.company_data['default_journal_bank'].id,
486 'receivable_account_id': cls.pos_receivable_bank.id,
487 'outstanding_account_id': cls.outstanding_bank.id,
488 'company_id': cls.env.company.id,
489 })
490 cls.cash_split_pm1 = cls.cash_pm1.copy(default={
491 'name': 'Split (Cash) PM',
492 'split_transactions': True,
493 'journal_id': cls.env['account.journal'].create({
494 'name': "Cash",
495 'code': "CSH %s" % config.id,
496 'type': 'cash',
497 }).id
498 })
499 cls.bank_split_pm1 = cls.bank_pm1.copy(default={
500 'name': 'Split (Bank) PM',
501 'split_transactions': True,
502 })
503 cls.pay_later_pm = cls.env['pos.payment.method'].create({'name': 'Pay Later', 'split_transactions': True})
504 config.write({'payment_method_ids': [(4, cls.cash_split_pm1.id), (4, cls.bank_split_pm1.id), (4, cls.cash_pm1.id), (4, cls.bank_pm1.id), (4, cls.pay_later_pm.id)]})
505 return config
506
507 @classmethod
508 def _create_other_currency_config(cls):
509 (cls.other_currency.rate_ids | cls.company_currency.rate_ids).unlink()
510 cls.env['res.currency.rate'].create({
511 'rate': 0.5,
512 'currency_id': cls.other_currency.id,
513 'name': datetime.today().date(),
514 })
515 other_cash_journal = cls.env['account.journal'].create({
516 'name': 'Cash Other',
517 'type': 'cash',
518 'company_id': cls.company.id,
519 'code': 'CSHO',
520 'sequence': 10,
521 'currency_id': cls.other_currency.id
522 })
523 other_invoice_journal = cls.env['account.journal'].create({
524 'name': 'Customer Invoice Other',
525 'type': 'sale',
526 'company_id': cls.company.id,
527 'code': 'INVO',
528 'sequence': 11,
529 'currency_id': cls.other_currency.id
530 })
531 other_sales_journal = cls.env['account.journal'].create({
532 'name':'PoS Sale Other',
533 'type': 'sale',
534 'code': 'POSO',
535 'company_id': cls.company.id,
536 'sequence': 12,
537 'currency_id': cls.other_currency.id
538 })
539 other_bank_journal = cls.env['account.journal'].create({
540 'name': 'Bank Other',
541 'type': 'bank',
542 'company_id': cls.company.id,
543 'code': 'BNKO',
544 'sequence': 13,
545 'currency_id': cls.other_currency.id
546 })
547 other_pricelist = cls.env['product.pricelist'].create({
548 'name': 'Public Pricelist Other',
549 'currency_id': cls.other_currency.id,
550 })
551 cls.cash_pm2 = cls.env['pos.payment.method'].create({
552 'name': 'Cash Other',
553 'journal_id': other_cash_journal.id,
554 'receivable_account_id': cls.pos_receivable_cash.id,
555 })
556 cls.bank_pm2 = cls.env['pos.payment.method'].create({
557 'name': 'Bank Other',
558 'journal_id': other_bank_journal.id,
559 'receivable_account_id': cls.pos_receivable_bank.id,
560 'outstanding_account_id': cls.outstanding_bank.id,
561 })
562
563 config = cls.env['pos.config'].create({
564 'name': 'Shop Other',
565 'invoice_journal_id': other_invoice_journal.id,
566 'journal_id': other_sales_journal.id,
567 'use_pricelist': True,
568 'available_pricelist_ids': other_pricelist.ids,
569 'pricelist_id': other_pricelist.id,
570 'payment_method_ids': [cls.cash_pm2.id, cls.bank_pm2.id],
571 })
572 return config
573
574 @classmethod
575 def _create_categ_anglo(cls):
576 return cls.env['product.category'].create({
577 'name': 'Anglo',
578 'parent_id': False,
579 'property_cost_method': 'fifo',
580 'property_valuation': 'real_time',
581 'property_stock_valuation_account_id': cls.company_data['default_account_stock_valuation'].copy().id
582 })
583
584 @classmethod
585 def _create_taxes(cls):
586 """ Create taxes
587
588 tax7: 7%, excluded in product price
589 tax10: 10%, included in product price
590 tax21: 21%, included in product price
591 """
592 def create_tag(name):
593 return cls.env['account.account.tag'].create({
594 'name': name,
595 'applicability': 'taxes',
596 'country_id': cls.env.company.account_fiscal_country_id.id
597 })
598
599 cls.tax_tag_invoice_base = create_tag('Invoice Base tag')
600 cls.tax_tag_invoice_tax = create_tag('Invoice Tax tag')
601 cls.tax_tag_refund_base = create_tag('Refund Base tag')
602 cls.tax_tag_refund_tax = create_tag('Refund Tax tag')
603
604 def create_tax(percentage, price_include_override='tax_excluded', include_base_amount=False):
605 return cls.env['account.tax'].create({
606 'name': f'Tax {percentage}%',
607 'amount': percentage,
608 'price_include_override': price_include_override,
609 'amount_type': 'percent',
610 'include_base_amount': include_base_amount,
611 'invoice_repartition_line_ids': [
612 (0, 0, {
613 'repartition_type': 'base',
614 'tag_ids': [(6, 0, cls.tax_tag_invoice_base.ids)],
615 }),
616 (0, 0, {
617 'repartition_type': 'tax',
618 'account_id': cls.tax_received_account.id,
619 'tag_ids': [(6, 0, cls.tax_tag_invoice_tax.ids)],
620 }),
621 ],
622 'refund_repartition_line_ids': [
623 (0, 0, {
624 'repartition_type': 'base',
625 'tag_ids': [(6, 0, cls.tax_tag_refund_base.ids)],
626 }),
627 (0, 0, {
628 'repartition_type': 'tax',
629 'account_id': cls.tax_received_account.id,
630 'tag_ids': [(6, 0, cls.tax_tag_refund_tax.ids)],
631 }),
632 ],
633 })
634
635 def create_tax_fixed(amount, price_include_override='tax_excluded', include_base_amount=False):
636 return cls.env['account.tax'].create({
637 'name': f'Tax fixed amount {amount}',
638 'amount': amount,
639 'price_include_override': price_include_override,
640 'include_base_amount': include_base_amount,
641 'amount_type': 'fixed',
642 'invoice_repartition_line_ids': [
643 (0, 0, {
644 'repartition_type': 'base',
645 'tag_ids': [(6, 0, cls.tax_tag_invoice_base.ids)],
646 }),
647 (0, 0, {
648 'repartition_type': 'tax',
649 'account_id': cls.tax_received_account.id,
650 'tag_ids': [(6, 0, cls.tax_tag_invoice_tax.ids)],
651 }),
652 ],
653 'refund_repartition_line_ids': [
654 (0, 0, {
655 'repartition_type': 'base',
656 'tag_ids': [(6, 0, cls.tax_tag_refund_base.ids)],
657 }),
658 (0, 0, {
659 'repartition_type': 'tax',
660 'account_id': cls.tax_received_account.id,
661 'tag_ids': [(6, 0, cls.tax_tag_refund_tax.ids)],
662 }),
663 ],
664 })
665
666 tax_fixed006 = create_tax_fixed(0.06, price_include_override='tax_included', include_base_amount=True)
667 tax_fixed012 = create_tax_fixed(0.12, price_include_override='tax_included', include_base_amount=True)
668 tax7 = create_tax(7, price_include_override='tax_excluded')
669 tax8 = create_tax(8, include_base_amount=True)
670 tax9 = create_tax(9)
671 tax10 = create_tax(10, price_include_override='tax_included')
672 tax21 = create_tax(21, price_include_override='tax_included')
673
674
675 tax_group_7_10 = tax7.copy()
676 with Form(tax_group_7_10) as tax:
677 tax.name = 'Tax 7+10%'
678 tax.amount_type = 'group'
679 tax.children_tax_ids.add(tax7)
680 tax.children_tax_ids.add(tax10)
681
682 return {
683 'tax7': tax7,
684 'tax8': tax8,
685 'tax9': tax9,
686 'tax10': tax10,
687 'tax21': tax21,
688 'tax_fixed006': tax_fixed006,
689 'tax_fixed012': tax_fixed012,
690 'tax_group_7_10': tax_group_7_10
691 }
692
693 ####################
694 ## public methods ##
695 ####################
696
697 def create_random_uid(self):
698 return ('%05d-%03d-%04d' % (randint(1, 99999), randint(1, 999), randint(1, 9999)))
699
700 def create_ui_order_data(self, pos_order_lines_ui_args, pos_order_ui_args={}, customer=False, is_invoiced=False, payments=None, uuid=None):
701 """ Mocks the order_data generated by the pos ui.
702
703 This is useful in making orders in an open pos session without making tours.
704 Its functionality is tested in test_pos_create_ui_order_data.py.
705
706 Before use, make sure that self is set with:
707 1. pricelist -> the pricelist of the current session
708 2. currency -> currency of the current session
709 3. pos_session -> the current session, equivalent to config.current_session_id
710 4. cash_pm -> first cash payment method in the current session
711 5. config -> the active pos.config
712
713 The above values should be set when `self.open_new_session` is called.
714
715 :param list(tuple) pos_order_lines_ui_args: pairs of `ordered product` and `quantity`
716 or triplet of `ordered product`, `quantity` and discount
717 :param list(tuple) payments: pair of `payment_method` and `amount`
718 """
719 default_fiscal_position = self.config.default_fiscal_position_id
720 fiscal_position = customer.property_account_position_id if customer else default_fiscal_position
721
722 def normalize_order_line_param(param):
723 if isinstance(param, dict):
724 return param
725
726 assert len(param) >= 2
727 return {
728 'product': param[0],
729 'quantity': param[1],
730 'discount': 0.0 if len(param) == 2 else param[2],
731 }
732
733 def create_order_line(product, quantity, **kwargs):
734 price_unit = self.pricelist._get_product_price(product, quantity)
735 tax_ids = fiscal_position.map_tax(product.taxes_id.filtered_domain(self.env['account.tax']._check_company_domain(self.env.company)))
736 discount = kwargs.get('discount', 0.0)
737 price_unit_after_discount = price_unit * (1 - discount / 100.0)
738 tax_values = (
739 tax_ids.compute_all(price_unit_after_discount, self.currency, quantity)
740 if tax_ids
741 else {
742 'total_excluded': price_unit * quantity,
743 'total_included': price_unit * quantity,
744 }
745 )
746 return (0, 0, {
747 'id': randint(1, 1000000),
748 'pack_lot_ids': [],
749 'price_unit': price_unit,
750 'product_id': product.id,
751 'price_subtotal': tax_values['total_excluded'],
752 'price_subtotal_incl': tax_values['total_included'],
753 'qty': quantity,
754 'tax_ids': [(6, 0, tax_ids.ids)],
755 **kwargs
756 })
757
758 def create_payment(payment_method, amount):
759 return (0, 0, {
760 'amount': amount,
761 'name': fields.Datetime.now(),
762 'payment_method_id': payment_method.id,
763 })
764
765 uuid = uuid or self.create_random_uid()
766
767 # 1. generate the order lines
768 order_lines = [
769 create_order_line(**normalize_order_line_param(param))
770 for param in pos_order_lines_ui_args
771 ]
772
773 # 2. generate the payments
774 total_amount_incl = sum(line[2]['price_subtotal_incl'] for line in order_lines)
775 if payments is None:
776 default_cash_pm = self.config.payment_method_ids.filtered(lambda pm: pm.is_cash_count and not pm.split_transactions)[:1]
777 if not default_cash_pm:
778 raise Exception('There should be a cash payment method set in the pos.config.')
779 payments = [create_payment(default_cash_pm, total_amount_incl)]
780 else:
781 payments = [
782 create_payment(pm, amount)
783 for pm, amount in payments
784 ]
785
786 # 3. complete the fields of the order_data
787 total_amount_base = sum(line[2]['price_subtotal'] for line in order_lines)
788 return {
789 'amount_paid': sum(payment[2]['amount'] for payment in payments),
790 'amount_return': 0,
791 'amount_tax': total_amount_incl - total_amount_base,
792 'amount_total': total_amount_incl,
793 'date_order': fields.Datetime.to_string(fields.Datetime.now()),
794 'fiscal_position_id': fiscal_position.id,
795 'pricelist_id': self.config.pricelist_id.id,
796 'name': 'Order %s' % uuid,
797 'last_order_preparation_change': '{}',
798 'lines': order_lines,
799 'partner_id': customer and customer.id,
800 'session_id': self.pos_session.id,
801 'payment_ids': payments,
802 'uuid': uuid,
803 'user_id': self.env.uid,
804 'to_invoice': is_invoiced,
805 **pos_order_ui_args,
806 }
807
808 @classmethod
809 def create_product(cls, name, category, lst_price, standard_price=None, tax_ids=None, sale_account=None):
810 product = cls.env['product.product'].create({
811 'is_storable': True,
812 'available_in_pos': True,
813 'taxes_id': [(5, 0, 0)] if not tax_ids else [(6, 0, tax_ids)],
814 'name': name,
815 'categ_id': category.id,
816 'lst_price': lst_price,
817 'standard_price': standard_price if standard_price else 0.0,
818 'company_id': cls.env.company.id,
819 })
820 if sale_account:
821 product.property_account_income_id = sale_account
822 return product
823
824 @classmethod
825 def adjust_inventory(cls, products, quantities):
826 """ Adjust inventory of the given products
827 """
828 for product, qty in zip(products, quantities):
829 cls.env['stock.quant'].with_context(inventory_mode=True).create({
830 'product_id': product.id,
831 'inventory_quantity': qty,
832 'location_id': cls.stock_location_components.id,
833 }).action_apply_inventory()
834
835 def open_new_session(self, opening_cash=0):
836 """ Used to open new pos session in each configuration.
837
838 - The idea is to properly set values that are constant
839 and commonly used in an open pos session.
840 - Calling this method is also a prerequisite for using
841 `self.create_ui_order_data` function.
842
843 Fields:
844 * config : the pos.config currently being used.
845 Its value is set at `self.setUp` of the inheriting
846 test class.
847 * pos_session : the current_session_id of config
848 * currency : currency of the current pos.session
849 * pricelist : the default pricelist of the session
850 """
851 self.config.open_ui()
852 self.pos_session = self.config.current_session_id
853 self.currency = self.pos_session.currency_id
854 self.pricelist = self.pos_session.config_id.pricelist_id
855 self.pos_session.set_opening_control(opening_cash, None)
856 return self.pos_session
857
858 def _run_test(self, args):
859 pos_session = self._start_pos_session(args['payment_methods'], args.get('opening_cash', 0))
860 _logger.info('DONE: Start session.')
861 orders_map = self._create_orders(args['orders'])
862 _logger.info('DONE: Orders created.')
863 before_closing_cb = args.get('before_closing_cb')
864 if before_closing_cb:
865 before_closing_cb()
866 _logger.info('DONE: Call of before_closing_cb.')
867 self._check_invoice_journal_entries(pos_session, orders_map, expected_values=args['journal_entries_before_closing'])
868 _logger.info('DONE: Checks for journal entries before closing the session.')
869 cash_payment_method = pos_session.payment_method_ids.filtered('is_cash_count')[:1]
870 total_cash_payment = sum(pos_session.mapped('order_ids.payment_ids').filtered(lambda payment: payment.payment_method_id.id == cash_payment_method.id).mapped('amount'))
871 pos_session.post_closing_cash_details(total_cash_payment)
872 pos_session.close_session_from_ui()
873 after_closing_cb = args.get('after_closing_cb')
874 if after_closing_cb:
875 after_closing_cb()
876 _logger.info('DONE: Call of after_closing_cb.')
877 self._check_session_journal_entries(pos_session, expected_values=args['journal_entries_after_closing'])
878 _logger.info('DONE: Checks for journal entries after closing the session.')
879
880 def _start_pos_session(self, payment_methods, opening_cash):
881 self.config.write({'payment_method_ids': [(6, 0, payment_methods.ids)]})
882 pos_session = self.open_new_session(opening_cash)
883 self.assertEqual(self.config.payment_method_ids.ids, pos_session.payment_method_ids.ids, msg='Payment methods in the config should be the same as the session.')
884 return pos_session
885
886 def _create_orders(self, order_data_params):
887 '''Returns a dict mapping uuid to its created pos.order record.'''
888 result = {}
889 order_data = [self.create_ui_order_data(**params) for params in order_data_params]
890 order_ids = [order['id'] for order in self.env['pos.order'].sync_from_ui(order_data)['pos.order']]
891 for order_id in self.env["pos.order"].browse(order_ids):
892 result[order_id.uuid] = order_id
893 return result
894
895 def _check_invoice_journal_entries(self, pos_session, orders_map, expected_values):
896 '''Checks the invoice, together with the payments, from each invoiced order.'''
897 currency_rounding = pos_session.currency_id.rounding
898
899 for uid in orders_map:
900 order = orders_map[uid]
901 if not order.is_invoiced:
902 continue
903 invoice = order.account_move
904 # allow not checking the invoice since pos is not creating the invoices
905 if expected_values[uid].get('invoice'):
906 self._assert_account_move(invoice, expected_values[uid]['invoice'])
907 _logger.info('DONE: Check of invoice for order %s.', uid)
908
909 for pos_payment in order.payment_ids:
910 if pos_payment.payment_method_id == self.pay_later_pm:
911 # Skip the pay later payments since there are no journal entries
912 # for them when invoicing.
913 continue
914
915 # This predicate is used to match the pos_payment's journal entry to the
916 # list of payments specified in the 'payments' field of the `_run_test`
917 # args.
918 def predicate(args):
919 payment_method, amount = args
920 first = payment_method == pos_payment.payment_method_id
921 second = tools.float_is_zero(pos_payment.amount - amount, precision_rounding=currency_rounding)
922 return first and second
923
924 self._find_then_assert_values(pos_payment.account_move_id, expected_values[uid]['payments'], predicate)
925 _logger.info('DONE: Check of invoice payment (%s, %s) for order %s.', pos_payment.payment_method_id.name, pos_payment.amount, uid)
926
927 def _check_session_journal_entries(self, pos_session, expected_values):
928 '''Checks the journal entries after closing the session excluding entries checked in `_check_invoice_journal_entries`.'''
929 currency_rounding = pos_session.currency_id.rounding
930
931 # check expected session journal entry
932 self._assert_account_move(pos_session.move_id, expected_values['session_journal_entry'])
933 _logger.info("DONE: Check of the session's account move.")
934
935 # check expected cash journal entries
936 for statement_line in pos_session.statement_line_ids:
937 def statement_line_predicate(args):
938 return tools.float_is_zero(statement_line.amount - args[0], precision_rounding=currency_rounding)
939 self._find_then_assert_values(statement_line.move_id, expected_values['cash_statement'], statement_line_predicate)
940 _logger.info("DONE: Check of cash statement lines.")
941
942 # check expected bank payments
943 for bank_payment in pos_session.bank_payment_ids:
944 def bank_payment_predicate(args):
945 return tools.float_is_zero(bank_payment.amount - args[0], precision_rounding=currency_rounding)
946 self._find_then_assert_values(bank_payment.move_id, expected_values['bank_payments'], bank_payment_predicate)
947 _logger.info("DONE: Check of bank account payments.")
948
949 def _find_then_assert_values(self, account_move, source_of_expected_vals, predicate):
950 expected_move_vals = next(move_vals for args, move_vals in source_of_expected_vals if predicate(args))
951 self._assert_account_move(account_move, expected_move_vals)
952
953 def _assert_account_move(self, account_move, expected_account_move_vals):
954 if expected_account_move_vals:
955 # We allow partial checks of the lines of the account move if `line_ids_predicate` is specified.
956 # This means that only those that satisfy the predicate are compared to the expected account move line_ids.
957 line_ids_predicate = expected_account_move_vals.pop('line_ids_predicate', lambda _: True)
958 line_ids = expected_account_move_vals.pop('line_ids')
959 reconciliation_statuses = []
960 for line in line_ids:
961 partially_reconciled = line.pop('partially_reconciled', False)
962 if partially_reconciled is True:
963 reconciliation_statuses.append('partially_reconciled')
964 else:
965 reconciliation_statuses.append('fully_reconciled' if line.get('reconciled') else 'not_reconciled')
966 account_move_line_ids = account_move.line_ids.filtered(line_ids_predicate)
967 self.assertRecordValues(account_move_line_ids, line_ids)
968 self.assertRecordValues(account_move, [expected_account_move_vals])
969
970 # Check reconciliation status
971 for line, reconciliation_status in zip(account_move_line_ids, reconciliation_statuses):
972 # See 'account_move_line._compute_amount_residual' for more explanation
973 if reconciliation_status == 'fully_reconciled':
974 if line.matching_number:
975 self.assertTrue(line.full_reconcile_id)
976 self.assertAlmostEqual(line.amount_residual, 0)
977 elif reconciliation_status == 'partially_reconciled':
978 self.assertFalse(line.full_reconcile_id)
979 if line.reconciled:
980 self.assertAlmostEqual(line.amount_residual, 0)
981 else:
982 self.assertGreater(abs(line.amount_residual), 0)
983 elif reconciliation_status == 'not_reconciled':
984 self.assertFalse(line.full_reconcile_id)
985 self.assertFalse(line.reconciled)
986 else:
987 # if the expected_account_move_vals is falsy, the account_move should be falsy.
988 self.assertFalse(account_move)
989
990 def make_payment(self, order, payment_method, amount):
991 """ Make payment for the order using the given payment method.
992 """
993 payment_context = {"active_id": order.id, "active_ids": order.ids}
994 return self.env['pos.make.payment'].with_context(**payment_context).create({
995 'amount': amount,
996 'payment_method_id': payment_method.id,
997 }).check()