size
int64
0
304k
ext
stringclasses
1 value
lang
stringclasses
1 value
branch
stringclasses
1 value
content
stringlengths
0
304k
avg_line_length
float64
0
238
max_line_length
int64
0
304k
9,880
py
PYTHON
15.0
# -*- coding: utf-8 -*- from freezegun import freeze_time from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo.tools.misc import format_amount @tagged('post_install', '-at_install') class TestAccountJournalDashboard(AccountTestInvoicingCommon): @freeze_time("2019-01-22") def test_customer_invoice_dashboard(self): journal = self.company_data['default_journal_sale'] invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'journal_id': journal.id, 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-21', 'date': '2019-01-21', 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'quantity': 40.0, 'name': 'product test 1', 'discount': 10.00, 'price_unit': 2.27, })] }) refund = self.env['account.move'].create({ 'move_type': 'out_refund', 'journal_id': journal.id, 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-21', 'date': '2019-01-21', 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'quantity': 1.0, 'name': 'product test 1', 'price_unit': 13.3, })] }) # Check Draft dashboard_data = journal.get_journal_dashboard_datas() self.assertEqual(dashboard_data['number_draft'], 2) self.assertIn('68.42', dashboard_data['sum_draft']) self.assertEqual(dashboard_data['number_waiting'], 0) self.assertIn('0.00', dashboard_data['sum_waiting']) # Check Both invoice.action_post() dashboard_data = journal.get_journal_dashboard_datas() self.assertEqual(dashboard_data['number_draft'], 1) self.assertIn('-13.30', dashboard_data['sum_draft']) self.assertEqual(dashboard_data['number_waiting'], 1) self.assertIn('81.72', dashboard_data['sum_waiting']) # Check waiting payment refund.action_post() dashboard_data = journal.get_journal_dashboard_datas() self.assertEqual(dashboard_data['number_draft'], 0) self.assertIn('0.00', dashboard_data['sum_draft']) self.assertEqual(dashboard_data['number_waiting'], 2) self.assertIn('68.42', dashboard_data['sum_waiting']) # Check partial receivable_account = refund.line_ids.mapped('account_id').filtered(lambda a: a.internal_type == 'receivable') payment = self.env['account.payment'].create({ 'amount': 10.0, 'payment_type': 'outbound', 'partner_type': 'customer', 'partner_id': self.partner_a.id, }) payment.action_post() (refund + payment.move_id).line_ids\ .filtered(lambda line: line.account_internal_type == 'receivable')\ .reconcile() dashboard_data = journal.get_journal_dashboard_datas() self.assertEqual(dashboard_data['number_draft'], 0) self.assertIn('0.00', dashboard_data['sum_draft']) self.assertEqual(dashboard_data['number_waiting'], 2) self.assertIn('78.42', dashboard_data['sum_waiting']) dashboard_data = journal.get_journal_dashboard_datas() self.assertEqual(dashboard_data['number_late'], 2) self.assertIn('78.42', dashboard_data['sum_late']) def test_last_statement(self): bank_journal = self.company_data['default_journal_bank'] invoices = self.env['account.move'].create([ { 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2022-05-17', 'date': '2022-05-17', 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'quantity': 1.0, 'name': 'product test 1', 'price_unit': 500.0, })] }, { 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2022-05-18', 'date': '2022-05-18', 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'quantity': 1.0, 'name': 'product test 1', 'price_unit': 700.0, })] }, { 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2022-05-17', 'date': '2022-05-17', 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'quantity': 1.0, 'name': 'product test 1', 'price_unit': 900.0, })] }, ]) invoices.action_post() payments = self.env['account.payment'].create([ { 'amount': 500.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': self.partner_a.id, 'journal_id': bank_journal.id, 'date': '2022-05-17', }, { 'amount': 700.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': self.partner_a.id, 'journal_id': bank_journal.id, 'date': '2022-05-18', }, { 'amount': 500.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': self.partner_a.id, 'journal_id': bank_journal.id, 'date': '2022-05-17', }, ]) payments.action_post() for invoice, payment in zip(invoices, payments): (invoice + payment.move_id).line_ids\ .filtered(lambda line: line.account_internal_type == 'receivable')\ .reconcile() # Create statements in bank journal. statements = self.env['account.bank.statement'].create([ { 'name': 'BNK1_1', 'date': '2022-05-17', 'journal_id': bank_journal.id, 'line_ids': [ (0, 0, {'date': '2022-05-17', 'payment_ref': invoices[0].name, 'amount': 500.0}), (0, 0, {'date': '2022-05-18', 'payment_ref': invoices[1].name, 'amount': 700.0}), ], 'balance_end_real': 1200.0, }, { 'name': 'BNK1_2', 'date': '2022-05-17', 'journal_id': bank_journal.id, 'line_ids': [(0, 0, {'date': '2022-05-17', 'payment_ref': invoices[2].name, 'amount': 900.0})], 'balance_end_real': 2100.0, } ]) statements.button_post() dashboard = bank_journal.get_journal_dashboard_datas() self.assertTrue(dashboard['last_balance'] == dashboard['account_balance']) def test_sale_purchase_journal_for_multi_currency_purchase(self): currency = self.currency_data['currency'] company_currency = self.company_data['currency'] invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': currency.id, 'invoice_line_ids': [ (0, 0, {'name': 'test', 'price_unit': 200}) ], }) invoice.action_post() payment = self.env['account.payment'].create({ 'amount': 90.0, 'date': '2016-01-01', 'payment_type': 'outbound', 'partner_type': 'supplier', 'partner_id': self.partner_a.id, 'currency_id': currency.id, }) payment.action_post() (invoice + payment.move_id).line_ids.filtered_domain([ ('account_id', '=', self.company_data['default_account_payable'].id) ]).reconcile() dashboard_data = self.company_data['default_journal_purchase'].get_journal_dashboard_datas() self.assertEqual(format_amount(self.env, 70, company_currency), dashboard_data['sum_waiting']) self.assertEqual(format_amount(self.env, 70, company_currency), dashboard_data['sum_late']) def test_sale_purchase_journal_for_multi_currency_sale(self): currency = self.currency_data['currency'] company_currency = self.company_data['currency'] invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': currency.id, 'invoice_line_ids': [ (0, 0, {'name': 'test', 'price_unit': 200}) ], }) invoice.action_post() payment = self.env['account.payment'].create({ 'amount': 90.0, 'date': '2016-01-01', 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': self.partner_a.id, 'currency_id': currency.id, }) payment.action_post() (invoice + payment.move_id).line_ids.filtered_domain([ ('account_id', '=', self.company_data['default_account_receivable'].id) ]).reconcile() dashboard_data = self.company_data['default_journal_sale'].get_journal_dashboard_datas() self.assertEqual(format_amount(self.env, 70, company_currency), dashboard_data['sum_waiting']) self.assertEqual(format_amount(self.env, 70, company_currency), dashboard_data['sum_late'])
37.142857
9,880
8,694
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo.exceptions import UserError, ValidationError @tagged('post_install', '-at_install') class TestAccountAccount(AccountTestInvoicingCommon): def test_changing_account_company(self): ''' Ensure you can't change the company of an account.account if there are some journal entries ''' self.env['account.move'].create({ 'move_type': 'entry', 'date': '2019-01-01', 'line_ids': [ (0, 0, { 'name': 'line_debit', 'account_id': self.company_data['default_account_revenue'].id, }), (0, 0, { 'name': 'line_credit', 'account_id': self.company_data['default_account_revenue'].id, }), ], }) with self.assertRaises(UserError), self.cr.savepoint(): self.company_data['default_account_revenue'].company_id = self.company_data_2['company'] def test_toggle_reconcile(self): ''' Test the feature when the user sets an account as reconcile/not reconcile with existing journal entries. ''' account = self.company_data['default_account_revenue'] move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2019-01-01', 'line_ids': [ (0, 0, { 'account_id': account.id, 'currency_id': self.currency_data['currency'].id, 'debit': 100.0, 'credit': 0.0, 'amount_currency': 200.0, }), (0, 0, { 'account_id': account.id, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 100.0, 'amount_currency': -200.0, }), ], }) move.action_post() self.assertRecordValues(move.line_ids, [ {'reconciled': False, 'amount_residual': 0.0, 'amount_residual_currency': 0.0}, {'reconciled': False, 'amount_residual': 0.0, 'amount_residual_currency': 0.0}, ]) # Set the account as reconcile and fully reconcile something. account.reconcile = True self.env['account.move.line'].invalidate_cache() self.assertRecordValues(move.line_ids, [ {'reconciled': False, 'amount_residual': 100.0, 'amount_residual_currency': 200.0}, {'reconciled': False, 'amount_residual': -100.0, 'amount_residual_currency': -200.0}, ]) move.line_ids.reconcile() self.assertRecordValues(move.line_ids, [ {'reconciled': True, 'amount_residual': 0.0, 'amount_residual_currency': 0.0}, {'reconciled': True, 'amount_residual': 0.0, 'amount_residual_currency': 0.0}, ]) # Set back to a not reconcile account and check the journal items. move.line_ids.remove_move_reconcile() account.reconcile = False self.env['account.move.line'].invalidate_cache() self.assertRecordValues(move.line_ids, [ {'reconciled': False, 'amount_residual': 0.0, 'amount_residual_currency': 0.0}, {'reconciled': False, 'amount_residual': 0.0, 'amount_residual_currency': 0.0}, ]) def test_toggle_reconcile_with_partials(self): ''' Test the feature when the user sets an account as reconcile/not reconcile with partial reconciliation. ''' account = self.company_data['default_account_revenue'] move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2019-01-01', 'line_ids': [ (0, 0, { 'account_id': account.id, 'currency_id': self.currency_data['currency'].id, 'debit': 100.0, 'credit': 0.0, 'amount_currency': 200.0, }), (0, 0, { 'account_id': account.id, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 50.0, 'amount_currency': -100.0, }), (0, 0, { 'account_id': self.company_data['default_account_expense'].id, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 50.0, 'amount_currency': -100.0, }), ], }) move.action_post() # Set the account as reconcile and partially reconcile something. account.reconcile = True self.env['account.move.line'].invalidate_cache() move.line_ids.filtered(lambda line: line.account_id == account).reconcile() # Try to set the account as a not-reconcile one. with self.assertRaises(UserError), self.cr.savepoint(): account.reconcile = False def test_toggle_reconcile_outstanding_account(self): ''' Test the feature when the user sets an account as not reconcilable when a journal is configured with this account as the payment credit or debit account. Since such an account should be reconcilable by nature, a ValidationError is raised.''' with self.assertRaises(ValidationError), self.cr.savepoint(): self.company_data['default_journal_bank'].company_id.account_journal_payment_debit_account_id.reconcile = False with self.assertRaises(ValidationError), self.cr.savepoint(): self.company_data['default_journal_bank'].company_id.account_journal_payment_credit_account_id.reconcile = False def test_remove_account_from_account_group(self): """Test if an account is well removed from account group""" group = self.env['account.group'].create({ 'name': 'test_group', 'code_prefix_start': 401000, 'code_prefix_end': 402000, 'company_id': self.env.company.id }) account_1 = self.company_data['default_account_revenue'].copy({'code': 401000}) account_2 = self.company_data['default_account_revenue'].copy({'code': 402000}) self.assertRecordValues(account_1 + account_2, [{'group_id': group.id}] * 2) group.code_prefix_end = 401000 self.assertRecordValues(account_1 + account_2, [{'group_id': group.id}, {'group_id': False}]) def test_compute_current_balance(self): """ Test if an account's current_balance is computed correctly """ account_payable = self.company_data['default_account_payable'] account_receivable = self.company_data['default_account_receivable'] payable_debit_move = { 'line_ids': [ (0, 0, {'name': 'debit', 'account_id': account_payable.id, 'debit': 100.0, 'credit': 0.0}), (0, 0, {'name': 'credit', 'account_id': account_receivable.id, 'debit': 0.0, 'credit': 100.0}), ], } payable_credit_move = { 'line_ids': [ (0, 0, {'name': 'credit', 'account_id': account_payable.id, 'debit': 0.0, 'credit': 100.0}), (0, 0, {'name': 'debit', 'account_id': account_receivable.id, 'debit': 100.0, 'credit': 0.0}), ], } self.assertEqual(account_payable.current_balance, 0) self.env['account.move'].create(payable_debit_move).action_post() account_payable._compute_current_balance() self.assertEqual(account_payable.current_balance, 100) self.env['account.move'].create(payable_credit_move).action_post() account_payable._compute_current_balance() self.assertEqual(account_payable.current_balance, 0) self.env['account.move'].create(payable_credit_move).action_post() account_payable._compute_current_balance() self.assertEqual(account_payable.current_balance, -100) self.env['account.move'].create(payable_credit_move).button_cancel() account_payable._compute_current_balance() self.assertEqual(account_payable.current_balance, -100, 'Canceled invoices/bills should not be used when computing the balance') # draft invoice self.env['account.move'].create(payable_credit_move) account_payable._compute_current_balance() self.assertEqual(account_payable.current_balance, -100, 'Draft invoices/bills should not be used when computing the balance')
44.13198
8,694
12,296
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.tests.common import AccountTestInvoicingHttpCommon from odoo.tests.common import tagged import json from odoo import http from odoo.tools import mute_logger @tagged('post_install', '-at_install') class TestPortalAttachment(AccountTestInvoicingHttpCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.out_invoice = cls.env['account.move'].with_context(tracking_disable=True).create({ 'move_type': 'out_invoice', 'partner_id': cls.partner_a.id, 'invoice_date': '2019-05-01', 'date': '2019-05-01', 'invoice_line_ids': [ (0, 0, {'name': 'line1', 'price_unit': 100.0}), ], }) cls.base_url = cls.out_invoice.get_base_url() @mute_logger('odoo.addons.http_routing.models.ir_http', 'odoo.http') def test_01_portal_attachment(self): """Test the portal chatter attachment route.""" self.authenticate(None, None) # Test public user can't create attachment without token of document res = self.url_open( url='%s/portal/attachment/add' % self.base_url, data={ 'name': "new attachment", 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'csrf_token': http.WebRequest.csrf_token(self), }, files=[('file', ('test.txt', b'test', 'plain/text'))], ) self.assertEqual(res.status_code, 400) self.assertIn("you do not have the rights", res.text) # Test public user can create attachment with token res = self.url_open( url='%s/portal/attachment/add' % self.base_url, data={ 'name': "new attachment", 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'csrf_token': http.WebRequest.csrf_token(self), 'access_token': self.out_invoice._portal_ensure_token(), }, files=[('file', ('test.txt', b'test', 'plain/text'))], ) self.assertEqual(res.status_code, 200) create_res = json.loads(res.content.decode('utf-8')) self.assertTrue(self.env['ir.attachment'].sudo().search([('id', '=', create_res['id'])])) # Test created attachment is private res_binary = self.url_open('/web/content/%d' % create_res['id']) self.assertEqual(res_binary.status_code, 404) # Test created access_token is working res_binary = self.url_open('/web/content/%d?access_token=%s' % (create_res['id'], create_res['access_token'])) self.assertEqual(res_binary.status_code, 200) # Test mimetype is neutered as non-admin res = self.url_open( url='%s/portal/attachment/add' % self.base_url, data={ 'name': "new attachment", 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'csrf_token': http.WebRequest.csrf_token(self), 'access_token': self.out_invoice._portal_ensure_token(), }, files=[('file', ('test.svg', b'<svg></svg>', 'image/svg+xml'))], ) self.assertEqual(res.status_code, 200) create_res = json.loads(res.content.decode('utf-8')) self.assertEqual(create_res['mimetype'], 'text/plain') res_binary = self.url_open('/web/content/%d?access_token=%s' % (create_res['id'], create_res['access_token'])) self.assertEqual(res_binary.headers['Content-Type'], 'text/plain') self.assertEqual(res_binary.content, b'<svg></svg>') res_image = self.url_open('/web/image/%d?access_token=%s' % (create_res['id'], create_res['access_token'])) self.assertEqual(res_image.headers['Content-Type'], 'text/plain') self.assertEqual(res_image.content, b'<svg></svg>') # Test attachment can't be removed without valid token res = self.opener.post( url='%s/portal/attachment/remove' % self.base_url, json={ 'params': { 'attachment_id': create_res['id'], 'access_token': "wrong", }, }, ) self.assertEqual(res.status_code, 200) self.assertTrue(self.env['ir.attachment'].sudo().search([('id', '=', create_res['id'])])) self.assertIn("you do not have the rights", res.text) # Test attachment can be removed with token if "pending" state res = self.opener.post( url='%s/portal/attachment/remove' % self.base_url, json={ 'params': { 'attachment_id': create_res['id'], 'access_token': create_res['access_token'], }, }, ) self.assertEqual(res.status_code, 200) remove_res = json.loads(res.content.decode('utf-8'))['result'] self.assertFalse(self.env['ir.attachment'].sudo().search([('id', '=', create_res['id'])])) self.assertTrue(remove_res is True) # Test attachment can't be removed if not "pending" state attachment = self.env['ir.attachment'].create({ 'name': 'an attachment', 'access_token': self.env['ir.attachment']._generate_access_token(), }) res = self.opener.post( url='%s/portal/attachment/remove' % self.base_url, json={ 'params': { 'attachment_id': attachment.id, 'access_token': attachment.access_token, }, }, ) self.assertEqual(res.status_code, 200) self.assertTrue(self.env['ir.attachment'].sudo().search([('id', '=', attachment.id)])) self.assertIn("not in a pending state", res.text) # Test attachment can't be removed if attached to a message attachment.write({ 'res_model': 'mail.compose.message', 'res_id': 0, }) attachment.flush() message = self.env['mail.message'].create({ 'attachment_ids': [(6, 0, attachment.ids)], }) res = self.opener.post( url='%s/portal/attachment/remove' % self.base_url, json={ 'params': { 'attachment_id': attachment.id, 'access_token': attachment.access_token, }, }, ) self.assertEqual(res.status_code, 200) self.assertTrue(attachment.exists()) self.assertIn("it is linked to a message", res.text) message.sudo().unlink() # Test attachment can't be associated if no attachment token. res = self.opener.post( url='%s/mail/chatter_post' % self.base_url, json={ 'params': { 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'message': "test message 1", 'attachment_ids': [attachment.id], 'attachment_tokens': ['false'], 'csrf_token': http.WebRequest.csrf_token(self), }, }, ) self.assertEqual(res.status_code, 200) self.assertIn("The attachment %s does not exist or you do not have the rights to access it." % attachment.id, res.text) # Test attachment can't be associated if no main document token res = self.opener.post( url='%s/mail/chatter_post' % self.base_url, json={ 'params': { 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'message': "test message 1", 'attachment_ids': [attachment.id], 'attachment_tokens': [attachment.access_token], 'csrf_token': http.WebRequest.csrf_token(self), }, }, ) self.assertEqual(res.status_code, 200) self.assertIn("You are not allowed to access 'Journal Entry' (account.move) records.", res.text) # Test attachment can't be associated if not "pending" state self.assertFalse(self.out_invoice.message_ids) attachment.write({'res_model': 'model'}) res = self.opener.post( url='%s/mail/chatter_post' % self.base_url, json={ 'params': { 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'message': "test message 1", 'attachment_ids': [attachment.id], 'attachment_tokens': [attachment.access_token], 'csrf_token': http.WebRequest.csrf_token(self), 'token': self.out_invoice._portal_ensure_token(), }, }, ) self.assertEqual(res.status_code, 200) self.out_invoice.invalidate_cache(fnames=['message_ids'], ids=self.out_invoice.ids) self.assertEqual(len(self.out_invoice.message_ids), 1) self.assertEqual(self.out_invoice.message_ids.body, "<p>test message 1</p>") self.assertFalse(self.out_invoice.message_ids.attachment_ids) # Test attachment can't be associated if not correct user attachment.write({'res_model': 'mail.compose.message'}) res = self.opener.post( url='%s/mail/chatter_post' % self.base_url, json={ 'params': { 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'message': "test message 2", 'attachment_ids': [attachment.id], 'attachment_tokens': [attachment.access_token], 'csrf_token': http.WebRequest.csrf_token(self), 'token': self.out_invoice._portal_ensure_token(), }, }, ) self.assertEqual(res.status_code, 200) self.out_invoice.invalidate_cache(fnames=['message_ids'], ids=self.out_invoice.ids) self.assertEqual(len(self.out_invoice.message_ids), 2) self.assertEqual(self.out_invoice.message_ids[0].body, "<p>test message 2</p>") self.assertFalse(self.out_invoice.message_ids.attachment_ids) # Test attachment can be associated if all good (complete flow) res = self.url_open( url='%s/portal/attachment/add' % self.base_url, data={ 'name': "final attachment", 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'csrf_token': http.WebRequest.csrf_token(self), 'access_token': self.out_invoice._portal_ensure_token(), }, files=[('file', ('test.txt', b'test', 'plain/text'))], ) self.assertEqual(res.status_code, 200) create_res = json.loads(res.content.decode('utf-8')) self.assertEqual(create_res['name'], "final attachment") res = self.opener.post( url='%s/mail/chatter_post' % self.base_url, json={ 'params': { 'res_model': self.out_invoice._name, 'res_id': self.out_invoice.id, 'message': "test message 3", 'attachment_ids': [create_res['id']], 'attachment_tokens': [create_res['access_token']], 'csrf_token': http.WebRequest.csrf_token(self), 'token': self.out_invoice._portal_ensure_token(), }, }, ) self.assertEqual(res.status_code, 200) self.out_invoice.invalidate_cache(fnames=['message_ids'], ids=self.out_invoice.ids) self.assertEqual(len(self.out_invoice.message_ids), 3) self.assertEqual(self.out_invoice.message_ids[0].body, "<p>test message 3</p>") self.assertEqual(len(self.out_invoice.message_ids[0].attachment_ids), 1)
43.602837
12,296
68,375
py
PYTHON
15.0
# -*- coding: utf-8 -*- from freezegun import freeze_time from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests.common import Form from odoo.tests import tagged from odoo import Command @tagged('post_install', '-at_install') class TestReconciliationMatchingRules(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) ################# # Company setup # ################# cls.currency_data_2 = cls.setup_multi_currency_data({ 'name': 'Dark Chocolate Coin', 'symbol': '🍫', 'currency_unit_label': 'Dark Choco', 'currency_subunit_label': 'Dark Cacao Powder', }, rate2016=10.0, rate2017=20.0) cls.company = cls.company_data['company'] cls.account_pay = cls.company_data['default_account_payable'] cls.current_assets_account = cls.env['account.account'].search([ ('user_type_id', '=', cls.env.ref('account.data_account_type_current_assets').id), ('company_id', '=', cls.company.id)], limit=1) cls.bank_journal = cls.env['account.journal'].search([('type', '=', 'bank'), ('company_id', '=', cls.company.id)], limit=1) cls.cash_journal = cls.env['account.journal'].search([('type', '=', 'cash'), ('company_id', '=', cls.company.id)], limit=1) cls.tax21 = cls.env['account.tax'].create({ 'name': '21%', 'type_tax_use': 'purchase', 'amount': 21, }) cls.tax12 = cls.env['account.tax'].create({ 'name': '12%', 'type_tax_use': 'purchase', 'amount': 12, }) cls.partner_1 = cls.env['res.partner'].create({'name': 'partner_1', 'company_id': cls.company.id}) cls.partner_2 = cls.env['res.partner'].create({'name': 'partner_2', 'company_id': cls.company.id}) cls.partner_3 = cls.env['res.partner'].create({'name': 'partner_3', 'company_id': cls.company.id}) ############### # Rules setup # ############### cls.rule_1 = cls.env['account.reconcile.model'].create({ 'name': 'Invoices Matching Rule', 'sequence': '1', 'rule_type': 'invoice_matching', 'auto_reconcile': False, 'match_nature': 'both', 'match_same_currency': True, 'allow_payment_tolerance': True, 'payment_tolerance_type': 'percentage', 'payment_tolerance_param': 0.0, 'match_partner': True, 'match_partner_ids': [(6, 0, (cls.partner_1 + cls.partner_2 + cls.partner_3).ids)], 'company_id': cls.company.id, 'line_ids': [(0, 0, {'account_id': cls.current_assets_account.id})], }) cls.rule_2 = cls.env['account.reconcile.model'].create({ 'name': 'write-off model', 'rule_type': 'writeoff_suggestion', 'match_partner': True, 'match_partner_ids': [], 'line_ids': [(0, 0, {'account_id': cls.current_assets_account.id})], }) ################## # Invoices setup # ################## cls.invoice_line_1 = cls._create_invoice_line(100, cls.partner_1, 'out_invoice') cls.invoice_line_2 = cls._create_invoice_line(200, cls.partner_1, 'out_invoice') cls.invoice_line_3 = cls._create_invoice_line(300, cls.partner_1, 'in_refund', name="RBILL/2019/09/0013") cls.invoice_line_4 = cls._create_invoice_line(1000, cls.partner_2, 'in_invoice') cls.invoice_line_5 = cls._create_invoice_line(600, cls.partner_3, 'out_invoice') cls.invoice_line_6 = cls._create_invoice_line(600, cls.partner_3, 'out_invoice', ref="RF12 3456") cls.invoice_line_7 = cls._create_invoice_line(200, cls.partner_3, 'out_invoice', pay_reference="RF12 3456") #################### # Statements setup # #################### # TODO : account_number, partner_name, transaction_type, narration invoice_number = cls.invoice_line_1.move_id.name cls.bank_st, cls.bank_st_2, cls.cash_st = cls.env['account.bank.statement'].create([ { 'name': 'test bank journal', 'journal_id': cls.bank_journal.id, 'line_ids': [ (0, 0, { 'date': '2020-01-01', 'payment_ref': 'invoice %s-%s' % tuple(invoice_number.split('/')[1:]), 'partner_id': cls.partner_1.id, 'amount': 100, 'sequence': 1, }), (0, 0, { 'date': '2020-01-01', 'payment_ref': 'xxxxx', 'partner_id': cls.partner_1.id, 'amount': 600, 'sequence': 2, }), ], }, { 'name': 'second test bank journal', 'journal_id': cls.bank_journal.id, 'line_ids': [ (0, 0, { 'date': '2020-01-01', 'payment_ref': 'nawak', 'narration': 'Communication: RF12 3456', 'partner_id': cls.partner_3.id, 'amount': 600, 'sequence': 1, }), (0, 0, { 'date': '2020-01-01', 'payment_ref': 'RF12 3456', 'partner_id': cls.partner_3.id, 'amount': 600, 'sequence': 2, }), (0, 0, { 'date': '2020-01-01', 'payment_ref': 'baaaaah', 'ref': 'RF12 3456', 'partner_id': cls.partner_3.id, 'amount': 600, 'sequence': 2, }), ], }, { 'name': 'test cash journal', 'journal_id': cls.cash_journal.id, 'line_ids': [ (0, 0, { 'date': '2020-01-01', 'payment_ref': 'yyyyy', 'partner_id': cls.partner_2.id, 'amount': -1000, 'sequence': 1, }), ], } ]) cls.bank_line_1, cls.bank_line_2 = cls.bank_st.line_ids cls.bank_line_3, cls.bank_line_4, cls.bank_line_5 = cls.bank_st_2.line_ids cls.cash_line_1 = cls.cash_st.line_ids cls._post_statements(cls) @classmethod def _create_invoice_line(cls, amount, partner, move_type, currency=None, pay_reference=None, ref=None, name=None, inv_date='2019-09-01'): ''' Create an invoice on the fly.''' invoice_form = Form(cls.env['account.move'].with_context(default_move_type=move_type, default_invoice_date=inv_date, default_date=inv_date)) invoice_form.partner_id = partner if currency: invoice_form.currency_id = currency if pay_reference: invoice_form.payment_reference = pay_reference if ref: invoice_form.ref = ref if name: invoice_form.name = name with invoice_form.invoice_line_ids.new() as invoice_line_form: invoice_line_form.name = 'xxxx' invoice_line_form.quantity = 1 invoice_line_form.price_unit = amount invoice_line_form.tax_ids.clear() invoice = invoice_form.save() invoice.action_post() lines = invoice.line_ids return lines.filtered(lambda l: l.account_id.user_type_id.type in ('receivable', 'payable')) @classmethod def _create_st_line(cls, amount=1000.0, date='2019-01-01', payment_ref='turlututu', **kwargs): st = cls.env['account.bank.statement'].create({ 'name': 'test_allow_payment_tolerance_1', 'journal_id': kwargs.get('journal_id', cls.bank_journal.id), 'line_ids': [Command.create({ 'amount': amount, 'date': date, 'payment_ref': payment_ref, 'partner_id': cls.partner_a.id, **kwargs, })], }) st.balance_end_real = st.balance_end st.button_post() return st.line_ids @classmethod def _create_reconcile_model(cls, **kwargs): return cls.env['account.reconcile.model'].create({ 'name': "test", 'rule_type': 'invoice_matching', 'allow_payment_tolerance': True, 'payment_tolerance_type': 'percentage', 'payment_tolerance_param': 0.0, **kwargs, 'line_ids': [ Command.create({ 'account_id': cls.company_data['default_account_revenue'].id, 'amount_type': 'percentage', 'label': f"test {i}", **line_vals, }) for i, line_vals in enumerate(kwargs.get('line_ids', [])) ], }) def _post_statements(self): self.bank_st.balance_end_real = self.bank_st.balance_end self.bank_st_2.balance_end_real = self.bank_st_2.balance_end self.cash_st.balance_end_real = self.cash_st.balance_end (self.bank_st + self.bank_st_2 + self.cash_st).button_post() @freeze_time('2020-01-01') def _check_statement_matching(self, rules, expected_values, statements=None): if statements is None: statements = self.bank_st + self.cash_st statement_lines = statements.mapped('line_ids').sorted() matching_values = rules._apply_rules(statement_lines, None) for st_line_id, values in matching_values.items(): values.pop('reconciled_lines', None) values.pop('write_off_vals', None) self.assertDictEqual(values, expected_values[st_line_id]) def test_matching_fields(self): # Check without restriction. self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_2.id, self.invoice_line_3.id, self.invoice_line_1.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) def test_matching_fields_match_text_location(self): self.rule_1.match_text_location_label = True self.rule_1.match_text_location_reference = False self.rule_1.match_text_location_note = False self.rule_1.allow_payment_tolerance = False self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_6.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) self.rule_1.match_text_location_label = True self.rule_1.match_text_location_reference = False self.rule_1.match_text_location_note = True self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_6.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) self.rule_1.match_text_location_label = True self.rule_1.match_text_location_reference = True self.rule_1.match_text_location_note = False self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) self.rule_1.match_text_location_label = True self.rule_1.match_text_location_reference = True self.rule_1.match_text_location_note = True self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_6.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_7.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) self.rule_1.match_text_location_label = False self.rule_1.match_text_location_reference = False self.rule_1.match_text_location_note = False self._check_statement_matching(self.rule_1, { self.bank_line_3.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_3.partner_id}, self.bank_line_4.id: {'aml_ids': [self.invoice_line_5.id], 'model': self.rule_1, 'partner': self.bank_line_4.partner_id}, self.bank_line_5.id: {'aml_ids': [self.invoice_line_6.id], 'model': self.rule_1, 'partner': self.bank_line_5.partner_id}, }, statements=self.bank_st_2) def test_matching_fields_match_text_location_no_partner(self): self.bank_line_2.unlink() # One line is enough for this test self.bank_line_1.partner_id = None self.partner_1.name = "Bernard Gagnant" self.rule_1.write({ 'match_partner': False, 'match_partner_ids': [(5, 0, 0)], 'line_ids': [(5, 0, 0)], }) st_line_initial_vals = {'ref': None, 'payment_ref': 'nothing', 'narration': None} recmod_initial_vals = {'match_text_location_label': False, 'match_text_location_note': False, 'match_text_location_reference': False} rec_mod_options_to_fields = { 'match_text_location_label': 'payment_ref', 'match_text_location_note': 'narration', 'match_text_location_reference': 'ref', } for rec_mod_field, st_line_field in rec_mod_options_to_fields.items(): self.rule_1.write({**recmod_initial_vals, rec_mod_field: True}) # Fully reinitialize the statement line self.bank_line_1.write(st_line_initial_vals) # Nothing should match self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, }, statements=self.bank_st) # Test matching with the invoice ref self.bank_line_1.write({st_line_field: self.invoice_line_1.move_id.payment_reference}) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': self.invoice_line_1.ids, 'model': self.rule_1, 'partner': self.env['res.partner']}, }, statements=self.bank_st) # Test matching with the partner name (reinitializing the statement line first) self.bank_line_1.write({**st_line_initial_vals, st_line_field: self.partner_1.name}) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': self.invoice_line_1.ids, 'model': self.rule_1, 'partner': self.env['res.partner']}, }, statements=self.bank_st) def test_matching_fields_match_journal_ids(self): self.rule_1.match_journal_ids |= self.cash_st.journal_id self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_journal_ids |= self.bank_st.journal_id + self.cash_st.journal_id def test_matching_fields_match_nature(self): self.rule_1.match_nature = 'amount_received' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_2.id, self.invoice_line_3.id, self.invoice_line_1.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': []}, }) self.rule_1.match_nature = 'amount_paid' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_nature = 'both' def test_matching_fields_match_amount(self): self.rule_1.match_amount = 'lower' self.rule_1.match_amount_max = 150 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': []}, }) self.rule_1.match_amount = 'greater' self.rule_1.match_amount_min = 200 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_1.id, self.invoice_line_2.id, self.invoice_line_3.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_amount = 'between' self.rule_1.match_amount_min = 200 self.rule_1.match_amount_max = 800 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_1.id, self.invoice_line_2.id, self.invoice_line_3.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': []}, }) self.rule_1.match_amount = False def test_matching_fields_match_label(self): self.rule_1.match_label = 'contains' self.rule_1.match_label_param = 'yyyyy' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_label = 'not_contains' self.rule_1.match_label_param = 'xxxxx' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_label = 'match_regex' self.rule_1.match_label_param = 'xxxxx|yyyyy' self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_1.id, self.invoice_line_2.id, self.invoice_line_3.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_label = False @freeze_time('2019-01-01') def test_zero_payment_tolerance(self): rule = self._create_reconcile_model(line_ids=[{}]) for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)): invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, inv_date='2019-01-01') # Exact matching. st_line = self._create_st_line(amount=bsl_sign * 1000.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id}}, statements=st_line.statement_id, ) # No matching because there is no tolerance. st_line = self._create_st_line(amount=bsl_sign * 990.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': []}}, statements=st_line.statement_id, ) # The payment amount is higher than the invoice one. st_line = self._create_st_line(amount=bsl_sign * 1010.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id}}, statements=st_line.statement_id, ) @freeze_time('2019-01-01') def test_zero_payment_tolerance_auto_reconcile(self): rule = self._create_reconcile_model( auto_reconcile=True, line_ids=[{}], ) for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)): invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, pay_reference='123456', inv_date='2019-01-01') # No matching because there is no tolerance. st_line = self._create_st_line(amount=bsl_sign * 990.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': []}}, statements=st_line.statement_id, ) # The payment amount is higher than the invoice one. st_line = self._create_st_line(amount=bsl_sign * 1010.0, payment_ref='123456') self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id, 'status': 'reconciled'}}, statements=st_line.statement_id, ) self.assertRecordValues(st_line.line_ids.sorted(lambda x: abs(x.balance)), [ # pylint: disable=bad-whitespace {'balance': bsl_sign * -10.0, 'account_id': invl.account_id.id, 'reconciled': False}, {'balance': bsl_sign * -1000.0, 'account_id': invl.account_id.id, 'reconciled': True}, {'balance': bsl_sign * 1010.0, 'account_id': self.bank_journal.default_account_id.id, 'reconciled': False}, ]) @freeze_time('2019-01-01') def test_not_enough_payment_tolerance(self): rule = self._create_reconcile_model( payment_tolerance_param=0.5, line_ids=[{}], ) for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)): invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, inv_date='2019-01-01') # No matching because there is no enough tolerance. st_line = self._create_st_line(amount=bsl_sign * 990.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': []}}, statements=st_line.statement_id, ) # The payment amount is higher than the invoice one. # However, since the invoice amount is lower than the payment amount, # the tolerance is not checked and the invoice line is matched. st_line = self._create_st_line(amount=bsl_sign * 1010.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id}}, statements=st_line.statement_id, ) @freeze_time('2019-01-01') def test_enough_payment_tolerance(self): rule = self._create_reconcile_model( payment_tolerance_param=1.0, line_ids=[{}], ) for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)): invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, inv_date='2019-01-01') # Enough tolerance to match the invoice line. st_line = self._create_st_line(amount=bsl_sign * 990.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id, 'status': 'write_off'}}, statements=st_line.statement_id, ) # The payment amount is higher than the invoice one. # However, since the invoice amount is lower than the payment amount, # the tolerance is not checked and the invoice line is matched. st_line = self._create_st_line(amount=bsl_sign * 1010.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id}}, statements=st_line.statement_id, ) @freeze_time('2019-01-01') def test_enough_payment_tolerance_auto_reconcile_not_full(self): rule = self._create_reconcile_model( payment_tolerance_param=1.0, auto_reconcile=True, line_ids=[{'amount_type': 'percentage_st_line', 'amount_string': '200.0'}], ) for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)): invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, pay_reference='123456', inv_date='2019-01-01') # Enough tolerance to match the invoice line. st_line = self._create_st_line(amount=bsl_sign * 990.0, payment_ref='123456') self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id, 'status': 'reconciled'}}, statements=st_line.statement_id, ) self.assertRecordValues(st_line.line_ids.sorted(lambda x: abs(x.balance)), [ # pylint: disable=bad-whitespace {'balance': bsl_sign * 990.0, 'account_id': self.bank_journal.default_account_id.id, 'reconciled': False}, {'balance': bsl_sign * -1000.0, 'account_id': invl.account_id.id, 'reconciled': True}, {'balance': bsl_sign * -1980.0, 'account_id': self.company_data['default_account_revenue'].id, 'reconciled': False}, {'balance': bsl_sign * 1990.0, 'account_id': invl.account_id.id, 'reconciled': False}, ]) @freeze_time('2019-01-01') def test_allow_payment_tolerance_lower_amount(self): rule = self._create_reconcile_model(line_ids=[{'amount_type': 'percentage_st_line'}]) for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)): invl = self._create_invoice_line(990.0, self.partner_a, inv_type, inv_date='2019-01-01') st_line = self._create_st_line(amount=bsl_sign * 1000) # Partial reconciliation. self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id}}, statements=st_line.statement_id, ) @freeze_time('2019-01-01') def test_enough_payment_tolerance_auto_reconcile(self): rule = self._create_reconcile_model( payment_tolerance_param=1.0, auto_reconcile=True, line_ids=[{}], ) for inv_type, bsl_sign in (('out_invoice', 1), ('in_invoice', -1)): invl = self._create_invoice_line(1000.0, self.partner_a, inv_type, pay_reference='123456', inv_date='2019-01-01') # Enough tolerance to match the invoice line. st_line = self._create_st_line(amount=bsl_sign * 990.0, payment_ref='123456') self._check_statement_matching( rule, {st_line.id: {'aml_ids': invl.ids, 'model': rule, 'partner': st_line.partner_id, 'status': 'reconciled'}}, statements=st_line.statement_id, ) self.assertRecordValues(st_line.line_ids.sorted(lambda x: abs(x.balance)), [ # pylint: disable=bad-whitespace {'balance': bsl_sign * 10.0, 'account_id': self.company_data['default_account_revenue'].id, 'reconciled': False}, {'balance': bsl_sign * 990.0, 'account_id': self.bank_journal.default_account_id.id, 'reconciled': False}, {'balance': bsl_sign * -1000.0, 'account_id': invl.account_id.id, 'reconciled': True}, ]) @freeze_time('2019-01-01') def test_percentage_st_line_auto_reconcile(self): rule = self._create_reconcile_model( payment_tolerance_param=1.0, rule_type='writeoff_suggestion', auto_reconcile=True, line_ids=[ {'amount_type': 'percentage_st_line', 'amount_string': '100.0', 'label': 'A'}, {'amount_type': 'percentage_st_line', 'amount_string': '-100.0', 'label': 'B'}, {'amount_type': 'percentage_st_line', 'amount_string': '100.0', 'label': 'C'}, ], ) for bsl_sign in (1, -1): st_line = self._create_st_line(amount=bsl_sign * 1000.0) self._check_statement_matching( rule, {st_line.id: {'aml_ids': [], 'model': rule, 'partner': st_line.partner_id, 'status': 'reconciled'}}, statements=st_line.statement_id, ) self.assertRecordValues(st_line.line_ids.sorted(lambda x: x.account_id), [ # pylint: disable=bad-whitespace {'balance': bsl_sign * 1000.0, 'account_id': self.bank_journal.default_account_id.id, 'reconciled': False}, {'balance': bsl_sign * -1000.0, 'account_id': self.company_data['default_account_revenue'].id, 'reconciled': False}, {'balance': bsl_sign * 1000.0, 'account_id': self.company_data['default_account_revenue'].id, 'reconciled': False}, {'balance': bsl_sign * -1000.0, 'account_id': self.company_data['default_account_revenue'].id, 'reconciled': False}, ]) def test_matching_fields_match_partner_category_ids(self): test_category = self.env['res.partner.category'].create({'name': 'Consulting Services'}) test_category2 = self.env['res.partner.category'].create({'name': 'Consulting Services2'}) self.partner_2.category_id = test_category + test_category2 self.rule_1.match_partner_category_ids |= test_category self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': []}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) self.rule_1.match_partner_category_ids = False def test_mixin_rules(self): ''' Test usage of rules together.''' # rule_1 is used before rule_2. self.rule_1.sequence = 1 self.rule_2.sequence = 2 self._check_statement_matching(self.rule_1 + self.rule_2, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [ self.invoice_line_2.id, self.invoice_line_3.id, self.invoice_line_1.id, ], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) # rule_2 is used before rule_1. self.rule_1.sequence = 2 self.rule_2.sequence = 1 self._check_statement_matching(self.rule_1 + self.rule_2, { self.bank_line_1.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.cash_line_1.partner_id}, }) # rule_2 is used before rule_1 but only on partner_1. self.rule_2.match_partner_ids |= self.partner_1 self._check_statement_matching(self.rule_1 + self.rule_2, { self.bank_line_1.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'write_off', 'partner': self.bank_line_2.partner_id}, self.cash_line_1.id: {'aml_ids': [self.invoice_line_4.id], 'model': self.rule_1, 'partner': self.cash_line_1.partner_id}, }) def test_auto_reconcile(self): ''' Test auto reconciliation.''' self.bank_line_1.amount += 5 self.rule_1.sequence = 2 self.rule_1.auto_reconcile = True self.rule_1.payment_tolerance_param = 10.0 self.rule_2.sequence = 1 self.rule_2.match_partner_ids |= self.partner_2 self.rule_2.auto_reconcile = True self._check_statement_matching(self.rule_1 + self.rule_2, { self.bank_line_1.id: { 'aml_ids': self.invoice_line_1.ids, 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id, }, self.bank_line_2.id: { 'aml_ids': (self.invoice_line_2 + self.invoice_line_3).ids, 'model': self.rule_1, 'partner': self.bank_line_2.partner_id, }, self.cash_line_1.id: {'aml_ids': [], 'model': self.rule_2, 'status': 'reconciled', 'partner': self.cash_line_1.partner_id}, }) # Check first line has been well reconciled. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 105.0, 'credit': 0.0}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 5.0}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 100.0}, ]) # Check second line has been well reconciled. self.assertRecordValues(self.cash_line_1.line_ids, [ {'partner_id': self.partner_2.id, 'debit': 0.0, 'credit': 1000.0}, {'partner_id': self.partner_2.id, 'debit': 1000.0, 'credit': 0.0}, ]) def test_larger_invoice_auto_reconcile(self): ''' Test auto reconciliation with an invoice with larger amount than the statement line's, for rules without write-offs.''' self.bank_line_1.amount = 40 self.invoice_line_1.move_id.payment_reference = self.bank_line_1.payment_ref self.rule_1.sequence = 2 self.rule_1.allow_payment_tolerance = False self.rule_1.auto_reconcile = True self.rule_1.line_ids = [(5, 0, 0)] self._check_statement_matching(self.rule_1, { self.bank_line_1.id: { 'aml_ids': self.invoice_line_1.ids, 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id, }, self.bank_line_2.id: { 'aml_ids': (self.invoice_line_2 + self.invoice_line_3).ids, 'model': self.rule_1, 'partner': self.bank_line_1.partner_id, }, }, statements=self.bank_st) # Check first line has been well reconciled. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 40.0, 'credit': 0.0}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 40.0}, ]) self.assertEqual(self.invoice_line_1.amount_residual, 60.0, "The invoice should have been partially reconciled") def test_auto_reconcile_with_duplicate_match(self): """ If multiple bank statement lines match with the same invoice, ensure the correct line is auto-validated and no crashing happens. """ # Only the invoice defined in this test should have this partner partner = self.env['res.partner'].create({'name': "The Only One"}) invoice_line = self._create_invoice_line( 2000, partner, 'out_invoice', ref="REF 7788") # Enable auto-validation and don't restrict the partners that can be matched on # so our newly created partner can be matched. self.rule_1.write({ 'auto_reconcile': True, 'match_partner_ids': [(5, 0, 0)], }) self.rule_1.match_partner_ids = [] # This line has a matching payment reference and the exact amount of the # invoice. As a result it should auto-validate. self.bank_line_1.amount = 2000 self.bank_line_1.partner_id = partner self.bank_line_1.payment_ref = "REF 7788" # This line doesn't have a matching amount or reference, but it does have a # matching partner. self.bank_line_2.amount = 1800 self.bank_line_2.partner_id = partner self.bank_line_2.payment_ref = "something" # Verify the auto-validation happens with the first line, and no exceptions. self._check_statement_matching(self.rule_1, { self.bank_line_1.id: { 'aml_ids': [invoice_line.id], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id }, self.bank_line_2.id: { 'aml_ids': [] }, }, statements=self.bank_st) def test_auto_reconcile_with_tax(self): ''' Test auto reconciliation with a tax amount included in the bank statement line''' self.rule_1.write({ 'auto_reconcile': True, 'rule_type': 'writeoff_suggestion', 'line_ids': [(1, self.rule_1.line_ids.id, { 'amount': 50, 'force_tax_included': True, 'tax_ids': [(6, 0, self.tax21.ids)], }), (0, 0, { 'amount': 100, 'force_tax_included': False, 'tax_ids': [(6, 0, self.tax12.ids)], 'account_id': self.current_assets_account.id, })] }) self.bank_line_1.amount = -121 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_2.partner_id}, }, statements=self.bank_st) # Check first line has been well reconciled. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 121.0, 'tax_ids': [], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 7.26, 'tax_ids': [], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 50.0, 'credit': 0.0, 'tax_ids': [self.tax21.id], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 10.5, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': self.tax21.id}, {'partner_id': self.partner_1.id, 'debit': 60.5, 'credit': 0.0, 'tax_ids': [self.tax12.id], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 7.26, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': self.tax12.id}, ]) def test_auto_reconcile_with_tax_fpos(self): """ Test the fiscal positions are applied by reconcile models when using taxes. """ self.rule_1.write({ 'auto_reconcile': True, 'rule_type': 'writeoff_suggestion', 'line_ids': [(1, self.rule_1.line_ids.id, { 'amount': 100, 'force_tax_included': True, 'tax_ids': [(6, 0, self.tax21.ids)], })] }) self.partner_1.country_id = self.env.ref('base.lu') belgium = self.env.ref('base.be') self.partner_2.country_id = belgium self.bank_line_2.partner_id = self.partner_2 self.bank_line_1.amount = -121 self.bank_line_2.amount = -112 self.env['account.fiscal.position'].create({ 'name': "Test", 'country_id': belgium.id, 'auto_apply': True, 'tax_ids': [ Command.create({ 'tax_src_id': self.tax21.id, 'tax_dest_id': self.tax12.id, }), ] }) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_2.partner_id}, }, statements=self.bank_st) self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 121.0, 'tax_ids': [], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 100.0, 'credit': 0.0, 'tax_ids': [self.tax21.id], 'tax_line_id': False}, {'partner_id': self.partner_1.id, 'debit': 21.0, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': self.tax21.id}, ]) self.assertRecordValues(self.bank_line_2.line_ids, [ {'partner_id': self.partner_2.id, 'debit': 0.0, 'credit': 112.0, 'tax_ids': [], 'tax_line_id': False}, {'partner_id': self.partner_2.id, 'debit': 100.0, 'credit': 0.0, 'tax_ids': [self.tax12.id], 'tax_line_id': False}, {'partner_id': self.partner_2.id, 'debit': 12.0, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': self.tax12.id}, ]) def test_reverted_move_matching(self): partner = self.partner_1 AccountMove = self.env['account.move'] move = AccountMove.create({ 'journal_id': self.bank_journal.id, 'line_ids': [ (0, 0, { 'account_id': self.account_pay.id, 'partner_id': partner.id, 'name': 'One of these days', 'debit': 10, }), (0, 0, { 'account_id': self.bank_journal.company_id.account_journal_payment_credit_account_id.id, 'partner_id': partner.id, 'name': 'I\'m gonna cut you into little pieces', 'credit': 10, }) ], }) payment_bnk_line = move.line_ids.filtered(lambda l: l.account_id == self.bank_journal.company_id.account_journal_payment_credit_account_id) move.action_post() move_reversed = move._reverse_moves() self.assertTrue(move_reversed.exists()) self.bank_line_1.write({ 'payment_ref': '8', 'partner_id': partner.id, 'amount': -10, }) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [payment_bnk_line.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': [self.invoice_line_1.id, self.invoice_line_2.id, self.invoice_line_3.id], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, }, statements=self.bank_st) def test_match_different_currencies(self): partner = self.env['res.partner'].create({'name': 'Bernard Gagnant'}) self.rule_1.write({'match_partner_ids': [(6, 0, partner.ids)], 'match_same_currency': False}) currency_inv = self.env.ref('base.EUR') currency_inv.active = True currency_statement = self.env.ref('base.JPY') currency_statement.active = True invoice_line = self._create_invoice_line(100, partner, 'out_invoice', currency=currency_inv) self.bank_line_1.write({'partner_id': partner.id, 'foreign_currency_id': currency_statement.id, 'amount_currency': 100, 'payment_ref': 'test'}) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': invoice_line.ids, 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, statements=self.bank_st) def test_auto_reconcile_with_tax_and_foreign_currency(self): ''' Test auto reconciliation of a bank statement in foreign currency journal with tax in counterpart values''' currency_statement = self.currency_data_2['currency'] journal = self.env['account.journal'].create({ 'name': 'test_match_multi_currencies', 'code': 'xxxx', 'type': 'bank', 'currency_id': currency_statement.id, }) self.rule_1.write({ 'auto_reconcile': True, 'rule_type': 'writeoff_suggestion', 'match_journal_ids': [(6, 0, journal.ids)], 'match_same_currency': False, 'match_nature': 'both', 'match_partner': False, 'match_label': 'contains', 'match_label_param': 'Tournicoti', # So that we only match what we want to test 'line_ids': [(1, self.rule_1.line_ids.id, { 'amount': 100, 'force_tax_included': True, 'tax_ids': [(6, 0, self.tax21.ids)], })] }) statement = self.env['account.bank.statement'].create({ 'name': 'test_match_multi_currencies', 'journal_id': journal.id, 'line_ids': [ (0, 0, { 'journal_id': journal.id, 'date': '2016-01-01', 'payment_ref': 'TournicotiTest', 'amount': 100.0, }), ], }) statement_line = statement.line_ids statement.button_post() self._check_statement_matching(self.rule_1, { statement_line.id: {'aml_ids': [], 'model': self.rule_1, 'status': 'reconciled', 'partner': self.env['res.partner']}, }, statements=statement) # Check first line has been well reconciled. self.assertRecordValues(statement_line.line_ids, [ {'partner_id': False, 'debit': 10.0, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': False}, {'partner_id': False, 'debit': 0.0, 'credit': 8.26, 'tax_ids': [self.tax21.id], 'tax_line_id': False}, {'partner_id': False, 'debit': 0.0, 'credit': 1.74, 'tax_ids': [], 'tax_line_id': self.tax21.id}, ]) def test_invoice_matching_rule_no_partner(self): """ Tests that a statement line without any partner can be matched to the right invoice if they have the same payment reference. """ self.invoice_line_1.move_id.write({'payment_reference': 'Tournicoti66'}) self.rule_1.allow_payment_tolerance = False self.bank_line_1.write({ 'payment_ref': 'Tournicoti66', 'partner_id': None, 'amount': 95, }) self.rule_1.write({ 'line_ids': [(5, 0, 0)], 'match_partner': False, 'match_label': 'contains', 'match_label_param': 'Tournicoti', # So that we only match what we want to test }) self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, self.bank_st) def test_inv_matching_rule_auto_rec_no_partner_with_writeoff(self): self.invoice_line_1.move_id.write({'payment_reference': 'doudlidou355'}) self.bank_line_1.write({ 'payment_ref': 'doudlidou355', 'partner_id': None, 'amount': 95, }) self.rule_1.write({ 'match_partner': False, 'match_label': 'contains', 'match_label_param': 'doudlidou', # So that we only match what we want to test 'payment_tolerance_param': 10.0, 'auto_reconcile': True, }) # Check bank reconciliation self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id, 'status': 'reconciled'}, self.bank_line_2.id: {'aml_ids': []}, }, self.bank_st) # Check invoice line has been fully reconciled, with a write-off. self.assertRecordValues(self.bank_line_1.line_ids, [ {'partner_id': self.partner_1.id, 'debit': 95.0, 'credit': 0.0, 'account_id': self.bank_journal.default_account_id.id, 'reconciled': False}, {'partner_id': self.partner_1.id, 'debit': 5.0, 'credit': 0.0, 'account_id': self.current_assets_account.id, 'reconciled': False}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 100.0, 'account_id': self.invoice_line_1.account_id.id, 'reconciled': True}, ]) self.assertEqual(self.invoice_line_1.amount_residual, 0.0, "The invoice should have been fully reconciled") def test_partner_mapping_rule(self): self.bank_line_1.write({'partner_id': None, 'payment_ref': 'toto42', 'narration': None}) self.bank_line_2.write({'partner_id': None}) # Do the test for both rule 1 and 2, so that we check invoice matching and write-off rules for rule in (self.rule_1 + self.rule_2): # To cope for minor differences in rule results matching_amls = rule.rule_type == 'invoice_matching' and self.invoice_line_1.ids or [] result_status = rule.rule_type == 'writeoff_suggestion' and {'status': 'write_off'} or {} match_result = {**result_status, 'aml_ids': matching_amls, 'model': rule, 'partner': self.partner_1} no_match_result = {'aml_ids': []} # Without mapping, there should be no match self._check_statement_matching(rule, { self.bank_line_1.id: no_match_result, self.bank_line_2.id: no_match_result, }, self.bank_st) # We add some mapping for payment reference to rule_1 rule.write({ 'partner_mapping_line_ids': [(0, 0, { 'partner_id': self.partner_1.id, 'payment_ref_regex': 'toto.*', })] }) # bank_line_1 should now match self._check_statement_matching(rule, { self.bank_line_1.id: match_result, self.bank_line_2.id: no_match_result, }, self.bank_st) # If we now add a narration regex to the same mapping line, nothing should match rule.partner_mapping_line_ids.write({'narration_regex': ".*coincoin"}) self.bank_line_1.write({'narration': None}) # Reset from possible previous iteration self._check_statement_matching(rule, { self.bank_line_1.id: no_match_result, self.bank_line_2.id: no_match_result, }, self.bank_st) # If we set the narration so that it matches the new mapping criterium, line_1 matches self.bank_line_1.write({'narration': "42coincoin"}) self._check_statement_matching(rule, { self.bank_line_1.id: match_result, self.bank_line_2.id: no_match_result, }, self.bank_st) def test_partner_name_in_communication(self): self.invoice_line_1.partner_id.write({'name': "Archibald Haddock"}) self.bank_line_1.write({'partner_id': None, 'payment_ref': '1234//HADDOCK-Archibald'}) self.bank_line_2.write({'partner_id': None}) self.rule_1.write({'match_partner': False}) # bank_line_1 should match, as its communication contains the invoice's partner name self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, self.bank_st) def test_partner_name_with_regexp_chars(self): self.invoice_line_1.partner_id.write({'name': "Archibald + Haddock"}) self.bank_line_1.write({'partner_id': None, 'payment_ref': '1234//HADDOCK+Archibald'}) self.bank_line_2.write({'partner_id': None}) self.rule_1.write({'match_partner': False}) # The query should still work self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': [self.invoice_line_1.id], 'model': self.rule_1, 'partner': self.bank_line_1.partner_id}, self.bank_line_2.id: {'aml_ids': []}, }, self.bank_st) def test_match_multi_currencies(self): ''' Ensure the matching of candidates is made using the right statement line currency. In this test, the value of the statement line is 100 USD = 300 GOL = 900 DAR and we want to match two journal items of: - 100 USD = 200 GOL (= 600 DAR from the statement line point of view) - 14 USD = 280 DAR Both journal items should be suggested to the user because they represents 98% of the statement line amount (DAR). ''' partner = self.env['res.partner'].create({'name': 'Bernard Perdant'}) journal = self.env['account.journal'].create({ 'name': 'test_match_multi_currencies', 'code': 'xxxx', 'type': 'bank', 'currency_id': self.currency_data['currency'].id, }) matching_rule = self.env['account.reconcile.model'].create({ 'name': 'test_match_multi_currencies', 'rule_type': 'invoice_matching', 'match_partner': True, 'match_partner_ids': [(6, 0, partner.ids)], 'allow_payment_tolerance': True, 'payment_tolerance_type': 'percentage', 'payment_tolerance_param': 5.0, 'match_same_currency': False, 'company_id': self.company_data['company'].id, 'past_months_limit': False, }) statement = self.env['account.bank.statement'].create({ 'name': 'test_match_multi_currencies', 'journal_id': journal.id, 'line_ids': [ (0, 0, { 'journal_id': journal.id, 'date': '2016-01-01', 'payment_ref': 'line', 'partner_id': partner.id, 'foreign_currency_id': self.currency_data_2['currency'].id, 'amount': 300.0, # Rate is 3 GOL = 1 USD in 2016. 'amount_currency': 900.0, # Rate is 10 DAR = 1 USD in 2016 but the rate used by the bank is 9:1. }), ], }) statement_line = statement.line_ids statement.button_post() move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'journal_id': self.company_data['default_journal_misc'].id, 'line_ids': [ # Rate is 2 GOL = 1 USD in 2017. # The statement line will consider this line equivalent to 600 DAR. (0, 0, { 'account_id': self.company_data['default_account_receivable'].id, 'partner_id': partner.id, 'currency_id': self.currency_data['currency'].id, 'debit': 100.0, 'credit': 0.0, 'amount_currency': 200.0, }), # Rate is 20 GOL = 1 USD in 2017. (0, 0, { 'account_id': self.company_data['default_account_receivable'].id, 'partner_id': partner.id, 'currency_id': self.currency_data_2['currency'].id, 'debit': 14.0, 'credit': 0.0, 'amount_currency': 280.0, }), # Line to balance the journal entry: (0, 0, { 'account_id': self.company_data['default_account_revenue'].id, 'debit': 0.0, 'credit': 114.0, }), ], }) move.action_post() move_line_1 = move.line_ids.filtered(lambda line: line.debit == 100.0) move_line_2 = move.line_ids.filtered(lambda line: line.debit == 14.0) self._check_statement_matching(matching_rule, { statement_line.id: {'aml_ids': (move_line_1 + move_line_2).ids, 'model': matching_rule, 'partner': statement_line.partner_id} }, statements=statement) @freeze_time('2020-01-01') def test_inv_matching_with_write_off(self): self.rule_1.payment_tolerance_param = 10.0 self.bank_st.line_ids[1].unlink() # We don't need this one here statement_line = self.bank_st.line_ids[0] statement_line.write({ 'payment_ref': self.invoice_line_1.move_id.payment_reference, 'amount': 90, }) # Test the invoice-matching part self._check_statement_matching(self.rule_1, { statement_line.id: {'aml_ids': self.invoice_line_1.ids, 'model': self.rule_1, 'partner': self.invoice_line_1.partner_id, 'status': 'write_off'}, }, self.bank_st) # Test the write-off part expected_write_off = { 'balance': 10, 'currency_id': self.company_data['currency'].id, 'reconcile_model_id': self.rule_1.id, 'account_id': self.current_assets_account.id, } matching_result = self.rule_1._apply_rules(statement_line) self.assertEqual(len(matching_result[statement_line.id].get('write_off_vals', [])), 1, "Exactly one write-off line should be proposed.") full_write_off_dict = matching_result[statement_line.id]['write_off_vals'][0] to_compare = {key: full_write_off_dict[key] for key in expected_write_off} self.assertDictEqual(expected_write_off, to_compare) @freeze_time('2020-01-01') def test_matching_with_write_off_foreign_currency(self): journal_foreign_curr = self.company_data['default_journal_bank'].copy() journal_foreign_curr.currency_id = self.currency_data['currency'] reco_model = self._create_reconcile_model( auto_reconcile=True, rule_type='writeoff_suggestion', line_ids=[{ 'amount_type': 'percentage', 'amount': 100.0, 'account_id': self.company_data['default_account_revenue'].id, }], ) st_line = self._create_st_line(amount=100.0, payment_ref='123456', journal_id=journal_foreign_curr.id) reco_model._apply_rules(st_line) self.assertRecordValues(st_line, [{'is_reconciled': True}]) self.assertRecordValues(st_line.line_ids.sorted('amount_currency'), [ {'amount_currency': -100.0, 'currency_id': self.currency_data['currency'].id, 'balance': -50.0}, {'amount_currency': 100.0, 'currency_id': self.currency_data['currency'].id, 'balance': 50.0}, ]) def test_inv_matching_with_write_off_autoreconcile(self): self.bank_line_1.amount = 95 self.rule_1.sequence = 2 self.rule_1.auto_reconcile = True self.rule_1.payment_tolerance_param = 10.0 self._check_statement_matching(self.rule_1, { self.bank_line_1.id: { 'aml_ids': self.invoice_line_1.ids, 'model': self.rule_1, 'status': 'reconciled', 'partner': self.bank_line_1.partner_id, }, self.bank_line_2.id: { 'aml_ids': (self.invoice_line_2 + self.invoice_line_3).ids, 'model': self.rule_1, 'partner': self.bank_line_2.partner_id, }, }, statements=self.bank_st) # Check first line has been properly reconciled. self.assertRecordValues(self.bank_line_1.line_ids, [ # pylint: disable=bad-whitespace {'partner_id': self.partner_1.id, 'debit': 95.0, 'credit': 0.0, 'account_id': self.bank_journal.default_account_id.id, 'reconciled': False}, {'partner_id': self.partner_1.id, 'debit': 5.0, 'credit': 0.0, 'account_id': self.current_assets_account.id, 'reconciled': False}, {'partner_id': self.partner_1.id, 'debit': 0.0, 'credit': 100.0, 'account_id': self.invoice_line_1.account_id.id, 'reconciled': True}, ]) self.assertEqual(self.invoice_line_1.amount_residual, 0.0, "The invoice should have been fully reconciled") def test_payment_similar_communications(self): def create_payment_line(amount, memo, partner): payment = self.env['account.payment'].create({ 'amount': amount, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': partner.id, 'ref': memo, 'destination_account_id': self.company_data['default_account_receivable'].id, }) payment.action_post() return payment.line_ids.filtered(lambda x: x.account_id.user_type_id.type not in {'receivable', 'payable'}) payment_partner = self.env['res.partner'].create({ 'name': "Bernard Gagnant", }) self.rule_1.match_partner_ids = [(6, 0, payment_partner.ids)] pmt_line_1 = create_payment_line(500, 'a1b2c3', payment_partner) pmt_line_2 = create_payment_line(500, 'a1b2c3', payment_partner) create_payment_line(500, 'd1e2f3', payment_partner) self.bank_line_1.write({ 'amount': 1000, 'payment_ref': 'a1b2c3', 'partner_id': payment_partner.id, }) self.bank_line_2.unlink() self.rule_1.allow_payment_tolerance = False self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': (pmt_line_1 + pmt_line_2).ids, 'model': self.rule_1, 'partner': payment_partner}, }, statements=self.bank_line_1.statement_id) def test_no_amount_check_keep_first(self): """ In case the reconciliation model doesn't check the total amount of the candidates, we still don't want to suggest more than are necessary to match the statement. For example, if a statement line amounts to 250 and is to be matched with three invoices of 100, 200 and 300 (retrieved in this order), only 100 and 200 should be proposed. """ self.rule_1.allow_payment_tolerance = False self.bank_line_2.amount = 250 self.bank_line_1.partner_id = None self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': [self.invoice_line_1.id, self.invoice_line_2.id], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, }, statements=self.bank_st) def test_no_amount_check_exact_match(self): """ If a reconciliation model finds enough candidates for a full reconciliation, it should still check the following candidates, in case one of them exactly matches the amount of the statement line. If such a candidate exist, all the other ones are disregarded. """ self.rule_1.allow_payment_tolerance = False self.bank_line_2.amount = 300 self.bank_line_1.partner_id = None self._check_statement_matching(self.rule_1, { self.bank_line_1.id: {'aml_ids': []}, self.bank_line_2.id: {'aml_ids': [self.invoice_line_3.id], 'model': self.rule_1, 'partner': self.bank_line_2.partner_id}, }, statements=self.bank_st) def test_matching_multi_currency_auto_validate(self): currency = self.setup_multi_currency_data( default_values={ 'name': 'Black Chocolate Coin', 'symbol': '🍫', 'currency_unit_label': 'Black Choco', 'currency_subunit_label': 'Black Cacao Powder', }, rate2016=11.2674, rate2017=11.2674, )['currency'] bank_journal = self.company_data['default_journal_bank'].copy() bank_journal.currency_id = currency invoice_line = self._create_invoice_line(100.0, self.partner_1, 'out_invoice', currency=currency) statement = self.env['account.bank.statement'].create({ 'name': 'test_matching_multi_currency_auto_validate', 'journal_id': bank_journal.id, 'line_ids': [ (0, 0, { 'journal_id': bank_journal.id, 'partner_id': self.partner_1.id, 'date': invoice_line.date, 'payment_ref': invoice_line.move_name, 'amount': invoice_line.amount_currency, }), ], }) statement_line = statement.line_ids statement.button_post() matching_rule = self.env['account.reconcile.model'].create({ 'name': 'test_matching_multi_currency_auto_validate', 'rule_type': 'invoice_matching', 'match_partner': True, 'match_partner_ids': [(6, 0, self.partner_1.ids)], 'allow_payment_tolerance': True, 'payment_tolerance_type': 'percentage', 'match_same_currency': True, 'past_months_limit': False, 'auto_reconcile': True, }) self._check_statement_matching( matching_rule, { statement_line.id: { 'aml_ids': invoice_line.ids, 'model': matching_rule, 'status': 'reconciled', 'partner': self.partner_1, }, }, statements=statement, ) self.assertRecordValues(statement_line.line_ids, [ # pylint: disable=bad-whitespace {'amount_currency': 100.0, 'debit': 8.88, 'credit': 0.0}, {'amount_currency': -100.0, 'debit': 0.0, 'credit': 8.88}, ])
46.79603
68,369
145,835
py
PYTHON
15.0
# -*- coding: utf-8 -*- # pylint: disable=C0326 from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo.tests.common import Form from odoo import fields, Command @tagged('post_install', '-at_install') class TestAccountMoveReconcile(AccountTestInvoicingCommon): ''' Tests about the account.partial.reconcile model, not the reconciliation itself but mainly the computation of the residual amounts on account.move.line. ''' @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.extra_receivable_account_1 = cls.copy_account(cls.company_data['default_account_receivable']) cls.extra_receivable_account_2 = cls.copy_account(cls.company_data['default_account_receivable']) cls.extra_payable_account_1 = cls.copy_account(cls.company_data['default_account_payable']) cls.extra_payable_account_2 = cls.copy_account(cls.company_data['default_account_payable']) # ==== Multi-currency setup ==== cls.currency_data_2 = cls.setup_multi_currency_data(default_values={ 'name': 'Diamond', 'symbol': '💎', 'currency_unit_label': 'Diamond', 'currency_subunit_label': 'Carbon', }, rate2016=6.0, rate2017=4.0) # ==== Cash Basis Taxes setup ==== cls.cash_basis_base_account = cls.env['account.account'].create({ 'code': 'cash_basis_base_account', 'name': 'cash_basis_base_account', 'user_type_id': cls.env.ref('account.data_account_type_revenue').id, 'company_id': cls.company_data['company'].id, }) cls.company_data['company'].account_cash_basis_base_account_id = cls.cash_basis_base_account cls.cash_basis_transfer_account = cls.env['account.account'].create({ 'code': 'cash_basis_transfer_account', 'name': 'cash_basis_transfer_account', 'user_type_id': cls.env.ref('account.data_account_type_revenue').id, 'company_id': cls.company_data['company'].id, }) cls.tax_account_1 = cls.env['account.account'].create({ 'code': 'tax_account_1', 'name': 'tax_account_1', 'user_type_id': cls.env.ref('account.data_account_type_revenue').id, 'company_id': cls.company_data['company'].id, }) cls.tax_account_2 = cls.env['account.account'].create({ 'code': 'tax_account_2', 'name': 'tax_account_2', 'user_type_id': cls.env.ref('account.data_account_type_revenue').id, 'company_id': cls.company_data['company'].id, }) cls.fake_country = cls.env['res.country'].create({ 'name': "The Island of the Fly", 'code': 'YY', }) cls.tax_tags = cls.env['account.account.tag'].create({ 'name': 'tax_tag_%s' % str(i), 'applicability': 'taxes', 'country_id': cls.company_data['company'].account_fiscal_country_id.id, } for i in range(8)) cls.cash_basis_tax_a_third_amount = cls.env['account.tax'].create({ 'name': 'tax_1', 'amount': 33.3333, 'company_id': cls.company_data['company'].id, 'cash_basis_transition_account_id': cls.cash_basis_transfer_account.id, 'tax_exigibility': 'on_payment', 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, cls.tax_tags[0].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_account_1.id, 'tag_ids': [(6, 0, cls.tax_tags[1].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, cls.tax_tags[2].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_account_1.id, 'tag_ids': [(6, 0, cls.tax_tags[3].ids)], }), ], }) cls.cash_basis_tax_tiny_amount = cls.env['account.tax'].create({ 'name': 'cash_basis_tax_tiny_amount', 'amount': 0.0001, 'company_id': cls.company_data['company'].id, 'cash_basis_transition_account_id': cls.cash_basis_transfer_account.id, 'tax_exigibility': 'on_payment', 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, cls.tax_tags[4].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_account_2.id, 'tag_ids': [(6, 0, cls.tax_tags[5].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, cls.tax_tags[6].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_account_2.id, 'tag_ids': [(6, 0, cls.tax_tags[7].ids)], }), ], }) # ------------------------------------------------------------------------- # HELPERS # ------------------------------------------------------------------------- def assertFullReconcile(self, full_reconcile, lines): exchange_difference_move = full_reconcile.exchange_move_id partials = lines.mapped('matched_debit_ids') + lines.mapped('matched_credit_ids') if full_reconcile.exchange_move_id: lines += exchange_difference_move.line_ids.filtered(lambda line: line.account_id == lines[0].account_id) # Use sets to not depend of the order. self.assertEqual(set(full_reconcile.partial_reconcile_ids), set(partials)) self.assertEqual(set(full_reconcile.reconciled_line_ids), set(lines)) # Ensure there is no residual amount left. self.assertRecordValues(lines, [{ 'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': bool(line.account_id.reconcile), } for line in lines]) def assertPartialReconcile(self, partials, expected_vals_list): partials = partials.sorted(lambda part: ( part.amount, part.debit_amount_currency, part.credit_amount_currency, )) self.assertRecordValues(partials, expected_vals_list) def assertAmountsGroupByAccount(self, amount_per_account): expected_values = {account.id: (account, balance, amount_currency) for account, balance, amount_currency in amount_per_account} if not expected_values: return self.cr.execute(''' SELECT line.account_id, COALESCE(SUM(line.balance), 0.0) AS total_balance, COALESCE(SUM(line.amount_currency), 0.0) AS total_amount_currency FROM account_move_line line WHERE line.account_id IN %s GROUP BY line.account_id ''', [tuple(expected_values.keys())]) for account_id, total_balance, total_amount_currency in self.cr.fetchall(): account, expected_balance, expected_amount_currency = expected_values[account_id] self.assertEqual( total_balance, expected_balance, "Balance of %s is incorrect" % account.name, ) self.assertEqual( total_amount_currency, expected_amount_currency, "Amount currency of %s is incorrect" % account.name, ) # ------------------------------------------------------------------------- # Test creation of account.partial.reconcile/account.full.reconcile # during the reconciliation. # ------------------------------------------------------------------------- def test_reconcile_single_currency(self): account_id = self.company_data['default_account_receivable'].id move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ (0, 0, {'debit': 1000.0, 'credit': 0.0, 'account_id': account_id}), (0, 0, {'debit': 200.0, 'credit': 0.0, 'account_id': account_id}), (0, 0, {'debit': 0.0, 'credit': 300.0, 'account_id': account_id}), (0, 0, {'debit': 0.0, 'credit': 400.0, 'account_id': account_id}), (0, 0, {'debit': 0.0, 'credit': 500.0, 'account_id': account_id}), ] }) move.action_post() line_1 = move.line_ids.filtered(lambda line: line.debit == 1000.0) line_2 = move.line_ids.filtered(lambda line: line.debit == 200.0) line_3 = move.line_ids.filtered(lambda line: line.credit == 300.0) line_4 = move.line_ids.filtered(lambda line: line.credit == 400.0) line_5 = move.line_ids.filtered(lambda line: line.credit == 500.0) self.assertRecordValues(line_1 + line_2 + line_3 + line_4 + line_5, [ {'amount_residual': 1000.0, 'amount_residual_currency': 1000.0, 'reconciled': False}, {'amount_residual': 200.0, 'amount_residual_currency': 200.0, 'reconciled': False}, {'amount_residual': -300.0, 'amount_residual_currency': -300.0, 'reconciled': False}, {'amount_residual': -400.0, 'amount_residual_currency': -400.0, 'reconciled': False}, {'amount_residual': -500.0, 'amount_residual_currency': -500.0, 'reconciled': False}, ]) res = (line_1 + line_3).reconcile() self.assertPartialReconcile(res['partials'], [{ 'amount': 300.0, 'debit_amount_currency': 300.0, 'credit_amount_currency': 300.0, 'debit_move_id': line_1.id, 'credit_move_id': line_3.id, }]) self.assertRecordValues(line_1 + line_3, [ {'amount_residual': 700.0, 'amount_residual_currency': 700.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) res = (line_1 + line_4).reconcile() self.assertPartialReconcile(res['partials'], [{ 'amount': 400.0, 'debit_amount_currency': 400.0, 'credit_amount_currency': 400.0, 'debit_move_id': line_1.id, 'credit_move_id': line_4.id, }]) self.assertRecordValues(line_1 + line_4, [ {'amount_residual': 300.0, 'amount_residual_currency': 300.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) res = (line_1 + line_5).reconcile() self.assertPartialReconcile(res['partials'], [{ 'amount': 300.0, 'debit_amount_currency': 300.0, 'credit_amount_currency': 300.0, 'debit_move_id': line_1.id, 'credit_move_id': line_5.id, }]) self.assertRecordValues(line_1 + line_5, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': -200.0, 'amount_residual_currency': -200.0, 'reconciled': False}, ]) res = (line_2 + line_5).reconcile() self.assertPartialReconcile(res['partials'], [{ 'amount': 200.0, 'debit_amount_currency': 200.0, 'credit_amount_currency': 200.0, 'debit_move_id': line_2.id, 'credit_move_id': line_5.id, }]) self.assertRecordValues(res['full_reconcile'], [{'exchange_move_id': False}]) self.assertFullReconcile(res['full_reconcile'], line_1 + line_2 + line_3 + line_4 + line_5) def test_reconcile_same_foreign_currency(self): account_id = self.company_data['default_account_receivable'].id # Rate is 3.0 in 2016, 2.0 in 2017. currency_id = self.currency_data['currency'].id moves = self.env['account.move'].create([ { 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ (0, 0, {'debit': 1200.0, 'credit': 0.0, 'amount_currency': 3600.0, 'account_id': account_id, 'currency_id': currency_id}), (0, 0, {'debit': 120.0, 'credit': 0.0, 'amount_currency': 360.0, 'account_id': account_id, 'currency_id': currency_id}), (0, 0, {'debit': 0.0, 'credit': 1320.0, 'account_id': account_id}), ] }, { 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 240.0, 'amount_currency': -480.0, 'account_id': account_id, 'currency_id': currency_id}), (0, 0, {'debit': 0.0, 'credit': 720.0, 'amount_currency': -1440.0, 'account_id': account_id, 'currency_id': currency_id}), (0, 0, {'debit': 0.0, 'credit': 1020.0, 'amount_currency': -2040.0, 'account_id': account_id, 'currency_id': currency_id}), (0, 0, {'debit': 1980.0, 'credit': 0.0, 'account_id': account_id}), ] } ]) moves.action_post() line_1 = moves.line_ids.filtered(lambda line: line.debit == 1200.0) line_2 = moves.line_ids.filtered(lambda line: line.debit == 120.0) line_3 = moves.line_ids.filtered(lambda line: line.credit == 240.0) line_4 = moves.line_ids.filtered(lambda line: line.credit == 720.0) line_5 = moves.line_ids.filtered(lambda line: line.credit == 1020.0) self.assertRecordValues(line_1 + line_2 + line_3 + line_4 + line_5, [ {'amount_residual': 1200.0, 'amount_residual_currency': 3600.0, 'reconciled': False}, {'amount_residual': 120.0, 'amount_residual_currency': 360.0, 'reconciled': False}, {'amount_residual': -240.0, 'amount_residual_currency': -480.0, 'reconciled': False}, {'amount_residual': -720.0, 'amount_residual_currency': -1440.0, 'reconciled': False}, {'amount_residual': -1020.0, 'amount_residual_currency': -2040.0, 'reconciled': False}, ]) res = (line_1 + line_3 + line_4).reconcile() self.assertPartialReconcile(res['partials'], [ # Partial generated when reconciling line_1 & line_3: { 'amount': 240.0, 'debit_amount_currency': 480.0, 'credit_amount_currency': 480.0, 'debit_move_id': line_1.id, 'credit_move_id': line_3.id, }, # Partial generated when reconciling line_1 & line_4: { 'amount': 720.0, 'debit_amount_currency': 1440.0, 'credit_amount_currency': 1440.0, 'debit_move_id': line_1.id, 'credit_move_id': line_4.id, }, ]) self.assertRecordValues(line_1 + line_3 + line_4, [ {'amount_residual': 240.0, 'amount_residual_currency': 1680.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) res = (line_1 + line_5).reconcile() self.assertPartialReconcile(res['partials'], [{ 'amount': 240.0, 'debit_amount_currency': 1680.0, 'credit_amount_currency': 1680.0, 'debit_move_id': line_1.id, 'credit_move_id': line_5.id, }]) self.assertRecordValues(line_1 + line_5, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': -780.0, 'amount_residual_currency': -360.0, 'reconciled': False}, ]) res = (line_2 + line_5).reconcile() exchange_diff = res['full_reconcile'].exchange_move_id exchange_diff_lines = exchange_diff.line_ids.sorted(lambda line: (line.currency_id, abs(line.amount_currency), -line.amount_currency)) self.assertRecordValues(exchange_diff_lines, [ # Fix line_2: { 'debit': 660.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': currency_id, 'account_id': account_id, }, { 'debit': 0.0, 'credit': 660.0, 'amount_currency': 0.0, 'currency_id': currency_id, 'account_id': exchange_diff.journal_id.company_id.income_currency_exchange_account_id.id, }, ]) self.assertPartialReconcile(res['partials'], [ # Partial generated when reconciling line_2 & line_5: { 'amount': 120.0, 'debit_amount_currency': 360.0, 'credit_amount_currency': 360.0, 'debit_move_id': line_2.id, 'credit_move_id': line_5.id, }, # Partial fixing line_4 (exchange difference): { 'amount': 660.0, 'debit_amount_currency': 0.0, 'credit_amount_currency': 0.0, 'debit_move_id': exchange_diff_lines[0].id, 'credit_move_id': line_5.id, }, ]) self.assertFullReconcile(res['full_reconcile'], line_1 + line_2 + line_3 + line_4 + line_5) def test_reconcile_multiple_currencies(self): account_id = self.company_data['default_account_receivable'].id # Rate is 3.0 in 2016, 2.0 in 2017. currency1_id = self.currency_data['currency'].id # Rate is 6.0 in 2016, 4.0 in 2017. currency2_id = self.currency_data_2['currency'].id moves = self.env['account.move'].create([ { 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ (0, 0, {'debit': 1200.0, 'credit': 0.0, 'amount_currency': 3600.0, 'account_id': account_id, 'currency_id': currency1_id}), (0, 0, {'debit': 780.0, 'credit': 0.0, 'amount_currency': 2340.0, 'account_id': account_id, 'currency_id': currency1_id}), (0, 0, {'debit': 0.0, 'credit': 1980.0, 'account_id': account_id}), ] }, { 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 240.0, 'amount_currency': -960.0, 'account_id': account_id, 'currency_id': currency2_id}), (0, 0, {'debit': 0.0, 'credit': 720.0, 'amount_currency': -2880.0, 'account_id': account_id, 'currency_id': currency2_id}), (0, 0, {'debit': 0.0, 'credit': 1020.0, 'amount_currency': -4080.0, 'account_id': account_id, 'currency_id': currency2_id}), (0, 0, {'debit': 1980.0, 'credit': 0.0, 'account_id': account_id}), ] } ]) moves.action_post() line_1 = moves.line_ids.filtered(lambda line: line.debit == 1200.0) line_2 = moves.line_ids.filtered(lambda line: line.debit == 780.0) line_3 = moves.line_ids.filtered(lambda line: line.credit == 240.0) line_4 = moves.line_ids.filtered(lambda line: line.credit == 720.0) line_5 = moves.line_ids.filtered(lambda line: line.credit == 1020.0) self.assertRecordValues(line_1 + line_2 + line_3 + line_4 + line_5, [ {'amount_residual': 1200.0, 'amount_residual_currency': 3600.0, 'reconciled': False}, {'amount_residual': 780.0, 'amount_residual_currency': 2340.0, 'reconciled': False}, {'amount_residual': -240.0, 'amount_residual_currency': -960.0, 'reconciled': False}, {'amount_residual': -720.0, 'amount_residual_currency': -2880.0, 'reconciled': False}, {'amount_residual': -1020.0, 'amount_residual_currency': -4080.0, 'reconciled': False}, ]) res = (line_1 + line_3 + line_4).reconcile() self.assertPartialReconcile(res['partials'], [ # Partial generated when reconciling line_1 & line_3: { 'amount': 240.0, 'debit_amount_currency': 480.0, 'credit_amount_currency': 1440.0, 'debit_move_id': line_1.id, 'credit_move_id': line_3.id, }, # Partial generated when reconciling line_1 & line_4: { 'amount': 720.0, 'debit_amount_currency': 1440.0, 'credit_amount_currency': 4320.0, 'debit_move_id': line_1.id, 'credit_move_id': line_4.id, }, ]) self.assertRecordValues(line_1 + line_3 + line_4, [ {'amount_residual': 240.0, 'amount_residual_currency': 1680.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 480.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 1440.0, 'reconciled': False}, ]) res = (line_1 + line_5).reconcile() self.assertPartialReconcile(res['partials'], [{ 'amount': 240.0, 'debit_amount_currency': 480.0, 'credit_amount_currency': 1440.0, 'debit_move_id': line_1.id, 'credit_move_id': line_5.id, }]) self.assertRecordValues(line_1 + line_5, [ {'amount_residual': 0.0, 'amount_residual_currency': 1200.0, 'reconciled': False}, {'amount_residual': -780.0, 'amount_residual_currency': -2640.0, 'reconciled': False}, ]) res = (line_2 + line_5).reconcile() exchange_diff = res['full_reconcile'].exchange_move_id exchange_diff_lines = exchange_diff.line_ids.sorted(lambda line: (line.currency_id, abs(line.amount_currency), -line.amount_currency)) self.assertRecordValues(exchange_diff_lines, [ # Fix line_2: { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 780.0, 'currency_id': currency1_id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -780.0, 'currency_id': currency1_id, 'account_id': account_id, }, # Fix line_3: { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 480.0, 'currency_id': currency2_id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -480.0, 'currency_id': currency2_id, 'account_id': account_id, }, # Fix line_4: { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 1440.0, 'currency_id': currency2_id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -1440.0, 'currency_id': currency2_id, 'account_id': account_id, }, # Fix line_5: { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 2040.0, 'currency_id': currency2_id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -2040.0, 'currency_id': currency2_id, 'account_id': account_id, }, # Fix line_1: { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 1200.0, 'currency_id': currency1_id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -1200.0, 'currency_id': currency1_id, 'account_id': account_id, }, ]) self.assertPartialReconcile(res['partials'], [ # Partial fixing line_3 (exchange difference): { 'amount': 0.0, 'debit_amount_currency': 480.0, 'credit_amount_currency': 480.0, 'debit_move_id': line_3.id, 'credit_move_id': exchange_diff_lines[3].id, }, # Partial fixing line_2 (exchange difference): { 'amount': 0.0, 'debit_amount_currency': 780.0, 'credit_amount_currency': 780.0, 'debit_move_id': line_2.id, 'credit_move_id': exchange_diff_lines[1].id, }, # Partial fixing line_1 (exchange difference): { 'amount': 0.0, 'debit_amount_currency': 1200.0, 'credit_amount_currency': 1200.0, 'debit_move_id': line_1.id, 'credit_move_id': exchange_diff_lines[9].id, }, # Partial fixing line_4 (exchange difference): { 'amount': 0.0, 'debit_amount_currency': 1440.0, 'credit_amount_currency': 1440.0, 'debit_move_id': line_4.id, 'credit_move_id': exchange_diff_lines[5].id, }, # Partial fixing line_5 (exchange difference): { 'amount': 0.0, 'debit_amount_currency': 2040.0, 'credit_amount_currency': 2040.0, 'debit_move_id': line_5.id, 'credit_move_id': exchange_diff_lines[7].id, }, # Partial generated when reconciling line_2 & line_5: { 'amount': 780.0, 'debit_amount_currency': 1560.0, 'credit_amount_currency': 4680.0, 'debit_move_id': line_2.id, 'credit_move_id': line_5.id, }, ]) self.assertFullReconcile(res['full_reconcile'], line_1 + line_2 + line_3 + line_4 + line_5) def test_reconcile_asymetric_rate_change(self): account_id = self.company_data['default_account_receivable'].id # Rate is 3.0 in 2016, 2.0 in 2017. currency1_id = self.currency_data['currency'].id # Rate is 6.0 in 2016, 4.0 in 2017. currency2_id = self.currency_data_2['currency'].id # Create rate changes for 2018: currency1 rate increases while currency2 rate decreases. self.env['res.currency.rate'].create({ 'name': '2018-01-01', 'rate': 8.0, 'currency_id': currency1_id, 'company_id': self.company_data['company'].id, }) self.env['res.currency.rate'].create({ 'name': '2018-01-01', 'rate': 2.0, 'currency_id': currency2_id, 'company_id': self.company_data['company'].id, }) moves = self.env['account.move'].create([ { 'move_type': 'entry', 'date': '2018-01-01', 'line_ids': [ (0, 0, { 'debit': 1200.0, 'credit': 0.0, 'amount_currency': 9600.0, 'account_id': account_id, 'currency_id': currency1_id, }), (0, 0, { 'debit': 960.0, 'credit': 0.0, 'amount_currency': 1920.0, 'account_id': account_id, 'currency_id': currency2_id, }), (0, 0, { 'debit': 0.0, 'credit': 2160.0, 'account_id': account_id, }), ] }, { 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, { 'debit': 0.0, 'credit': 1200.0, 'amount_currency': -4800.0, 'account_id': account_id, 'currency_id': currency2_id, }), (0, 0, { 'debit': 0.0, 'credit': 960.0, 'amount_currency': -1920.0, 'account_id': account_id, 'currency_id': currency1_id, }), (0, 0, { 'debit': 2160.0, 'credit': 0.0, 'account_id': account_id, }), ] } ]) moves.action_post() line_1 = moves.line_ids.filtered(lambda line: line.debit == 1200.0) line_2 = moves.line_ids.filtered(lambda line: line.debit == 960.0) line_3 = moves.line_ids.filtered(lambda line: line.credit == 1200.0) line_4 = moves.line_ids.filtered(lambda line: line.credit == 960.0) self.assertRecordValues(line_1 + line_2 + line_3 + line_4, [ {'amount_residual': 1200.0, 'amount_residual_currency': 9600.0, 'reconciled': False}, {'amount_residual': 960.0, 'amount_residual_currency': 1920.0, 'reconciled': False}, {'amount_residual': -1200.0, 'amount_residual_currency': -4800.0, 'reconciled': False}, {'amount_residual': -960.0, 'amount_residual_currency': -1920.0, 'reconciled': False}, ]) # Reconcile with debit_line currency rate increased and credit_line currency rate decreased between # credit_line.date and debit_line.date. res = (line_1 + line_3).reconcile() exchange_diff = res['full_reconcile'].exchange_move_id exchange_diff_lines = exchange_diff.line_ids.sorted(lambda line: (line.currency_id, abs(line.amount_currency), -line.amount_currency)) self.assertRecordValues(exchange_diff_lines, [ { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 2400.0, 'currency_id': currency2_id, 'account_id': account_id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -2400.0, 'currency_id': currency2_id, 'account_id': exchange_diff.journal_id.company_id.income_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 7200.0, 'currency_id': currency1_id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -7200.0, 'currency_id': currency1_id, 'account_id': account_id, } ]) self.assertPartialReconcile(res['partials'], [ { 'amount': 0.0, 'debit_amount_currency': 2400.0, 'credit_amount_currency': 2400.0, 'debit_move_id': exchange_diff_lines[0].id, 'credit_move_id': line_3.id, }, { 'amount': 0.0, 'debit_amount_currency': 7200.0, 'credit_amount_currency': 7200.0, 'debit_move_id': line_1.id, 'credit_move_id': exchange_diff_lines[3].id, }, { 'amount': 1200.0, 'debit_amount_currency': 2400.0, 'credit_amount_currency': 2400.0, 'debit_move_id': line_1.id, 'credit_move_id': line_3.id, }, ]) self.assertRecordValues(line_1 + line_3, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) # Reconcile with debit_line currency rate decreased and credit_line currency rate increased between # credit_line.date and debit_line.date. res = (line_2 + line_4).reconcile() exchange_diff = res['full_reconcile'].exchange_move_id exchange_diff_lines = exchange_diff.line_ids.sorted(lambda line: (line.currency_id, abs(line.amount_currency), -line.amount_currency)) self.assertRecordValues(exchange_diff_lines, [ { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 5760.0, 'currency_id': currency1_id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -5760.0, 'currency_id': currency1_id, 'account_id': account_id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 1920.0, 'currency_id': currency2_id, 'account_id': account_id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -1920.0, 'currency_id': currency2_id, 'account_id': exchange_diff.journal_id.company_id.income_currency_exchange_account_id.id, } ]) self.assertPartialReconcile(res['partials'], [ { 'amount': 0.0, 'debit_amount_currency': 1920.0, 'credit_amount_currency': 1920.0, 'debit_move_id': exchange_diff_lines[2].id, 'credit_move_id': line_2.id, }, { 'amount': 0.0, 'debit_amount_currency': 5760.0, 'credit_amount_currency': 5760.0, 'debit_move_id': line_4.id, 'credit_move_id': exchange_diff_lines[1].id, }, { 'amount': 960.0, 'debit_amount_currency': 3840.0, 'credit_amount_currency': 7680.0, 'debit_move_id': line_2.id, 'credit_move_id': line_4.id, }, ]) self.assertRecordValues(line_2 + line_4, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) def test_reverse_with_multiple_lines(self): """ Test if all lines from a reversed entry are fully reconciled """ move = self.env['account.move'].create({ 'move_type': 'entry', 'line_ids': [ (0, 0, { 'debit': 1200.0, 'credit': 0.0, 'amount_currency': 3600.0, 'account_id': self.company_data['default_account_receivable'].id, }), (0, 0, { 'debit': 0.0, 'credit': 200.0, 'account_id': self.company_data['default_account_payable'].id, }), (0, 0, { 'debit': 0.0, 'credit': 400.0, 'account_id': self.company_data['default_account_payable'].id, }), (0, 0, { 'debit': 0.0, 'credit': 600.0, 'account_id': self.company_data['default_account_payable'].id, }), ], }) move.action_post() lines_to_reconcile = move.line_ids.filtered(lambda x: (x.account_id.reconcile or x.account_id.internal_type == 'liquidity') and not x.reconciled) self.assertRecordValues(lines_to_reconcile, [ {'debit': 1200.0, 'credit': 0.0, 'reconciled': False}, {'debit': 0.0, 'credit': 200.0, 'reconciled': False}, {'debit': 0.0, 'credit': 400.0, 'reconciled': False}, {'debit': 0.0, 'credit': 600.0, 'reconciled': False}, ]) reversed_move = move._reverse_moves(cancel=True) reversed_lines = reversed_move.line_ids.filtered(lambda x: ( x.account_id.reconcile or x.account_id.internal_type == 'liquidity' )) self.assertRecordValues(reversed_lines, [ {'debit': 0.0, 'credit': 1200.0, 'reconciled': True}, {'debit': 200.0, 'credit': 0.0, 'reconciled': True}, {'debit': 400.0, 'credit': 0.0, 'reconciled': True}, {'debit': 600.0, 'credit': 0.0, 'reconciled': True}, ]) self.assertTrue(all([line.full_reconcile_id for line in reversed_lines])) def test_reverse_exchange_difference_same_foreign_currency(self): move_2016 = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ (0, 0, { 'debit': 1200.0, 'credit': 0.0, 'amount_currency': 3600.0, 'account_id': self.company_data['default_account_receivable'].id, 'currency_id': self.currency_data['currency'].id, }), (0, 0, { 'debit': 0.0, 'credit': 1200.0, 'account_id': self.company_data['default_account_revenue'].id, }), ], }) move_2017 = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, { 'debit': 0.0, 'credit': 1800.0, 'amount_currency': -3600.0, 'account_id': self.company_data['default_account_receivable'].id, 'currency_id': self.currency_data['currency'].id, }), (0, 0, { 'debit': 1800.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, }), ], }) (move_2016 + move_2017).action_post() rec_line_2016 = move_2016.line_ids.filtered(lambda line: line.account_id.internal_type == 'receivable') rec_line_2017 = move_2017.line_ids.filtered(lambda line: line.account_id.internal_type == 'receivable') self.assertRecordValues(rec_line_2016 + rec_line_2017, [ {'amount_residual': 1200.0, 'amount_residual_currency': 3600.0, 'reconciled': False}, {'amount_residual': -1800.0, 'amount_residual_currency': -3600.0, 'reconciled': False}, ]) # Reconcile. res = (rec_line_2016 + rec_line_2017).reconcile() self.assertRecordValues(rec_line_2016 + rec_line_2017, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) exchange_diff = res['full_reconcile'].exchange_move_id exchange_diff_lines = exchange_diff.line_ids.sorted('balance') self.assertRecordValues(exchange_diff_lines, [ { 'debit': 0.0, 'credit': 600.0, 'amount_currency': 0.0, 'currency_id': self.currency_data['currency'].id, 'account_id': exchange_diff.journal_id.company_id.income_currency_exchange_account_id.id, }, { 'debit': 600.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': self.currency_data['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, }, ]) self.assertRecordValues(exchange_diff_lines, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) # Unreconcile. # A reversal is created to cancel the exchange difference journal entry. (rec_line_2016 + rec_line_2017).remove_move_reconcile() reverse_exchange_diff = exchange_diff_lines[1].matched_credit_ids.credit_move_id.move_id reverse_exchange_diff_lines = reverse_exchange_diff.line_ids.sorted('balance') self.assertRecordValues(reverse_exchange_diff_lines, [ { 'debit': 0.0, 'credit': 600.0, 'amount_currency': 0.0, 'currency_id': self.currency_data['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, }, { 'debit': 600.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': self.currency_data['currency'].id, 'account_id': exchange_diff.journal_id.company_id.income_currency_exchange_account_id.id, }, ]) self.assertRecordValues(exchange_diff_lines + reverse_exchange_diff_lines, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, ]) partials = reverse_exchange_diff_lines.matched_debit_ids + reverse_exchange_diff_lines.matched_credit_ids self.assertPartialReconcile(partials, [{ 'amount': 600.0, 'debit_amount_currency': 0.0, 'credit_amount_currency': 0.0, 'debit_move_id': exchange_diff_lines[1].id, 'credit_move_id': reverse_exchange_diff_lines[0].id, }]) def test_reverse_exchange_multiple_foreign_currencies(self): move_2016 = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ (0, 0, { 'debit': 1200.0, 'credit': 0.0, 'amount_currency': 7200.0, 'account_id': self.company_data['default_account_receivable'].id, 'currency_id': self.currency_data_2['currency'].id, }), (0, 0, { 'debit': 0.0, 'credit': 1200.0, 'account_id': self.company_data['default_account_revenue'].id, }), ], }) move_2017 = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, { 'debit': 0.0, 'credit': 1200.0, 'amount_currency': -2400.0, 'account_id': self.company_data['default_account_receivable'].id, 'currency_id': self.currency_data['currency'].id, }), (0, 0, { 'debit': 1200.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, }), ], }) (move_2016 + move_2017).action_post() rec_line_2016 = move_2016.line_ids.filtered(lambda line: line.account_id.internal_type == 'receivable') rec_line_2017 = move_2017.line_ids.filtered(lambda line: line.account_id.internal_type == 'receivable') self.assertRecordValues(rec_line_2016 + rec_line_2017, [ {'amount_residual': 1200.0, 'amount_residual_currency': 7200.0, 'reconciled': False}, {'amount_residual': -1200.0, 'amount_residual_currency': -2400.0, 'reconciled': False}, ]) # Reconcile. res = (rec_line_2016 + rec_line_2017).reconcile() self.assertRecordValues(rec_line_2016 + rec_line_2017, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) exchange_diff = res['full_reconcile'].exchange_move_id exchange_diff_lines = exchange_diff.line_ids.sorted('amount_currency') self.assertRecordValues(exchange_diff_lines, [ { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -2400.0, 'currency_id': self.currency_data_2['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -1200.0, 'currency_id': self.currency_data['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 1200.0, 'currency_id': self.currency_data['currency'].id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 2400.0, 'currency_id': self.currency_data_2['currency'].id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, ]) self.assertRecordValues(exchange_diff_lines, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, ]) # Unreconcile. # A reversal is created to cancel the exchange difference journal entry. (rec_line_2016 + rec_line_2017).remove_move_reconcile() reverse_exchange_diff = exchange_diff_lines[1].matched_debit_ids.debit_move_id.move_id reverse_exchange_diff_lines = reverse_exchange_diff.line_ids.sorted('amount_currency') self.assertRecordValues(reverse_exchange_diff_lines, [ { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -2400.0, 'currency_id': self.currency_data_2['currency'].id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': -1200.0, 'currency_id': self.currency_data['currency'].id, 'account_id': exchange_diff.journal_id.company_id.expense_currency_exchange_account_id.id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 1200.0, 'currency_id': self.currency_data['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, }, { 'debit': 0.0, 'credit': 0.0, 'amount_currency': 2400.0, 'currency_id': self.currency_data_2['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, }, ]) self.assertRecordValues(exchange_diff_lines + reverse_exchange_diff_lines, [ {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': False}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, {'amount_residual': 0.0, 'amount_residual_currency': 0.0, 'reconciled': True}, ]) partials = reverse_exchange_diff_lines.matched_debit_ids + reverse_exchange_diff_lines.matched_credit_ids self.assertPartialReconcile(partials, [ { 'amount': 0.0, 'debit_amount_currency': 1200.0, 'credit_amount_currency': 1200.0, 'debit_move_id': reverse_exchange_diff_lines[2].id, 'credit_move_id': exchange_diff_lines[1].id, }, { 'amount': 0.0, 'debit_amount_currency': 2400.0, 'credit_amount_currency': 2400.0, 'debit_move_id': reverse_exchange_diff_lines[3].id, 'credit_move_id': exchange_diff_lines[0].id, }, ]) def test_reconcile_rounding_issue(self): rate = 1/1.5289 currency = self.setup_multi_currency_data(default_values={ 'name': 'XXX', 'symbol': 'XXX', 'currency_unit_label': 'XX', 'currency_subunit_label': 'X', 'rounding': 0.01, }, rate2016=rate, rate2017=rate)['currency'] # Create an invoice 26.45 XXX = 40.43 USD invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'currency_id': currency.id, 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'price_unit': 23.0, 'tax_ids': [(6, 0, self.company_data['default_tax_sale'].ids)], })], }) invoice.action_post() # Pay it with 100.0 USD self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=invoice.ids)\ .create({'amount': 100.0, 'currency_id': self.company_data['currency'].id})\ ._create_payments() self.assertTrue(invoice.payment_state in ('in_payment', 'paid')) # ------------------------------------------------------------------------- # Test creation of extra journal entries during the reconciliation to # deal with taxes that are exigible on payment (cash basis). # ------------------------------------------------------------------------- def test_reconcile_cash_basis_workflow_single_currency(self): ''' Test the generated journal entries during the reconciliation to manage the cash basis taxes. Also, - Test the case when there is multiple receivable/payable accounts. - Test the reconciliation with tiny amounts. - Check there is no rounding issue when making the percentage. - Check there is no lost cents when the journal entry is fully reconciled. ''' self.env.company.tax_exigibility = True cash_basis_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 100.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, (self.cash_basis_tax_a_third_amount + self.cash_basis_tax_tiny_amount).ids)], }), # Tax lines (0, 0, { 'debit': 0.0, 'credit': 33.33, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), (0, 0, { 'debit': 0.0, 'credit': 0.01, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_tiny_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable lines (0, 0, { 'debit': 44.45, 'credit': 0.0, 'account_id': self.extra_receivable_account_1.id, }), (0, 0, { 'debit': 44.45, 'credit': 0.0, 'account_id': self.extra_receivable_account_2.id, }), (0, 0, { 'debit': 44.45, 'credit': 0.0, 'account_id': self.extra_receivable_account_2.id, }), (0, 0, { 'debit': 0.0, 'credit': 0.01, 'account_id': self.extra_payable_account_1.id, }), ] }) payment_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 33.34, 'account_id': self.extra_receivable_account_1.id}), (0, 0, {'debit': 0.0, 'credit': 11.11, 'account_id': self.extra_receivable_account_1.id}), (0, 0, {'debit': 0.0, 'credit': 88.89, 'account_id': self.extra_receivable_account_2.id}), (0, 0, {'debit': 0.0, 'credit': 0.01, 'account_id': self.extra_receivable_account_2.id}), (0, 0, {'debit': 0.01, 'credit': 0.0, 'account_id': self.extra_payable_account_1.id}), (0, 0, {'debit': 133.34, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id}), ] }) (cash_basis_move + payment_move).action_post() # Initial amounts by accounts: self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, -33.34, -33.34), (self.tax_account_1, 0.0, 0.0), (self.tax_account_2, 0.0, 0.0), (self.cash_basis_base_account, 0.0, 0.0), ]) # There is 44.45 + 44.45 + 44.45 + 0.01 = 133.36 to reconcile on 'cash_basis_move'. # Reconciling all the amount in extra_receivable_account_1 should compute 2 percentages: # 33.34 / 133.36 = 0.25 # 11.11 / 133.36 = 0.083308338 receivable_lines_1 = (cash_basis_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_1) res = receivable_lines_1.reconcile() self.assertFullReconcile(res['full_reconcile'], receivable_lines_1) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 2) self.assertRecordValues(res['tax_cash_basis_moves'][0].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 25.0, 'credit': 0.0, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 25.0, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 8.33, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 8.33, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'account_id': self.tax_account_2.id}, ]) self.assertRecordValues(res['tax_cash_basis_moves'][1].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 8.33, 'credit': 0.0, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 8.33, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 2.78, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 2.78, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'account_id': self.tax_account_2.id}, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, -22.23, -22.23), (self.tax_account_1, -11.11, -11.11), (self.tax_account_2, 0.0, 0.0), ]) # Reconciling all the amount in extra_receivable_account_2 should compute 3 percentages: # 44.45 / 133.36 = 0.333308338 # 44.44 / 133.36 = 0.333233353 # 0.01 / 133.36 = 0.000074985 receivable_lines_2 = (cash_basis_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_2) res = receivable_lines_2.reconcile() self.assertFullReconcile(res['full_reconcile'], receivable_lines_2) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 3) self.assertRecordValues(res['tax_cash_basis_moves'][0].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 33.33, 'credit': 0.0, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 33.33, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 11.11, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 11.11, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'account_id': self.tax_account_2.id}, ]) self.assertRecordValues(res['tax_cash_basis_moves'][1].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 33.32, 'credit': 0.0, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 33.32, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 11.11, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 11.11, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'account_id': self.tax_account_2.id}, ]) self.assertRecordValues(res['tax_cash_basis_moves'][2].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 0.01, 'credit': 0.0, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 0.01, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 0.0, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'account_id': self.tax_account_2.id}, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, -0.01, -0.01), (self.tax_account_1, -33.33, -33.33), (self.tax_account_2, 0.0, 0.0), ]) # Reconciling all the amount in extra_payable_account_1 should trigger the matching number and ensure all # the base amount has been covered without any rounding issue. payable_lines_1 = (cash_basis_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_payable_account_1) res = payable_lines_1.reconcile() self.assertFullReconcile(res['full_reconcile'], payable_lines_1) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 1) self.assertRecordValues(res['tax_cash_basis_moves'].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 0.01, 'credit': 0.0, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 0.01, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 0.0, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'account_id': self.tax_account_2.id}, ]) self.assertRecordValues(res['full_reconcile'].exchange_move_id.line_ids, [ {'account_id': self.tax_account_2.id, 'debit': 0.0, 'credit': 0.01, 'tax_ids': [], 'tax_line_id': self.cash_basis_tax_tiny_amount.id}, {'account_id': self.cash_basis_transfer_account.id, 'debit': 0.01, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': False}, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, 0.0, 0.0), (self.tax_account_1, -33.33, -33.33), (self.tax_account_2, -0.01, -0.01), ]) def test_reconcile_cash_basis_workflow_multi_currency(self): ''' Same as before with a foreign currency. ''' self.env.company.tax_exigibility = True currency_id = self.currency_data['currency'].id taxes = self.cash_basis_tax_a_third_amount + self.cash_basis_tax_tiny_amount cash_basis_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 33.34, 'amount_currency': -100.0, 'currency_id': currency_id, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, taxes.ids)], }), # Tax lines (0, 0, { 'debit': 0.0, 'credit': 11.10, 'amount_currency': -33.33, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), (0, 0, { 'debit': 0.0, 'credit': 0.01, 'amount_currency': -0.01, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_tiny_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable lines (0, 0, { 'debit': 14.82, 'credit': 0.0, 'amount_currency': 44.45, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id, }), (0, 0, { 'debit': 14.82, 'credit': 0.0, 'amount_currency': 44.45, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_2.id, }), (0, 0, { 'debit': 14.82, 'credit': 0.0, 'amount_currency': 44.45, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_2.id, }), (0, 0, { 'debit': 0.0, 'credit': 0.01, 'amount_currency': -0.01, 'currency_id': currency_id, 'account_id': self.extra_payable_account_1.id, }), ] }) payment_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 16.67, 'amount_currency': -33.34, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id}), (0, 0, {'debit': 0.0, 'credit': 5.6, 'amount_currency': -11.11, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id}), (0, 0, {'debit': 0.0, 'credit': 44.45, 'amount_currency': -88.89, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_2.id}), (0, 0, {'debit': 0.0, 'credit': 0.01, 'amount_currency': -0.01, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_2.id}), (0, 0, {'debit': 0.01, 'credit': 0.0, 'amount_currency': 0.01, 'currency_id': currency_id, 'account_id': self.extra_payable_account_1.id}), (0, 0, {'debit': 66.72, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id}), ] }) (cash_basis_move + payment_move).action_post() # Initial amounts by accounts: self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, -11.11, -33.34), (self.tax_account_1, 0.0, 0.0), (self.tax_account_2, 0.0, 0.0), ]) # There is 44.45 + 44.45 + 44.45 + 0.01 = 133.36 to reconcile on 'cash_basis_move'. # Reconciling all the amount in extra_receivable_account_1 should compute 2 percentages: # 33.34 / 133.36 = 0.25 # 11.11 / 133.36 = 0.083308338 receivable_lines_1 = (cash_basis_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_1) res = receivable_lines_1.reconcile() self.assertFullReconcile(res['full_reconcile'], receivable_lines_1) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 2) self.assertRecordValues(res['tax_cash_basis_moves'][0].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 12.5, 'credit': 0.0, 'amount_currency': 25.0, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 12.5, 'amount_currency': -25.0, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 4.17, 'credit': 0.0, 'amount_currency': 8.333, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 4.17, 'amount_currency': -8.333, 'currency_id': currency_id, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.003, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': -0.003, 'currency_id': currency_id, 'account_id': self.tax_account_2.id}, ]) self.assertRecordValues(res['tax_cash_basis_moves'][1].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 4.2, 'credit': 0.0, 'amount_currency': 8.331, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 4.2, 'amount_currency': -8.331, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 1.4, 'credit': 0.0, 'amount_currency': 2.777, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 1.4, 'amount_currency': -2.777, 'currency_id': currency_id, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.001, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': -0.001, 'currency_id': currency_id, 'account_id': self.tax_account_2.id}, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, -5.54, -22.226), (self.tax_account_1, -5.57, -11.11), (self.tax_account_2, 0.0, -0.004), ]) # Reconciling all the amount in extra_receivable_account_2 should compute 3 percentages: # 44.45 / 133.36 = 0.333308338 # 44.44 / 133.36 = 0.333233353 # 0.01 / 133.36 = 0.000074985 receivable_lines_2 = (cash_basis_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_2) res = receivable_lines_2.reconcile() self.assertFullReconcile(res['full_reconcile'], receivable_lines_2) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 3) self.assertRecordValues(res['tax_cash_basis_moves'][0].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 16.67, 'credit': 0.0, 'amount_currency': 33.331, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 16.67, 'amount_currency': -33.331, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 5.56, 'credit': 0.0, 'amount_currency': 11.109, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 5.56, 'amount_currency': -11.109, 'currency_id': currency_id, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.003, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': -0.003, 'currency_id': currency_id, 'account_id': self.tax_account_2.id}, ]) self.assertRecordValues(res['tax_cash_basis_moves'][1].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 16.66, 'credit': 0.0, 'amount_currency': 33.323, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 16.66, 'amount_currency': -33.323, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 5.55, 'credit': 0.0, 'amount_currency': 11.107, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 5.55, 'amount_currency': -11.107, 'currency_id': currency_id, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.003, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': -0.003, 'currency_id': currency_id, 'account_id': self.tax_account_2.id}, ]) self.assertRecordValues(res['tax_cash_basis_moves'][2].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 0.01, 'credit': 0.0, 'amount_currency': 0.007, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 0.01, 'amount_currency': -0.007, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.002, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': -0.002, 'currency_id': currency_id, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': currency_id, 'account_id': self.tax_account_2.id}, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, 5.57, -0.002), (self.tax_account_1, -16.68, -33.328), (self.tax_account_2, 0.0, -0.01), ]) # Reconciling all the amount in extra_payable_account_1 should trigger the matching number and ensure all # the base amount has been covered without any rounding issue. payable_lines_1 = (cash_basis_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_payable_account_1) res = payable_lines_1.reconcile() self.assertFullReconcile(res['full_reconcile'], payable_lines_1) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 1) self.assertRecordValues(res['tax_cash_basis_moves'].line_ids, [ # Base amount of tax_1 & tax_2: {'debit': 0.01, 'credit': 0.0, 'amount_currency': 0.007, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 0.01, 'amount_currency': -0.007, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.002, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': -0.002, 'currency_id': currency_id, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': currency_id, 'account_id': self.tax_account_2.id}, ]) self.assertRecordValues(res['full_reconcile'].exchange_move_id.line_ids, [ {'account_id': self.cash_basis_base_account.id, 'debit': 16.71, 'credit': 0.0, 'tax_ids': taxes.ids, 'tax_line_id': False}, {'account_id': self.cash_basis_base_account.id, 'debit': 0.0, 'credit': 16.71, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.tax_account_1.id, 'debit': 5.58, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': self.cash_basis_tax_a_third_amount.id}, {'account_id': self.cash_basis_transfer_account.id, 'debit': 0.0, 'credit': 5.58, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.tax_account_2.id, 'debit': 0.0, 'credit': 0.01, 'tax_ids': [], 'tax_line_id': self.cash_basis_tax_tiny_amount.id}, {'account_id': self.cash_basis_transfer_account.id, 'debit': 0.01, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': False}, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, 0.0, 0.0), (self.tax_account_1, -11.1, -33.33), (self.tax_account_2, -0.01, -0.01), ]) def test_reconcile_cash_basis_exchange_difference_transfer_account_check_entries_1(self): ''' Test the generation of the exchange difference for a tax cash basis journal entry when the transfer account is not reconcilable. ''' self.env.company.tax_exigibility = True currency_id = self.currency_data['currency'].id # Rate 1/3 in 2016. cash_basis_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 100.0, 'amount_currency': -300.0, 'currency_id': currency_id, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], }), # Tax line (0, 0, { 'debit': 0.0, 'credit': 33.33, 'amount_currency': -100.0, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable lines (0, 0, { 'debit': 133.33, 'credit': 0.0, 'amount_currency': 400.0, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id, }), ] }) # Rate 1/2 in 2017. payment_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, { 'debit': 0.0, 'credit': 201.0, 'amount_currency': -402.0, # Don't create the full reconcile directly. 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id, }), (0, 0, { 'debit': 201.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, }), ] }) # Move making the payment fully paid. end_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, { 'debit': 1.0, 'credit': 0.0, 'amount_currency': 2.0, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id, }), (0, 0, { 'debit': 0.0, 'credit': 1.0, 'account_id': self.company_data['default_account_revenue'].id, }), ] }) (cash_basis_move + payment_move + end_move).action_post() self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, -33.33, -100.0), (self.tax_account_1, 0.0, 0.0), ]) receivable_lines = (cash_basis_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_1) res = receivable_lines.reconcile() self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 1) self.assertRecordValues(res['tax_cash_basis_moves'].line_ids, [ # Base amount: {'debit': 150.0, 'credit': 0.0, 'amount_currency': 300.0, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 150.0, 'amount_currency': -300.0, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, # tax: {'debit': 50.0, 'credit': 0.0, 'amount_currency': 100.0, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 50.0, 'amount_currency': -100.0, 'currency_id': currency_id, 'account_id': self.tax_account_1.id}, ]) receivable_lines2 = (payment_move + end_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_1) res = receivable_lines2.reconcile() self.assertFullReconcile(res['full_reconcile'], receivable_lines + receivable_lines2) exchange_diff = res['full_reconcile'].exchange_move_id exchange_diff_lines = exchange_diff.line_ids\ .filtered(lambda line: line.account_id == self.cash_basis_transfer_account)\ .sorted(lambda line: (line.account_id, line.debit, line.credit)) self.assertRecordValues(exchange_diff_lines, [ { 'debit': 0.0, 'credit': 16.67, 'amount_currency': 0.0, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id, }, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, 0.0, 0.0), (self.tax_account_1, -33.33, -100.0), ]) def test_reconcile_cash_basis_exchange_difference_transfer_account_check_entries_2(self): ''' Test the generation of the exchange difference for a tax cash basis journal entry when the transfer account is not a reconcile one. ''' self.env.company.tax_exigibility = True currency_id = self.setup_multi_currency_data(default_values={ 'name': 'bitcoin', 'symbol': 'bc', 'currency_unit_label': 'Bitcoin', 'currency_subunit_label': 'Tiny bitcoin', }, rate2016=0.5, rate2017=0.66666666666666)['currency'].id # Rate 2/1 in 2016. caba_inv = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 200.0, 'amount_currency': -100.0, 'currency_id': currency_id, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], }), # Tax line (0, 0, { 'debit': 0.0, 'credit': 20.0, 'amount_currency': -10.0, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable lines (0, 0, { 'debit': 220.0, 'credit': 0.0, 'amount_currency': 110.0, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id, }), ] }) caba_inv.action_post() # Rate 3/2 in 2017. Full payment of 110 in foreign currency pmt_wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=caba_inv.ids).create({ 'payment_date': '2017-01-01', 'journal_id': self.company_data['default_journal_bank'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, }) pmt_wizard._create_payments() partial_rec = caba_inv.mapped('line_ids.matched_credit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', 'in', partial_rec.ids)]) self.assertRecordValues(caba_move.line_ids, [ {'account_id': self.cash_basis_base_account.id, 'debit': 150.0, 'credit': 0.0, 'amount_currency': 100.0, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.cash_basis_base_account.id, 'debit': 0.0, 'credit': 150.0, 'amount_currency': -100.0, 'tax_ids': self.cash_basis_tax_a_third_amount.ids, 'tax_line_id': False}, {'account_id': self.cash_basis_transfer_account.id, 'debit': 15.0, 'credit': 0.0, 'amount_currency': 10.0, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.tax_account_1.id, 'debit': 0.0, 'credit': 15.0, 'amount_currency': -10.0, 'tax_ids': [], 'tax_line_id': self.cash_basis_tax_a_third_amount.id}, ]) receivable_line = caba_inv.line_ids.filtered(lambda x: x.account_id.internal_type == 'receivable') self.assertTrue(receivable_line.full_reconcile_id, "Invoice should be fully paid") exchange_move = receivable_line.full_reconcile_id.exchange_move_id self.assertTrue(exchange_move, "There should be an exchange difference move created") self.assertRecordValues(exchange_move.line_ids, [ {'account_id': receivable_line.account_id.id, 'debit': 0.0, 'credit': 55.0, 'amount_currency': 0.0, 'tax_ids': [], 'tax_line_id': False}, {'account_id': caba_move.company_id.expense_currency_exchange_account_id.id, 'debit': 55.0, 'credit': 0.0, 'amount_currency': 0.0, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.cash_basis_base_account.id, 'debit': 0.0, 'credit': 50.0, 'amount_currency': 0.0, 'tax_ids': self.cash_basis_tax_a_third_amount.ids, 'tax_line_id': False}, {'account_id': self.cash_basis_base_account.id, 'debit': 50.0, 'credit': 0.0, 'amount_currency': 0.0, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.tax_account_1.id, 'debit': 0.0, 'credit': 5.0, 'amount_currency': 0.0, 'tax_ids': [], 'tax_line_id': self.cash_basis_tax_a_third_amount.id}, {'account_id': self.cash_basis_transfer_account.id, 'debit': 5.0, 'credit': 0.0, 'amount_currency': 0.0, 'tax_ids': [], 'tax_line_id': False}, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, 0.0, 0.0), (self.tax_account_1, -20.0, -10.0), ]) def test_reconcile_cash_basis_exchange_difference_transfer_account_check_entries_3(self): ''' Test the generation of the exchange difference for a tax cash basis journal entry when the transfer account is not a reconcile one. ''' self.env.company.tax_exigibility = True currency_id = self.setup_multi_currency_data(default_values={ 'name': 'bitcoin', 'symbol': 'bc', 'currency_unit_label': 'Bitcoin', 'currency_subunit_label': 'Tiny bitcoin', 'rounding': 0.01, }, rate2016=0.5, rate2017=0.66666666666666)['currency'].id # Rate 2/1 in 2016. caba_inv = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 200.0, 'amount_currency': -100.0, 'currency_id': currency_id, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], }), # Tax line (0, 0, { 'debit': 0.0, 'credit': 20.0, 'amount_currency': -10.0, 'currency_id': currency_id, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable lines (0, 0, { 'debit': 220.0, 'credit': 0.0, 'amount_currency': 110.0, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id, }), ] }) caba_inv.action_post() # Rate 3/2 in 2017. Full payment of 220 in company currency pmt_wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=caba_inv.ids).create({ 'payment_date': '2017-01-01', 'journal_id': self.company_data['default_journal_bank'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, 'currency_id': self.company_data['currency'].id, 'amount': 220.0, }) pmt_wizard._create_payments() caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', 'in', caba_inv.line_ids.matched_credit_ids.ids)]) self.assertRecordValues(caba_move.line_ids, [ {'account_id': self.cash_basis_base_account.id, 'debit': 200.01, 'credit': 0.0, 'amount_currency': 133.34, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.cash_basis_base_account.id, 'debit': 0.0, 'credit': 200.01, 'amount_currency': -133.34, 'tax_ids': self.cash_basis_tax_a_third_amount.ids, 'tax_line_id': False}, {'account_id': self.cash_basis_transfer_account.id, 'debit': 20.0, 'credit': 0.0, 'amount_currency': 13.33, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.tax_account_1.id, 'debit': 0.0, 'credit': 20.0, 'amount_currency': -13.33, 'tax_ids': [], 'tax_line_id': self.cash_basis_tax_a_third_amount.id}, ]) receivable_line = caba_inv.line_ids.filtered(lambda x: x.account_id.internal_type == 'receivable') self.assertTrue(receivable_line.full_reconcile_id, "Invoice should be fully paid") exchange_move = receivable_line.full_reconcile_id.exchange_move_id self.assertRecordValues(exchange_move.line_ids, [ {'account_id': self.extra_receivable_account_1.id, 'debit': 0.0, 'credit': 0.0, 'amount_currency': 36.67, 'tax_ids': [], 'tax_line_id': False}, {'account_id': caba_move.company_id.income_currency_exchange_account_id.id, 'debit': 0.0, 'credit': 0.0, 'amount_currency': -36.67, 'tax_ids': [], 'tax_line_id': False}, {'account_id': self.cash_basis_base_account.id, 'debit': 0.01, 'credit': 0.0, 'amount_currency': 0.0, 'tax_ids': self.cash_basis_tax_a_third_amount.ids, 'tax_line_id': False}, {'account_id': self.cash_basis_base_account.id, 'debit': 0.0, 'credit': 0.01, 'amount_currency': 0.0, 'tax_ids': [], 'tax_line_id': False}, ]) self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (self.cash_basis_transfer_account, 0.0, 3.33), (self.tax_account_1, -20.0, -13.33), ]) def test_reconcile_cash_basis_exchange_difference_transfer_account_check_entries_4(self): ''' Test the generation of the exchange difference for a tax cash basis journal entry when the tax account is a reconcile one. ''' self.env.company.tax_exigibility = True currency_id = self.currency_data['currency'].id cash_basis_transition_account = self.env['account.account'].create({ 'code': '209.01.01', 'name': 'Cash Basis Transition Account', 'user_type_id': self.env.ref('account.data_account_type_current_liabilities').id, 'company_id': self.company_data['company'].id, 'reconcile': True, }) self.cash_basis_tax_a_third_amount.write({ 'cash_basis_transition_account_id': cash_basis_transition_account.id, }) # Rate 1/3 in 2016. cash_basis_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 100.0, 'amount_currency': -300.0, 'currency_id': currency_id, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], }), # Tax line (0, 0, { 'debit': 0.0, 'credit': 33.33, 'amount_currency': -100.0, 'currency_id': currency_id, 'account_id': cash_basis_transition_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable lines (0, 0, { 'debit': 133.33, 'credit': 0.0, 'amount_currency': 400.0, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id, }), ] }) # Rate 1/2 in 2017. payment_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, { 'debit': 0.0, 'credit': 200.0, 'amount_currency': -400.0, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id, }), (0, 0, { 'debit': 200.0, 'credit': 0.0, 'amount_currency': 400.0, 'currency_id': currency_id, 'account_id': self.company_data['default_account_revenue'].id, }), ] }) (cash_basis_move + payment_move).action_post() self.assertAmountsGroupByAccount([ # Account Balance Amount Currency (cash_basis_transition_account, -33.33, -100.0), (self.tax_account_1, 0.0, 0.0), ]) receivable_lines = (cash_basis_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_1) res = receivable_lines.reconcile() self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 1) # Tax values based on payment # Invoice amount 300 (amount currency) with payment rate 2 (400 payment amount divided by 200 invoice balance) # - Base amount: 150 company currency # - Tax amount: 50 company currency self.assertRecordValues(res['tax_cash_basis_moves'].line_ids, [ # Base amount: {'debit': 150.0, 'credit': 0.0, 'amount_currency': 300.0, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 150.0, 'amount_currency': -300.0, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, # tax: {'debit': 50.0, 'credit': 0.0, 'amount_currency': 100.0, 'currency_id': currency_id, 'account_id': cash_basis_transition_account.id}, {'debit': 0.0, 'credit': 50.0, 'amount_currency': -100.0, 'currency_id': currency_id, 'account_id': self.tax_account_1.id}, ]) exchange_diff = res['full_reconcile'].exchange_move_id # Exchange difference # 66.67 amount residual on the payment line after reconciling receivable line of the cash basis move with the payment counterpart # 50.00 difference of the cash_basis_move base line and the CABA entry created by the system self.assertRecordValues(exchange_diff.line_ids, [ {'debit': 66.67, 'credit': 0.0, 'currency_id': currency_id, 'account_id': self.extra_receivable_account_1.id}, {'debit': 0.0, 'credit': 66.67, 'currency_id': currency_id, 'account_id': self.company_data['company'].income_currency_exchange_account_id.id}, {'debit': 50.0, 'credit': 0.0, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 50.0, 'currency_id': currency_id, 'account_id': self.cash_basis_base_account.id}, ]) def test_reconcile_cash_basis_refund_multicurrency(self): self.env.company.tax_exigibility = True rates_data = self.setup_multi_currency_data(default_values={ 'name': 'Playmock', 'symbol': '🦌', 'rounding': 0.01, 'currency_unit_label': 'Playmock', 'currency_subunit_label': 'Cent', }, rate2016=0.5, rate2017=0.33333333333333333) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'currency_id': rates_data['currency'].id, 'invoice_date': '2016-01-01', 'invoice_line_ids': [(0, 0, { 'name': 'dudu', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], })], }) refund = self.env['account.move'].create({ 'move_type': 'out_refund', 'partner_id': self.partner_a.id, 'currency_id': rates_data['currency'].id, 'invoice_date': '2017-01-01', 'invoice_line_ids': [(0, 0, { 'name': 'dudu', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], })], }) invoice.action_post() refund.action_post() (refund + invoice).line_ids.filtered(lambda x: x.account_id.user_type_id.type == 'receivable').reconcile() # Check the cash basis moves self.assertRecordValues( self.env['account.move'].search([('tax_cash_basis_origin_move_id', '=', invoice.id)]).line_ids, [ { 'debit': 200, 'credit': 0, 'amount_currency': 100, 'currency_id': rates_data['currency'].id, 'tax_ids': [], 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { 'debit': 0, 'credit': 200, 'amount_currency': -100, 'currency_id': rates_data['currency'].id, 'tax_ids': self.cash_basis_tax_a_third_amount.ids, 'tax_repartition_line_id': None, 'tax_tag_ids': self.tax_tags[0].ids, }, { 'debit': 66.66, 'credit': 0, 'amount_currency': 33.33, 'currency_id': rates_data['currency'].id, 'tax_ids': [], 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { 'debit': 0, 'credit': 66.66, 'amount_currency': -33.33, 'currency_id': rates_data['currency'].id, 'tax_ids': [], 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_tag_ids': self.tax_tags[1].ids, }, ] ) self.assertRecordValues( self.env['account.move'].search([('tax_cash_basis_origin_move_id', '=', refund.id)]).line_ids, [ { 'debit': 0, 'credit': 300, 'amount_currency': -100, 'currency_id': rates_data['currency'].id, 'tax_ids': [], 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { 'debit': 300, 'credit': 0, 'amount_currency': 100, 'currency_id': rates_data['currency'].id, 'tax_ids': self.cash_basis_tax_a_third_amount.ids, 'tax_repartition_line_id': None, 'tax_tag_ids': self.tax_tags[2].ids, }, { 'debit': 0, 'credit': 99.99, 'amount_currency': -33.33, 'currency_id': rates_data['currency'].id, 'tax_ids': [], 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { 'debit': 99.99, 'credit': 0, 'amount_currency': 33.33, 'currency_id': rates_data['currency'].id, 'tax_ids': [], 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_tag_ids': self.tax_tags[3].ids, }, ] ) # Check the exchange difference move, to be sure no cash basis rounding data was added into it self.assertRecordValues( invoice.line_ids.full_reconcile_id.exchange_move_id.line_ids, [ { 'debit': 133.33, 'credit': 0, 'amount_currency': 0, 'currency_id': rates_data['currency'].id, 'tax_ids': [], 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { 'debit': 0, 'credit': 133.33, 'amount_currency': 0, 'currency_id': rates_data['currency'].id, 'tax_ids': [], 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, ] ) def test_reconcile_cash_basis_revert(self): ''' Ensure the cash basis journal entry can be reverted. ''' self.env.company.tax_exigibility = True self.cash_basis_transfer_account.reconcile = True self.cash_basis_tax_a_third_amount.cash_basis_transition_account_id = self.tax_account_1 invoice_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 100.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], }), # Tax line (0, 0, { 'debit': 0.0, 'credit': 33.33, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable line (0, 0, { 'debit': 133.33, 'credit': 0.0, 'account_id': self.extra_receivable_account_1.id, }), ] }) payment_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 133.33, 'account_id': self.extra_receivable_account_1.id}), (0, 0, {'debit': 133.33, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id}), ] }) (invoice_move + payment_move).action_post() receivable_lines = (invoice_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_1) res = receivable_lines.reconcile() # == Check reconciliation of invoice with payment == self.assertFullReconcile(res['full_reconcile'], receivable_lines) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 1) # == Check the reconciliation of invoice with tax cash basis journal entry. # /!\ We make the assumption the tax cash basis journal entry is well created. tax_cash_basis_move = res['tax_cash_basis_moves'] taxes_lines = (invoice_move.line_ids + tax_cash_basis_move.line_ids.filtered('debit'))\ .filtered(lambda line: line.account_id == self.cash_basis_transfer_account) taxes_full_reconcile = taxes_lines.matched_debit_ids.full_reconcile_id self.assertTrue(taxes_full_reconcile) self.assertFullReconcile(taxes_full_reconcile, taxes_lines) # == Check the reconciliation after the reverse == tax_cash_basis_move_reverse = tax_cash_basis_move._reverse_moves(cancel=True) self.assertFullReconcile(res['full_reconcile'], receivable_lines) # == Check the reconciliation of the tax cash basis journal entry with its reverse == reversed_taxes_lines = (tax_cash_basis_move + tax_cash_basis_move_reverse).line_ids\ .filtered(lambda line: line.account_id == self.cash_basis_transfer_account) reversed_taxes_full_reconcile = reversed_taxes_lines.matched_debit_ids.full_reconcile_id self.assertTrue(reversed_taxes_full_reconcile) self.assertFullReconcile(reversed_taxes_full_reconcile, reversed_taxes_lines) def test_reconcile_cash_basis_tax_grid_refund(self): self.env.company.tax_exigibility = True invoice_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 100.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], }), # Tax line (0, 0, { 'debit': 0.0, 'credit': 33.33, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable line (0, 0, { 'debit': 133.33, 'credit': 0.0, 'account_id': self.extra_receivable_account_1.id, }), ] }) refund_move = self.env['account.move'].create({ 'move_type': 'out_refund', 'partner_id': self.partner_a.id, 'invoice_date': '2016-01-01', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 100.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], }), # Tax line (0, 0, { 'debit': 33.33, 'credit': 0.0, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.refund_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable line (0, 0, { 'debit': 0.0, 'credit': 133.33, 'account_id': self.extra_receivable_account_1.id, }), ] }) (invoice_move + refund_move).action_post() receivable_lines = (invoice_move + refund_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_1) res = receivable_lines.reconcile() self.assertFullReconcile(res['full_reconcile'], receivable_lines) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 2) tax_cash_basis_moves = res['tax_cash_basis_moves'].sorted(lambda move: move.tax_cash_basis_origin_move_id.id) # Invoice: cb_lines = tax_cash_basis_moves[0].line_ids.sorted(lambda line: (-abs(line.balance), -line.debit, line.account_id)) self.assertRecordValues(cb_lines, [ # Base amount: {'debit': 100.0, 'credit': 0.0, 'tax_tag_ids': [], 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 100.0, 'tax_tag_ids': self.tax_tags[0].ids, 'account_id': self.cash_basis_base_account.id}, # tax: {'debit': 33.33, 'credit': 0.0, 'tax_tag_ids': [], 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 33.33, 'tax_tag_ids': self.tax_tags[1].ids, 'account_id': self.tax_account_1.id}, ]) # Refund: cb_lines = tax_cash_basis_moves[1].line_ids.sorted(lambda line: (-abs(line.balance), -line.debit, line.account_id)) self.assertRecordValues(cb_lines, [ # Base amount: {'debit': 100.0, 'credit': 0.0, 'tax_tag_ids': self.tax_tags[2].ids, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 100.0, 'tax_tag_ids': [], 'account_id': self.cash_basis_base_account.id}, # tax: {'debit': 33.33, 'credit': 0.0, 'tax_tag_ids': self.tax_tags[3].ids, 'account_id': self.tax_account_1.id}, {'debit': 0.0, 'credit': 33.33, 'tax_tag_ids': [], 'account_id': self.cash_basis_transfer_account.id}, ]) def test_reconcile_cash_basis_tax_grid_reversal(self): invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'date': '2016-01-01', 'invoice_line_ids': [(0, 0, { 'product_id': self.product_a.id, 'price_unit': 1000.0, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], })], }) invoice.action_post() self.assertRecordValues(invoice.line_ids.sorted('balance'), [ {'debit': 0.0, 'credit': 1000.0, 'tax_tag_ids': [], 'account_id': self.company_data['default_account_revenue'].id}, {'debit': 0.0, 'credit': 333.33, 'tax_tag_ids': [], 'account_id': self.cash_basis_transfer_account.id}, {'debit': 1333.33, 'credit': 0.0, 'tax_tag_ids': [], 'account_id': self.company_data['default_account_receivable'].id}, ]) reversal_wizard = self.env['account.move.reversal']\ .with_context(active_model='account.move', active_ids=invoice.ids)\ .create({ 'reason': "test_reconcile_cash_basis_tax_grid_reversal", 'refund_method': 'refund', 'journal_id': invoice.journal_id.id, }) refund = self.env['account.move'].browse(reversal_wizard.reverse_moves()['res_id']) refund.action_post() self.assertRecordValues(refund.line_ids.sorted('balance'), [ {'debit': 0.0, 'credit': 1333.33, 'tax_tag_ids': [], 'account_id': self.company_data['default_account_receivable'].id}, {'debit': 333.33, 'credit': 0.0, 'tax_tag_ids': [], 'account_id': self.cash_basis_transfer_account.id}, {'debit': 1000.0, 'credit': 0.0, 'tax_tag_ids': [], 'account_id': self.company_data['default_account_revenue'].id}, ]) reversal_wizard = self.env['account.move.reversal']\ .with_context(active_model='account.move', active_ids=refund.ids)\ .create({ 'reason': "test_reconcile_cash_basis_tax_grid_reversal", 'refund_method': 'refund', 'journal_id': refund.journal_id.id, }) reversed_refund = self.env['account.move'].browse(reversal_wizard.reverse_moves()['res_id']) self.assertRecordValues(reversed_refund.line_ids.sorted('balance'), [ {'debit': 0.0, 'credit': 1000.0, 'tax_tag_ids': [], 'account_id': self.company_data['default_account_revenue'].id}, {'debit': 0.0, 'credit': 333.33, 'tax_tag_ids': [], 'account_id': self.cash_basis_transfer_account.id}, {'debit': 1333.33, 'credit': 0.0, 'tax_tag_ids': [], 'account_id': self.company_data['default_account_receivable'].id}, ]) def test_reconcile_cash_basis_tax_grid_multi_taxes(self): ''' Test the tax grid when reconciling an invoice with multiple taxes/tax repartition. ''' self.env.company.tax_exigibility = True base_taxes = self.cash_basis_tax_a_third_amount + self.cash_basis_tax_tiny_amount base_tags = self.tax_tags[0] + self.tax_tags[4] # An invoice with 2 taxes: invoice_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2016-01-01', 'line_ids': [ # Base Tax line (0, 0, { 'debit': 0.0, 'credit': 100.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, base_taxes.ids)], }), # Tax lines (0, 0, { 'debit': 0.0, 'credit': 33.33, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_a_third_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), (0, 0, { 'debit': 0.0, 'credit': 0.01, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': self.cash_basis_tax_tiny_amount.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable lines (0, 0, { 'debit': 133.34, 'credit': 0.0, 'account_id': self.extra_receivable_account_1.id, }), ] }) # A payment paying the full invoice amount. payment_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': '2017-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 133.34, 'account_id': self.extra_receivable_account_1.id}), (0, 0, {'debit': 133.34, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id}), ] }) (invoice_move + payment_move).action_post() receivable_lines = (invoice_move + payment_move).line_ids\ .filtered(lambda line: line.account_id == self.extra_receivable_account_1) res = receivable_lines.reconcile() self.assertFullReconcile(res['full_reconcile'], receivable_lines) self.assertEqual(len(res.get('tax_cash_basis_moves', [])), 1) self.assertRecordValues(res['tax_cash_basis_moves'].line_ids, [ # Base amount x 2 because there is two taxes: {'debit': 100.0, 'credit': 0.0, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 100.0, 'tax_ids': base_taxes.ids, 'tax_tag_ids': base_tags.ids, 'account_id': self.cash_basis_base_account.id}, # tax_1: {'debit': 33.33, 'credit': 0.0, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 33.33, 'tax_ids': [], 'tax_tag_ids': self.tax_tags[1].ids, 'account_id': self.tax_account_1.id}, # tax_2: {'debit': 0.01, 'credit': 0.0, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': self.cash_basis_transfer_account.id}, {'debit': 0.0, 'credit': 0.01, 'tax_ids': [], 'tax_tag_ids': self.tax_tags[5].ids, 'account_id': self.tax_account_2.id}, ]) def test_caba_mix_reconciliation(self): """ Test the reconciliation of tax lines (when using a reconcilable tax account) for cases mixing taxes exigible on payment and on invoices. """ # Make the tax account reconcilable self.tax_account_1.reconcile = True self.env.company.tax_exigibility = True # Create a tax using the same accounts as the CABA one non_caba_tax = self.env['account.tax'].create({ 'name': 'tax 20%', 'type_tax_use': 'purchase', 'company_id': self.company_data['company'].id, 'amount': 20, 'tax_exigibility': 'on_invoice', 'invoice_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0,0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': self.tax_account_1.id, }), ], 'refund_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0,0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': self.tax_account_1.id, }), ], }) # Create an invoice with a non-CABA tax non_caba_inv = self.init_invoice('in_invoice', amounts=[1000], post=True, taxes=non_caba_tax) # Create an invoice with a CABA tax using the same tax account and pay it caba_inv = self.init_invoice('in_invoice', amounts=[300], post=True, taxes=self.cash_basis_tax_a_third_amount) pmt_wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=caba_inv.ids).create({ 'payment_date': caba_inv.date, 'journal_id': self.company_data['default_journal_bank'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, }) pmt_wizard._create_payments() partial_rec = caba_inv.mapped('line_ids.matched_debit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) # Create a misc operation with a line on the tax account, for full reconcile of those tax lines misc_move = self.env['account.move'].create({ 'name': "Misc move", 'journal_id': self.company_data['default_journal_misc'].id, 'line_ids': [ (0, 0, { 'name': 'line 1', 'account_id': self.tax_account_1.id, 'credit': 300, }), (0, 0, { 'name': 'line 2', 'account_id': self.company_data['default_account_expense'].id, # Whatever the account here 'debit': 300, }) ], }) misc_move.action_post() lines_to_reconcile = (misc_move + caba_move + non_caba_inv).mapped('line_ids').filtered(lambda x: x.account_id == self.tax_account_1) lines_to_reconcile.reconcile() # Check full reconciliation self.assertTrue(all(line.full_reconcile_id for line in lines_to_reconcile), "All tax lines should be fully reconciled") def test_caba_double_tax(self): """ Test the CABA entries generated from an invoice with almost equal lines, different only on analytic accounting """ # Make the tax account reconcilable self.tax_account_1.reconcile = True self.env.company.tax_exigibility = True # Create an invoice with a CABA tax using 'Include in analytic cost' move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice', account_predictive_bills_disable_prediction=True)) move_form.invoice_date = fields.Date.from_string('2019-01-01') move_form.partner_id = self.partner_a self.cash_basis_tax_a_third_amount.analytic = True test_analytic_account = self.env['account.analytic.account'].create({'name': 'test_analytic_account'}) tax = self.cash_basis_tax_a_third_amount # line with analytic account, will generate 2 lines in CABA move with move_form.invoice_line_ids.new() as line_form: line_form.name = "test line with analytic account" line_form.product_id = self.product_a line_form.tax_ids.clear() line_form.tax_ids.add(tax) line_form.analytic_account_id = test_analytic_account line_form.price_unit = 100 # line with analytic account, will generate other 2 lines in CABA move # even if the tax is the same with move_form.invoice_line_ids.new() as line_form: line_form.name = "test line" line_form.product_id = self.product_a line_form.tax_ids.clear() line_form.tax_ids.add(tax) line_form.price_unit = 100 rslt = move_form.save() rslt.action_post() pmt_wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=rslt.ids).create({ 'amount': rslt.amount_total, 'payment_date': rslt.date, 'journal_id': self.company_data['default_journal_bank'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, }) pmt_wizard._create_payments() partial_rec = rslt.mapped('line_ids.matched_debit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) self.assertEqual(len(caba_move.line_ids), 4, "All lines should be there") self.assertEqual(caba_move.line_ids.filtered(lambda x: x.tax_line_id).balance, 66.66, "Tax amount should take into account both lines") def test_caba_double_tax_negative_line(self): """ Tests making a cash basis invoice with 2 lines using the same tax: a positive and a negative one. """ self.env.company.tax_exigibility = True invoice = self.init_invoice('in_invoice', amounts=[300, -60], post=True, taxes=self.cash_basis_tax_a_third_amount) pmt_wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({ 'amount': 320, 'payment_date': invoice.date, 'journal_id': self.company_data['default_journal_bank'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, }) pmt_wizard._create_payments() partial_rec = invoice.mapped('line_ids.matched_debit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) self.assertRecordValues(caba_move.line_ids.sorted(lambda line: (-abs(line.balance), -line.debit, line.account_id)), [ # Base amount: {'debit': 240.0, 'credit': 0.0, 'tax_tag_ids': self.tax_tags[0].ids, 'account_id': self.cash_basis_base_account.id}, {'debit': 0.0, 'credit': 240.0, 'tax_tag_ids': [], 'account_id': self.cash_basis_base_account.id}, # tax: {'debit': 80.0, 'credit': 0.0, 'tax_tag_ids': self.tax_tags[1].ids, 'account_id': self.tax_account_1.id}, {'debit': 0.0, 'credit': 80.0, 'tax_tag_ids': [], 'account_id': self.cash_basis_transfer_account.id}, ]) def test_caba_dest_acc_reconciliation_partial_pmt(self): """ Test the reconciliation of tax lines (when using a reconcilable tax account) for partially paid invoices with cash basis taxes. This test is especially useful to check the implementation of the use case tested by test_reconciliation_cash_basis_foreign_currency_low_values does not have unwanted side effects. """ # Make the tax account reconcilable self.tax_account_1.reconcile = True self.env.company.tax_exigibility = True # Create an invoice with a CABA tax using the same tax account and pay half of it caba_inv = self.init_invoice('in_invoice', amounts=[900], post=True, taxes=self.cash_basis_tax_a_third_amount) pmt_wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=caba_inv.ids).create({ 'amount': 600, 'payment_date': caba_inv.date, 'journal_id': self.company_data['default_journal_bank'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, }) pmt_wizard._create_payments() partial_rec = caba_inv.mapped('line_ids.matched_debit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) # Create a misc operation with a line on the tax account, for full reconcile with the tax line misc_move = self.env['account.move'].create({ 'name': "Misc move", 'journal_id': self.company_data['default_journal_misc'].id, 'line_ids': [ (0, 0, { 'name': 'line 1', 'account_id': self.tax_account_1.id, 'credit': 150, }), (0, 0, { 'name': 'line 2', 'account_id': self.company_data['default_account_expense'].id, # Whatever the account here 'debit': 150, }) ], }) misc_move.action_post() lines_to_reconcile = (misc_move + caba_move).mapped('line_ids').filtered(lambda x: x.account_id == self.tax_account_1) lines_to_reconcile.reconcile() # Check full reconciliation self.assertTrue(all(line.full_reconcile_id for line in lines_to_reconcile), "All tax lines should be fully reconciled") def test_caba_undo_reconciliation(self): ''' Make sure there is no traceback like "Record has already been deleted" during the deletion of partials. ''' self.cash_basis_transfer_account.reconcile = True bill = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'date': '2019-01-01', 'invoice_line_ids': [(0, 0, { 'name': 'line', 'account_id': self.company_data['default_account_expense'].id, 'price_unit': 1000.0, 'tax_ids': [(6, 0, self.cash_basis_tax_a_third_amount.ids)], })], }) bill.action_post() # Register a payment creating the CABA journal entry on the fly and reconcile it with the tax line. self.env['account.payment.register']\ .with_context(active_ids=bill.ids, active_model='account.move')\ .create({})\ ._create_payments() bill.button_draft() def test_caba_foreign_vat(self): self.env.company.tax_exigibility = True test_country = self.env['res.country'].create({ 'name': "Bretonnia", 'code': 'wh', }) foreign_vat_fpos = self.env['account.fiscal.position'].create({ 'name': "Fiscal Position to the Holy Grail", 'country_id': test_country.id, 'foreign_vat': 'WH1234', }) foreign_caba_tax = self.env['account.tax'].create({ 'name': 'tax_1', 'amount': 33.3333, 'company_id': self.company_data['company'].id, 'cash_basis_transition_account_id': self.cash_basis_transfer_account.id, 'tax_exigibility': 'on_payment', 'country_id': test_country.id, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', }), ], }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2021-07-01', 'fiscal_position_id': foreign_vat_fpos.id, 'invoice_line_ids': [ Command.create({ 'name': "test", 'price_unit': 100, 'tax_ids': [Command.set(foreign_caba_tax.ids)], }), ] }) invoice.action_post() self.env['account.payment.register'].with_context(active_ids=invoice.ids, active_model='account.move').create({ 'payment_date': invoice.date, })._create_payments() caba_move = self.env['account.move'].search([('tax_cash_basis_origin_move_id', '=', invoice.id)]) self.assertEqual(caba_move.fiscal_position_id, foreign_vat_fpos, "The foreign VAT fiscal position should be kept in the the cash basis move.") def test_caba_tax_group(self): """ Test the CABA entries generated from an invoice with a tax group """ self.env.company.tax_exigibility = True # Make the tax account reconcilable self.tax_account_1.reconcile = True # Create an invoice with a CABA tax using 'Include in analytic cost' move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice', account_predictive_bills_disable_prediction=True)) move_form.invoice_date = fields.Date.from_string('2019-01-01') move_form.partner_id = self.partner_a tax_a = self.cash_basis_tax_a_third_amount tax_b = self.cash_basis_tax_tiny_amount tax_group = self.env['account.tax'].create({ 'name': 'tax group', 'amount_type': 'group', 'company_id': self.company_data['company'].id, 'children_tax_ids': [Command.set([tax_a.id, tax_b.id])], }) # line with analytic account, will generate 2 lines in CABA move invoice = self.env['account.move'].create({ 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'move_type': 'entry', 'line_ids': [ # Base Tax line Command.create({ 'debit': 0.0, 'credit': 3000.0, 'amount_currency': 3000.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [Command.set(tax_group.ids)], }), # Tax line A Command.create({ 'debit': 0.0, 'credit': 1000.0, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': tax_a.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Tax line B Command.create({ 'debit': 0.0, 'credit': 1.0, 'account_id': self.cash_basis_transfer_account.id, 'tax_repartition_line_id': tax_b.invoice_repartition_line_ids.filtered(lambda line: line.repartition_type == 'tax').id, }), # Receivable lines Command.create({ 'debit': 4001.0, 'credit': 0.0, 'account_id': self.extra_receivable_account_1.id, }), ] }) invoice.action_post() pmt_wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({}) pmt_wizard._create_payments() caba_move = self.env['account.move'].search([('tax_cash_basis_origin_move_id', '=', invoice.id)]) self.assertEqual(len(caba_move.line_ids), 6, "All lines should be there") self.assertRecordValues(caba_move.line_ids, [ {'balance': 3000.0, 'tax_line_id': False}, {'balance': -3000.0, 'tax_line_id': False}, {'balance': 1000.0, 'tax_line_id': False}, {'balance': -1000.0, 'tax_line_id': tax_a.id}, {'balance': 1.0, 'tax_line_id': False}, {'balance': -1.0, 'tax_line_id': tax_b.id}, ]) def test_cash_basis_taxline_without_account(self): """ Make sure that cash basis taxlines that don't have an account are handled properly. """ self.env.company.tax_exigibility = True tax = self.env['account.tax'].create({ 'name': 'cash basis 20%', 'type_tax_use': 'purchase', 'amount': 20, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': self.cash_basis_transfer_account.id, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 40, 'account_id': self.tax_account_1.id, 'repartition_type': 'tax', }), (0, 0, { 'factor_percent': 60, 'repartition_type': 'tax', }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 40, 'account_id': self.tax_account_1.id, 'repartition_type': 'tax', }), (0, 0, { 'factor_percent': 60, 'repartition_type': 'tax', }), ], }) # create invoice move_form = Form(self.env['account.move'].with_context( default_move_type='in_invoice')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2017-01-01') with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a line_form.tax_ids.clear() line_form.tax_ids.add(tax) invoice = move_form.save() invoice.action_post() # make payment self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({ 'payment_date': invoice.date, })._create_payments() # check caba move partial_rec = invoice.mapped('line_ids.matched_debit_ids') caba_move = self.env['account.move'].search( [('tax_cash_basis_rec_id', '=', partial_rec.id)]) expected_values = [ { 'account_id': self.cash_basis_base_account.id, 'debit': 0.0, 'credit': 800.0 }, { 'account_id': self.cash_basis_base_account.id, 'debit': 800.0, 'credit': 0.0 }, { 'account_id': self.cash_basis_transfer_account.id, 'debit': 0.0, 'credit': 64.0 }, { 'account_id': self.tax_account_1.id, 'debit': 64.0, 'credit': 0.0}, { 'account_id': self.cash_basis_transfer_account.id, 'debit': 0.0, 'credit': 96.0 }, { 'account_id': self.cash_basis_base_account.id, 'debit': 96.0, 'credit': 0.0 } ] self.assertRecordValues(caba_move.line_ids, expected_values) def test_cash_basis_full_refund(self): """ Ensure the caba entry and the exchange difference journal entry for caba are not created in case of full refund. """ self.env.company.tax_exigibility = True tax = self.env['account.tax'].create({ 'name': 'cash basis 20%', 'type_tax_use': 'purchase', 'amount': 20, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': self.cash_basis_transfer_account.id, }) invoice = self.init_invoice('out_invoice', post=True, amounts=[1000.0], taxes=tax) # Reverse completely the invoice. credit_note_wizard = self.env['account.move.reversal']\ .with_context({'active_ids': invoice.ids, 'active_model': 'account.move'})\ .create({ 'refund_method': 'cancel', 'reason': 'test_cash_basis_full_refund', 'journal_id': invoice.journal_id.id, }) action_values = credit_note_wizard.reverse_moves() self.assertRecordValues(invoice, [{'payment_state': 'reversed'}]) # Check no CABA move has been created. cash_basis_moves = self.env['account.move']\ .search([('tax_cash_basis_origin_move_id', 'in', (invoice.id, action_values['res_id']))]) self.assertFalse(cash_basis_moves) # No exchange journal entry created for CABA. caba_transfer_amls = self.env['account.move.line'].search([ ('account_id', '=', self.cash_basis_transfer_account.id), ('move_id', 'not in', (invoice.id, action_values['res_id'])), ]) self.assertFalse(caba_transfer_amls.move_id)
47.163325
145,829
38,858
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged, new_test_user from odoo.tests.common import Form @tagged('post_install', '-at_install') class TestAccountPayment(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) company = cls.company_data['default_journal_bank'].company_id cls.payment_debit_account_id = cls.copy_account(company.account_journal_payment_debit_account_id) cls.payment_credit_account_id = cls.copy_account(company.account_journal_payment_credit_account_id) cls.bank_journal_1 = cls.company_data['default_journal_bank'] cls.bank_journal_2 = cls.company_data['default_journal_bank'].copy() cls.partner_bank_account1 = cls.env['res.partner.bank'].create({ 'acc_number': "0123456789", 'partner_id': cls.partner_a.id, 'acc_type': 'bank', }) cls.partner_bank_account2 = cls.env['res.partner.bank'].create({ 'acc_number': "9876543210", 'partner_id': cls.partner_a.id, 'acc_type': 'bank', }) cls.comp_bank_account1 = cls.env['res.partner.bank'].create({ 'acc_number': "985632147", 'partner_id': cls.env.company.partner_id.id, 'acc_type': 'bank', }) cls.comp_bank_account2 = cls.env['res.partner.bank'].create({ 'acc_number': "741258963", 'partner_id': cls.env.company.partner_id.id, 'acc_type': 'bank', }) company.write({ 'account_journal_payment_debit_account_id': cls.payment_debit_account_id.id, 'account_journal_payment_credit_account_id': cls.payment_credit_account_id.id }) def test_payment_move_sync_create_write(self): copy_receivable = self.copy_account(self.company_data['default_account_receivable']) payment = self.env['account.payment'].create({ 'amount': 50.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'destination_account_id': copy_receivable.id, }) expected_payment_values = { 'amount': 50.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'payment_reference': False, 'is_reconciled': False, 'currency_id': self.company_data['currency'].id, 'partner_id': False, 'destination_account_id': copy_receivable.id, 'payment_method_line_id': self.inbound_payment_method_line.id, } expected_move_values = { 'currency_id': self.company_data['currency'].id, 'partner_id': False, } expected_liquidity_line = { 'debit': 50.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.payment_debit_account_id.id, } expected_counterpart_line = { 'debit': 0.0, 'credit': 50.0, 'amount_currency': -50.0, 'currency_id': self.company_data['currency'].id, 'account_id': copy_receivable.id, } self.assertRecordValues(payment, [expected_payment_values]) self.assertRecordValues(payment.move_id, [expected_move_values]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ expected_counterpart_line, expected_liquidity_line, ]) # ==== Check editing the account.payment ==== payment.write({ 'partner_type': 'supplier', 'currency_id': self.currency_data['currency'].id, 'partner_id': self.partner_a.id, }) self.assertRecordValues(payment, [{ **expected_payment_values, 'partner_type': 'supplier', 'destination_account_id': self.partner_a.property_account_payable_id.id, 'currency_id': self.currency_data['currency'].id, 'partner_id': self.partner_a.id, }]) self.assertRecordValues(payment.move_id, [{ **expected_move_values, 'currency_id': self.currency_data['currency'].id, 'partner_id': self.partner_a.id, }]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { **expected_counterpart_line, 'debit': 0.0, 'credit': 25.0, 'amount_currency': -50.0, 'currency_id': self.currency_data['currency'].id, 'account_id': self.partner_a.property_account_payable_id.id, }, { **expected_liquidity_line, 'debit': 25.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.currency_data['currency'].id, }, ]) # ==== Check editing the account.move.line ==== liquidity_lines, counterpart_lines, writeoff_lines = payment._seek_for_lines() payment.move_id.write({ 'line_ids': [ (1, counterpart_lines.id, { 'debit': 0.0, 'credit': 75.0, 'amount_currency': -75.0, 'currency_id': self.company_data['currency'].id, 'account_id': copy_receivable.id, 'partner_id': self.partner_b.id, }), (1, liquidity_lines.id, { 'debit': 100.0, 'credit': 0.0, 'amount_currency': 100.0, 'currency_id': self.company_data['currency'].id, 'partner_id': self.partner_b.id, }), # Additional write-off: (0, 0, { 'debit': 0.0, 'credit': 25.0, 'amount_currency': -25.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['default_account_revenue'].id, 'partner_id': self.partner_b.id, }), ] }) self.assertRecordValues(payment, [{ **expected_payment_values, 'amount': 100.0, 'partner_id': self.partner_b.id, }]) self.assertRecordValues(payment.move_id, [{ **expected_move_values, 'partner_id': self.partner_b.id, }]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { **expected_counterpart_line, 'debit': 0.0, 'credit': 75.0, 'amount_currency': -75.0, 'partner_id': self.partner_b.id, }, { 'debit': 0.0, 'credit': 25.0, 'amount_currency': -25.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['default_account_revenue'].id, 'partner_id': self.partner_b.id, }, { **expected_liquidity_line, 'debit': 100.0, 'credit': 0.0, 'amount_currency': 100.0, 'account_id': self.payment_debit_account_id.id, 'partner_id': self.partner_b.id, }, ]) def test_payment_move_sync_update_journal_custom_accounts(self): """The objective is to edit the journal of a payment in order to check if the accounts are updated.""" company = self.company_data['company'] # Create two different inbound accounts outstanding_payment_A = company.account_journal_payment_debit_account_id outstanding_payment_B = company.account_journal_payment_debit_account_id.copy() # Create two different journals with a different account journal_A = self.company_data['default_journal_bank'] journal_A.inbound_payment_method_line_ids.payment_account_id = outstanding_payment_A journal_B = self.company_data['default_journal_bank'].copy() journal_B.inbound_payment_method_line_ids.payment_account_id = outstanding_payment_B # Fill the form payment pay_form = Form(self.env['account.payment'].with_context(default_journal_id=self.company_data['default_journal_bank'].id)) pay_form.amount = 50.0 pay_form.payment_type = 'inbound' pay_form.partner_type = 'customer' pay_form.partner_id = self.partner_a pay_form.journal_id = journal_A # Save the form (to create move and move line) payment = pay_form.save() # Check the payment self.assertRecordValues(payment, [{ 'amount': 50.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'payment_reference': False, 'is_reconciled': False, 'currency_id': self.company_data['currency'].id, 'partner_id': self.partner_a.id, 'journal_id': journal_A.id }]) self.assertRecordValues(payment.move_id, [{ 'currency_id': self.company_data['currency'].id, 'partner_id': self.partner_a.id, 'journal_id': journal_A.id, }]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { 'debit': 0.0, 'credit': 50.0, 'amount_currency': -50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, }, { 'debit': 50.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.company_data['currency'].id, 'account_id': outstanding_payment_A.id, }, ]) # Change the journal on the form pay_form.journal_id = journal_B # Save the form (to write move and move line) payment = pay_form.save() # Check the payment self.assertRecordValues(payment, [{ 'amount': 50.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'payment_reference': False, 'is_reconciled': False, 'currency_id': self.company_data['currency'].id, 'partner_id': self.partner_a.id, 'journal_id': journal_B.id }]) self.assertRecordValues(payment.move_id, [{ 'currency_id': self.company_data['currency'].id, 'partner_id': self.partner_a.id, 'journal_id': journal_B.id, }]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { 'debit': 0.0, 'credit': 50.0, 'amount_currency': -50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, }, { 'debit': 50.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.company_data['currency'].id, 'account_id': outstanding_payment_B.id, }, ]) def test_payment_move_sync_onchange(self): pay_form = Form(self.env['account.payment'].with_context(default_journal_id=self.company_data['default_journal_bank'].id)) pay_form.amount = 50.0 pay_form.payment_type = 'inbound' pay_form.partner_type = 'customer' pay_form.partner_id = self.partner_a payment = pay_form.save() expected_payment_values = { 'amount': 50.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'payment_reference': False, 'is_reconciled': False, 'currency_id': self.company_data['currency'].id, 'partner_id': self.partner_a.id, 'destination_account_id': self.partner_a.property_account_receivable_id.id, 'payment_method_line_id': self.inbound_payment_method_line.id, } expected_move_values = { 'currency_id': self.company_data['currency'].id, 'partner_id': self.partner_a.id, } expected_liquidity_line = { 'debit': 50.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.payment_debit_account_id.id, } expected_counterpart_line = { 'debit': 0.0, 'credit': 50.0, 'amount_currency': -50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['default_account_receivable'].id, } self.assertRecordValues(payment, [expected_payment_values]) self.assertRecordValues(payment.move_id, [expected_move_values]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ expected_counterpart_line, expected_liquidity_line, ]) # ==== Check editing the account.payment ==== pay_form = Form(payment) pay_form.partner_type = 'supplier' pay_form.currency_id = self.currency_data['currency'] pay_form.partner_id = self.partner_a payment = pay_form.save() self.assertRecordValues(payment, [{ **expected_payment_values, 'partner_type': 'supplier', 'destination_account_id': self.partner_a.property_account_payable_id.id, 'currency_id': self.currency_data['currency'].id, 'partner_id': self.partner_a.id, }]) self.assertRecordValues(payment.move_id, [{ **expected_move_values, 'currency_id': self.currency_data['currency'].id, 'partner_id': self.partner_a.id, }]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { **expected_counterpart_line, 'debit': 0.0, 'credit': 25.0, 'amount_currency': -50.0, 'currency_id': self.currency_data['currency'].id, 'account_id': self.partner_a.property_account_payable_id.id, }, { **expected_liquidity_line, 'debit': 25.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.currency_data['currency'].id, }, ]) # ==== Check editing the account.move.line ==== move_form = Form(payment.move_id) with move_form.line_ids.edit(0) as line_form: line_form.currency_id = self.company_data['currency'] line_form.amount_currency = 100.0 line_form.partner_id = self.partner_b with move_form.line_ids.edit(1) as line_form: line_form.currency_id = self.company_data['currency'] line_form.amount_currency = -75.0 line_form.account_id = self.company_data['default_account_receivable'] line_form.partner_id = self.partner_b with move_form.line_ids.new() as line_form: line_form.currency_id = self.company_data['currency'] line_form.amount_currency = -25.0 line_form.account_id = self.company_data['default_account_revenue'] line_form.partner_id = self.partner_b move_form.save() self.assertRecordValues(payment, [{ **expected_payment_values, 'amount': 100.0, 'partner_id': self.partner_b.id, }]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { **expected_counterpart_line, 'debit': 0.0, 'credit': 75.0, 'amount_currency': -75.0, 'partner_id': self.partner_b.id, }, { 'debit': 0.0, 'credit': 25.0, 'amount_currency': -25.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['default_account_revenue'].id, 'partner_id': self.partner_b.id, }, { **expected_liquidity_line, 'debit': 100.0, 'credit': 0.0, 'amount_currency': 100.0, 'account_id': self.payment_debit_account_id.id, 'partner_id': self.partner_b.id, }, ]) def test_inbound_payment_sync_writeoff_debit_sign(self): payment = self.env['account.payment'].create({ 'amount': 100.0, 'payment_type': 'inbound', 'partner_type': 'customer', }) # ==== Edit the account.move.line ==== liquidity_lines, counterpart_lines, dummy = payment._seek_for_lines() payment.move_id.write({ 'line_ids': [ (1, liquidity_lines.id, {'debit': 100.0}), (1, counterpart_lines.id, {'credit': 125.0}), (0, 0, {'debit': 25.0, 'account_id': self.company_data['default_account_revenue'].id}), ], }) self.assertRecordValues(payment, [{ 'payment_type': 'inbound', 'partner_type': 'customer', 'amount': 100.0, }]) # ==== Edit the account.payment amount ==== payment.write({ 'partner_type': 'supplier', 'amount': 100.1, 'destination_account_id': self.company_data['default_account_payable'].id, }) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { 'debit': 0.0, 'credit': 125.1, 'account_id': self.company_data['default_account_payable'].id, }, { 'debit': 25.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, }, { 'debit': 100.1, 'credit': 0.0, 'account_id': self.payment_debit_account_id.id, }, ]) def test_inbound_payment_sync_writeoff_credit_sign(self): payment = self.env['account.payment'].create({ 'amount': 100.0, 'payment_type': 'inbound', 'partner_type': 'customer', }) # ==== Edit the account.move.line ==== liquidity_lines, counterpart_lines, dummy = payment._seek_for_lines() payment.move_id.write({ 'line_ids': [ (1, liquidity_lines.id, {'debit': 100.0}), (1, counterpart_lines.id, {'credit': 75.0}), (0, 0, {'credit': 25.0, 'account_id': self.company_data['default_account_revenue'].id}), ], }) self.assertRecordValues(payment, [{ 'payment_type': 'inbound', 'partner_type': 'customer', 'amount': 100.0, }]) # ==== Edit the account.payment amount ==== payment.write({ 'partner_type': 'supplier', 'amount': 100.1, 'destination_account_id': self.company_data['default_account_payable'].id, }) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { 'debit': 0.0, 'credit': 75.1, 'account_id': self.company_data['default_account_payable'].id, }, { 'debit': 0.0, 'credit': 25.0, 'account_id': self.company_data['default_account_revenue'].id, }, { 'debit': 100.1, 'credit': 0.0, 'account_id': self.payment_debit_account_id.id, }, ]) def test_outbound_payment_sync_writeoff_debit_sign(self): payment = self.env['account.payment'].create({ 'amount': 100.0, 'payment_type': 'outbound', 'partner_type': 'supplier', }) # ==== Edit the account.move.line ==== liquidity_lines, counterpart_lines, dummy = payment._seek_for_lines() payment.move_id.write({ 'line_ids': [ (1, liquidity_lines.id, {'credit': 100.0}), (1, counterpart_lines.id, {'debit': 75.0}), (0, 0, {'debit': 25.0, 'account_id': self.company_data['default_account_revenue'].id}), ], }) self.assertRecordValues(payment, [{ 'payment_type': 'outbound', 'partner_type': 'supplier', 'amount': 100.0, }]) # ==== Edit the account.payment amount ==== payment.write({ 'partner_type': 'customer', 'amount': 100.1, 'destination_account_id': self.company_data['default_account_receivable'].id, }) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { 'debit': 0.0, 'credit': 100.1, 'account_id': self.payment_credit_account_id.id, }, { 'debit': 25.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, }, { 'debit': 75.1, 'credit': 0.0, 'account_id': self.company_data['default_account_receivable'].id, }, ]) def test_outbound_payment_sync_writeoff_credit_sign(self): payment = self.env['account.payment'].create({ 'amount': 100.0, 'payment_type': 'outbound', 'partner_type': 'supplier', }) # ==== Edit the account.move.line ==== liquidity_lines, counterpart_lines, dummy = payment._seek_for_lines() payment.move_id.write({ 'line_ids': [ (1, liquidity_lines.id, {'credit': 100.0}), (1, counterpart_lines.id, {'debit': 125.0}), (0, 0, {'credit': 25.0, 'account_id': self.company_data['default_account_revenue'].id}), ], }) self.assertRecordValues(payment, [{ 'payment_type': 'outbound', 'partner_type': 'supplier', 'amount': 100.0, }]) # ==== Edit the account.payment amount ==== payment.write({ 'partner_type': 'customer', 'amount': 100.1, 'destination_account_id': self.company_data['default_account_receivable'].id, }) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { 'debit': 0.0, 'credit': 100.1, 'account_id': self.payment_credit_account_id.id, }, { 'debit': 0.0, 'credit': 25.0, 'account_id': self.company_data['default_account_revenue'].id, }, { 'debit': 125.1, 'credit': 0.0, 'account_id': self.company_data['default_account_receivable'].id, }, ]) def test_internal_transfer(self): copy_receivable = self.copy_account(self.company_data['default_account_receivable']) payment = self.env['account.payment'].create({ 'amount': 50.0, 'is_internal_transfer': True, 'destination_journal_id': self.company_data['default_journal_cash'].id, }) expected_payment_values = { 'amount': 50.0, 'payment_type': 'inbound', 'currency_id': self.company_data['currency'].id, 'partner_id': self.company_data['company'].partner_id.id, 'destination_account_id': self.company_data['company'].transfer_account_id.id, } expected_move_values = { 'currency_id': self.company_data['currency'].id, 'partner_id': self.company_data['company'].partner_id.id, } expected_liquidity_line = { 'debit': 50.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.payment_debit_account_id.id, } expected_counterpart_line = { 'debit': 0.0, 'credit': 50.0, 'amount_currency': -50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['company'].transfer_account_id.id, } self.assertRecordValues(payment, [expected_payment_values]) self.assertRecordValues(payment.move_id, [expected_move_values]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ expected_counterpart_line, expected_liquidity_line, ]) # ==== Check editing the account.payment ==== payment.write({ 'partner_type': 'customer', 'partner_id': self.partner_a.id, 'destination_account_id': copy_receivable.id, }) self.assertRecordValues(payment, [{ **expected_payment_values, 'partner_type': 'customer', 'destination_account_id': copy_receivable.id, 'partner_id': self.partner_a.id, 'is_internal_transfer': False, }]) self.assertRecordValues(payment.move_id, [{ **expected_move_values, 'partner_id': self.partner_a.id, }]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { **expected_counterpart_line, 'account_id': copy_receivable.id, }, expected_liquidity_line, ]) # ==== Check editing the account.move.line ==== liquidity_lines, counterpart_lines, writeoff_lines = payment._seek_for_lines() payment.move_id.write({ 'line_ids': [ (1, counterpart_lines.id, { 'account_id': self.company_data['company'].transfer_account_id.id, 'partner_id': self.company_data['company'].partner_id.id, }), (1, liquidity_lines.id, { 'partner_id': self.company_data['company'].partner_id.id, }), ] }) self.assertRecordValues(payment, [expected_payment_values]) self.assertRecordValues(payment.move_id, [expected_move_values]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ expected_counterpart_line, expected_liquidity_line, ]) # ==== Check creation of paired internal transfer payment ==== payment = self.env['account.payment'].create({ 'amount': 50.0, 'is_internal_transfer': True, 'payment_type': 'inbound', 'destination_journal_id': self.company_data['default_journal_cash'].id, }) payment.action_post() paired_payment = self.env['account.payment'].search([('payment_type', '=', 'outbound')]) expected_payment_values = { 'amount': 50.0, 'payment_type': 'outbound', 'currency_id': self.company_data['currency'].id, 'partner_id': self.company_data['company'].partner_id.id, 'destination_account_id': self.company_data['company'].transfer_account_id.id, } expected_move_values = { 'currency_id': self.company_data['currency'].id, 'partner_id': self.company_data['company'].partner_id.id, } expected_liquidity_line = { 'debit': 0.0, 'credit': 50.0, 'amount_currency': -50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['default_journal_cash'].company_id.account_journal_payment_credit_account_id.id, } expected_counterpart_line = { 'debit': 50.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.company_data['currency'].id, 'account_id': self.company_data['company'].transfer_account_id.id, } self.assertRecordValues(paired_payment, [expected_payment_values]) self.assertRecordValues(paired_payment.move_id, [expected_move_values]) self.assertRecordValues(paired_payment.line_ids.sorted('balance'), [ expected_liquidity_line, expected_counterpart_line, ]) def test_compute_currency_id(self): ''' When creating a new account.payment without specifying a currency, the default currency should be the one set on the journal. ''' self.company_data['default_journal_bank'].write({ 'currency_id': self.currency_data['currency'].id, }) payment = self.env['account.payment'].create({ 'amount': 50.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': self.partner_a.id, 'journal_id': self.company_data['default_journal_bank'].id, }) self.assertRecordValues(payment, [{ 'currency_id': self.currency_data['currency'].id, }]) self.assertRecordValues(payment.move_id, [{ 'currency_id': self.currency_data['currency'].id, }]) self.assertRecordValues(payment.line_ids.sorted('balance'), [ { 'debit': 0.0, 'credit': 25.0, 'amount_currency': -50.0, 'currency_id': self.currency_data['currency'].id, }, { 'debit': 25.0, 'credit': 0.0, 'amount_currency': 50.0, 'currency_id': self.currency_data['currency'].id, }, ]) def test_reconciliation_payment_states(self): payment = self.env['account.payment'].create({ 'amount': 50.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'destination_account_id': self.company_data['default_account_receivable'].id, }) liquidity_lines, counterpart_lines, writeoff_lines = payment._seek_for_lines() self.assertRecordValues(payment, [{ 'is_reconciled': False, 'is_matched': False, }]) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_line_ids': [(0, 0, { 'name': '50 to pay', 'price_unit': 50.0, 'quantity': 1, 'account_id': self.company_data['default_account_revenue'].id, })], }) payment.action_post() invoice.action_post() (counterpart_lines + invoice.line_ids.filtered(lambda line: line.account_internal_type == 'receivable'))\ .reconcile() self.assertRecordValues(payment, [{ 'is_reconciled': True, 'is_matched': False, }]) statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'journal_id': self.company_data['default_journal_bank'].id, 'line_ids': [ (0, 0, { 'payment_ref': '50 to pay', 'partner_id': self.partner_a.id, 'amount': 50.0, }), ], }) statement.button_post() statement_line = statement.line_ids statement_line.reconcile([{'id': liquidity_lines.id}]) self.assertRecordValues(payment, [{ 'is_reconciled': True, 'is_matched': True, }]) def test_payment_name(self): AccountPayment = self.env['account.payment'] AccountPayment.search([]).unlink() payment = AccountPayment.create({ 'journal_id': self.company_data['default_journal_bank'].id, }) self.assertRegex(payment.name, r'BNK1/\d{4}/\d{2}/0001') with Form(AccountPayment.with_context(default_move_journal_types=('bank', 'cash'))) as payment_form: self.assertEqual(payment_form._values['name'], '/') payment_form.journal_id = self.company_data['default_journal_cash'] self.assertRegex(payment_form._values['name'], r'CSH1/\d{4}/\d{2}/0001') payment_form.journal_id = self.company_data['default_journal_bank'] payment = payment_form.save() self.assertEqual(payment.name, '/') payment.action_post() self.assertRegex(payment.name, r'BNK1/\d{4}/\d{2}/0002') def test_payment_without_default_company_account(self): """ The purpose of this test is to check the specific behavior when duplicating an inbound payment, then change the copy to an outbound payment when we set the outstanding accounts (payments and receipts) on a journal but not on the company level. """ company = self.company_data['company'] bank_journal = self.company_data['default_journal_bank'] bank_journal.outbound_payment_method_line_ids.payment_account_id = company.account_journal_payment_credit_account_id bank_journal.inbound_payment_method_line_ids.payment_account_id = company.account_journal_payment_debit_account_id company.account_journal_payment_debit_account_id = False company.account_journal_payment_credit_account_id = False payment = self.env['account.payment'].create({ 'amount': 5.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'journal_id': bank_journal.id, }) self.assertRecordValues(payment, [{ 'amount': 5.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'payment_reference': False, 'is_reconciled': False, 'currency_id': self.company_data['currency'].id, 'partner_id': False, 'payment_method_line_id': self.inbound_payment_method_line.id, }]) payment.payment_type = 'outbound' self.assertRecordValues(payment, [{ 'amount': 5.0, 'payment_type': 'outbound', 'partner_type': 'customer', 'payment_reference': False, 'is_reconciled': False, 'currency_id': self.company_data['currency'].id, 'partner_id': False, 'payment_method_line_id': self.outbound_payment_method_line.id, }]) def test_suggested_default_partner_bank(self): """ Ensure the 'partner_bank_id' is well computed on payments. When the payment is inbound, the money must be received by a bank account linked to the company. In case of outbound payment, the bank account must be found on the partner. """ payment = self.env['account.payment'].create({ 'journal_id': self.bank_journal_1.id, 'amount': 50.0, 'payment_type': 'outbound', 'partner_type': 'supplier', 'partner_id': self.partner_a.id, }) self.assertRecordValues(payment, [{ 'available_partner_bank_ids': self.partner_a.bank_ids.ids, 'partner_bank_id': self.partner_bank_account1.id, }]) payment.payment_type = 'inbound' self.assertRecordValues(payment, [{ 'available_partner_bank_ids': [], 'partner_bank_id': False, }]) self.bank_journal_2.bank_account_id = self.comp_bank_account2 # A sequence is automatically added on the first move. We need to clean it before changing the journal. payment.name = False payment.journal_id = self.bank_journal_2 self.assertRecordValues(payment, [{ 'available_partner_bank_ids': self.comp_bank_account2.ids, 'partner_bank_id': self.comp_bank_account2.id, }]) def test_internal_transfer_right_accounts(self): """The purpose of this test is to check that the right accounts are computed when making an internal bank transfer""" company = self.env.company transfer_account = company.transfer_account_id bank = self.bank_journal_1 bank_2 = self.bank_journal_2 payment = self.env['account.payment'].create({ 'is_internal_transfer': True, 'payment_type': 'outbound', 'amount': 100.0, 'journal_id': bank.id, 'destination_journal_id': bank_2.id, }) payment.action_post() self.assertRecordValues(payment.line_ids, [ {'account_id': company.account_journal_payment_credit_account_id.id}, {'account_id': transfer_account.id}, ]) self.assertRecordValues(payment.paired_internal_transfer_payment_id.line_ids, [ {'account_id': company.account_journal_payment_debit_account_id.id}, {'account_id': transfer_account.id}, ]) # We check the behavior when setting specific receipts/payments account on bank journals bank.inbound_payment_method_line_ids.payment_account_id = company.account_journal_payment_debit_account_id.copy({'code': 1001}) bank.outbound_payment_method_line_ids.payment_account_id = company.account_journal_payment_credit_account_id.copy({'code': 1002}) bank_2.inbound_payment_method_line_ids.payment_account_id = company.account_journal_payment_debit_account_id.copy({'code': 2001}) bank_2.outbound_payment_method_line_ids.payment_account_id = company.account_journal_payment_credit_account_id.copy({'code': 2002}) payment = self.env['account.payment'].create({ 'is_internal_transfer': True, 'payment_type': 'outbound', 'amount': 100.0, 'journal_id': bank.id, 'destination_journal_id': bank_2.id, }) payment.action_post() self.assertRecordValues(payment.line_ids, [ {'account_id': bank.outbound_payment_method_line_ids.payment_account_id.id,}, {'account_id': transfer_account.id}, ]) self.assertRecordValues(payment.paired_internal_transfer_payment_id.line_ids, [ {'account_id': bank_2.inbound_payment_method_line_ids.payment_account_id.id}, {'account_id': transfer_account.id}, ])
38.896897
38,858
21,100
py
PYTHON
15.0
import logging from odoo import Command from odoo.addons.account.models.chart_template import update_taxes_from_templates from odoo.exceptions import ValidationError from odoo.tests import tagged from odoo.tests.common import TransactionCase @tagged('post_install', '-at_install') class TestChartTemplate(TransactionCase): @classmethod def setUpClass(cls): """ Set up a company with the generic chart template, containing two taxes and a fiscal position. We need to add xml_ids to the templates because they are loaded from their xml_ids """ super().setUpClass() us_country_id = cls.env.ref('base.us').id cls.company = cls.env['res.company'].create({ 'name': 'TestCompany1', 'country_id': us_country_id, 'account_fiscal_country_id': us_country_id, }) cls.chart_template_xmlid = 'l10n_test.test_chart_template_xmlid' cls.chart_template = cls.env['account.chart.template']._load_records([{ 'xml_id': cls.chart_template_xmlid, 'values': { 'name': 'Test Chart Template US', 'currency_id': cls.env.ref('base.USD').id, 'bank_account_code_prefix': 1000, 'cash_account_code_prefix': 2000, 'transfer_account_code_prefix': 3000, 'country_id': us_country_id, } }]) account_templates = cls.env['account.account.template']._load_records([{ 'xml_id': 'account.test_account_income_template', 'values': { 'name': 'property_income_account', 'code': '222221', 'user_type_id': cls.env.ref('account.data_account_type_revenue').id, 'chart_template_id': cls.chart_template.id, } }, { 'xml_id': 'account.test_account_expense_template', 'values': { 'name': 'property_expense_account', 'code': '222222', 'user_type_id': cls.env.ref('account.data_account_type_expenses').id, 'chart_template_id': cls.chart_template.id, } }]) cls.chart_template.property_account_income_categ_id = account_templates[0].id cls.chart_template.property_account_expense_categ_id = account_templates[1].id cls.fiscal_position_template = cls._create_fiscal_position_template('account.test_fiscal_position_template', 'US fiscal position test', us_country_id) cls.tax_template_1 = cls._create_tax_template('account.test_tax_template_1', 'Tax name 1', 1, tag_name='tag_name_1') cls.tax_template_2 = cls._create_tax_template('account.test_tax_template_2', 'Tax name 2', 2, tag_name='tag_name_2') cls.fiscal_position_tax_template_1 = cls._create_fiscal_position_tax_template( cls.fiscal_position_template, 'account.test_fp_tax_template_1', cls.tax_template_1, cls.tax_template_2 ) cls.chart_template.try_loading(company=cls.company, install_demo=False) cls.fiscal_position = cls.env['account.fiscal.position'].search([ ('company_id', '=', cls.company.id), ('name', '=', cls.fiscal_position_template.name), ]) @classmethod def create_tax_template(cls, name, template_name, amount): # TODO to remove in master logging.warning("Deprecated method, please use _create_tax_template() instead") return cls._create_tax_template(template_name, name, amount, tag_name=None) @classmethod def _create_group_tax_template(cls, tax_template_xmlid, name, chart_template_id=None, active=True): children_1 = cls._create_tax_template(f'{tax_template_xmlid}_children1', f'{name}_children_1', 10, active=active) children_2 = cls._create_tax_template(f'{tax_template_xmlid}_children2', f'{name}_children_2', 15, active=active) return cls.env['account.tax.template']._load_records([{ 'xml_id': tax_template_xmlid, 'values': { 'name': name, 'amount_type': 'group', 'type_tax_use': 'none', 'active': active, 'chart_template_id': chart_template_id if chart_template_id else cls.chart_template.id, 'children_tax_ids': [Command.set((children_1 + children_2).ids)], }, }]) @classmethod def _create_tax_template(cls, tax_template_xmlid, name, amount, tag_name=None, chart_template_id=None, account_data=None, active=True): if tag_name: tag = cls.env['account.account.tag'].create({ 'name': tag_name, 'applicability': 'taxes', 'country_id': cls.company.account_fiscal_country_id.id, }) if account_data: account_vals = { 'name': account_data['name'], 'code': account_data['code'], 'user_type_id': cls.env.ref('account.data_account_type_current_liabilities').id, } # We have to instantiate both the template and the record since we suppose accounts are already created. account_template = cls.env['account.account.template'].create(account_vals) account_vals.update({'company_id': cls.company.id}) cls.env['account.account'].create(account_vals) return cls.env['account.tax.template']._load_records([{ 'xml_id': tax_template_xmlid, 'values': { 'name': name, 'amount': amount, 'type_tax_use': 'none', 'active': active, 'chart_template_id': chart_template_id if chart_template_id else cls.chart_template.id, 'invoice_repartition_line_ids': [ Command.create({ 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tag.ids)] if tag_name else None, }), Command.create({ 'factor_percent': 100, 'account_id': account_template.id if account_data else None, 'repartition_type': 'tax', }), ], 'refund_repartition_line_ids': [ Command.create({ 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tag.ids)] if tag_name else None, }), Command.create({ 'factor_percent': 100, 'account_id': account_template.id if account_data else None, 'repartition_type': 'tax', }), ], }, }]) @classmethod def _create_fiscal_position_template(cls, fp_template_xmlid, fp_template_name, country_id): return cls.env['account.fiscal.position.template']._load_records([{ 'xml_id': fp_template_xmlid, 'values': { 'name': fp_template_name, 'chart_template_id': cls.chart_template.id, 'country_id': country_id, 'auto_apply': True, }, }]) @classmethod def _create_fiscal_position_tax_template(cls, fiscal_position_template, fiscal_position_tax_template_xmlid, tax_template_src, tax_template_dest): return cls.env['account.fiscal.position.tax.template']._load_records([{ 'xml_id': fiscal_position_tax_template_xmlid, 'values': { 'tax_src_id': tax_template_src.id, 'tax_dest_id': tax_template_dest.id, 'position_id': fiscal_position_template.id, }, }]) def test_update_taxes_new_template(self): """ Tests that adding a new tax template and a fiscal position tax template creates this new tax and fiscal position line when updating """ tax_template_3 = self._create_tax_template('account.test_tax_3_template', 'Tax name 3', 3, tag_name='tag_name_3') tax_template_4 = self._create_tax_template('account.test_tax_4_template', 'Tax name 4', 4, account_data={'name': 'account_name_4', 'code': 'TACT'}) self._create_fiscal_position_tax_template(self.fiscal_position_template, 'account.test_fiscal_position_tax_template', tax_template_3, tax_template_4) update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) taxes = self.env['account.tax'].search([ ('company_id', '=', self.company.id), ('name', 'in', [tax_template_3.name, tax_template_4.name]), ]) self.assertRecordValues(taxes, [ {'name': 'Tax name 3', 'amount': 3}, {'name': 'Tax name 4', 'amount': 4}, ]) self.assertEqual(taxes.invoice_repartition_line_ids.tag_ids.name, 'tag_name_3') self.assertEqual(taxes.invoice_repartition_line_ids.account_id.name, 'account_name_4') self.assertRecordValues(self.fiscal_position.tax_ids.tax_src_id, [ {'name': 'Tax name 1'}, {'name': 'Tax name 3'}, ]) self.assertRecordValues(self.fiscal_position.tax_ids.tax_dest_id, [ {'name': 'Tax name 2'}, {'name': 'Tax name 4'}, ]) def test_update_taxes_existing_template_update(self): """ When a template is close enough from the corresponding existing tax we want to update that tax with the template values. """ self.tax_template_1.invoice_repartition_line_ids.tag_ids.name += " [DUP]" update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) tax = self.env['account.tax'].search([ ('company_id', '=', self.company.id), ('name', '=', self.tax_template_1.name), ]) # Check that tax was not recreated self.assertEqual(len(tax), 1) # Check that tags have been updated self.assertEqual(tax.invoice_repartition_line_ids.tag_ids.name, self.tax_template_1.invoice_repartition_line_ids.tag_ids.name) def test_update_taxes_existing_template_recreation(self): """ When a template is too different from the corresponding existing tax we want to recreate a new taxes from template. """ # We increment the amount so the template gets slightly different from the # corresponding tax and triggers recreation old_tax_name = self.tax_template_1.name old_tax_amount = self.tax_template_1.amount self.tax_template_1.name = "Tax name 1 modified" self.tax_template_1.amount += 1 update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) # Check that old tax has not been changed old_tax = self.env['account.tax'].search([ ('company_id', '=', self.company.id), ('name', '=', old_tax_name), ], limit=1) self.assertEqual(old_tax[0].amount, old_tax_amount) # Check that new tax has been recreated tax = self.env['account.tax'].search([ ('company_id', '=', self.company.id), ('name', '=', self.tax_template_1.name), ], limit=1) self.assertEqual(tax[0].amount, self.tax_template_1.amount) def test_update_taxes_remove_fiscal_position_from_tax(self): """ Tests that when we remove the tax from the fiscal position mapping it is not recreated after update of taxes. """ self.fiscal_position.tax_ids.unlink() update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) self.assertEqual(len(self.fiscal_position.tax_ids), 0) def test_update_taxes_conflict_name(self): """ When recreating a tax during update a conflict name can occur since we need to respect unique constraint on (name, company_id, type_tax_use, tax_scope). To do so, the old tax needs to be prefixed with '[old] '. """ # We increment the amount so the template gets slightly different from the # corresponding tax and triggers recreation old_amount = self.tax_template_1.amount self.tax_template_1.amount += 1 update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) taxes_from_template_1 = self.env['account.tax'].search([ ('company_id', '=', self.company.id), ('name', 'like', f"%{self.tax_template_1.name}"), ]) self.assertRecordValues(taxes_from_template_1, [ {'name': f"[old] {self.tax_template_1.name}", 'amount': old_amount}, {'name': f"{self.tax_template_1.name}", 'amount': self.tax_template_1.amount}, ]) def test_update_taxes_multi_company(self): """ In a multi-company environment all companies should be correctly updated.""" company_2 = self.env['res.company'].create({ 'name': 'TestCompany2', 'country_id': self.env.ref('base.us').id, 'account_fiscal_country_id': self.env.ref('base.us').id, }) self.chart_template.try_loading(company=company_2, install_demo=False) # triggers recreation of taxes related to template 1 self.tax_template_1.amount += 1 update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) taxes_from_template_1 = self.env['account.tax'].search([ ('name', 'like', f"%{self.tax_template_1.name}"), ('company_id', 'in', [self.company.id, company_2.id]), ]) # we should have 4 records: 2 companies * (1 original tax + 1 recreated tax) self.assertEqual(len(taxes_from_template_1), 4) def test_message_to_accountants(self): """ When we duplicate a tax because it was too different from the existing one we send a message to accountant advisors. This message should only be sent to advisors and not to regular users. """ # create 1 normal user, 2 accountants managers accountant_manager_group = self.env.ref('account.group_account_manager') advisor_users = self.env['res.users'].create([{ 'name': 'AccountAdvisorTest1', 'login': 'aat1', 'password': 'aat1aat1', 'groups_id': [(4, accountant_manager_group.id)], }, { 'name': 'AccountAdvisorTest2', 'login': 'aat2', 'password': 'aat2aat2', 'groups_id': [(4, accountant_manager_group.id)], }]) normal_user = self.env['res.users'].create([{ 'name': 'AccountUserTest1', 'login': 'aut1', 'password': 'aut1aut1', 'groups_id': [(4, self.env.ref('account.group_account_user').id)], }]) # create situation where we need to recreate the tax during update to get notification(s) sent self.tax_template_1.amount += 1 update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) # accountants received the message self.assertEqual(self.env['mail.message'].search_count([ ('partner_ids', 'in', advisor_users.partner_id.ids), ('body', 'like', f"%{self.tax_template_1.name}%"), # we look for taxes' name that have been sent in the message's body ]), 1) # normal user didn't self.assertEqual(self.env['mail.message'].search_count([ ('partner_ids', 'in', normal_user.partner_id.ids), ('body', 'like', f"%{self.tax_template_1.name}%"), # we look for taxes' name that have been sent in the message's body ]), 0) def test_update_taxes_foreign_taxes(self): """ When taxes are instantiated through the fiscal position system (in multivat), its taxes should also be updated. """ country_test = self.env['res.country'].create({ 'name': 'Country Test', 'code': 'ZZ', }) chart_template_xmlid_test = 'l10n_test2.test_chart_template_xmlid_2' chart_template_test = self.env['account.chart.template']._load_records([{ 'xml_id': chart_template_xmlid_test, 'values': { 'name': 'Test Chart Template ZZ', 'currency_id': self.env.ref('base.EUR').id, 'bank_account_code_prefix': 1000, 'cash_account_code_prefix': 2000, 'transfer_account_code_prefix': 3000, 'country_id': country_test.id, } }]) self._create_tax_template('account.test_tax_test_template', 'Tax name 1 TEST', 10, chart_template_id=chart_template_test.id) self.env['account.tax.template']._try_instantiating_foreign_taxes(country_test, self.company) self._create_tax_template('account.test_tax_test_template2', 'Tax name 2 TEST', 15, chart_template_id=chart_template_test.id) update_taxes_from_templates(self.env.cr, chart_template_xmlid_test) tax_test_model_data = self.env['ir.model.data'].search([ ('name', '=', f'{self.company.id}_test_tax_test_template2'), ('model', '=', 'account.tax'), ]) self.assertEqual(len(tax_test_model_data), 1, "Taxes should have been created even if the chart_template is installed through fiscal position system.") def test_update_taxes_chart_template_country_check(self): """ We can't update taxes that don't match the chart_template's country. """ self.company.chart_template_id.country_id = self.env.ref('base.lu') # We provoke one recreation and one update self.tax_template_1.amount += 1 self.tax_template_2.invoice_repartition_line_ids.tag_ids.name = 'tag_name_2_modified' with self.assertRaises(ValidationError): update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) def test_update_taxes_fiscal_country_check(self): """ If there is no country set on chart_template, the taxes can only be updated if their country matches the fiscal country. """ self.chart_template.country_id = None country_lu = self.env.ref('base.lu') self.company.account_fiscal_country_id = country_lu self.tax_template_1.amount += 1 self.tax_template_2.invoice_repartition_line_ids.tag_ids.name = 'tag_name_2_modified' with self.assertRaises(ValidationError): update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) def test_update_taxes_children_tax_ids(self): """ Ensures children_tax_ids are correctly generated when updating taxes with amount_type='group'. """ group_tax_name = 'Group Tax name 1 TEST' self._create_group_tax_template('account.test_group_tax_test_template', group_tax_name, chart_template_id=self.chart_template.id) update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) parent_tax = self.env['account.tax'].search([ ('company_id', '=', self.company.id), ('name', '=', group_tax_name), ]) children_taxes = self.env['account.tax'].search([ ('company_id', '=', self.company.id), ('name', 'like', f'{group_tax_name}_%'), ]) self.assertEqual(len(parent_tax), 1, "The parent tax should have been created.") self.assertEqual(len(children_taxes), 2, "Two children should have been created.") self.assertEqual(parent_tax.children_tax_ids.ids, children_taxes.ids, "The parent and its children taxes should be linked together.") def test_update_taxes_children_tax_ids_inactive(self): """ Ensure tax templates are correctly generated when updating taxes with children taxes, even if templates are inactive. """ group_tax_name = 'Group Tax name 1 inactive TEST' self._create_group_tax_template('account.test_group_tax_test_template_inactive', group_tax_name, chart_template_id=self.chart_template.id, active=False) update_taxes_from_templates(self.env.cr, self.chart_template_xmlid) parent_tax = self.env['account.tax'].with_context(active_test=False).search([ ('company_id', '=', self.company.id), ('name', '=', group_tax_name), ]) children_taxes = self.env['account.tax'].with_context(active_test=False).search([ ('company_id', '=', self.company.id), ('name', 'like', f'{group_tax_name}_%'), ]) self.assertEqual(len(parent_tax), 1, "The parent tax should have been created, even if it is inactive.") self.assertFalse(parent_tax.active, "The parent tax should be inactive.") self.assertEqual(len(children_taxes), 2, "Two children should have been created, even if they are inactive.") self.assertEqual(children_taxes.mapped('active'), [False] * 2, "Children taxes should be inactive.")
50.118765
21,100
44,748
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged @tagged('post_install', '-at_install') class TestTaxCommon(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) # Setup another company having a rounding of 1.0. cls.currency_data['currency'].rounding = 1.0 cls.currency_no_decimal = cls.currency_data['currency'] cls.company_data_2 = cls.setup_company_data('company_2', currency_id=cls.currency_no_decimal.id) cls.env.user.company_id = cls.company_data['company'] cls.fixed_tax = cls.env['account.tax'].create({ 'name': "Fixed tax", 'amount_type': 'fixed', 'amount': 10, 'sequence': 1, }) cls.fixed_tax_bis = cls.env['account.tax'].create({ 'name': "Fixed tax bis", 'amount_type': 'fixed', 'amount': 15, 'sequence': 2, }) cls.percent_tax = cls.env['account.tax'].create({ 'name': "Percent tax", 'amount_type': 'percent', 'amount': 10, 'sequence': 3, }) cls.percent_tax_bis = cls.env['account.tax'].create({ 'name': "Percent tax bis", 'amount_type': 'percent', 'amount': 10, 'sequence': 4, }) cls.division_tax = cls.env['account.tax'].create({ 'name': "Division tax", 'amount_type': 'division', 'amount': 10, 'sequence': 4, }) cls.group_tax = cls.env['account.tax'].create({ 'name': "Group tax", 'amount_type': 'group', 'amount': 0, 'sequence': 5, 'children_tax_ids': [ (4, cls.fixed_tax.id, 0), (4, cls.percent_tax.id, 0) ] }) cls.group_tax_bis = cls.env['account.tax'].create({ 'name': "Group tax bis", 'amount_type': 'group', 'amount': 0, 'sequence': 6, 'children_tax_ids': [ (4, cls.fixed_tax.id, 0), (4, cls.percent_tax.id, 0) ] }) cls.group_tax_percent = cls.env['account.tax'].create({ 'name': "Group tax percent", 'amount_type': 'group', 'amount': 0, 'sequence': 6, 'children_tax_ids': [ (4, cls.percent_tax.id, 0), (4, cls.percent_tax_bis.id, 0) ] }) cls.group_of_group_tax = cls.env['account.tax'].create({ 'name': "Group of group tax", 'amount_type': 'group', 'amount': 0, 'sequence': 7, 'children_tax_ids': [ (4, cls.group_tax.id, 0), (4, cls.group_tax_bis.id, 0) ] }) cls.tax_with_no_account = cls.env['account.tax'].create({ 'name': "Tax with no account", 'amount_type': 'fixed', 'amount': 0, 'sequence': 8, }) some_account = cls.env['account.account'].search([], limit=1) cls.tax_with_account = cls.env['account.tax'].create({ 'name': "Tax with account", 'amount_type': 'fixed', 'amount': 0, 'sequence': 8, 'invoice_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0,0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': some_account.id, }), ], 'refund_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0,0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': some_account.id, }), ], }) cls.tax_0_percent = cls.env['account.tax'].with_company(cls.company_data['company']).create({ 'name': "test_0_percent", 'amount_type': 'percent', 'amount': 0, }) cls.tax_5_percent = cls.env['account.tax'].with_company(cls.company_data['company']).create({ 'name': "test_5_percent", 'amount_type': 'percent', 'amount': 5, }) cls.tax_8_percent = cls.env['account.tax'].with_company(cls.company_data['company']).create({ 'name': "test_8_percent", 'amount_type': 'percent', 'amount': 8, }) cls.tax_12_percent = cls.env['account.tax'].with_company(cls.company_data['company']).create({ 'name': "test_12_percent", 'amount_type': 'percent', 'amount': 12, }) cls.tax_19_percent = cls.env['account.tax'].with_company(cls.company_data_2['company']).create({ 'name': "test_19_percent", 'amount_type': 'percent', 'amount': 19, }) cls.tax_21_percent = cls.env['account.tax'].with_company(cls.company_data['company']).create({ 'name': "test_21_percent", 'amount_type': 'percent', 'amount': 19, }) cls.tax_21_percent = cls.env['account.tax'].with_company(cls.company_data['company']).create({ 'name': "test_rounding_methods_2", 'amount_type': 'percent', 'amount': 21, }) cls.bank_journal = cls.company_data['default_journal_bank'] cls.bank_account = cls.bank_journal.default_account_id cls.expense_account = cls.company_data['default_account_expense'] def _check_compute_all_results(self, total_included, total_excluded, taxes, res): self.assertAlmostEqual(res['total_included'], total_included) self.assertAlmostEqual(res['total_excluded'], total_excluded) for i in range(0, len(taxes)): self.assertAlmostEqual(res['taxes'][i]['base'], taxes[i][0]) self.assertAlmostEqual(res['taxes'][i]['amount'], taxes[i][1]) @tagged('post_install', '-at_install') class TestTax(TestTaxCommon): @classmethod def setUpClass(cls): super(TestTax, cls).setUpClass() def test_tax_group_of_group_tax(self): self.fixed_tax.include_base_amount = True res = self.group_of_group_tax.compute_all(200.0) self._check_compute_all_results( 263, # 'total_included' 200, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (200.0, 10.0), # | 1 | 10 | | t (210.0, 21.0), # | 3 | 10% | | (210.0, 10.0), # | 1 | 10 | | t (220.0, 22.0), # | 3 | 10% | | # --------------------------------------------------- ], res ) def test_tax_group(self): res = self.group_tax.compute_all(200.0) self._check_compute_all_results( 230, # 'total_included' 200, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (200.0, 10.0), # | 1 | 10 | | (200.0, 20.0), # | 3 | 10% | | # --------------------------------------------------- ], res ) def test_tax_group_percent(self): res = self.group_tax_percent.with_context({'force_price_include':True}).compute_all(100.0) self._check_compute_all_results( 100, # 'total_included' 83.33, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (83.33, 8.33), # | 1 | 10% | | (83.33, 8.34), # | 2 | 10% | | # --------------------------------------------------- ], res ) def test_tax_percent_division(self): self.division_tax.price_include = True self.division_tax.include_base_amount = True res_division = self.division_tax.compute_all(200.0) self._check_compute_all_results( 200, # 'total_included' 180, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (180.0, 20.0), # | 4 | 10/ | t | t # --------------------------------------------------- ], res_division ) self.percent_tax.price_include = False self.percent_tax.include_base_amount = False res_percent = self.percent_tax.compute_all(100.0) self._check_compute_all_results( 110, # 'total_included' 100, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (100.0, 10.0), # | 3 | 10% | | # --------------------------------------------------- ], res_percent ) self.division_tax.price_include = False self.division_tax.include_base_amount = False res_division = self.division_tax.compute_all(180.0) self._check_compute_all_results( 200, # 'total_included' 180, # 'total_excluded' [ # base, amount | seq | amount | incl | incl_base # --------------------------------------------------- (180.0, 20.0), # | 4 | 10/ | | # --------------------------------------------------- ], res_division ) self.percent_tax.price_include = True self.percent_tax.include_base_amount = True res_percent = self.percent_tax.compute_all(110.0) self._check_compute_all_results( 110, # 'total_included' 100, # 'total_excluded' [ # base, amount | seq | amount | incl | incl_base # --------------------------------------------------- (100.0, 10.0), # | 3 | 10% | t | t # --------------------------------------------------- ], res_percent ) self.percent_tax_bis.price_include = True self.percent_tax_bis.include_base_amount = True self.percent_tax_bis.amount = 21 res_percent = self.percent_tax_bis.compute_all(7.0) self._check_compute_all_results( 7.0, # 'total_included' 5.79, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (5.79, 1.21), # | 3 | 21% | t | t # --------------------------------------------------- ], res_percent ) def test_tax_sequence_normalized_set(self): self.division_tax.sequence = 1 self.fixed_tax.sequence = 2 self.percent_tax.sequence = 3 taxes_set = (self.group_tax | self.division_tax) res = taxes_set.compute_all(200.0) self._check_compute_all_results( 252.22, # 'total_included' 200, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (200.0, 22.22), # | 1 | 10/ | | (200.0, 10.0), # | 2 | 10 | | (200.0, 20.0), # | 3 | 10% | | # --------------------------------------------------- ], res ) def test_fixed_tax_include_base_amount(self): self.fixed_tax.include_base_amount = True res = self.group_tax.compute_all(200.0) self._check_compute_all_results( 231, # 'total_included' 200, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (200.0, 10.0), # | 1 | 10 | | t (210.0, 21.0), # | 3 | 10% | | # --------------------------------------------------- ], res ) self.fixed_tax.price_include = True self.fixed_tax.include_base_amount = False res = self.fixed_tax.compute_all(100.0, quantity=2.0) self._check_compute_all_results( 200, # 'total_included' 180, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (180.0, 20.0), # | 1 | 20 | | t # --------------------------------------------------- ], res ) def test_percent_tax_include_base_amount(self): self.percent_tax.price_include = True self.percent_tax.amount = 21.0 res = self.percent_tax.compute_all(7.0) self._check_compute_all_results( 7.0, # 'total_included' 5.79, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (5.79, 1.21), # | 3 | 21% | t | # --------------------------------------------------- ], res ) self.percent_tax.price_include = True self.percent_tax.amount = 20.0 res = self.percent_tax.compute_all(399.99) self._check_compute_all_results( 399.99, # 'total_included' 333.33, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (333.33, 66.66), # | 3 | 20% | t | # --------------------------------------------------- ], res ) def test_tax_decimals(self): """Test the rounding of taxes up to 6 decimals (maximum decimals places allowed for currencies)""" self.env.user.company_id.currency_id.rounding = 0.000001 self.percent_tax.price_include = True self.percent_tax.amount = 21.0 res = self.percent_tax.compute_all(7.0) self._check_compute_all_results( 7.0, # 'total_included' 5.785124, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # -------------------------------------------------------- (5.785124, 1.214876), # | 3 | 21% | t | # -------------------------------------------------------- ], res ) self.percent_tax.price_include = True self.percent_tax.amount = 20.0 res = self.percent_tax.compute_all(399.999999) self._check_compute_all_results( 399.999999, # 'total_included' 333.333333, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # ----------------------------------------------------------- (333.333333, 66.666666), # | 3 | 20% | t | # ----------------------------------------------------------- ], res ) def test_advanced_taxes_computation_0(self): '''Test more advanced taxes computation (see issue 34471).''' tax_1 = self.env['account.tax'].create({ 'name': 'test_advanced_taxes_computation_0_1', 'amount_type': 'percent', 'amount': 10, 'price_include': True, 'include_base_amount': True, 'sequence': 1, 'invoice_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], 'refund_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], }) tax_2 = self.env['account.tax'].create({ 'name': 'test_advanced_taxes_computation_0_2', 'amount_type': 'percent', 'amount': 10, 'sequence': 2, 'invoice_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], 'refund_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], }) tax_3 = self.env['account.tax'].create({ 'name': 'test_advanced_taxes_computation_0_3', 'amount_type': 'percent', 'amount': 10, 'price_include': True, 'sequence': 3, 'invoice_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], 'refund_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], }) tax_4 = self.env['account.tax'].create({ 'name': 'test_advanced_taxes_computation_0_4', 'amount_type': 'percent', 'amount': 10, 'sequence': 4, 'invoice_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], 'refund_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], }) tax_5 = self.env['account.tax'].create({ 'name': 'test_advanced_taxes_computation_0_5', 'amount_type': 'percent', 'amount': 10, 'price_include': True, 'sequence': 5, 'invoice_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], 'refund_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], }) taxes = tax_1 + tax_2 + tax_3 + tax_4 + tax_5 # Test with positive amount. self._check_compute_all_results( 154, # 'total_included' 100, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (100.0, 5.0), # | 1 | 10% | t | t (100.0, 5.0), # | 1 | 10% | t | t (110.0, 5.5), # | 2 | 10% | | (110.0, 5.5), # | 2 | 10% | | (110.0, 5.5), # | 3 | 10% | t | (110.0, 5.5), # | 3 | 10% | t | (110.0, 5.5), # | 4 | 10% | | (110.0, 5.5), # | 4 | 10% | | (110.0, 5.5), # | 5 | 10% | t | (110.0, 5.5), # | 5 | 10% | t | # --------------------------------------------------- ], taxes.compute_all(132.0) ) # Test with negative amount. self._check_compute_all_results( -154, # 'total_included' -100, # 'total_excluded' [ # base , amount | seq | amount | incl | incl_base # --------------------------------------------------- (-100.0, -5.0), # | 1 | 10% | t | t (-100.0, -5.0), # | 1 | 10% | t | t (-110.0, -5.5), # | 2 | 10% | | (-110.0, -5.5), # | 2 | 10% | | (-110.0, -5.5), # | 3 | 10% | t | (-110.0, -5.5), # | 3 | 10% | t | (-110.0, -5.5), # | 4 | 10% | | (-110.0, -5.5), # | 4 | 10% | | (-110.0, -5.5), # | 5 | 10% | t | (-110.0, -5.5), # | 5 | 10% | t | # --------------------------------------------------- ], taxes.compute_all(-132.0) ) def test_intracomm_taxes_computation_0(self): ''' Test usage of intracomm taxes having e.g.+100%, -100% as repartition lines. ''' intracomm_tax = self.env['account.tax'].create({ 'name': 'test_intracomm_taxes_computation_0_1', 'amount_type': 'percent', 'amount': 21, 'invoice_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': -100.0}), ], 'refund_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': -100.0}), ], }) # Test with positive amount. self._check_compute_all_results( 100, # 'total_included' 100, # 'total_excluded' [ # base , amount # --------------- (100.0, 21.0), (100.0, -21.0), # --------------- ], intracomm_tax.compute_all(100.0) ) # Test with negative amount. self._check_compute_all_results( -100, # 'total_included' -100, # 'total_excluded' [ # base , amount # --------------- (-100.0, -21.0), (-100.0, 21.0), # --------------- ], intracomm_tax.compute_all(-100.0) ) def test_rounding_issues_0(self): ''' Test taxes having a complex setup of repartition lines. ''' tax = self.env['account.tax'].create({ 'name': 'test_rounding_issues_0', 'amount_type': 'percent', 'amount': 3, 'invoice_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], 'refund_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), ], }) # Test with positive amount. self._check_compute_all_results( 1.09, # 'total_included' 1, # 'total_excluded' [ # base , amount # --------------- (1.0, 0.01), (1.0, 0.01), (1.0, 0.01), (1.0, 0.02), (1.0, 0.02), (1.0, 0.02), # --------------- ], tax.compute_all(1.0) ) # Test with negative amount. self._check_compute_all_results( -1.09, # 'total_included' -1, # 'total_excluded' [ # base , amount # --------------- (-1.0, -0.01), (-1.0, -0.01), (-1.0, -0.01), (-1.0, -0.02), (-1.0, -0.02), (-1.0, -0.02), # --------------- ], tax.compute_all(-1.0) ) def test_rounding_issues_1(self): ''' Test taxes having a complex setup of repartition lines. ''' tax = self.env['account.tax'].create({ 'name': 'test_advanced_taxes_repartition_lines_computation_1', 'amount_type': 'percent', 'amount': 3, 'invoice_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': -50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 25.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 25.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': -25.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': -25.0}), ], 'refund_repartition_line_ids': [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': -50.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 25.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 25.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': -25.0}), (0, 0, {'repartition_type': 'tax', 'factor_percent': -25.0}), ], }) # Test with positive amount. self._check_compute_all_results( 1, # 'total_included' 1, # 'total_excluded' [ # base , amount # --------------- (1.0, 0.02), (1.0, -0.02), (1.0, 0.01), (1.0, 0.01), (1.0, -0.01), (1.0, -0.01), # --------------- ], tax.compute_all(1.0) ) # Test with negative amount. self._check_compute_all_results( -1, # 'total_included' -1, # 'total_excluded' [ # base , amount # --------------- (-1.0, -0.02), (-1.0, 0.02), (-1.0, -0.01), (-1.0, -0.01), (-1.0, 0.01), (-1.0, 0.01), # --------------- ], tax.compute_all(-1.0) ) def test_rounding_tax_excluded_round_per_line_01(self): ''' Test the rounding of a 19% price excluded tax in an invoice having 22689 and 9176 as lines. The decimal precision is set to zero. The computation must be similar to round(22689 * 0.19) + round(9176 * 0.19). ''' self.tax_19_percent.company_id.currency_id.rounding = 1.0 self.tax_19_percent.company_id.tax_calculation_rounding_method = 'round_per_line' res1 = self.tax_19_percent.compute_all(22689) self._check_compute_all_results( 27000, # 'total_included' 22689, # 'total_excluded' [ # base, amount # --------------- (22689, 4311), # --------------- ], res1 ) res2 = self.tax_19_percent.compute_all(9176) self._check_compute_all_results( 10919, # 'total_included' 9176, # 'total_excluded' [ # base , amount # --------------- (9176, 1743), # --------------- ], res2 ) def test_rounding_tax_excluded_round_globally(self): ''' Test the rounding of a 19% price excluded tax in an invoice having 22689 and 9176 as lines. The decimal precision is set to zero. The computation must be similar to round((22689 + 9176) * 0.19). ''' self.tax_19_percent.company_id.tax_calculation_rounding_method = 'round_globally' res1 = self.tax_19_percent.compute_all(22689) self._check_compute_all_results( 27000, # 'total_included' 22689, # 'total_excluded' [ # base, amount # --------------- (22689, 4310.91), # --------------- ], res1 ) res2 = self.tax_19_percent.compute_all(9176) self._check_compute_all_results( 10919, # 'total_included' 9176, # 'total_excluded' [ # base , amount # --------------- (9176, 1743.44), # --------------- ], res2 ) def test_rounding_tax_included_round_per_line_01(self): ''' Test the rounding of a 19% price included tax in an invoice having 27000 and 10920 as lines. The decimal precision is set to zero. The computation must be similar to round(27000 / 1.19) + round(10920 / 1.19). ''' self.tax_19_percent.price_include = True self.tax_19_percent.company_id.currency_id.rounding = 1.0 self.tax_19_percent.company_id.tax_calculation_rounding_method = 'round_per_line' res1 = self.tax_19_percent.compute_all(27000) self._check_compute_all_results( 27000, # 'total_included' 22689, # 'total_excluded' [ # base , amount # --------------- (22689, 4311), # --------------- ], res1 ) res2 = self.tax_19_percent.compute_all(10920) self._check_compute_all_results( 10920, # 'total_included' 9176, # 'total_excluded' [ # base , amount # --------------- (9176, 1744), # --------------- ], res2 ) def test_rounding_tax_included_round_per_line_02(self): ''' Test the rounding of a 12% price included tax in an invoice having 52.50 as line. The decimal precision is set to 2. ''' self.tax_12_percent.price_include = True self.tax_12_percent.company_id.currency_id.rounding = 0.01 res1 = self.tax_12_percent.compute_all(52.50) self._check_compute_all_results( 52.50, # 'total_included' 46.88, # 'total_excluded' [ # base , amount # ------------- (46.88, 5.62), # ------------- ], res1 ) def test_rounding_tax_included_round_per_line_03(self): ''' Test the rounding of a 8% and 0% price included tax in an invoice having 8 * 15.55 as line. The decimal precision is set to 2. ''' self.tax_0_percent.company_id.currency_id.rounding = 0.01 self.tax_0_percent.price_include = True self.tax_8_percent.price_include = True self.group_tax.children_tax_ids = [(6, 0, self.tax_0_percent.ids)] self.group_tax_bis.children_tax_ids = [(6, 0, self.tax_8_percent.ids)] res1 = (self.tax_8_percent | self.tax_0_percent).compute_all(15.55, quantity=8.0) self._check_compute_all_results( 124.40, # 'total_included' 115.19, # 'total_excluded' [ # base , amount # ------------- (115.19, 9.21), (115.19, 0.00), # ------------- ], res1 ) res2 = (self.tax_0_percent | self.tax_8_percent).compute_all(15.55, quantity=8.0) self._check_compute_all_results( 124.40, # 'total_included' 115.19, # 'total_excluded' [ # base , amount # ------------- (115.19, 0.00), (115.19, 9.21), # ------------- ], res2 ) def test_rounding_tax_included_round_per_line_04(self): ''' Test the rounding of a 5% price included tax. The decimal precision is set to 0.05. ''' self.tax_5_percent.price_include = True self.tax_5_percent.company_id.currency_id.rounding = 0.05 self.tax_5_percent.company_id.tax_calculation_rounding_method = 'round_per_line' res1 = self.tax_5_percent.compute_all(5) self._check_compute_all_results( 5, # 'total_included' 4.75, # 'total_excluded' [ # base , amount # --------------- (4.75, 0.25), # --------------- ], res1 ) res2 = self.tax_5_percent.compute_all(10) self._check_compute_all_results( 10, # 'total_included' 9.5, # 'total_excluded' [ # base , amount # --------------- (9.5, 0.5), # --------------- ], res2 ) res3 = self.tax_5_percent.compute_all(50) self._check_compute_all_results( 50, # 'total_included' 47.6, # 'total_excluded' [ # base , amount # --------------- (47.6, 2.4), # --------------- ], res3 ) def test_rounding_tax_included_round_globally_01(self): ''' Test the rounding of a 19% price included tax in an invoice having 27000 and 10920 as lines. The decimal precision is set to zero. The computation must be similar to round((27000 + 10920) / 1.19). ''' self.tax_19_percent.price_include = True self.tax_19_percent.company_id.tax_calculation_rounding_method = 'round_globally' res1 = self.tax_19_percent.compute_all(27000) self._check_compute_all_results( 27000, # 'total_included' 22689, # 'total_excluded' [ # base , amount # --------------- (22689, 4311), # --------------- ], res1 ) res2 = self.tax_19_percent.compute_all(10920) self._check_compute_all_results( 10920, # 'total_included' 9176, # 'total_excluded' [ # base , amount # --------------- (9176, 1744), # --------------- ], res2 ) def test_rounding_tax_included_round_globally_02(self): ''' Test the rounding of a 21% price included tax in an invoice having 11.90 and 2.80 as lines. The decimal precision is set to 2. ''' self.tax_21_percent.price_include = True self.tax_21_percent.company_id.currency_id.rounding = 0.01 self.tax_21_percent.company_id.tax_calculation_rounding_method = 'round_globally' res1 = self.tax_21_percent.compute_all(11.90) self._check_compute_all_results( 11.90, # 'total_included' 9.83, # 'total_excluded' [ # base , amount # --------------- (9.83, 2.07), # --------------- ], res1 ) res2 = self.tax_21_percent.compute_all(2.80) self._check_compute_all_results( 2.80, # 'total_included' 2.31, # 'total_excluded' [ # base , amount # --------------- (2.31, 0.49), # --------------- ], res2 ) def test_rounding_tax_included_round_globally_03(self): ''' Test the rounding of a 5% price included tax. The decimal precision is set to 0.05. ''' self.tax_5_percent.price_include = True self.tax_5_percent.company_id.currency_id.rounding = 0.05 self.tax_5_percent.company_id.tax_calculation_rounding_method = 'round_globally' res1 = self.tax_5_percent.compute_all(5) self._check_compute_all_results( 5, # 'total_included' 4.75, # 'total_excluded' [ # base , amount # --------------- (4.75, 0.25), # --------------- ], res1 ) res2 = self.tax_5_percent.compute_all(10) self._check_compute_all_results( 10, # 'total_included' 9.5, # 'total_excluded' [ # base , amount # --------------- (9.50, 0.50), # --------------- ], res2 ) res3 = self.tax_5_percent.compute_all(50) self._check_compute_all_results( 50, # 'total_included' 47.6, # 'total_excluded' [ # base , amount # --------------- (47.60, 2.40), # --------------- ], res3 ) def test_is_base_affected(self): taxes = self.env['account.tax'].create([{ 'name': 'test_is_base_affected%s' % i, 'amount_type': 'percent', 'amount': amount, 'include_base_amount': include_base_amount, 'is_base_affected': is_base_affected, 'sequence': i, } for i, amount, include_base_amount, is_base_affected in [ (0, 6, True, True), (1, 6, True, False), (2, 10, False, True), ]]) compute_all_results = taxes.compute_all(100.0) # Check the balance of the generated move lines self._check_compute_all_results( 123.2, # 'total_included' 100.0, # 'total_excluded' [ # base, amount # ------------------------- (100.0, 6.0), (100.0, 6.0), (112.0, 11.2), # ------------------------- ], compute_all_results, ) # Check the tax_ids on tax lines expected_tax_ids_list = [taxes[2].ids, taxes[2].ids, []] tax_ids_list = [tax_line['tax_ids'] for tax_line in compute_all_results['taxes']] self.assertEqual(tax_ids_list, expected_tax_ids_list, "Only a tax affected by previous taxes should have tax_ids set on its tax line when used after an 'include_base_amount' tax.") def test_mixing_price_included_excluded_with_affect_base(self): tax_10_fix = self.env['account.tax'].create({ 'name': "tax_10_fix", 'amount_type': 'fixed', 'amount': 10.0, 'include_base_amount': True, }) tax_21 = self.env['account.tax'].create({ 'name': "tax_21", 'amount_type': 'percent', 'amount': 21.0, 'price_include': True, 'include_base_amount': True, }) self._check_compute_all_results( 1222.1, # 'total_included' 1000.0, # 'total_excluded' [ # base , amount # --------------- (1000.0, 10.0), (1010.0, 212.1), # --------------- ], (tax_10_fix + tax_21).compute_all(1210), ) def test_price_included_repartition_sum_0(self): """ Tests the case where a tax with a non-zero value has a sum of tax repartition factors of zero and is included in price. It shouldn't behave in the same way as a 0% tax. """ test_tax = self.env['account.tax'].create({ 'name': "Definitely not a 0% tax", 'amount_type': 'percent', 'amount': 42, 'price_include': True, 'invoice_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0,0, { 'factor_percent': 100, 'repartition_type': 'tax', }), (0,0, { 'factor_percent': -100, 'repartition_type': 'tax', }), ], 'refund_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0,0, { 'factor_percent': 100, 'repartition_type': 'tax', }), (0,0, { 'factor_percent': -100, 'repartition_type': 'tax', }), ], }) compute_all_res = test_tax.compute_all(100) self._check_compute_all_results( 100, # 'total_included' 100, # 'total_excluded' [ # base , amount # --------------- (100, 42), (100, -42), # --------------- ], compute_all_res )
38.278871
44,748
5,160
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.tests.common import TransactionCase class AccountingTestTemplConsistency(TransactionCase): '''Test the templates consistency between some objects like account.account when account.account.template. ''' def get_model_fields(self, model, extra_domain=None): # Retrieve fields to compare domain = [ ('model', '=', model), ('state', '=', 'base'), ('related', '=', False), ('compute', '=', False), ('store', '=', True), ] if extra_domain: domain += extra_domain return self.env['ir.model.fields'].search(domain) def check_fields_consistency(self, model_from, model_to, exceptions=None): '''Check the consistency of fields from one model to another by comparing if all fields in the model_from are present in the model_to. :param model_from: The model to compare. :param model_to: The compared model. :param exceptions: Not copied model's fields. ''' extra_domain = [('name', 'not in', exceptions)] if exceptions else [] from_fields = self.get_model_fields(model_from, extra_domain=extra_domain).filtered_domain([('modules', '=', 'account')]) to_fields_set = set([f.name for f in self.get_model_fields(model_to)]) for field in from_fields: assert field.name in to_fields_set,\ 'Missing field "%s" from "%s" in model "%s".' % (field.name, model_from, model_to) def test_account_account_fields(self): '''Test fields consistency for ('account.account', 'account.account.template') ''' self.check_fields_consistency( 'account.account.template', 'account.account', exceptions=['chart_template_id', 'nocreate']) self.check_fields_consistency( 'account.account', 'account.account.template', exceptions=['company_id', 'deprecated', 'opening_debit', 'opening_credit', 'allowed_journal_ids', 'group_id', 'root_id', 'is_off_balance']) def test_account_tax_fields(self): '''Test fields consistency for ('account.tax', 'account.tax.template') ''' self.check_fields_consistency('account.tax.template', 'account.tax', exceptions=['chart_template_id']) self.check_fields_consistency('account.tax', 'account.tax.template', exceptions=['company_id', 'country_id']) self.check_fields_consistency('account.tax.repartition.line.template', 'account.tax.repartition.line', exceptions=['plus_report_line_ids', 'minus_report_line_ids']) self.check_fields_consistency('account.tax.repartition.line', 'account.tax.repartition.line.template', exceptions=['tag_ids', 'country_id', 'company_id', 'sequence']) def test_fiscal_position_fields(self): '''Test fields consistency for ('account.fiscal.position', 'account.fiscal.position.template') ''' #main self.check_fields_consistency('account.fiscal.position.template', 'account.fiscal.position', exceptions=['chart_template_id']) self.check_fields_consistency('account.fiscal.position', 'account.fiscal.position.template', exceptions=['active', 'company_id', 'states_count', 'foreign_vat']) #taxes self.check_fields_consistency('account.fiscal.position.tax.template', 'account.fiscal.position.tax') self.check_fields_consistency('account.fiscal.position.tax', 'account.fiscal.position.tax.template') #accounts self.check_fields_consistency('account.fiscal.position.account.template', 'account.fiscal.position.account') self.check_fields_consistency('account.fiscal.position.account', 'account.fiscal.position.account.template') def test_reconcile_model_fields(self): '''Test fields consistency for ('account.reconcile.model', 'account.reconcile.model.template') ''' self.check_fields_consistency('account.reconcile.model.template', 'account.reconcile.model', exceptions=['chart_template_id']) # exclude fields from inherited 'mail.thread' mail_thread_fields = [field.name for field in self.get_model_fields('mail.thread')] self.check_fields_consistency( 'account.reconcile.model', 'account.reconcile.model.template', exceptions=mail_thread_fields + ['active', 'company_id', 'past_months_limit', 'partner_mapping_line_ids'], ) # lines self.check_fields_consistency('account.reconcile.model.line.template', 'account.reconcile.model.line', exceptions=['chart_template_id']) self.check_fields_consistency('account.reconcile.model.line', 'account.reconcile.model.line.template', exceptions=['company_id', 'journal_id', 'analytic_account_id', 'analytic_tag_ids', 'amount']) def test_account_group_fields(self): '''Test fields consistency for ('account.group', 'account.group.template') ''' self.check_fields_consistency('account.group', 'account.group.template', exceptions=['company_id', 'parent_path']) self.check_fields_consistency('account.group.template', 'account.group', exceptions=['chart_template_id'])
60.705882
5,160
45,697
py
PYTHON
15.0
# -*- coding: utf-8 -*- #pylint: disable=too-many-lines from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo import Command @tagged('post_install', '-at_install') class TestAccountTaxDetailsReport(AccountTestInvoicingCommon): def _dispatch_move_lines(self, moves): base_lines = moves.line_ids\ .filtered(lambda x: x.tax_ids and not x.tax_line_id)\ .sorted(lambda x: (x.move_id, x.id, -abs(x.amount_currency))) tax_lines = moves.line_ids\ .filtered(lambda x: x.tax_line_id)\ .sorted(lambda x: (x.move_id, x.tax_line_id, x.tax_ids, x.tax_repartition_line_id)) return base_lines, tax_lines def _get_tax_details(self, fallback=False, extra_domain=None): domain = [('company_id', '=', self.env.company.id)] + (extra_domain or []) tax_details_query, tax_details_params = self.env['account.move.line']._get_query_tax_details_from_domain(domain, fallback=fallback) self.cr.execute(tax_details_query, tax_details_params) tax_details_res = self.cr.dictfetchall() return sorted(tax_details_res, key=lambda x: (x['base_line_id'], abs(x['base_amount']), abs(x['tax_amount']))) def assertTaxDetailsValues(self, tax_details, expected_values_list): self.assertEqual(len(tax_details), len(expected_values_list)) for i, expected_values in enumerate(expected_values_list): keys = set(expected_values.keys()) tax_detail = tax_details[i] self.assertDictEqual({k: v for k, v in tax_detail.items() if k in keys}, expected_values) def assertTotalAmounts(self, moves, tax_details): tax_lines = moves.line_ids.filtered('tax_line_id') taxes = tax_lines.mapped(lambda x: x.group_tax_id or x.tax_line_id) for tax in taxes: lines = tax_lines.filtered(lambda x: (x.group_tax_id or x.tax_line_id) == tax) tax_amount = sum(lines.mapped('balance')) tax_details_amount = sum(x['tax_amount'] for x in tax_details if (x['group_tax_id'] or x['tax_id']) == tax.id) self.assertAlmostEqual(tax_amount, tax_details_amount) def test_affect_base_amount_1(self): tax_20_affect = self.env['account.tax'].create({ 'name': "tax_20_affect", 'amount_type': 'percent', 'amount': 20.0, 'include_base_amount': True, }) tax_10 = self.env['account.tax'].create({ 'name': "tax_10", 'amount_type': 'percent', 'amount': 10.0, }) tax_5 = self.env['account.tax'].create({ 'name': "tax_5", 'amount_type': 'percent', 'amount': 5.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set((tax_20_affect + tax_10 + tax_5).ids)], }), Command.create({ 'name': 'line2', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set(tax_10.ids)], }), Command.create({ 'name': 'line3', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set(tax_10.ids)], }), Command.create({ 'name': 'line4', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 2000.0, 'tax_ids': [Command.set((tax_20_affect + tax_10).ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues(tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -200.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -200.0, 'tax_amount': -20.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -1000.0, 'tax_amount': -50.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -1000.0, 'tax_amount': -200.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[3].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -400.0, 'tax_amount': -40.0, }, { 'base_line_id': base_lines[3].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -2000.0, 'tax_amount': -200.0, }, { 'base_line_id': base_lines[3].id, 'tax_line_id': tax_lines[3].id, 'base_amount': -2000.0, 'tax_amount': -400.0, }, ]) self.assertTotalAmounts(invoice, tax_details) # Same with a group of taxes tax_group = self.env['account.tax'].create({ 'name': "tax_group", 'amount_type': 'group', 'children_tax_ids': [Command.set((tax_20_affect + tax_10 + tax_5).ids)], }) invoice.write({ 'invoice_line_ids': [Command.update(base_lines[0].id, { 'tax_ids': [Command.set(tax_group.ids)], })], }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues(tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[4].id, 'base_amount': -200.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[3].id, 'base_amount': -200.0, 'tax_amount': -20.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[4].id, 'base_amount': -1000.0, 'tax_amount': -50.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[3].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -1000.0, 'tax_amount': -200.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[3].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -400.0, 'tax_amount': -40.0, }, { 'base_line_id': base_lines[3].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -2000.0, 'tax_amount': -200.0, }, { 'base_line_id': base_lines[3].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -2000.0, 'tax_amount': -400.0, }, ]) self.assertTotalAmounts(invoice, tax_details) def test_affect_base_amount_2(self): taxes_10_affect = self.env['account.tax'].create([{ 'name': "tax_10_affect_%s" % i, 'amount_type': 'percent', 'amount': 10.0, 'include_base_amount': True, } for i in range(3)]) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set(taxes_10_affect.ids)], }), Command.create({ 'name': 'line2', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set((taxes_10_affect[0] + taxes_10_affect[2]).ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -100.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -100.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -110.0, 'tax_amount': -11.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -100.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[3].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_affect_base_amount_3(self): eco_tax = self.env['account.tax'].create({ 'name': "eco_tax", 'amount_type': 'fixed', 'amount': 5.0, 'include_base_amount': True, }) tax_20 = self.env['account.tax'].create({ 'name': "tax_20", 'amount_type': 'percent', 'amount': 20.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 95.0, 'tax_ids': [Command.set((eco_tax + tax_20).ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -5.0, 'tax_amount': -1.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -95.0, 'tax_amount': -5.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -95.0, 'tax_amount': -19.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_affect_base_amount_4(self): tax_10 = self.env['account.tax'].create({ 'name': "eco_tax", 'amount_type': 'percent', 'amount': 10.0, 'include_base_amount': True, }) tax_20 = self.env['account.tax'].create({ 'name': "tax_20", 'amount_type': 'percent', 'amount': 20.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 100.0, 'tax_ids': [Command.set((tax_10 + tax_20).ids)], }), Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 100.0, 'tax_ids': [Command.set(tax_10.ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -10.0, 'tax_amount': -2.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -100.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -100.0, 'tax_amount': -20.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -100.0, 'tax_amount': -10.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_affect_base_amount_5(self): affecting_tax = self.env['account.tax'].create({ 'name': 'Affecting', 'amount': 42, 'amount_type': 'percent', 'type_tax_use': 'sale', 'include_base_amount': True, 'sequence': 0, }) affected_tax = self.env['account.tax'].create({ 'name': 'Affected', 'amount': 10, 'amount_type': 'percent', 'type_tax_use': 'sale', 'sequence': 1 }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2021-08-01', 'invoice_line_ids': [ Command.create({ 'name': "affecting", 'account_id': self.company_data['default_account_revenue'].id, 'quantity': 1.0, 'price_unit': 100.0, 'tax_ids': affecting_tax.ids, }), Command.create({ 'name': "affected", 'account_id': self.company_data['default_account_revenue'].id, 'quantity': 1.0, 'price_unit': 100.0, 'tax_ids': affected_tax.ids, }), Command.create({ 'name': "affecting + affected", 'account_id': self.company_data['default_account_revenue'].id, 'quantity': 1.0, 'price_unit': 100.0, 'tax_ids': (affecting_tax + affected_tax).ids, }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -100.0, 'tax_amount': -42.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -100.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -42.0, 'tax_amount': -4.2, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -100.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines[2].id, 'base_amount': -100.0, 'tax_amount': -42.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_round_globally_rounding(self): self.env.company.tax_calculation_rounding_method = 'round_globally' tax_50 = self.env['account.tax'].create({ 'name': "tax_50", 'amount_type': 'percent', 'amount': 50.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line%s' % i, 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 0.01, 'tax_ids': [Command.set(tax_50.ids)], }) for i in range(7)] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines.id, 'base_amount': -0.01, 'tax_amount': -0.01, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines.id, 'base_amount': -0.01, 'tax_amount': 0.0, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines.id, 'base_amount': -0.01, 'tax_amount': -0.01, }, { 'base_line_id': base_lines[3].id, 'tax_line_id': tax_lines.id, 'base_amount': -0.01, 'tax_amount': 0.00, }, { 'base_line_id': base_lines[4].id, 'tax_line_id': tax_lines.id, 'base_amount': -0.01, 'tax_amount': -0.01, }, { 'base_line_id': base_lines[5].id, 'tax_line_id': tax_lines.id, 'base_amount': -0.01, 'tax_amount': 0.0, }, { 'base_line_id': base_lines[6].id, 'tax_line_id': tax_lines.id, 'base_amount': -0.01, 'tax_amount': -0.01, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_partitioning_lines_by_moves(self): tax_20_affect = self.env['account.tax'].create({ 'name': "tax_20_affect", 'amount_type': 'percent', 'amount': 20.0, 'include_base_amount': True, }) tax_10 = self.env['account.tax'].create({ 'name': "tax_10", 'amount_type': 'percent', 'amount': 10.0, }) invoices = self.env['account.move'] expected_values_list = [] for i in range(1, 6): invoice = invoices.create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': i * 1000.0, 'tax_ids': [Command.set((tax_20_affect + tax_10).ids)], }), ] }) invoices |= invoice base_lines, tax_lines = self._dispatch_move_lines(invoice) expected_values_list += [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -200.0 * i, 'tax_amount': -20.0 * i, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -1000.0 * i, 'tax_amount': -100.0 * i, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -1000.0 * i, 'tax_amount': -200.0 * i, }, ] tax_details = self._get_tax_details() self.assertTaxDetailsValues(tax_details, expected_values_list) self.assertTotalAmounts(invoices, tax_details) def test_fixed_tax_with_negative_quantity(self): fixed_tax = self.env['account.tax'].create({ 'name': "fixed_tax", 'amount_type': 'fixed', 'amount': 10.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 100.0, 'quantity': 5, 'tax_ids': [Command.set(fixed_tax.ids)], }), Command.create({ 'name': 'line2', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 100.0, 'quantity': 9, 'tax_ids': [Command.set(fixed_tax.ids)], }), Command.create({ 'name': 'line3', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 100.0, 'quantity': -4, 'tax_ids': [Command.set(fixed_tax.ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -500.0, 'tax_amount': -50.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -900.0, 'tax_amount': -90.0, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines[0].id, 'base_amount': 400.0, 'tax_amount': 40.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_percent_tax_with_negative_balance(self): percent_tax = self.env['account.tax'].create({ 'name': "percent_tax", 'amount_type': 'percent', 'amount': 10.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 500.0, 'tax_ids': [Command.set(percent_tax.ids)], }), Command.create({ 'name': 'line2', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 900.0, 'tax_ids': [Command.set(percent_tax.ids)], }), Command.create({ 'name': 'line3', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': -400.0, 'tax_ids': [Command.set(percent_tax.ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -500.0, 'tax_amount': -50.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -900.0, 'tax_amount': -90.0, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines[0].id, 'base_amount': 400.0, 'tax_amount': 40.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_fixed_tax_with_negative_balance(self): fixed_tax = self.env['account.tax'].create({ 'name': "fixed_tax", 'amount_type': 'fixed', 'amount': 10.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 500.0, 'tax_ids': [Command.set(fixed_tax.ids)], }), Command.create({ 'name': 'line2', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 900.0, 'tax_ids': [Command.set(fixed_tax.ids)], }), Command.create({ 'name': 'line3', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': -400.0, 'tax_ids': [Command.set(fixed_tax.ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -500.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -900.0, 'tax_amount': -10.0, }, { 'base_line_id': base_lines[2].id, 'tax_line_id': tax_lines[0].id, 'base_amount': 400.0, 'tax_amount': 10.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_multiple_same_tax_lines(self): """ In expense, the same tax line could be generated multiple times. """ percent_tax = self.env['account.tax'].create({ 'name': "percent_tax", 'amount_type': 'percent', 'amount': 10.0, }) tax_rep = percent_tax.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') move = self.env['account.move'].create({ 'date': '2019-01-01', 'line_ids': [ # Base lines Command.create({ 'name': 'base1', 'debit': 1000.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [Command.set(percent_tax.ids)], }), Command.create({ 'name': 'base2', 'debit': 10000.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [Command.set(percent_tax.ids)], }), # Tax lines Command.create({ 'name': 'tax1', 'debit': 100.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_repartition_line_id': tax_rep.id, }), Command.create({ 'name': 'tax1', 'debit': 1000.0, 'credit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_repartition_line_id': tax_rep.id, }), # Balance Command.create({ 'name': 'balance', 'debit': 0.0, 'credit': 12100.0, 'account_id': self.company_data['default_account_receivable'].id, }), ], }) base_lines, tax_lines = self._dispatch_move_lines(move) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': 1000.0, 'tax_amount': 9.09, }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': 1000.0, 'tax_amount': 90.91, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[0].id, 'base_amount': 10000.0, 'tax_amount': 90.91, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[1].id, 'base_amount': 10000.0, 'tax_amount': 909.09, }, ], ) self.assertTotalAmounts(move, tax_details) def test_multiple_same_tax_lines_multi_currencies_manual_edition(self): percent_tax = self.env['account.tax'].create({ 'name': "percent_tax", 'amount_type': 'percent', 'amount': 10.0, }) tax_rep = percent_tax.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') move = self.env['account.move'].create({ 'date': '2019-01-01', 'line_ids': [ # Base lines Command.create({ 'name': 'base1', 'debit': 1200.0, 'credit': 0.0, 'amount_currency': 2400.0, 'account_id': self.company_data['default_account_revenue'].id, 'currency_id': self.currency_data['currency'].id, 'tax_ids': [Command.set(percent_tax.ids)], }), Command.create({ 'name': 'base2', 'debit': 12000.0, 'credit': 0.0, 'amount_currency': 6000.0, 'account_id': self.company_data['default_account_revenue'].id, 'currency_id': self.currency_data['currency'].id, 'tax_ids': [Command.set(percent_tax.ids)], }), # Tax lines Command.create({ 'name': 'tax1', 'debit': 120.0, 'credit': 0.0, 'amount_currency': 360.0, 'account_id': self.company_data['default_account_revenue'].id, 'currency_id': self.currency_data['currency'].id, 'tax_repartition_line_id': tax_rep.id, }), Command.create({ 'name': 'tax1', 'debit': 1200.0, 'credit': 0.0, 'amount_currency': 200.0, 'account_id': self.company_data['default_account_revenue'].id, 'currency_id': self.currency_data['currency'].id, 'tax_repartition_line_id': tax_rep.id, }), # Balance Command.create({ 'name': 'balance', 'debit': 0.0, 'credit': 14520.0, 'account_id': self.company_data['default_account_receivable'].id, }), ], }) base_lines, tax_lines = self._dispatch_move_lines(move) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': 1200.0, 'tax_amount': 10.91, 'base_amount_currency': 2400.0, 'tax_amount_currency': 102.857, # (2400.0 / 8400.0) * (360.0 / 560.0) * 560.0 }, { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[1].id, 'base_amount': 1200.0, 'tax_amount': 109.09, 'base_amount_currency': 2400.0, 'tax_amount_currency': 57.143, # (2400.0 / 8400.0) * (200.0 / 560.0) * 560.0 }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[0].id, 'base_amount': 12000.0, 'tax_amount': 109.09, 'base_amount_currency': 6000.0, 'tax_amount_currency': 257.143, # (6000.0 / 8400.0) * (360.0 / 560.0) * 560.0 }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[1].id, 'base_amount': 12000.0, 'tax_amount': 1090.91, 'base_amount_currency': 6000.0, 'tax_amount_currency': 142.857, # (6000.0 / 8400.0) * (200.0 / 560.0) * 560.0 }, ], ) self.assertTotalAmounts(move, tax_details) def test_mixing_tax_inside_and_outside_a_group_of_taxes(self): percent_tax = self.env['account.tax'].create({ 'name': "percent_tax", 'amount_type': 'percent', 'amount': 10.0, }) tax_group = self.env['account.tax'].create({ 'name': "tax_group", 'amount_type': 'group', 'children_tax_ids': [Command.set(percent_tax.ids)], }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set(percent_tax.ids)], }), Command.create({ 'name': 'line2', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set(tax_group.ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, { 'base_line_id': base_lines[1].id, 'tax_line_id': tax_lines[1].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_broken_configuration(self): percent_tax = self.env['account.tax'].create({ 'name': "percent_tax", 'amount_type': 'percent', 'amount': 10.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set(percent_tax.ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) # Break the configuration tax_lines.account_id = self.company_data['default_account_assets'] tax_details = self._get_tax_details(fallback=True) self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_tax_on_payment(self): percent_tax = self.env['account.tax'].create({ 'name': "percent_tax", 'amount_type': 'percent', 'amount': 10.0, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': self.company_data['default_account_assets'].id, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line1', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': 1000.0, 'tax_ids': [Command.set(percent_tax.ids)], }), ] }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details() self.assertTaxDetailsValues( tax_details, [ { 'base_line_id': base_lines[0].id, 'tax_line_id': tax_lines[0].id, 'base_amount': -1000.0, 'tax_amount': -100.0, }, ], ) self.assertTotalAmounts(invoice, tax_details) def test_amounts_sign(self): for tax_sign in (1, -1): tax = self.env['account.tax'].create({ 'name': "tax", 'amount_type': 'percent', 'amount': tax_sign * 10.0, }) amounts_list = [ (-1000.0, 7000.0, -2000.0), (1000.0, -7000.0, 2000.0), (-1000.0, -7000.0, 2000.0), (1000.0, 7000.0, -2000.0), ] for amounts in amounts_list: with self.subTest(tax_sign=tax_sign, amounts=amounts): invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': [ Command.create({ 'name': 'line2', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': amount, 'tax_ids': [Command.set(tax.ids)], }) for amount in amounts], }) base_lines, tax_lines = self._dispatch_move_lines(invoice) tax_details = self._get_tax_details(extra_domain=[('move_id', '=', invoice.id)]) self.assertTaxDetailsValues( tax_details, [ { 'tax_line_id': tax_lines[0].id, 'base_amount': amount, 'tax_amount': tax_sign * amount * 0.1, } for amount in amounts], ) self.assertTotalAmounts(invoice, tax_details)
37.672712
45,697
50,821
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.exceptions import UserError from odoo.tests import tagged, Form from odoo import fields @tagged('post_install', '-at_install') class TestAccountPaymentRegister(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.currency_data_3 = cls.setup_multi_currency_data({ 'name': "Umbrella", 'symbol': '☂', 'currency_unit_label': "Umbrella", 'currency_subunit_label': "Broken Umbrella", }, rate2017=0.01) cls.payment_debit_account_id = cls.company_data['default_journal_bank'].company_id.account_journal_payment_debit_account_id.copy() cls.payment_credit_account_id = cls.company_data['default_journal_bank'].company_id.account_journal_payment_credit_account_id.copy() cls.bank_journal_1 = cls.company_data['default_journal_bank'] cls.bank_journal_2 = cls.company_data['default_journal_bank'].copy() cls.partner_bank_account1 = cls.env['res.partner.bank'].create({ 'acc_number': "0123456789", 'partner_id': cls.partner_a.id, 'acc_type': 'bank', }) cls.partner_bank_account2 = cls.env['res.partner.bank'].create({ 'acc_number': "9876543210", 'partner_id': cls.partner_a.id, 'acc_type': 'bank', }) cls.comp_bank_account1 = cls.env['res.partner.bank'].create({ 'acc_number': "985632147", 'partner_id': cls.env.company.partner_id.id, 'acc_type': 'bank', }) cls.comp_bank_account2 = cls.env['res.partner.bank'].create({ 'acc_number': "741258963", 'partner_id': cls.env.company.partner_id.id, 'acc_type': 'bank', }) # Customer invoices sharing the same batch. cls.out_invoice_1 = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': cls.partner_a.id, 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, {'product_id': cls.product_a.id, 'price_unit': 1000.0})], }) cls.out_invoice_2 = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': cls.partner_a.id, 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, {'product_id': cls.product_a.id, 'price_unit': 2000.0})], }) cls.out_invoice_3 = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': cls.partner_a.id, 'invoice_line_ids': [(0, 0, {'product_id': cls.product_a.id, 'price_unit': 12.01})], }) cls.out_invoice_4 = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': cls.partner_a.id, 'invoice_line_ids': [(0, 0, {'product_id': cls.product_a.id, 'price_unit': 11.99})], }) (cls.out_invoice_1 + cls.out_invoice_2 + cls.out_invoice_3 + cls.out_invoice_4).action_post() # Vendor bills, in_invoice_1 + in_invoice_2 are sharing the same batch but not in_invoice_3. cls.in_invoice_1 = cls.env['account.move'].create({ 'move_type': 'in_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': cls.partner_a.id, 'invoice_line_ids': [(0, 0, {'product_id': cls.product_a.id, 'price_unit': 1000.0})], }) cls.in_invoice_2 = cls.env['account.move'].create({ 'move_type': 'in_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': cls.partner_a.id, 'invoice_line_ids': [(0, 0, {'product_id': cls.product_a.id, 'price_unit': 2000.0})], }) cls.in_invoice_3 = cls.env['account.move'].create({ 'move_type': 'in_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': cls.partner_b.id, 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, {'product_id': cls.product_a.id, 'price_unit': 3000.0})], }) (cls.in_invoice_1 + cls.in_invoice_2 + cls.in_invoice_3).action_post() # Credit note cls.in_refund_1 = cls.env['account.move'].create({ 'move_type': 'in_refund', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': cls.partner_a.id, 'invoice_line_ids': [(0, 0, {'product_id': cls.product_a.id, 'price_unit': 1600.0})], }) cls.in_refund_1.action_post() def test_register_payment_single_batch_grouped_keep_open_lower_amount(self): ''' Pay 800.0 with 'open' as payment difference handling on two customer invoices (1000 + 2000). ''' active_ids = (self.out_invoice_1 + self.out_invoice_2).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'amount': 800.0, 'group_payment': True, 'payment_difference_handling': 'open', 'currency_id': self.currency_data['currency'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, })._create_payments() self.assertRecordValues(payments, [{ 'ref': 'INV/2017/00001 INV/2017/00002', 'payment_method_line_id': self.inbound_payment_method_line.id, }]) self.assertRecordValues(payments.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 400.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -800.0, 'reconciled': True, }, # Liquidity line: { 'debit': 400.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 800.0, 'reconciled': False, }, ]) def test_register_payment_single_batch_grouped_keep_open_higher_amount(self): ''' Pay 3100.0 with 'open' as payment difference handling on two customer invoices (1000 + 2000). ''' active_ids = (self.out_invoice_1 + self.out_invoice_2).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'amount': 3100.0, 'group_payment': True, 'payment_difference_handling': 'open', 'currency_id': self.currency_data['currency'].id, 'payment_method_line_id': self.inbound_payment_method_line.id, })._create_payments() self.assertRecordValues(payments, [{ 'ref': 'INV/2017/00001 INV/2017/00002', 'payment_method_line_id': self.inbound_payment_method_line.id, }]) self.assertRecordValues(payments.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 1550.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -3100.0, 'reconciled': False, }, # Liquidity line: { 'debit': 1550.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 3100.0, 'reconciled': False, }, ]) def test_register_payment_single_batch_grouped_writeoff_lower_amount_debit(self): ''' Pay 800.0 with 'reconcile' as payment difference handling on two customer invoices (1000 + 2000). ''' active_ids = (self.out_invoice_1 + self.out_invoice_2).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'amount': 800.0, 'group_payment': True, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.company_data['default_account_revenue'].id, 'writeoff_label': 'writeoff', 'payment_method_line_id': self.inbound_payment_method_line.id, })._create_payments() self.assertRecordValues(payments, [{ 'ref': 'INV/2017/00001 INV/2017/00002', 'payment_method_line_id': self.inbound_payment_method_line.id, }]) self.assertRecordValues(payments.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 1500.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -3000.0, 'reconciled': True, }, # Liquidity line: { 'debit': 400.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 800.0, 'reconciled': False, }, # Writeoff line: { 'debit': 1100.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 2200.0, 'reconciled': False, }, ]) def test_register_payment_single_batch_grouped_writeoff_higher_amount_debit(self): ''' Pay 3100.0 with 'reconcile' as payment difference handling on two customer invoices (1000 + 2000). ''' active_ids = (self.out_invoice_1 + self.out_invoice_2).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'amount': 3100.0, 'group_payment': True, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.company_data['default_account_revenue'].id, 'writeoff_label': 'writeoff', 'payment_method_line_id': self.inbound_payment_method_line.id, })._create_payments() self.assertRecordValues(payments, [{ 'ref': 'INV/2017/00001 INV/2017/00002', 'payment_method_line_id': self.inbound_payment_method_line.id, }]) self.assertRecordValues(payments.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 1500.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -3000.0, 'reconciled': True, }, # Writeoff line: { 'debit': 0.0, 'credit': 50.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -100.0, 'reconciled': False, }, # Liquidity line: { 'debit': 1550.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 3100.0, 'reconciled': False, }, ]) def test_register_payment_single_batch_grouped_writeoff_lower_amount_credit(self): ''' Pay 800.0 with 'reconcile' as payment difference handling on two vendor billes (1000 + 2000). ''' active_ids = (self.in_invoice_1 + self.in_invoice_2).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'amount': 800.0, 'group_payment': True, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.company_data['default_account_revenue'].id, 'writeoff_label': 'writeoff', 'payment_method_line_id': self.inbound_payment_method_line.id, })._create_payments() self.assertRecordValues(payments, [{ 'ref': 'BILL/2017/01/0001 BILL/2017/01/0002', 'payment_method_line_id': self.inbound_payment_method_line.id, }]) self.assertRecordValues(payments.line_ids.sorted('balance'), [ # Writeoff line: { 'debit': 0.0, 'credit': 2200.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -2200.0, 'reconciled': False, }, # Liquidity line: { 'debit': 0.0, 'credit': 800.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -800.0, 'reconciled': False, }, # Payable line: { 'debit': 3000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 3000.0, 'reconciled': True, }, ]) def test_register_payment_single_batch_grouped_writeoff_higher_amount_credit(self): ''' Pay 3100.0 with 'reconcile' as payment difference handling on two vendor billes (1000 + 2000). ''' active_ids = (self.in_invoice_1 + self.in_invoice_2).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'amount': 3100.0, 'group_payment': True, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.company_data['default_account_revenue'].id, 'writeoff_label': 'writeoff', 'payment_method_line_id': self.inbound_payment_method_line.id, })._create_payments() self.assertRecordValues(payments, [{ 'ref': 'BILL/2017/01/0001 BILL/2017/01/0002', 'payment_method_line_id': self.inbound_payment_method_line.id, }]) self.assertRecordValues(payments.line_ids.sorted('balance'), [ # Liquidity line: { 'debit': 0.0, 'credit': 3100.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -3100.0, 'reconciled': False, }, # Writeoff line: { 'debit': 100.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 100.0, 'reconciled': False, }, # Payable line: { 'debit': 3000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 3000.0, 'reconciled': True, }, ]) def test_register_payment_single_batch_not_grouped(self): ''' Choose to pay two customer invoices with separated payments (1000 + 2000). ''' active_ids = (self.out_invoice_1 + self.out_invoice_2).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'group_payment': False, })._create_payments() self.assertRecordValues(payments, [ { 'ref': 'INV/2017/00001', 'payment_method_line_id': self.inbound_payment_method_line.id, }, { 'ref': 'INV/2017/00002', 'payment_method_line_id': self.inbound_payment_method_line.id, }, ]) self.assertRecordValues(payments[0].line_ids.sorted('balance') + payments[1].line_ids.sorted('balance'), [ # == Payment 1: to pay out_invoice_1 == # Receivable line: { 'debit': 0.0, 'credit': 500.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'reconciled': True, }, # Liquidity line: { 'debit': 500.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1000.0, 'reconciled': False, }, # == Payment 2: to pay out_invoice_2 == # Receivable line: { 'debit': 0.0, 'credit': 1000.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -2000.0, 'reconciled': True, }, # Liquidity line: { 'debit': 1000.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 2000.0, 'reconciled': False, }, ]) def test_register_payment_different_type_single_batch_not_grouped(self): """ Choose to pay a bill and a refund with separated payments (1000 + -2000).""" active_ids = (self.in_invoice_1 + self.in_refund_1).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'group_payment': False, })._create_payments() self.assertRecordValues(payments[0], [ { 'ref': 'BILL/2017/01/0001', 'payment_type': 'outbound', } ]) self.assertRecordValues(payments[1], [ { 'ref': 'RBILL/2017/01/0001', 'payment_type': 'inbound', }, ]) self.assertRecordValues(payments[0].line_ids.sorted('balance'), [ # == Payment 1: to pay in_invoice_1 == # Liquidity line: { 'debit': 0.0, 'credit': 1000.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1000.0, 'reconciled': False, }, # Payable line: { 'debit': 1000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1000.0, 'reconciled': True, }, ]) self.assertRecordValues(payments[1].line_ids.sorted('balance'), [ # == Payment 2: to pay in_refund_1 == # Payable line: { 'debit': 0.0, 'credit': 1600.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1600.0, 'reconciled': True, }, # Liquidity line: { 'debit': 1600.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1600.0, 'reconciled': False, }, ]) def test_register_payment_single_batch_grouped_with_credit_note(self): ''' Pay 1400.0 on two vendor bills (1000.0 + 2000.0) and one credit note (1600.0). ''' active_ids = (self.in_invoice_1 + self.in_invoice_2 + self.in_refund_1).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'group_payment': True, })._create_payments() self.assertRecordValues(payments, [ { 'ref': 'BILL/2017/01/0001 BILL/2017/01/0002 RBILL/2017/01/0001', 'payment_method_line_id': self.outbound_payment_method_line.id, }, ]) self.assertRecordValues(payments[0].line_ids.sorted('balance'), [ # Liquidity line: { 'debit': 0.0, 'credit': 1400.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1400.0, 'reconciled': False, }, # Payable line: { 'debit': 1400.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1400.0, 'reconciled': True, }, ]) def test_register_payment_multiple_batch_grouped_with_credit_note(self): ''' Do not batch payments if multiple partner_bank_id ''' bank1 = self.env['res.partner.bank'].create({ 'acc_number': 'BE43798822936101', 'partner_id': self.partner_a.id, }) bank2 = self.env['res.partner.bank'].create({ 'acc_number': 'BE85812541345906', 'partner_id': self.partner_a.id, }) self.in_invoice_1.partner_bank_id = bank1 self.in_invoice_2.partner_bank_id = bank2 active_ids = (self.in_invoice_1 + self.in_invoice_2 + self.in_refund_1).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'group_payment': True, })._create_payments() self.assertRecordValues(payments, [ { 'ref': 'BILL/2017/01/0001', 'payment_method_line_id': self.outbound_payment_method_line.id, }, { 'ref': 'BILL/2017/01/0002', 'payment_method_line_id': self.outbound_payment_method_line.id, }, { 'ref': 'RBILL/2017/01/0001', 'payment_method_line_id': self.inbound_payment_method_line.id, }, ]) self.assertRecordValues(payments[0].line_ids.sorted('balance') + payments[1].line_ids.sorted('balance') + payments[2].line_ids.sorted('balance'), [ # Liquidity line: { 'debit': 0.0, 'credit': 1000.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1000.0, 'reconciled': False, }, # Payable line: { 'debit': 1000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1000.0, 'reconciled': True, }, # Liquidity line: { 'debit': 0.0, 'credit': 2000.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -2000.0, 'reconciled': False, }, # Payable line: { 'debit': 2000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 2000.0, 'reconciled': True, }, # Receivable line: { 'debit': 0.0, 'credit': 1600.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1600.0, 'reconciled': True, }, # Liquidity line: { 'debit': 1600.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1600.0, 'reconciled': False, }, ]) def test_register_payment_multi_batches_grouped(self): ''' Choose to pay multiple batches, one with two customer invoices (1000 + 2000) and one with a vendor bill of 600, by grouping payments. ''' active_ids = (self.in_invoice_1 + self.in_invoice_2 + self.in_invoice_3).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'group_payment': True, })._create_payments() self.assertRecordValues(payments, [ { 'ref': 'BILL/2017/01/0001 BILL/2017/01/0002', 'payment_method_line_id': self.outbound_payment_method_line.id, }, { 'ref': 'BILL/2017/01/0003', 'payment_method_line_id': self.outbound_payment_method_line.id, }, ]) self.assertRecordValues(payments[0].line_ids.sorted('balance') + payments[1].line_ids.sorted('balance'), [ # == Payment 1: to pay in_invoice_1 & in_invoice_2 == # Liquidity line: { 'debit': 0.0, 'credit': 3000.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -3000.0, 'reconciled': False, }, # Payable line: { 'debit': 3000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 3000.0, 'reconciled': True, }, # == Payment 2: to pay in_invoice_3 == # Liquidity line: { 'debit': 0.0, 'credit': 1500.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -3000.0, 'reconciled': False, }, # Payable line: { 'debit': 1500.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 3000.0, 'reconciled': True, }, ]) def test_register_payment_multi_batches_not_grouped(self): ''' Choose to pay multiple batches, one with two customer invoices (1000 + 2000) and one with a vendor bill of 600, by splitting payments. ''' self.in_invoice_1.partner_bank_id = self.partner_bank_account1 self.in_invoice_2.partner_bank_id = self.partner_bank_account2 active_ids = (self.in_invoice_1 + self.in_invoice_2 + self.in_invoice_3).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'group_payment': False, })._create_payments() self.assertRecordValues(payments, [ { 'journal_id': self.bank_journal_1.id, 'ref': 'BILL/2017/01/0001', 'payment_method_line_id': self.outbound_payment_method_line.id, 'partner_bank_id': self.partner_bank_account1.id, }, { 'journal_id': self.bank_journal_1.id, 'ref': 'BILL/2017/01/0002', 'payment_method_line_id': self.outbound_payment_method_line.id, 'partner_bank_id': self.partner_bank_account2.id, }, { 'journal_id': self.bank_journal_1.id, 'ref': 'BILL/2017/01/0003', 'payment_method_line_id': self.outbound_payment_method_line.id, 'partner_bank_id': False, }, ]) self.assertRecordValues(payments[0].line_ids.sorted('balance') + payments[1].line_ids.sorted('balance') + payments[2].line_ids.sorted('balance'), [ # == Payment 1: to pay in_invoice_1 == # Liquidity line: { 'debit': 0.0, 'credit': 1000.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1000.0, 'reconciled': False, }, # Payable line: { 'debit': 1000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1000.0, 'reconciled': True, }, # == Payment 2: to pay in_invoice_2 == # Liquidity line: { 'debit': 0.0, 'credit': 2000.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -2000.0, 'reconciled': False, }, # Payable line: { 'debit': 2000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 2000.0, 'reconciled': True, }, # == Payment 3: to pay in_invoice_3 == # Liquidity line: { 'debit': 0.0, 'credit': 1500.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -3000.0, 'reconciled': False, }, # Payable line: { 'debit': 1500.0, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 3000.0, 'reconciled': True, }, ]) def test_register_payment_constraints(self): # Test to register a payment for a draft journal entry. self.out_invoice_1.button_draft() with self.assertRaises(UserError), self.cr.savepoint(): self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_1.ids)\ .create({}) # Test to register a payment for an already fully reconciled journal entry. self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_2.ids)\ .create({})\ ._create_payments() with self.assertRaises(UserError), self.cr.savepoint(): self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_2.ids)\ .create({}) def test_register_payment_multi_currency_conversion(self): ''' When registering a payment using a different currency than the invoice, the amount should update when changing wizard date ''' PaymentRegister = self.env['account.payment.register'] data = [ (self.out_invoice_2, self.company_data['currency'], [1000.0, 666.67], "invoice is in foreign currency and payment is in company currency"), (self.out_invoice_3, self.currency_data['currency'], [24.02, 36.03], "invoice is in company currency and payment is in foreign currency"), (self.out_invoice_2, self.currency_data_3['currency'], [10.0, 2000.0], "invoice and payment are in different foreign currencies"), ] date = ('2017-01-01', '2016-01-01') for invoice, pay_currency, expected_amounts, msg in data: wizard = Form(PaymentRegister.with_context(active_model='account.move', active_ids=invoice.ids)) wizard.currency_id = pay_currency for d, expected in zip(date, expected_amounts): payment_date = fields.Date.from_string(d) wizard.payment_date = payment_date self.assertEqual(wizard.amount, expected, f"Amount in payment wizard when {msg} is not correct") def test_register_payment_multi_currency_rounding_issue_positive_delta(self): ''' When registering a payment using a different currency than the invoice one, the invoice must be fully paid at the end whatever the currency rate. ''' payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_3.ids)\ .create({ 'currency_id': self.currency_data_3['currency'].id, 'amount': 0.12, })\ ._create_payments() self.assertRecordValues(payment.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 12.01, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.12, 'reconciled': True, }, # Liquidity line: { 'debit': 12.01, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.12, 'reconciled': False, }, ]) def test_register_payment_multi_currency_rounding_issue_negative_delta(self): ''' When registering a payment using a different currency than the invoice one, the invoice must be fully paid at the end whatever the currency rate. ''' payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_4.ids)\ .create({ 'currency_id': self.currency_data_3['currency'].id, 'amount': 0.12, })\ ._create_payments() self.assertRecordValues(payment.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 11.99, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.12, 'reconciled': True, }, # Liquidity line: { 'debit': 11.99, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.12, 'reconciled': False, }, ]) def test_register_payment_multi_currency_rounding_issue_writeoff_lower_amount_keep_open(self): payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_3.ids)\ .create({ 'currency_id': self.currency_data_3['currency'].id, 'amount': 0.08, 'payment_difference_handling': 'open', })\ ._create_payments() self.assertRecordValues(payment.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 8.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.08, 'reconciled': True, }, # Liquidity line: { 'debit': 8.0, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.08, 'reconciled': False, }, ]) def test_register_payment_multi_currency_rounding_issue_writeoff_lower_amount_reconcile_positive_delta(self): payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_3.ids)\ .create({ 'currency_id': self.currency_data_3['currency'].id, 'amount': 0.08, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.company_data['default_account_revenue'].id, 'writeoff_label': 'writeoff', })\ ._create_payments() self.assertRecordValues(payment.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 12.01, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.12, 'reconciled': True, }, # Write-off line: { 'debit': 4.0, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.04, 'reconciled': False, }, # Liquidity line: { 'debit': 8.01, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.08, 'reconciled': False, }, ]) def test_register_payment_multi_currency_rounding_issue_writeoff_lower_amount_reconcile_negative_delta(self): payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_4.ids)\ .create({ 'currency_id': self.currency_data_3['currency'].id, 'amount': 0.08, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.company_data['default_account_revenue'].id, 'writeoff_label': 'writeoff', })\ ._create_payments() self.assertRecordValues(payment.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 11.99, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.12, 'reconciled': True, }, # Write-off line: { 'debit': 4.0, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.04, 'reconciled': False, }, # Liquidity line: { 'debit': 7.99, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.08, 'reconciled': False, }, ]) def test_register_payment_multi_currency_rounding_issue_writeoff_higher_amount_reconcile_positive_delta(self): payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_3.ids)\ .create({ 'currency_id': self.currency_data_3['currency'].id, 'amount': 0.16, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.company_data['default_account_revenue'].id, 'writeoff_label': 'writeoff', })\ ._create_payments() self.assertRecordValues(payment.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 12.01, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.12, 'reconciled': True, }, # Write-off line: { 'debit': 0.0, 'credit': 4.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.04, 'reconciled': False, }, # Liquidity line: { 'debit': 16.01, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.16, 'reconciled': False, }, ]) def test_register_payment_multi_currency_rounding_issue_writeoff_higher_amount_reconcile_negative_delta(self): payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=self.out_invoice_4.ids)\ .create({ 'currency_id': self.currency_data_3['currency'].id, 'amount': 0.16, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.company_data['default_account_revenue'].id, 'writeoff_label': 'writeoff', })\ ._create_payments() self.assertRecordValues(payment.line_ids.sorted('balance'), [ # Receivable line: { 'debit': 0.0, 'credit': 11.99, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.12, 'reconciled': True, }, # Write-off line: { 'debit': 0.0, 'credit': 4.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': -0.04, 'reconciled': False, }, # Liquidity line: { 'debit': 15.99, 'credit': 0.0, 'currency_id': self.currency_data_3['currency'].id, 'amount_currency': 0.16, 'reconciled': False, }, ]) def test_suggested_default_partner_bank_inbound_payment(self): """ Test the suggested bank account on the wizard for inbound payment. """ self.out_invoice_1.partner_bank_id = False ctx = {'active_model': 'account.move', 'active_ids': self.out_invoice_1.ids} wizard = self.env['account.payment.register'].with_context(**ctx).create({}) self.assertRecordValues(wizard, [{ 'journal_id': self.bank_journal_1.id, 'available_partner_bank_ids': [], 'partner_bank_id': False, }]) self.bank_journal_2.bank_account_id = self.out_invoice_1.partner_bank_id = self.comp_bank_account2 wizard = self.env['account.payment.register'].with_context(**ctx).create({}) self.assertRecordValues(wizard, [{ 'journal_id': self.bank_journal_2.id, 'available_partner_bank_ids': self.comp_bank_account2.ids, 'partner_bank_id': self.comp_bank_account2.id, }]) wizard.journal_id = self.bank_journal_1 self.assertRecordValues(wizard, [{ 'journal_id': self.bank_journal_1.id, 'available_partner_bank_ids': [], 'partner_bank_id': False, }]) def test_suggested_default_partner_bank_outbound_payment(self): """ Test the suggested bank account on the wizard for outbound payment. """ self.in_invoice_1.partner_bank_id = False ctx = {'active_model': 'account.move', 'active_ids': self.in_invoice_1.ids} wizard = self.env['account.payment.register'].with_context(**ctx).create({}) self.assertRecordValues(wizard, [{ 'journal_id': self.bank_journal_1.id, 'available_partner_bank_ids': self.partner_a.bank_ids.ids, 'partner_bank_id': self.partner_bank_account1.id, }]) self.in_invoice_1.partner_bank_id = self.partner_bank_account2 wizard = self.env['account.payment.register'].with_context(**ctx).create({}) self.assertRecordValues(wizard, [{ 'journal_id': self.bank_journal_1.id, 'available_partner_bank_ids': self.partner_a.bank_ids.ids, 'partner_bank_id': self.partner_bank_account2.id, }]) wizard.journal_id = self.bank_journal_2 self.assertRecordValues(wizard, [{ 'journal_id': self.bank_journal_2.id, 'available_partner_bank_ids': self.partner_a.bank_ids.ids, 'partner_bank_id': self.partner_bank_account2.id, }]) def test_register_payment_inbound_multiple_bank_account(self): """ Pay customer invoices with different bank accounts. """ self.out_invoice_1.partner_bank_id = self.comp_bank_account1 self.out_invoice_2.partner_bank_id = self.comp_bank_account2 self.bank_journal_2.bank_account_id = self.comp_bank_account2 ctx = {'active_model': 'account.move', 'active_ids': (self.out_invoice_1 + self.out_invoice_2).ids} wizard = self.env['account.payment.register'].with_context(**ctx).create({'journal_id': self.bank_journal_2.id}) payments = wizard._create_payments() self.assertRecordValues(payments, [ { 'journal_id': self.bank_journal_2.id, 'ref': 'INV/2017/00001', 'partner_bank_id': self.comp_bank_account2.id, }, { 'journal_id': self.bank_journal_2.id, 'ref': 'INV/2017/00002', 'partner_bank_id': self.comp_bank_account2.id, }, ]) def test_payment_method_different_type_single_batch_not_grouped(self): """ Test payment methods when paying a bill and a refund with separated payments (1000 + -2000).""" invoice_1 = self.in_invoice_1 invoice_2 = invoice_1.copy({'invoice_date': invoice_1.invoice_date, 'partner_id': self.partner_b.id}) refund_1, refund_2 = self.env['account.move'].create([ { 'move_type': 'in_refund', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': self.partner_a.id, 'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 1600.0})], }, { 'move_type': 'in_refund', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': self.partner_b.id, 'invoice_line_ids': [(0, 0, {'product_id': self.product_a.id, 'price_unit': 1600.0})], }, ]) (invoice_2 + refund_1 + refund_2).action_post() for moves in ((invoice_1 + invoice_2), (refund_1 + refund_2)): wizard = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=moves.ids).create({ 'group_payment': False, }) expected_available_payment_method_lines = wizard.journal_id.inbound_payment_method_line_ids if moves[0].move_type == 'in_refund' else wizard.journal_id.outbound_payment_method_line_ids self.assertRecordValues(wizard, [ { 'available_payment_method_line_ids': expected_available_payment_method_lines.ids, 'payment_method_line_id': expected_available_payment_method_lines[:1].id, } ]) active_ids = (invoice_1 + invoice_2 + refund_1 + refund_2).ids payments = self.env['account.payment.register'].with_context(active_model='account.move', active_ids=active_ids).create({ 'group_payment': False, })._create_payments() self.assertRecordValues(payments[0], [ { 'ref': 'BILL/2017/01/0001', 'payment_method_line_id': self.bank_journal_1.outbound_payment_method_line_ids[0].id, 'payment_type': 'outbound', } ]) self.assertRecordValues(payments[1], [ { 'ref': 'RBILL/2017/01/0002', 'payment_method_line_id': self.bank_journal_1.inbound_payment_method_line_ids[0].id, 'payment_type': 'inbound', }, ]) self.assertRecordValues(payments[2], [ { 'ref': 'BILL/2017/01/0004', 'payment_method_line_id': self.bank_journal_1.outbound_payment_method_line_ids[0].id, 'payment_type': 'outbound', } ]) self.assertRecordValues(payments[3], [ { 'ref': 'RBILL/2017/01/0003', 'payment_method_line_id': self.bank_journal_1.inbound_payment_method_line_ids[0].id, 'payment_type': 'inbound', }, ]) self.assertRecordValues(payments[0].line_ids.sorted('balance'), [ # == Payment 1: to pay invoice_1 == # Liquidity line: { 'debit': 0.0, 'credit': 1000.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1000.0, 'reconciled': False, }, # Payable line: { 'debit': 1000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1000.0, 'reconciled': True, }, ]) self.assertRecordValues(payments[1].line_ids.sorted('balance'), [ # == Payment 3: to pay refund_1 == # Payable line: { 'debit': 0.0, 'credit': 1600.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1600.0, 'reconciled': True, }, # Liquidity line: { 'debit': 1600.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1600.0, 'reconciled': False, }, ]) self.assertRecordValues(payments[2].line_ids.sorted('balance'), [ # == Payment 2: to pay invoice_2 == # Liquidity line: { 'debit': 0.0, 'credit': 1000.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1000.0, 'reconciled': False, }, # Payable line: { 'debit': 1000.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1000.0, 'reconciled': True, }, ]) self.assertRecordValues(payments[3].line_ids.sorted('balance'), [ # == Payment 4: to pay refund_2 == # Payable line: { 'debit': 0.0, 'credit': 1600.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': -1600.0, 'reconciled': True, }, # Liquidity line: { 'debit': 1600.0, 'credit': 0.0, 'currency_id': self.company_data['currency'].id, 'amount_currency': 1600.0, 'reconciled': False, }, ])
40.884151
50,819
1,170
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo.exceptions import UserError @tagged('post_install', '-at_install') class TestAccountTax(AccountTestInvoicingCommon): def test_changing_tax_company(self): ''' Ensure you can't change the company of an account.tax if there are some journal entries ''' # Avoid duplicate key value violates unique constraint "account_tax_name_company_uniq". self.company_data['default_tax_sale'].name = 'test_changing_account_company' self.env['account.move'].create({ 'move_type': 'out_invoice', 'date': '2019-01-01', 'invoice_line_ids': [ (0, 0, { 'name': 'invoice_line', 'quantity': 1.0, 'price_unit': 100.0, 'tax_ids': [(6, 0, self.company_data['default_tax_sale'].ids)], }), ], }) with self.assertRaises(UserError), self.cr.savepoint(): self.company_data['default_tax_sale'].company_id = self.company_data_2['company']
39
1,170
75,313
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo.tests.common import Form from odoo.exceptions import ValidationError, UserError from odoo import fields from unittest.mock import patch class TestAccountBankStatementCommon(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) # We need a third currency as you could have a company's currency != journal's currency != cls.currency_data_2 = cls.setup_multi_currency_data(default_values={ 'name': 'Dark Chocolate Coin', 'symbol': '🍫', 'currency_unit_label': 'Dark Choco', 'currency_subunit_label': 'Dark Cacao Powder', }, rate2016=6.0, rate2017=4.0) cls.currency_data_3 = cls.setup_multi_currency_data(default_values={ 'name': 'Black Chocolate Coin', 'symbol': '🍫', 'currency_unit_label': 'Black Choco', 'currency_subunit_label': 'Black Cacao Powder', }, rate2016=12.0, rate2017=8.0) cls.bank_journal_1 = cls.company_data['default_journal_bank'] cls.bank_journal_2 = cls.bank_journal_1.copy() cls.bank_journal_3 = cls.bank_journal_2.copy() cls.currency_1 = cls.company_data['currency'] cls.currency_2 = cls.currency_data['currency'] cls.currency_3 = cls.currency_data_2['currency'] cls.currency_4 = cls.currency_data_3['currency'] def assertBankStatementLine(self, statement_line, expected_statement_line_vals, expected_move_line_vals): self.assertRecordValues(statement_line, [expected_statement_line_vals]) self.assertRecordValues(statement_line.line_ids.sorted('balance'), expected_move_line_vals) @tagged('post_install', '-at_install') class TestAccountBankStatement(TestAccountBankStatementCommon): # ------------------------------------------------------------------------- # TESTS about the statement model. # ------------------------------------------------------------------------- def test_starting_ending_balance_chaining(self): # Create first statement on 2019-01-02. bnk1 = self.env['account.bank.statement'].create({ 'name': 'BNK1', 'date': '2019-01-02', 'journal_id': self.company_data['default_journal_bank'].id, 'line_ids': [(0, 0, {'payment_ref': '/', 'amount': 100.0})], }) self.assertRecordValues(bnk1, [{ 'balance_start': 0.0, 'balance_end_real': 100.0, 'balance_end': 100.0, 'previous_statement_id': False, }]) # Create a new statement after that one. bnk2 = self.env['account.bank.statement'].create({ 'name': 'BNK2', 'date': '2019-01-10', 'journal_id': self.company_data['default_journal_bank'].id, 'line_ids': [(0, 0, {'payment_ref': '/', 'amount': 50.0})], }) self.assertRecordValues(bnk2, [{ 'balance_start': 100.0, 'balance_end_real': 150.0, 'balance_end': 150.0, 'previous_statement_id': bnk1.id, }]) # Create new statement with given ending balance. bnk3 = self.env['account.bank.statement'].create({ 'name': 'BNK3', 'date': '2019-01-15', 'journal_id': self.company_data['default_journal_bank'].id, 'line_ids': [(0, 0, {'payment_ref': '/', 'amount': 25.0})], 'balance_end_real': 200.0, }) self.assertRecordValues(bnk3, [{ 'balance_start': 150.0, 'balance_end_real': 200.0, 'balance_end': 175.0, 'previous_statement_id': bnk2.id, }]) # Create new statement with a date right after BNK1. bnk4 = self.env['account.bank.statement'].create({ 'name': 'BNK4', 'date': '2019-01-03', 'journal_id': self.company_data['default_journal_bank'].id, 'line_ids': [(0, 0, {'payment_ref': '/', 'amount': 100.0})], }) self.assertRecordValues(bnk4, [{ 'balance_start': 100.0, 'balance_end_real': 200.0, 'balance_end': 200.0, 'previous_statement_id': bnk1.id, }]) # BNK2/BNK3 should have changed their previous statements. self.assertRecordValues(bnk2, [{ 'balance_start': 200.0, 'balance_end_real': 250.0, 'balance_end': 250.0, 'previous_statement_id': bnk4.id, }]) self.assertRecordValues(bnk3, [{ 'balance_start': 250.0, 'balance_end_real': 200.0, 'balance_end': 275.0, 'previous_statement_id': bnk2.id, }]) # Correct the ending balance of BNK3. bnk3.balance_end_real = 275 # Change date of BNK4 to be the last. bnk4.date = '2019-01-20' self.assertRecordValues(bnk1, [{ 'balance_start': 0.0, 'balance_end_real': 100.0, 'balance_end': 100.0, 'previous_statement_id': False, }]) self.assertRecordValues(bnk2, [{ 'balance_start': 100.0, 'balance_end_real': 150.0, 'balance_end': 150.0, 'previous_statement_id': bnk1.id, }]) self.assertRecordValues(bnk3, [{ 'balance_start': 150.0, 'balance_end_real': 175.0, 'balance_end': 175.0, 'previous_statement_id': bnk2.id, }]) self.assertRecordValues(bnk4, [{ 'balance_start': 175.0, 'balance_end_real': 200.0, 'balance_end': 275.0, 'previous_statement_id': bnk3.id, }]) # Correct the ending balance of BNK4. bnk4.balance_end_real = 275 # Move BNK3 to first position. bnk3.date = '2019-01-01' self.assertRecordValues(bnk3, [{ 'balance_start': 0.0, 'balance_end_real': 25.0, 'balance_end': 25.0, 'previous_statement_id': False, }]) self.assertRecordValues(bnk1, [{ 'balance_start': 25.0, 'balance_end_real': 125.0, 'balance_end': 125.0, 'previous_statement_id': bnk3.id, }]) self.assertRecordValues(bnk2, [{ 'balance_start': 125.0, 'balance_end_real': 175.0, 'balance_end': 175.0, 'previous_statement_id': bnk1.id, }]) self.assertRecordValues(bnk4, [{ 'balance_start': 175.0, 'balance_end_real': 275.0, 'balance_end': 275.0, 'previous_statement_id': bnk2.id, }]) # Move BNK1 to the third position. bnk1.date = '2019-01-11' self.assertRecordValues(bnk3, [{ 'balance_start': 0.0, 'balance_end_real': 25.0, 'balance_end': 25.0, 'previous_statement_id': False, }]) self.assertRecordValues(bnk2, [{ 'balance_start': 25.0, 'balance_end_real': 75.0, 'balance_end': 75.0, 'previous_statement_id': bnk3.id, }]) self.assertRecordValues(bnk1, [{ 'balance_start': 75.0, 'balance_end_real': 175.0, 'balance_end': 175.0, 'previous_statement_id': bnk2.id, }]) self.assertRecordValues(bnk4, [{ 'balance_start': 175.0, 'balance_end_real': 275.0, 'balance_end': 275.0, 'previous_statement_id': bnk1.id, }]) # Delete BNK3 and BNK1. (bnk3 + bnk1).unlink() self.assertRecordValues(bnk2, [{ 'balance_start': 0.0, 'balance_end_real': 50.0, 'balance_end': 50.0, 'previous_statement_id': False, }]) self.assertRecordValues(bnk4, [{ 'balance_start': 50.0, 'balance_end_real': 275.0, 'balance_end': 150.0, 'previous_statement_id': bnk2.id, }]) def test_statements_different_journal(self): # Create statements in bank journal. bnk1_1 = self.env['account.bank.statement'].create({ 'name': 'BNK1_1', 'date': '2019-01-01', 'journal_id': self.company_data['default_journal_bank'].id, 'line_ids': [(0, 0, {'payment_ref': '/', 'amount': 100.0})], 'balance_end_real': 100.0, }) bnk1_2 = self.env['account.bank.statement'].create({ 'name': 'BNK1_2', 'date': '2019-01-10', 'journal_id': self.company_data['default_journal_bank'].id, 'line_ids': [(0, 0, {'payment_ref': '/', 'amount': 50.0})], }) # Create statements in cash journal. bnk2_1 = self.env['account.bank.statement'].create({ 'name': 'BNK2_1', 'date': '2019-01-02', 'journal_id': self.company_data['default_journal_cash'].id, 'line_ids': [(0, 0, {'payment_ref': '/', 'amount': 20.0})], 'balance_end_real': 20.0, }) bnk2_2 = self.env['account.bank.statement'].create({ 'name': 'BNK2_2', 'date': '2019-01-12', 'journal_id': self.company_data['default_journal_cash'].id, 'line_ids': [(0, 0, {'payment_ref': '/', 'amount': 10.0})], }) self.assertRecordValues(bnk1_1, [{ 'balance_start': 0.0, 'balance_end_real': 100.0, 'balance_end': 100.0, 'previous_statement_id': False, }]) self.assertRecordValues(bnk1_2, [{ 'balance_start': 100.0, 'balance_end_real': 150.0, 'balance_end': 150.0, 'previous_statement_id': bnk1_1.id, }]) self.assertRecordValues(bnk2_1, [{ 'balance_start': 0.0, 'balance_end_real': 20.0, 'balance_end': 20.0, 'previous_statement_id': False, }]) self.assertRecordValues(bnk2_2, [{ 'balance_start': 20.0, 'balance_end_real': 0.0, 'balance_end': 30.0, 'previous_statement_id': bnk2_1.id, }]) def test_cash_statement_with_difference(self): ''' A cash statement always creates an additional line to store the cash difference towards the ending balance. ''' statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.company_data['default_journal_cash'].id, 'balance_end_real': 100.0, }) statement.button_post() self.assertRecordValues(statement.line_ids, [{ 'amount': 100.0, 'is_reconciled': True, }]) def test_bank_statement_with_difference(self): """ Test that a bank statement with difference could be posted but not validated. """ bank_statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_1.id, 'balance_start': 10.0, 'balance_end_real': 100.0, 'balance_end': 10.0, 'line_ids': [(0, 0, { 'date': fields.Date.to_date('2019-01-01'), 'payment_ref': 'transaction_abc', 'amount': 10, 'partner_id': self.partner_a.id, })] }) bank_statement.button_post() # Check if the bank statement is well posted (No check on the balance as the balance could be edited after). self.assertEqual(bank_statement.state, 'posted') # Check that the bank statement couldn't be validated with balance_end != balance_end_real with self.assertRaises(UserError): bank_statement.button_validate() # Check if we can validate the bank statement if balance_end == balance_end_real bank_statement.balance_end_real = bank_statement.balance_end for line in bank_statement.line_ids: line.reconcile([{ 'name': line.payment_ref, 'partner_id': line.partner_id.id, 'currency_id': self.currency_1.id, 'account_id': bank_statement.journal_id.suspense_account_id.id, 'debit': 10.0, 'credit': 0.0, 'amount_currency': 10.0, }]) bank_statement.button_validate() self.assertEqual(bank_statement.state, 'confirm') @tagged('post_install', '-at_install') class TestAccountBankStatementLine(TestAccountBankStatementCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.statement = cls.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': cls.bank_journal_1.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': cls.partner_a.id, 'foreign_currency_id': cls.currency_2.id, 'amount': 1250.0, 'amount_currency': 2500.0, }), ], }) cls.statement_line = cls.statement.line_ids cls.expected_st_line = { 'date': fields.Date.from_string('2019-01-01'), 'journal_id': cls.statement.journal_id.id, 'payment_ref': 'line_1', 'partner_id': cls.partner_a.id, 'currency_id': cls.currency_1.id, 'foreign_currency_id': cls.currency_2.id, 'amount': 1250.0, 'amount_currency': 2500.0, 'is_reconciled': False, } cls.expected_bank_line = { 'name': cls.statement_line.payment_ref, 'partner_id': cls.statement_line.partner_id.id, 'currency_id': cls.currency_1.id, 'account_id': cls.statement.journal_id.default_account_id.id, 'debit': 1250.0, 'credit': 0.0, 'amount_currency': 1250.0, } cls.expected_counterpart_line = { 'name': cls.statement_line.payment_ref, 'partner_id': cls.statement_line.partner_id.id, 'currency_id': cls.currency_2.id, 'account_id': cls.statement.journal_id.suspense_account_id.id, 'debit': 0.0, 'credit': 1250.0, 'amount_currency': -2500.0, } # ------------------------------------------------------------------------- # TESTS about the statement line model. # ------------------------------------------------------------------------- def _test_statement_line_edition( self, journal, amount, amount_currency, journal_currency, foreign_currency, expected_liquidity_values, expected_counterpart_values): ''' Test the edition of a statement line from itself or from its linked journal entry. :param journal: The account.journal record that will be set on the statement line. :param amount: The amount in journal's currency. :param amount_currency: The amount in the foreign currency. :param journal_currency: The journal's currency as a res.currency record. :param foreign_currency: The foreign currency as a res.currency record. :param expected_liquidity_values: The expected account.move.line values for the liquidity line. :param expected_counterpart_values: The expected account.move.line values for the counterpart line. ''' if journal_currency: journal.currency_id = journal_currency.id statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': journal.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': foreign_currency and foreign_currency.id, 'amount': amount, 'amount_currency': amount_currency, }), ], }) statement_line = statement.line_ids # ==== Test the statement line amounts are correct ==== # If there is a bug in the compute/inverse methods, the amount/amount_currency could be # incorrect directly after the creation of the statement line. self.assertRecordValues(statement_line, [{ 'amount': amount, 'amount_currency': amount_currency, }]) self.assertRecordValues(statement_line.move_id, [{ 'partner_id': self.partner_a.id, 'currency_id': (statement_line.foreign_currency_id or statement_line.currency_id).id, }]) # ==== Test the edition of statement line amounts ==== # The statement line must remain consistent with its account.move. # To test the compute/inverse methods are correctly managing all currency setup, # we check the edition of amounts in both directions statement line <-> journal entry. # Check initial state of the statement line. liquidity_lines, suspense_lines, other_lines = statement_line._seek_for_lines() self.assertRecordValues(liquidity_lines, [expected_liquidity_values]) self.assertRecordValues(suspense_lines, [expected_counterpart_values]) # Check the account.move is still correct after editing the account.bank.statement.line. statement_line.write({ 'amount': statement_line.amount * 2, 'amount_currency': statement_line.amount_currency * 2, }) self.assertRecordValues(statement_line, [{ 'amount': amount * 2, 'amount_currency': amount_currency * 2, }]) self.assertRecordValues(liquidity_lines, [{ **expected_liquidity_values, 'debit': expected_liquidity_values.get('debit', 0.0) * 2, 'credit': expected_liquidity_values.get('credit', 0.0) * 2, 'amount_currency': expected_liquidity_values.get('amount_currency', 0.0) * 2, }]) self.assertRecordValues(suspense_lines, [{ 'debit': expected_counterpart_values.get('debit', 0.0) * 2, 'credit': expected_counterpart_values.get('credit', 0.0) * 2, 'amount_currency': expected_counterpart_values.get('amount_currency', 0.0) * 2, }]) # Check the account.bank.statement.line is still correct after editing the account.move. statement_line.move_id.write({'line_ids': [ (1, liquidity_lines.id, { 'debit': expected_liquidity_values.get('debit', 0.0), 'credit': expected_liquidity_values.get('credit', 0.0), 'amount_currency': expected_liquidity_values.get('amount_currency', 0.0), }), (1, suspense_lines.id, { 'debit': expected_counterpart_values.get('debit', 0.0), 'credit': expected_counterpart_values.get('credit', 0.0), 'amount_currency': expected_counterpart_values.get('amount_currency', 0.0), }), ]}) self.assertRecordValues(statement_line, [{ 'amount': amount, 'amount_currency': amount_currency, }]) def _test_edition_customer_and_supplier_flows( self, amount, amount_currency, journal_currency, foreign_currency, expected_liquidity_values, expected_counterpart_values): ''' Test '_test_statement_line_edition' using the customer (positive amounts) & the supplier flow (negative amounts). :param amount: The amount in journal's currency. :param amount_currency: The amount in the foreign currency. :param journal_currency: The journal's currency as a res.currency record. :param foreign_currency: The foreign currency as a res.currency record. :param expected_liquidity_values: The expected account.move.line values for the liquidity line. :param expected_counterpart_values: The expected account.move.line values for the counterpart line. ''' # Check the full process with positive amount (customer process). self._test_statement_line_edition( self.bank_journal_2, amount, amount_currency, journal_currency, foreign_currency, expected_liquidity_values, expected_counterpart_values, ) # Check the full process with negative amount (supplier process). self._test_statement_line_edition( self.bank_journal_3, -amount, -amount_currency, journal_currency, foreign_currency, { **expected_liquidity_values, 'debit': expected_liquidity_values.get('credit', 0.0), 'credit': expected_liquidity_values.get('debit', 0.0), 'amount_currency': -expected_liquidity_values.get('amount_currency', 0.0), }, { **expected_counterpart_values, 'debit': expected_counterpart_values.get('credit', 0.0), 'credit': expected_counterpart_values.get('debit', 0.0), 'amount_currency': -expected_counterpart_values.get('amount_currency', 0.0), }, ) def test_edition_journal_curr_2_statement_curr_3(self): self._test_edition_customer_and_supplier_flows( 80.0, 120.0, self.currency_2, self.currency_3, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -120.0, 'currency_id': self.currency_3.id}, ) def test_edition_journal_curr_2_statement_curr_1(self): self._test_edition_customer_and_supplier_flows( 120.0, 80.0, self.currency_2, self.currency_1, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 120.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -80.0, 'currency_id': self.currency_1.id}, ) def test_edition_journal_curr_1_statement_curr_2(self): self._test_edition_customer_and_supplier_flows( 80.0, 120.0, self.currency_1, self.currency_2, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -120.0, 'currency_id': self.currency_2.id}, ) def test_edition_journal_curr_2_statement_false(self): self._test_edition_customer_and_supplier_flows( 80.0, 0.0, self.currency_2, False, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -80.0, 'currency_id': self.currency_2.id}, ) def test_edition_journal_curr_1_statement_false(self): self._test_edition_customer_and_supplier_flows( 80.0, 0.0, self.currency_1, False, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -80.0, 'currency_id': self.currency_1.id}, ) def test_zero_amount_journal_curr_1_statement_curr_2(self): self.bank_journal_2.currency_id = self.currency_1 statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': self.currency_2.id, 'amount': 0.0, 'amount_currency': 10.0, }), ], }) self.assertRecordValues(statement.line_ids.move_id.line_ids, [ {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': -10.0, 'currency_id': self.currency_2.id}, ]) def test_zero_amount_currency_journal_curr_1_statement_curr_2(self): self.bank_journal_2.currency_id = self.currency_1 statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': self.currency_2.id, 'amount': 10.0, 'amount_currency': 0.0, }), ], }) self.assertRecordValues(statement.line_ids.move_id.line_ids, [ {'debit': 10.0, 'credit': 0.0, 'amount_currency': 10.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 10.0, 'amount_currency': 0.0, 'currency_id': self.currency_2.id}, ]) def test_zero_amount_journal_curr_2_statement_curr_1(self): self.bank_journal_2.currency_id = self.currency_2 statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': self.currency_1.id, 'amount': 0.0, 'amount_currency': 10.0, }), ], }) self.assertRecordValues(statement.line_ids.move_id.line_ids, [ {'debit': 10.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 10.0, 'amount_currency': -10.0, 'currency_id': self.currency_1.id}, ]) def test_zero_amount_currency_journal_curr_2_statement_curr_1(self): self.bank_journal_2.currency_id = self.currency_2 statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': self.currency_1.id, 'amount': 10.0, 'amount_currency': 0.0, }), ], }) self.assertRecordValues(statement.line_ids.move_id.line_ids, [ {'debit': 0.0, 'credit': 0.0, 'amount_currency': 10.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': self.currency_1.id}, ]) def test_zero_amount_journal_curr_2_statement_curr_3(self): self.bank_journal_2.currency_id = self.currency_2 statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': self.currency_3.id, 'amount': 0.0, 'amount_currency': 10.0, }), ], }) self.assertRecordValues(statement.line_ids.move_id.line_ids, [ {'debit': 0.0, 'credit': 0.0, 'amount_currency': 0.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 0.0, 'amount_currency': -10.0, 'currency_id': self.currency_3.id}, ]) def test_zero_amount_currency_journal_curr_2_statement_curr_3(self): self.bank_journal_2.currency_id = self.currency_2 statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': self.currency_3.id, 'amount': 10.0, 'amount_currency': 0.0, }), ], }) self.assertRecordValues(statement.line_ids.move_id.line_ids, [ {'debit': 5.0, 'credit': 0.0, 'amount_currency': 10.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 5.0, 'amount_currency': 0.0, 'currency_id': self.currency_3.id}, ]) def test_constraints(self): def assertStatementLineConstraint(statement_vals, statement_line_vals): with self.assertRaises(Exception), self.cr.savepoint(): self.env['account.bank.statement'].create({ **statement_vals, 'line_ids': [(0, 0, statement_line_vals)], }) statement_vals = { 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_2.id, } statement_line_vals = { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': False, 'amount': 10.0, 'amount_currency': 0.0, } # ==== Test constraints at creation ==== # Can't have a stand alone amount in foreign currency without foreign currency set. assertStatementLineConstraint(statement_vals, { **statement_line_vals, 'amount_currency': 10.0, }) # ==== Test constraints at edition ==== statement = self.env['account.bank.statement'].create({ **statement_vals, 'line_ids': [(0, 0, statement_line_vals)], }) st_line = statement.line_ids # You can't messed up the journal entry by adding another liquidity line. addition_lines_to_create = [ { 'debit': 1.0, 'credit': 0, 'account_id': self.bank_journal_2.default_account_id.id, 'move_id': st_line.move_id.id, }, { 'debit': 0, 'credit': 1.0, 'account_id': self.company_data['default_account_revenue'].id, 'move_id': st_line.move_id.id, }, ] with self.assertRaises(UserError), self.cr.savepoint(): st_line.move_id.write({ 'line_ids': [(0, 0, vals) for vals in addition_lines_to_create] }) with self.assertRaises(UserError), self.cr.savepoint(): st_line.line_ids.create(addition_lines_to_create) # You can't set the journal entry in an unconsistent state. with self.assertRaises(UserError), self.cr.savepoint(): st_line.move_id.action_post() def test_statement_line_move_onchange_1(self): ''' Test the consistency between the account.bank.statement.line and the generated account.move.lines using the form view emulator. ''' # Check the initial state of the statement line. self.assertBankStatementLine(self.statement_line, self.expected_st_line, [self.expected_counterpart_line, self.expected_bank_line]) # Inverse the amount + change them. with Form(self.statement) as statement_form: with statement_form.line_ids.edit(0) as st_line_form: st_line_form.amount = -2000.0 st_line_form.amount_currency = -4000.0 st_line_form.foreign_currency_id = self.currency_3 self.assertBankStatementLine(self.statement_line, { **self.expected_st_line, 'amount': -2000.0, 'amount_currency': -4000.0, 'foreign_currency_id': self.currency_3.id, }, [ { **self.expected_bank_line, 'debit': 0.0, 'credit': 2000.0, 'amount_currency': -2000.0, 'currency_id': self.currency_1.id, }, { **self.expected_counterpart_line, 'debit': 2000.0, 'credit': 0.0, 'amount_currency': 4000.0, 'currency_id': self.currency_3.id, }, ]) # Check changing the label and the partner. with Form(self.statement) as statement_form: with statement_form.line_ids.edit(0) as st_line_form: st_line_form.payment_ref = 'line_1 (bis)' st_line_form.partner_id = self.partner_b self.assertBankStatementLine(self.statement_line, { **self.expected_st_line, 'payment_ref': self.statement_line.payment_ref, 'partner_id': self.statement_line.partner_id.id, 'amount': -2000.0, 'amount_currency': -4000.0, 'foreign_currency_id': self.currency_3.id, }, [ { **self.expected_bank_line, 'name': self.statement_line.payment_ref, 'partner_id': self.statement_line.partner_id.id, 'debit': 0.0, 'credit': 2000.0, 'amount_currency': -2000.0, 'currency_id': self.currency_1.id, }, { **self.expected_counterpart_line, 'name': self.statement_line.payment_ref, 'partner_id': self.statement_line.partner_id.id, 'debit': 2000.0, 'credit': 0.0, 'amount_currency': 4000.0, 'currency_id': self.currency_3.id, }, ]) # ------------------------------------------------------------------------- # TESTS about reconciliation: # - Test '_prepare_counterpart_move_line_vals': one test for each case. # - Test 'reconcile': 3 cases: # - Open-balance in debit. # - Open-balance in credit. # - No open-balance. # - Test 'button_undo_reconciliation'. # ------------------------------------------------------------------------- def _test_statement_line_reconciliation( self, journal, amount, amount_currency, counterpart_amount, journal_currency, foreign_currency, counterpart_currency, expected_liquidity_values, expected_counterpart_values): ''' Test the reconciliation of a statement line. :param journal: The account.journal record that will be set on the statement line. :param amount: The amount in journal's currency. :param amount_currency: The amount in the foreign currency. :param counterpart_amount: The amount of the invoice to reconcile. :param journal_currency: The journal's currency as a res.currency record. :param foreign_currency: The foreign currency as a res.currency record. :param counterpart_currency: The invoice currency as a res.currency record. :param expected_liquidity_values: The expected account.move.line values for the liquidity line. :param expected_counterpart_values: The expected account.move.line values for the counterpart line. ''' if journal_currency: journal.currency_id = journal_currency.id statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': journal.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': foreign_currency and foreign_currency.id, 'amount': amount, 'amount_currency': amount_currency, }), ], }) statement_line = statement.line_ids # - There is 3 flows to check: # * The invoice will fully reconcile the statement line. # * The invoice will partially reconcile the statement line and leads to an open balance in debit. # * The invoice will partially reconcile the statement line and leads to an open balance in credit. # - The dates are different to be sure the reconciliation will preserve the conversion rate bank side. move_type = 'out_invoice' if counterpart_amount < 0.0 else 'in_invoice' test_invoices = self.env['account.move'].create([ { 'move_type': move_type, 'invoice_date': fields.Date.from_string('2016-01-01'), 'date': fields.Date.from_string('2016-01-01'), 'partner_id': self.partner_a.id, 'currency_id': counterpart_currency.id, 'invoice_line_ids': [ (0, None, { 'name': 'counterpart line, same amount', 'account_id': self.company_data['default_account_revenue'].id, 'quantity': 1, 'price_unit': abs(counterpart_amount), }), ], }, { 'move_type': move_type, 'invoice_date': fields.Date.from_string('2016-01-01'), 'date': fields.Date.from_string('2016-01-01'), 'partner_id': self.partner_a.id, 'currency_id': counterpart_currency.id, 'invoice_line_ids': [ (0, None, { 'name': 'counterpart line, lower amount', 'account_id': self.company_data['default_account_revenue'].id, 'quantity': 1, 'price_unit': abs(counterpart_amount / 2), }), ], }, { 'move_type': move_type, 'invoice_date': fields.Date.from_string('2016-01-01'), 'date': fields.Date.from_string('2016-01-01'), 'partner_id': self.partner_a.id, 'currency_id': counterpart_currency.id, 'invoice_line_ids': [ (0, None, { 'name': 'counterpart line, bigger amount', 'account_id': self.company_data['default_account_revenue'].id, 'quantity': 1, 'price_unit': abs(counterpart_amount * 2), }), ], }, ]) test_invoices.action_post() statement.button_post() counterpart_lines = test_invoices.mapped('line_ids').filtered(lambda line: line.account_internal_type in ('receivable', 'payable')) # Check the full reconciliation. statement_line.reconcile([{'id': counterpart_lines[0].id}]) liquidity_lines, suspense_lines, other_lines = statement_line._seek_for_lines() self.assertRecordValues(liquidity_lines, [expected_liquidity_values]) self.assertRecordValues(other_lines, [expected_counterpart_values]) # Check the reconciliation with partial lower amount. statement_line.button_undo_reconciliation() statement_line.reconcile([{'id': counterpart_lines[1].id}]) liquidity_lines, suspense_lines, other_lines = statement_line._seek_for_lines() self.assertRecordValues(liquidity_lines, [expected_liquidity_values]) self.assertRecordValues(other_lines.sorted('balance', reverse=amount < 0.0), [ { **expected_counterpart_values, 'debit': expected_counterpart_values.get('debit', 0.0) / 2, 'credit': expected_counterpart_values.get('credit', 0.0) / 2, 'amount_currency': expected_counterpart_values.get('amount_currency', 0.0) / 2, }, { 'debit': expected_counterpart_values.get('debit', 0.0) / 2, 'credit': expected_counterpart_values.get('credit', 0.0) / 2, 'amount_currency': expected_counterpart_values.get('amount_currency', 0.0) / 2, 'currency_id': expected_counterpart_values.get('currency_id'), }, ]) # Check the reconciliation with partial higher amount. statement_line.button_undo_reconciliation() statement_line.reconcile([{'id': counterpart_lines[2].id}]) liquidity_lines, suspense_lines, other_lines = statement_line._seek_for_lines() self.assertRecordValues(liquidity_lines, [expected_liquidity_values]) self.assertRecordValues(other_lines.sorted('balance', reverse=amount < 0.0), [ { **expected_counterpart_values, 'debit': expected_counterpart_values.get('debit', 0.0) * 2, 'credit': expected_counterpart_values.get('credit', 0.0) * 2, 'amount_currency': expected_counterpart_values.get('amount_currency', 0.0) * 2, }, { 'debit': expected_counterpart_values.get('credit', 0.0), 'credit': expected_counterpart_values.get('debit', 0.0), 'amount_currency': -expected_counterpart_values.get('amount_currency', 0.0), 'currency_id': expected_counterpart_values.get('currency_id'), }, ]) # Make sure the statement line is still correct. self.assertRecordValues(statement_line, [{ 'amount': amount, 'amount_currency': amount_currency, }]) def _test_reconciliation_customer_and_supplier_flows( self, amount, amount_currency, counterpart_amount, journal_currency, foreign_currency, counterpart_currency, expected_liquidity_values, expected_counterpart_values): ''' Test '_test_statement_line_reconciliation' using the customer (positive amounts) & the supplier flow (negative amounts). :param amount: The amount in journal's currency. :param amount_currency: The amount in the foreign currency. :param counterpart_amount: The amount of the invoice to reconcile. :param journal_currency: The journal's currency as a res.currency record. :param foreign_currency: The foreign currency as a res.currency record. :param counterpart_currency: The invoice currency as a res.currency record. :param expected_liquidity_values: The expected account.move.line values for the liquidity line. :param expected_counterpart_values: The expected account.move.line values for the counterpart line. ''' # Check the full process with positive amount (customer process). self._test_statement_line_reconciliation( self.bank_journal_2, amount, amount_currency, counterpart_amount, journal_currency, foreign_currency, counterpart_currency, expected_liquidity_values, expected_counterpart_values, ) # Check the full process with negative amount (supplier process). self._test_statement_line_reconciliation( self.bank_journal_3, -amount, -amount_currency, -counterpart_amount, journal_currency, foreign_currency, counterpart_currency, { **expected_liquidity_values, 'debit': expected_liquidity_values.get('credit', 0.0), 'credit': expected_liquidity_values.get('debit', 0.0), 'amount_currency': -expected_liquidity_values.get('amount_currency', 0.0), }, { **expected_counterpart_values, 'debit': expected_counterpart_values.get('credit', 0.0), 'credit': expected_counterpart_values.get('debit', 0.0), 'amount_currency': -expected_counterpart_values.get('amount_currency', 0.0), }, ) def test_reconciliation_journal_curr_2_statement_curr_3_counterpart_curr_3(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 120.0, -120.0, self.currency_2, self.currency_3, self.currency_3, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -120.0, 'currency_id': self.currency_3.id}, ) def test_reconciliation_journal_curr_2_statement_curr_1_counterpart_curr_2(self): self._test_reconciliation_customer_and_supplier_flows( 120.0, 80.0, -120.0, self.currency_2, self.currency_1, self.currency_2, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 120.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -80.0, 'currency_id': self.currency_1.id}, ) def test_reconciliation_journal_curr_2_statement_curr_3_counterpart_curr_2(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 120.0, -80.0, self.currency_2, self.currency_3, self.currency_2, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -120.0, 'currency_id': self.currency_3.id}, ) def test_reconciliation_journal_curr_2_statement_curr_3_counterpart_curr_4(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 120.0, -480.0, self.currency_2, self.currency_3, self.currency_4, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -120.0, 'currency_id': self.currency_3.id}, ) def test_reconciliation_journal_curr_1_statement_curr_2_counterpart_curr_2(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 120.0, -120.0, self.currency_1, self.currency_2, self.currency_2, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -120.0, 'currency_id': self.currency_2.id}, ) def test_reconciliation_journal_curr_1_statement_curr_2_counterpart_curr_3(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 120.0, -480.0, self.currency_1, self.currency_2, self.currency_3, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -120.0, 'currency_id': self.currency_2.id}, ) def test_reconciliation_journal_curr_2_statement_false_counterpart_curr_2(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 0.0, -80.0, self.currency_2, False, self.currency_2, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -80.0, 'currency_id': self.currency_2.id}, ) def test_reconciliation_journal_curr_2_statement_false_counterpart_curr_3(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 0.0, -240.0, self.currency_2, False, self.currency_3, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -80.0, 'currency_id': self.currency_2.id}, ) def test_reconciliation_journal_curr_1_statement_false_counterpart_curr_3(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 0.0, -480.0, self.currency_1, False, self.currency_3, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -80.0, 'currency_id': self.currency_1.id}, ) def test_reconciliation_journal_curr_2_statement_curr_1_counterpart_curr_1(self): self._test_reconciliation_customer_and_supplier_flows( 120.0, 80.0, -80.0, self.currency_2, self.currency_1, self.currency_1, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 120.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -80.0, 'currency_id': self.currency_1.id}, ) def test_reconciliation_journal_curr_2_statement_curr_3_counterpart_curr_1(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 120.0, -40.0, self.currency_2, self.currency_3, self.currency_1, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -120.0, 'currency_id': self.currency_3.id}, ) def test_reconciliation_journal_curr_1_statement_curr_2_counterpart_curr_1(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 120.0, -80.0, self.currency_1, self.currency_2, self.currency_1, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -120.0, 'currency_id': self.currency_2.id}, ) def test_reconciliation_journal_curr_2_statement_false_counterpart_curr_1(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 0.0, -40.0, self.currency_2, False, self.currency_1, {'debit': 40.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_2.id}, {'debit': 0.0, 'credit': 40.0, 'amount_currency': -80.0, 'currency_id': self.currency_2.id}, ) def test_reconciliation_journal_curr_1_statement_false_counterpart_curr_1(self): self._test_reconciliation_customer_and_supplier_flows( 80.0, 0.0, -80.0, self.currency_1, False, self.currency_1, {'debit': 80.0, 'credit': 0.0, 'amount_currency': 80.0, 'currency_id': self.currency_1.id}, {'debit': 0.0, 'credit': 80.0, 'amount_currency': -80.0, 'currency_id': self.currency_1.id}, ) def test_reconciliation_move_draft(self): ''' Ensures that the account move of a reconciled statement cannot be set to draft ''' statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_1.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'amount': 100.0, }), ], }) statement.button_post() statement.line_ids[0].reconcile([{'name': 'test', 'account_id': self.company_data['default_account_revenue'].id, 'balance': -100}]) statement.button_validate_or_action() account_move = statement.line_ids.move_id with self.assertRaises(UserError): account_move.button_draft() def test_reconciliation_statement_line_state(self): ''' Test the reconciliation on the bank statement line with a foreign currency on the journal: - Ensure the statement line is_reconciled field is well computed. - Ensure the reconciliation is working well when dealing with a foreign currency at different dates. - Ensure the reconciliation can be undo. - Ensure the reconciliation is still possible with to_check. ''' self.statement.button_post() receivable_acc_1 = self.company_data['default_account_receivable'] receivable_acc_2 = self.copy_account(self.company_data['default_account_receivable']) payment_account = self.bank_journal_1.company_id.account_journal_payment_debit_account_id random_acc_1 = self.company_data['default_account_revenue'] random_acc_2 = self.copy_account(self.company_data['default_account_revenue']) test_move = self.env['account.move'].create({ 'move_type': 'entry', 'date': fields.Date.from_string('2016-01-01'), 'line_ids': [ (0, None, { 'name': 'counterpart of the whole move', 'account_id': random_acc_1.id, 'debit': 0.0, 'credit': 1030.0, }), (0, None, { 'name': 'test line 1 - receivable account', 'account_id': receivable_acc_1.id, 'currency_id': self.currency_2.id, 'debit': 500.0, 'credit': 0.0, 'amount_currency': 1500.0, }), (0, None, { 'name': 'test line 2 - another receivable account', 'account_id': receivable_acc_2.id, 'currency_id': self.currency_2.id, 'debit': 500.0, 'credit': 0.0, 'amount_currency': 1500.0, }), (0, None, { 'name': 'test line 3 - payment transfer account', 'account_id': payment_account.id, 'currency_id': self.currency_2.id, 'debit': 30.0, 'credit': 0.0, 'amount_currency': 90.0, }), ] }) test_move.action_post() test_line_1 = test_move.line_ids.filtered(lambda line: line.account_id == receivable_acc_1) test_line_2 = test_move.line_ids.filtered(lambda line: line.account_id == receivable_acc_2) test_line_3 = test_move.line_ids.filtered(lambda line: line.account_id == payment_account) self.statement_line.reconcile([ # test line 1 # Will reconcile 300.0 in balance, 600.0 in amount_currency. {'id': test_line_1.id, 'balance': -600.0}, # test line 2 # Will reconcile 250.0 in balance, 500.0 in amount_currency. {'id': test_line_2.id, 'balance': -500.0}, # test line 3 # Will reconcile 30.0 in balance, 90.0 in amount_currency. {'id': test_line_3.id}, # test line 4 # Will reconcile 50.0 in balance, 100.0 in amount_currency. {'name': 'whatever', 'account_id': random_acc_1.id, 'balance': -100.0}, ]) self.assertBankStatementLine(self.statement_line, { **self.expected_st_line, 'is_reconciled': True, }, [ { 'name': '%s: Open Balance' % self.statement_line.payment_ref, 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': receivable_acc_1.id, # This account is retrieved on the partner. 'debit': 0.0, 'credit': 605.0, 'amount_currency': -1210.0, 'amount_residual': -605.0, 'amount_residual_currency': -1210.0, }, { 'name': test_line_1.name, 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': receivable_acc_1.id, 'debit': 0.0, 'credit': 300.0, 'amount_currency': -600.0, 'amount_residual': 0.0, 'amount_residual_currency': 0.0, }, { 'name': test_line_2.name, 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': receivable_acc_2.id, 'debit': 0.0, 'credit': 250.0, 'amount_currency': -500.0, 'amount_residual': 0.0, 'amount_residual_currency': 0.0, }, { 'name': 'whatever', 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': random_acc_1.id, 'debit': 0.0, 'credit': 50.0, 'amount_currency': -100.0, 'amount_residual': 0.0, 'amount_residual_currency': 0.0, }, { 'name': test_line_3.name, 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': test_line_3.account_id.id, 'debit': 0.0, 'credit': 45.0, 'amount_currency': -90.0, 'amount_residual': 0.0, 'amount_residual_currency': 0.0, }, { **self.expected_bank_line, 'amount_residual': 1250.0, 'amount_residual_currency': 1250.0, }, ]) # Undo the reconciliation to return to the initial state. self.statement_line.button_undo_reconciliation() self.assertBankStatementLine(self.statement_line, self.expected_st_line, [self.expected_counterpart_line, self.expected_bank_line]) # Modify the counterpart line with to_check enabled. self.statement_line.reconcile([ {'name': 'whatever', 'account_id': random_acc_1.id, 'balance': -100.0}, ], to_check=True) self.assertBankStatementLine(self.statement_line, { **self.expected_st_line, 'is_reconciled': True, }, [ { 'name': '%s: Open Balance' % self.statement_line.payment_ref, 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': receivable_acc_1.id, # This account is retrieved on the partner. 'debit': 0.0, 'credit': 1200.0, 'amount_currency': -2400.0, 'amount_residual': -1200.0, 'amount_residual_currency': -2400.0, }, { 'name': 'whatever', 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': random_acc_1.id, 'debit': 0.0, 'credit': 50.0, 'amount_currency': -100.0, 'amount_residual': 0.0, 'amount_residual_currency': 0.0, }, { **self.expected_bank_line, 'amount_residual': 1250.0, 'amount_residual_currency': 1250.0, }, ]) # Modify the counterpart line. Should be allowed by the to_check enabled. self.statement_line.reconcile([ {'name': 'whatever again', 'account_id': random_acc_2.id, 'balance': -500.0}, ]) self.assertBankStatementLine(self.statement_line, { **self.expected_st_line, 'is_reconciled': True, }, [ { 'name': '%s: Open Balance' % self.statement_line.payment_ref, 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': receivable_acc_1.id, # This account is retrieved on the partner. 'debit': 0.0, 'credit': 1000.0, 'amount_currency': -2000.0, 'amount_residual': -1000.0, 'amount_residual_currency': -2000.0, }, { 'name': 'whatever again', 'partner_id': self.statement_line.partner_id.id, 'currency_id': self.currency_2.id, 'account_id': random_acc_2.id, 'debit': 0.0, 'credit': 250.0, 'amount_currency': -500.0, 'amount_residual': 0.0, 'amount_residual_currency': 0.0, }, { **self.expected_bank_line, 'amount_residual': 1250.0, 'amount_residual_currency': 1250.0, }, ]) # The statement line is no longer in the 'to_check' mode. # Reconciling again should raise an error. with self.assertRaises(UserError), self.cr.savepoint(): self.statement_line.reconcile([ {'name': 'whatever', 'account_id': random_acc_1.id, 'balance': -100.0}, ]) def test_reconciliation_statement_line_foreign_currency(self): statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_1.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'foreign_currency_id': self.currency_2.id, 'amount': -80.0, 'amount_currency': -120.0, }), ], }) statement.button_post() statement_line = statement.line_ids invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'invoice_date': '2019-01-01', 'date': '2019-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.currency_2.id, 'invoice_line_ids': [ (0, None, { 'name': 'counterpart line, same amount', 'account_id': self.company_data['default_account_revenue'].id, 'quantity': 1, 'price_unit': 120.0, }), ], }) invoice.action_post() invoice_line = invoice.line_ids.filtered(lambda line: line.account_internal_type == 'payable') statement_line.reconcile([{'id': invoice_line.id}], allow_partial=True) self.assertRecordValues(statement_line.line_ids, [ # pylint: disable=bad-whitespace {'amount_currency': -80.0, 'currency_id': self.currency_1.id, 'balance': -80.0, 'reconciled': False}, {'amount_currency': 120.0, 'currency_id': self.currency_2.id, 'balance': 80.0, 'reconciled': True}, ]) def test_conversion_rate_rounding_issue(self): ''' Ensure the reconciliation is well handling the rounding issue due to multiple currency conversion rates. In this test, the resulting journal entry after reconciliation is: {'amount_currency': 7541.66, 'debit': 6446.97, 'credit': 0.0} {'amount_currency': 226.04, 'debit': 193.22, 'credit': 0.0} {'amount_currency': -7767.70, 'debit': 0.0, 'credit': 6640.19} ... but 226.04 / 1.1698 = 193.23. In this situation, 0.01 has been removed from this write-off line in order to avoid an unecessary open-balance line being an exchange difference issue. ''' self.bank_journal_2.currency_id = self.currency_2 self.currency_data['rates'][-1].rate = 1.1698 statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2017-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': 'line_1', 'partner_id': self.partner_a.id, 'amount': 7541.66, }), ], }) statement.button_post() statement_line = statement.line_ids payment = self.env['account.payment'].create({ 'amount': 7767.70, 'date': '2019-01-01', 'currency_id': self.currency_2.id, 'payment_type': 'inbound', 'partner_type': 'customer', }) payment.action_post() liquidity_lines, counterpart_lines, writeoff_lines = payment._seek_for_lines() self.assertRecordValues(liquidity_lines, [{'amount_currency': 7767.70}]) statement_line.reconcile([ {'id': liquidity_lines.id}, {'balance': 226.04, 'account_id': self.company_data['default_account_revenue'].id, 'name': "write-off"}, ]) self.assertRecordValues(statement_line.line_ids, [ {'amount_currency': 7541.66, 'debit': 6446.97, 'credit': 0.0}, {'amount_currency': 226.04, 'debit': 193.22, 'credit': 0.0}, {'amount_currency': -7767.70, 'debit': 0.0, 'credit': 6640.19}, ]) def test_zero_amount_statement_line(self): ''' Ensure the statement line is directly marked as reconciled when having an amount of zero. ''' self.company_data['company'].account_journal_suspense_account_id.reconcile = False statement = self.env['account.bank.statement'].with_context(skip_check_amounts_currencies=True).create({ 'name': 'test_statement', 'date': '2017-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': "Happy new year", 'amount': 0.0, }), ], }) statement_line = statement.line_ids self.assertRecordValues(statement_line, [{'is_reconciled': True, 'amount_residual': 0.0}]) def test_bank_statement_line_analytic(self): ''' Ensure the analytic lines are generated during the reconciliation. ''' analytic_account = self.env['account.analytic.account'].create({'name': 'analytic_account'}) statement = self.env['account.bank.statement'].with_context(skip_check_amounts_currencies=True).create({ 'name': 'test_statement', 'date': '2017-01-01', 'journal_id': self.bank_journal_2.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': "line", 'amount': 100.0, }), ], }) statement_line = statement.line_ids statement_line.reconcile([{ 'balance': -100.0, 'account_id': self.company_data['default_account_revenue'].id, 'name': "write-off", 'analytic_account_id': analytic_account.id, }]) # Check the analytic account is there. self.assertRecordValues(statement_line.line_ids.sorted('balance'), [ {'balance': -100.0, 'analytic_account_id': analytic_account.id}, {'balance': 100.0, 'analytic_account_id': False}, ]) # Check the analytic lines. self.assertRecordValues(statement_line.line_ids.analytic_line_ids, [ {'amount': 100.0, 'account_id': analytic_account.id}, ]) def test_reconciliation_line_with_no_partner(self): """ Ensure that entry lines and statement line have no partner when reconciling lines without partner with others with partner """ statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_1.id, 'line_ids': [ (0, 0, { 'date': '2022-01-01', 'payment_ref': "Happy new year", 'amount': 200.0, }), ], }) statement.button_post() partner = self.env['res.partner'].create({'name': 'test'}) receivable_account = self.company_data['default_account_receivable'] outstanding_account = self.env['account.account'].search([('code', '=', '101402'), ('company_id', '=', self.env.company.id)]) payments = self.env['account.payment'].create([ { 'name': 'Payment without partner', 'date': fields.Date.from_string('2022-01-01'), 'is_internal_transfer': False, 'amount': 100.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'destination_account_id': receivable_account.id, 'journal_id': self.bank_journal_1.id, }, { 'name': 'Payment with partner', 'date': fields.Date.from_string('2022-01-01'), 'is_internal_transfer': False, 'amount': 100.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': partner.id, 'destination_account_id': receivable_account.id, 'journal_id': self.bank_journal_1.id, }, ]) payments.action_post() statement_line = statement.line_ids statement_line.reconcile([ {'id': payments[0].move_id.line_ids.filtered(lambda line: line.account_id == outstanding_account).id}, {'id': payments[1].move_id.line_ids.filtered(lambda line: line.account_id == outstanding_account).id}, ]) self.assertRecordValues( statement.line_ids.move_id.line_ids, [ { 'debit': 200.0, 'credit': 0.0, 'partner_id': False, 'account_id': self.bank_journal_1.default_account_id.id }, { 'debit': 0.0, 'credit': 100.0, 'partner_id': False, 'account_id': outstanding_account.id }, { 'debit': 0.0, 'credit': 100.0, 'partner_id': partner.id, 'account_id': outstanding_account.id }, ]) self.assertRecordValues(statement.line_ids, [{ 'partner_id': False, }]) def test_statement_line_note_onchange_partner(self): """ Check if narration field stays as it is when changing the partner in reconciliation widget. """ bank_stmt = self.env['account.bank.statement'].create({ 'company_id': self.env.company.id, 'journal_id': self.bank_journal_1.id, 'name': 'test', }) bank_stmt_line = self.env['account.bank.statement.line'].create({ 'payment_ref': 'testLine', 'statement_id': bank_stmt.id, 'narration': 'This is a note', 'amount': 100, }) bank_stmt_line.partner_id = self.partner_b self.assertRecordValues(bank_stmt_line, [{ 'payment_ref': 'testLine', 'statement_id': bank_stmt.id, 'narration': '<p>This is a note</p>', 'amount': 100, }]) def test_create_statement_line_with_inconsistent_currencies(self): statement = self.env['account.bank.statement'].create({ 'name': 'test_statement', 'date': '2019-01-01', 'journal_id': self.bank_journal_1.id, 'line_ids': [ (0, 0, { 'date': '2019-01-01', 'payment_ref': "Happy new year", 'amount': 200.0, 'amount_currency': 200.0, 'foreign_currency_id': self.env.company.currency_id.id, }), ], }) self.assertRecordValues(statement.line_ids, [{ 'currency_id': self.env.company.currency_id.id, 'foreign_currency_id': False, 'amount': 200.0, 'amount_currency': 0.0, }])
44.246181
75,307
4,226
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo import fields from odoo.tests.common import Form @tagged('post_install', '-at_install') class TestAccountInvoiceRounding(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.pay_term_today = cls.env['account.payment.term'].create({ 'name': 'Today', 'line_ids': [ (0, 0, { 'value': 'balance', 'days': 0, 'option': 'day_after_invoice_date', }), ], }) cls.pay_term_min_31days_15th = cls.env['account.payment.term'].create({ 'name': 'the 15th of the month, min 31 days from now', 'line_ids': [ (0, 0, { 'value': 'balance', 'days': 31, 'day_of_the_month': 15, 'option': 'day_after_invoice_date', }), ], }) cls.pay_term_45_end_month = cls.env['account.payment.term'].create({ 'name': '45 Days from End of Month', 'line_ids': [ (0, 0, { 'value': 'balance', 'days': 45, 'option': 'after_invoice_month', }), ], }) cls.pay_term_last_day_of_month = cls.env['account.payment.term'].create({ 'name': 'Last Day of month', 'line_ids': [ (0, 0, { 'value': 'balance', 'days': 31, 'option': 'day_current_month', }), ], }) cls.pay_term_first_day_next_month = cls.env['account.payment.term'].create({ 'name': 'First day next month', 'line_ids': [ (0, 0, { 'value': 'balance', 'days': 1, 'option': 'day_following_month', }), ], }) cls.invoice = cls.init_invoice('out_refund', products=cls.product_a+cls.product_b) def assertPaymentTerm(self, pay_term, invoice_date, dates): with Form(self.invoice) as move_form: move_form.invoice_payment_term_id = pay_term move_form.invoice_date = invoice_date move_form.date = invoice_date self.assertEqual( self.invoice.line_ids.filtered( lambda l: l.account_id == self.company_data['default_account_receivable'] ).mapped('date_maturity'), [fields.Date.from_string(date) for date in dates], ) def test_payment_term(self): self.assertPaymentTerm(self.pay_term_today, '2019-01-01', ['2019-01-01']) self.assertPaymentTerm(self.pay_term_today, '2019-01-15', ['2019-01-15']) self.assertPaymentTerm(self.pay_term_today, '2019-01-31', ['2019-01-31']) self.assertPaymentTerm(self.pay_term_45_end_month, '2019-01-01', ['2019-03-17']) self.assertPaymentTerm(self.pay_term_45_end_month, '2019-01-15', ['2019-03-17']) self.assertPaymentTerm(self.pay_term_45_end_month, '2019-01-31', ['2019-03-17']) self.assertPaymentTerm(self.pay_term_min_31days_15th, '2019-01-01', ['2019-02-15']) self.assertPaymentTerm(self.pay_term_min_31days_15th, '2019-01-15', ['2019-02-15']) self.assertPaymentTerm(self.pay_term_min_31days_15th, '2019-01-31', ['2019-03-15']) self.assertPaymentTerm(self.pay_term_last_day_of_month, '2019-01-01', ['2019-01-31']) self.assertPaymentTerm(self.pay_term_last_day_of_month, '2019-01-15', ['2019-01-31']) self.assertPaymentTerm(self.pay_term_last_day_of_month, '2019-01-31', ['2019-01-31']) self.assertPaymentTerm(self.pay_term_first_day_next_month, '2019-01-01', ['2019-02-01']) self.assertPaymentTerm(self.pay_term_first_day_next_month, '2019-01-15', ['2019-02-01']) self.assertPaymentTerm(self.pay_term_first_day_next_month, '2019-01-31', ['2019-02-01'])
42.686869
4,226
11,397
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common class TestFiscalPosition(common.TransactionCase): """Tests for fiscal positions in auto apply (account.fiscal.position). If a partner has a vat number, the fiscal positions with "vat_required=True" are preferred. """ @classmethod def setUpClass(cls): super(TestFiscalPosition, cls).setUpClass() cls.fp = cls.env['account.fiscal.position'] # reset any existing FP cls.fp.search([]).write({'auto_apply': False}) cls.res_partner = cls.env['res.partner'] cls.be = be = cls.env.ref('base.be') cls.fr = fr = cls.env.ref('base.fr') cls.mx = mx = cls.env.ref('base.mx') cls.eu = cls.env.ref('base.europe') cls.nl = cls.env.ref('base.nl') cls.us = cls.env.ref('base.us') cls.state_fr = cls.env['res.country.state'].create(dict( name="State", code="ST", country_id=fr.id)) cls.jc = cls.res_partner.create(dict( name="JCVD", vat="BE0477472701", country_id=be.id)) cls.ben = cls.res_partner.create(dict( name="BP", country_id=be.id)) cls.george = cls.res_partner.create(dict( name="George", vat="BE0477472701", country_id=fr.id)) cls.alberto = cls.res_partner.create(dict( name="Alberto", vat="BE0477472701", country_id=mx.id)) cls.be_nat = cls.fp.create(dict( name="BE-NAT", auto_apply=True, country_id=be.id, vat_required=False, sequence=10)) cls.fr_b2c = cls.fp.create(dict( name="EU-VAT-FR-B2C", auto_apply=True, country_id=fr.id, vat_required=False, sequence=40)) cls.fr_b2b = cls.fp.create(dict( name="EU-VAT-FR-B2B", auto_apply=True, country_id=fr.id, vat_required=True, sequence=50)) def test_10_fp_country(self): def assert_fp(partner, expected_pos, message): self.assertEqual( self.fp.get_fiscal_position(partner.id).id, expected_pos.id, message) george, jc, ben, alberto = self.george, self.jc, self.ben, self.alberto # B2B has precedence over B2C for same country even when sequence gives lower precedence self.assertGreater(self.fr_b2b.sequence, self.fr_b2c.sequence) assert_fp(george, self.fr_b2b, "FR-B2B should have precedence over FR-B2C") self.fr_b2b.auto_apply = False assert_fp(george, self.fr_b2c, "FR-B2C should match now") self.fr_b2b.auto_apply = True # Create positions matching on Country Group and on NO country at all self.eu_intra_b2b = self.fp.create(dict( name="EU-INTRA B2B", auto_apply=True, country_group_id=self.eu.id, vat_required=True, sequence=20)) self.world = self.fp.create(dict( name="WORLD-EXTRA", auto_apply=True, vat_required=False, sequence=30)) # Country match has higher precedence than group match or sequence self.assertGreater(self.fr_b2b.sequence, self.eu_intra_b2b.sequence) assert_fp(george, self.fr_b2b, "FR-B2B should have precedence over EU-INTRA B2B") # B2B has precedence regardless of country or group match self.assertGreater(self.eu_intra_b2b.sequence, self.be_nat.sequence) assert_fp(jc, self.eu_intra_b2b, "EU-INTRA B2B should match before BE-NAT") # Lower sequence = higher precedence if country/group and VAT matches self.assertFalse(ben.vat) # No VAT set assert_fp(ben, self.be_nat, "BE-NAT should match before EU-INTRA due to lower sequence") # Remove BE from EU group, now BE-NAT should be the fallback match before the wildcard WORLD self.be.write({'country_group_ids': [(3, self.eu.id)]}) self.assertTrue(jc.vat) # VAT set assert_fp(jc, self.be_nat, "BE-NAT should match as fallback even w/o VAT match") # No country = wildcard match only if nothing else matches self.assertTrue(alberto.vat) # with VAT assert_fp(alberto, self.world, "WORLD-EXTRA should match anything else (1)") alberto.vat = False # or without assert_fp(alberto, self.world, "WORLD-EXTRA should match anything else (2)") # Zip range self.fr_b2b_zip100 = self.fr_b2b.copy(dict(zip_from=0, zip_to=5000, sequence=60)) george.zip = 6000 assert_fp(george, self.fr_b2b, "FR-B2B with wrong zip range should not match") george.zip = 3000 assert_fp(george, self.fr_b2b_zip100, "FR-B2B with zip range should have precedence") # States self.fr_b2b_state = self.fr_b2b.copy(dict(state_ids=[(4, self.state_fr.id)], sequence=70)) george.state_id = self.state_fr assert_fp(george, self.fr_b2b_zip100, "FR-B2B with zip should have precedence over states") george.zip = False assert_fp(george, self.fr_b2b_state, "FR-B2B with states should have precedence") # Dedicated position has max precedence george.property_account_position_id = self.be_nat assert_fp(george, self.be_nat, "Forced position has max precedence") def test_20_fp_one_tax_2m(self): self.src_tax = self.env['account.tax'].create({'name': "SRC", 'amount': 0.0}) self.dst1_tax = self.env['account.tax'].create({'name': "DST1", 'amount': 0.0}) self.dst2_tax = self.env['account.tax'].create({'name': "DST2", 'amount': 0.0}) self.fp2m = self.fp.create({ 'name': "FP-TAX2TAXES", 'tax_ids': [ (0,0,{ 'tax_src_id': self.src_tax.id, 'tax_dest_id': self.dst1_tax.id }), (0,0,{ 'tax_src_id': self.src_tax.id, 'tax_dest_id': self.dst2_tax.id }) ] }) mapped_taxes = self.fp2m.map_tax(self.src_tax) self.assertEqual(mapped_taxes, self.dst1_tax | self.dst2_tax) def test_30_fp_delivery_address(self): # Make sure the billing company is from Belgium (within the EU) self.env.company.vat = 'BE0477472701' self.env.company.country_id = self.be # Reset any existing FP self.env['account.fiscal.position'].search([]).auto_apply = False # Create the fiscal positions fp_be_nat = self.env['account.fiscal.position'].create({ 'name': 'Régime National', 'auto_apply': True, 'country_id': self.be.id, 'vat_required': True, 'sequence': 10, }) fp_eu_priv = self.env['account.fiscal.position'].create({ 'name': 'EU privé', 'auto_apply': True, 'country_group_id': self.eu.id, 'vat_required': False, 'sequence': 20, }) fp_eu_intra = self.env['account.fiscal.position'].create({ 'name': 'Régime Intra-Communautaire', 'auto_apply': True, 'country_group_id': self.eu.id, 'vat_required': True, 'sequence': 30, }) fp_eu_extra = self.env['account.fiscal.position'].create({ 'name': 'Régime Extra-Communautaire', 'auto_apply': True, 'vat_required': False, 'sequence': 40, }) # Create the partners partner_be_vat = self.env['res.partner'].create({ 'name': 'BE VAT', 'vat': 'BE0477472701', 'country_id': self.be.id, }) partner_nl_vat = self.env['res.partner'].create({ 'name': 'NL VAT', 'vat': 'NL123456782B90', 'country_id': self.nl.id, }) partner_nl_no_vat = self.env['res.partner'].create({ 'name': 'NL NO VAT', 'country_id': self.nl.id, }) partner_us_no_vat = self.env['res.partner'].create({ 'name': 'US NO VAT', 'country_id': self.us.id, }) # Case : 1 # Billing (VAT/country) : BE/BE # Delivery (VAT/country) : NL/NL # Expected FP : Régime National self.assertEqual( self.env['account.fiscal.position'].get_fiscal_position(partner_be_vat.id, partner_nl_vat.id), fp_be_nat ) # Case : 2 # Billing (VAT/country) : NL/NL # Delivery (VAT/country) : BE/BE # Expected FP : Régime National self.assertEqual( self.env['account.fiscal.position'].get_fiscal_position(partner_nl_vat.id, partner_be_vat.id), fp_be_nat ) # Case : 3 # Billing (VAT/country) : BE/BE # Delivery (VAT/country) : None/NL # Expected FP : Régime National self.assertEqual( self.env['account.fiscal.position'].get_fiscal_position(partner_be_vat.id, partner_nl_no_vat.id), fp_be_nat ) # Case : 4 # Billing (VAT/country) : NL/NL # Delivery (VAT/country) : NL/NL # Expected FP : Régime Intra-Communautaire self.assertEqual( self.env['account.fiscal.position'].get_fiscal_position(partner_nl_vat.id, partner_nl_vat.id), fp_eu_intra ) # Case : 5 # Billing (VAT/country) : None/NL # Delivery (VAT/country) : None/NL # Expected FP : EU privé self.assertEqual( self.env['account.fiscal.position'].get_fiscal_position(partner_nl_no_vat.id, partner_nl_no_vat.id), fp_eu_priv ) # Case : 6 # Billing (VAT/country) : None/US # Delivery (VAT/country) : None/US # Expected FP : Régime Extra-Communautaire self.assertEqual( self.env['account.fiscal.position'].get_fiscal_position(partner_us_no_vat.id, partner_us_no_vat.id), fp_eu_extra )
42.330855
11,387
26,328
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo.tests.common import Form, TransactionCase from odoo import fields, api, SUPERUSER_ID from odoo.exceptions import ValidationError, UserError from odoo.tools import mute_logger from dateutil.relativedelta import relativedelta from freezegun import freeze_time from functools import reduce import json import psycopg2 class TestSequenceMixinCommon(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.test_move = cls.create_move() @classmethod def create_move(cls, date=None, journal=None, name=None, post=False): move = cls.env['account.move'].create({ 'move_type': 'entry', 'date': date or '2016-01-01', 'line_ids': [ (0, None, { 'name': 'line', 'account_id': cls.company_data['default_account_revenue'].id, }), ] }) if journal: move.name = False move.journal_id = journal if name: move.name = name if post: move.action_post() return move @tagged('post_install', '-at_install') class TestSequenceMixin(TestSequenceMixinCommon): def test_sequence_change_date(self): """Change the sequence when we change the date iff it has never been posted.""" # Check setup self.assertEqual(self.test_move.state, 'draft') self.assertEqual(self.test_move.name, 'MISC/2016/01/0001') self.assertEqual(fields.Date.to_string(self.test_move.date), '2016-01-01') # Never posetd, the number must change if we change the date self.test_move.date = '2020-02-02' self.assertEqual(self.test_move.name, 'MISC/2020/02/0001') # We don't recompute user's input when posting self.test_move.name = 'MyMISC/2020/0000001' self.test_move.action_post() self.assertEqual(self.test_move.name, 'MyMISC/2020/0000001') # Has been posted, and it doesn't change anymore self.test_move.button_draft() self.test_move.date = '2020-01-02' self.test_move.action_post() self.assertEqual(self.test_move.name, 'MyMISC/2020/0000001') def test_sequence_draft_change_date(self): # When a draft entry is added to an empty period, it should get a name. # When a draft entry with a name is moved to a period already having entries, its name should be reset to '/'. new_move = self.test_move.copy({'date': '2016-02-01'}) new_multiple_move_1 = self.test_move.copy({'date': '2016-03-01'}) new_multiple_move_2 = self.test_move.copy({'date': '2016-04-01'}) new_moves = new_multiple_move_1 + new_multiple_move_2 # Empty period, so a name should be set self.assertEqual(new_move.name, 'MISC/2016/02/0001') self.assertEqual(new_multiple_move_1.name, 'MISC/2016/03/0001') self.assertEqual(new_multiple_move_2.name, 'MISC/2016/04/0001') # Move to an existing period with another move in it new_move.date = fields.Date.to_date('2016-01-10') new_moves.date = fields.Date.to_date('2016-01-15') # Not an empty period, so names should be reset to '/' (draft) self.assertEqual(new_move.name, '/') self.assertEqual(new_multiple_move_1.name, '/') self.assertEqual(new_multiple_move_2.name, '/') # Move back to a period with no moves in it new_move.date = fields.Date.to_date('2016-02-01') new_moves.date = fields.Date.to_date('2016-03-01') # All moves in the previously empty periods should be given a name instead of `/` self.assertEqual(new_move.name, 'MISC/2016/02/0001') self.assertEqual(new_multiple_move_1.name, 'MISC/2016/03/0001') # Since this is the second one in the same period, it should remain `/` self.assertEqual(new_multiple_move_2.name, '/') # Move both moves back to different periods, both with already moves in it. new_multiple_move_1.date = fields.Date.to_date('2016-01-10') new_multiple_move_2.date = fields.Date.to_date('2016-02-10') # Moves are not in empty periods, so names should be set to '/' (draft) self.assertEqual(new_multiple_move_1.name, '/') self.assertEqual(new_multiple_move_2.name, '/') # Change the journal of the last two moves (empty) journal = self.env['account.journal'].create({ 'name': 'awesome journal', 'type': 'general', 'code': 'AJ', }) new_moves.journal_id = journal # Both moves should be assigned a name, since no moves are in the journal and they are in different periods. self.assertEqual(new_multiple_move_1.name, 'AJ/2016/01/0001') self.assertEqual(new_multiple_move_2.name, 'AJ/2016/02/0001') # When the date is removed in the form view, the name should not recompute with Form(new_multiple_move_1) as move_form: move_form.date = False self.assertEqual(new_multiple_move_1.name, 'AJ/2016/01/0001') move_form.date = fields.Date.to_date('2016-01-10') def test_journal_sequence(self): self.assertEqual(self.test_move.name, 'MISC/2016/01/0001') self.test_move.action_post() self.assertEqual(self.test_move.name, 'MISC/2016/01/0001') copy1 = self.create_move(date=self.test_move.date) self.assertEqual(copy1.name, '/') copy1.action_post() self.assertEqual(copy1.name, 'MISC/2016/01/0002') copy2 = self.create_move(date=self.test_move.date) new_journal = self.test_move.journal_id.copy() new_journal.code = "MISC2" copy2.journal_id = new_journal self.assertEqual(copy2.name, 'MISC2/2016/01/0001') with Form(copy2) as move_form: # It is editable in the form with mute_logger('odoo.tests.common.onchange'): move_form.name = 'MyMISC/2016/0001' self.assertIn( 'The sequence will restart at 1 at the start of every year', move_form._perform_onchange(['name'])['warning']['message'], ) move_form.journal_id = self.test_move.journal_id self.assertEqual(move_form.name, '/') move_form.journal_id = new_journal self.assertEqual(move_form.name, 'MISC2/2016/01/0001') with mute_logger('odoo.tests.common.onchange'): move_form.name = 'MyMISC/2016/0001' self.assertIn( 'The sequence will restart at 1 at the start of every year', move_form._perform_onchange(['name'])['warning']['message'], ) copy2.action_post() self.assertEqual(copy2.name, 'MyMISC/2016/0001') copy3 = self.create_move(date=copy2.date, journal=new_journal) self.assertEqual(copy3.name, '/') with self.assertRaises(AssertionError): with Form(copy2) as move_form: # It is not editable in the form move_form.name = 'MyMISC/2016/0002' copy3.action_post() self.assertEqual(copy3.name, 'MyMISC/2016/0002') copy3.name = 'MISC2/2016/00002' copy4 = self.create_move(date=copy2.date, journal=new_journal) copy4.action_post() self.assertEqual(copy4.name, 'MISC2/2016/00003') copy5 = self.create_move(date=copy2.date, journal=new_journal) copy5.date = '2021-02-02' copy5.action_post() self.assertEqual(copy5.name, 'MISC2/2021/00001') copy5.name = 'N\'importe quoi?' copy6 = self.create_move(date=copy5.date, journal=new_journal) copy6.action_post() self.assertEqual(copy6.name, 'N\'importe quoi?1') def test_journal_sequence_format(self): """Test different format of sequences and what it becomes on another period""" sequences = [ ('JRNL/2016/00001', 'JRNL/2016/00002', 'JRNL/2016/00003', 'JRNL/2017/00001'), ('1234567', '1234568', '1234569', '1234570'), ('20190910', '20190911', '20190912', '20190913'), ('2016-0910', '2016-0911', '2016-0912', '2017-0001'), ('201603-10', '201603-11', '201604-01', '201703-01'), ('16-03-10', '16-03-11', '16-04-01', '17-03-01'), ('2016-10', '2016-11', '2016-12', '2017-01'), ('045-001-000002', '045-001-000003', '045-001-000004', '045-001-000005'), ('JRNL/2016/00001suffix', 'JRNL/2016/00002suffix', 'JRNL/2016/00003suffix', 'JRNL/2017/00001suffix'), ] init_move = self.create_move(date='2016-03-12') next_move = self.create_move(date='2016-03-12') next_move_month = self.create_move(date='2016-04-12') next_move_year = self.create_move(date='2017-03-12') next_moves = (next_move + next_move_month + next_move_year) next_moves.action_post() for sequence_init, sequence_next, sequence_next_month, sequence_next_year in sequences: init_move.name = sequence_init next_moves.name = False next_moves._compute_name() self.assertEqual( [next_move.name, next_move_month.name, next_move_year.name], [sequence_next, sequence_next_month, sequence_next_year], ) def test_journal_next_sequence(self): """Sequences behave correctly even when there is not enough padding.""" prefix = "TEST_ORDER/2016/" self.test_move.name = f"{prefix}1" for c in range(2, 25): copy = self.create_move(date=self.test_move.date) copy.name = "/" copy.action_post() self.assertEqual(copy.name, f"{prefix}{c}") def test_journal_sequence_multiple_type(self): """Domain is computed accordingly to different types.""" entry, entry2, invoice, invoice2, refund, refund2 = ( self.create_move(date='2016-01-01') for i in range(6) ) (invoice + invoice2 + refund + refund2).write({ 'journal_id': self.company_data['default_journal_sale'].id, 'partner_id': 1, 'invoice_date': '2016-01-01', }) (invoice + invoice2).move_type = 'out_invoice' (refund + refund2).move_type = 'out_refund' all_moves = (entry + entry2 + invoice + invoice2 + refund + refund2) all_moves.name = False all_moves.action_post() self.assertEqual(entry.name, 'MISC/2016/01/0002') self.assertEqual(entry2.name, 'MISC/2016/01/0003') self.assertEqual(invoice.name, 'INV/2016/00001') self.assertEqual(invoice2.name, 'INV/2016/00002') self.assertEqual(refund.name, 'RINV/2016/00001') self.assertEqual(refund2.name, 'RINV/2016/00002') def test_journal_sequence_groupby_compute(self): """The grouping optimization is correctly done.""" # Setup two journals with a sequence that resets yearly journals = self.env['account.journal'].create([{ 'name': f'Journal{i}', 'code': f'J{i}', 'type': 'general', } for i in range(2)]) account = self.env['account.account'].search([], limit=1) moves = self.env['account.move'].create([{ 'journal_id': journals[i].id, 'line_ids': [(0, 0, {'account_id': account.id, 'name': 'line'})], 'date': '2010-01-01', } for i in range(2)])._post() for i in range(2): moves[i].name = f'J{i}/2010/00001' # Check that the moves are correctly batched moves = self.env['account.move'].create([{ 'journal_id': journals[journal_index].id, 'line_ids': [(0, 0, {'account_id': account.id, 'name': 'line'})], 'date': f'2010-{month}-01', } for journal_index, month in [(1, 1), (0, 1), (1, 2), (1, 1)]])._post() self.assertEqual( moves.mapped('name'), ['J1/2010/00002', 'J0/2010/00002', 'J1/2010/00004', 'J1/2010/00003'], ) journals[0].code = 'OLD' journals.flush() journal_same_code = self.env['account.journal'].create([{ 'name': 'Journal0', 'code': 'J0', 'type': 'general', }]) moves = ( self.create_move(date='2010-01-01', journal=journal_same_code, name='J0/2010/00001') + self.create_move(date='2010-01-01', journal=journal_same_code) + self.create_move(date='2010-01-01', journal=journal_same_code) + self.create_move(date='2010-01-01', journal=journals[0]) )._post() self.assertEqual( moves.mapped('name'), ['J0/2010/00001', 'J0/2010/00002', 'J0/2010/00003', 'J0/2010/00003'], ) def test_journal_override_sequence_regex(self): """There is a possibility to override the regex and change the order of the paramters.""" self.create_move(date='2020-01-01', name='00000876-G 0002/2020') next_move = self.create_move(date='2020-01-01') next_move.action_post() self.assertEqual(next_move.name, '00000876-G 0002/2021') # Wait, I didn't want this! next_move.button_draft() next_move.name = False next_move.journal_id.sequence_override_regex = r'^(?P<seq>\d*)(?P<suffix1>.*?)(?P<year>(\d{4})?)(?P<suffix2>)$' next_move.action_post() self.assertEqual(next_move.name, '00000877-G 0002/2020') # Pfew, better! next_move = self.create_move(date='2020-01-01') next_move.action_post() self.assertEqual(next_move.name, '00000878-G 0002/2020') next_move = self.create_move(date='2017-05-02') next_move.action_post() self.assertEqual(next_move.name, '00000001-G 0002/2017') def test_journal_sequence_ordering(self): """Entries are correctly sorted when posting multiple at once.""" self.test_move.name = 'XMISC/2016/00001' copies = reduce((lambda x, y: x+y), [ self.create_move(date=self.test_move.date) for i in range(6) ]) copies[0].date = '2019-03-05' copies[1].date = '2019-03-06' copies[2].date = '2019-03-07' copies[3].date = '2019-03-04' copies[4].date = '2019-03-05' copies[5].date = '2019-03-05' # that entry is actualy the first one of the period, so it already has a name # set it to '/' so that it is recomputed at post to be ordered correctly. copies[0].name = '/' copies.action_post() # Ordered by date self.assertEqual(copies[0].name, 'XMISC/2019/00002') self.assertEqual(copies[1].name, 'XMISC/2019/00005') self.assertEqual(copies[2].name, 'XMISC/2019/00006') self.assertEqual(copies[3].name, 'XMISC/2019/00001') self.assertEqual(copies[4].name, 'XMISC/2019/00003') self.assertEqual(copies[5].name, 'XMISC/2019/00004') # Can't have twice the same name with self.assertRaises(ValidationError): copies[0].name = 'XMISC/2019/00001' # Lets remove the order by date copies[0].name = 'XMISC/2019/10001' copies[1].name = 'XMISC/2019/10002' copies[2].name = 'XMISC/2019/10003' copies[3].name = 'XMISC/2019/10004' copies[4].name = 'XMISC/2019/10005' copies[5].name = 'XMISC/2019/10006' copies[4].button_draft() copies[4].with_context(force_delete=True).unlink() copies[5].button_draft() wizard = Form(self.env['account.resequence.wizard'].with_context( active_ids=set(copies.ids) - set(copies[4].ids), active_model='account.move'), ) new_values = json.loads(wizard.new_values) self.assertEqual(new_values[str(copies[0].id)]['new_by_date'], 'XMISC/2019/10002') self.assertEqual(new_values[str(copies[0].id)]['new_by_name'], 'XMISC/2019/10001') self.assertEqual(new_values[str(copies[1].id)]['new_by_date'], 'XMISC/2019/10004') self.assertEqual(new_values[str(copies[1].id)]['new_by_name'], 'XMISC/2019/10002') self.assertEqual(new_values[str(copies[2].id)]['new_by_date'], 'XMISC/2019/10005') self.assertEqual(new_values[str(copies[2].id)]['new_by_name'], 'XMISC/2019/10003') self.assertEqual(new_values[str(copies[3].id)]['new_by_date'], 'XMISC/2019/10001') self.assertEqual(new_values[str(copies[3].id)]['new_by_name'], 'XMISC/2019/10004') self.assertEqual(new_values[str(copies[5].id)]['new_by_date'], 'XMISC/2019/10003') self.assertEqual(new_values[str(copies[5].id)]['new_by_name'], 'XMISC/2019/10005') wizard.save().resequence() self.assertEqual(copies[3].state, 'posted') self.assertEqual(copies[5].name, 'XMISC/2019/10005') self.assertEqual(copies[5].state, 'draft') def test_sequence_get_more_specific(self): """There is the ability to change the format (i.e. from yearly to montlhy).""" def test_date(date, name): test = self.create_move(date=date) test.action_post() self.assertEqual(test.name, name) def set_sequence(date, name): return self.create_move(date=date, name=name)._post() # Start with a continuous sequence self.test_move.name = 'MISC/00001' # Change the prefix to reset every year starting in 2017 new_year = set_sequence(self.test_move.date + relativedelta(years=1), 'MISC/2017/00001') # Change the prefix to reset every month starting in February 2017 new_month = set_sequence(new_year.date + relativedelta(months=1), 'MISC/2017/02/00001') test_date(self.test_move.date, 'MISC/00002') # Keep the old prefix in 2016 test_date(new_year.date, 'MISC/2017/00002') # Keep the new prefix in 2017 test_date(new_month.date, 'MISC/2017/02/00002') # Keep the new prefix in February 2017 # Change the prefix to never reset (again) year starting in 2018 (Please don't do that) reset_never = set_sequence(self.test_move.date + relativedelta(years=2), 'MISC/00100') test_date(reset_never.date, 'MISC/00101') # Keep the new prefix in 2018 def test_resequence_clash(self): """Resequence doesn't clash when it uses a name set in the same batch but that will be overriden later.""" moves = self.env['account.move'] for i in range(3): moves += self.create_move(name=str(i)) moves.action_post() mistake = moves[1] mistake.button_draft() mistake.posted_before = False mistake.with_context(force_delete=True).unlink() moves -= mistake self.env['account.resequence.wizard'].create({ 'move_ids': moves.ids, 'first_name': '2', }).resequence() @freeze_time('2021-10-01 00:00:00') def test_change_journal_on_first_account_move(self): """Changing the journal on the first move is allowed""" journal = self.env['account.journal'].create({ 'name': 'awesome journal', 'type': 'general', 'code': 'AJ', }) move = self.env['account.move'].create({}) self.assertEqual(move.name, 'MISC/2021/10/0001') with Form(move) as move_form: move_form.journal_id = journal self.assertEqual(move.name, 'AJ/2021/10/0001') @tagged('post_install', '-at_install') class TestSequenceMixinDeletion(TestSequenceMixinCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) journal = cls.env['account.journal'].create({ 'name': 'Test sequences - deletion', 'code': 'SEQDEL', 'type': 'general', }) cls.move_1_1 = cls.create_move('2021-01-01', journal, name='TOTO/2021/01/0001', post=True) cls.move_1_2 = cls.create_move('2021-01-02', journal, post=True) cls.move_1_3 = cls.create_move('2021-01-03', journal, post=True) cls.move_2_1 = cls.create_move('2021-02-01', journal, post=True) cls.move_draft = cls.create_move('2021-02-02', journal, post=False) cls.move_2_2 = cls.create_move('2021-02-03', journal, post=True) cls.move_3_1 = cls.create_move('2021-02-10', journal, name='TURLUTUTU/21/02/001', post=True) def test_sequence_deletion_1(self): """The last element of a sequence chain should always be deletable if in draft state. Trying to delete another part of the chain shouldn't work. """ # A draft move without any name can always be deleted. self.move_draft.unlink() # The moves that are not at the end of their sequence chain cannot be deleted for move in (self.move_1_1, self.move_1_2, self.move_2_1): move.button_draft() with self.assertRaises(UserError): move.unlink() # The last element of each sequence chain should allow deletion. # Everything should be deletable if we follow this order (a bit randomized on purpose) for move in (self.move_1_3, self.move_1_2, self.move_3_1, self.move_2_2, self.move_2_1, self.move_1_1): move.button_draft() move.unlink() def test_sequence_deletion_2(self): """Can delete in batch.""" all_moves = (self.move_1_3 + self.move_1_2 + self.move_3_1 + self.move_2_2 + self.move_2_1 + self.move_1_1) all_moves.button_draft() all_moves.unlink() def test_sequence_deletion_3(self): """Cannot delete non sequential batches.""" all_moves = (self.move_1_3 + self.move_3_1 + self.move_2_2 + self.move_2_1 + self.move_1_1) all_moves.button_draft() with self.assertRaises(UserError): all_moves.unlink() def test_sequence_deletion_4(self): """Cannot delete batches not containing the last entry.""" all_moves = (self.move_1_2 + self.move_3_1 + self.move_2_2 + self.move_2_1 + self.move_1_1) all_moves.button_draft() with self.assertRaises(UserError): all_moves.unlink() @tagged('post_install', '-at_install') class TestSequenceMixinConcurrency(TransactionCase): def setUp(self): super().setUp() with self.env.registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) journal = env['account.journal'].create({ 'name': 'concurency_test', 'code': 'CT', 'type': 'general', }) account = env['account.account'].create({ 'code': 'CT', 'name': 'CT', 'user_type_id': env.ref('account.data_account_type_fixed_assets').id, }) moves = env['account.move'].create([{ 'journal_id': journal.id, 'date': fields.Date.from_string('2016-01-01'), 'line_ids': [(0, 0, {'name': 'name', 'account_id': account.id})] }] * 3) moves.name = '/' moves[0].action_post() self.assertEqual(moves.mapped('name'), ['CT/2016/01/0001', '/', '/']) env.cr.commit() self.data = { 'move_ids': moves.ids, 'account_id': account.id, 'journal_id': journal.id, 'envs': [ api.Environment(self.env.registry.cursor(), SUPERUSER_ID, {}), api.Environment(self.env.registry.cursor(), SUPERUSER_ID, {}), api.Environment(self.env.registry.cursor(), SUPERUSER_ID, {}), ], } self.addCleanup(self.cleanUp) def cleanUp(self): with self.env.registry.cursor() as cr: env = api.Environment(cr, SUPERUSER_ID, {}) moves = env['account.move'].browse(self.data['move_ids']) moves.button_draft() moves.posted_before = False moves.unlink() journal = env['account.journal'].browse(self.data['journal_id']) journal.unlink() account = env['account.account'].browse(self.data['account_id']) account.unlink() env.cr.commit() for env in self.data['envs']: env.cr.close() def test_sequence_concurency(self): """Computing the same name in concurent transactions is not allowed.""" env0, env1, env2 = self.data['envs'] # start the transactions here on cr1 to simulate concurency with cr2 env1.cr.execute('SELECT 1') # post in cr2 move = env2['account.move'].browse(self.data['move_ids'][1]) move.action_post() env2.cr.commit() # try to post in cr1, should fail because this transaction started before the post in cr2 move = env1['account.move'].browse(self.data['move_ids'][2]) with self.assertRaises(psycopg2.OperationalError), mute_logger('odoo.sql_db'): move.action_post() # check the values moves = env0['account.move'].browse(self.data['move_ids']) self.assertEqual(moves.mapped('name'), ['CT/2016/01/0001', 'CT/2016/01/0002', '/']) def test_sequence_concurency_no_useless_lock(self): """Do not lock needlessly when the sequence is not computed""" env0, env1, env2 = self.data['envs'] # start the transactions here on cr1 to simulate concurency with cr2 env1.cr.execute('SELECT 1') # get the last sequence in cr1 (for instance opening a form view) move = env2['account.move'].browse(self.data['move_ids'][1]) move.highest_name env2.cr.commit() # post in cr1, should work even though cr2 read values move = env1['account.move'].browse(self.data['move_ids'][2]) move.action_post() env1.cr.commit() # check the values moves = env0['account.move'].browse(self.data['move_ids']) self.assertEqual(moves.mapped('name'), ['CT/2016/01/0001', '/', 'CT/2016/01/0002'])
43.88
26,328
32,662
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields from odoo.tests.common import TransactionCase, HttpCase, tagged, Form import time import base64 from lxml import etree @tagged('post_install', '-at_install') class AccountTestInvoicingCommon(TransactionCase): @classmethod def safe_copy(cls, record): return record and record.copy() @classmethod def copy_account(cls, account, default=None): suffix_nb = 1 while True: new_code = '%s (%s)' % (account.code, suffix_nb) if account.search_count([('company_id', '=', account.company_id.id), ('code', '=', new_code)]): suffix_nb += 1 else: return account.copy(default={**(default or {}), 'code': new_code}) @classmethod def setUpClass(cls, chart_template_ref=None): super(AccountTestInvoicingCommon, cls).setUpClass() assert 'post_install' in cls.test_tags, 'This test requires a CoA to be installed, it should be tagged "post_install"' if chart_template_ref: chart_template = cls.env.ref(chart_template_ref) else: chart_template = cls.env.ref('l10n_generic_coa.configurable_chart_template', raise_if_not_found=False) if not chart_template: cls.tearDownClass() # skipTest raises exception cls.skipTest(cls, "Accounting Tests skipped because the user's company has no chart of accounts.") # Create user. user = cls.env['res.users'].create({ 'name': 'Because I am accountman!', 'login': 'accountman', 'password': 'accountman', 'groups_id': [(6, 0, cls.env.user.groups_id.ids), (4, cls.env.ref('account.group_account_user').id)], }) user.partner_id.email = 'accountman@test.com' # Shadow the current environment/cursor with one having the report user. # This is mandatory to test access rights. cls.env = cls.env(user=user) cls.cr = cls.env.cr cls.company_data_2 = cls.setup_company_data('company_2_data', chart_template=chart_template) cls.company_data = cls.setup_company_data('company_1_data', chart_template=chart_template) user.write({ 'company_ids': [(6, 0, (cls.company_data['company'] + cls.company_data_2['company']).ids)], 'company_id': cls.company_data['company'].id, }) cls.currency_data = cls.setup_multi_currency_data() # ==== Taxes ==== cls.tax_sale_a = cls.company_data['default_tax_sale'] cls.tax_sale_b = cls.safe_copy(cls.company_data['default_tax_sale']) cls.tax_purchase_a = cls.company_data['default_tax_purchase'] cls.tax_purchase_b = cls.safe_copy(cls.company_data['default_tax_purchase']) cls.tax_armageddon = cls.setup_armageddon_tax('complex_tax', cls.company_data) # ==== Products ==== cls.product_a = cls.env['product.product'].create({ 'name': 'product_a', 'uom_id': cls.env.ref('uom.product_uom_unit').id, 'lst_price': 1000.0, 'standard_price': 800.0, 'property_account_income_id': cls.company_data['default_account_revenue'].id, 'property_account_expense_id': cls.company_data['default_account_expense'].id, 'taxes_id': [(6, 0, cls.tax_sale_a.ids)], 'supplier_taxes_id': [(6, 0, cls.tax_purchase_a.ids)], }) cls.product_b = cls.env['product.product'].create({ 'name': 'product_b', 'uom_id': cls.env.ref('uom.product_uom_dozen').id, 'lst_price': 200.0, 'standard_price': 160.0, 'property_account_income_id': cls.copy_account(cls.company_data['default_account_revenue']).id, 'property_account_expense_id': cls.copy_account(cls.company_data['default_account_expense']).id, 'taxes_id': [(6, 0, (cls.tax_sale_a + cls.tax_sale_b).ids)], 'supplier_taxes_id': [(6, 0, (cls.tax_purchase_a + cls.tax_purchase_b).ids)], }) # ==== Fiscal positions ==== cls.fiscal_pos_a = cls.env['account.fiscal.position'].create({ 'name': 'fiscal_pos_a', 'tax_ids': ([(0, None, { 'tax_src_id': cls.tax_sale_a.id, 'tax_dest_id': cls.tax_sale_b.id, })] if cls.tax_sale_b else []) + ([(0, None, { 'tax_src_id': cls.tax_purchase_a.id, 'tax_dest_id': cls.tax_purchase_b.id, })] if cls.tax_purchase_b else []), 'account_ids': [ (0, None, { 'account_src_id': cls.product_a.property_account_income_id.id, 'account_dest_id': cls.product_b.property_account_income_id.id, }), (0, None, { 'account_src_id': cls.product_a.property_account_expense_id.id, 'account_dest_id': cls.product_b.property_account_expense_id.id, }), ], }) # ==== Payment terms ==== cls.pay_terms_a = cls.env.ref('account.account_payment_term_immediate') cls.pay_terms_b = cls.env['account.payment.term'].create({ 'name': '30% Advance End of Following Month', 'note': 'Payment terms: 30% Advance End of Following Month', 'line_ids': [ (0, 0, { 'value': 'percent', 'value_amount': 30.0, 'sequence': 400, 'days': 0, 'option': 'day_after_invoice_date', }), (0, 0, { 'value': 'balance', 'value_amount': 0.0, 'sequence': 500, 'days': 31, 'option': 'day_following_month', }), ], }) # ==== Partners ==== cls.partner_a = cls.env['res.partner'].create({ 'name': 'partner_a', 'property_payment_term_id': cls.pay_terms_a.id, 'property_supplier_payment_term_id': cls.pay_terms_a.id, 'property_account_receivable_id': cls.company_data['default_account_receivable'].id, 'property_account_payable_id': cls.company_data['default_account_payable'].id, 'company_id': False, }) cls.partner_b = cls.env['res.partner'].create({ 'name': 'partner_b', 'property_payment_term_id': cls.pay_terms_b.id, 'property_supplier_payment_term_id': cls.pay_terms_b.id, 'property_account_position_id': cls.fiscal_pos_a.id, 'property_account_receivable_id': cls.company_data['default_account_receivable'].copy().id, 'property_account_payable_id': cls.company_data['default_account_payable'].copy().id, 'company_id': False, }) # ==== Cash rounding ==== cls.cash_rounding_a = cls.env['account.cash.rounding'].create({ 'name': 'add_invoice_line', 'rounding': 0.05, 'strategy': 'add_invoice_line', 'profit_account_id': cls.company_data['default_account_revenue'].copy().id, 'loss_account_id': cls.company_data['default_account_expense'].copy().id, 'rounding_method': 'UP', }) cls.cash_rounding_b = cls.env['account.cash.rounding'].create({ 'name': 'biggest_tax', 'rounding': 0.05, 'strategy': 'biggest_tax', 'rounding_method': 'DOWN', }) # ==== Payment methods ==== bank_journal = cls.company_data['default_journal_bank'] cls.inbound_payment_method_line = bank_journal.inbound_payment_method_line_ids[0] cls.outbound_payment_method_line = bank_journal.outbound_payment_method_line_ids[0] @classmethod def setup_company_data(cls, company_name, chart_template=None, **kwargs): ''' Create a new company having the name passed as parameter. A chart of accounts will be installed to this company: the same as the current company one. The current user will get access to this company. :param chart_template: The chart template to be used on this new company. :param company_name: The name of the company. :return: A dictionary will be returned containing all relevant accounting data for testing. ''' def search_account(company, chart_template, field_name, domain): template_code = chart_template[field_name].code domain = [('company_id', '=', company.id)] + domain account = None if template_code: account = cls.env['account.account'].search(domain + [('code', '=like', template_code + '%')], limit=1) if not account: account = cls.env['account.account'].search(domain, limit=1) return account chart_template = chart_template or cls.env.company.chart_template_id company = cls.env['res.company'].create({ 'name': company_name, **kwargs, }) cls.env.user.company_ids |= company chart_template.try_loading(company=company, install_demo=False) # The currency could be different after the installation of the chart template. if kwargs.get('currency_id'): company.write({'currency_id': kwargs['currency_id']}) return { 'company': company, 'currency': company.currency_id, 'default_account_revenue': cls.env['account.account'].search([ ('company_id', '=', company.id), ('user_type_id', '=', cls.env.ref('account.data_account_type_revenue').id) ], limit=1), 'default_account_expense': cls.env['account.account'].search([ ('company_id', '=', company.id), ('user_type_id', '=', cls.env.ref('account.data_account_type_expenses').id) ], limit=1), 'default_account_receivable': search_account(company, chart_template, 'property_account_receivable_id', [ ('user_type_id.type', '=', 'receivable') ]), 'default_account_payable': cls.env['account.account'].search([ ('company_id', '=', company.id), ('user_type_id.type', '=', 'payable') ], limit=1), 'default_account_assets': cls.env['account.account'].search([ ('company_id', '=', company.id), ('user_type_id', '=', cls.env.ref('account.data_account_type_current_assets').id) ], limit=1), 'default_account_tax_sale': company.account_sale_tax_id.mapped('invoice_repartition_line_ids.account_id'), 'default_account_tax_purchase': company.account_purchase_tax_id.mapped('invoice_repartition_line_ids.account_id'), 'default_journal_misc': cls.env['account.journal'].search([ ('company_id', '=', company.id), ('type', '=', 'general') ], limit=1), 'default_journal_sale': cls.env['account.journal'].search([ ('company_id', '=', company.id), ('type', '=', 'sale') ], limit=1), 'default_journal_purchase': cls.env['account.journal'].search([ ('company_id', '=', company.id), ('type', '=', 'purchase') ], limit=1), 'default_journal_bank': cls.env['account.journal'].search([ ('company_id', '=', company.id), ('type', '=', 'bank') ], limit=1), 'default_journal_cash': cls.env['account.journal'].search([ ('company_id', '=', company.id), ('type', '=', 'cash') ], limit=1), 'default_tax_sale': company.account_sale_tax_id, 'default_tax_purchase': company.account_purchase_tax_id, } @classmethod def setup_multi_currency_data(cls, default_values=None, rate2016=3.0, rate2017=2.0): default_values = default_values or {} foreign_currency = cls.env['res.currency'].create({ 'name': 'Gold Coin', 'symbol': '☺', 'rounding': 0.001, 'position': 'after', 'currency_unit_label': 'Gold', 'currency_subunit_label': 'Silver', **default_values, }) rate1 = cls.env['res.currency.rate'].create({ 'name': '2016-01-01', 'rate': rate2016, 'currency_id': foreign_currency.id, 'company_id': cls.env.company.id, }) rate2 = cls.env['res.currency.rate'].create({ 'name': '2017-01-01', 'rate': rate2017, 'currency_id': foreign_currency.id, 'company_id': cls.env.company.id, }) return { 'currency': foreign_currency, 'rates': rate1 + rate2, } @classmethod def setup_armageddon_tax(cls, tax_name, company_data): return cls.env['account.tax'].create({ 'name': '%s (group)' % tax_name, 'amount_type': 'group', 'amount': 0.0, 'country_id': company_data['company'].account_fiscal_country_id.id, 'children_tax_ids': [ (0, 0, { 'name': '%s (child 1)' % tax_name, 'amount_type': 'percent', 'amount': 20.0, 'country_id': company_data['company'].account_fiscal_country_id.id, 'price_include': True, 'include_base_amount': True, 'tax_exigibility': 'on_invoice', 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 40, 'repartition_type': 'tax', 'account_id': company_data['default_account_tax_sale'].id, }), (0, 0, { 'factor_percent': 60, 'repartition_type': 'tax', # /!\ No account set. }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 40, 'repartition_type': 'tax', 'account_id': company_data['default_account_tax_sale'].id, }), (0, 0, { 'factor_percent': 60, 'repartition_type': 'tax', # /!\ No account set. }), ], }), (0, 0, { 'name': '%s (child 2)' % tax_name, 'amount_type': 'percent', 'amount': 10.0, 'country_id': company_data['company'].account_fiscal_country_id.id, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': cls.safe_copy(company_data['default_account_tax_sale']).id, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': company_data['default_account_tax_sale'].id, }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': company_data['default_account_tax_sale'].id, }), ], }), ], }) @classmethod def init_invoice(cls, move_type, partner=None, invoice_date=None, post=False, products=None, amounts=None, taxes=None, company=False, currency=None): move_form = Form(cls.env['account.move'] \ .with_company(company or cls.env.company) \ .with_context(default_move_type=move_type, account_predictive_bills_disable_prediction=True)) move_form.invoice_date = invoice_date or fields.Date.from_string('2019-01-01') move_form.date = move_form.invoice_date move_form.partner_id = partner or cls.partner_a move_form.currency_id = currency if currency else cls.company_data['currency'] for product in (products or []): with move_form.invoice_line_ids.new() as line_form: line_form.product_id = product if taxes: line_form.tax_ids.clear() for tax in taxes: line_form.tax_ids.add(tax) for amount in (amounts or []): with move_form.invoice_line_ids.new() as line_form: line_form.name = "test line" # We use account_predictive_bills_disable_prediction context key so that # this doesn't trigger prediction in case enterprise (hence account_predictive_bills) is installed line_form.price_unit = amount if taxes: line_form.tax_ids.clear() for tax in taxes: line_form.tax_ids.add(tax) rslt = move_form.save() if post: rslt.action_post() return rslt def assertInvoiceValues(self, move, expected_lines_values, expected_move_values): def sort_lines(lines): return lines.sorted(lambda line: (line.exclude_from_invoice_tab, not bool(line.tax_line_id), line.name or '', line.balance)) self.assertRecordValues(sort_lines(move.line_ids.sorted()), expected_lines_values) self.assertRecordValues(sort_lines(move.invoice_line_ids.sorted()), expected_lines_values[:len(move.invoice_line_ids)]) self.assertRecordValues(move, [expected_move_values]) #################################################### # Xml Comparison #################################################### def _turn_node_as_dict_hierarchy(self, node): ''' Turn the node as a python dictionary to be compared later with another one. Allow to ignore the management of namespaces. :param node: A node inside an xml tree. :return: A python dictionary. ''' tag_split = node.tag.split('}') tag_wo_ns = tag_split[-1] attrib_wo_ns = {k: v for k, v in node.attrib.items() if '}' not in k} return { 'tag': tag_wo_ns, 'namespace': None if len(tag_split) < 2 else tag_split[0], 'text': (node.text or '').strip(), 'attrib': attrib_wo_ns, 'children': [self._turn_node_as_dict_hierarchy(child_node) for child_node in node.getchildren()], } def assertXmlTreeEqual(self, xml_tree, expected_xml_tree): ''' Compare two lxml.etree. :param xml_tree: The current tree. :param expected_xml_tree: The expected tree. ''' def assertNodeDictEqual(node_dict, expected_node_dict): ''' Compare nodes created by the `_turn_node_as_dict_hierarchy` method. :param node_dict: The node to compare with. :param expected_node_dict: The expected node. ''' # Check tag. self.assertEqual(node_dict['tag'], expected_node_dict['tag']) # Check attributes. node_dict_attrib = {k: '___ignore___' if expected_node_dict['attrib'].get(k) == '___ignore___' else v for k, v in node_dict['attrib'].items()} expected_node_dict_attrib = {k: v for k, v in expected_node_dict['attrib'].items() if v != '___remove___'} self.assertDictEqual( node_dict_attrib, expected_node_dict_attrib, "Element attributes are different for node %s" % node_dict['tag'], ) # Check text. if expected_node_dict['text'] != '___ignore___': self.assertEqual( node_dict['text'], expected_node_dict['text'], "Element text are different for node %s" % node_dict['tag'], ) # Check children. self.assertEqual( [child['tag'] for child in node_dict['children']], [child['tag'] for child in expected_node_dict['children']], "Number of children elements for node %s is different." % node_dict['tag'], ) for child_node_dict, expected_child_node_dict in zip(node_dict['children'], expected_node_dict['children']): assertNodeDictEqual(child_node_dict, expected_child_node_dict) assertNodeDictEqual( self._turn_node_as_dict_hierarchy(xml_tree), self._turn_node_as_dict_hierarchy(expected_xml_tree), ) def with_applied_xpath(self, xml_tree, xpath): ''' Applies the xpath to the xml_tree passed as parameter. :param xml_tree: An instance of etree. :param xpath: The xpath to apply as a string. :return: The resulting etree after applying the xpaths. ''' diff_xml_tree = etree.fromstring('<data>%s</data>' % xpath) return self.env['ir.ui.view'].apply_inheritance_specs(xml_tree, diff_xml_tree) def get_xml_tree_from_attachment(self, attachment): ''' Extract an instance of etree from an ir.attachment. :param attachment: An ir.attachment. :return: An instance of etree. ''' return etree.fromstring(base64.b64decode(attachment.with_context(bin_size=False).datas)) def get_xml_tree_from_string(self, xml_tree_str): ''' Convert the string passed as parameter to an instance of etree. :param xml_tree_str: A string representing an xml. :return: An instance of etree. ''' return etree.fromstring(xml_tree_str) @tagged('post_install', '-at_install') class AccountTestInvoicingHttpCommon(AccountTestInvoicingCommon, HttpCase): pass class TestAccountReconciliationCommon(AccountTestInvoicingCommon): """Tests for reconciliation (account.tax) Test used to check that when doing a sale or purchase invoice in a different currency, the result will be balanced. """ @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.company = cls.company_data['company'] cls.company.currency_id = cls.env.ref('base.EUR') cls.partner_agrolait = cls.env['res.partner'].create({ 'name': 'Deco Addict', 'is_company': True, 'country_id': cls.env.ref('base.us').id, }) cls.partner_agrolait_id = cls.partner_agrolait.id cls.currency_swiss_id = cls.env.ref("base.CHF").id cls.currency_usd_id = cls.env.ref("base.USD").id cls.currency_euro_id = cls.env.ref("base.EUR").id cls.account_rcv = cls.company_data['default_account_receivable'] cls.account_rsa = cls.company_data['default_account_payable'] cls.product = cls.env['product.product'].create({ 'name': 'Product Product 4', 'standard_price': 500.0, 'list_price': 750.0, 'type': 'consu', 'categ_id': cls.env.ref('product.product_category_all').id, }) cls.bank_journal_euro = cls.env['account.journal'].create({'name': 'Bank', 'type': 'bank', 'code': 'BNK67'}) cls.account_euro = cls.bank_journal_euro.default_account_id cls.bank_journal_usd = cls.env['account.journal'].create({'name': 'Bank US', 'type': 'bank', 'code': 'BNK68', 'currency_id': cls.currency_usd_id}) cls.account_usd = cls.bank_journal_usd.default_account_id cls.fx_journal = cls.company.currency_exchange_journal_id cls.diff_income_account = cls.company.income_currency_exchange_account_id cls.diff_expense_account = cls.company.expense_currency_exchange_account_id cls.expense_account = cls.company_data['default_account_expense'] # cash basis intermediary account cls.tax_waiting_account = cls.env['account.account'].create({ 'name': 'TAX_WAIT', 'code': 'TWAIT', 'user_type_id': cls.env.ref('account.data_account_type_current_liabilities').id, 'reconcile': True, 'company_id': cls.company.id, }) # cash basis final account cls.tax_final_account = cls.env['account.account'].create({ 'name': 'TAX_TO_DEDUCT', 'code': 'TDEDUCT', 'user_type_id': cls.env.ref('account.data_account_type_current_assets').id, 'company_id': cls.company.id, }) cls.tax_base_amount_account = cls.env['account.account'].create({ 'name': 'TAX_BASE', 'code': 'TBASE', 'user_type_id': cls.env.ref('account.data_account_type_current_assets').id, 'company_id': cls.company.id, }) cls.company.account_cash_basis_base_account_id = cls.tax_base_amount_account.id # Journals cls.purchase_journal = cls.company_data['default_journal_purchase'] cls.cash_basis_journal = cls.env['account.journal'].create({ 'name': 'Test CABA', 'code': 'tCABA', 'type': 'general', }) cls.general_journal = cls.company_data['default_journal_misc'] # Tax Cash Basis cls.tax_cash_basis = cls.env['account.tax'].create({ 'name': 'cash basis 20%', 'type_tax_use': 'purchase', 'company_id': cls.company.id, 'country_id': cls.company.account_fiscal_country_id.id, 'amount': 20, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': cls.tax_waiting_account.id, 'invoice_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0,0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_final_account.id, }), ], 'refund_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', }), (0,0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': cls.tax_final_account.id, }), ], }) cls.env['res.currency.rate'].create([ { 'currency_id': cls.env.ref('base.EUR').id, 'name': '2010-01-02', 'rate': 1.0, }, { 'currency_id': cls.env.ref('base.USD').id, 'name': '2010-01-02', 'rate': 1.2834, }, { 'currency_id': cls.env.ref('base.USD').id, 'name': time.strftime('%Y-06-05'), 'rate': 1.5289, } ]) def _create_invoice(self, move_type='out_invoice', invoice_amount=50, currency_id=None, partner_id=None, date_invoice=None, payment_term_id=False, auto_validate=False): date_invoice = date_invoice or time.strftime('%Y') + '-07-01' invoice_vals = { 'move_type': move_type, 'partner_id': partner_id or self.partner_agrolait_id, 'invoice_date': date_invoice, 'date': date_invoice, 'invoice_line_ids': [(0, 0, { 'name': 'product that cost %s' % invoice_amount, 'quantity': 1, 'price_unit': invoice_amount, 'tax_ids': [(6, 0, [])], })] } if payment_term_id: invoice_vals['invoice_payment_term_id'] = payment_term_id if currency_id: invoice_vals['currency_id'] = currency_id invoice = self.env['account.move'].with_context(default_move_type=move_type).create(invoice_vals) if auto_validate: invoice.action_post() return invoice def create_invoice(self, move_type='out_invoice', invoice_amount=50, currency_id=None): return self._create_invoice(move_type=move_type, invoice_amount=invoice_amount, currency_id=currency_id, auto_validate=True) def create_invoice_partner(self, move_type='out_invoice', invoice_amount=50, currency_id=None, partner_id=False, payment_term_id=False): return self._create_invoice( move_type=move_type, invoice_amount=invoice_amount, currency_id=currency_id, partner_id=partner_id, payment_term_id=payment_term_id, auto_validate=True ) def make_payment(self, invoice_record, bank_journal, amount=0.0, amount_currency=0.0, currency_id=None, reconcile_param=None): reconcile_param = reconcile_param or [] bank_stmt = self.env['account.bank.statement'].create({ 'journal_id': bank_journal.id, 'date': time.strftime('%Y') + '-07-15', 'name': 'payment' + invoice_record.name, 'line_ids': [(0, 0, { 'payment_ref': 'payment', 'partner_id': self.partner_agrolait_id, 'amount': amount, 'amount_currency': amount_currency, 'foreign_currency_id': currency_id, })], }) bank_stmt.button_post() bank_stmt.line_ids[0].reconcile(reconcile_param) return bank_stmt def make_customer_and_supplier_flows(self, invoice_currency_id, invoice_amount, bank_journal, amount, amount_currency, transaction_currency_id): #we create an invoice in given invoice_currency invoice_record = self.create_invoice(move_type='out_invoice', invoice_amount=invoice_amount, currency_id=invoice_currency_id) #we encode a payment on it, on the given bank_journal with amount, amount_currency and transaction_currency given line = invoice_record.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) bank_stmt = self.make_payment(invoice_record, bank_journal, amount=amount, amount_currency=amount_currency, currency_id=transaction_currency_id, reconcile_param=[{'id': line.id}]) customer_move_lines = bank_stmt.line_ids.line_ids #we create a supplier bill in given invoice_currency invoice_record = self.create_invoice(move_type='in_invoice', invoice_amount=invoice_amount, currency_id=invoice_currency_id) #we encode a payment on it, on the given bank_journal with amount, amount_currency and transaction_currency given line = invoice_record.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) bank_stmt = self.make_payment(invoice_record, bank_journal, amount=-amount, amount_currency=-amount_currency, currency_id=transaction_currency_id, reconcile_param=[{'id': line.id}]) supplier_move_lines = bank_stmt.line_ids.line_ids return customer_move_lines, supplier_move_lines
45.550907
32,660
2,464
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo.exceptions import UserError @tagged('post_install', '-at_install') class TestAccountAnalyticAccount(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.env.user.write({ 'groups_id': [ (4, cls.env.ref('analytic.group_analytic_accounting').id), (4, cls.env.ref('analytic.group_analytic_tags').id), ], }) # By default, tests are run with the current user set on the first company. cls.env.user.company_id = cls.company_data['company'] cls.test_analytic_account = cls.env['account.analytic.account'].create({'name': 'test_analytic_account'}) cls.test_analytic_tag = cls.env['account.analytic.tag'].create({'name': 'test_analytic_tag'}) def test_changing_analytic_company(self): ''' Ensure you can't change the company of an account.analytic.account if there are some journal entries ''' self.env['account.move'].create({ 'move_type': 'entry', 'date': '2019-01-01', 'line_ids': [ (0, 0, { 'name': 'line_debit', 'account_id': self.company_data['default_account_revenue'].id, 'analytic_account_id': self.test_analytic_account.id, 'analytic_tag_ids': [(6, 0, self.test_analytic_tag.ids)], }), (0, 0, { 'name': 'line_credit', 'account_id': self.company_data['default_account_revenue'].id, }), ], }) # Set a different company on the analytic account. with self.assertRaises(UserError), self.cr.savepoint(): self.test_analytic_account.company_id = self.company_data_2['company'] # Making the analytic account not company dependent is allowed. self.test_analytic_account.company_id = False # Set a different company on the analytic tag. with self.assertRaises(UserError), self.cr.savepoint(): self.test_analytic_tag.company_id = self.company_data_2['company'] # Making the analytic tag not company dependent is allowed. self.test_analytic_tag.company_id = False
41.762712
2,464
4,307
py
PYTHON
15.0
# -*- coding: utf-8 -*- import base64 import io from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.exceptions import UserError from odoo.tools import pdf from odoo.tests import tagged from odoo.tools import file_open from PyPDF2 import PdfFileReader, PdfFileWriter @tagged('post_install', '-at_install') class TestIrActionsReport(AccountTestInvoicingCommon): def setUp(self): super().setUp() self.file = file_open('base/tests/minimal.pdf', 'rb').read() self.minimal_reader_buffer = io.BytesIO(self.file) self.minimal_pdf_reader = pdf.OdooPdfFileReader(self.minimal_reader_buffer) def test_download_one_corrupted_pdf(self): """ PyPDF2 is not flawless. We can upload a PDF that can be previsualised but that cannot be merged by PyPDF2. In the case of "Print Original Bills", we want to be able to download the pdf from the list view. We test that, when selecting one record, it can be printed (downloaded) without error. """ attach_name = 'original_vendor_bill.pdf' in_invoice_1 = self.env['account.move'].create({ 'move_type': 'in_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01' }) self.env['ir.attachment'].create({ 'datas': base64.b64encode(self.file), 'name': attach_name, 'mimetype': 'application/pdf', 'res_model': 'account.move', 'res_id': in_invoice_1.id, }) test_record_report = self.env.ref('account.action_account_original_vendor_bill').with_context(force_report_rendering=True)._render_qweb_pdf(in_invoice_1.id) self.assertTrue(test_record_report, "The PDF should have been generated") def test_download_one_encrypted_pdf(self): """ Same as test_download_one_corrupted_pdf but for encrypted pdf with no password and set encryption type to 5 (not known by PyPDF2) """ attach_name = 'original_vendor_bill.pdf' # we need to encrypt the file with file_open('base/tests/minimal.pdf', 'rb') as pdf_file: pdf_reader = PdfFileReader(pdf_file) pdf_writer = PdfFileWriter() for page_num in range(pdf_reader.getNumPages()): pdf_writer.addPage(pdf_reader.getPage(page_num)) # Encrypt the PDF pdf_writer.encrypt('', use_128bit=True) # Get the binary output_buffer = io.BytesIO() pdf_writer.write(output_buffer) encrypted_file = output_buffer.getvalue() # we need to change the encryption value from 4 to 5 to simulate an encryption not used by PyPDF2 encrypt_start = encrypted_file.find(b'/Encrypt') encrypt_end = encrypted_file.find(b'>>', encrypt_start) encrypt_version = encrypted_file[encrypt_start : encrypt_end] encrypted_file = encrypted_file.replace(encrypt_version, encrypt_version.replace(b'4', b'5')) in_invoice_1 = self.env['account.move'].create({ 'move_type': 'in_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01' }) self.env['ir.attachment'].create({ 'datas': base64.b64encode(encrypted_file), 'name': attach_name, 'mimetype': 'application/pdf', 'res_model': 'account.move', 'res_id': in_invoice_1.id, }) test_record_report = self.env.ref('account.action_account_original_vendor_bill').with_context(force_report_rendering=True)._render_qweb_pdf(in_invoice_1.id) self.assertTrue(test_record_report, "The PDF should have been generated") in_invoice_2 = in_invoice_1.copy() self.env['ir.attachment'].create({ 'datas': base64.b64encode(self.file), 'name': attach_name, 'mimetype': 'application/pdf', 'res_model': 'account.move', 'res_id': in_invoice_2.id, }) # trying to merge with a corrupted attachment should not work with self.assertRaises(UserError): self.env.ref('account.action_account_original_vendor_bill').with_context(force_report_rendering=True)._render_qweb_pdf(res_ids=[in_invoice_1.id, in_invoice_2.id])
43.94898
4,307
80,583
py
PYTHON
15.0
# -*- coding: utf-8 -*- # pylint: disable=bad-whitespace from freezegun import freeze_time from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests.common import Form from odoo.tests import tagged from odoo import fields, Command from odoo.exceptions import UserError, ValidationError from collections import defaultdict @tagged('post_install', '-at_install') class TestAccountMoveInInvoiceOnchanges(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.invoice = cls.init_invoice('in_invoice', products=cls.product_a+cls.product_b) cls.product_line_vals_1 = { 'name': cls.product_a.name, 'product_id': cls.product_a.id, 'account_id': cls.product_a.property_account_expense_id.id, 'partner_id': cls.partner_a.id, 'product_uom_id': cls.product_a.uom_id.id, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 800.0, 'price_subtotal': 800.0, 'price_total': 920.0, 'tax_ids': cls.product_a.supplier_taxes_id.ids, 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 800.0, 'debit': 800.0, 'credit': 0.0, 'date_maturity': False, } cls.product_line_vals_2 = { 'name': cls.product_b.name, 'product_id': cls.product_b.id, 'account_id': cls.product_b.property_account_expense_id.id, 'partner_id': cls.partner_a.id, 'product_uom_id': cls.product_b.uom_id.id, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 160.0, 'price_subtotal': 160.0, 'price_total': 208.0, 'tax_ids': cls.product_b.supplier_taxes_id.ids, 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 160.0, 'debit': 160.0, 'credit': 0.0, 'date_maturity': False, } cls.tax_line_vals_1 = { 'name': cls.tax_purchase_a.name, 'product_id': False, 'account_id': cls.company_data['default_account_tax_purchase'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 144.0, 'price_subtotal': 144.0, 'price_total': 144.0, 'tax_ids': [], 'tax_line_id': cls.tax_purchase_a.id, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 144.0, 'debit': 144.0, 'credit': 0.0, 'date_maturity': False, } cls.tax_line_vals_2 = { 'name': cls.tax_purchase_b.name, 'product_id': False, 'account_id': cls.company_data['default_account_tax_purchase'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 24.0, 'price_subtotal': 24.0, 'price_total': 24.0, 'tax_ids': [], 'tax_line_id': cls.tax_purchase_b.id, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 24.0, 'debit': 24.0, 'credit': 0.0, 'date_maturity': False, } cls.term_line_vals_1 = { 'name': '', 'product_id': False, 'account_id': cls.company_data['default_account_payable'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -1128.0, 'price_subtotal': -1128.0, 'price_total': -1128.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -1128.0, 'debit': 0.0, 'credit': 1128.0, 'date_maturity': fields.Date.from_string('2019-01-01'), } cls.move_vals = { 'partner_id': cls.partner_a.id, 'currency_id': cls.company_data['currency'].id, 'journal_id': cls.company_data['default_journal_purchase'].id, 'date': fields.Date.from_string('2019-01-01'), 'fiscal_position_id': False, 'payment_reference': '', 'invoice_payment_term_id': cls.pay_terms_a.id, 'amount_untaxed': 960.0, 'amount_tax': 168.0, 'amount_total': 1128.0, } def setUp(self): super(TestAccountMoveInInvoiceOnchanges, self).setUp() self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) def test_in_invoice_onchange_invoice_date(self): for tax_date, invoice_date, accounting_date in [ ('2019-03-31', '2019-05-12', '2019-05-31'), ('2019-03-31', '2019-02-10', '2019-04-30'), ('2019-05-31', '2019-06-15', '2019-06-30'), ]: self.invoice.company_id.tax_lock_date = tax_date with Form(self.invoice) as move_form: move_form.invoice_date = invoice_date self.assertEqual(self.invoice.date, fields.Date.to_date(accounting_date)) @freeze_time('2021-09-16') def test_in_invoice_onchange_invoice_date_2(self): invoice_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice', account_predictive_bills_disable_prediction=True)) invoice_form.partner_id = self.partner_a invoice_form.invoice_payment_term_id = self.env.ref('account.account_payment_term_30days') with invoice_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a invoice_form.invoice_date = fields.Date.from_string('2021-09-01') invoice = invoice_form.save() self.assertRecordValues(invoice, [{ 'date': fields.Date.from_string('2021-09-16'), 'invoice_date': fields.Date.from_string('2021-09-01'), 'invoice_date_due': fields.Date.from_string('2021-10-01'), }]) def test_in_invoice_line_onchange_product_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.product_id = self.product_b move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'name': self.product_b.name, 'product_id': self.product_b.id, 'product_uom_id': self.product_b.uom_id.id, 'account_id': self.product_b.property_account_expense_id.id, 'price_unit': 160.0, 'price_subtotal': 160.0, 'price_total': 208.0, 'tax_ids': self.product_b.supplier_taxes_id.ids, 'amount_currency': 160.0, 'debit': 160.0, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 48.0, 'price_subtotal': 48.0, 'price_total': 48.0, 'amount_currency': 48.0, 'debit': 48.0, }, { **self.tax_line_vals_2, 'price_unit': 48.0, 'price_subtotal': 48.0, 'price_total': 48.0, 'amount_currency': 48.0, 'debit': 48.0, }, { **self.term_line_vals_1, 'price_unit': -416.0, 'price_subtotal': -416.0, 'price_total': -416.0, 'amount_currency': -416.0, 'credit': 416.0, }, ], { **self.move_vals, 'amount_untaxed': 320.0, 'amount_tax': 96.0, 'amount_total': 416.0, }) def test_in_invoice_line_onchange_product_2_with_fiscal_pos(self): ''' Test mapping a price-included tax (10%) with a price-excluded tax (20%) on a price_unit of 110.0. The price_unit should be 100.0 after applying the fiscal position. ''' tax_price_include = self.env['account.tax'].create({ 'name': '10% incl', 'type_tax_use': 'purchase', 'amount_type': 'percent', 'amount': 10, 'price_include': True, 'include_base_amount': True, }) tax_price_exclude = self.env['account.tax'].create({ 'name': '15% excl', 'type_tax_use': 'purchase', 'amount_type': 'percent', 'amount': 15, }) fiscal_position = self.env['account.fiscal.position'].create({ 'name': 'fiscal_pos_a', 'tax_ids': [ (0, None, { 'tax_src_id': tax_price_include.id, 'tax_dest_id': tax_price_exclude.id, }), ], }) product = self.env['product.product'].create({ 'name': 'product', 'uom_id': self.env.ref('uom.product_uom_unit').id, 'standard_price': 110.0, 'supplier_taxes_id': [(6, 0, tax_price_include.ids)], }) move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2019-01-01') move_form.currency_id = self.currency_data['currency'] move_form.fiscal_position_id = fiscal_position with move_form.invoice_line_ids.new() as line_form: line_form.product_id = product invoice = move_form.save() self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'price_unit': 200.0, 'price_subtotal': 200.0, 'price_total': 230.0, 'tax_ids': tax_price_exclude.ids, 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 100.0, 'credit': 0.0, }, { 'product_id': False, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'tax_ids': [], 'tax_line_id': tax_price_exclude.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'debit': 15.0, 'credit': 0.0, }, { 'product_id': False, 'price_unit': -230.0, 'price_subtotal': -230.0, 'price_total': -230.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -230.0, 'debit': 0.0, 'credit': 115.0, }, ], { 'currency_id': self.currency_data['currency'].id, 'fiscal_position_id': fiscal_position.id, 'amount_untaxed': 200.0, 'amount_tax': 30.0, 'amount_total': 230.0, }) uom_dozen = self.env.ref('uom.product_uom_dozen') with Form(invoice) as move_form: with move_form.invoice_line_ids.edit(0) as line_form: line_form.product_uom_id = uom_dozen self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'product_uom_id': uom_dozen.id, 'price_unit': 2400.0, 'price_subtotal': 2400.0, 'price_total': 2760.0, 'tax_ids': tax_price_exclude.ids, 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 2400.0, 'debit': 1200.0, 'credit': 0.0, }, { 'product_id': False, 'product_uom_id': False, 'price_unit': 360.0, 'price_subtotal': 360.0, 'price_total': 360.0, 'tax_ids': [], 'tax_line_id': tax_price_exclude.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 360.0, 'debit': 180.0, 'credit': 0.0, }, { 'product_id': False, 'product_uom_id': False, 'price_unit': -2760.0, 'price_subtotal': -2760.0, 'price_total': -2760.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -2760.0, 'debit': 0.0, 'credit': 1380.0, }, ], { 'currency_id': self.currency_data['currency'].id, 'fiscal_position_id': fiscal_position.id, 'amount_untaxed': 2400.0, 'amount_tax': 360.0, 'amount_total': 2760.0, }) def test_in_invoice_line_onchange_product_2_with_fiscal_pos_2(self): ''' Test mapping a price-included tax (10%) with another price-included tax (20%) on a price_unit of 110.0. The price_unit should be 120.0 after applying the fiscal position. ''' tax_price_include_1 = self.env['account.tax'].create({ 'name': '10% incl', 'type_tax_use': 'purchase', 'amount_type': 'percent', 'amount': 10, 'price_include': True, 'include_base_amount': True, }) tax_price_include_2 = self.env['account.tax'].create({ 'name': '20% incl', 'type_tax_use': 'purchase', 'amount_type': 'percent', 'amount': 20, 'price_include': True, 'include_base_amount': True, }) fiscal_position = self.env['account.fiscal.position'].create({ 'name': 'fiscal_pos_a', 'tax_ids': [ (0, None, { 'tax_src_id': tax_price_include_1.id, 'tax_dest_id': tax_price_include_2.id, }), ], }) product = self.env['product.product'].create({ 'name': 'product', 'uom_id': self.env.ref('uom.product_uom_unit').id, 'standard_price': 110.0, 'supplier_taxes_id': [(6, 0, tax_price_include_1.ids)], }) move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2019-01-01') move_form.currency_id = self.currency_data['currency'] move_form.fiscal_position_id = fiscal_position with move_form.invoice_line_ids.new() as line_form: line_form.product_id = product invoice = move_form.save() self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'price_unit': 240.0, 'price_subtotal': 200.0, 'price_total': 240.0, 'tax_ids': tax_price_include_2.ids, 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 100.0, 'credit': 0.0, }, { 'product_id': False, 'price_unit': 40.0, 'price_subtotal': 40.0, 'price_total': 40.0, 'tax_ids': [], 'tax_line_id': tax_price_include_2.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 40.0, 'debit': 20.0, 'credit': 0.0, }, { 'product_id': False, 'price_unit': -240.0, 'price_subtotal': -240.0, 'price_total': -240.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -240.0, 'debit': 0.0, 'credit': 120.0, }, ], { 'currency_id': self.currency_data['currency'].id, 'fiscal_position_id': fiscal_position.id, 'amount_untaxed': 200.0, 'amount_tax': 40.0, 'amount_total': 240.0, }) uom_dozen = self.env.ref('uom.product_uom_dozen') with Form(invoice) as move_form: with move_form.invoice_line_ids.edit(0) as line_form: line_form.product_uom_id = uom_dozen self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'product_uom_id': uom_dozen.id, 'price_unit': 2880.0, 'price_subtotal': 2400.0, 'price_total': 2880.0, 'tax_ids': tax_price_include_2.ids, 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 2400.0, 'debit': 1200.0, 'credit': 0.0, }, { 'product_id': False, 'product_uom_id': False, 'price_unit': 480.0, 'price_subtotal': 480.0, 'price_total': 480.0, 'tax_ids': [], 'tax_line_id': tax_price_include_2.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 480.0, 'debit': 240.0, 'credit': 0.0, }, { 'product_id': False, 'product_uom_id': False, 'price_unit': -2880.0, 'price_subtotal': -2880.0, 'price_total': -2880.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -2880.0, 'debit': 0.0, 'credit': 1440.0, }, ], { 'currency_id': self.currency_data['currency'].id, 'fiscal_position_id': fiscal_position.id, 'amount_untaxed': 2400.0, 'amount_tax': 480.0, 'amount_total': 2880.0, }) def test_in_invoice_line_onchange_business_fields_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: # Current price_unit is 800. # We set quantity = 4, discount = 50%, price_unit = 400. The debit/credit fields don't change because (4 * 400) * 0.5 = 800. line_form.quantity = 4 line_form.discount = 50 line_form.price_unit = 400 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 4, 'discount': 50.0, 'price_unit': 400.0, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) move_form = Form(self.invoice) with move_form.line_ids.edit(2) as line_form: # Reset field except the discount that becomes 100%. # /!\ The modification is made on the accounting tab. line_form.quantity = 1 line_form.discount = 100 line_form.price_unit = 800 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'discount': 100.0, 'price_subtotal': 0.0, 'price_total': 0.0, 'amount_currency': 0.0, 'debit': 0.0, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 24.0, 'price_subtotal': 24.0, 'price_total': 24.0, 'amount_currency': 24.0, 'debit': 24.0, }, self.tax_line_vals_2, { **self.term_line_vals_1, 'price_unit': -208.0, 'price_subtotal': -208.0, 'price_total': -208.0, 'amount_currency': -208.0, 'credit': 208.0, }, ], { **self.move_vals, 'amount_untaxed': 160.0, 'amount_tax': 48.0, 'amount_total': 208.0, }) def test_in_invoice_line_onchange_accounting_fields_1(self): move_form = Form(self.invoice) with move_form.line_ids.edit(2) as line_form: # Custom debit on the first product line. line_form.debit = 3000 with move_form.line_ids.edit(3) as line_form: # Custom credit on the second product line. Credit should be reset by onchange. # /!\ It's a negative line. line_form.credit = 500 with move_form.line_ids.edit(0) as line_form: # Custom debit on the first tax line. line_form.debit = 800 with move_form.line_ids.edit(4) as line_form: # Custom debit on the second tax line. line_form.debit = 250 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 3000.0, 'price_subtotal': 3000.0, 'price_total': 3450.0, 'amount_currency': 3000.0, 'debit': 3000.0, }, { **self.product_line_vals_2, 'price_unit': -500.0, 'price_subtotal': -500.0, 'price_total': -650.0, 'amount_currency': -500.0, 'debit': 0.0, 'credit': 500.0, }, { **self.tax_line_vals_1, 'price_unit': 800.0, 'price_subtotal': 800.0, 'price_total': 800.0, 'amount_currency': 800.0, 'debit': 800.0, }, { **self.tax_line_vals_2, 'price_unit': 250.0, 'price_subtotal': 250.0, 'price_total': 250.0, 'amount_currency': 250.0, 'debit': 250.0, }, { **self.term_line_vals_1, 'price_unit': -3550.0, 'price_subtotal': -3550.0, 'price_total': -3550.0, 'amount_currency': -3550.0, 'credit': 3550.0, }, ], { **self.move_vals, 'amount_untaxed': 2500.0, 'amount_tax': 1050.0, 'amount_total': 3550.0, }) def test_in_invoice_line_onchange_partner_1(self): move_form = Form(self.invoice) move_form.partner_id = self.partner_b move_form.payment_reference = 'turlututu' move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'partner_id': self.partner_b.id, }, { **self.product_line_vals_2, 'partner_id': self.partner_b.id, }, { **self.tax_line_vals_1, 'partner_id': self.partner_b.id, }, { **self.tax_line_vals_2, 'partner_id': self.partner_b.id, }, { **self.term_line_vals_1, 'name': 'turlututu', 'partner_id': self.partner_b.id, 'account_id': self.partner_b.property_account_payable_id.id, 'price_unit': -789.6, 'price_subtotal': -789.6, 'price_total': -789.6, 'amount_currency': -789.6, 'credit': 789.6, 'date_maturity': fields.Date.from_string('2019-02-28'), }, { **self.term_line_vals_1, 'name': 'turlututu', 'partner_id': self.partner_b.id, 'account_id': self.partner_b.property_account_payable_id.id, 'price_unit': -338.4, 'price_subtotal': -338.4, 'price_total': -338.4, 'amount_currency': -338.4, 'credit': 338.4, }, ], { **self.move_vals, 'partner_id': self.partner_b.id, 'payment_reference': 'turlututu', 'fiscal_position_id': self.fiscal_pos_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'amount_untaxed': 960.0, 'amount_tax': 168.0, 'amount_total': 1128.0, }) # Remove lines and recreate them to apply the fiscal position. move_form = Form(self.invoice) move_form.invoice_line_ids.remove(0) move_form.invoice_line_ids.remove(0) with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_b move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'account_id': self.product_b.property_account_expense_id.id, 'partner_id': self.partner_b.id, 'tax_ids': self.tax_purchase_b.ids, }, { **self.product_line_vals_2, 'partner_id': self.partner_b.id, 'price_total': 184.0, 'tax_ids': self.tax_purchase_b.ids, }, { **self.tax_line_vals_1, 'name': self.tax_purchase_b.name, 'partner_id': self.partner_b.id, 'tax_line_id': self.tax_purchase_b.id, }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_payable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -772.8, 'price_subtotal': -772.8, 'price_total': -772.8, 'amount_currency': -772.8, 'credit': 772.8, 'date_maturity': fields.Date.from_string('2019-02-28'), }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_payable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -331.2, 'price_subtotal': -331.2, 'price_total': -331.2, 'amount_currency': -331.2, 'credit': 331.2, }, ], { **self.move_vals, 'partner_id': self.partner_b.id, 'payment_reference': 'turlututu', 'fiscal_position_id': self.fiscal_pos_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'amount_untaxed': 960.0, 'amount_tax': 144.0, 'amount_total': 1104.0, }) def test_in_invoice_line_onchange_taxes_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 960 line_form.tax_ids.add(self.tax_armageddon) move_form.save() child_tax_1 = self.tax_armageddon.children_tax_ids[0] child_tax_2 = self.tax_armageddon.children_tax_ids[1] self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 960.0, 'price_subtotal': 800.0, 'price_total': 1176.0, 'tax_ids': (self.tax_purchase_a + self.tax_armageddon).ids, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, { 'name': child_tax_1.name, 'product_id': False, 'account_id': self.company_data['default_account_tax_sale'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 64.0, 'price_subtotal': 64.0, 'price_total': 70.4, 'tax_ids': child_tax_2.ids, 'tax_line_id': child_tax_1.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': 64.0, 'debit': 64.0, 'credit': 0.0, 'date_maturity': False, }, { 'name': child_tax_1.name, 'product_id': False, 'account_id': self.company_data['default_account_expense'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 96.0, 'price_subtotal': 96.0, 'price_total': 105.6, 'tax_ids': child_tax_2.ids, 'tax_line_id': child_tax_1.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': 96.0, 'debit': 96.0, 'credit': 0.0, 'date_maturity': False, }, { 'name': child_tax_2.name, 'product_id': False, 'account_id': child_tax_2.cash_basis_transition_account_id.id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 96.0, 'price_subtotal': 96.0, 'price_total': 96.0, 'tax_ids': [], 'tax_line_id': child_tax_2.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': 96.0, 'debit': 96.0, 'credit': 0.0, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -1384.0, 'price_subtotal': -1384.0, 'price_total': -1384.0, 'amount_currency': -1384.0, 'credit': 1384.0, }, ], { **self.move_vals, 'amount_untaxed': 960.0, 'amount_tax': 424.0, 'amount_total': 1384.0, }) def test_in_invoice_line_onchange_cash_rounding_1(self): # Test 'add_invoice_line' rounding move_form = Form(self.invoice) # Add a cash rounding having 'add_invoice_line'. move_form.invoice_cash_rounding_id = self.cash_rounding_a move_form.save() # The cash rounding does nothing as the total is already rounded. self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 799.99 move_form.save() self.assertInvoiceValues(self.invoice, [ { 'name': 'add_invoice_line', 'product_id': False, 'account_id': self.cash_rounding_a.loss_account_id.id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 0.01, 'price_subtotal': 0.01, 'price_total': 0.01, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.company_data['currency'].id, 'amount_currency': 0.01, 'debit': 0.01, 'credit': 0.0, 'date_maturity': False, }, { **self.product_line_vals_1, 'price_unit': 799.99, 'price_subtotal': 799.99, 'price_total': 919.99, 'amount_currency': 799.99, 'debit': 799.99, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) # Test 'biggest_tax' rounding self.company_data['company'].country_id = self.env.ref('base.us') # Add a tag to product_a's default tax tax_line_tag = self.env['account.account.tag'].create({ 'name': "Tax tag", 'applicability': 'taxes', 'country_id': self.company_data['company'].country_id.id, }) repartition_line = self.tax_purchase_a.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') repartition_line.write({'tag_ids': [(4, tax_line_tag.id, 0)]}) # Create the invoice biggest_tax_invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'invoice_date': '2019-01-01', 'partner_id': self.partner_a.id, 'invoice_cash_rounding_id': self.cash_rounding_b.id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, 0, { 'product_id': self.product_a.id, 'price_unit': 799.99, 'tax_ids': [(6, 0, self.product_a.supplier_taxes_id.ids)], 'product_uom_id': self.product_a.uom_id.id, }), (0, 0, { 'product_id': self.product_b.id, 'price_unit': self.product_b.standard_price, 'tax_ids': [(6, 0, self.product_b.supplier_taxes_id.ids)], 'product_uom_id': self.product_b.uom_id.id, }), ], }) self.assertInvoiceValues(biggest_tax_invoice, [ { **self.product_line_vals_1, 'price_unit': 799.99, 'price_subtotal': 799.99, 'price_total': 919.99, 'amount_currency': 799.99, 'debit': 799.99, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { **self.product_line_vals_2, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { **self.tax_line_vals_1, 'tax_repartition_line_id': repartition_line.id, 'tax_tag_ids': tax_line_tag.ids, }, { **self.tax_line_vals_2, 'tax_repartition_line_id': self.tax_purchase_b.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_tag_ids': [], }, { 'name': '%s (rounding)' % self.tax_purchase_a.name, 'product_id': False, 'account_id': self.company_data['default_account_tax_purchase'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -0.04, 'price_subtotal': -0.04, 'price_total': -0.04, 'tax_ids': [], 'tax_line_id': self.tax_purchase_a.id, 'tax_repartition_line_id': repartition_line.id, 'tax_tag_ids': tax_line_tag.ids, 'currency_id': self.company_data['currency'].id, 'amount_currency': -0.04, 'debit': 0.0, 'credit': 0.04, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -1127.95, 'price_subtotal': -1127.95, 'price_total': -1127.95, 'amount_currency': -1127.95, 'credit': 1127.95, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, ], { **self.move_vals, 'amount_untaxed': 959.99, 'amount_tax': 167.96, 'amount_total': 1127.95, }) def test_in_invoice_line_onchange_currency_1(self): move_form = Form(self.invoice) move_form.currency_id = self.currency_data['currency'] move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 800.0, 'debit': 400.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 160.0, 'debit': 80.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 144.0, 'debit': 72.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 24.0, 'debit': 12.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1128.0, 'credit': 564.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) move_form = Form(self.invoice) # Change the date to get another rate: 1/3 instead of 1/2. move_form.date = fields.Date.from_string('2016-01-01') move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 800.0, 'debit': 266.67, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 160.0, 'debit': 53.33, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 144.0, 'debit': 48.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 24.0, 'debit': 8.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1128.0, 'credit': 376.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), }) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: # 0.045 * 0.1 = 0.0045. As the foreign currency has a 0.001 rounding, # the result should be 0.005 after rounding. line_form.quantity = 0.1 line_form.price_unit = 0.045 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 0.1, 'price_unit': 0.05, 'price_subtotal': 0.005, 'price_total': 0.006, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 0.005, 'debit': 0.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 160.0, 'debit': 53.33, }, { **self.tax_line_vals_1, 'price_unit': 24.0, 'price_subtotal': 24.001, 'price_total': 24.001, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 24.001, 'debit': 8.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 24.0, 'debit': 8.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'price_unit': -208.01, 'price_subtotal': -208.006, 'price_total': -208.006, 'amount_currency': -208.006, 'credit': 69.33, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), 'amount_untaxed': 160.005, 'amount_tax': 48.001, 'amount_total': 208.006, }) # Exit the multi-currencies. move_form = Form(self.invoice) move_form.currency_id = self.company_data['currency'] move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 0.1, 'price_unit': 0.05, 'price_subtotal': 0.01, 'price_total': 0.01, 'amount_currency': 0.01, 'debit': 0.01, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 24.0, 'price_subtotal': 24.0, 'price_total': 24.0, 'amount_currency': 24.0, 'debit': 24.0, }, self.tax_line_vals_2, { **self.term_line_vals_1, 'price_unit': -208.01, 'price_subtotal': -208.01, 'price_total': -208.01, 'amount_currency': -208.01, 'credit': 208.01, }, ], { **self.move_vals, 'currency_id': self.company_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), 'amount_untaxed': 160.01, 'amount_tax': 48.0, 'amount_total': 208.01, }) def test_in_invoice_onchange_past_invoice_1(self): copy_invoice = self.invoice.copy() move_form = Form(self.invoice) move_form.invoice_line_ids.remove(0) move_form.invoice_line_ids.remove(0) move_form.invoice_vendor_bill_id = copy_invoice move_form.save() self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) def test_in_invoice_create_refund(self): self.invoice.action_post() move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.from_string('2019-02-01'), 'reason': 'no reason', 'refund_method': 'refund', 'journal_id': self.invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertEqual(self.invoice.payment_state, 'not_paid', "Refunding with a draft credit note should keep the invoice 'not_paid'.") self.assertInvoiceValues(reverse_move, [ { **self.product_line_vals_1, 'amount_currency': -800.0, 'debit': 0.0, 'credit': 800.0, }, { **self.product_line_vals_2, 'amount_currency': -160.0, 'debit': 0.0, 'credit': 160.0, }, { **self.tax_line_vals_1, 'amount_currency': -144.0, 'debit': 0.0, 'credit': 144.0, }, { **self.tax_line_vals_2, 'amount_currency': -24.0, 'debit': 0.0, 'credit': 24.0, }, { **self.term_line_vals_1, 'name': '', 'amount_currency': 1128.0, 'debit': 1128.0, 'credit': 0.0, 'date_maturity': move_reversal.date, }, ], { **self.move_vals, 'invoice_payment_term_id': None, 'date': move_reversal.date, 'state': 'draft', 'ref': 'Reversal of: %s, %s' % (self.invoice.name, move_reversal.reason), 'payment_state': 'not_paid', }) move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.from_string('2019-02-01'), 'reason': 'no reason again', 'refund_method': 'cancel', 'journal_id': self.invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertEqual(self.invoice.payment_state, 'reversed', "After cancelling it with a reverse invoice, an invoice should be in 'reversed' state.") self.assertInvoiceValues(reverse_move, [ { **self.product_line_vals_1, 'amount_currency': -800.0, 'debit': 0.0, 'credit': 800.0, }, { **self.product_line_vals_2, 'amount_currency': -160.0, 'debit': 0.0, 'credit': 160.0, }, { **self.tax_line_vals_1, 'amount_currency': -144.0, 'debit': 0.0, 'credit': 144.0, }, { **self.tax_line_vals_2, 'amount_currency': -24.0, 'debit': 0.0, 'credit': 24.0, }, { **self.term_line_vals_1, 'name': '', 'amount_currency': 1128.0, 'debit': 1128.0, 'credit': 0.0, 'date_maturity': move_reversal.date, }, ], { **self.move_vals, 'invoice_payment_term_id': None, 'date': move_reversal.date, 'state': 'posted', 'ref': 'Reversal of: %s, %s' % (self.invoice.name, move_reversal.reason), 'payment_state': 'paid', }) def test_in_invoice_create_refund_multi_currency(self): ''' Test the account.move.reversal takes care about the currency rates when setting a custom reversal date. ''' move_form = Form(self.invoice) move_form.date = '2016-01-01' move_form.currency_id = self.currency_data['currency'] move_form.save() self.invoice.action_post() # The currency rate changed from 1/3 to 1/2. move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.from_string('2017-01-01'), 'reason': 'no reason', 'refund_method': 'refund', 'journal_id': self.invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertEqual(self.invoice.payment_state, 'not_paid', "Refunding with a draft credit note should keep the invoice 'not_paid'.") self.assertInvoiceValues(reverse_move, [ { **self.product_line_vals_1, 'amount_currency': -800.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 400.0, }, { **self.product_line_vals_2, 'amount_currency': -160.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 80.0, }, { **self.tax_line_vals_1, 'amount_currency': -144.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 72.0, }, { **self.tax_line_vals_2, 'amount_currency': -24.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 12.0, }, { **self.term_line_vals_1, 'name': '', 'amount_currency': 1128.0, 'currency_id': self.currency_data['currency'].id, 'debit': 564.0, 'credit': 0.0, 'date_maturity': move_reversal.date, }, ], { **self.move_vals, 'invoice_payment_term_id': None, 'currency_id': self.currency_data['currency'].id, 'date': move_reversal.date, 'state': 'draft', 'ref': 'Reversal of: %s, %s' % (self.invoice.name, move_reversal.reason), 'payment_state': 'not_paid', }) move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.from_string('2017-01-01'), 'reason': 'no reason again', 'refund_method': 'cancel', 'journal_id': self.invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertEqual(self.invoice.payment_state, 'reversed', "After cancelling it with a reverse invoice, an invoice should be in 'reversed' state.") self.assertInvoiceValues(reverse_move, [ { **self.product_line_vals_1, 'amount_currency': -800.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 400.0, }, { **self.product_line_vals_2, 'amount_currency': -160.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 80.0, }, { **self.tax_line_vals_1, 'amount_currency': -144.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 72.0, }, { **self.tax_line_vals_2, 'amount_currency': -24.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 12.0, }, { **self.term_line_vals_1, 'name': '', 'amount_currency': 1128.0, 'currency_id': self.currency_data['currency'].id, 'debit': 564.0, 'credit': 0.0, 'date_maturity': move_reversal.date, }, ], { **self.move_vals, 'invoice_payment_term_id': None, 'currency_id': self.currency_data['currency'].id, 'date': move_reversal.date, 'state': 'posted', 'ref': 'Reversal of: %s, %s' % (self.invoice.name, move_reversal.reason), 'payment_state': 'paid', }) def test_in_invoice_create_1(self): # Test creating an account_move with the least information. move = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 800.0, 'debit': 400.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 160.0, 'debit': 80.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 144.0, 'debit': 72.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 24.0, 'debit': 12.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1128.0, 'credit': 564.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_in_invoice_write_1(self): # Test creating an account_move with the least information. move = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), ], }) move.write({ 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 800.0, 'debit': 400.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 160.0, 'debit': 80.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 144.0, 'debit': 72.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 24.0, 'debit': 12.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1128.0, 'credit': 564.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_in_invoice_duplicate_supplier_reference(self): ''' Ensure two vendor bills can't share the same vendor reference. ''' self.invoice.ref = 'a supplier reference' invoice2 = self.invoice.copy(default={'invoice_date': self.invoice.invoice_date}) invoice2.ref = 'a supplier reference' with self.assertRaises(ValidationError): invoice2.action_post() def test_in_invoice_switch_in_refund_1(self): # Test creating an account_move with an in_invoice_type and switch it in an in_refund. move = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) move.action_switch_invoice_into_refund_credit_note() self.assertRecordValues(move, [{'move_type': 'in_refund'}]) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -800.0, 'credit': 400.0, 'debit': 0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -160.0, 'credit': 80.0, 'debit': 0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -144.0, 'credit': 72.0, 'debit': 0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.0, 'credit': 12.0, 'debit': 0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1128.0, 'debit': 564.0, 'credit': 0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_in_invoice_switch_in_refund_2(self): # Test creating an account_move with an in_invoice_type and switch it in an in_refund and a negative quantity. move = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'quantity': -self.product_line_vals_1['quantity'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'quantity': -self.product_line_vals_2['quantity'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -800.0, 'price_subtotal': -800.0, 'price_total': -920.0, 'credit': 400.0, 'debit': 0, 'quantity': -1.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -160.0, 'price_subtotal': -160.0, 'price_total': -208.0, 'credit': 80.0, 'debit': 0, 'quantity': -1.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -144.0, 'price_subtotal': -144.0, 'price_total': -144.0, 'price_unit': -144.0, 'credit': 72.0, 'debit': 0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.0, 'price_subtotal': -24.0, 'price_total': -24.0, 'price_unit': -24.0, 'credit': 12.0, 'debit': 0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1128.0, 'price_subtotal': 1128.0, 'price_total': 1128.0, 'price_unit': 1128.0, 'debit': 564.0, 'credit': 0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'amount_tax' : -self.move_vals['amount_tax'], 'amount_total' : -self.move_vals['amount_total'], 'amount_untaxed' : -self.move_vals['amount_untaxed'], }) move.action_switch_invoice_into_refund_credit_note() self.assertRecordValues(move, [{'move_type': 'in_refund'}]) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -800.0, 'credit': 400.0, 'debit': 0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -160.0, 'credit': 80.0, 'debit': 0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -144.0, 'credit': 72.0, 'debit': 0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.0, 'credit': 12.0, 'debit': 0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1128.0, 'debit': 564.0, 'credit': 0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'amount_tax' : self.move_vals['amount_tax'], 'amount_total' : self.move_vals['amount_total'], 'amount_untaxed' : self.move_vals['amount_untaxed'], }) def test_in_invoice_change_period_accrual_1(self): move = self.env['account.move'].create({ 'move_type': 'in_invoice', 'date': '2017-01-01', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2017-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, None, { 'name': self.product_line_vals_1['name'], 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'quantity': self.product_line_vals_1['quantity'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': self.product_line_vals_1['tax_ids'], }), (0, None, { 'name': self.product_line_vals_2['name'], 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'quantity': self.product_line_vals_2['quantity'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': self.product_line_vals_2['tax_ids'], }), ] }) move.action_post() wizard = self.env['account.automatic.entry.wizard']\ .with_context(active_model='account.move.line', active_ids=move.invoice_line_ids.ids).create({ 'action': 'change_period', 'date': '2018-01-01', 'percentage': 60, 'journal_id': self.company_data['default_journal_misc'].id, 'expense_accrual_account': self.env['account.account'].create({ 'name': 'Accrual Expense Account', 'code': '234567', 'user_type_id': self.env.ref('account.data_account_type_expenses').id, 'reconcile': True, }).id, 'revenue_accrual_account': self.env['account.account'].create({ 'name': 'Accrual Revenue Account', 'code': '765432', 'user_type_id': self.env.ref('account.data_account_type_expenses').id, 'reconcile': True, }).id, }) wizard_res = wizard.do_action() self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 800.0, 'debit': 400.0, 'credit': 0.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 160.0, 'debit': 80.0, 'credit': 0.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 144.0, 'debit': 72.0, 'credit': 0.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 24.0, 'debit': 12.0, 'credit': 0.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1128.0, 'debit': 0.0, 'credit': 564.0, 'date_maturity': fields.Date.from_string('2017-01-01'), }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2017-01-01'), }) accrual_lines = self.env['account.move'].browse(wizard_res['domain'][0][2]).line_ids.sorted('date') self.assertRecordValues(accrual_lines, [ {'amount_currency': -480.0, 'debit': 0.0, 'credit': 240.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': 480.0, 'debit': 240.0, 'credit': 0.0, 'account_id': wizard.expense_accrual_account.id, 'reconciled': True}, {'amount_currency': -96.0, 'debit': 0.0, 'credit': 48.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': 96.0, 'debit': 48.0, 'credit': 0.0, 'account_id': wizard.expense_accrual_account.id, 'reconciled': True}, {'amount_currency': 480.0, 'debit': 240.0, 'credit': 0.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': -480.0, 'debit': 0.0, 'credit': 240.0, 'account_id': wizard.expense_accrual_account.id, 'reconciled': True}, {'amount_currency': 96.0, 'debit': 48.0, 'credit': 0.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': -96.0, 'debit': 0.0, 'credit': 48.0, 'account_id': wizard.expense_accrual_account.id, 'reconciled': True}, ]) def test_in_invoice_reverse_caba(self): tax_waiting_account = self.env['account.account'].create({ 'name': 'TAX_WAIT', 'code': 'TWAIT', 'user_type_id': self.env.ref('account.data_account_type_current_liabilities').id, 'reconcile': True, 'company_id': self.company_data['company'].id, }) tax_final_account = self.env['account.account'].create({ 'name': 'TAX_TO_DEDUCT', 'code': 'TDEDUCT', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) tax_base_amount_account = self.env['account.account'].create({ 'name': 'TAX_BASE', 'code': 'TBASE', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) self.env.company.account_cash_basis_base_account_id = tax_base_amount_account self.env.company.tax_exigibility = True tax_tags = defaultdict(dict) for line_type, repartition_type in [(l, r) for l in ('invoice', 'refund') for r in ('base', 'tax')]: tax_tags[line_type][repartition_type] = self.env['account.account.tag'].create({ 'name': '%s %s tag' % (line_type, repartition_type), 'applicability': 'taxes', 'country_id': self.env.ref('base.us').id, }) tax = self.env['account.tax'].create({ 'name': 'cash basis 10%', 'type_tax_use': 'purchase', 'amount': 10, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': tax_waiting_account.id, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['invoice']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['invoice']['tax'].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['refund']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['refund']['tax'].ids)], }), ], }) # create invoice move_form = Form(self.env['account.move'].with_context(default_move_type='in_invoice')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2017-01-01') with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a line_form.tax_ids.clear() line_form.tax_ids.add(tax) invoice = move_form.save() invoice.action_post() # make payment self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({ 'payment_date': invoice.date, })._create_payments() # check caba move partial_rec = invoice.mapped('line_ids.matched_debit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) expected_values = [ { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_base_amount_account.id, 'debit': 0.0, 'credit': 800.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': tax.ids, 'tax_tag_ids': tax_tags['invoice']['base'].ids, 'account_id': tax_base_amount_account.id, 'debit': 800.0, 'credit': 0.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_waiting_account.id, 'debit': 0.0, 'credit': 80.0, }, { 'tax_line_id': tax.id, 'tax_repartition_line_id': tax.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_ids': [], 'tax_tag_ids': tax_tags['invoice']['tax'].ids, 'account_id': tax_final_account.id, 'debit': 80.0, 'credit': 0.0, }, ] self.assertRecordValues(caba_move.line_ids, expected_values) # unreconcile credit_aml = invoice.line_ids.filtered('credit') credit_aml.remove_move_reconcile() # check caba move reverse is same as caba move with only debit/credit inverted reversed_caba_move = self.env['account.move'].search([('reversed_entry_id', '=', caba_move.id)]) for value in expected_values: value.update({ 'debit': value['credit'], 'credit': value['debit'], }) self.assertRecordValues(reversed_caba_move.line_ids, expected_values) def test_in_invoice_line_tax_line_delete(self): with Form(self.invoice) as invoice_form: lines_count = len(invoice_form.line_ids) with invoice_form.line_ids.edit(0) as line_form: tax = line_form.tax_line_id invoice_form.line_ids.remove(0) # check that the tax line is recreated self.assertEqual(len(invoice_form.line_ids), lines_count) # Assert the tax line is recreated for the tax self.assertIn(tax, self.invoice.line_ids.tax_line_id) def test_invoice_sent_to_additional_partner(self): """ Make sure that when an invoice is a partner to a partner who is not the invoiced customer, they receive a link containing an access token, allowing them to view the invoice without needing to log in. """ # Create a simple invoice for the partner invoice = self.init_invoice( 'out_invoice', partner=self.partner_a, invoice_date='2023-04-17', amounts=[100]) # Set the invoice to the 'posted' state invoice.action_post() # Create a partner not related to the invoice additional_partner = self.env['res.partner'].create({ 'name': "Additional Partner", 'email': "additional@example.com", }) # Send the invoice action = invoice.with_context(discard_logo_check=True).action_invoice_sent() action_context = action['context'] # Create the email using the wizard and add the additional partner as a recipient invoice_send_wizard = self.env['account.invoice.send'].with_context( action_context, active_ids=[invoice.id] ).create({'is_print': False}) invoice_send_wizard.partner_ids |= additional_partner invoice_send_wizard.template_id.auto_delete = False invoice_send_wizard.send_and_print_action() # Find the email sent to the additional partner additional_partner_mail = self.env['mail.mail'].search([ ('res_id', '=', invoice.id), ('recipient_ids', '=', additional_partner.id) ]) self.assertTrue(additional_partner_mail) self.assertIn('access_token=', additional_partner_mail.body_html, "The additional partner should be sent the link including the token")
39.061076
80,583
1,389
py
PYTHON
15.0
# -*- coding: utf-8 -*- import logging from odoo.tests import standalone _logger = logging.getLogger(__name__) @standalone('all_l10n') def test_all_l10n(env): """ This test will install all the l10n_* modules. As the module install is not yet fully transactional, the modules will remain installed after the test. """ assert env.ref('base.module_account').demo, "Need the demo to test with data" l10n_mods = env['ir.module.module'].search([ ('name', 'like', 'l10n%'), ('state', '=', 'uninstalled'), ]) l10n_mods.button_immediate_install() env.reset() # clear the set of environments env = env() # get an environment that refers to the new registry coas = env['account.chart.template'].search([ ('id', 'not in', env['res.company'].search([]).chart_template_id.ids) ]) for coa in coas: cname = 'company_%s' % str(coa.id) company = env['res.company'].create({ 'name': cname, 'country_id': coa.country_id.id, }) env.user.company_ids += company env.user.company_id = company _logger.info('Testing COA: %s (company: %s)' % (coa.name, cname)) try: with env.cr.savepoint(): coa.try_loading() except Exception: _logger.error("Error when creating COA %s", coa.name, exc_info=True)
33.878049
1,389
1,542
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.addons.account.tests.common import AccountTestInvoicingHttpCommon from odoo.tests.common import tagged @tagged('post_install', '-at_install') class TestTourRenderInvoiceReport(AccountTestInvoicingHttpCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.env.user.write({ 'groups_id': [ (6, 0, (cls.env.ref('account.group_account_invoice') + cls.env.ref('base.group_system')).ids), ], }) cls.out_invoice = cls.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': cls.partner_a.id, 'invoice_date': '2019-05-01', 'date': '2019-05-01', 'invoice_line_ids': [ (0, 0, {'name': 'line1', 'price_unit': 100.0}), ], }) cls.out_invoice.action_post() report_layout = cls.env.ref('web.report_layout_standard') cls.company_data['company'].write({ 'primary_color': '#123456', 'secondary_color': '#789101', 'external_report_layout_id': report_layout.view_id.id, }) cls.env.ref('account.account_invoices_without_payment').report_type = 'qweb-html' def test_render_account_document_layout(self): self.start_tour('/web', 'account_render_report', login=self.env.user.login, timeout=200)
36.714286
1,542
36,913
py
PYTHON
15.0
# -*- coding: utf-8 -*- # pylint: disable=C0326 from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged, Form @tagged('post_install', '-at_install') class TestInvoiceTaxes(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.company_data['company'].country_id = cls.env.ref('base.us') cls.percent_tax_1 = cls.env['account.tax'].create({ 'name': '21%', 'amount_type': 'percent', 'amount': 21, 'sequence': 10, }) cls.percent_tax_1_incl = cls.env['account.tax'].create({ 'name': '21% incl', 'amount_type': 'percent', 'amount': 21, 'price_include': True, 'include_base_amount': True, 'sequence': 20, }) cls.percent_tax_2 = cls.env['account.tax'].create({ 'name': '12%', 'amount_type': 'percent', 'amount': 12, 'sequence': 30, }) cls.percent_tax_3_incl = cls.env['account.tax'].create({ 'name': '5% incl', 'amount_type': 'percent', 'amount': 5, 'price_include': True, 'include_base_amount': True, 'sequence': 40, }) cls.group_tax = cls.env['account.tax'].create({ 'name': 'group 12% + 21%', 'amount_type': 'group', 'amount': 21, 'children_tax_ids': [ (4, cls.percent_tax_1_incl.id), (4, cls.percent_tax_2.id) ], 'sequence': 40, }) cls.tax_report = cls.env['account.tax.report'].create({ 'name': "Tax report", 'country_id': cls.company_data['company'].country_id.id, }) cls.tax_report_line = cls.env['account.tax.report.line'].create({ 'name': 'test_tax_report_line', 'tag_name': 'test_tax_report_line', 'report_id': cls.tax_report.id, 'sequence': 10, }) cls.tax_tag_pos = cls.tax_report_line.tag_ids.filtered(lambda x: not x.tax_negate) cls.tax_tag_neg = cls.tax_report_line.tag_ids.filtered(lambda x: x.tax_negate) cls.base_tax_report_line = cls.env['account.tax.report.line'].create({ 'name': 'base_test_tax_report_line', 'tag_name': 'base_test_tax_report_line', 'report_id': cls.tax_report.id, 'sequence': 10, }) cls.base_tag_pos = cls.base_tax_report_line.tag_ids.filtered(lambda x: not x.tax_negate) cls.base_tag_neg = cls.base_tax_report_line.tag_ids.filtered(lambda x: x.tax_negate) def _create_invoice(self, taxes_per_line, inv_type='out_invoice', currency_id=False, invoice_payment_term_id=False): ''' Create an invoice on the fly. :param taxes_per_line: A list of tuple (price_unit, account.tax recordset) ''' vals = { 'move_type': inv_type, 'partner_id': self.partner_a.id, 'invoice_line_ids': [(0, 0, { 'name': 'xxxx', 'quantity': 1, 'price_unit': amount, 'tax_ids': [(6, 0, taxes.ids)], }) for amount, taxes in taxes_per_line], } if currency_id: vals['currency_id'] = currency_id.id if invoice_payment_term_id: vals['invoice_payment_term_id'] = invoice_payment_term_id.id return self.env['account.move'].create(vals) def test_one_tax_per_line(self): ''' Test: price_unit | Taxes ------------------ 100 | 21% 121 | 21% incl 100 | 12% Expected: Tax | Taxes | Base | Amount -------------------------------------------- 21% | / | 100 | 21 21% incl | / | 100 | 21 12% | / | 100 | 12 ''' invoice = self._create_invoice([ (100, self.percent_tax_1), (121, self.percent_tax_1_incl), (100, self.percent_tax_2), ]) invoice.action_post() self.assertRecordValues(invoice.line_ids.filtered('tax_line_id'), [ {'name': self.percent_tax_1.name, 'tax_base_amount': 100, 'price_unit': 21, 'tax_ids': []}, {'name': self.percent_tax_1_incl.name, 'tax_base_amount': 100, 'price_unit': 21, 'tax_ids': []}, {'name': self.percent_tax_2.name, 'tax_base_amount': 100, 'price_unit': 12, 'tax_ids': []}, ]) def test_affecting_base_amount(self): ''' Test: price_unit | Taxes ------------------ 121 | 21% incl, 12% 100 | 12% Expected: Tax | Taxes | Base | Amount -------------------------------------------- 21% incl | 12% | 100 | 21 12% | / | 121 | 14.52 12% | / | 100 | 12 ''' invoice = self._create_invoice([ (121, self.percent_tax_1_incl + self.percent_tax_2), (100, self.percent_tax_2), ]) invoice.action_post() self.assertRecordValues(invoice.line_ids.filtered('tax_line_id').sorted(lambda x: x.price_unit), [ {'name': self.percent_tax_1_incl.name, 'tax_base_amount': 100, 'price_unit': 21, 'tax_ids': [self.percent_tax_2.id]}, {'name': self.percent_tax_2.name, 'tax_base_amount': 221, 'price_unit': 26.52, 'tax_ids': []}, ]) def test_group_of_taxes(self): ''' Test: price_unit | Taxes ------------------ 121 | 21% incl + 12% 100 | 12% Expected: Tax | Taxes | Base | Amount -------------------------------------------- 21% incl | / | 100 | 21 12% | 21% incl | 121 | 14.52 12% | / | 100 | 12 ''' invoice = self._create_invoice([ (121, self.group_tax), (100, self.percent_tax_2), ]) invoice.action_post() self.assertRecordValues(invoice.line_ids.filtered('tax_line_id').sorted('balance'), [ {'name': self.percent_tax_1_incl.name, 'tax_base_amount': 100.0, 'balance': -21.0, 'tax_ids': [self.percent_tax_2.id]}, {'name': self.percent_tax_2.name, 'tax_base_amount': 121.0, 'balance': -14.52, 'tax_ids': []}, {'name': self.percent_tax_2.name, 'tax_base_amount': 100.0, 'balance': -12.0, 'tax_ids': []}, ]) def _create_tax_tag(self, tag_name): return self.env['account.account.tag'].create({ 'name': tag_name, 'applicability': 'taxes', 'country_id': self.env.company.country_id.id, }) def test_tax_repartition(self): inv_base_tag = self._create_tax_tag('invoice_base') inv_tax_tag_10 = self._create_tax_tag('invoice_tax_10') inv_tax_tag_90 = self._create_tax_tag('invoice_tax_90') ref_base_tag = self._create_tax_tag('refund_base') ref_tax_tag = self._create_tax_tag('refund_tax') user_type = self.env.ref('account.data_account_type_current_assets') account_1 = self.env['account.account'].create({'name': 'test1', 'code': 'test1', 'user_type_id': user_type.id}) account_2 = self.env['account.account'].create({'name': 'test2', 'code': 'test2', 'user_type_id': user_type.id}) tax = self.env['account.tax'].create({ 'name': "Tax with account", 'amount_type': 'fixed', 'type_tax_use': 'sale', 'amount': 42, 'invoice_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(4, inv_base_tag.id, 0)], }), (0,0, { 'factor_percent': 10, 'repartition_type': 'tax', 'account_id': account_1.id, 'tag_ids': [(4, inv_tax_tag_10.id, 0)], }), (0,0, { 'factor_percent': 90, 'repartition_type': 'tax', 'account_id': account_2.id, 'tag_ids': [(4, inv_tax_tag_90.id, 0)], }), ], 'refund_repartition_line_ids': [ (0,0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(4, ref_base_tag.id, 0)], }), (0,0, { 'factor_percent': 10, 'repartition_type': 'tax', 'tag_ids': [(4, ref_tax_tag.id, 0)], }), (0,0, { 'factor_percent': 90, 'repartition_type': 'tax', 'account_id': account_1.id, 'tag_ids': [(4, ref_tax_tag.id, 0)], }), ], }) # Test invoice repartition invoice = self._create_invoice([(100, tax)], inv_type='out_invoice') invoice.action_post() self.assertEqual(len(invoice.line_ids), 4, "There should be 4 account move lines created for the invoice: payable, base and 2 tax lines") inv_base_line = invoice.line_ids.filtered(lambda x: not x.tax_repartition_line_id and x.account_id.user_type_id.type != 'receivable') self.assertEqual(len(inv_base_line), 1, "There should be only one base line generated") self.assertEqual(abs(inv_base_line.balance), 100, "Base amount should be 100") self.assertEqual(inv_base_line.tax_tag_ids, inv_base_tag, "Base line should have received base tag") inv_tax_lines = invoice.line_ids.filtered(lambda x: x.tax_repartition_line_id.repartition_type == 'tax') self.assertEqual(len(inv_tax_lines), 2, "There should be two tax lines, one for each repartition line.") self.assertEqual(abs(inv_tax_lines.filtered(lambda x: x.account_id == account_1).balance), 4.2, "Tax line on account 1 should amount to 4.2 (10% of 42)") self.assertEqual(inv_tax_lines.filtered(lambda x: x.account_id == account_1).tax_tag_ids, inv_tax_tag_10, "Tax line on account 1 should have 10% tag") self.assertAlmostEqual(abs(inv_tax_lines.filtered(lambda x: x.account_id == account_2).balance), 37.8, 2, "Tax line on account 2 should amount to 37.8 (90% of 42)") self.assertEqual(inv_tax_lines.filtered(lambda x: x.account_id == account_2).tax_tag_ids, inv_tax_tag_90, "Tax line on account 2 should have 90% tag") # Test refund repartition refund = self._create_invoice([(100, tax)], inv_type='out_refund') refund.action_post() self.assertEqual(len(refund.line_ids), 4, "There should be 4 account move lines created for the refund: payable, base and 2 tax lines") ref_base_line = refund.line_ids.filtered(lambda x: not x.tax_repartition_line_id and x.account_id.user_type_id.type != 'receivable') self.assertEqual(len(ref_base_line), 1, "There should be only one base line generated") self.assertEqual(abs(ref_base_line.balance), 100, "Base amount should be 100") self.assertEqual(ref_base_line.tax_tag_ids, ref_base_tag, "Base line should have received base tag") ref_tax_lines = refund.line_ids.filtered(lambda x: x.tax_repartition_line_id.repartition_type == 'tax') self.assertEqual(len(ref_tax_lines), 2, "There should be two refund tax lines") self.assertEqual(abs(ref_tax_lines.filtered(lambda x: x.account_id == ref_base_line.account_id).balance), 4.2, "Refund tax line on base account should amount to 4.2 (10% of 42)") self.assertAlmostEqual(abs(ref_tax_lines.filtered(lambda x: x.account_id == account_1).balance), 37.8, 2, "Refund tax line on account 1 should amount to 37.8 (90% of 42)") self.assertEqual(ref_tax_lines.mapped('tax_tag_ids'), ref_tax_tag, "Refund tax lines should have the right tag") def test_division_tax(self): ''' Test that when using division tax, with percentage amount 100% any change on price unit is correctly reflected on the whole move. Complete scenario: - Create a division tax, 100% amount, included in price. - Create an invoice, with only the mentioned tax - Change price_unit of the aml - Total price of the move should change as well ''' sale_tax = self.env['account.tax'].create({ 'name': 'tax', 'type_tax_use': 'sale', 'amount_type': 'division', 'amount': 100, 'price_include': True, 'include_base_amount': True, }) invoice = self._create_invoice([(100, sale_tax)]) self.assertRecordValues(invoice.line_ids.filtered('tax_line_id'), [{ 'name': sale_tax.name, 'tax_base_amount': 0.0, 'balance': -100, }]) # change price unit, everything should change as well with Form(invoice) as invoice_form: with invoice_form.line_ids.edit(0) as line_edit: line_edit.price_unit = 200 self.assertRecordValues(invoice.line_ids.filtered('tax_line_id'), [{ 'name': sale_tax.name, 'tax_base_amount': 0.0, 'balance': -200, }]) def test_misc_journal_entry_tax_tags_sale(self): sale_tax = self.env['account.tax'].create({ 'name': 'tax', 'type_tax_use': 'sale', 'amount_type': 'percent', 'amount': 10, 'invoice_repartition_line_ids': [ (0, 0, { 'repartition_type': 'base', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.base_tag_pos.ids)], }), (0, 0, { 'repartition_type': 'tax', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.tax_tag_pos.ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'repartition_type': 'base', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.base_tag_neg.ids)], }), (0, 0, { 'repartition_type': 'tax', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.tax_tag_neg.ids)], }), ], }) inv_tax_rep_ln = sale_tax.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') ref_tax_rep_ln = sale_tax.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') # === Tax in debit === move_form = Form(self.env['account.move'], view='account.view_move_form') move_form.ref = 'azerty' # Debit base tax line. with move_form.line_ids.new() as credit_line: credit_line.name = 'debit_line_1' credit_line.account_id = self.company_data['default_account_revenue'] credit_line.debit = 1000.0 credit_line.tax_ids.clear() credit_line.tax_ids.add(sale_tax) self.assertTrue(credit_line.recompute_tax_line) # Balance the journal entry. with move_form.line_ids.new() as credit_line: credit_line.name = 'balance' credit_line.account_id = self.company_data['default_account_revenue'] credit_line.credit = 1100.0 move = move_form.save() self.assertRecordValues(move.line_ids.sorted('balance'), [ {'balance': -1100.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 0, 'tax_repartition_line_id': False, 'tax_tag_invert': False}, {'balance': 100.0, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_neg.ids, 'tax_base_amount': 1000, 'tax_repartition_line_id': ref_tax_rep_ln.id, 'tax_tag_invert': False}, {'balance': 1000.0, 'tax_ids': sale_tax.ids, 'tax_tag_ids': self.base_tag_neg.ids, 'tax_base_amount': 0, 'tax_repartition_line_id': False, 'tax_tag_invert': False}, ]) # === Tax in credit === move_form = Form(self.env['account.move'], view='account.view_move_form') move_form.ref = 'azerty' # Debit base tax line. with move_form.line_ids.new() as credit_line: credit_line.name = 'debit_line_1' credit_line.account_id = self.company_data['default_account_revenue'] credit_line.credit = 1000.0 credit_line.tax_ids.clear() credit_line.tax_ids.add(sale_tax) self.assertTrue(credit_line.recompute_tax_line) # Balance the journal entry. with move_form.line_ids.new() as debit_line: debit_line.name = 'balance' debit_line.account_id = self.company_data['default_account_revenue'] debit_line.debit = 1100.0 move = move_form.save() self.assertRecordValues(move.line_ids.sorted('balance'), [ {'balance': -1000.0, 'tax_ids': sale_tax.ids, 'tax_tag_ids': self.base_tag_pos.ids, 'tax_base_amount': 0, 'tax_repartition_line_id': False, 'tax_tag_invert': True}, {'balance': -100.0, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_pos.ids, 'tax_base_amount': 1000, 'tax_repartition_line_id': inv_tax_rep_ln.id, 'tax_tag_invert': True}, {'balance': 1100.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 0, 'tax_repartition_line_id': False, 'tax_tag_invert': False}, ]) def test_misc_journal_entry_tax_tags_purchase(self): purch_tax = self.env['account.tax'].create({ 'name': 'tax', 'type_tax_use': 'purchase', 'amount_type': 'percent', 'amount': 10, 'invoice_repartition_line_ids': [ (0, 0, { 'repartition_type': 'base', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.base_tag_pos.ids)], }), (0, 0, { 'repartition_type': 'tax', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.tax_tag_pos.ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'repartition_type': 'base', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.base_tag_neg.ids)], }), (0, 0, { 'repartition_type': 'tax', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.tax_tag_neg.ids)], }), ], }) inv_tax_rep_ln = purch_tax.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') ref_tax_rep_ln = purch_tax.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') # === Tax in debit === move_form = Form(self.env['account.move']) move_form.ref = 'azerty' # Debit base tax line. with move_form.line_ids.new() as credit_line: credit_line.name = 'debit_line_1' credit_line.account_id = self.company_data['default_account_revenue'] credit_line.debit = 1000.0 credit_line.tax_ids.clear() credit_line.tax_ids.add(purch_tax) self.assertTrue(credit_line.recompute_tax_line) # Balance the journal entry. with move_form.line_ids.new() as credit_line: credit_line.name = 'balance' credit_line.account_id = self.company_data['default_account_revenue'] credit_line.credit = 1100.0 move = move_form.save() self.assertRecordValues(move.line_ids.sorted('balance'), [ {'balance': -1100.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 0, 'tax_repartition_line_id': False, 'tax_tag_invert': False}, {'balance': 100.0, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_pos.ids, 'tax_base_amount': 1000, 'tax_repartition_line_id': inv_tax_rep_ln.id, 'tax_tag_invert': False}, {'balance': 1000.0, 'tax_ids': purch_tax.ids, 'tax_tag_ids': self.base_tag_pos.ids, 'tax_base_amount': 0, 'tax_repartition_line_id': False, 'tax_tag_invert': False}, ]) # === Tax in credit === move_form = Form(self.env['account.move']) move_form.ref = 'azerty' # Debit base tax line. with move_form.line_ids.new() as credit_line: credit_line.name = 'debit_line_1' credit_line.account_id = self.company_data['default_account_revenue'] credit_line.credit = 1000.0 credit_line.tax_ids.clear() credit_line.tax_ids.add(purch_tax) self.assertTrue(credit_line.recompute_tax_line) # Balance the journal entry. with move_form.line_ids.new() as debit_line: debit_line.name = 'balance' debit_line.account_id = self.company_data['default_account_revenue'] debit_line.debit = 1100.0 move = move_form.save() self.assertRecordValues(move.line_ids.sorted('balance'), [ {'balance': -1000.0, 'tax_ids': purch_tax.ids, 'tax_tag_ids': self.base_tag_neg.ids, 'tax_base_amount': 0, 'tax_repartition_line_id': False, 'tax_tag_invert': True}, {'balance': -100.0, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_neg.ids, 'tax_base_amount': 1000, 'tax_repartition_line_id': ref_tax_rep_ln.id, 'tax_tag_invert': True}, {'balance': 1100.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 0, 'tax_repartition_line_id': False, 'tax_tag_invert': False}, ]) def test_misc_entry_tax_group_signs(self): """ Tests sign inversion of the tags on misc operations made with tax groups. """ def _create_group_of_taxes(tax_type): # We use asymmetric tags between the child taxes to avoid shadowing errors child1_sale_tax = self.env['account.tax'].create({ 'sequence': 1, 'name': 'child1_%s' % tax_type, 'type_tax_use': 'none', 'amount_type': 'percent', 'amount': 5, 'invoice_repartition_line_ids': [ (0, 0, { 'repartition_type': 'base', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.base_tag_pos.ids)], }), (0, 0, { 'repartition_type': 'tax', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.tax_tag_pos.ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'repartition_type': 'base', 'factor_percent': 100.0, }), (0, 0, { 'repartition_type': 'tax', 'factor_percent': 100.0, }), ], }) child2_sale_tax = self.env['account.tax'].create({ 'sequence': 2, 'name': 'child2_%s' % tax_type, 'type_tax_use': 'none', 'amount_type': 'percent', 'amount': 10, 'invoice_repartition_line_ids': [ (0, 0, { 'repartition_type': 'base', 'factor_percent': 100.0, }), (0, 0, { 'repartition_type': 'tax', 'factor_percent': 100.0, }), ], 'refund_repartition_line_ids': [ (0, 0, { 'repartition_type': 'base', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.base_tag_neg.ids)], }), (0, 0, { 'repartition_type': 'tax', 'factor_percent': 100.0, 'tag_ids': [(6, 0, self.tax_tag_neg.ids)], }), ], }) return self.env['account.tax'].create({ 'name': 'group_%s' % tax_type, 'type_tax_use': tax_type, 'amount_type': 'group', 'amount': 10, 'children_tax_ids':[(6,0,[child1_sale_tax.id, child2_sale_tax.id])] }) def _create_misc_operation(tax, tax_field): with Form(self.env['account.move'], view='account.view_move_form') as move_form: for line_field in ('debit', 'credit'): line_amount = tax_field == line_field and 1000 or 1150 with move_form.line_ids.new() as line_form: line_form.name = '%s_line' % line_field line_form.account_id = self.company_data['default_account_revenue'] line_form.debit = line_field == 'debit' and line_amount or 0 line_form.credit = line_field == 'credit' and line_amount or 0 if tax_field == line_field: line_form.tax_ids.clear() line_form.tax_ids.add(tax) return move_form.save() sale_group = _create_group_of_taxes('sale') purchase_group = _create_group_of_taxes('purchase') # Sale tax on debit: use refund repartition debit_sale_move = _create_misc_operation(sale_group, 'debit') self.assertRecordValues(debit_sale_move.line_ids.sorted('balance'), [ {'balance': -1150.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 0}, {'balance': 50.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 1000}, {'balance': 100.0, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_neg.ids, 'tax_base_amount': 1000}, {'balance': 1000.0, 'tax_ids': sale_group.ids, 'tax_tag_ids': self.base_tag_neg.ids, 'tax_base_amount': 0}, ]) # Sale tax on credit: use invoice repartition credit_sale_move = _create_misc_operation(sale_group, 'credit') self.assertRecordValues(credit_sale_move.line_ids.sorted('balance'), [ {'balance': -1000.0, 'tax_ids': sale_group.ids, 'tax_tag_ids': self.base_tag_pos.ids, 'tax_base_amount': 0}, {'balance': -100.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 1000}, {'balance': -50.0, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_pos.ids, 'tax_base_amount': 1000}, {'balance': 1150.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 0}, ]) # Purchase tax on debit: use invoice repartition debit_purchase_move = _create_misc_operation(purchase_group, 'debit') self.assertRecordValues(debit_purchase_move.line_ids.sorted('balance'), [ {'balance': -1150.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 0}, {'balance': 50.0, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_pos.ids, 'tax_base_amount': 1000}, {'balance': 100.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 1000}, {'balance': 1000.0, 'tax_ids': purchase_group.ids, 'tax_tag_ids': self.base_tag_pos.ids, 'tax_base_amount': 0}, ]) # Purchase tax on credit: use refund repartition credit_purchase_move = _create_misc_operation(purchase_group, 'credit') self.assertRecordValues(credit_purchase_move.line_ids.sorted('balance'), [ {'balance': -1000.0, 'tax_ids': purchase_group.ids, 'tax_tag_ids': self.base_tag_neg.ids, 'tax_base_amount': 0}, {'balance': -100.0, 'tax_ids': [], 'tax_tag_ids': self.tax_tag_neg.ids, 'tax_base_amount': 1000}, {'balance': -50.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 1000}, {'balance': 1150.0, 'tax_ids': [], 'tax_tag_ids': [], 'tax_base_amount': 0}, ]) def test_tax_calculation_foreign_currency_large_quantity(self): ''' Test: Foreign currency with rate of 1.1726 and tax of 21% price_unit | Quantity | Taxes ------------------ 2.82 | 20000 | 21% not incl ''' self.env['res.currency.rate'].create({ 'name': '2018-01-01', 'rate': 1.1726, 'currency_id': self.currency_data['currency'].id, 'company_id': self.env.company.id, }) self.currency_data['currency'].rounding = 0.05 invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'currency_id': self.currency_data['currency'].id, 'invoice_date': '2018-01-01', 'date': '2018-01-01', 'invoice_line_ids': [(0, 0, { 'name': 'xxxx', 'quantity': 20000, 'price_unit': 2.82, 'tax_ids': [(6, 0, self.percent_tax_1.ids)], })] }) self.assertRecordValues(invoice.line_ids.filtered('tax_line_id'), [{ 'tax_base_amount': 48098.24, # 20000 * 2.82 / 1.1726 'credit': 10100.63, # tax_base_amount * 0.21 }]) def test_ensure_no_unbalanced_entry(self): ''' Ensure to not create an unbalanced journal entry when saving. ''' self.env['res.currency.rate'].create({ 'name': '2018-01-01', 'rate': 0.654065014, 'currency_id': self.currency_data['currency'].id, 'company_id': self.env.company.id, }) self.currency_data['currency'].rounding = 0.05 invoice = self._create_invoice([ (5, self.percent_tax_3_incl), (10, self.percent_tax_3_incl), (50, self.percent_tax_3_incl), ], currency_id=self.currency_data['currency'], invoice_payment_term_id=self.pay_terms_a) invoice.action_post() def test_tax_calculation_multi_currency(self): self.env['res.currency.rate'].create({ 'name': '2018-01-01', 'rate': 0.273748, 'currency_id': self.currency_data['currency'].id, 'company_id': self.env.company.id, }) self.currency_data['currency'].rounding = 0.01 invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'currency_id': self.currency_data['currency'].id, 'invoice_date': '2018-01-01', 'date': '2018-01-01', 'invoice_line_ids': [(0, 0, { 'name': 'xxxx', 'quantity': 1, 'price_unit': 155.32, 'tax_ids': [(6, 0, self.percent_tax_1.ids)], })] }) self.assertRecordValues(invoice.line_ids.filtered('tax_line_id'), [{ 'tax_base_amount': 567.38, # 155.32 * 1 / (1 / 0.273748) 'balance': -119.16, # tax_base_amount * 0.21 }]) self.assertRecordValues(invoice.line_ids.filtered(lambda l: not l.name), [{ 'balance': 686.54 }]) with Form(invoice) as invoice_form: invoice_form.currency_id = self.currency_data['currency'] self.assertRecordValues(invoice.line_ids.filtered('tax_line_id'), [{ 'tax_base_amount': 567.38, 'balance': -119.16, }]) self.assertRecordValues(invoice.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable'), [{ 'balance': 686.54 }]) def test_change_tax_line_account_when_tax_zero_percent(self): """ This test checks the following flow: - Invoice with three invoice lines: • One with tax > 0% • One with tax == 0% • One with tax == 0 fixed - On line_ids, change the account of the tax line The tax line should still be there and the account should be effectively changed """ tax_0_percent, tax_0_fixed = self.env['account.tax'].create([ { 'name': '0%', 'amount_type': 'percent', 'amount': 0, 'sequence': 10, }, { 'name': '0 fixed', 'amount_type': 'fixed', 'amount': 0, 'sequence': 10, } ]) new_account_revenue = self.company_data['default_account_revenue'].copy() invoice = self._create_invoice([(500, self.percent_tax_1), (300, tax_0_percent), (100, tax_0_fixed)], inv_type='out_invoice') self.assertRecordValues(invoice.line_ids, [ { 'account_id': self.company_data['default_account_revenue'].id, 'name': 'xxxx', 'tax_ids': self.percent_tax_1.ids, 'debit': 0.0, 'credit': 500.0, }, { 'account_id': self.company_data['default_account_revenue'].id, 'name': 'xxxx', 'tax_ids': tax_0_percent.ids, 'debit': 0.0, 'credit': 300.0, }, { 'account_id': self.company_data['default_account_revenue'].id, 'name': 'xxxx', 'tax_ids': tax_0_fixed.ids, 'debit': 0.0, 'credit': 100.0, }, { 'account_id': self.company_data['default_account_revenue'].id, 'name': '21%', 'tax_ids': [], 'debit': 0.0, 'credit': 105.0, }, { 'account_id': self.company_data['default_account_receivable'].id, 'name': '', 'tax_ids': [], 'debit': 1005.0, 'credit': 0.0, } ]) with Form(invoice) as invoice_form: with invoice_form.line_ids.edit(3) as line: line.account_id = new_account_revenue self.assertRecordValues(invoice.line_ids, [ { 'account_id': self.company_data['default_account_revenue'].id, 'name': 'xxxx', 'tax_ids': self.percent_tax_1.ids, 'debit': 0.0, 'credit': 500.0, }, { 'account_id': self.company_data['default_account_revenue'].id, 'name': 'xxxx', 'tax_ids': tax_0_percent.ids, 'debit': 0.0, 'credit': 300.0, }, { 'account_id': self.company_data['default_account_revenue'].id, 'name': 'xxxx', 'tax_ids': tax_0_fixed.ids, 'debit': 0.0, 'credit': 100.0, }, { 'account_id': new_account_revenue.id, 'name': '21%', 'tax_ids': [], 'debit': 0.0, 'credit': 105.0, }, { 'account_id': self.company_data['default_account_receivable'].id, 'name': '', 'tax_ids': [], 'debit': 1005.0, 'credit': 0.0, } ])
44.735758
36,907
8,714
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged import json @tagged('post_install', '-at_install') class TestAccountMovePaymentsWidget(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.receivable_account = cls.company_data['default_account_receivable'] cls.payable_account = cls.company_data['default_account_payable'] cls.currency_data_2 = cls.setup_multi_currency_data(default_values={ 'name': 'Stars', 'symbol': '☆', 'currency_unit_label': 'Stars', 'currency_subunit_label': 'Little Stars', }, rate2016=6.0, rate2017=4.0) cls.curr_1 = cls.company_data['currency'] cls.curr_2 = cls.currency_data['currency'] cls.curr_3 = cls.currency_data_2['currency'] cls.payment_2016_curr_1 = cls.env['account.move'].create({ 'date': '2016-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 500.0, 'amount_currency': -500.0, 'currency_id': cls.curr_1.id, 'account_id': cls.receivable_account.id, 'partner_id': cls.partner_a.id}), (0, 0, {'debit': 500.0, 'credit': 0.0, 'amount_currency': 500.0, 'currency_id': cls.curr_1.id, 'account_id': cls.payable_account.id, 'partner_id': cls.partner_a.id}), ], }) cls.payment_2016_curr_1.action_post() cls.payment_2016_curr_2 = cls.env['account.move'].create({ 'date': '2016-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 500.0, 'amount_currency': -1550.0, 'currency_id': cls.curr_2.id, 'account_id': cls.receivable_account.id, 'partner_id': cls.partner_a.id}), (0, 0, {'debit': 500.0, 'credit': 0.0, 'amount_currency': 1550.0, 'currency_id': cls.curr_2.id, 'account_id': cls.payable_account.id, 'partner_id': cls.partner_a.id}), ], }) cls.payment_2016_curr_2.action_post() cls.payment_2017_curr_2 = cls.env['account.move'].create({ 'date': '2017-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 500.0, 'amount_currency': -950.0, 'currency_id': cls.curr_2.id, 'account_id': cls.receivable_account.id, 'partner_id': cls.partner_a.id}), (0, 0, {'debit': 500.0, 'credit': 0.0, 'amount_currency': 950.0, 'currency_id': cls.curr_2.id, 'account_id': cls.payable_account.id, 'partner_id': cls.partner_a.id}), ], }) cls.payment_2017_curr_2.action_post() cls.payment_2016_curr_3 = cls.env['account.move'].create({ 'date': '2016-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 500.0, 'amount_currency': -3050.0, 'currency_id': cls.curr_3.id, 'account_id': cls.receivable_account.id, 'partner_id': cls.partner_a.id}), (0, 0, {'debit': 500.0, 'credit': 0.0, 'amount_currency': 3050.0, 'currency_id': cls.curr_3.id, 'account_id': cls.payable_account.id, 'partner_id': cls.partner_a.id}), ], }) cls.payment_2016_curr_3.action_post() cls.payment_2017_curr_3 = cls.env['account.move'].create({ 'date': '2017-01-01', 'line_ids': [ (0, 0, {'debit': 0.0, 'credit': 500.0, 'amount_currency': -1950.0, 'currency_id': cls.curr_3.id, 'account_id': cls.receivable_account.id, 'partner_id': cls.partner_a.id}), (0, 0, {'debit': 500.0, 'credit': 0.0, 'amount_currency': 1950.0, 'currency_id': cls.curr_3.id, 'account_id': cls.payable_account.id, 'partner_id': cls.partner_a.id}), ], }) cls.payment_2017_curr_3.action_post() # ------------------------------------------------------------------------- # HELPERS # ------------------------------------------------------------------------- def _test_all_outstanding_payments(self, invoice, expected_amounts): ''' Check the outstanding payments widget before/after the reconciliation. :param invoice: An account.move record. :param expected_amounts: A map <move_id> -> <amount> ''' # Check suggested outstanding payments. to_reconcile_payments_widget_vals = json.loads(invoice.invoice_outstanding_credits_debits_widget) self.assertTrue(to_reconcile_payments_widget_vals) current_amounts = {vals['move_id']: vals['amount'] for vals in to_reconcile_payments_widget_vals['content']} self.assertDictEqual(current_amounts, expected_amounts) # Reconcile pay_term_lines = invoice.line_ids\ .filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) to_reconcile = self.env['account.move'].browse(list(current_amounts.keys()))\ .line_ids\ .filtered(lambda line: line.account_id == pay_term_lines.account_id) (pay_term_lines + to_reconcile).reconcile() # Check payments after reconciliation. reconciled_payments_widget_vals = json.loads(invoice.invoice_payments_widget) self.assertTrue(reconciled_payments_widget_vals) current_amounts = {vals['move_id']: vals['amount'] for vals in reconciled_payments_widget_vals['content']} self.assertDictEqual(current_amounts, expected_amounts) # ------------------------------------------------------------------------- # TESTS # ------------------------------------------------------------------------- def test_outstanding_payments_single_currency(self): ''' Test the outstanding payments widget on invoices having the same currency as the company one. ''' # Customer invoice of 2500.0 in curr_1. out_invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.curr_1.id, 'invoice_line_ids': [(0, 0, {'name': '/', 'price_unit': 2500.0})], }) out_invoice.action_post() # Vendor bill of 2500.0 in curr_1. in_invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.curr_1.id, 'invoice_line_ids': [(0, 0, {'name': '/', 'price_unit': 2500.0})], }) in_invoice.action_post() expected_amounts = { self.payment_2016_curr_1.id: 500.0, self.payment_2016_curr_2.id: 500.0, self.payment_2017_curr_2.id: 500.0, self.payment_2016_curr_3.id: 500.0, self.payment_2017_curr_3.id: 500.0, } self._test_all_outstanding_payments(out_invoice, expected_amounts) self._test_all_outstanding_payments(in_invoice, expected_amounts) def test_outstanding_payments_foreign_currency(self): ''' Test the outstanding payments widget on invoices having a foreign currency. ''' # Customer invoice of 2500.0 in curr_1. out_invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.curr_2.id, 'invoice_line_ids': [(0, 0, {'name': '/', 'price_unit': 7500.0})], }) out_invoice.action_post() # Vendor bill of 2500.0 in curr_1. in_invoice = self.env['account.move'].create({ 'move_type': 'in_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.curr_2.id, 'invoice_line_ids': [(0, 0, {'name': '/', 'price_unit': 7500.0})], }) in_invoice.action_post() expected_amounts = { self.payment_2016_curr_1.id: 1500.0, self.payment_2016_curr_2.id: 1550.0, self.payment_2017_curr_2.id: 950.0, self.payment_2016_curr_3.id: 1500.0, self.payment_2017_curr_3.id: 1000.0, } self._test_all_outstanding_payments(out_invoice, expected_amounts) self._test_all_outstanding_payments(in_invoice, expected_amounts)
47.347826
8,712
42,525
py
PYTHON
15.0
# -*- coding: utf-8 -*- # pylint: disable=bad-whitespace from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests.common import Form from odoo.tests import tagged from odoo import fields, Command from collections import defaultdict @tagged('post_install', '-at_install') class TestAccountMoveOutRefundOnchanges(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.invoice = cls.init_invoice('out_refund', products=cls.product_a+cls.product_b) cls.product_line_vals_1 = { 'name': cls.product_a.name, 'product_id': cls.product_a.id, 'account_id': cls.product_a.property_account_income_id.id, 'partner_id': cls.partner_a.id, 'product_uom_id': cls.product_a.uom_id.id, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 1000.0, 'price_subtotal': 1000.0, 'price_total': 1150.0, 'tax_ids': cls.product_a.taxes_id.ids, 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 1000.0, 'debit': 1000.0, 'credit': 0.0, 'date_maturity': False, } cls.product_line_vals_2 = { 'name': cls.product_b.name, 'product_id': cls.product_b.id, 'account_id': cls.product_b.property_account_income_id.id, 'partner_id': cls.partner_a.id, 'product_uom_id': cls.product_b.uom_id.id, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 200.0, 'price_subtotal': 200.0, 'price_total': 260.0, 'tax_ids': cls.product_b.taxes_id.ids, 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 200.0, 'debit': 200.0, 'credit': 0.0, 'date_maturity': False, } cls.tax_line_vals_1 = { 'name': cls.tax_sale_a.name, 'product_id': False, 'account_id': cls.company_data['default_account_tax_sale'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 180.0, 'price_subtotal': 180.0, 'price_total': 180.0, 'tax_ids': [], 'tax_line_id': cls.tax_sale_a.id, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 180.0, 'debit': 180.0, 'credit': 0.0, 'date_maturity': False, } cls.tax_line_vals_2 = { 'name': cls.tax_sale_b.name, 'product_id': False, 'account_id': cls.company_data['default_account_tax_sale'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'tax_ids': [], 'tax_line_id': cls.tax_sale_b.id, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 30.0, 'debit': 30.0, 'credit': 0.0, 'date_maturity': False, } cls.term_line_vals_1 = { 'name': '', 'product_id': False, 'account_id': cls.company_data['default_account_receivable'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -1410.0, 'price_subtotal': -1410.0, 'price_total': -1410.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -1410.0, 'debit': 0.0, 'credit': 1410.0, 'date_maturity': fields.Date.from_string('2019-01-01'), } cls.move_vals = { 'partner_id': cls.partner_a.id, 'currency_id': cls.company_data['currency'].id, 'journal_id': cls.company_data['default_journal_sale'].id, 'date': fields.Date.from_string('2019-01-01'), 'fiscal_position_id': False, 'payment_reference': '', 'invoice_payment_term_id': cls.pay_terms_a.id, 'amount_untaxed': 1200.0, 'amount_tax': 210.0, 'amount_total': 1410.0, } def setUp(self): super(TestAccountMoveOutRefundOnchanges, self).setUp() self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) def test_out_refund_line_onchange_product_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.product_id = self.product_b move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'name': self.product_b.name, 'product_id': self.product_b.id, 'product_uom_id': self.product_b.uom_id.id, 'account_id': self.product_b.property_account_income_id.id, 'price_unit': 200.0, 'price_subtotal': 200.0, 'price_total': 260.0, 'tax_ids': self.product_b.taxes_id.ids, 'amount_currency': 200.0, 'debit': 200.0, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 60.0, 'price_subtotal': 60.0, 'price_total': 60.0, 'amount_currency': 60.0, 'debit': 60.0, }, { **self.tax_line_vals_2, 'price_unit': 60.0, 'price_subtotal': 60.0, 'price_total': 60.0, 'amount_currency': 60.0, 'debit': 60.0, }, { **self.term_line_vals_1, 'price_unit': -520.0, 'price_subtotal': -520.0, 'price_total': -520.0, 'amount_currency': -520.0, 'credit': 520.0, }, ], { **self.move_vals, 'amount_untaxed': 400.0, 'amount_tax': 120.0, 'amount_total': 520.0, }) def test_out_refund_line_onchange_business_fields_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: # Current price_unit is 1000. # We set quantity = 4, discount = 50%, price_unit = 400. The debit/credit fields don't change because (4 * 500) * 0.5 = 1000. line_form.quantity = 4 line_form.discount = 50 line_form.price_unit = 500 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 4, 'discount': 50.0, 'price_unit': 500.0, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) move_form = Form(self.invoice) with move_form.line_ids.edit(2) as line_form: # Reset field except the discount that becomes 100%. # /!\ The modification is made on the accounting tab. line_form.quantity = 1 line_form.discount = 100 line_form.price_unit = 1000 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'discount': 100.0, 'price_subtotal': 0.0, 'price_total': 0.0, 'amount_currency': 0.0, 'debit': 0.0, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'amount_currency': 30.0, 'debit': 30.0, }, self.tax_line_vals_2, { **self.term_line_vals_1, 'price_unit': -260.0, 'price_subtotal': -260.0, 'price_total': -260.0, 'amount_currency': -260.0, 'credit': 260.0, }, ], { **self.move_vals, 'amount_untaxed': 200.0, 'amount_tax': 60.0, 'amount_total': 260.0, }) def test_out_refund_line_onchange_accounting_fields_1(self): move_form = Form(self.invoice) with move_form.line_ids.edit(2) as line_form: # Custom debit on the first product line. line_form.debit = 3000 with move_form.line_ids.edit(3) as line_form: # Custom credit on the second product line. Credit should be reset by onchange. # /!\ It's a negative line. line_form.credit = 500 with move_form.line_ids.edit(0) as line_form: # Custom debit on the first tax line. line_form.debit = 800 with move_form.line_ids.edit(4) as line_form: # Custom debit on the second tax line. line_form.debit = 250 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 3000.0, 'price_subtotal': 3000.0, 'price_total': 3450.0, 'amount_currency': 3000.0, 'debit': 3000.0, }, { **self.product_line_vals_2, 'price_unit': -500.0, 'price_subtotal': -500.0, 'price_total': -650.0, 'amount_currency': -500.0, 'debit': 0.0, 'credit': 500.0, }, { **self.tax_line_vals_1, 'price_unit': 800.0, 'price_subtotal': 800.0, 'price_total': 800.0, 'amount_currency': 800.0, 'debit': 800.0, }, { **self.tax_line_vals_2, 'price_unit': 250.0, 'price_subtotal': 250.0, 'price_total': 250.0, 'amount_currency': 250.0, 'debit': 250.0, }, { **self.term_line_vals_1, 'price_unit': -3550.0, 'price_subtotal': -3550.0, 'price_total': -3550.0, 'amount_currency': -3550.0, 'credit': 3550.0, }, ], { **self.move_vals, 'amount_untaxed': 2500.0, 'amount_tax': 1050.0, 'amount_total': 3550.0, }) def test_out_refund_line_onchange_partner_1(self): move_form = Form(self.invoice) move_form.partner_id = self.partner_b move_form.payment_reference = 'turlututu' move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'partner_id': self.partner_b.id, }, { **self.product_line_vals_2, 'partner_id': self.partner_b.id, }, { **self.tax_line_vals_1, 'partner_id': self.partner_b.id, }, { **self.tax_line_vals_2, 'partner_id': self.partner_b.id, }, { **self.term_line_vals_1, 'name': 'turlututu', 'partner_id': self.partner_b.id, 'account_id': self.partner_b.property_account_receivable_id.id, 'price_unit': -987.0, 'price_subtotal': -987.0, 'price_total': -987.0, 'amount_currency': -987.0, 'credit': 987.0, 'date_maturity': fields.Date.from_string('2019-02-28'), }, { **self.term_line_vals_1, 'name': 'turlututu', 'partner_id': self.partner_b.id, 'account_id': self.partner_b.property_account_receivable_id.id, 'price_unit': -423.0, 'price_subtotal': -423.0, 'price_total': -423.0, 'amount_currency': -423.0, 'credit': 423.0, }, ], { **self.move_vals, 'partner_id': self.partner_b.id, 'payment_reference': 'turlututu', 'fiscal_position_id': self.fiscal_pos_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'amount_untaxed': 1200.0, 'amount_tax': 210.0, 'amount_total': 1410.0, }) # Remove lines and recreate them to apply the fiscal position. move_form = Form(self.invoice) move_form.invoice_line_ids.remove(0) move_form.invoice_line_ids.remove(0) with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_b move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'account_id': self.product_b.property_account_income_id.id, 'partner_id': self.partner_b.id, 'tax_ids': self.tax_sale_b.ids, }, { **self.product_line_vals_2, 'partner_id': self.partner_b.id, 'price_total': 230.0, 'tax_ids': self.tax_sale_b.ids, }, { **self.tax_line_vals_1, 'name': self.tax_sale_b.name, 'partner_id': self.partner_b.id, 'tax_line_id': self.tax_sale_b.id, }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_receivable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -966.0, 'price_subtotal': -966.0, 'price_total': -966.0, 'amount_currency': -966.0, 'credit': 966.0, 'date_maturity': fields.Date.from_string('2019-02-28'), }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_receivable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -414.0, 'price_subtotal': -414.0, 'price_total': -414.0, 'amount_currency': -414.0, 'credit': 414.0, }, ], { **self.move_vals, 'partner_id': self.partner_b.id, 'payment_reference': 'turlututu', 'fiscal_position_id': self.fiscal_pos_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'amount_untaxed': 1200.0, 'amount_tax': 180.0, 'amount_total': 1380.0, }) def test_out_refund_line_onchange_taxes_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 1200 line_form.tax_ids.add(self.tax_armageddon) move_form.save() child_tax_1 = self.tax_armageddon.children_tax_ids[0] child_tax_2 = self.tax_armageddon.children_tax_ids[1] self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 1200.0, 'price_subtotal': 1000.0, 'price_total': 1470.0, 'tax_ids': (self.tax_sale_a + self.tax_armageddon).ids, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, { 'name': child_tax_1.name, 'product_id': False, 'account_id': self.company_data['default_account_tax_sale'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 80.0, 'price_subtotal': 80.0, 'price_total': 88.0, 'tax_ids': child_tax_2.ids, 'tax_line_id': child_tax_1.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': 80.0, 'debit': 80.0, 'credit': 0.0, 'date_maturity': False, }, { 'name': child_tax_1.name, 'product_id': False, 'account_id': self.company_data['default_account_revenue'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 120.0, 'price_subtotal': 120.0, 'price_total': 132.0, 'tax_ids': child_tax_2.ids, 'tax_line_id': child_tax_1.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': 120.0, 'debit': 120.0, 'credit': 0.0, 'date_maturity': False, }, { 'name': child_tax_2.name, 'product_id': False, 'account_id': child_tax_2.cash_basis_transition_account_id.id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 120.0, 'price_subtotal': 120.0, 'price_total': 120.0, 'tax_ids': [], 'tax_line_id': child_tax_2.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': 120.0, 'debit': 120.0, 'credit': 0.0, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -1730.0, 'price_subtotal': -1730.0, 'price_total': -1730.0, 'amount_currency': -1730.0, 'credit': 1730.0, }, ], { **self.move_vals, 'amount_untaxed': 1200.0, 'amount_tax': 530.0, 'amount_total': 1730.0, }) def test_out_refund_line_onchange_cash_rounding_1(self): # Test 'add_invoice_line' rounding move_form = Form(self.invoice) # Add a cash rounding having 'add_invoice_line'. move_form.invoice_cash_rounding_id = self.cash_rounding_a move_form.save() # The cash rounding does nothing as the total is already rounded. self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 999.99 move_form.save() self.assertInvoiceValues(self.invoice, [ { 'name': 'add_invoice_line', 'product_id': False, 'account_id': self.cash_rounding_a.loss_account_id.id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 0.01, 'price_subtotal': 0.01, 'price_total': 0.01, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.company_data['currency'].id, 'amount_currency': 0.01, 'debit': 0.01, 'credit': 0.0, 'date_maturity': False, }, { **self.product_line_vals_1, 'price_unit': 999.99, 'price_subtotal': 999.99, 'price_total': 1149.99, 'amount_currency': 999.99, 'debit': 999.99, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) # Test 'biggest_tax' rounding self.company_data['company'].country_id = self.env.ref('base.us') # Add a tag to product_a's default tax tax_line_tag = self.env['account.account.tag'].create({ 'name': "Tax tag", 'applicability': 'taxes', 'country_id': self.company_data['company'].country_id.id, }) repartition_line = self.tax_sale_a.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') repartition_line.write({'tag_ids': [(4, tax_line_tag.id, 0)]}) # Create the invoice biggest_tax_invoice = self.env['account.move'].create({ 'move_type': 'out_refund', 'invoice_date': '2019-01-01', 'partner_id': self.partner_a.id, 'invoice_cash_rounding_id': self.cash_rounding_b.id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, 0, { 'product_id': self.product_a.id, 'price_unit': 999.99, 'tax_ids': [(6, 0, self.product_a.taxes_id.ids)], 'product_uom_id': self.product_a.uom_id.id, }), (0, 0, { 'product_id': self.product_b.id, 'price_unit': self.product_b.lst_price, 'tax_ids': [(6, 0, self.product_b.taxes_id.ids)], 'product_uom_id': self.product_b.uom_id.id, }), ], }) self.assertInvoiceValues(biggest_tax_invoice, [ { **self.product_line_vals_1, 'price_unit': 999.99, 'price_subtotal': 999.99, 'price_total': 1149.99, 'amount_currency': 999.99, 'debit': 999.99, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { **self.product_line_vals_2, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { **self.tax_line_vals_1, 'tax_repartition_line_id': repartition_line.id, 'tax_tag_ids': tax_line_tag.ids, }, { **self.tax_line_vals_2, 'tax_repartition_line_id': self.tax_sale_b.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_tag_ids': [], }, { 'name': '%s (rounding)' % self.tax_sale_a.name, 'product_id': False, 'account_id': self.company_data['default_account_tax_sale'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -0.04, 'price_subtotal': -0.04, 'price_total': -0.04, 'tax_ids': [], 'tax_line_id': self.tax_sale_a.id, 'tax_repartition_line_id': repartition_line.id, 'tax_tag_ids': tax_line_tag.ids, 'currency_id': self.company_data['currency'].id, 'amount_currency': -0.04, 'debit': 0.0, 'credit': 0.04, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -1409.95, 'price_subtotal': -1409.95, 'price_total': -1409.95, 'amount_currency': -1409.95, 'credit': 1409.95, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, ], { **self.move_vals, 'amount_untaxed': 1199.99, 'amount_tax': 209.96, 'amount_total': 1409.95, }) def test_out_refund_line_onchange_currency_1(self): move_form = Form(self.invoice) move_form.currency_id = self.currency_data['currency'] move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1000.0, 'debit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 180.0, 'debit': 90.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'debit': 15.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1410.0, 'credit': 705.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) move_form = Form(self.invoice) # Change the date to get another rate: 1/3 instead of 1/2. move_form.date = fields.Date.from_string('2016-01-01') move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1000.0, 'debit': 333.33, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 66.67, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 180.0, 'debit': 60.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'debit': 10.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1410.0, 'credit': 470.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), }) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: # 0.045 * 0.1 = 0.0045. As the foreign currency has a 0.001 rounding, # the result should be 0.005 after rounding. line_form.quantity = 0.1 line_form.price_unit = 0.045 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 0.1, 'price_unit': 0.05, 'price_subtotal': 0.005, 'price_total': 0.006, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 0.005, 'debit': 0.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 66.67, }, { **self.tax_line_vals_1, 'price_unit': 30.0, 'price_subtotal': 30.001, 'price_total': 30.001, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.001, 'debit': 10.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'debit': 10.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'price_unit': -260.01, 'price_subtotal': -260.006, 'price_total': -260.006, 'amount_currency': -260.006, 'credit': 86.67, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), 'amount_untaxed': 200.005, 'amount_tax': 60.001, 'amount_total': 260.006, }) # Exit the multi-currencies. move_form = Form(self.invoice) move_form.currency_id = self.company_data['currency'] move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 0.1, 'price_unit': 0.05, 'price_subtotal': 0.01, 'price_total': 0.01, 'amount_currency': 0.01, 'debit': 0.01, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'amount_currency': 30.0, 'debit': 30.0, }, self.tax_line_vals_2, { **self.term_line_vals_1, 'price_unit': -260.01, 'price_subtotal': -260.01, 'price_total': -260.01, 'amount_currency': -260.01, 'credit': 260.01, }, ], { **self.move_vals, 'currency_id': self.company_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), 'amount_untaxed': 200.01, 'amount_tax': 60.0, 'amount_total': 260.01, }) def test_out_refund_create_1(self): # Test creating an account_move with the least information. move = self.env['account.move'].create({ 'move_type': 'out_refund', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1000.0, 'debit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 180.0, 'debit': 90.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'debit': 15.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1410.0, 'credit': 705.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_out_refund_write_1(self): # Test creating an account_move with the least information. move = self.env['account.move'].create({ 'move_type': 'out_refund', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), ], }) move.write({ 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1000.0, 'debit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 180.0, 'debit': 90.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'debit': 15.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1410.0, 'credit': 705.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_out_refund_reverse_caba(self): tax_waiting_account = self.env['account.account'].create({ 'name': 'TAX_WAIT', 'code': 'TWAIT', 'user_type_id': self.env.ref('account.data_account_type_current_liabilities').id, 'reconcile': True, 'company_id': self.company_data['company'].id, }) tax_final_account = self.env['account.account'].create({ 'name': 'TAX_TO_DEDUCT', 'code': 'TDEDUCT', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) tax_base_amount_account = self.env['account.account'].create({ 'name': 'TAX_BASE', 'code': 'TBASE', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) self.env.company.account_cash_basis_base_account_id = tax_base_amount_account self.env.company.tax_exigibility = True tax_tags = defaultdict(dict) for line_type, repartition_type in [(l, r) for l in ('invoice', 'refund') for r in ('base', 'tax')]: tax_tags[line_type][repartition_type] = self.env['account.account.tag'].create({ 'name': '%s %s tag' % (line_type, repartition_type), 'applicability': 'taxes', 'country_id': self.env.ref('base.us').id, }) tax = self.env['account.tax'].create({ 'name': 'cash basis 10%', 'type_tax_use': 'sale', 'amount': 10, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': tax_waiting_account.id, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['invoice']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['invoice']['tax'].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['refund']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['refund']['tax'].ids)], }), ], }) # create invoice move_form = Form(self.env['account.move'].with_context(default_move_type='out_refund')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2017-01-01') with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a line_form.tax_ids.clear() line_form.tax_ids.add(tax) invoice = move_form.save() invoice.action_post() # make payment self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({ 'payment_date': invoice.date, })._create_payments() # check caba move partial_rec = invoice.mapped('line_ids.matched_debit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) expected_values = [ { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_base_amount_account.id, 'debit': 0.0, 'credit': 1000.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': tax.ids, 'tax_tag_ids': tax_tags['refund']['base'].ids, 'account_id': tax_base_amount_account.id, 'debit': 1000.0, 'credit': 0.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_waiting_account.id, 'debit': 0.0, 'credit': 100.0, }, { 'tax_line_id': tax.id, 'tax_repartition_line_id': tax.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_ids': [], 'tax_tag_ids': tax_tags['refund']['tax'].ids, 'account_id': tax_final_account.id, 'debit': 100.0, 'credit': 0.0, }, ] self.assertRecordValues(caba_move.line_ids, expected_values) # unreconcile credit_aml = invoice.line_ids.filtered('credit') credit_aml.remove_move_reconcile() # check caba move reverse is same as caba move with only debit/credit inverted reversed_caba_move = self.env['account.move'].search([('reversed_entry_id', '=', caba_move.id)]) for value in expected_values: value.update({ 'debit': value['credit'], 'credit': value['debit'], }) self.assertRecordValues(reversed_caba_move.line_ids, expected_values)
37.76643
42,525
4,611
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged from odoo import fields @tagged('post_install', '-at_install') class TestAccountInvoiceReport(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.invoices = cls.env['account.move'].create([ { 'move_type': 'out_invoice', 'partner_id': cls.partner_a.id, 'invoice_date': fields.Date.from_string('2016-01-01'), 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [ (0, None, { 'product_id': cls.product_a.id, 'quantity': 3, 'price_unit': 750, }), (0, None, { 'product_id': cls.product_a.id, 'quantity': 1, 'price_unit': 3000, }), ] }, { 'move_type': 'out_receipt', 'invoice_date': fields.Date.from_string('2016-01-01'), 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [ (0, None, { 'product_id': cls.product_a.id, 'quantity': 1, 'price_unit': 6000, }), ] }, { 'move_type': 'out_refund', 'partner_id': cls.partner_a.id, 'invoice_date': fields.Date.from_string('2017-01-01'), 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [ (0, None, { 'product_id': cls.product_a.id, 'quantity': 1, 'price_unit': 1200, }), ] }, { 'move_type': 'in_invoice', 'partner_id': cls.partner_a.id, 'invoice_date': fields.Date.from_string('2016-01-01'), 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [ (0, None, { 'product_id': cls.product_a.id, 'quantity': 1, 'price_unit': 60, }), ] }, { 'move_type': 'in_receipt', 'partner_id': cls.partner_a.id, 'invoice_date': fields.Date.from_string('2016-01-01'), 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [ (0, None, { 'product_id': cls.product_a.id, 'quantity': 1, 'price_unit': 60, }), ] }, { 'move_type': 'in_refund', 'partner_id': cls.partner_a.id, 'invoice_date': fields.Date.from_string('2017-01-01'), 'currency_id': cls.currency_data['currency'].id, 'invoice_line_ids': [ (0, None, { 'product_id': cls.product_a.id, 'quantity': 1, 'price_unit': 12, }), ] }, ]) def assertInvoiceReportValues(self, expected_values_list): reports = self.env['account.invoice.report'].search([('company_id', '=', self.company_data['company'].id)], order='price_subtotal DESC, quantity ASC') expected_values_dict = [{ 'price_average': vals[0], 'price_subtotal': vals[1], 'quantity': vals[2], } for vals in expected_values_list] self.assertRecordValues(reports, expected_values_dict) def test_invoice_report_multiple_types(self): self.assertInvoiceReportValues([ #price_average price_subtotal quantity [2000, 2000, 1], [1000, 1000, 1], [250, 750, 3], [6, 6, 1], [20, -20, -1], [20, -20, -1], [600, -600, -1], ])
38.747899
4,611
29,577
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged, new_test_user from odoo.tests.common import Form from odoo import fields, api, SUPERUSER_ID from odoo.exceptions import ValidationError, UserError, RedirectWarning from odoo.tools import mute_logger from dateutil.relativedelta import relativedelta from functools import reduce import json import psycopg2 from collections import defaultdict @tagged('post_install', '-at_install') class TestAccountMove(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) tax_repartition_line = cls.company_data['default_tax_sale'].refund_repartition_line_ids\ .filtered(lambda line: line.repartition_type == 'tax') cls.test_move = cls.env['account.move'].create({ 'move_type': 'entry', 'date': fields.Date.from_string('2016-01-01'), 'line_ids': [ (0, None, { 'name': 'revenue line 1', 'account_id': cls.company_data['default_account_revenue'].id, 'debit': 500.0, 'credit': 0.0, }), (0, None, { 'name': 'revenue line 2', 'account_id': cls.company_data['default_account_revenue'].id, 'debit': 1000.0, 'credit': 0.0, 'tax_ids': [(6, 0, cls.company_data['default_tax_sale'].ids)], }), (0, None, { 'name': 'tax line', 'account_id': cls.company_data['default_account_tax_sale'].id, 'debit': 150.0, 'credit': 0.0, 'tax_repartition_line_id': tax_repartition_line.id, }), (0, None, { 'name': 'counterpart line', 'account_id': cls.company_data['default_account_expense'].id, 'debit': 0.0, 'credit': 1650.0, }), ] }) def test_custom_currency_on_account_1(self): custom_account = self.company_data['default_account_revenue'].copy() # The currency set on the account is not the same as the one set on the company. # It should raise an error. custom_account.currency_id = self.currency_data['currency'] with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.line_ids[0].account_id = custom_account # The currency set on the account is the same as the one set on the company. # It should not raise an error. custom_account.currency_id = self.company_data['currency'] self.test_move.line_ids[0].account_id = custom_account def test_misc_fiscalyear_lock_date_1(self): self.test_move.action_post() # Set the lock date after the journal entry date. self.test_move.company_id.fiscalyear_lock_date = fields.Date.from_string('2017-01-01') # lines[0] = 'counterpart line' # lines[1] = 'tax line' # lines[2] = 'revenue line 1' # lines[3] = 'revenue line 2' lines = self.test_move.line_ids.sorted('debit') # Editing the reference should be allowed. self.test_move.ref = 'whatever' # Try to edit a line into a locked fiscal year. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.write({ 'line_ids': [ (1, lines[0].id, {'credit': lines[0].credit + 100.0}), (1, lines[2].id, {'debit': lines[2].debit + 100.0}), ], }) # Try to edit the account of a line. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.line_ids[0].write({'account_id': self.test_move.line_ids[0].account_id.copy().id}) # Try to edit a line. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.write({ 'line_ids': [ (1, lines[0].id, {'credit': lines[0].credit + 100.0}), (1, lines[3].id, {'debit': lines[3].debit + 100.0}), ], }) # Try to add a new tax on a line. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.write({ 'line_ids': [ (1, lines[2].id, {'tax_ids': [(6, 0, self.company_data['default_tax_purchase'].ids)]}), ], }) # Try to create a new line. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.write({ 'line_ids': [ (1, lines[0].id, {'credit': lines[0].credit + 100.0}), (0, None, { 'name': 'revenue line 1', 'account_id': self.company_data['default_account_revenue'].id, 'debit': 100.0, 'credit': 0.0, }), ], }) # You can't remove the journal entry from a locked period. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.date = fields.Date.from_string('2018-01-01') with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.name = "Othername" with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.unlink() with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.button_draft() # Try to add a new journal entry prior to the lock date. copy_move = self.test_move.copy({'date': '2017-01-01'}) # The date has been changed to the first valid date. self.assertEqual(copy_move.date, copy_move.company_id.fiscalyear_lock_date + relativedelta(days=1)) def test_misc_fiscalyear_lock_date_2(self): self.test_move.action_post() # Create a bank statement to get a balance in the suspense account. statement = self.env['account.bank.statement'].create({ 'journal_id': self.company_data['default_journal_bank'].id, 'date': '2016-01-01', 'line_ids': [ (0, 0, {'payment_ref': 'test', 'amount': 10.0}) ], }) statement.button_post() # You can't lock the fiscal year if there is some unreconciled statement. with self.assertRaises(RedirectWarning), self.cr.savepoint(): self.test_move.company_id.fiscalyear_lock_date = fields.Date.from_string('2017-01-01') def test_misc_tax_lock_date_1(self): self.test_move.action_post() # Set the tax lock date after the journal entry date. self.test_move.company_id.tax_lock_date = fields.Date.from_string('2017-01-01') # lines[0] = 'counterpart line' # lines[1] = 'tax line' # lines[2] = 'revenue line 1' # lines[3] = 'revenue line 2' lines = self.test_move.line_ids.sorted('debit') # Try to edit a line not affecting the taxes. self.test_move.write({ 'line_ids': [ (1, lines[0].id, {'credit': lines[0].credit + 100.0}), (1, lines[2].id, {'debit': lines[2].debit + 100.0}), ], }) # Try to edit the account of a line. self.test_move.line_ids[0].write({'account_id': self.test_move.line_ids[0].account_id.copy().id}) # Try to edit a line having some taxes. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.write({ 'line_ids': [ (1, lines[0].id, {'credit': lines[0].credit + 100.0}), (1, lines[3].id, {'debit': lines[3].debit + 100.0}), ], }) # Try to add a new tax on a line. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.write({ 'line_ids': [ (1, lines[2].id, {'tax_ids': [(6, 0, self.company_data['default_tax_purchase'].ids)]}), ], }) # Try to edit a tax line. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.write({ 'line_ids': [ (1, lines[0].id, {'credit': lines[0].credit + 100.0}), (1, lines[1].id, {'debit': lines[1].debit + 100.0}), ], }) # Try to create a line not affecting the taxes. self.test_move.write({ 'line_ids': [ (1, lines[0].id, {'credit': lines[0].credit + 100.0}), (0, None, { 'name': 'revenue line 1', 'account_id': self.company_data['default_account_revenue'].id, 'debit': 100.0, 'credit': 0.0, }), ], }) # Try to create a line affecting the taxes. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.write({ 'line_ids': [ (1, lines[0].id, {'credit': lines[0].credit + 100.0}), (0, None, { 'name': 'revenue line 2', 'account_id': self.company_data['default_account_revenue'].id, 'debit': 1000.0, 'credit': 0.0, 'tax_ids': [(6, 0, self.company_data['default_tax_sale'].ids)], }), ], }) # You can't remove the journal entry from a locked period. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.date = fields.Date.from_string('2018-01-01') with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.name = "Othername" with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.unlink() with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.button_draft() copy_move = self.test_move.copy({'date': self.test_move.date}) # /!\ The date is changed automatically to the next available one during the post. copy_move.action_post() # You can't change the date to one being in a locked period. with self.assertRaises(UserError), self.cr.savepoint(): copy_move.date = fields.Date.from_string('2017-01-01') def test_misc_draft_reconciled_entries_1(self): draft_moves = self.env['account.move'].create([ { 'move_type': 'entry', 'line_ids': [ (0, None, { 'name': 'move 1 receivable line', 'account_id': self.company_data['default_account_receivable'].id, 'debit': 1000.0, 'credit': 0.0, }), (0, None, { 'name': 'move 1 counterpart line', 'account_id': self.company_data['default_account_expense'].id, 'debit': 0.0, 'credit': 1000.0, }), ] }, { 'move_type': 'entry', 'line_ids': [ (0, None, { 'name': 'move 2 receivable line', 'account_id': self.company_data['default_account_receivable'].id, 'debit': 0.0, 'credit': 2000.0, }), (0, None, { 'name': 'move 2 counterpart line', 'account_id': self.company_data['default_account_expense'].id, 'debit': 2000.0, 'credit': 0.0, }), ] }, ]) # lines[0] = 'move 2 receivable line' # lines[1] = 'move 1 counterpart line' # lines[2] = 'move 1 receivable line' # lines[3] = 'move 2 counterpart line' draft_moves.action_post() lines = draft_moves.mapped('line_ids').sorted('balance') (lines[0] + lines[2]).reconcile() # You can't write something impacting the reconciliation on an already reconciled line. with self.assertRaises(UserError), self.cr.savepoint(): draft_moves[0].write({ 'line_ids': [ (1, lines[1].id, {'credit': lines[1].credit + 100.0}), (1, lines[2].id, {'debit': lines[2].debit + 100.0}), ] }) # The write must not raise anything because the rounding of the monetary field should ignore such tiny amount. draft_moves[0].write({ 'line_ids': [ (1, lines[1].id, {'credit': lines[1].credit + 0.0000001}), (1, lines[2].id, {'debit': lines[2].debit + 0.0000001}), ] }) # You can't unlink an already reconciled line. with self.assertRaises(UserError), self.cr.savepoint(): draft_moves.unlink() def test_misc_always_balanced_move(self): ''' Ensure there is no way to make ''' # You can't remove a journal item making the journal entry unbalanced. with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.line_ids[0].unlink() # Same check using write instead of unlink. with self.assertRaises(UserError), self.cr.savepoint(): balance = self.test_move.line_ids[0].balance + 5 self.test_move.line_ids[0].write({ 'debit': balance if balance > 0.0 else 0.0, 'credit': -balance if balance < 0.0 else 0.0, }) # You can remove journal items if the related journal entry is still balanced. self.test_move.line_ids.unlink() def test_add_followers_on_post(self): # Add some existing partners, some from another company company = self.env['res.company'].create({'name': 'Oopo'}) company.flush() existing_partners = self.env['res.partner'].create([{ 'name': 'Jean', 'company_id': company.id, },{ 'name': 'Paulus', }]) self.test_move.message_subscribe(existing_partners.ids) user = new_test_user(self.env, login='jag', groups='account.group_account_invoice') move = self.test_move.with_user(user) partner = self.env['res.partner'].create({'name': 'Belouga'}) move.partner_id = partner move.action_post() self.assertEqual(move.message_partner_ids, self.env.user.partner_id | existing_partners | partner) def test_misc_move_onchange(self): ''' Test the behavior on onchanges for account.move having 'entry' as type. ''' move_form = Form(self.env['account.move']) # Rate 1:3 move_form.date = fields.Date.from_string('2016-01-01') # New line that should get 400.0 as debit. with move_form.line_ids.new() as line_form: line_form.name = 'debit_line' line_form.account_id = self.company_data['default_account_revenue'] line_form.currency_id = self.currency_data['currency'] line_form.amount_currency = 1200.0 # New line that should get 400.0 as credit. with move_form.line_ids.new() as line_form: line_form.name = 'credit_line' line_form.account_id = self.company_data['default_account_revenue'] line_form.currency_id = self.currency_data['currency'] line_form.amount_currency = -1200.0 move = move_form.save() self.assertRecordValues( move.line_ids.sorted('debit'), [ { 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1200.0, 'debit': 0.0, 'credit': 400.0, }, { 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1200.0, 'debit': 400.0, 'credit': 0.0, }, ], ) # === Change the date to change the currency conversion's rate === with Form(move) as move_form: move_form.date = fields.Date.from_string('2017-01-01') self.assertRecordValues( move.line_ids.sorted('debit'), [ { 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1200.0, 'debit': 0.0, 'credit': 600.0, }, { 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1200.0, 'debit': 600.0, 'credit': 0.0, }, ], ) def test_included_tax(self): ''' Test an account.move.line is created automatically when adding a tax. This test uses the following scenario: - Create manually a debit line of 1000 having an included tax. - Assume a line containing the tax amount is created automatically. - Create manually a credit line to balance the two previous lines. - Save the move. included tax = 20% Name | Debit | Credit | Tax_ids | Tax_line_id's name -----------------------|-----------|-----------|---------------|------------------- debit_line_1 | 1000 | | tax | included_tax_line | 200 | | | included_tax_line credit_line_1 | | 1200 | | ''' self.included_percent_tax = self.env['account.tax'].create({ 'name': 'included_tax_line', 'amount_type': 'percent', 'amount': 20, 'price_include': True, 'include_base_amount': False, }) self.account = self.company_data['default_account_revenue'] move_form = Form(self.env['account.move'].with_context(default_move_type='entry')) # Create a new account.move.line with debit amount. with move_form.line_ids.new() as debit_line: debit_line.name = 'debit_line_1' debit_line.account_id = self.account debit_line.debit = 1000 debit_line.tax_ids.clear() debit_line.tax_ids.add(self.included_percent_tax) self.assertTrue(debit_line.recompute_tax_line) # Create a third account.move.line with credit amount. with move_form.line_ids.new() as credit_line: credit_line.name = 'credit_line_1' credit_line.account_id = self.account credit_line.credit = 1200 move = move_form.save() self.assertRecordValues(move.line_ids, [ {'name': 'debit_line_1', 'debit': 1000.0, 'credit': 0.0, 'tax_ids': [self.included_percent_tax.id], 'tax_line_id': False}, {'name': 'included_tax_line', 'debit': 200.0, 'credit': 0.0, 'tax_ids': [], 'tax_line_id': self.included_percent_tax.id}, {'name': 'credit_line_1', 'debit': 0.0, 'credit': 1200.0, 'tax_ids': [], 'tax_line_id': False}, ]) def test_misc_prevent_unlink_posted_items(self): # You cannot remove journal items if the related journal entry is posted. self.test_move.action_post() with self.assertRaises(UserError), self.cr.savepoint(): self.test_move.line_ids.unlink() # You can remove journal items if the related journal entry is draft. self.test_move.button_draft() self.test_move.line_ids.unlink() def test_account_move_inactive_currency_raise_error_on_post(self): """ Ensure a move cannot be posted when using an inactive currency """ move = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [{}] }) move.currency_id.active = False with self.assertRaises(UserError), self.cr.savepoint(): move.action_post() # Make sure that the invoice can still be posted when the currency is active move.action_activate_currency() move.action_post() self.assertEqual(move.state, 'posted') def test_invoice_like_entry_reverse_caba(self): tax_waiting_account = self.env['account.account'].create({ 'name': 'TAX_WAIT', 'code': 'TWAIT', 'user_type_id': self.env.ref('account.data_account_type_current_liabilities').id, 'reconcile': True, 'company_id': self.company_data['company'].id, }) tax_final_account = self.env['account.account'].create({ 'name': 'TAX_TO_DEDUCT', 'code': 'TDEDUCT', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) tax_base_amount_account = self.env['account.account'].create({ 'name': 'TAX_BASE', 'code': 'TBASE', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) self.env.company.account_cash_basis_base_account_id = tax_base_amount_account self.env.company.tax_exigibility = True tax_tags = defaultdict(dict) for line_type, repartition_type in [(l, r) for l in ('invoice', 'refund') for r in ('base', 'tax')]: tax_tags[line_type][repartition_type] = self.env['account.account.tag'].create({ 'name': '%s %s tag' % (line_type, repartition_type), 'applicability': 'taxes', 'country_id': self.env.ref('base.us').id, }) tax = self.env['account.tax'].create({ 'name': 'cash basis 10%', 'type_tax_use': 'sale', 'amount': 10, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': tax_waiting_account.id, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['invoice']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['invoice']['tax'].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['refund']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['refund']['tax'].ids)], }), ], }) move = self.env['account.move'].create({ 'move_type': 'entry', 'date': fields.Date.from_string('2016-01-01'), 'line_ids': [ (0, None, { 'name': 'revenue line', 'account_id': self.company_data['default_account_revenue'].id, 'debit': 0.0, 'credit': 1000.0, 'tax_ids': [(6, 0, tax.ids)], 'tax_tag_ids': [(6, 0, tax_tags['invoice']['base'].ids)], }), (0, None, { 'name': 'tax line 1', 'account_id': tax_waiting_account.id, 'debit': 0.0, 'credit': 100.0, 'tax_tag_ids': [(6, 0, tax_tags['invoice']['tax'].ids)], 'tax_repartition_line_id': tax.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, }), (0, None, { 'name': 'counterpart line', 'account_id': self.company_data['default_account_receivable'].id, 'debit': 1100.0, 'credit': 0.0, }), ] }) move.action_post() # make payment payment = self.env['account.payment'].create({ 'payment_type': 'inbound', 'payment_method_id': self.env.ref('account.account_payment_method_manual_in').id, 'partner_type': 'customer', 'partner_id': self.partner_a.id, 'amount': 1100, 'date': move.date, 'journal_id': self.company_data['default_journal_bank'].id, }) payment.action_post() (payment.move_id + move).line_ids.filtered(lambda x: x.account_id == self.company_data['default_account_receivable']).reconcile() # check caba move partial_rec = move.mapped('line_ids.matched_credit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) expected_values = [ { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_base_amount_account.id, 'debit': 1000.0, 'credit': 0.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': tax.ids, 'tax_tag_ids': tax_tags['invoice']['base'].ids, 'account_id': tax_base_amount_account.id, 'debit': 0.0, 'credit': 1000.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_waiting_account.id, 'debit': 100.0, 'credit': 0.0, }, { 'tax_line_id': tax.id, 'tax_repartition_line_id': tax.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_ids': [], 'tax_tag_ids': tax_tags['invoice']['tax'].ids, 'account_id': tax_final_account.id, 'debit': 0.0, 'credit': 100.0, }, ] self.assertRecordValues(caba_move.line_ids, expected_values) # unreconcile debit_aml = move.line_ids.filtered('debit') debit_aml.remove_move_reconcile() # check caba move reverse is same as caba move with only debit/credit inverted reversed_caba_move = self.env['account.move'].search([('reversed_entry_id', '=', caba_move.id)]) for value in expected_values: value.update({ 'debit': value['credit'], 'credit': value['debit'], }) self.assertRecordValues(reversed_caba_move.line_ids, expected_values) def _get_cache_count(self, model_name='account.move', field_name='name'): model = self.env[model_name] field = model._fields[field_name] return len(self.env.cache.get_records(model, field)) def test_cache_invalidation(self): self.env['account.move'].invalidate_cache() lines = self.test_move.line_ids # prefetch lines.mapped('move_id.name') # check account.move cache self.assertEqual(self._get_cache_count(), 1) self.env['account.move.line'].invalidate_cache(ids=lines.ids) self.assertEqual(self._get_cache_count(), 0) def test_misc_prevent_edit_tax_on_posted_moves(self): # You cannot remove journal items if the related journal entry is posted. self.test_move.action_post() with self.assertRaisesRegex(UserError, "You cannot modify the taxes related to a posted journal item"),\ self.cr.savepoint(): self.test_move.line_ids.filtered(lambda l: l.tax_ids).tax_ids = False with self.assertRaisesRegex(UserError, "You cannot modify the taxes related to a posted journal item"),\ self.cr.savepoint(): self.test_move.line_ids.filtered(lambda l: l.tax_line_id).tax_line_id = False # You can remove journal items if the related journal entry is draft. self.test_move.button_draft() self.assertTrue(self.test_move.line_ids.unlink())
41.834512
29,577
1,270
py
PYTHON
15.0
# Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import Command import odoo.tests @odoo.tests.tagged('post_install_l10n', 'post_install', '-at_install') class TestUi(odoo.tests.HttpCase): def test_01_account_tour(self): # Reset country and fiscal country, so that fields added by localizations are # hidden and non-required, and don't make the tour crash. # Also remove default taxes from the company and its accounts, to avoid inconsistencies # with empty fiscal country. self.env.company.write({ 'country_id': None, # Also resets account_fiscal_country_id 'account_sale_tax_id': None, 'account_purchase_tax_id': None, }) account_with_taxes = self.env['account.account'].search([('tax_ids', '!=', False), ('company_id', '=', self.env.company.id)]) account_with_taxes.write({ 'tax_ids': [Command.clear()], }) # This tour doesn't work with demo data on runbot all_moves = self.env['account.move'].search([('move_type', '!=', 'entry')]) all_moves.button_draft() all_moves.with_context(force_delete=True).unlink() self.start_tour("/web", 'account_tour', login="admin")
45.357143
1,270
43,185
py
PYTHON
15.0
# -*- coding: utf-8 -*- # pylint: disable=bad-whitespace from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests.common import Form from odoo.tests import tagged from odoo import fields, Command from collections import defaultdict @tagged('post_install', '-at_install') class TestAccountMoveInRefundOnchanges(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.invoice = cls.init_invoice('in_refund', products=cls.product_a+cls.product_b) cls.product_line_vals_1 = { 'name': cls.product_a.name, 'product_id': cls.product_a.id, 'account_id': cls.product_a.property_account_expense_id.id, 'partner_id': cls.partner_a.id, 'product_uom_id': cls.product_a.uom_id.id, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 800.0, 'price_subtotal': 800.0, 'price_total': 920.0, 'tax_ids': cls.product_a.supplier_taxes_id.ids, 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -800.0, 'debit': 0.0, 'credit': 800.0, 'date_maturity': False, } cls.product_line_vals_2 = { 'name': cls.product_b.name, 'product_id': cls.product_b.id, 'account_id': cls.product_b.property_account_expense_id.id, 'partner_id': cls.partner_a.id, 'product_uom_id': cls.product_b.uom_id.id, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 160.0, 'price_subtotal': 160.0, 'price_total': 208.0, 'tax_ids': cls.product_b.supplier_taxes_id.ids, 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -160.0, 'debit': 0.0, 'credit': 160.0, 'date_maturity': False, } cls.tax_line_vals_1 = { 'name': cls.tax_purchase_a.name, 'product_id': False, 'account_id': cls.company_data['default_account_tax_purchase'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 144.0, 'price_subtotal': 144.0, 'price_total': 144.0, 'tax_ids': [], 'tax_line_id': cls.tax_purchase_a.id, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -144.0, 'debit': 0.0, 'credit': 144.0, 'date_maturity': False, } cls.tax_line_vals_2 = { 'name': cls.tax_purchase_b.name, 'product_id': False, 'account_id': cls.company_data['default_account_tax_purchase'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 24.0, 'price_subtotal': 24.0, 'price_total': 24.0, 'tax_ids': [], 'tax_line_id': cls.tax_purchase_b.id, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -24.0, 'debit': 0.0, 'credit': 24.0, 'date_maturity': False, } cls.term_line_vals_1 = { 'name': '', 'product_id': False, 'account_id': cls.company_data['default_account_payable'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -1128.0, 'price_subtotal': -1128.0, 'price_total': -1128.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 1128.0, 'debit': 1128.0, 'credit': 0.0, 'date_maturity': fields.Date.from_string('2019-01-01'), } cls.move_vals = { 'partner_id': cls.partner_a.id, 'currency_id': cls.company_data['currency'].id, 'journal_id': cls.company_data['default_journal_purchase'].id, 'date': fields.Date.from_string('2019-01-01'), 'fiscal_position_id': False, 'payment_reference': '', 'invoice_payment_term_id': cls.pay_terms_a.id, 'amount_untaxed': 960.0, 'amount_tax': 168.0, 'amount_total': 1128.0, } def setUp(self): super(TestAccountMoveInRefundOnchanges, self).setUp() self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) def test_in_refund_line_onchange_product_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.product_id = self.product_b move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'name': self.product_b.name, 'product_id': self.product_b.id, 'product_uom_id': self.product_b.uom_id.id, 'account_id': self.product_b.property_account_expense_id.id, 'price_unit': 160.0, 'price_subtotal': 160.0, 'price_total': 208.0, 'tax_ids': self.product_b.supplier_taxes_id.ids, 'amount_currency': -160.0, 'credit': 160.0, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 48.0, 'price_subtotal': 48.0, 'price_total': 48.0, 'amount_currency': -48.0, 'credit': 48.0, }, { **self.tax_line_vals_2, 'price_unit': 48.0, 'price_subtotal': 48.0, 'price_total': 48.0, 'amount_currency': -48.0, 'credit': 48.0, }, { **self.term_line_vals_1, 'price_unit': -416.0, 'price_subtotal': -416.0, 'price_total': -416.0, 'amount_currency': 416.0, 'debit': 416.0, }, ], { **self.move_vals, 'amount_untaxed': 320.0, 'amount_tax': 96.0, 'amount_total': 416.0, }) def test_in_refund_line_onchange_business_fields_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: # Current price_unit is 800. # We set quantity = 4, discount = 50%, price_unit = 400. The debit/credit fields don't change because (4 * 400) * 0.5 = 800. line_form.quantity = 4 line_form.discount = 50 line_form.price_unit = 400 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 4, 'discount': 50.0, 'price_unit': 400.0, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) move_form = Form(self.invoice) with move_form.line_ids.edit(2) as line_form: # Reset field except the discount that becomes 100%. # /!\ The modification is made on the accounting tab. line_form.quantity = 1 line_form.discount = 100 line_form.price_unit = 800 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'discount': 100.0, 'price_subtotal': 0.0, 'price_total': 0.0, 'amount_currency': 0.0, 'credit': 0.0, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 24.0, 'price_subtotal': 24.0, 'price_total': 24.0, 'amount_currency': -24.0, 'credit': 24.0, }, self.tax_line_vals_2, { **self.term_line_vals_1, 'price_unit': -208.0, 'price_subtotal': -208.0, 'price_total': -208.0, 'amount_currency': 208.0, 'debit': 208.0, }, ], { **self.move_vals, 'amount_untaxed': 160.0, 'amount_tax': 48.0, 'amount_total': 208.0, }) def test_in_refund_line_onchange_accounting_fields_1(self): move_form = Form(self.invoice) with move_form.line_ids.edit(2) as line_form: # Custom credit on the first product line. line_form.credit = 3000 with move_form.line_ids.edit(3) as line_form: # Custom debit on the second product line. Credit should be reset by onchange. # /!\ It's a negative line. line_form.debit = 500 with move_form.line_ids.edit(0) as line_form: # Custom credit on the first tax line. line_form.credit = 800 with move_form.line_ids.edit(4) as line_form: # Custom credit on the second tax line. line_form.credit = 250 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 3000.0, 'price_subtotal': 3000.0, 'price_total': 3450.0, 'amount_currency': -3000.0, 'credit': 3000.0, }, { **self.product_line_vals_2, 'price_unit': -500.0, 'price_subtotal': -500.0, 'price_total': -650.0, 'amount_currency': 500.0, 'debit': 500.0, 'credit': 0.0, }, { **self.tax_line_vals_1, 'price_unit': 800.0, 'price_subtotal': 800.0, 'price_total': 800.0, 'amount_currency': -800.0, 'credit': 800.0, }, { **self.tax_line_vals_2, 'price_unit': 250.0, 'price_subtotal': 250.0, 'price_total': 250.0, 'amount_currency': -250.0, 'credit': 250.0, }, { **self.term_line_vals_1, 'price_unit': -3550.0, 'price_subtotal': -3550.0, 'price_total': -3550.0, 'amount_currency': 3550.0, 'debit': 3550.0, }, ], { **self.move_vals, 'amount_untaxed': 2500.0, 'amount_tax': 1050.0, 'amount_total': 3550.0, }) def test_in_refund_line_onchange_partner_1(self): move_form = Form(self.invoice) move_form.partner_id = self.partner_b move_form.payment_reference = 'turlututu' move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'partner_id': self.partner_b.id, }, { **self.product_line_vals_2, 'partner_id': self.partner_b.id, }, { **self.tax_line_vals_1, 'partner_id': self.partner_b.id, }, { **self.tax_line_vals_2, 'partner_id': self.partner_b.id, }, { **self.term_line_vals_1, 'name': 'turlututu', 'partner_id': self.partner_b.id, 'account_id': self.partner_b.property_account_payable_id.id, 'price_unit': -338.4, 'price_subtotal': -338.4, 'price_total': -338.4, 'amount_currency': 338.4, 'debit': 338.4, }, { **self.term_line_vals_1, 'name': 'turlututu', 'partner_id': self.partner_b.id, 'account_id': self.partner_b.property_account_payable_id.id, 'price_unit': -789.6, 'price_subtotal': -789.6, 'price_total': -789.6, 'amount_currency': 789.6, 'debit': 789.6, 'date_maturity': fields.Date.from_string('2019-02-28'), }, ], { **self.move_vals, 'partner_id': self.partner_b.id, 'payment_reference': 'turlututu', 'fiscal_position_id': self.fiscal_pos_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'amount_untaxed': 960.0, 'amount_tax': 168.0, 'amount_total': 1128.0, }) # Remove lines and recreate them to apply the fiscal position. move_form = Form(self.invoice) move_form.invoice_line_ids.remove(0) move_form.invoice_line_ids.remove(0) with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_b move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'account_id': self.product_b.property_account_expense_id.id, 'partner_id': self.partner_b.id, 'tax_ids': self.tax_purchase_b.ids, }, { **self.product_line_vals_2, 'partner_id': self.partner_b.id, 'price_total': 184.0, 'tax_ids': self.tax_purchase_b.ids, }, { **self.tax_line_vals_1, 'name': self.tax_purchase_b.name, 'partner_id': self.partner_b.id, 'tax_line_id': self.tax_purchase_b.id, }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_payable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -331.2, 'price_subtotal': -331.2, 'price_total': -331.2, 'amount_currency': 331.2, 'debit': 331.2, }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_payable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -772.8, 'price_subtotal': -772.8, 'price_total': -772.8, 'amount_currency': 772.8, 'debit': 772.8, 'date_maturity': fields.Date.from_string('2019-02-28'), }, ], { **self.move_vals, 'partner_id': self.partner_b.id, 'payment_reference': 'turlututu', 'fiscal_position_id': self.fiscal_pos_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'amount_untaxed': 960.0, 'amount_tax': 144.0, 'amount_total': 1104.0, }) def test_in_refund_line_onchange_taxes_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 960 line_form.tax_ids.add(self.tax_armageddon) move_form.save() child_tax_1 = self.tax_armageddon.children_tax_ids[0] child_tax_2 = self.tax_armageddon.children_tax_ids[1] self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 960.0, 'price_subtotal': 800.0, 'price_total': 1176.0, 'tax_ids': (self.tax_purchase_a + self.tax_armageddon).ids, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, { 'name': child_tax_1.name, 'product_id': False, 'account_id': self.company_data['default_account_expense'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 96.0, 'price_subtotal': 96.0, 'price_total': 105.6, 'tax_ids': child_tax_2.ids, 'tax_line_id': child_tax_1.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': -96.0, 'debit': 0.0, 'credit': 96.0, 'date_maturity': False, }, { 'name': child_tax_1.name, 'product_id': False, 'account_id': self.company_data['default_account_tax_sale'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 64.0, 'price_subtotal': 64.0, 'price_total': 70.4, 'tax_ids': child_tax_2.ids, 'tax_line_id': child_tax_1.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': -64.0, 'debit': 0.0, 'credit': 64.0, 'date_maturity': False, }, { 'name': child_tax_2.name, 'product_id': False, 'account_id': child_tax_2.cash_basis_transition_account_id.id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 96.0, 'price_subtotal': 96.0, 'price_total': 96.0, 'tax_ids': [], 'tax_line_id': child_tax_2.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': -96.0, 'debit': 0.0, 'credit': 96.0, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -1384.0, 'price_subtotal': -1384.0, 'price_total': -1384.0, 'amount_currency': 1384.0, 'debit': 1384.0, }, ], { **self.move_vals, 'amount_untaxed': 960.0, 'amount_tax': 424.0, 'amount_total': 1384.0, }) def test_in_refund_line_onchange_cash_rounding_1(self): # Test 'add_invoice_line' rounding move_form = Form(self.invoice) # Add a cash rounding having 'add_invoice_line'. move_form.invoice_cash_rounding_id = self.cash_rounding_a move_form.save() # The cash rounding does nothing as the total is already rounded. self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 799.99 move_form.save() self.assertInvoiceValues(self.invoice, [ { 'name': 'add_invoice_line', 'product_id': False, 'account_id': self.cash_rounding_a.profit_account_id.id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 0.01, 'price_subtotal': 0.01, 'price_total': 0.01, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.company_data['currency'].id, 'amount_currency': -0.01, 'debit': 0.0, 'credit': 0.01, 'date_maturity': False, }, { **self.product_line_vals_1, 'price_unit': 799.99, 'price_subtotal': 799.99, 'price_total': 919.99, 'amount_currency': -799.99, 'credit': 799.99, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) # Test 'biggest_tax' rounding self.company_data['company'].country_id = self.env.ref('base.us') # Add a tag to product_a's default tax tax_line_tag = self.env['account.account.tag'].create({ 'name': "Tax tag", 'applicability': 'taxes', 'country_id': self.company_data['company'].country_id.id, }) repartition_line = self.tax_purchase_a.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') repartition_line.write({'tag_ids': [(4, tax_line_tag.id, 0)]}) # Create the invoice biggest_tax_invoice = self.env['account.move'].create({ 'move_type': 'in_refund', 'invoice_date': '2019-01-01', 'partner_id': self.partner_a.id, 'invoice_cash_rounding_id': self.cash_rounding_b.id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, 0, { 'product_id': self.product_a.id, 'price_unit': 799.99, 'tax_ids': [(6, 0, self.product_a.supplier_taxes_id.ids)], 'product_uom_id': self.product_a.uom_id.id, }), (0, 0, { 'product_id': self.product_b.id, 'price_unit': self.product_b.standard_price, 'tax_ids': [(6, 0, self.product_b.supplier_taxes_id.ids)], 'product_uom_id': self.product_b.uom_id.id, }), ], }) self.assertInvoiceValues(biggest_tax_invoice, [ { **self.product_line_vals_1, 'price_unit': 799.99, 'price_subtotal': 799.99, 'price_total': 919.99, 'amount_currency': -799.99, 'credit': 799.99, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { **self.product_line_vals_2, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { **self.tax_line_vals_1, 'tax_repartition_line_id': repartition_line.id, 'tax_tag_ids': tax_line_tag.ids, }, { **self.tax_line_vals_2, 'tax_repartition_line_id': self.tax_purchase_b.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_tag_ids': [], }, { 'name': '%s (rounding)' % self.tax_purchase_a.name, 'product_id': False, 'account_id': self.company_data['default_account_tax_purchase'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -0.04, 'price_subtotal': -0.04, 'price_total': -0.04, 'tax_ids': [], 'tax_line_id': self.tax_purchase_a.id, 'tax_repartition_line_id': repartition_line.id, 'tax_tag_ids': tax_line_tag.ids, 'currency_id': self.company_data['currency'].id, 'amount_currency': 0.04, 'debit': 0.04, 'credit': 0.0, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -1127.95, 'price_subtotal': -1127.95, 'price_total': -1127.95, 'amount_currency': 1127.95, 'debit': 1127.95, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, ], { **self.move_vals, 'amount_untaxed': 959.99, 'amount_tax': 167.96, 'amount_total': 1127.95, }) def test_in_refund_line_onchange_currency_1(self): move_form = Form(self.invoice) move_form.currency_id = self.currency_data['currency'] move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -800.0, 'credit': 400.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -160.0, 'credit': 80.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -144.0, 'credit': 72.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.0, 'credit': 12.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1128.0, 'debit': 564.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) move_form = Form(self.invoice) # Change the date to get another rate: 1/3 instead of 1/2. move_form.date = fields.Date.from_string('2016-01-01') move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -800.0, 'credit': 266.67, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -160.0, 'credit': 53.33, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -144.0, 'credit': 48.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.0, 'credit': 8.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1128.0, 'debit': 376.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), }) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: # 0.045 * 0.1 = 0.0045. As the foreign currency has a 0.001 rounding, # the result should be 0.005 after rounding. line_form.quantity = 0.1 line_form.price_unit = 0.045 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 0.1, 'price_unit': 0.05, 'price_subtotal': 0.005, 'price_total': 0.006, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -0.005, 'credit': 0.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -160.0, 'credit': 53.33, }, { **self.tax_line_vals_1, 'price_unit': 24.0, 'price_subtotal': 24.001, 'price_total': 24.001, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.001, 'credit': 8.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.0, 'credit': 8.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'price_unit': -208.01, 'price_subtotal': -208.006, 'price_total': -208.006, 'amount_currency': 208.006, 'debit': 69.33, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), 'amount_untaxed': 160.005, 'amount_tax': 48.001, 'amount_total': 208.006, }) # Exit the multi-currencies. move_form = Form(self.invoice) move_form.currency_id = self.company_data['currency'] move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 0.1, 'price_unit': 0.05, 'price_subtotal': 0.01, 'price_total': 0.01, 'amount_currency': -0.01, 'credit': 0.01, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 24.0, 'price_subtotal': 24.0, 'price_total': 24.0, 'amount_currency': -24.0, 'credit': 24.0, }, self.tax_line_vals_2, { **self.term_line_vals_1, 'price_unit': -208.01, 'price_subtotal': -208.01, 'price_total': -208.01, 'amount_currency': 208.01, 'debit': 208.01, }, ], { **self.move_vals, 'currency_id': self.company_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), 'amount_untaxed': 160.01, 'amount_tax': 48.0, 'amount_total': 208.01, }) def test_in_refund_onchange_past_invoice_1(self): copy_invoice = self.invoice.copy() move_form = Form(self.invoice) move_form.invoice_line_ids.remove(0) move_form.invoice_line_ids.remove(0) move_form.invoice_vendor_bill_id = copy_invoice move_form.save() self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) def test_in_refund_create_1(self): # Test creating an account_move with the least information. move = self.env['account.move'].create({ 'move_type': 'in_refund', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -800.0, 'credit': 400.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -160.0, 'credit': 80.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -144.0, 'credit': 72.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.0, 'credit': 12.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1128.0, 'debit': 564.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_in_refund_write_1(self): # Test creating an account_move with the least information. move = self.env['account.move'].create({ 'move_type': 'in_refund', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), ], }) move.write({ 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -800.0, 'credit': 400.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -160.0, 'credit': 80.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -144.0, 'credit': 72.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -24.0, 'credit': 12.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1128.0, 'debit': 564.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_in_refund_reverse_caba(self): tax_waiting_account = self.env['account.account'].create({ 'name': 'TAX_WAIT', 'code': 'TWAIT', 'user_type_id': self.env.ref('account.data_account_type_current_liabilities').id, 'reconcile': True, 'company_id': self.company_data['company'].id, }) tax_final_account = self.env['account.account'].create({ 'name': 'TAX_TO_DEDUCT', 'code': 'TDEDUCT', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) tax_base_amount_account = self.env['account.account'].create({ 'name': 'TAX_BASE', 'code': 'TBASE', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) self.env.company.account_cash_basis_base_account_id = tax_base_amount_account self.env.company.tax_exigibility = True tax_tags = defaultdict(dict) for line_type, repartition_type in [(l, r) for l in ('invoice', 'refund') for r in ('base', 'tax')]: tax_tags[line_type][repartition_type] = self.env['account.account.tag'].create({ 'name': '%s %s tag' % (line_type, repartition_type), 'applicability': 'taxes', 'country_id': self.env.ref('base.us').id, }) tax = self.env['account.tax'].create({ 'name': 'cash basis 10%', 'type_tax_use': 'purchase', 'amount': 10, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': tax_waiting_account.id, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['invoice']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['invoice']['tax'].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['refund']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['refund']['tax'].ids)], }), ], }) # create invoice move_form = Form(self.env['account.move'].with_context(default_move_type='in_refund')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2017-01-01') with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a line_form.tax_ids.clear() line_form.tax_ids.add(tax) invoice = move_form.save() invoice.action_post() # make payment self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({ 'payment_date': invoice.date, })._create_payments() # check caba move partial_rec = invoice.mapped('line_ids.matched_credit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) expected_values = [ { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_base_amount_account.id, 'debit': 800.0, 'credit': 0.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': tax.ids, 'tax_tag_ids': tax_tags['refund']['base'].ids, 'account_id': tax_base_amount_account.id, 'debit': 0.0, 'credit': 800.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_waiting_account.id, 'debit': 80.0, 'credit': 0.0, }, { 'tax_line_id': tax.id, 'tax_repartition_line_id': tax.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_ids': [], 'tax_tag_ids': tax_tags['refund']['tax'].ids, 'account_id': tax_final_account.id, 'debit': 0.0, 'credit': 80.0, }, ] self.assertRecordValues(caba_move.line_ids, expected_values) # unreconcile debit_aml = invoice.line_ids.filtered('debit') debit_aml.remove_move_reconcile() # check caba move reverse is same as caba move with only debit/credit inverted reversed_caba_move = self.env['account.move'].search([('reversed_entry_id', '=', caba_move.id)]) for value in expected_values: value.update({ 'debit': value['credit'], 'credit': value['debit'], }) self.assertRecordValues(reversed_caba_move.line_ids, expected_values)
37.749126
43,185
56,300
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time import unittest from datetime import timedelta from odoo import api, fields from odoo.addons.account.tests.common import TestAccountReconciliationCommon from odoo.tests import Form, tagged @tagged('post_install', '-at_install') class TestReconciliationExec(TestAccountReconciliationCommon): @classmethod def setUpClass(cls): super().setUpClass() cls.env['res.currency.rate'].search([]).unlink() def test_statement_euro_invoice_usd_transaction_euro_full(self): self.env['res.currency.rate'].create({ 'name': '%s-07-01' % time.strftime('%Y'), 'rate': 1.5289, 'currency_id': self.currency_usd_id, }) # Create a customer invoice of 50 USD. partner = self.env['res.partner'].create({'name': 'test'}) move = self.env['account.move'].with_context(default_move_type='out_invoice').create({ 'move_type': 'out_invoice', 'partner_id': partner.id, 'invoice_date': '%s-07-01' % time.strftime('%Y'), 'date': '%s-07-01' % time.strftime('%Y'), 'currency_id': self.currency_usd_id, 'invoice_line_ids': [ (0, 0, {'quantity': 1, 'price_unit': 50.0, 'name': 'test'}) ], }) move.action_post() # Create a bank statement of 40 EURO. bank_stmt = self.env['account.bank.statement'].create({ 'journal_id': self.bank_journal_euro.id, 'date': '%s-01-01' % time.strftime('%Y'), 'line_ids': [ (0, 0, { 'payment_ref': 'test', 'partner_id': partner.id, 'amount': 40.0, 'date': '%s-01-01' % time.strftime('%Y') }) ], }) # Reconcile the bank statement with the invoice. receivable_line = move.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) bank_stmt.button_post() bank_stmt.line_ids[0].reconcile([ {'id': receivable_line.id}, {'name': 'exchange difference', 'balance': -7.3, 'account_id': self.diff_income_account.id}, ]) self.assertRecordValues(bank_stmt.line_ids.line_ids, [ {'debit': 40.0, 'credit': 0.0, 'amount_currency': 40.0, 'currency_id': self.currency_euro_id}, {'debit': 0.0, 'credit': 7.3, 'amount_currency': -7.3, 'currency_id': self.currency_euro_id}, {'debit': 0.0, 'credit': 32.7, 'amount_currency': -32.7, 'currency_id': self.currency_euro_id}, ]) # The invoice should be paid, as the payments totally cover its total self.assertEqual(move.payment_state, 'paid', 'The invoice should be paid by now') self.assertTrue(receivable_line.reconciled, 'The invoice should be totally reconciled') self.assertTrue(receivable_line.full_reconcile_id, 'The invoice should have a full reconcile number') self.assertEqual(receivable_line.amount_residual, 0, 'The invoice should be totally reconciled') self.assertEqual(receivable_line.amount_residual_currency, 0, 'The invoice should be totally reconciled') @unittest.skip('adapt to new accounting') def test_balanced_exchanges_gain_loss(self): # The point of this test is to show that we handle correctly the gain/loss exchanges during reconciliations in foreign currencies. # For instance, with a company set in EUR, and a USD rate set to 0.033, # the reconciliation of an invoice of 2.00 USD (60.61 EUR) and a bank statement of two lines of 1.00 USD (30.30 EUR) # will lead to an exchange loss, that should be handled correctly within the journal items. env = api.Environment(self.cr, self.uid, {}) # We update the currency rate of the currency USD in order to force the gain/loss exchanges in next steps rateUSDbis = env.ref("base.rateUSDbis") rateUSDbis.write({ 'name': time.strftime('%Y-%m-%d') + ' 00:00:00', 'rate': 0.033, }) # We create a customer invoice of 2.00 USD invoice = self.account_invoice_model.create({ 'partner_id': self.partner_agrolait_id, 'currency_id': self.currency_usd_id, 'name': 'Foreign invoice with exchange gain', 'account_id': self.account_rcv_id, 'move_type': 'out_invoice', 'invoice_date': time.strftime('%Y-%m-%d'), 'date': time.strftime('%Y-%m-%d'), 'journal_id': self.bank_journal_usd_id, 'invoice_line': [ (0, 0, { 'name': 'line that will lead to an exchange gain', 'quantity': 1, 'price_unit': 2, }) ] }) invoice.action_post() # We create a bank statement with two lines of 1.00 USD each. statement = self.env['account.bank.statement'].create({ 'journal_id': self.bank_journal_usd_id, 'date': time.strftime('%Y-%m-%d'), 'line_ids': [ (0, 0, { 'name': 'half payment', 'partner_id': self.partner_agrolait_id, 'amount': 1.0, 'date': time.strftime('%Y-%m-%d') }), (0, 0, { 'name': 'second half payment', 'partner_id': self.partner_agrolait_id, 'amount': 1.0, 'date': time.strftime('%Y-%m-%d') }) ] }) # We process the reconciliation of the invoice line with the two bank statement lines line_id = None for l in invoice.line_id: if l.account_id.id == self.account_rcv_id: line_id = l break for statement_line in statement.line_ids: statement_line.reconcile([{'id': line_id.id}]) # The invoice should be paid, as the payments totally cover its total self.assertEqual(invoice.state, 'paid', 'The invoice should be paid by now') reconcile = None for payment in invoice.payment_ids: reconcile = payment.reconcile_model_id break # The invoice should be reconciled (entirely, not a partial reconciliation) self.assertTrue(reconcile, 'The invoice should be totally reconciled') result = {} exchange_loss_line = None for line in reconcile.line_id: res_account = result.setdefault(line.account_id, {'debit': 0.0, 'credit': 0.0, 'count': 0}) res_account['debit'] = res_account['debit'] + line.debit res_account['credit'] = res_account['credit'] + line.credit res_account['count'] += 1 if line.credit == 0.01: exchange_loss_line = line # We should be able to find a move line of 0.01 EUR on the Debtors account, being the cent we lost during the currency exchange self.assertTrue(exchange_loss_line, 'There should be one move line of 0.01 EUR in credit') # The journal items of the reconciliation should have their debit and credit total equal # Besides, the total debit and total credit should be 60.61 EUR (2.00 USD) self.assertEqual(sum(res['debit'] for res in result.values()), 60.61) self.assertEqual(sum(res['credit'] for res in result.items()), 60.61) counterpart_exchange_loss_line = None for line in exchange_loss_line.move_id.line_id: if line.account_id.id == self.account_fx_expense_id: counterpart_exchange_loss_line = line # We should be able to find a move line of 0.01 EUR on the Foreign Exchange Loss account self.assertTrue(counterpart_exchange_loss_line, 'There should be one move line of 0.01 EUR on account "Foreign Exchange Loss"') def test_manual_reconcile_wizard_opw678153(self): def create_move(name, amount, amount_currency, currency_id): debit_line_vals = { 'name': name, 'debit': amount > 0 and amount or 0.0, 'credit': amount < 0 and -amount or 0.0, 'account_id': self.account_rcv.id, 'amount_currency': amount_currency, 'currency_id': currency_id, } credit_line_vals = debit_line_vals.copy() credit_line_vals['debit'] = debit_line_vals['credit'] credit_line_vals['credit'] = debit_line_vals['debit'] credit_line_vals['account_id'] = self.account_rsa.id credit_line_vals['amount_currency'] = -debit_line_vals['amount_currency'] vals = { 'journal_id': self.bank_journal_euro.id, 'line_ids': [(0,0, debit_line_vals), (0, 0, credit_line_vals)] } move = self.env['account.move'].create(vals) move.action_post() return move.id move_list_vals = [ ('1', -1.83, 0, self.currency_swiss_id), ('2', 728.35, 795.05, self.currency_swiss_id), ('3', -4.46, 0, self.currency_swiss_id), ('4', 0.32, 0, self.currency_swiss_id), ('5', 14.72, 16.20, self.currency_swiss_id), ('6', -737.10, -811.25, self.currency_swiss_id), ] move_ids = [] for name, amount, amount_currency, currency_id in move_list_vals: move_ids.append(create_move(name, amount, amount_currency, currency_id)) aml_recs = self.env['account.move.line'].search([('move_id', 'in', move_ids), ('account_id', '=', self.account_rcv.id), ('reconciled', '=', False)]) aml_recs.reconcile() for aml in aml_recs: self.assertTrue(aml.reconciled, 'The journal item should be totally reconciled') self.assertEqual(aml.amount_residual, 0, 'The journal item should be totally reconciled') self.assertEqual(aml.amount_residual_currency, 0, 'The journal item should be totally reconciled') def test_partial_reconcile_currencies_01(self): # client Account (payable, rsa) # Debit Credit # -------------------------------------------------------- # Pay a : 25/0.5 = 50 | Inv a : 50/0.5 = 100 # Pay b: 50/0.75 = 66.66 | Inv b : 50/0.75 = 66.66 # Pay c: 25/0.8 = 31.25 | # # Debit_currency = 100 | Credit currency = 100 # Debit = 147.91 | Credit = 166.66 # Balance Debit = 18.75 # Counterpart Credit goes in Exchange diff dest_journal_id = self.env['account.journal'].create({ 'name': 'dest_journal_id', 'type': 'bank', }) # Setting up rates for USD (main_company is in EUR) self.env['res.currency.rate'].create({'name': time.strftime('%Y') + '-' + '07' + '-01', 'rate': 0.5, 'currency_id': self.currency_usd_id, 'company_id': self.company.id}) self.env['res.currency.rate'].create({'name': time.strftime('%Y') + '-' + '08' + '-01', 'rate': 0.75, 'currency_id': self.currency_usd_id, 'company_id': self.company.id}) self.env['res.currency.rate'].create({'name': time.strftime('%Y') + '-' + '09' + '-01', 'rate': 0.80, 'currency_id': self.currency_usd_id, 'company_id': self.company.id}) # Preparing Invoices (from vendor) invoice_a = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'partner_id': self.partner_agrolait_id, 'currency_id': self.currency_usd_id, 'invoice_date': '%s-07-01' % time.strftime('%Y'), 'date': '%s-07-01' % time.strftime('%Y'), 'invoice_line_ids': [ (0, 0, {'product_id': self.product.id, 'quantity': 1, 'price_unit': 50.0}) ], }) invoice_b = self.env['account.move'].with_context(default_move_type='in_invoice').create({ 'move_type': 'in_invoice', 'partner_id': self.partner_agrolait_id, 'currency_id': self.currency_usd_id, 'invoice_date': '%s-08-01' % time.strftime('%Y'), 'date': '%s-08-01' % time.strftime('%Y'), 'invoice_line_ids': [ (0, 0, {'product_id': self.product.id, 'quantity': 1, 'price_unit': 50.0}) ], }) (invoice_a + invoice_b).action_post() # Preparing Payments # One partial for invoice_a (fully assigned to it) payment_a = self.env['account.payment'].create({'payment_type': 'outbound', 'amount': 25, 'currency_id': self.currency_usd_id, 'journal_id': self.bank_journal_euro.id, 'company_id': self.company.id, 'date': time.strftime('%Y') + '-' + '07' + '-01', 'partner_id': self.partner_agrolait_id, 'payment_method_line_id': self.inbound_payment_method_line.id, 'partner_type': 'supplier'}) # One that will complete the payment of a, the rest goes to b payment_b = self.env['account.payment'].create({'payment_type': 'outbound', 'amount': 50, 'currency_id': self.currency_usd_id, 'journal_id': self.bank_journal_euro.id, 'company_id': self.company.id, 'date': time.strftime('%Y') + '-' + '08' + '-01', 'partner_id': self.partner_agrolait_id, 'payment_method_line_id': self.outbound_payment_method_line.id, 'partner_type': 'supplier'}) # The last one will complete the payment of b payment_c = self.env['account.payment'].create({'payment_type': 'outbound', 'amount': 25, 'currency_id': self.currency_usd_id, 'journal_id': self.bank_journal_euro.id, 'company_id': self.company.id, 'date': time.strftime('%Y') + '-' + '09' + '-01', 'partner_id': self.partner_agrolait_id, 'payment_method_line_id': self.outbound_payment_method_line.id, 'partner_type': 'supplier'}) payment_a.action_post() payment_b.action_post() payment_c.action_post() # Assigning payments to invoices debit_line_a = payment_a.line_ids.filtered(lambda l: l.debit and l.account_id == self.account_rsa) debit_line_b = payment_b.line_ids.filtered(lambda l: l.debit and l.account_id == self.account_rsa) debit_line_c = payment_c.line_ids.filtered(lambda l: l.debit and l.account_id == self.account_rsa) invoice_a.js_assign_outstanding_line(debit_line_a.id) invoice_a.js_assign_outstanding_line(debit_line_b.id) invoice_b.js_assign_outstanding_line(debit_line_b.id) invoice_b.js_assign_outstanding_line(debit_line_c.id) # Asserting correctness (only in the payable account) full_reconcile = False reconciled_amls = (debit_line_a + debit_line_b + debit_line_c + (invoice_a + invoice_b).mapped('line_ids'))\ .filtered(lambda l: l.account_id == self.account_rsa) for aml in reconciled_amls: self.assertEqual(aml.amount_residual, 0.0) self.assertEqual(aml.amount_residual_currency, 0.0) self.assertTrue(aml.reconciled) if not full_reconcile: full_reconcile = aml.full_reconcile_id else: self.assertTrue(aml.full_reconcile_id == full_reconcile) full_rec_move = full_reconcile.exchange_move_id # Globally check whether the amount is correct self.assertEqual(sum(full_rec_move.mapped('line_ids.debit')), 18.75) # Checking if the direction of the move is correct full_rec_payable = full_rec_move.line_ids.filtered(lambda l: l.account_id == self.account_rsa) self.assertEqual(full_rec_payable.balance, 18.75) def test_unreconcile(self): # Use case: # 2 invoices paid with a single payment. Unreconcile the payment with one invoice, the # other invoice should remain reconciled. inv1 = self.create_invoice(invoice_amount=10, currency_id=self.currency_usd_id) inv2 = self.create_invoice(invoice_amount=20, currency_id=self.currency_usd_id) payment = self.env['account.payment'].create({ 'payment_type': 'inbound', 'payment_method_line_id': self.inbound_payment_method_line.id, 'partner_type': 'customer', 'partner_id': self.partner_agrolait_id, 'amount': 100, 'currency_id': self.currency_usd_id, 'journal_id': self.bank_journal_usd.id, }) payment.action_post() credit_aml = payment.line_ids.filtered('credit') # Check residual before assignation self.assertAlmostEqual(inv1.amount_residual, 10) self.assertAlmostEqual(inv2.amount_residual, 20) # Assign credit and residual inv1.js_assign_outstanding_line(credit_aml.id) inv2.js_assign_outstanding_line(credit_aml.id) self.assertAlmostEqual(inv1.amount_residual, 0) self.assertAlmostEqual(inv2.amount_residual, 0) # Unreconcile one invoice at a time and check residual credit_aml.remove_move_reconcile() self.assertAlmostEqual(inv1.amount_residual, 10) self.assertAlmostEqual(inv2.amount_residual, 20) def test_unreconcile_exchange(self): # Use case: # - Company currency in EUR # - Create 2 rates for USD: # 1.0 on 2018-01-01 # 0.5 on 2018-02-01 # - Create an invoice on 2018-01-02 of 111 USD # - Register a payment on 2018-02-02 of 111 USD # - Unreconcile the payment self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_usd_id, 'company_id': self.company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-08-01', 'rate': 0.5, 'currency_id': self.currency_usd_id, 'company_id': self.company.id }) inv = self.create_invoice(invoice_amount=111, currency_id=self.currency_usd_id) payment = self.env['account.payment'].create({ 'payment_type': 'inbound', 'payment_method_line_id': self.inbound_payment_method_line.id, 'partner_type': 'customer', 'partner_id': self.partner_agrolait_id, 'amount': 111, 'currency_id': self.currency_usd_id, 'journal_id': self.bank_journal_usd.id, 'date': time.strftime('%Y') + '-08-01', }) payment.action_post() credit_aml = payment.line_ids.filtered('credit') # Check residual before assignation self.assertAlmostEqual(inv.amount_residual, 111) # Assign credit, check exchange move and residual inv.js_assign_outstanding_line(credit_aml.id) self.assertEqual(len(payment.line_ids.mapped('full_reconcile_id').exchange_move_id), 1) self.assertAlmostEqual(inv.amount_residual, 0) # Unreconcile invoice and check residual credit_aml.remove_move_reconcile() self.assertAlmostEqual(inv.amount_residual, 111) def test_revert_payment_and_reconcile(self): payment = self.env['account.payment'].create({ 'payment_method_line_id': self.inbound_payment_method_line.id, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': self.partner_agrolait_id, 'journal_id': self.bank_journal_usd.id, 'date': '2018-06-04', 'amount': 666, }) payment.action_post() self.assertEqual(len(payment.line_ids), 2) bank_line = payment.line_ids.filtered(lambda l: l.account_id.id == self.bank_journal_usd.company_id.account_journal_payment_debit_account_id.id) customer_line = payment.line_ids - bank_line self.assertEqual(len(bank_line), 1) self.assertEqual(len(customer_line), 1) self.assertNotEqual(bank_line.id, customer_line.id) self.assertEqual(bank_line.move_id.id, customer_line.move_id.id) move = bank_line.move_id # Reversing the payment's move reversed_move = move._reverse_moves([{'date': '2018-06-04'}]) self.assertEqual(len(reversed_move), 1) self.assertEqual(len(reversed_move.line_ids), 2) # Testing the reconciliation matching between the move lines and their reversed counterparts reversed_bank_line = reversed_move.line_ids.filtered(lambda l: l.account_id.id == self.bank_journal_usd.company_id.account_journal_payment_debit_account_id.id) reversed_customer_line = reversed_move.line_ids - reversed_bank_line self.assertEqual(len(reversed_bank_line), 1) self.assertEqual(len(reversed_customer_line), 1) self.assertNotEqual(reversed_bank_line.id, reversed_customer_line.id) self.assertEqual(reversed_bank_line.move_id.id, reversed_customer_line.move_id.id) self.assertEqual(reversed_bank_line.full_reconcile_id.id, bank_line.full_reconcile_id.id) self.assertEqual(reversed_customer_line.full_reconcile_id.id, customer_line.full_reconcile_id.id) def test_revert_payment_and_reconcile_exchange(self): # A reversal of a reconciled payment which created a currency exchange entry, should create reversal moves # which move lines should be reconciled two by two with the original move's lines def _determine_debit_credit_line(move): line_ids_reconciliable = move.line_ids.filtered(lambda l: l.account_id.reconcile or l.account_id.internal_type == 'liquidity') return line_ids_reconciliable.filtered(lambda l: l.debit), line_ids_reconciliable.filtered(lambda l: l.credit) def _move_revert_test_pair(move, revert): self.assertTrue(move.line_ids) self.assertTrue(revert.line_ids) move_lines = _determine_debit_credit_line(move) revert_lines = _determine_debit_credit_line(revert) # in the case of the exchange entry, only one pair of lines will be found if move_lines[0] and revert_lines[1]: self.assertTrue(move_lines[0].full_reconcile_id.exists()) self.assertEqual(move_lines[0].full_reconcile_id.id, revert_lines[1].full_reconcile_id.id) if move_lines[1] and revert_lines[0]: self.assertTrue(move_lines[1].full_reconcile_id.exists()) self.assertEqual(move_lines[1].full_reconcile_id.id, revert_lines[0].full_reconcile_id.id) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_usd_id, 'company_id': self.company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-08-01', 'rate': 0.5, 'currency_id': self.currency_usd_id, 'company_id': self.company.id }) inv = self.create_invoice(invoice_amount=111, currency_id=self.currency_usd_id) payment = self.env['account.payment'].create({ 'payment_type': 'inbound', 'payment_method_line_id': self.inbound_payment_method_line.id, 'partner_type': 'customer', 'partner_id': self.partner_agrolait_id, 'amount': 111, 'currency_id': self.currency_usd_id, 'journal_id': self.bank_journal_usd.id, 'date': time.strftime('%Y') + '-08-01', }) payment.action_post() credit_aml = payment.line_ids.filtered('credit') inv.js_assign_outstanding_line(credit_aml.id) self.assertTrue(inv.payment_state in ('in_payment', 'paid'), "Invoice should be paid") exchange_reconcile = payment.line_ids.mapped('full_reconcile_id') exchange_move = exchange_reconcile.exchange_move_id payment_move = payment.line_ids[0].move_id reverted_payment_move = payment_move._reverse_moves([{'date': time.strftime('%Y') + '-08-01'}], cancel=True) # After reversal of payment, the invoice should be open self.assertTrue(inv.state == 'posted', 'The invoice should be open again') self.assertFalse(exchange_reconcile.exists()) reverted_exchange_move = self.env['account.move'].search([('journal_id', '=', exchange_move.journal_id.id), ('ref', 'ilike', exchange_move.name)], limit=1) _move_revert_test_pair(payment_move, reverted_payment_move) _move_revert_test_pair(exchange_move, reverted_exchange_move) def test_partial_reconcile_currencies_02(self): #### # Day 1: Invoice Cust/001 to customer (expressed in USD) # Market value of USD (day 1): 1 USD = 0.5 EUR # * Dr. 100 USD / 50 EUR - Accounts receivable # * Cr. 100 USD / 50 EUR - Revenue #### dest_journal_id = self.env['account.journal'].create({ 'name': 'turlututu', 'type': 'bank', 'company_id': self.env.company.id, }) self.env['res.currency.rate'].create({ 'currency_id': self.currency_usd_id, 'name': time.strftime('%Y') + '-01-01', 'rate': 2, }) invoice_cust_1 = self.env['account.move'].with_context(default_move_type='out_invoice').create({ 'move_type': 'out_invoice', 'partner_id': self.partner_agrolait_id, 'invoice_date': '%s-01-01' % time.strftime('%Y'), 'date': '%s-01-01' % time.strftime('%Y'), 'currency_id': self.currency_usd_id, 'invoice_line_ids': [ (0, 0, {'quantity': 1, 'price_unit': 100.0, 'name': 'product that cost 100'}) ], }) invoice_cust_1.action_post() aml = invoice_cust_1.invoice_line_ids[0] self.assertEqual(aml.credit, 50.0) ##### # Day 2: Receive payment for half invoice Cust/1 (in USD) # ------------------------------------------------------- # Market value of USD (day 2): 1 USD = 1 EUR # Payment transaction: # * Dr. 50 USD / 50 EUR - EUR Bank (valued at market price # at the time of receiving the money) # * Cr. 50 USD / 50 EUR - Accounts Receivable ##### self.env['res.currency.rate'].create({ 'currency_id': self.currency_usd_id, 'name': time.strftime('%Y') + '-01-02', 'rate': 1, }) payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=invoice_cust_1.ids)\ .create({ 'payment_date': time.strftime('%Y') + '-01-02', 'amount': 50, 'journal_id': dest_journal_id.id, 'currency_id': self.currency_usd_id, })\ ._create_payments() # We expect at this point that the invoice should still be open, in 'partial' state, # because they owe us still 50 CC. self.assertEqual(invoice_cust_1.payment_state, 'partial', 'Invoice is in status %s' % invoice_cust_1.state) def test_multiple_term_reconciliation_opw_1906665(self): '''Test that when registering a payment to an invoice with multiple payment term lines the reconciliation happens against the line with the earliest date_maturity ''' payment_term = self.env['account.payment.term'].create({ 'name': 'Pay in 2 installments', 'line_ids': [ # Pay 50% immediately (0, 0, { 'value': 'percent', 'value_amount': 50, }), # Pay the rest after 14 days (0, 0, { 'value': 'balance', 'days': 14, }) ], }) # can't use self.create_invoice because it validates and we need to set payment_term_id invoice = self.create_invoice_partner( partner_id=self.partner_agrolait_id, payment_term_id=payment_term.id, currency_id=self.currency_usd_id, ) payment = self.env['account.payment'].create({ 'date': time.strftime('%Y') + '-07-15', 'payment_type': 'inbound', 'payment_method_line_id': self.inbound_payment_method_line.id, 'partner_type': 'customer', 'partner_id': self.partner_agrolait_id, 'amount': 25, 'currency_id': self.currency_usd_id, 'journal_id': self.bank_journal_usd.id, }) payment.action_post() receivable_line = payment.line_ids.filtered('credit') invoice.js_assign_outstanding_line(receivable_line.id) self.assertTrue(receivable_line.matched_debit_ids) def test_reconciliation_with_currency(self): #reconciliation on an account having a foreign currency being #the same as the company one account_rcv = self.account_rcv account_rcv.currency_id = self.currency_euro_id aml_obj = self.env['account.move.line'].with_context( check_move_validity=False) general_move1 = self.env['account.move'].create({ 'name': 'general1', 'journal_id': self.general_journal.id, }) aml_obj.create({ 'name': 'debit1', 'account_id': account_rcv.id, 'debit': 11, 'move_id': general_move1.id, }) aml_obj.create({ 'name': 'credit1', 'account_id': self.account_rsa.id, 'credit': 11, 'move_id': general_move1.id, }) general_move1.action_post() general_move2 = self.env['account.move'].create({ 'name': 'general2', 'journal_id': self.general_journal.id, }) aml_obj.create({ 'name': 'credit2', 'account_id': account_rcv.id, 'credit': 10, 'move_id': general_move2.id, }) aml_obj.create({ 'name': 'debit2', 'account_id': self.account_rsa.id, 'debit': 10, 'move_id': general_move2.id, }) general_move2.action_post() general_move3 = self.env['account.move'].create({ 'name': 'general3', 'journal_id': self.general_journal.id, }) aml_obj.create({ 'name': 'credit3', 'account_id': account_rcv.id, 'credit': 1, 'move_id': general_move3.id, }) aml_obj.create({ 'name': 'debit3', 'account_id': self.account_rsa.id, 'debit': 1, 'move_id': general_move3.id, }) general_move3.action_post() to_reconcile = ((general_move1 + general_move2 + general_move3) .mapped('line_ids') .filtered(lambda l: l.account_id.id == account_rcv.id)) to_reconcile.reconcile() for aml in to_reconcile: self.assertEqual(aml.amount_residual, 0.0) def test_inv_refund_foreign_payment_writeoff_domestic2(self): company = self.company self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_euro_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.110600, # Don't change this ! 'currency_id': self.currency_usd_id, 'company_id': self.company.id }) inv1 = self.create_invoice(invoice_amount=800, currency_id=self.currency_usd_id) inv2 = self.create_invoice(move_type="out_refund", invoice_amount=400, currency_id=self.currency_usd_id) payment = self.env['account.payment'].create({ 'date': time.strftime('%Y') + '-07-15', 'payment_method_line_id': self.inbound_payment_method_line.id, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': inv1.partner_id.id, 'amount': 200.00, 'journal_id': self.bank_journal_euro.id, 'company_id': company.id, }) payment.action_post() inv1_receivable = inv1.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') inv2_receivable = inv2.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') pay_receivable = payment.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') move_balance = self.env['account.move'].create({ 'partner_id': inv1.partner_id.id, 'date': time.strftime('%Y') + '-07-01', 'journal_id': self.bank_journal_euro.id, 'line_ids': [ (0, False, {'credit': 160.16, 'account_id': inv1_receivable.account_id.id, 'name': 'Balance WriteOff'}), (0, False, {'debit': 160.16, 'account_id': self.diff_expense_account.id, 'name': 'Balance WriteOff'}), ] }) move_balance.action_post() move_balance_receiv = move_balance.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') (inv1_receivable + inv2_receivable + pay_receivable + move_balance_receiv).reconcile() self.assertTrue(inv1_receivable.full_reconcile_id.exists()) self.assertEqual(inv1_receivable.full_reconcile_id, inv2_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, pay_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, move_balance_receiv.full_reconcile_id) self.assertTrue(inv1.payment_state in ('in_payment', 'paid'), "Invoice should be paid") self.assertEqual(inv2.payment_state, 'paid') def test_inv_refund_foreign_payment_writeoff_domestic3(self): """ Receivable Domestic (Foreign) 592.47 (658.00) | INV 1 > Done in foreign | 202.59 (225.00) INV 2 > Done in foreign | 372.10 (413.25) PAYMENT > Done in domestic (the 413.25 is virtual, non stored) | 17.78 (19.75) WriteOff > Done in domestic (the 19.75 is virtual, non stored) Reconciliation should be full Invoices should be marked as paid """ company = self.company self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_euro_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.110600, # Don't change this ! 'currency_id': self.currency_usd_id, 'company_id': company.id }) inv1 = self.create_invoice(invoice_amount=658, currency_id=self.currency_usd_id) inv2 = self.create_invoice(move_type="out_refund", invoice_amount=225, currency_id=self.currency_usd_id) payment = self.env['account.payment'].create({ 'payment_method_line_id': self.inbound_payment_method_line.id, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': inv1.partner_id.id, 'amount': 372.10, 'date': time.strftime('%Y') + '-07-01', 'journal_id': self.bank_journal_euro.id, 'company_id': company.id, }) payment.action_post() inv1_receivable = inv1.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') inv2_receivable = inv2.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') pay_receivable = payment.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') move_balance = self.env['account.move'].create({ 'partner_id': inv1.partner_id.id, 'date': time.strftime('%Y') + '-07-01', 'journal_id': self.bank_journal_euro.id, 'line_ids': [ (0, False, {'credit': 17.78, 'account_id': inv1_receivable.account_id.id, 'name': 'Balance WriteOff'}), (0, False, {'debit': 17.78, 'account_id': self.diff_expense_account.id, 'name': 'Balance WriteOff'}), ] }) move_balance.action_post() move_balance_receiv = move_balance.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') (inv1_receivable + inv2_receivable + pay_receivable + move_balance_receiv).reconcile() self.assertTrue(inv1_receivable.full_reconcile_id.exists()) self.assertEqual(inv1_receivable.full_reconcile_id, inv2_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, pay_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, move_balance_receiv.full_reconcile_id) self.assertFalse(inv1_receivable.full_reconcile_id.exchange_move_id) self.assertTrue(inv1.payment_state in ('in_payment', 'paid'), "Invoice should be paid") self.assertEqual(inv2.payment_state, 'paid') def test_inv_refund_foreign_payment_writeoff_domestic4(self): """ Receivable Domestic (Foreign) 658.00 (658.00) | INV 1 > Done in foreign | 202.59 (225.00) INV 2 > Done in foreign | 372.10 (413.25) PAYMENT > Done in domestic (the 413.25 is virtual, non stored) | 83.31 (92.52) WriteOff > Done in domestic (the 92.52 is virtual, non stored) Reconciliation should be full Invoices should be marked as paid """ company = self.company self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_euro_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, # Don't change this ! 'currency_id': self.currency_usd_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-15', 'rate': 1.110600, # Don't change this ! 'currency_id': self.currency_usd_id, 'company_id': company.id }) inv1 = self._create_invoice(invoice_amount=658, currency_id=self.currency_usd_id, date_invoice=time.strftime('%Y') + '-07-01', auto_validate=True) inv2 = self._create_invoice(move_type="out_refund", invoice_amount=225, currency_id=self.currency_usd_id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) payment = self.env['account.payment'].create({ 'date': time.strftime('%Y') + '-07-15', 'payment_method_line_id': self.inbound_payment_method_line.id, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': inv1.partner_id.id, 'amount': 372.10, 'journal_id': self.bank_journal_euro.id, 'company_id': company.id, 'currency_id': self.currency_euro_id, }) payment.action_post() inv1_receivable = inv1.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') inv2_receivable = inv2.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') pay_receivable = payment.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertEqual(inv1_receivable.balance, 658) self.assertEqual(inv2_receivable.balance, -202.59) self.assertEqual(pay_receivable.balance, -372.1) move_balance = self.env['account.move'].create({ 'partner_id': inv1.partner_id.id, 'date': time.strftime('%Y') + '-07-15', 'journal_id': self.bank_journal_usd.id, 'line_ids': [ (0, False, {'credit': 83.31, 'account_id': inv1_receivable.account_id.id, 'name': 'Balance WriteOff'}), (0, False, {'debit': 83.31, 'account_id': self.diff_expense_account.id, 'name': 'Balance WriteOff'}), ] }) move_balance.action_post() move_balance_receiv = move_balance.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') (inv1_receivable + inv2_receivable + pay_receivable + move_balance_receiv).reconcile() self.assertTrue(inv1_receivable.full_reconcile_id.exists()) self.assertEqual(inv1_receivable.full_reconcile_id, inv2_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, pay_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, move_balance_receiv.full_reconcile_id) self.assertTrue(inv1.payment_state in ('in_payment', 'paid'), "Invoice should be paid") self.assertEqual(inv2.payment_state, 'paid') def test_inv_refund_foreign_payment_writeoff_domestic5(self): """ Receivable Domestic (Foreign) 600.00 (600.00) | INV 1 > Done in foreign | 250.00 (250.00) INV 2 > Done in foreign | 314.07 (314.07) PAYMENT > Done in domestic (foreign non stored) | 35.93 (60.93) WriteOff > Done in domestic (foreign non stored). WriteOff is included in payment Reconciliation should be full, without exchange difference Invoices should be marked as paid """ company = self.company self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_euro_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, # Don't change this ! 'currency_id': self.currency_usd_id, 'company_id': company.id }) inv1 = self._create_invoice(invoice_amount=600, currency_id=self.currency_usd_id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) inv2 = self._create_invoice(move_type="out_refund", invoice_amount=250, currency_id=self.currency_usd_id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) inv1_receivable = inv1.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') inv2_receivable = inv2.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertEqual(inv1_receivable.balance, 600.00) self.assertEqual(inv2_receivable.balance, -250) # partially pay the invoice with the refund inv1.js_assign_outstanding_line(inv2_receivable.id) self.assertEqual(inv1.amount_residual, 350) payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=inv1.ids)\ .create({ 'payment_date': time.strftime('%Y') + '-07-15', 'amount': 314.07, 'journal_id': self.bank_journal_euro.id, 'currency_id': self.currency_euro_id, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.diff_income_account.id, })\ ._create_payments() payment_receivable = payment.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertEqual(payment_receivable.balance, -350) self.assertTrue(inv1_receivable.full_reconcile_id.exists()) self.assertEqual(inv1_receivable.full_reconcile_id, inv2_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, payment_receivable.full_reconcile_id) self.assertFalse(inv1_receivable.full_reconcile_id.exchange_move_id) self.assertTrue(inv1.payment_state in ('in_payment', 'paid'), "Invoice should be paid") self.assertEqual(inv2.payment_state, 'paid') def test_inv_refund_foreign_payment_writeoff_domestic6(self): """ Receivable Domestic (Foreign) 540.25 (600.00) | INV 1 > Done in foreign | 225.10 (250.00) INV 2 > Done in foreign | 315.15 (350.00) PAYMENT > Done in domestic (the 350.00 is virtual, non stored) """ company = self.company self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_euro_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.1106, # Don't change this ! 'currency_id': self.currency_usd_id, 'company_id': company.id }) inv1 = self._create_invoice(invoice_amount=600, currency_id=self.currency_usd_id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) inv2 = self._create_invoice(move_type="out_refund", invoice_amount=250, currency_id=self.currency_usd_id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) inv1_receivable = inv1.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') inv2_receivable = inv2.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertEqual(inv1_receivable.balance, 540.25) self.assertEqual(inv2_receivable.balance, -225.10) # partially pay the invoice with the refund inv1.js_assign_outstanding_line(inv2_receivable.id) self.assertAlmostEqual(inv1.amount_residual, 350) self.assertAlmostEqual(inv1_receivable.amount_residual, 315.15) payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=inv1.ids)\ .create({ 'payment_date': time.strftime('%Y') + '-07-15', 'amount': 314.07, 'journal_id': self.bank_journal_euro.id, 'currency_id': self.currency_euro_id, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.diff_income_account.id, })\ ._create_payments() payment_receivable = payment.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertTrue(inv1_receivable.full_reconcile_id.exists()) self.assertEqual(inv1_receivable.full_reconcile_id, inv2_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, payment_receivable.full_reconcile_id) self.assertTrue(inv1.payment_state in ('in_payment', 'paid'), "Invoice should be paid") self.assertEqual(inv2.payment_state, 'paid') def test_inv_refund_foreign_payment_writeoff_domestic6bis(self): """ Same as domestic6, but only in foreign currencies Obviously, it should lead to the same kind of results Here there is no exchange difference entry though """ foreign_0 = self.env['res.currency'].create({ 'name': 'foreign0', 'symbol': 'F0' }) foreign_1 = self.env['res.currency'].browse(self.currency_usd_id) company = self.company self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_euro_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': foreign_0.id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.1106, # Don't change this ! 'currency_id': foreign_1.id, 'company_id': company.id }) inv1 = self._create_invoice(invoice_amount=600, currency_id=foreign_1.id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) inv2 = self._create_invoice(move_type="out_refund", invoice_amount=250, currency_id=foreign_1.id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) inv1_receivable = inv1.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') inv2_receivable = inv2.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertEqual(inv1_receivable.balance, 540.25) self.assertEqual(inv2_receivable.balance, -225.10) # partially pay the invoice with the refund inv1.js_assign_outstanding_line(inv2_receivable.id) self.assertAlmostEqual(inv1.amount_residual, 350) self.assertAlmostEqual(inv1_receivable.amount_residual, 315.15) payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=inv1.ids)\ .create({ 'payment_date': time.strftime('%Y') + '-07-15', 'amount': 314.07, 'journal_id': self.bank_journal_euro.id, 'currency_id': foreign_0.id, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.diff_income_account.id, })\ ._create_payments() payment_receivable = payment.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertTrue(inv1_receivable.full_reconcile_id.exists()) self.assertEqual(inv1_receivable.full_reconcile_id, inv2_receivable.full_reconcile_id) self.assertEqual(inv1_receivable.full_reconcile_id, payment_receivable.full_reconcile_id) self.assertTrue(inv1.payment_state in ('in_payment', 'paid'), "Invoice should be paid") self.assertEqual(inv2.payment_state, 'paid') def test_inv_refund_foreign_payment_writeoff_domestic7(self): """ Receivable Domestic (Foreign) 5384.48 (5980.00) | INV 1 > Done in foreign | 5384.43 (5979.95) PAYMENT > Done in domestic (foreign non stored) | 0.05 (0.00) WriteOff > Done in domestic (foreign non stored). WriteOff is included in payment, so, the amount in currency is irrelevant Reconciliation should be full, without exchange difference Invoices should be marked as paid """ company = self.company self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_euro_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.1106, # Don't change this ! 'currency_id': self.currency_usd_id, 'company_id': company.id }) inv1 = self._create_invoice(invoice_amount=5980, currency_id=self.currency_usd_id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) inv1_receivable = inv1.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertAlmostEqual(inv1_receivable.balance, 5384.48) payment = self.env['account.payment.register']\ .with_context(active_model='account.move', active_ids=inv1.ids)\ .create({ 'payment_date': time.strftime('%Y') + '-07-15', 'amount': 5384.43, 'journal_id': self.bank_journal_euro.id, 'currency_id': self.currency_euro_id, 'payment_difference_handling': 'reconcile', 'writeoff_account_id': self.diff_income_account.id, })\ ._create_payments() payment_receivable = payment.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertTrue(inv1_receivable.full_reconcile_id.exists()) self.assertEqual(inv1_receivable.full_reconcile_id, payment_receivable.full_reconcile_id) self.assertFalse(inv1_receivable.full_reconcile_id.exchange_move_id) self.assertTrue(inv1.payment_state in ('in_payment', 'paid'), "Invoice should be paid") def test_inv_refund_foreign_payment_writeoff_domestic8(self): """ Roughly the same as *_domestic7 Though it simulates going through the reconciliation widget Because the WriteOff is on a different line than the payment """ company = self.company self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.0, 'currency_id': self.currency_euro_id, 'company_id': company.id }) self.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-07-01', 'rate': 1.1106, # Don't change this ! 'currency_id': self.currency_usd_id, 'company_id': company.id }) inv1 = self._create_invoice(invoice_amount=5980, currency_id=self.currency_usd_id, date_invoice=time.strftime('%Y') + '-07-15', auto_validate=True) inv1_receivable = inv1.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') self.assertAlmostEqual(inv1_receivable.balance, 5384.48) Payment = self.env['account.payment'] payment = Payment.create({ 'date': time.strftime('%Y') + '-07-15', 'payment_method_line_id': self.inbound_payment_method_line.id, 'payment_type': 'inbound', 'partner_type': 'customer', 'partner_id': inv1.partner_id.id, 'amount': 5384.43, 'journal_id': self.bank_journal_euro.id, 'company_id': company.id, 'currency_id': self.currency_euro_id, }) payment.action_post() payment_receivable = payment.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') move_balance = self.env['account.move'].create({ 'partner_id': inv1.partner_id.id, 'date': time.strftime('%Y') + '-07-15', 'journal_id': self.bank_journal_usd.id, 'line_ids': [ (0, False, {'credit': 0.05, 'account_id': inv1_receivable.account_id.id, 'name': 'Balance WriteOff'}), (0, False, {'debit': 0.05, 'account_id': self.diff_expense_account.id, 'name': 'Balance WriteOff'}), ] }) move_balance.action_post() move_balance_receiv = move_balance.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') (inv1_receivable + payment_receivable + move_balance_receiv).reconcile() self.assertTrue(inv1_receivable.full_reconcile_id.exists()) self.assertEqual(inv1_receivable.full_reconcile_id, payment_receivable.full_reconcile_id) self.assertEqual(move_balance_receiv.full_reconcile_id, inv1_receivable.full_reconcile_id) self.assertTrue(inv1.payment_state in ('in_payment', 'paid'), "Invoice should be paid")
47.152429
56,300
143,975
py
PYTHON
15.0
# -*- coding: utf-8 -*- # pylint: disable=bad-whitespace from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests.common import Form from odoo.tests import tagged from odoo import fields, Command from odoo.exceptions import UserError from collections import defaultdict from unittest.mock import patch from datetime import timedelta from freezegun import freeze_time @tagged('post_install', '-at_install') class TestAccountMoveOutInvoiceOnchanges(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.invoice = cls.init_invoice('out_invoice', products=cls.product_a+cls.product_b) cls.product_line_vals_1 = { 'name': cls.product_a.name, 'product_id': cls.product_a.id, 'account_id': cls.product_a.property_account_income_id.id, 'partner_id': cls.partner_a.id, 'product_uom_id': cls.product_a.uom_id.id, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 1000.0, 'price_subtotal': 1000.0, 'price_total': 1150.0, 'tax_ids': cls.product_a.taxes_id.ids, 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -1000.0, 'debit': 0.0, 'credit': 1000.0, 'date_maturity': False, } cls.product_line_vals_2 = { 'name': cls.product_b.name, 'product_id': cls.product_b.id, 'account_id': cls.product_b.property_account_income_id.id, 'partner_id': cls.partner_a.id, 'product_uom_id': cls.product_b.uom_id.id, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 200.0, 'price_subtotal': 200.0, 'price_total': 260.0, 'tax_ids': cls.product_b.taxes_id.ids, 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -200.0, 'debit': 0.0, 'credit': 200.0, 'date_maturity': False, } cls.tax_line_vals_1 = { 'name': cls.tax_sale_a.name, 'product_id': False, 'account_id': cls.company_data['default_account_tax_sale'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 180.0, 'price_subtotal': 180.0, 'price_total': 180.0, 'tax_ids': [], 'tax_line_id': cls.tax_sale_a.id, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -180.0, 'debit': 0.0, 'credit': 180.0, 'date_maturity': False, } cls.tax_line_vals_2 = { 'name': cls.tax_sale_b.name, 'product_id': False, 'account_id': cls.company_data['default_account_tax_sale'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'tax_ids': [], 'tax_line_id': cls.tax_sale_b.id, 'currency_id': cls.company_data['currency'].id, 'amount_currency': -30.0, 'debit': 0.0, 'credit': 30.0, 'date_maturity': False, } cls.term_line_vals_1 = { 'name': '', 'product_id': False, 'account_id': cls.company_data['default_account_receivable'].id, 'partner_id': cls.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -1410.0, 'price_subtotal': -1410.0, 'price_total': -1410.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': cls.company_data['currency'].id, 'amount_currency': 1410.0, 'debit': 1410.0, 'credit': 0.0, 'date_maturity': fields.Date.from_string('2019-01-01'), } cls.move_vals = { 'partner_id': cls.partner_a.id, 'currency_id': cls.company_data['currency'].id, 'journal_id': cls.company_data['default_journal_sale'].id, 'date': fields.Date.from_string('2019-01-01'), 'fiscal_position_id': False, 'payment_reference': '', 'invoice_payment_term_id': cls.pay_terms_a.id, 'amount_untaxed': 1200.0, 'amount_tax': 210.0, 'amount_total': 1410.0, } def setUp(self): super(TestAccountMoveOutInvoiceOnchanges, self).setUp() self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) @freeze_time('2020-01-15') def test_out_invoice_onchange_invoice_date(self): for tax_date, invoice_date, accounting_date in [ ('2019-03-31', '2019-05-12', '2019-05-12'), ('2019-03-31', '2019-02-10', '2019-12-31'), ('2019-05-31', '2019-06-15', '2019-06-15'), ]: self.invoice.company_id.tax_lock_date = tax_date invoice = self.invoice.copy() with Form(invoice) as move_form: move_form.invoice_date = invoice_date invoice.action_post() self.assertEqual(invoice.date, fields.Date.to_date(accounting_date)) def test_out_invoice_line_onchange_product_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.product_id = self.product_b move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'name': self.product_b.name, 'product_id': self.product_b.id, 'product_uom_id': self.product_b.uom_id.id, 'account_id': self.product_b.property_account_income_id.id, 'price_unit': 200.0, 'price_subtotal': 200.0, 'price_total': 260.0, 'tax_ids': self.product_b.taxes_id.ids, 'amount_currency': -200.0, 'credit': 200.0, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 60.0, 'price_subtotal': 60.0, 'price_total': 60.0, 'amount_currency': -60.0, 'credit': 60.0, }, { **self.tax_line_vals_2, 'price_unit': 60.0, 'price_subtotal': 60.0, 'price_total': 60.0, 'amount_currency': -60.0, 'credit': 60.0, }, { **self.term_line_vals_1, 'price_unit': -520.0, 'price_subtotal': -520.0, 'price_total': -520.0, 'amount_currency': 520.0, 'debit': 520.0, }, ], { **self.move_vals, 'amount_untaxed': 400.0, 'amount_tax': 120.0, 'amount_total': 520.0, }) def test_out_invoice_line_onchange_product_2_with_fiscal_pos_1(self): ''' Test mapping a price-included tax (10%) with a price-excluded tax (20%) on a price_unit of 110.0. The price_unit should be 100.0 after applying the fiscal position. ''' tax_price_include = self.env['account.tax'].create({ 'name': '10% incl', 'type_tax_use': 'sale', 'amount_type': 'percent', 'amount': 10, 'price_include': True, 'include_base_amount': True, }) tax_price_exclude = self.env['account.tax'].create({ 'name': '15% excl', 'type_tax_use': 'sale', 'amount_type': 'percent', 'amount': 15, }) fiscal_position = self.env['account.fiscal.position'].create({ 'name': 'fiscal_pos_a', 'tax_ids': [ (0, None, { 'tax_src_id': tax_price_include.id, 'tax_dest_id': tax_price_exclude.id, }), ], }) product = self.env['product.product'].create({ 'name': 'product', 'uom_id': self.env.ref('uom.product_uom_unit').id, 'lst_price': 110.0, 'taxes_id': [(6, 0, tax_price_include.ids)], }) move_form = Form(self.env['account.move'].with_context(default_move_type='out_invoice')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2019-01-01') move_form.currency_id = self.currency_data['currency'] move_form.fiscal_position_id = fiscal_position with move_form.invoice_line_ids.new() as line_form: line_form.product_id = product invoice = move_form.save() self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'price_unit': 200.0, 'price_subtotal': 200.0, 'price_total': 230.0, 'tax_ids': tax_price_exclude.ids, 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'debit': 0.0, 'credit': 100.0, }, { 'product_id': False, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'tax_ids': [], 'tax_line_id': tax_price_exclude.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'debit': 0.0, 'credit': 15.0, }, { 'product_id': False, 'price_unit': -230.0, 'price_subtotal': -230.0, 'price_total': -230.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 230.0, 'debit': 115.0, 'credit': 0.0, }, ], { 'currency_id': self.currency_data['currency'].id, 'fiscal_position_id': fiscal_position.id, 'amount_untaxed': 200.0, 'amount_tax': 30.0, 'amount_total': 230.0, }) uom_dozen = self.env.ref('uom.product_uom_dozen') with Form(invoice) as move_form: with move_form.invoice_line_ids.edit(0) as line_form: line_form.product_uom_id = uom_dozen self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'product_uom_id': uom_dozen.id, 'price_unit': 2400.0, 'price_subtotal': 2400.0, 'price_total': 2760.0, 'tax_ids': tax_price_exclude.ids, 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -2400.0, 'debit': 0.0, 'credit': 1200.0, }, { 'product_id': False, 'product_uom_id': False, 'price_unit': 360.0, 'price_subtotal': 360.0, 'price_total': 360.0, 'tax_ids': [], 'tax_line_id': tax_price_exclude.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -360.0, 'debit': 0.0, 'credit': 180.0, }, { 'product_id': False, 'product_uom_id': False, 'price_unit': -2760.0, 'price_subtotal': -2760.0, 'price_total': -2760.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 2760.0, 'debit': 1380.0, 'credit': 0.0, }, ], { 'currency_id': self.currency_data['currency'].id, 'fiscal_position_id': fiscal_position.id, 'amount_untaxed': 2400.0, 'amount_tax': 360.0, 'amount_total': 2760.0, }) def test_out_invoice_line_onchange_product_2_with_fiscal_pos_2(self): ''' Test mapping a price-included tax (10%) with another price-included tax (20%) on a price_unit of 110.0. The price_unit should be 120.0 after applying the fiscal position. ''' tax_price_include_1 = self.env['account.tax'].create({ 'name': '10% incl', 'type_tax_use': 'sale', 'amount_type': 'percent', 'amount': 10, 'price_include': True, 'include_base_amount': True, }) tax_price_include_2 = self.env['account.tax'].create({ 'name': '20% incl', 'type_tax_use': 'sale', 'amount_type': 'percent', 'amount': 20, 'price_include': True, 'include_base_amount': True, }) fiscal_position = self.env['account.fiscal.position'].create({ 'name': 'fiscal_pos_a', 'tax_ids': [ (0, None, { 'tax_src_id': tax_price_include_1.id, 'tax_dest_id': tax_price_include_2.id, }), ], }) product = self.env['product.product'].create({ 'name': 'product', 'uom_id': self.env.ref('uom.product_uom_unit').id, 'lst_price': 110.0, 'taxes_id': [(6, 0, tax_price_include_1.ids)], }) move_form = Form(self.env['account.move'].with_context(default_move_type='out_invoice')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2019-01-01') move_form.currency_id = self.currency_data['currency'] move_form.fiscal_position_id = fiscal_position with move_form.invoice_line_ids.new() as line_form: line_form.product_id = product invoice = move_form.save() self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'price_unit': 240.0, 'price_subtotal': 200.0, 'price_total': 240.0, 'tax_ids': tax_price_include_2.ids, 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'debit': 0.0, 'credit': 100.0, }, { 'product_id': False, 'price_unit': 40.0, 'price_subtotal': 40.0, 'price_total': 40.0, 'tax_ids': [], 'tax_line_id': tax_price_include_2.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -40.0, 'debit': 0.0, 'credit': 20.0, }, { 'product_id': False, 'price_unit': -240.0, 'price_subtotal': -240.0, 'price_total': -240.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 240.0, 'debit': 120.0, 'credit': 0.0, }, ], { 'currency_id': self.currency_data['currency'].id, 'fiscal_position_id': fiscal_position.id, 'amount_untaxed': 200.0, 'amount_tax': 40.0, 'amount_total': 240.0, }) uom_dozen = self.env.ref('uom.product_uom_dozen') with Form(invoice) as move_form: with move_form.invoice_line_ids.edit(0) as line_form: line_form.product_uom_id = uom_dozen self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'product_uom_id': uom_dozen.id, 'price_unit': 2880.0, 'price_subtotal': 2400.0, 'price_total': 2880.0, 'tax_ids': tax_price_include_2.ids, 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -2400.0, 'debit': 0.0, 'credit': 1200.0, }, { 'product_id': False, 'product_uom_id': False, 'price_unit': 480.0, 'price_subtotal': 480.0, 'price_total': 480.0, 'tax_ids': [], 'tax_line_id': tax_price_include_2.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -480.0, 'debit': 0.0, 'credit': 240.0, }, { 'product_id': False, 'product_uom_id': False, 'price_unit': -2880.0, 'price_subtotal': -2880.0, 'price_total': -2880.0, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 2880.0, 'debit': 1440.0, 'credit': 0.0, }, ], { 'currency_id': self.currency_data['currency'].id, 'fiscal_position_id': fiscal_position.id, 'amount_untaxed': 2400.0, 'amount_tax': 480.0, 'amount_total': 2880.0, }) def test_out_invoice_line_onchange_business_fields_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: # Current price_unit is 1000. # We set quantity = 4, discount = 50%, price_unit = 400. The debit/credit fields don't change because (4 * 500) * 0.5 = 1000. line_form.quantity = 4 line_form.discount = 50 line_form.price_unit = 500 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 4, 'discount': 50.0, 'price_unit': 500.0, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) move_form = Form(self.invoice) with move_form.line_ids.edit(2) as line_form: # Reset field except the discount that becomes 100%. # /!\ The modification is made on the accounting tab. line_form.quantity = 1 line_form.discount = 100 line_form.price_unit = 1000 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'discount': 100.0, 'price_subtotal': 0.0, 'price_total': 0.0, 'amount_currency': 0.0, 'credit': 0.0, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'amount_currency': -30.0, 'credit': 30.0, }, self.tax_line_vals_2, { **self.term_line_vals_1, 'price_unit': -260.0, 'price_subtotal': -260.0, 'price_total': -260.0, 'amount_currency': 260.0, 'debit': 260.0, }, ], { **self.move_vals, 'amount_untaxed': 200.0, 'amount_tax': 60.0, 'amount_total': 260.0, }) def test_out_invoice_line_onchange_accounting_fields_1(self): move_form = Form(self.invoice) with move_form.line_ids.edit(2) as line_form: # Custom credit on the first product line. line_form.credit = 3000 with move_form.line_ids.edit(3) as line_form: # Custom debit on the second product line. Credit should be reset by onchange. # /!\ It's a negative line. line_form.debit = 500 with move_form.line_ids.edit(0) as line_form: # Custom credit on the first tax line. line_form.credit = 800 with move_form.line_ids.edit(4) as line_form: # Custom credit on the second tax line. line_form.credit = 250 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 3000.0, 'price_subtotal': 3000.0, 'price_total': 3450.0, 'amount_currency': -3000.0, 'credit': 3000.0, }, { **self.product_line_vals_2, 'price_unit': -500.0, 'price_subtotal': -500.0, 'price_total': -650.0, 'amount_currency': 500.0, 'debit': 500.0, 'credit': 0.0, }, { **self.tax_line_vals_1, 'price_unit': 800.0, 'price_subtotal': 800.0, 'price_total': 800.0, 'amount_currency': -800.0, 'credit': 800.0, }, { **self.tax_line_vals_2, 'price_unit': 250.0, 'price_subtotal': 250.0, 'price_total': 250.0, 'amount_currency': -250.0, 'credit': 250.0, }, { **self.term_line_vals_1, 'price_unit': -3550.0, 'price_subtotal': -3550.0, 'price_total': -3550.0, 'amount_currency': 3550.0, 'debit': 3550.0, }, ], { **self.move_vals, 'amount_untaxed': 2500.0, 'amount_tax': 1050.0, 'amount_total': 3550.0, }) def test_out_invoice_line_onchange_partner_1(self): move_form = Form(self.invoice) move_form.partner_id = self.partner_b move_form.payment_reference = 'turlututu' move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'partner_id': self.partner_b.id, }, { **self.product_line_vals_2, 'partner_id': self.partner_b.id, }, { **self.tax_line_vals_1, 'partner_id': self.partner_b.id, }, { **self.tax_line_vals_2, 'partner_id': self.partner_b.id, }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_receivable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -423.0, 'price_subtotal': -423.0, 'price_total': -423.0, 'amount_currency': 423.0, 'debit': 423.0, }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_receivable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -987.0, 'price_subtotal': -987.0, 'price_total': -987.0, 'amount_currency': 987.0, 'debit': 987.0, 'date_maturity': fields.Date.from_string('2019-02-28'), }, ], { **self.move_vals, 'partner_id': self.partner_b.id, 'payment_reference': 'turlututu', 'fiscal_position_id': self.fiscal_pos_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'amount_untaxed': 1200.0, 'amount_tax': 210.0, 'amount_total': 1410.0, }) # Remove lines and recreate them to apply the fiscal position. move_form = Form(self.invoice) move_form.invoice_line_ids.remove(0) move_form.invoice_line_ids.remove(0) with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_b move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'account_id': self.product_b.property_account_income_id.id, 'partner_id': self.partner_b.id, 'tax_ids': self.tax_sale_b.ids, }, { **self.product_line_vals_2, 'partner_id': self.partner_b.id, 'price_total': 230.0, 'tax_ids': self.tax_sale_b.ids, }, { **self.tax_line_vals_1, 'name': self.tax_sale_b.name, 'partner_id': self.partner_b.id, 'tax_line_id': self.tax_sale_b.id, }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_receivable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -414.0, 'price_subtotal': -414.0, 'price_total': -414.0, 'amount_currency': 414.0, 'debit': 414.0, }, { **self.term_line_vals_1, 'name': 'turlututu', 'account_id': self.partner_b.property_account_receivable_id.id, 'partner_id': self.partner_b.id, 'price_unit': -966.0, 'price_subtotal': -966.0, 'price_total': -966.0, 'amount_currency': 966.0, 'debit': 966.0, 'date_maturity': fields.Date.from_string('2019-02-28'), }, ], { **self.move_vals, 'partner_id': self.partner_b.id, 'payment_reference': 'turlututu', 'fiscal_position_id': self.fiscal_pos_a.id, 'invoice_payment_term_id': self.pay_terms_b.id, 'amount_untaxed': 1200.0, 'amount_tax': 180.0, 'amount_total': 1380.0, }) def test_out_invoice_line_onchange_taxes_1(self): move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 1200 line_form.tax_ids.add(self.tax_armageddon) move_form.save() child_tax_1 = self.tax_armageddon.children_tax_ids[0] child_tax_2 = self.tax_armageddon.children_tax_ids[1] self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 1200.0, 'price_subtotal': 1000.0, 'price_total': 1470.0, 'tax_ids': (self.tax_sale_a + self.tax_armageddon).ids, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, { 'name': child_tax_1.name, 'product_id': False, 'account_id': self.company_data['default_account_revenue'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 120.0, 'price_subtotal': 120.0, 'price_total': 132.0, 'tax_ids': child_tax_2.ids, 'tax_line_id': child_tax_1.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': -120.0, 'debit': 0.0, 'credit': 120.0, 'date_maturity': False, }, { 'name': child_tax_1.name, 'product_id': False, 'account_id': self.company_data['default_account_tax_sale'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 80.0, 'price_subtotal': 80.0, 'price_total': 88.0, 'tax_ids': child_tax_2.ids, 'tax_line_id': child_tax_1.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': -80.0, 'debit': 0.0, 'credit': 80.0, 'date_maturity': False, }, { 'name': child_tax_2.name, 'product_id': False, 'account_id': child_tax_2.cash_basis_transition_account_id.id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 120.0, 'price_subtotal': 120.0, 'price_total': 120.0, 'tax_ids': [], 'tax_line_id': child_tax_2.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': -120.0, 'debit': 0.0, 'credit': 120.0, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -1730.0, 'price_subtotal': -1730.0, 'price_total': -1730.0, 'amount_currency': 1730.0, 'debit': 1730.0, }, ], { **self.move_vals, 'amount_untaxed': 1200.0, 'amount_tax': 530.0, 'amount_total': 1730.0, }) def test_out_invoice_line_onchange_rounding_price_subtotal_1(self): ''' Seek for rounding issue on the price_subtotal when dealing with a price_unit having more digits than the foreign currency one. ''' decimal_precision_name = self.env['account.move.line']._fields['price_unit']._digits decimal_precision = self.env['decimal.precision'].search([('name', '=', decimal_precision_name)]) self.assertTrue(decimal_precision, "Decimal precision '%s' not found" % decimal_precision_name) self.currency_data['currency'].rounding = 0.01 decimal_precision.digits = 4 def check_invoice_values(invoice): self.assertInvoiceValues(invoice, [ { 'quantity': 1.0, 'price_unit': 0.025, 'price_subtotal': 0.03, 'debit': 0.0, 'credit': 0.02, 'currency_id': self.currency_data['currency'].id, }, { 'quantity': 1.0, 'price_unit': -0.03, 'price_subtotal': -0.03, 'debit': 0.02, 'credit': 0.0, 'currency_id': self.currency_data['currency'].id, }, ], { 'amount_untaxed': 0.03, 'amount_tax': 0.0, 'amount_total': 0.03, }) # == Test at the creation of the invoice == invoice_1 = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.currency_data['currency'].id, 'invoice_line_ids': [(0, 0, { 'name': 'test line', 'price_unit': 0.025, 'quantity': 1, 'account_id': self.company_data['default_account_revenue'].id, })], }) check_invoice_values(invoice_1) # == Test when writing on the invoice == invoice_2 = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.currency_data['currency'].id, }) invoice_2.write({ 'invoice_line_ids': [(0, 0, { 'name': 'test line', 'price_unit': 0.025, 'quantity': 1, 'account_id': self.company_data['default_account_revenue'].id, })], }) check_invoice_values(invoice_2) def test_out_invoice_line_onchange_rounding_price_subtotal_2(self): """ Ensure the cyclic computations implemented using onchanges are not leading to rounding issues when using price-included taxes. For example: 100 / 1.21 ~= 82.64 but 82.64 * 1.21 ~= 99.99 != 100.0. """ def check_invoice_values(invoice): self.assertInvoiceValues(invoice, [ { 'price_unit': 100.0, 'price_subtotal': 82.64, 'debit': 0.0, 'credit': 82.64, }, { 'price_unit': 17.36, 'price_subtotal': 17.36, 'debit': 0.0, 'credit': 17.36, }, { 'price_unit': -100.0, 'price_subtotal': -100.0, 'debit': 100.0, 'credit': 0.0, }, ], { 'amount_untaxed': 82.64, 'amount_tax': 17.36, 'amount_total': 100.0, }) tax = self.env['account.tax'].create({ 'name': '21%', 'amount': 21.0, 'price_include': True, 'include_base_amount': True, }) # == Test assigning tax directly == invoice_create = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'partner_id': self.partner_a.id, 'invoice_line_ids': [(0, 0, { 'name': 'test line', 'price_unit': 100.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, tax.ids)], })], }) check_invoice_values(invoice_create) move_form = Form(self.env['account.move'].with_context(default_move_type='out_invoice')) move_form.invoice_date = fields.Date.from_string('2017-01-01') move_form.partner_id = self.partner_a with move_form.invoice_line_ids.new() as line_form: line_form.name = 'test line' line_form.price_unit = 100.0 line_form.account_id = self.company_data['default_account_revenue'] line_form.tax_ids.clear() line_form.tax_ids.add(tax) invoice_onchange = move_form.save() check_invoice_values(invoice_onchange) # == Test when the tax is set on a product == product = self.env['product.product'].create({ 'name': 'product', 'lst_price': 100.0, 'property_account_income_id': self.company_data['default_account_revenue'].id, 'taxes_id': [(6, 0, tax.ids)], }) move_form = Form(self.env['account.move'].with_context(default_move_type='out_invoice')) move_form.invoice_date = fields.Date.from_string('2017-01-01') move_form.partner_id = self.partner_a with move_form.invoice_line_ids.new() as line_form: line_form.product_id = product invoice_onchange = move_form.save() check_invoice_values(invoice_onchange) # == Test with a fiscal position == fiscal_position = self.env['account.fiscal.position'].create({'name': 'fiscal_position'}) move_form = Form(self.env['account.move'].with_context(default_move_type='out_invoice')) move_form.invoice_date = fields.Date.from_string('2017-01-01') move_form.partner_id = self.partner_a move_form.fiscal_position_id = fiscal_position with move_form.invoice_line_ids.new() as line_form: line_form.product_id = product invoice_onchange = move_form.save() check_invoice_values(invoice_onchange) def test_out_invoice_line_onchange_taxes_2_price_unit_tax_included(self): ''' Seek for rounding issue in the price unit. Suppose a price_unit of 2300 with a 5.5% price-included tax applied on it. The computed balance will be computed as follow: 2300.0 / 1.055 = 2180.0948 ~ 2180.09. Since accounting / business fields are synchronized, the inverse computation will try to recompute the price_unit based on the balance: 2180.09 * 1.055 = 2299.99495 ~ 2299.99. This test ensures the price_unit is not overridden in such case. ''' tax_price_include = self.env['account.tax'].create({ 'name': 'Tax 5.5% price included', 'amount': 5.5, 'amount_type': 'percent', 'price_include': True, }) # == Single-currency == # price_unit=2300 with 15% tax (excluded) + 5.5% tax (included). move_form = Form(self.invoice) move_form.invoice_line_ids.remove(1) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 2300 line_form.tax_ids.add(tax_price_include) move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 2300.0, 'price_subtotal': 2180.09, 'price_total': 2627.01, 'tax_ids': (self.product_a.taxes_id + tax_price_include).ids, 'amount_currency': -2180.09, 'credit': 2180.09, }, { **self.tax_line_vals_1, 'price_unit': 327.01, 'price_subtotal': 327.01, 'price_total': 327.01, 'amount_currency': -327.01, 'credit': 327.01, }, { 'name': tax_price_include.name, 'product_id': False, 'account_id': self.product_line_vals_1['account_id'], 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 119.91, 'price_subtotal': 119.91, 'price_total': 119.91, 'tax_ids': [], 'tax_line_id': tax_price_include.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': -119.91, 'debit': 0.0, 'credit': 119.91, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -2627.01, 'price_subtotal': -2627.01, 'price_total': -2627.01, 'amount_currency': 2627.01, 'debit': 2627.01, }, ], { **self.move_vals, 'amount_untaxed': 2180.09, 'amount_tax': 446.92, 'amount_total': 2627.01, }) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = -2300 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': -2300.0, 'price_subtotal': -2180.09, 'price_total': -2627.01, 'tax_ids': (self.product_a.taxes_id + tax_price_include).ids, 'amount_currency': 2180.09, 'debit': 2180.09, 'credit': 0.0, }, { **self.tax_line_vals_1, 'price_unit': -327.01, 'price_subtotal': -327.01, 'price_total': -327.01, 'amount_currency': 327.01, 'debit': 327.01, 'credit': 0.0, }, { 'name': tax_price_include.name, 'product_id': False, 'account_id': self.product_line_vals_1['account_id'], 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -119.91, 'price_subtotal': -119.91, 'price_total': -119.91, 'tax_ids': [], 'tax_line_id': tax_price_include.id, 'currency_id': self.company_data['currency'].id, 'amount_currency': 119.91, 'debit': 119.91, 'credit': 0.0, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': 2627.01, 'price_subtotal': 2627.01, 'price_total': 2627.01, 'amount_currency': -2627.01, 'debit': 0.0, 'credit': 2627.01, }, ], { **self.move_vals, 'amount_untaxed': -2180.09, 'amount_tax': -446.92, 'amount_total': -2627.01, }) # == Multi-currencies == move_form = Form(self.invoice) move_form.currency_id = self.currency_data['currency'] with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 2300 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': 2300.0, 'price_subtotal': 2180.095, 'price_total': 2627.014, 'tax_ids': (self.product_a.taxes_id + tax_price_include).ids, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -2180.095, 'credit': 1090.05, }, { **self.tax_line_vals_1, 'price_unit': 327.014, 'price_subtotal': 327.014, 'price_total': 327.014, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -327.014, 'credit': 163.51, }, { 'name': tax_price_include.name, 'product_id': False, 'account_id': self.product_line_vals_1['account_id'], 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 119.905, 'price_subtotal': 119.905, 'price_total': 119.905, 'tax_ids': [], 'tax_line_id': tax_price_include.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -119.905, 'debit': 0.0, 'credit': 59.95, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -2627.014, 'price_subtotal': -2627.014, 'price_total': -2627.014, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 2627.014, 'debit': 1313.51, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'amount_untaxed': 2180.095, 'amount_tax': 446.919, 'amount_total': 2627.014, }) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = -2300 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'price_unit': -2300.0, 'price_subtotal': -2180.095, 'price_total': -2627.014, 'tax_ids': (self.product_a.taxes_id + tax_price_include).ids, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 2180.095, 'debit': 1090.05, 'credit': 0.0, }, { **self.tax_line_vals_1, 'price_unit': -327.014, 'price_subtotal': -327.014, 'price_total': -327.014, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 327.014, 'debit': 163.51, 'credit': 0.0, }, { 'name': tax_price_include.name, 'product_id': False, 'account_id': self.product_line_vals_1['account_id'], 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -119.905, 'price_subtotal': -119.905, 'price_total': -119.905, 'tax_ids': [], 'tax_line_id': tax_price_include.id, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 119.905, 'debit': 59.95, 'credit': 0.0, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': 2627.014, 'price_subtotal': 2627.014, 'price_total': 2627.014, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -2627.014, 'debit': 0.0, 'credit': 1313.51, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'amount_untaxed': -2180.095, 'amount_tax': -446.919, 'amount_total': -2627.014, }) def test_out_invoice_line_onchange_analytic(self): self.env.user.groups_id += self.env.ref('analytic.group_analytic_accounting') self.env.user.groups_id += self.env.ref('analytic.group_analytic_tags') analytic_tag = self.env['account.analytic.tag'].create({ 'name': 'test_analytic_tag', }) analytic_account = self.env['account.analytic.account'].create({ 'name': 'test_analytic_account', 'partner_id': self.invoice.partner_id.id, 'code': 'TEST' }) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.analytic_account_id = analytic_account line_form.analytic_tag_ids.add(analytic_tag) move_form.save() # The tax is not flagged as an analytic one. It should change nothing on the taxes. self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'analytic_account_id': analytic_account.id, 'analytic_tag_ids': analytic_tag.ids, }, { **self.product_line_vals_2, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.tax_line_vals_1, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.tax_line_vals_2, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.term_line_vals_1, 'analytic_account_id': False, 'analytic_tag_ids': [], }, ], self.move_vals) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.analytic_account_id = self.env['account.analytic.account'] line_form.analytic_tag_ids.clear() move_form.save() # Enable the analytic self.tax_sale_a.analytic = True move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.analytic_account_id = analytic_account line_form.analytic_tag_ids.add(analytic_tag) move_form.save() # The tax is flagged as an analytic one. # A new tax line must be generated. self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'analytic_account_id': analytic_account.id, 'analytic_tag_ids': analytic_tag.ids, }, { **self.product_line_vals_2, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.tax_line_vals_1, 'price_unit': 150.0, 'price_subtotal': 150.0, 'price_total': 150.0, 'amount_currency': -150.0, 'credit': 150.0, 'analytic_account_id': analytic_account.id, 'analytic_tag_ids': analytic_tag.ids, }, { **self.tax_line_vals_1, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'amount_currency': -30.0, 'credit': 30.0, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.tax_line_vals_2, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.term_line_vals_1, 'analytic_account_id': False, 'analytic_tag_ids': [], }, ], self.move_vals) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.analytic_account_id = self.env['account.analytic.account'] line_form.analytic_tag_ids.clear() move_form.save() # The tax line has been removed. self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.product_line_vals_2, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.tax_line_vals_1, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.tax_line_vals_2, 'analytic_account_id': False, 'analytic_tag_ids': [], }, { **self.term_line_vals_1, 'analytic_account_id': False, 'analytic_tag_ids': [], }, ], self.move_vals) def test_out_invoice_line_onchange_analytic_2(self): self.env.user.groups_id += self.env.ref('analytic.group_analytic_accounting') analytic_account = self.env['account.analytic.account'].create({ 'name': 'test_analytic_account1', 'code': 'TEST1' }) self.invoice.write({'invoice_line_ids': [(1, self.invoice.invoice_line_ids.ids[0], { 'analytic_account_id': analytic_account.id, })]}) self.assertRecordValues(self.invoice.invoice_line_ids, [ {'analytic_account_id': analytic_account.id}, {'analytic_account_id': False}, ]) # We can remove the analytic account, it is not recomputed by an invalidation self.invoice.write({'invoice_line_ids': [(1, self.invoice.invoice_line_ids.ids[0], { 'analytic_account_id': False, })]}) self.assertRecordValues(self.invoice.invoice_line_ids, [ {'analytic_account_id': False}, {'analytic_account_id': False}, ]) def test_out_invoice_line_onchange_cash_rounding_1(self): # Test 'add_invoice_line' rounding move_form = Form(self.invoice) # Add a cash rounding having 'add_invoice_line'. move_form.invoice_cash_rounding_id = self.cash_rounding_a move_form.save() # The cash rounding does nothing as the total is already rounded. self.assertInvoiceValues(self.invoice, [ self.product_line_vals_1, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: line_form.price_unit = 999.99 move_form.save() self.assertInvoiceValues(self.invoice, [ { 'name': 'add_invoice_line', 'product_id': False, 'account_id': self.cash_rounding_a.profit_account_id.id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': 0.01, 'price_subtotal': 0.01, 'price_total': 0.01, 'tax_ids': [], 'tax_line_id': False, 'currency_id': self.company_data['currency'].id, 'amount_currency': -0.01, 'debit': 0.0, 'credit': 0.01, 'date_maturity': False, }, { **self.product_line_vals_1, 'price_unit': 999.99, 'price_subtotal': 999.99, 'price_total': 1149.99, 'amount_currency': -999.99, 'credit': 999.99, }, self.product_line_vals_2, self.tax_line_vals_1, self.tax_line_vals_2, self.term_line_vals_1, ], self.move_vals) # Test 'biggest_tax' rounding self.company_data['company'].country_id = self.env.ref('base.us') # Add a tag to product_a's default tax tax_line_tag = self.env['account.account.tag'].create({ 'name': "Tax tag", 'applicability': 'taxes', 'country_id': self.company_data['company'].country_id.id, }) repartition_line = self.tax_sale_a.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') repartition_line.write({'tag_ids': [(4, tax_line_tag.id, 0)]}) # Create the invoice biggest_tax_invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2019-01-01', 'partner_id': self.partner_a.id, 'invoice_cash_rounding_id': self.cash_rounding_b.id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, 0, { 'product_id': self.product_a.id, 'price_unit': 999.99, 'tax_ids': [(6, 0, self.product_a.taxes_id.ids)], 'product_uom_id': self.product_a.uom_id.id, }), (0, 0, { 'product_id': self.product_b.id, 'price_unit': self.product_b.lst_price, 'tax_ids': [(6, 0, self.product_b.taxes_id.ids)], 'product_uom_id': self.product_b.uom_id.id, }), ], }) self.assertInvoiceValues(biggest_tax_invoice, [ { **self.product_line_vals_1, 'price_unit': 999.99, 'price_subtotal': 999.99, 'price_total': 1149.99, 'amount_currency': -999.99, 'credit': 999.99, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { **self.product_line_vals_2, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, { **self.tax_line_vals_1, 'tax_repartition_line_id': repartition_line.id, 'tax_tag_ids': tax_line_tag.ids, }, { **self.tax_line_vals_2, 'tax_repartition_line_id': self.tax_sale_b.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_tag_ids': [], }, { 'name': '%s (rounding)' % self.tax_sale_a.name, 'product_id': False, 'account_id': self.company_data['default_account_tax_sale'].id, 'partner_id': self.partner_a.id, 'product_uom_id': False, 'quantity': 1.0, 'discount': 0.0, 'price_unit': -0.04, 'price_subtotal': -0.04, 'price_total': -0.04, 'tax_ids': [], 'tax_line_id': self.tax_sale_a.id, 'tax_repartition_line_id': repartition_line.id, 'tax_tag_ids': tax_line_tag.ids, 'currency_id': self.company_data['currency'].id, 'amount_currency': 0.04, 'debit': 0.04, 'credit': 0.0, 'date_maturity': False, }, { **self.term_line_vals_1, 'price_unit': -1409.95, 'price_subtotal': -1409.95, 'price_total': -1409.95, 'amount_currency': 1409.95, 'debit': 1409.95, 'tax_repartition_line_id': None, 'tax_tag_ids': [], }, ], { **self.move_vals, 'amount_untaxed': 1199.99, 'amount_tax': 209.96, 'amount_total': 1409.95, }) def test_cash_rounding_with_rounding_method_set_to_global(self): """ Test that cash roundings are computed correctly when tax calculation rounding method is set to `round_globally`. """ self.env.company.tax_calculation_rounding_method = 'round_globally' cash_rounding = self.env['account.cash.rounding'].create({ 'name': 'add_invoice_line', 'rounding': 0.05, 'strategy': 'add_invoice_line', 'profit_account_id': self.company_data['default_account_revenue'].copy().id, 'loss_account_id': self.company_data['default_account_expense'].copy().id, 'rounding_method': 'HALF-UP', }) tax7_7 = self.env['account.tax'].create({ 'name': "tax7_7", 'amount_type': 'percent', 'amount': 7.7, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2019-01-01', 'partner_id': self.partner_a.id, 'invoice_cash_rounding_id': cash_rounding.id, 'invoice_line_ids': [ (0, 0, { 'name': 'test product', 'price_unit': 295.0, 'tax_ids': [(6, 0, tax7_7.ids)], }), ], }) self.assertEqual(invoice.amount_total, 317.70) def test_out_invoice_line_onchange_currency_1(self): move_form = Form(self.invoice.with_context(dudu=True)) move_form.currency_id = self.currency_data['currency'] move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'credit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'credit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -180.0, 'credit': 90.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'credit': 15.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1410.0, 'debit': 705.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) move_form = Form(self.invoice) # Change the date to get another rate: 1/3 instead of 1/2. move_form.date = fields.Date.from_string('2016-01-01') move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'credit': 333.33, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'credit': 66.67, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -180.0, 'credit': 60.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'credit': 10.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1410.0, 'debit': 470.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), }) move_form = Form(self.invoice) with move_form.invoice_line_ids.edit(0) as line_form: # 0.045 * 0.1 = 0.0045. As the foreign currency has a 0.001 rounding, # the result should be 0.005 after rounding. line_form.quantity = 0.1 line_form.price_unit = 0.045 move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 0.1, 'price_unit': 0.05, 'price_subtotal': 0.005, 'price_total': 0.006, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -0.005, 'credit': 0.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'credit': 66.67, }, { **self.tax_line_vals_1, 'price_unit': 30.0, 'price_subtotal': 30.001, 'price_total': 30.001, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.001, 'credit': 10.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'credit': 10.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'price_unit': -260.01, 'price_subtotal': -260.006, 'price_total': -260.006, 'amount_currency': 260.006, 'debit': 86.67, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), 'amount_untaxed': 200.005, 'amount_tax': 60.001, 'amount_total': 260.006, }) # Exit the multi-currencies. move_form = Form(self.invoice) move_form.currency_id = self.company_data['currency'] move_form.save() self.assertInvoiceValues(self.invoice, [ { **self.product_line_vals_1, 'quantity': 0.1, 'price_unit': 0.05, 'price_subtotal': 0.01, 'price_total': 0.01, 'amount_currency': -0.01, 'credit': 0.01, }, self.product_line_vals_2, { **self.tax_line_vals_1, 'price_unit': 30.0, 'price_subtotal': 30.0, 'price_total': 30.0, 'amount_currency': -30.0, 'credit': 30.0, }, self.tax_line_vals_2, { **self.term_line_vals_1, 'price_unit': -260.01, 'price_subtotal': -260.01, 'price_total': -260.01, 'amount_currency': 260.01, 'debit': 260.01, }, ], { **self.move_vals, 'currency_id': self.company_data['currency'].id, 'date': fields.Date.from_string('2016-01-01'), 'amount_untaxed': 200.01, 'amount_tax': 60.0, 'amount_total': 260.01, }) def test_out_invoice_line_tax_fixed_price_include_free_product(self): ''' Check that fixed tax include are correctly computed while the price_unit is 0 ''' fixed_tax_price_include = self.env['account.tax'].create({ 'name': 'BEBAT 0.05', 'type_tax_use': 'sale', 'amount_type': 'fixed', 'amount': 0.05, 'price_include': True, 'include_base_amount': True, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2022-03-03', 'date': '2022-03-03', 'partner_id': self.partner_a.id, 'invoice_line_ids': [(0, 0, { 'name': 'Free product', 'price_unit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, fixed_tax_price_include.ids)], })], }) self.assertRecordValues(invoice, [{ 'amount_untaxed': -0.05, 'amount_tax': 0.05, 'amount_total': 0.0, }]) def test_out_invoice_line_taxes_fixed_price_include_free_product(self): ''' Check that fixed tax include are correctly computed while the price_unit is 0 ''' # please ensure this test remains consistent with # test_free_product_and_price_include_fixed_tax in the sale module fixed_tax_price_include_1 = self.env['account.tax'].create({ 'name': 'BEBAT 0.05', 'type_tax_use': 'sale', 'amount_type': 'fixed', 'amount': 0.05, 'price_include': True, 'include_base_amount': True, }) fixed_tax_price_include_2 = self.env['account.tax'].create({ 'name': 'Recupel 0.25', 'type_tax_use': 'sale', 'amount_type': 'fixed', 'amount': 0.25, 'price_include': True, 'include_base_amount': True, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2022-03-03', 'date': '2022-03-03', 'partner_id': self.partner_a.id, 'invoice_line_ids': [(0, 0, { 'name': 'Free product', 'price_unit': 0.0, 'account_id': self.company_data['default_account_revenue'].id, 'tax_ids': [(6, 0, (fixed_tax_price_include_1 + fixed_tax_price_include_2).ids)], })], }) self.assertRecordValues(invoice, [{ 'amount_untaxed': -0.30, 'amount_tax': 0.30, 'amount_total': 0.0, }]) def test_out_invoice_create_refund(self): self.invoice.action_post() move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.from_string('2019-02-01'), 'reason': 'no reason', 'refund_method': 'refund', 'journal_id': self.invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertEqual(self.invoice.payment_state, 'not_paid', "Refunding with a draft credit note should keep the invoice 'not_paid'.") self.assertInvoiceValues(reverse_move, [ { **self.product_line_vals_1, 'amount_currency': 1000.0, 'debit': 1000.0, 'credit': 0.0, }, { **self.product_line_vals_2, 'amount_currency': 200.0, 'debit': 200.0, 'credit': 0.0, }, { **self.tax_line_vals_1, 'amount_currency': 180.0, 'debit': 180.0, 'credit': 0.0, }, { **self.tax_line_vals_2, 'amount_currency': 30.0, 'debit': 30.0, 'credit': 0.0, }, { **self.term_line_vals_1, 'name': '', 'amount_currency': -1410.0, 'debit': 0.0, 'credit': 1410.0, 'date_maturity': move_reversal.date, }, ], { **self.move_vals, 'invoice_payment_term_id': None, 'name': 'RINV/2019/00001', 'date': move_reversal.date, 'state': 'draft', 'ref': 'Reversal of: %s, %s' % (self.invoice.name, move_reversal.reason), 'payment_state': 'not_paid', }) move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.from_string('2019-02-01'), 'reason': 'no reason', 'refund_method': 'cancel', 'journal_id': self.invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertEqual(self.invoice.payment_state, 'reversed', "After cancelling it with a reverse invoice, an invoice should be in 'reversed' state.") self.assertInvoiceValues(reverse_move, [ { **self.product_line_vals_1, 'amount_currency': 1000.0, 'debit': 1000.0, 'credit': 0.0, }, { **self.product_line_vals_2, 'amount_currency': 200.0, 'debit': 200.0, 'credit': 0.0, }, { **self.tax_line_vals_1, 'amount_currency': 180.0, 'debit': 180.0, 'credit': 0.0, }, { **self.tax_line_vals_2, 'amount_currency': 30.0, 'debit': 30.0, 'credit': 0.0, }, { **self.term_line_vals_1, 'name': '', 'amount_currency': -1410.0, 'debit': 0.0, 'credit': 1410.0, 'date_maturity': move_reversal.date, }, ], { **self.move_vals, 'invoice_payment_term_id': None, 'date': move_reversal.date, 'state': 'posted', 'ref': 'Reversal of: %s, %s' % (self.invoice.name, move_reversal.reason), 'payment_state': 'paid', }) def test_out_invoice_create_refund_multi_currency(self): ''' Test the account.move.reversal takes care about the currency rates when setting a custom reversal date. ''' move_form = Form(self.invoice) move_form.date = '2016-01-01' move_form.currency_id = self.currency_data['currency'] move_form.save() self.invoice.action_post() # The currency rate changed from 1/3 to 1/2. move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.from_string('2017-01-01'), 'reason': 'no reason', 'refund_method': 'refund', 'journal_id': self.invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertEqual(self.invoice.payment_state, 'not_paid', "Refunding with a draft credit note should keep the invoice 'not_paid'.") self.assertInvoiceValues(reverse_move, [ { **self.product_line_vals_1, 'amount_currency': 1000.0, 'currency_id': self.currency_data['currency'].id, 'debit': 500.0, 'credit': 0.0, }, { **self.product_line_vals_2, 'amount_currency': 200.0, 'currency_id': self.currency_data['currency'].id, 'debit': 100.0, 'credit': 0.0, }, { **self.tax_line_vals_1, 'amount_currency': 180.0, 'currency_id': self.currency_data['currency'].id, 'debit': 90.0, 'credit': 0.0, }, { **self.tax_line_vals_2, 'amount_currency': 30.0, 'currency_id': self.currency_data['currency'].id, 'debit': 15.0, 'credit': 0.0, }, { **self.term_line_vals_1, 'name': '', 'amount_currency': -1410.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 705.0, 'date_maturity': move_reversal.date, }, ], { **self.move_vals, 'invoice_payment_term_id': None, 'currency_id': self.currency_data['currency'].id, 'date': move_reversal.date, 'state': 'draft', 'ref': 'Reversal of: %s, %s' % (self.invoice.name, move_reversal.reason), 'payment_state': 'not_paid', }) move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.from_string('2017-01-01'), 'reason': 'no reason', 'refund_method': 'cancel', 'journal_id': self.invoice.journal_id.id, }) reversal = move_reversal.reverse_moves() reverse_move = self.env['account.move'].browse(reversal['res_id']) self.assertEqual(self.invoice.payment_state, 'reversed', "After cancelling it with a reverse invoice, an invoice should be in 'reversed' state.") self.assertInvoiceValues(reverse_move, [ { **self.product_line_vals_1, 'amount_currency': 1000.0, 'currency_id': self.currency_data['currency'].id, 'debit': 500.0, 'credit': 0.0, }, { **self.product_line_vals_2, 'amount_currency': 200.0, 'currency_id': self.currency_data['currency'].id, 'debit': 100.0, 'credit': 0.0, }, { **self.tax_line_vals_1, 'amount_currency': 180.0, 'currency_id': self.currency_data['currency'].id, 'debit': 90.0, 'credit': 0.0, }, { **self.tax_line_vals_2, 'amount_currency': 30.0, 'currency_id': self.currency_data['currency'].id, 'debit': 15.0, 'credit': 0.0, }, { **self.term_line_vals_1, 'name': '', 'amount_currency': -1410.0, 'currency_id': self.currency_data['currency'].id, 'debit': 0.0, 'credit': 705.0, 'date_maturity': move_reversal.date, }, ], { **self.move_vals, 'invoice_payment_term_id': None, 'currency_id': self.currency_data['currency'].id, 'date': move_reversal.date, 'state': 'posted', 'ref': 'Reversal of: %s, %s' % (self.invoice.name, move_reversal.reason), 'payment_state': 'paid', }) def test_out_invoice_create_refund_auto_post(self): self.invoice.action_post() move_reversal = self.env['account.move.reversal'].with_context(active_model="account.move", active_ids=self.invoice.ids).create({ 'date': fields.Date.today() + timedelta(days=7), 'reason': 'no reason', 'refund_method': 'modify', 'journal_id': self.invoice.journal_id.id, }) move_reversal.reverse_moves() refund = self.env['account.move'].search([('move_type', '=', 'out_refund'), ('company_id', '=', self.invoice.company_id.id)]) self.assertRecordValues(refund, [{ 'state': 'draft', 'auto_post': True, }]) def test_out_invoice_create_1(self): # Test creating an account_move with the least information. move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, None, { 'product_id': self.product_a.id, 'product_uom_id': self.product_a.uom_id.id, 'quantity': 1.0, 'price_unit': 1000.0, 'tax_ids': [(6, 0, self.product_a.taxes_id.ids)], }), (0, None, { 'product_id': self.product_b.id, 'product_uom_id': self.product_b.uom_id.id, 'quantity': 1.0, 'price_unit': 200.0, 'tax_ids': [(6, 0, self.product_b.taxes_id.ids)], }), ] }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'credit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'credit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -180.0, 'credit': 90.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'credit': 15.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1410.0, 'debit': 705.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_out_invoice_create_child_partner(self): # Test creating an account_move on a child partner. # This needs to attach the lines to the parent partner id. partner_a_child = self.env['res.partner'].create({ 'name': 'partner_a_child', 'parent_id': self.partner_a.id }) move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': partner_a_child.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertEqual(partner_a_child.id, move.partner_id.id, 'Keep child partner on the account move record') self.assertEqual(self.partner_a.id, move.line_ids[0].partner_id.id, 'Set parent partner on the account move line records') def test_out_invoice_write_1(self): # Test creating an account_move with the least information. move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), ], }) move.write({ 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'credit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'credit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -180.0, 'credit': 90.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'credit': 15.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1410.0, 'debit': 705.0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_out_invoice_write_2(self): ''' Ensure to not messing the invoice when writing a bad account type. ''' move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_line_ids': [ (0, None, { 'name': 'test_out_invoice_write_2', 'quantity': 1.0, 'price_unit': 2000, }), ] }) receivable_lines = move.line_ids.filtered(lambda line: line.account_id.user_type_id.type == 'receivable') not_receivable_lines = move.line_ids - receivable_lines # Write a receivable account on a not-receivable line. with self.assertRaises(UserError), self.cr.savepoint(): not_receivable_lines.write({'account_id': receivable_lines[0].account_id.copy().id}) # Write a not-receivable account on a receivable line. with self.assertRaises(UserError), self.cr.savepoint(): receivable_lines.write({'account_id': not_receivable_lines[0].account_id.copy().id}) # Write another receivable account on a receivable line. receivable_lines.write({'account_id': receivable_lines[0].account_id.copy().id}) def test_out_invoice_post_1(self): ''' Check the invoice_date will be set automatically at the post date. ''' frozen_today = fields.Date.today() with patch.object(fields.Date, 'today', lambda *args, **kwargs: frozen_today), patch.object(fields.Date, 'context_today', lambda *args, **kwargs: frozen_today): # Create an invoice with rate 1/3. move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2016-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) # Remove the invoice_date to check: # - The invoice_date must be set automatically at today during the post. # - As the invoice_date changed, date did too so the currency rate has changed (1/3 => 1/2). # - A different invoice_date implies also a new date_maturity. # Add a manual edition of a tax line: # - The modification must be preserved in the business fields. # - The journal entry must be balanced before / after the post. move.write({ 'invoice_date': False, 'line_ids': [ (1, move.line_ids.filtered(lambda line: line.tax_line_id.id == self.tax_line_vals_1['tax_line_id']).id, { 'amount_currency': -200.0, }), (1, move.line_ids.filtered(lambda line: line.date_maturity).id, { 'amount_currency': 1430.0, }), ], }) move.action_post() self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'credit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'credit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'price_unit': 200.0, 'price_subtotal': 200.0, 'price_total': 200.0, 'amount_currency': -200.0, 'credit': 100.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'credit': 15.0, }, { **self.term_line_vals_1, 'name': move.name, 'currency_id': self.currency_data['currency'].id, 'price_unit': -1430.0, 'price_subtotal': -1430.0, 'price_total': -1430.0, 'amount_currency': 1430.0, 'debit': 715.0, 'date_maturity': frozen_today, }, ], { **self.move_vals, 'payment_reference': move.name, 'currency_id': self.currency_data['currency'].id, 'date': frozen_today, 'invoice_date': frozen_today, 'invoice_date_due': frozen_today, 'amount_tax': 230.0, 'amount_total': 1430.0, }) @freeze_time('2017-01-15') def test_out_invoice_post_2(self): ''' Check the date will be set automatically at today due to the tax lock date. ''' # Create an invoice with rate 1/3. move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2016-01-01'), 'date': fields.Date.from_string('2015-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, None, { 'name': self.product_line_vals_1['name'], 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'quantity': self.product_line_vals_1['quantity'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': self.product_line_vals_1['tax_ids'], }), (0, None, { 'name': self.product_line_vals_2['name'], 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'quantity': self.product_line_vals_2['quantity'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': self.product_line_vals_2['tax_ids'], }), ], }) # Add a manual edition of a tax line: # - The modification must be preserved in the business fields. # - The journal entry must be balanced before / after the post. move.write({ 'line_ids': [ (1, move.line_ids.filtered(lambda line: line.tax_line_id.id == self.tax_line_vals_1['tax_line_id']).id, { 'amount_currency': -200.0, }), (1, move.line_ids.filtered(lambda line: line.date_maturity).id, { 'amount_currency': 1430.0, }), ], }) # Set the tax lock date: # - The date must be set automatically at the date of today (2017-01-15). # - As the date changed, the currency rate has changed (1/3 => 1/2). move.company_id.tax_lock_date = fields.Date.from_string('2016-12-31') move.action_post() self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'debit': 0.0, 'credit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'debit': 0.0, 'credit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'price_unit': 200.0, 'price_subtotal': 200.0, 'price_total': 200.0, 'amount_currency': -200.0, 'debit': 0.0, 'credit': 100.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'debit': 0.0, 'credit': 15.0, }, { **self.term_line_vals_1, 'name': move.name, 'currency_id': self.currency_data['currency'].id, 'price_unit': -1430.0, 'price_subtotal': -1430.0, 'price_total': -1430.0, 'amount_currency': 1430.0, 'debit': 715.0, 'credit': 0.0, 'date_maturity': fields.Date.from_string('2016-01-01'), }, ], { **self.move_vals, 'payment_reference': move.name, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2017-01-15'), 'amount_untaxed': 1200.0, 'amount_tax': 230.0, 'amount_total': 1430.0, }) def test_out_invoice_switch_out_refund_1(self): # Test creating an account_move with an out_invoice_type and switch it in an out_refund. move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) move.action_switch_invoice_into_refund_credit_note() self.assertRecordValues(move, [{'move_type': 'out_refund'}]) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1000.0, 'debit': 500.0, 'credit': 0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 100.0, 'credit': 0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 180.0, 'debit': 90.0, 'credit': 0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'debit': 15.0, 'credit': 0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1410.0, 'credit': 705.0, 'debit': 0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, }) def test_out_invoice_switch_out_refund_2(self): # Test creating an account_move with an out_invoice_type and switch it in an out_refund and a negative quantity. move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ Command.create({ 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'price_unit': self.product_line_vals_1['price_unit'], 'quantity': -self.product_line_vals_1['quantity'], 'tax_ids': [Command.set(self.product_line_vals_1['tax_ids'])], }), Command.create({ 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'price_unit': self.product_line_vals_2['price_unit'], 'quantity': -self.product_line_vals_2['quantity'], 'tax_ids': [Command.set(self.product_line_vals_2['tax_ids'])], }), ], }) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1000.0, 'price_subtotal': -1000.0, 'price_total': -1150.0, 'debit': 500.0, 'credit': 0, 'quantity': -1.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'price_subtotal': -200.0, 'price_total': -260.0, 'debit': 100.0, 'credit': 0, 'quantity': -1.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 180.0, 'price_subtotal': -180.0, 'price_total': -180.0, 'price_unit': -180.0, 'debit': 90.0, 'credit': 0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'price_subtotal': -30.0, 'price_total': -30.0, 'price_unit': -30.0, 'debit': 15.0, 'credit': 0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1410.0, 'price_subtotal': 1410.0, 'price_total': 1410.0, 'price_unit': 1410.0, 'credit': 705.0, 'debit': 0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'amount_tax' : -self.move_vals['amount_tax'], 'amount_total' : -self.move_vals['amount_total'], 'amount_untaxed' : -self.move_vals['amount_untaxed'], }) move.action_switch_invoice_into_refund_credit_note() self.assertRecordValues(move, [{'move_type': 'out_refund'}]) self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 1000.0, 'debit': 500.0, 'credit': 0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 200.0, 'debit': 100.0, 'credit': 0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 180.0, 'debit': 90.0, 'credit': 0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': 30.0, 'debit': 15.0, 'credit': 0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1410.0, 'credit': 705.0, 'debit': 0, }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'amount_tax' : self.move_vals['amount_tax'], 'amount_total' : self.move_vals['amount_total'], 'amount_untaxed' : self.move_vals['amount_untaxed'], }) def test_out_invoice_reverse_move_tags(self): country = self.env.ref('base.us') tags = self.env['account.account.tag'].create([{ 'name': "Test tag %s" % i, 'applicability': 'taxes', 'country_id': country.id, } for i in range(8)]) taxes = self.env['account.tax'].create([{ 'name': "Test tax include_base_amount = %s" % include_base_amount, 'amount': 10.0, 'include_base_amount': include_base_amount, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tags[(i * 4)].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'tag_ids': [(6, 0, tags[(i * 4) + 1].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tags[(i * 4) + 2].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'tag_ids': [(6, 0, tags[(i * 4) + 3].ids)], }), ], } for i, include_base_amount in enumerate((True, False))]) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, 0, { 'product_id': self.product_a.id, 'price_unit': 1000.0, 'tax_ids': [(6, 0, taxes.ids)], }), ] }) invoice.action_post() self.assertRecordValues(invoice.line_ids.sorted('tax_line_id'), [ # Product line {'tax_line_id': False, 'tax_ids': taxes.ids, 'tax_tag_ids': (tags[0] + tags[4]).ids}, # Receivable line {'tax_line_id': False, 'tax_ids': [], 'tax_tag_ids': []}, # Tax lines {'tax_line_id': taxes[0].id, 'tax_ids': taxes[1].ids, 'tax_tag_ids': (tags[1] + tags[4]).ids}, {'tax_line_id': taxes[1].id, 'tax_ids': [], 'tax_tag_ids': tags[5].ids}, ]) refund = invoice._reverse_moves(cancel=True) self.assertRecordValues(refund.line_ids.sorted('tax_line_id'), [ # Product line {'tax_line_id': False, 'tax_ids': taxes.ids, 'tax_tag_ids': (tags[2] + tags[6]).ids}, # Receivable line {'tax_line_id': False, 'tax_ids': [], 'tax_tag_ids': []}, # Tax lines {'tax_line_id': taxes[0].id, 'tax_ids': taxes[1].ids, 'tax_tag_ids': (tags[3] + tags[6]).ids}, {'tax_line_id': taxes[1].id, 'tax_ids': [], 'tax_tag_ids': tags[7].ids}, ]) def test_out_invoice_change_period_accrual_1(self): move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'date': '2017-01-01', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2017-01-01'), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, None, { 'name': self.product_line_vals_1['name'], 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'quantity': self.product_line_vals_1['quantity'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': self.product_line_vals_1['tax_ids'], }), (0, None, { 'name': self.product_line_vals_2['name'], 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'quantity': self.product_line_vals_2['quantity'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': self.product_line_vals_2['tax_ids'], }), ] }) move.action_post() wizard = self.env['account.automatic.entry.wizard']\ .with_context(active_model='account.move.line', active_ids=move.invoice_line_ids.ids).create({ 'action': 'change_period', 'date': '2018-01-01', 'percentage': 60, 'journal_id': self.company_data['default_journal_misc'].id, 'expense_accrual_account': self.env['account.account'].create({ 'name': 'Accrual Expense Account', 'code': '234567', 'user_type_id': self.env.ref('account.data_account_type_expenses').id, 'reconcile': True, }).id, 'revenue_accrual_account': self.env['account.account'].create({ 'name': 'Accrual Revenue Account', 'code': '765432', 'user_type_id': self.env.ref('account.data_account_type_expenses').id, 'reconcile': True, }).id, }) wizard_res = wizard.do_action() self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'debit': 0.0, 'credit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'debit': 0.0, 'credit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -180.0, 'debit': 0.0, 'credit': 90.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'debit': 0.0, 'credit': 15.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'name': 'INV/2017/00001', 'amount_currency': 1410.0, 'debit': 705.0, 'credit': 0.0, 'date_maturity': fields.Date.from_string('2017-01-01'), }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string('2017-01-01'), 'payment_reference': 'INV/2017/00001', }) accrual_lines = self.env['account.move'].browse(wizard_res['domain'][0][2]).line_ids.sorted('date') self.assertRecordValues(accrual_lines, [ {'amount_currency': 600.0, 'debit': 300.0, 'credit': 0.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': -600.0, 'debit': 0.0, 'credit': 300.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': 120.0, 'debit': 60.0, 'credit': 0.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': -120.0, 'debit': 0.0, 'credit': 60.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': -600.0, 'debit': 0.0, 'credit': 300.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': 600.0, 'debit': 300.0, 'credit': 0.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': -120.0, 'debit': 0.0, 'credit': 60.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': 120.0, 'debit': 60.0, 'credit': 0.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, ]) def test_out_invoice_multi_date_change_period_accrual(self): dates = ['2017-01-01', '2017-01-01', '2017-02-01'] values = [] for date in dates: values.append({ 'move_type': 'out_invoice', 'date': date, 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string(date), 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.pay_terms_a.id, 'invoice_line_ids': [ (0, None, { 'name': self.product_line_vals_1['name'], 'product_id': self.product_line_vals_1['product_id'], 'product_uom_id': self.product_line_vals_1['product_uom_id'], 'quantity': self.product_line_vals_1['quantity'], 'price_unit': self.product_line_vals_1['price_unit'], 'tax_ids': self.product_line_vals_1['tax_ids'], }), (0, None, { 'name': self.product_line_vals_2['name'], 'product_id': self.product_line_vals_2['product_id'], 'product_uom_id': self.product_line_vals_2['product_uom_id'], 'quantity': self.product_line_vals_2['quantity'], 'price_unit': self.product_line_vals_2['price_unit'], 'tax_ids': self.product_line_vals_2['tax_ids'], }), ] }) moves = self.env['account.move'].create(values) moves.action_post() wizard = self.env['account.automatic.entry.wizard'].with_context( active_model='account.move.line', active_ids=moves.invoice_line_ids.ids, ).create({ 'action': 'change_period', 'date': '2018-01-01', 'percentage': 60, 'journal_id': self.company_data['default_journal_misc'].id, 'expense_accrual_account': self.env['account.account'].create({ 'name': 'Accrual Expense Account', 'code': '234567', 'user_type_id': self.env.ref('account.data_account_type_expenses').id, 'reconcile': True, }).id, 'revenue_accrual_account': self.env['account.account'].create({ 'name': 'Accrual Revenue Account', 'code': '765432', 'user_type_id': self.env.ref('account.data_account_type_expenses').id, 'reconcile': True, }).id, }) wizard_res = wizard.do_action() for date, move, ref in zip(dates, moves, ['INV/2017/00001', 'INV/2017/00002', 'INV/2017/00003']): self.assertInvoiceValues(move, [ { **self.product_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'debit': 0.0, 'credit': 500.0, }, { **self.product_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'debit': 0.0, 'credit': 100.0, }, { **self.tax_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -180.0, 'debit': 0.0, 'credit': 90.0, }, { **self.tax_line_vals_2, 'currency_id': self.currency_data['currency'].id, 'amount_currency': -30.0, 'debit': 0.0, 'credit': 15.0, }, { **self.term_line_vals_1, 'currency_id': self.currency_data['currency'].id, 'name': ref, 'amount_currency': 1410.0, 'debit': 705.0, 'credit': 0.0, 'date_maturity': fields.Date.from_string(date), }, ], { **self.move_vals, 'currency_id': self.currency_data['currency'].id, 'date': fields.Date.from_string(date), 'payment_reference': ref, }) moves = self.env['account.move'].browse(wizard_res['domain'][0][2]) accrual_lines = moves.line_ids.sorted('date') self.assertRecordValues(accrual_lines, [ {'amount_currency': 600.0, 'debit': 300.0, 'credit': 0.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': -600.0, 'debit': 0.0, 'credit': 300.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': 120.0, 'debit': 60.0, 'credit': 0.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': -120.0, 'debit': 0.0, 'credit': 60.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': 600.0, 'debit': 300.0, 'credit': 0.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': -600.0, 'debit': 0.0, 'credit': 300.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': 120.0, 'debit': 60.0, 'credit': 0.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': -120.0, 'debit': 0.0, 'credit': 60.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': 600.0, 'debit': 300.0, 'credit': 0.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': -600.0, 'debit': 0.0, 'credit': 300.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': 120.0, 'debit': 60.0, 'credit': 0.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': -120.0, 'debit': 0.0, 'credit': 60.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': -600.0, 'debit': 0.0, 'credit': 300.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': 600.0, 'debit': 300.0, 'credit': 0.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': -120.0, 'debit': 0.0, 'credit': 60.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': 120.0, 'debit': 60.0, 'credit': 0.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': -600.0, 'debit': 0.0, 'credit': 300.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': 600.0, 'debit': 300.0, 'credit': 0.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': -120.0, 'debit': 0.0, 'credit': 60.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': 120.0, 'debit': 60.0, 'credit': 0.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': -600.0, 'debit': 0.0, 'credit': 300.0, 'account_id': self.product_line_vals_1['account_id'], 'reconciled': False}, {'amount_currency': 600.0, 'debit': 300.0, 'credit': 0.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, {'amount_currency': -120.0, 'debit': 0.0, 'credit': 60.0, 'account_id': self.product_line_vals_2['account_id'], 'reconciled': False}, {'amount_currency': 120.0, 'debit': 60.0, 'credit': 0.0, 'account_id': wizard.revenue_accrual_account.id, 'reconciled': True}, ]) def test_out_invoice_filter_zero_balance_lines(self): zero_balance_payment_term = self.env['account.payment.term'].create({ 'name': 'zero_balance_payment_term', 'line_ids': [ (0, 0, { 'value': 'percent', 'value_amount': 100.0, 'sequence': 10, 'days': 0, 'option': 'day_after_invoice_date', }), (0, 0, { 'value': 'balance', 'value_amount': 0.0, 'sequence': 20, 'days': 0, 'option': 'day_after_invoice_date', }), ], }) zero_balance_tax = self.env['account.tax'].create({ 'name': 'zero_balance_tax', 'amount_type': 'percent', 'amount': 0.0, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': fields.Date.from_string('2019-01-01'), 'invoice_payment_term_id': zero_balance_payment_term.id, 'invoice_line_ids': [(0, None, { 'name': 'whatever', 'quantity': 1.0, 'price_unit': 1000.0, 'tax_ids': [(6, 0, zero_balance_tax.ids)], })] }) self.assertEqual(len(invoice.invoice_line_ids), 1) self.assertEqual(len(invoice.line_ids), 2) def test_out_invoice_recomputation_receivable_lines(self): ''' Test a tricky specific case caused by some framework limitations. Indeed, when saving a record, some fields are written to the records even if the value is the same as the previous one. It could lead to an unbalanced journal entry when the recomputed line is the receivable/payable one. For example, the computed price_subtotal are the following: 1471.95 / 0.14 = 10513.93 906468.18 / 0.14 = 6474772.71 1730.84 / 0.14 = 12363.14 17.99 / 0.14 = 128.50 SUM = 6497778.28 But when recomputing the receivable line: 909688.96 / 0.14 = 6497778.285714286 => 6497778.29 This recomputation was made because the framework was writing the same 'price_unit' as the previous value leading to a recomputation of the debit/credit. ''' self.env['decimal.precision'].search([ ('name', '=', self.env['account.move.line']._fields['price_unit']._digits), ]).digits = 5 self.env['res.currency.rate'].create({ 'name': '2019-01-01', 'rate': 0.14, 'currency_id': self.currency_data['currency'].id, 'company_id': self.company_data['company'].id, }) invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2019-01-01', 'date': '2019-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.currency_data['currency'].id, 'invoice_payment_term_id': self.env.ref('account.account_payment_term_immediate').id, 'invoice_line_ids': [ (0, 0, {'name': 'line1', 'price_unit': 38.73553, 'quantity': 38.0}), (0, 0, {'name': 'line2', 'price_unit': 4083.19000, 'quantity': 222.0}), (0, 0, {'name': 'line3', 'price_unit': 49.45257, 'quantity': 35.0}), (0, 0, {'name': 'line4', 'price_unit': 17.99000, 'quantity': 1.0}), ], }) # assertNotUnbalancedEntryWhenSaving with Form(invoice) as move_form: move_form.invoice_payment_term_id = self.env.ref('account.account_payment_term_30days') def test_out_invoice_rounding_recomputation_receivable_lines(self): ''' Test rounding error due to the fact that subtracting then rounding is different from rounding then subtracting. ''' self.env['decimal.precision'].search([ ('name', '=', self.env['account.move.line']._fields['price_unit']._digits), ]).digits = 5 self.env['res.currency.rate'].search([]).unlink() invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2019-01-01', 'date': '2019-01-01', 'partner_id': self.partner_a.id, 'invoice_payment_term_id': self.env.ref('account.account_payment_term_immediate').id, }) # assertNotUnbalancedEntryWhenSaving with Form(invoice) as move_form: with move_form.invoice_line_ids.new() as line_form: line_form.name = 'line1' line_form.account_id = self.company_data['default_account_revenue'] line_form.tax_ids.clear() line_form.price_unit = 0.89500 move_form.save() def test_out_invoice_multi_company(self): ''' Ensure the properties are found on the right company. ''' product = self.env['product.product'].create({ 'name': 'product', 'uom_id': self.env.ref('uom.product_uom_unit').id, 'lst_price': 1000.0, 'standard_price': 800.0, 'company_id': False, }) partner = self.env['res.partner'].create({ 'name': 'partner', 'company_id': False, }) journal = self.env['account.journal'].create({ 'name': 'test_out_invoice_multi_company', 'code': 'XXXXX', 'type': 'sale', 'company_id': self.company_data_2['company'].id, }) product.with_company(self.company_data['company']).write({ 'property_account_income_id': self.company_data['default_account_revenue'].id, }) partner.with_company(self.company_data['company']).write({ 'property_account_receivable_id': self.company_data['default_account_receivable'].id, }) product.with_company(self.company_data_2['company']).write({ 'property_account_income_id': self.company_data_2['default_account_revenue'].id, }) partner.with_company(self.company_data_2['company']).write({ 'property_account_receivable_id': self.company_data_2['default_account_receivable'].id, }) def _check_invoice_values(invoice): self.assertInvoiceValues(invoice, [ { 'product_id': product.id, 'account_id': self.company_data_2['default_account_revenue'].id, 'debit': 0.0, 'credit': 1000.0, }, { 'product_id': False, 'account_id': self.company_data_2['default_account_receivable'].id, 'debit': 1000.0, 'credit': 0.0, }, ], { 'amount_untaxed': 1000.0, 'amount_total': 1000.0, }) invoice_create = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2017-01-01', 'date': '2017-01-01', 'partner_id': partner.id, 'journal_id': journal.id, 'invoice_line_ids': [(0, 0, { 'product_id': product.id, 'price_unit': 1000.0, })], }) _check_invoice_values(invoice_create) move_form = Form(self.env['account.move'].with_context(default_move_type='out_invoice')) move_form.journal_id = journal move_form.partner_id = partner move_form.invoice_date = fields.Date.from_string('2017-01-01') with move_form.invoice_line_ids.new() as line_form: line_form.product_id = product line_form.tax_ids.clear() invoice_onchange = move_form.save() _check_invoice_values(invoice_onchange) def test_out_invoice_multiple_switch_payment_terms(self): ''' When switching immediate payment term to 30% advance then back to immediate payment term, ensure the receivable line is back to its previous value. If some business fields are not well updated, it could lead to a recomputation of debit/credit when writing and then, an unbalanced journal entry. ''' # assertNotUnbalancedEntryWhenSaving with Form(self.invoice) as move_form: move_form.invoice_payment_term_id = self.pay_terms_b # Switch to 30% in advance payment terms move_form.invoice_payment_term_id = self.pay_terms_a # Back to immediate payment term def test_out_invoice_copy_custom_date(self): """ When creating a refund for a given invoice, the invoice is copied first. This test ensures the payment terms are well recomputed in order to take the new date into account. """ invoice = self.env['account.move'].create({ 'move_type': 'out_invoice', 'invoice_date': '2017-01-01', 'invoice_date_due': '2017-01-01', 'date': '2017-01-01', 'partner_id': self.partner_a.id, 'currency_id': self.currency_data['currency'].id, 'invoice_line_ids': [ (0, None, { 'product_id': self.product_a.id, 'product_uom_id': self.product_a.uom_id.id, 'quantity': 1.0, 'price_unit': 1000.0, 'tax_ids': [(6, 0, self.product_a.taxes_id.ids)], }), ] }) copy_invoice = invoice.copy(default={'invoice_date_due': '2018-01-01'}) self.assertRecordValues(copy_invoice, [ {'invoice_date_due': fields.Date.from_string('2018-01-01')}, ]) self.assertRecordValues(copy_invoice.line_ids.filtered('date_maturity'), [ {'date_maturity': fields.Date.from_string('2018-01-01')}, ]) def test_out_invoice_note_and_tax_partner_is_set(self): # Make sure that, when creating an invoice by giving a list of lines with the last one being a note, # the partner_id of the tax line is properly set. invoice_vals_list = [{ 'move_type': 'out_invoice', 'currency_id': self.currency_data['currency'].id, 'partner_id': self.partner_a.id, 'journal_id': self.company_data['default_journal_sale'].id, 'invoice_line_ids': [ (0, 0, { 'name': 'My super product.', 'quantity': 1.0, 'price_unit': 750.0, 'tax_ids': [(6, 0, self.product_a.taxes_id.ids)], }), (0, 0, { 'display_type': 'line_note', 'name': 'This is a note', 'account_id': False, }), ], }] moves = self.env['account.move'].create(invoice_vals_list) tax_line = moves.line_ids.filtered('tax_line_id') self.assertEqual(tax_line.partner_id.id, self.partner_a.id) def test_out_invoice_reverse_caba(self): tax_waiting_account = self.env['account.account'].create({ 'name': 'TAX_WAIT', 'code': 'TWAIT', 'user_type_id': self.env.ref('account.data_account_type_current_liabilities').id, 'reconcile': True, 'company_id': self.company_data['company'].id, }) tax_final_account = self.env['account.account'].create({ 'name': 'TAX_TO_DEDUCT', 'code': 'TDEDUCT', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) tax_base_amount_account = self.env['account.account'].create({ 'name': 'TAX_BASE', 'code': 'TBASE', 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': self.company_data['company'].id, }) self.env.company.account_cash_basis_base_account_id = tax_base_amount_account self.env.company.tax_exigibility = True tax_tags = defaultdict(dict) for line_type, repartition_type in [(l, r) for l in ('invoice', 'refund') for r in ('base', 'tax')]: tax_tags[line_type][repartition_type] = self.env['account.account.tag'].create({ 'name': '%s %s tag' % (line_type, repartition_type), 'applicability': 'taxes', 'country_id': self.env.ref('base.us').id, }) tax = self.env['account.tax'].create({ 'name': 'cash basis 10%', 'type_tax_use': 'sale', 'amount': 10, 'tax_exigibility': 'on_payment', 'cash_basis_transition_account_id': tax_waiting_account.id, 'invoice_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['invoice']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['invoice']['tax'].ids)], }), ], 'refund_repartition_line_ids': [ (0, 0, { 'factor_percent': 100, 'repartition_type': 'base', 'tag_ids': [(6, 0, tax_tags['refund']['base'].ids)], }), (0, 0, { 'factor_percent': 100, 'repartition_type': 'tax', 'account_id': tax_final_account.id, 'tag_ids': [(6, 0, tax_tags['refund']['tax'].ids)], }), ], }) # create invoice move_form = Form(self.env['account.move'].with_context(default_move_type='out_invoice')) move_form.partner_id = self.partner_a move_form.invoice_date = fields.Date.from_string('2017-01-01') with move_form.invoice_line_ids.new() as line_form: line_form.product_id = self.product_a line_form.tax_ids.clear() line_form.tax_ids.add(tax) invoice = move_form.save() invoice.action_post() # make payment self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({ 'payment_date': invoice.date, })._create_payments() # check caba move partial_rec = invoice.mapped('line_ids.matched_credit_ids') caba_move = self.env['account.move'].search([('tax_cash_basis_rec_id', '=', partial_rec.id)]) expected_values = [ { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_base_amount_account.id, 'debit': 1000.0, 'credit': 0.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': tax.ids, 'tax_tag_ids': tax_tags['invoice']['base'].ids, 'account_id': tax_base_amount_account.id, 'debit': 0.0, 'credit': 1000.0, }, { 'tax_line_id': False, 'tax_repartition_line_id': False, 'tax_ids': [], 'tax_tag_ids': [], 'account_id': tax_waiting_account.id, 'debit': 100.0, 'credit': 0.0, }, { 'tax_line_id': tax.id, 'tax_repartition_line_id': tax.invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax').id, 'tax_ids': [], 'tax_tag_ids': tax_tags['invoice']['tax'].ids, 'account_id': tax_final_account.id, 'debit': 0.0, 'credit': 100.0, }, ] self.assertRecordValues(caba_move.line_ids, expected_values) # unreconcile debit_aml = invoice.line_ids.filtered('debit') debit_aml.remove_move_reconcile() # check caba move reverse is same as caba move with only debit/credit inverted reversed_caba_move = self.env['account.move'].search([('reversed_entry_id', '=', caba_move.id)]) for value in expected_values: value.update({ 'debit': value['credit'], 'credit': value['debit'], }) self.assertRecordValues(reversed_caba_move.line_ids, expected_values) @freeze_time('2019-01-01') def test_out_invoice_duplicate_currency_rate(self): ''' Test the correct update of currency rate on invoice duplication''' move_form = Form(self.invoice) move_form.date = '2016-01-01' move_form.currency_id = self.currency_data['currency'] move_form.save() self.invoice.action_post() # === Duplicate invoice. The currency conversion's rate should change to match today rate === copy = self.invoice.copy() copy.action_post() self.assertRecordValues( copy.line_ids.filtered(lambda l: not l.exclude_from_invoice_tab), [ { 'currency_id': self.currency_data['currency'].id, 'amount_currency': -1000.0, 'debit': 0.0, 'credit': 500.0, }, { 'currency_id': self.currency_data['currency'].id, 'amount_currency': -200.0, 'debit': 0.0, 'credit': 100.0, }, ], ) def test_out_invoice_depreciated_account(self): move = self.env['account.move'].create({ 'move_type': 'out_invoice', 'currency_id': self.currency_data['currency'].id, 'partner_id': self.partner_a.id, 'journal_id': self.company_data['default_journal_sale'].id, 'invoice_line_ids': [ (0, 0, { 'name': 'My super product.', 'quantity': 1.0, 'price_unit': 750.0, 'account_id': self.product_a.property_account_income_id.id, }) ], }) self.product_a.property_account_income_id.deprecated = True with self.assertRaises(UserError), self.cr.savepoint(): move.action_post() @freeze_time('2019-01-01') def test_date_reversal_exchange_move(self): """ Test the date of the reversal of an exchange move created when unreconciling a payment made in the past, when no lock date is set. It should be the last day of the month of the exchange move date if sequence is incremented by month, and the last day of the year of the exchange move date if sequence is incremented by year. """ for format_incrementor, expected_date in (('month', '2017-01-31'), ('year', '2017-12-31')): with self.subTest(format_incrementor=format_incrementor, expected_date=expected_date): invoice = self.init_invoice(move_type='out_invoice', partner=self.partner_a, invoice_date='2016-01-20', post=True, amounts=[750.0], currency=self.currency_data['currency']) new_exchange_journal = self.env['account.journal'].create({ 'name': f'Exchange Journal for {invoice.name}', 'code': f'EXCH{invoice.sequence_number}', 'type': 'general', 'company_id': self.env.company.id, }) # Need a first move in the new journal to initiate the sequence with a right incrementor, depending on the wanted format self.env['account.move'].create({ 'journal_id': new_exchange_journal.id, 'name': 'EXCH/2019/00001' if format_incrementor == 'year' else 'EXCH/2019/01/0001', 'line_ids': [ (0, 0, { 'account_id': self.company_data['default_account_receivable'].id, 'debit': 125.0, 'credit': 0.0, }), (0, 0, { 'account_id': self.company_data['default_account_revenue'].id, 'debit': 0.0, 'credit': 125.0, }) ] }) self.env.company.currency_exchange_journal_id = new_exchange_journal self.env['account.payment.register'].with_context(active_model='account.move', active_ids=invoice.ids).create({ 'payment_date': '2017-01-20', })._create_payments() line_receivable = invoice.line_ids.filtered(lambda l: l.account_id.internal_type == 'receivable') exchange_move = line_receivable.full_reconcile_id.exchange_move_id # Date of the exchange move should be the date of the payment self.assertEqual(exchange_move.date, fields.Date.to_date('2017-01-20')) line_receivable.remove_move_reconcile() exchange_move_reversal = exchange_move.reversal_move_id # Date of the reversal of the exchange move should be the last day of the month/year of the payment depending on the sequence format self.assertEqual(exchange_move_reversal.date, fields.Date.to_date(expected_date))
40.397026
143,975
1,036
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged @tagged('post_install', '-at_install') class TestAccountMovePartnerCount(AccountTestInvoicingCommon): def test_account_move_count(self): self.env['account.move'].create([ { 'move_type': 'out_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': self.partner_a.id, 'invoice_line_ids': [(0, 0, {'name': 'aaaa', 'price_unit': 100.0})], }, { 'move_type': 'in_invoice', 'date': '2017-01-01', 'invoice_date': '2017-01-01', 'partner_id': self.partner_a.id, 'invoice_line_ids': [(0, 0, {'name': 'aaaa', 'price_unit': 100.0})], }, ]).action_post() self.assertEqual(self.partner_a.supplier_rank, 1) self.assertEqual(self.partner_a.customer_rank, 1)
35.724138
1,036
8,621
py
PYTHON
15.0
# -*- coding: utf-8 -*- from unittest.mock import patch import odoo.tools from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.addons.account.models.account_payment_method import AccountPaymentMethod from odoo.tests import tagged from odoo.exceptions import UserError, ValidationError @tagged('post_install', '-at_install') class TestAccountJournal(AccountTestInvoicingCommon): def test_constraint_currency_consistency_with_accounts(self): ''' The accounts linked to a bank/cash journal must share the same foreign currency if specified. ''' journal_bank = self.company_data['default_journal_bank'] journal_bank.currency_id = self.currency_data['currency'] # Try to set a different currency on the 'debit' account. with self.assertRaises(ValidationError), self.cr.savepoint(): journal_bank.default_account_id.currency_id = self.company_data['currency'] def test_changing_journal_company(self): ''' Ensure you can't change the company of an account.journal if there are some journal entries ''' self.env['account.move'].create({ 'move_type': 'entry', 'date': '2019-01-01', 'journal_id': self.company_data['default_journal_sale'].id, }) with self.assertRaises(UserError), self.cr.savepoint(): self.company_data['default_journal_sale'].company_id = self.company_data_2['company'] def test_account_control_create_journal_entry(self): move_vals = { 'line_ids': [ (0, 0, { 'name': 'debit', 'account_id': self.company_data['default_account_revenue'].id, 'debit': 100.0, 'credit': 0.0, }), (0, 0, { 'name': 'credit', 'account_id': self.company_data['default_account_expense'].id, 'debit': 0.0, 'credit': 100.0, }), ], } # Should fail because 'default_account_expense' is not allowed. self.company_data['default_journal_misc'].account_control_ids |= self.company_data['default_account_revenue'] with self.assertRaises(UserError), self.cr.savepoint(): self.env['account.move'].create(move_vals) # Should be allowed because both accounts are accepted. self.company_data['default_journal_misc'].account_control_ids |= self.company_data['default_account_expense'] self.env['account.move'].create(move_vals) def test_default_account_type_control_create_journal_entry(self): move_vals = { 'line_ids': [ (0, 0, { 'name': 'debit', 'account_id': self.company_data['default_account_revenue'].id, 'debit': 100.0, 'credit': 0.0, }), (0, 0, { 'name': 'credit', 'account_id': self.company_data['default_account_expense'].id, 'debit': 0.0, 'credit': 100.0, }), ], } # Set the 'default_account_id' on the journal and make sure it will not raise an error, # even if it is not explicitly included in the 'type_control_ids'. self.company_data['default_journal_misc'].default_account_id = self.company_data['default_account_expense'].id # Should fail because 'default_account_revenue' type is not allowed. self.company_data['default_journal_misc'].type_control_ids |= self.company_data['default_account_receivable'].user_type_id with self.assertRaises(UserError), self.cr.savepoint(): self.env['account.move'].create(move_vals) # Should pass because both account types are allowed. # 'default_account_revenue' explicitly and 'default_account_expense' implicitly. self.company_data['default_journal_misc'].type_control_ids |= self.company_data['default_account_revenue'].user_type_id self.env['account.move'].create(move_vals) def test_account_control_existing_journal_entry(self): self.env['account.move'].create({ 'line_ids': [ (0, 0, { 'name': 'debit', 'account_id': self.company_data['default_account_revenue'].id, 'debit': 100.0, 'credit': 0.0, }), (0, 0, { 'name': 'credit', 'account_id': self.company_data['default_account_expense'].id, 'debit': 0.0, 'credit': 100.0, }), ], }) # There is already an other line using the 'default_account_expense' account. with self.assertRaises(ValidationError), self.cr.savepoint(): self.company_data['default_journal_misc'].account_control_ids |= self.company_data['default_account_revenue'] # Assigning both should be allowed self.company_data['default_journal_misc'].account_control_ids = \ self.company_data['default_account_revenue'] + self.company_data['default_account_expense'] def test_account_journal_add_new_payment_method_multi(self): """ Test the automatic creation of payment method lines with the mode set to multi """ Method_get_payment_method_information = AccountPaymentMethod._get_payment_method_information def _get_payment_method_information(self): res = Method_get_payment_method_information(self) res['multi'] = {'mode': 'multi', 'domain': [('type', '=', 'bank')]} return res with patch.object(AccountPaymentMethod, '_get_payment_method_information', _get_payment_method_information): self.env['account.payment.method'].sudo().create({ 'name': 'Multi method', 'code': 'multi', 'payment_type': 'inbound' }) journals = self.env['account.journal'].search([('inbound_payment_method_line_ids.code', '=', 'multi')]) # The two bank journals have been set self.assertEqual(len(journals), 2) def test_remove_payment_method_lines(self): """ Payment method lines are a bit special in the way their removal is handled. If they are linked to a payment at the moment of the deletion, they won't be deleted but the journal_id will be set to False. If they are not linked to any payment, they will be deleted as expected. """ # Linked to a payment. It will not be deleted, but its journal_id will be set to False. first_method = self.inbound_payment_method_line self.env['account.payment'].create({ 'amount': 100.0, 'payment_type': 'inbound', 'partner_type': 'customer', 'payment_method_line_id': first_method.id, }) first_method.unlink() self.assertFalse(first_method.journal_id) # Not linked to anything. It will be deleted. second_method = self.outbound_payment_method_line second_method.unlink() self.assertFalse(second_method.exists()) @odoo.tools.mute_logger('odoo.addons.account.models.account_journal') def test_account_journal_alias_name(self): journal = self.company_data['default_journal_misc'] self.assertEqual(journal._get_alias_values(journal.type)['alias_name'], 'Miscellaneous Operations-company_1_data') self.assertEqual(journal._get_alias_values(journal.type, 'ぁ')['alias_name'], 'MISC-company_1_data') journal.name = 'ぁ' self.assertEqual(journal._get_alias_values(journal.type)['alias_name'], 'MISC-company_1_data') journal.code = 'ぁ' self.assertEqual(journal._get_alias_values(journal.type)['alias_name'], 'general-company_1_data') self.company_data_2['company'].name = 'ぁ' company_2_id = str(self.company_data_2['company'].id) journal_2 = self.company_data_2['default_journal_sale'] self.assertEqual(journal_2._get_alias_values(journal_2.type)['alias_name'], 'Customer Invoices-' + company_2_id) journal_2.name = 'ぁ' self.assertEqual(journal_2._get_alias_values(journal_2.type)['alias_name'], 'INV-' + company_2_id) journal_2.code = 'ぁ' self.assertEqual(journal_2._get_alias_values(journal_2.type)['alias_name'], 'sale-' + company_2_id)
45.550265
8,609
14,757
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged, Form import time @tagged('post_install', '-at_install') class TestTransferWizard(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.company = cls.company_data['company'] cls.receivable_account = cls.company_data['default_account_receivable'] cls.payable_account = cls.company_data['default_account_payable'] cls.accounts = cls.env['account.account'].search([('reconcile', '=', False), ('company_id', '=', cls.company.id)], limit=5) cls.journal = cls.company_data['default_journal_misc'] # Set rate for base currency to 1 cls.env['res.currency.rate'].search([('company_id', '=', cls.company.id), ('currency_id', '=', cls.company.currency_id.id)]).write({'rate': 1}) # Create test currencies cls.test_currency_1 = cls.env['res.currency'].create({ 'name': "PMK", 'symbol':'P', }) cls.test_currency_2 = cls.env['res.currency'].create({ 'name': "toto", 'symbol':'To', }) cls.test_currency_3 = cls.env['res.currency'].create({ 'name': "titi", 'symbol':'Ti', }) # Create test rates cls.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-' + '01' + '-01', 'rate': 0.5, 'currency_id': cls.test_currency_1.id, 'company_id': cls.company.id }) cls.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-' + '01' + '-01', 'rate': 2, 'currency_id': cls.test_currency_2.id, 'company_id': cls.company.id }) cls.env['res.currency.rate'].create({ 'name': time.strftime('%Y') + '-' + '01' + '-01', 'rate': 10, 'currency_id': cls.test_currency_3.id, 'company_id': cls.company.id }) # Create an account using a foreign currency cls.test_currency_account = cls.env['account.account'].create({ 'name': 'test destination account', 'code': 'test_dest_acc', 'user_type_id': cls.env['ir.model.data']._xmlid_to_res_id('account.data_account_type_current_assets'), 'currency_id': cls.test_currency_3.id, }) # Create test account.move cls.move_1 = cls.env['account.move'].create({ 'journal_id': cls.journal.id, 'line_ids': [ (0, 0, { 'name': "test1_1", 'account_id': cls.receivable_account.id, 'debit': 500, }), (0, 0, { 'name': "test1_2", 'account_id': cls.accounts[0].id, 'credit': 500, }), (0, 0, { 'name': "test1_3", 'account_id': cls.accounts[0].id, 'debit': 800, 'partner_id': cls.partner_a.id, }), (0, 0, { 'name': "test1_4", 'account_id': cls.accounts[1].id, 'credit': 500, }), (0, 0, { 'name': "test1_5", 'account_id': cls.accounts[2].id, 'credit': 300, 'partner_id': cls.partner_a.id, }), (0, 0, { 'name': "test1_6", 'account_id': cls.accounts[0].id, 'debit': 270, 'currency_id': cls.test_currency_1.id, 'amount_currency': 540, }), (0, 0, { 'name': "test1_7", 'account_id': cls.accounts[1].id, 'credit': 140, }), (0, 0, { 'name': "test1_8", 'account_id': cls.accounts[2].id, 'credit': 160, }), (0, 0, { 'name': "test1_9", 'account_id': cls.accounts[2].id, 'debit': 30, 'currency_id': cls.test_currency_2.id, 'amount_currency': 15, }), ] }) cls.move_1.action_post() cls.move_2 = cls.env['account.move'].create({ 'journal_id': cls.journal.id, 'line_ids': [ (0, 0, { 'name': "test2_1", 'account_id': cls.accounts[1].id, 'debit': 400, }), (0, 0, { 'name': "test2_2", 'account_id': cls.payable_account.id, 'credit': 400, }), (0, 0, { 'name': "test2_3", 'account_id': cls.accounts[3].id, 'debit': 250, 'partner_id': cls.partner_a.id, }), (0, 0, { 'name': "test2_4", 'account_id': cls.accounts[1].id, 'debit': 480, 'partner_id': cls.partner_b.id, }), (0, 0, { 'name': "test2_5", 'account_id': cls.accounts[2].id, 'credit': 730, 'partner_id': cls.partner_a.id, }), (0, 0, { 'name': "test2_6", 'account_id': cls.accounts[2].id, 'credit': 412, 'partner_id': cls.partner_a.id, 'currency_id': cls.test_currency_2.id, 'amount_currency': -633, }), (0, 0, { 'name': "test2_7", 'account_id': cls.accounts[1].id, 'debit': 572, }), (0, 0, { 'name': "test2_8", 'account_id': cls.accounts[2].id, 'credit': 100, 'partner_id': cls.partner_a.id, 'currency_id': cls.test_currency_2.id, 'amount_currency': -123, }), (0, 0, { 'name': "test2_9", 'account_id': cls.accounts[2].id, 'credit': 60, 'partner_id': cls.partner_a.id, 'currency_id': cls.test_currency_1.id, 'amount_currency': -10, }), ] }) cls.move_2.action_post() def test_transfer_wizard_reconcile(self): """ Tests reconciliation when doing a transfer with the wizard """ active_move_lines = (self.move_1 + self.move_2).mapped('line_ids').filtered(lambda x: x.account_id.user_type_id.type in ('receivable', 'payable')) # We use a form to pass the context properly to the depends_context move_line_ids field context = {'active_model': 'account.move.line', 'active_ids': active_move_lines.ids} with Form(self.env['account.automatic.entry.wizard'].with_context(context)) as wizard_form: wizard_form.action = 'change_account' wizard_form.destination_account_id = self.receivable_account wizard_form.journal_id = self.journal wizard = wizard_form.save() transfer_move_id = wizard.do_action()['res_id'] transfer_move = self.env['account.move'].browse(transfer_move_id) payable_transfer = transfer_move.line_ids.filtered(lambda x: x.account_id == self.payable_account) receivable_transfer = transfer_move.line_ids.filtered(lambda x: x.account_id == self.receivable_account) self.assertTrue(payable_transfer.reconciled, "Payable line of the transfer move should be fully reconciled") self.assertAlmostEqual(self.move_1.line_ids.filtered(lambda x: x.account_id == self.receivable_account).amount_residual, 100, self.company.currency_id.decimal_places, "Receivable line of the original move should be partially reconciled, and still have a residual amount of 100 (500 - 400 from payable account)") self.assertTrue(self.move_2.line_ids.filtered(lambda x: x.account_id == self.payable_account).reconciled, "Payable line of the original move should be fully reconciled") self.assertAlmostEqual(receivable_transfer.amount_residual, 0, self.company.currency_id.decimal_places, "Receivable line from the transfer move should have nothing left to reconcile") self.assertAlmostEqual(payable_transfer.debit, 400, self.company.currency_id.decimal_places, "400 should have been debited from payable account to apply the transfer") self.assertAlmostEqual(receivable_transfer.credit, 400, self.company.currency_id.decimal_places, "400 should have been credited to receivable account to apply the transfer") def test_transfer_wizard_grouping(self): """ Tests grouping (by account and partner) when doing a transfer with the wizard """ active_move_lines = (self.move_1 + self.move_2).mapped('line_ids').filtered(lambda x: x.name in ('test1_3', 'test1_4', 'test1_5', 'test2_3', 'test2_4', 'test2_5', 'test2_6', 'test2_8')) # We use a form to pass the context properly to the depends_context move_line_ids field context = {'active_model': 'account.move.line', 'active_ids': active_move_lines.ids} with Form(self.env['account.automatic.entry.wizard'].with_context(context)) as wizard_form: wizard_form.action = 'change_account' wizard_form.destination_account_id = self.accounts[4] wizard_form.journal_id = self.journal wizard = wizard_form.save() transfer_move_id = wizard.do_action()['res_id'] transfer_move = self.env['account.move'].browse(transfer_move_id) groups = {} for line in transfer_move.line_ids: key = (line.account_id, line.partner_id or None, line.currency_id) self.assertFalse(groups.get(key), "There should be only one line per (account, partner, currency) group in the transfer move.") groups[key] = line self.assertAlmostEqual(groups[(self.accounts[0], self.partner_a, self.company_data['currency'])].balance, -800, self.company.currency_id.decimal_places) self.assertAlmostEqual(groups[(self.accounts[1], None, self.company_data['currency'])].balance, 500, self.company.currency_id.decimal_places) self.assertAlmostEqual(groups[(self.accounts[1], self.partner_b, self.company_data['currency'])].balance, -480, self.company.currency_id.decimal_places) self.assertAlmostEqual(groups[(self.accounts[2], self.partner_a, self.company_data['currency'])].balance, 1030, self.company.currency_id.decimal_places) self.assertAlmostEqual(groups[(self.accounts[2], self.partner_a, self.test_currency_2)].balance, 512, self.company.currency_id.decimal_places) self.assertAlmostEqual(groups[(self.accounts[3], self.partner_a, self.company_data['currency'])].balance, -250, self.company.currency_id.decimal_places) def test_transfer_wizard_currency_conversion(self): """ Tests multi currency use of the transfer wizard, checking the conversion is propperly done when using a destination account with a currency_id set. """ active_move_lines = self.move_1.mapped('line_ids').filtered(lambda x: x.name in ('test1_6', 'test1_9')) # We use a form to pass the context properly to the depends_context move_line_ids field context = {'active_model': 'account.move.line', 'active_ids': active_move_lines.ids} with Form(self.env['account.automatic.entry.wizard'].with_context(context)) as wizard_form: wizard_form.action = 'change_account' wizard_form.destination_account_id = self.test_currency_account wizard_form.journal_id = self.journal wizard = wizard_form.save() transfer_move_id = wizard.do_action()['res_id'] transfer_move = self.env['account.move'].browse(transfer_move_id) destination_line = transfer_move.line_ids.filtered(lambda x: x.account_id == self.test_currency_account) self.assertEqual(destination_line.currency_id, self.test_currency_3, "Transferring to an account with a currency set should keep this currency on the transfer line.") self.assertAlmostEqual(destination_line.amount_currency, 3000, self.company.currency_id.decimal_places, "Transferring two lines with different currencies (and the same partner) on an account with a currency set should convert the balance of these lines into this account's currency (here (270 + 30) * 10 = 3000)") def test_transfer_wizard_no_currency_conversion(self): """ Tests multi currency use of the transfer wizard, verifying that currency amounts are kept on distinct lines when transferring to an account without any currency specified. """ active_move_lines = self.move_2.mapped('line_ids').filtered(lambda x: x.name in ('test2_9', 'test2_6', 'test2_8')) # We use a form to pass the context properly to the depends_context move_line_ids field context = {'active_model': 'account.move.line', 'active_ids': active_move_lines.ids} with Form(self.env['account.automatic.entry.wizard'].with_context(context)) as wizard_form: wizard_form.action = 'change_account' wizard_form.destination_account_id = self.receivable_account wizard_form.journal_id = self.journal wizard = wizard_form.save() transfer_move_id = wizard.do_action()['res_id'] transfer_move = self.env['account.move'].browse(transfer_move_id) destination_lines = transfer_move.line_ids.filtered(lambda x: x.account_id == self.receivable_account) self.assertEqual(len(destination_lines), 2, "Two lines should have been created on destination account: one for each currency (the lines with same partner and currency should have been aggregated)") self.assertAlmostEqual(destination_lines.filtered(lambda x: x.currency_id == self.test_currency_1).amount_currency, -10, self.test_currency_1.decimal_places) self.assertAlmostEqual(destination_lines.filtered(lambda x: x.currency_id == self.test_currency_2).amount_currency, -756, self.test_currency_2.decimal_places)
50.71134
14,757
17,585
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged import json @tagged('post_install', '-at_install') class TestTaxTotals(AccountTestInvoicingCommon): @classmethod def setUpClass(cls, chart_template_ref=None): super().setUpClass(chart_template_ref=chart_template_ref) cls.tax_group1 = cls.env['account.tax.group'].create({ 'name': '1', 'sequence': 1 }) cls.tax_group2 = cls.env['account.tax.group'].create({ 'name': '2', 'sequence': 2 }) cls.tax_group_sub1 = cls.env['account.tax.group'].create({ 'name': 'subtotals 1', 'preceding_subtotal': "PRE GROUP 1", 'sequence': 3 }) cls.tax_group_sub2 = cls.env['account.tax.group'].create({ 'name': 'subtotals 2', 'preceding_subtotal': "PRE GROUP 2", 'sequence': 4 }) cls.tax_group_sub3 = cls.env['account.tax.group'].create({ 'name': 'subtotals 3', 'preceding_subtotal': "PRE GROUP 1", # same as sub1, on purpose 'sequence': 5 }) def assertTaxTotals(self, document, expected_values): main_keys_to_ignore = {'formatted_amount_total', 'formatted_amount_untaxed'} group_keys_to_ignore = {'group_key', 'formatted_tax_group_amount', 'formatted_tax_group_base_amount'} subtotals_keys_to_ignore = {'formatted_amount'} to_compare = json.loads(document.tax_totals_json) for key in main_keys_to_ignore: del to_compare[key] for key in group_keys_to_ignore: for groups in to_compare['groups_by_subtotal'].values(): for group in groups: del group[key] for key in subtotals_keys_to_ignore: for subtotal in to_compare['subtotals']: del subtotal[key] self.assertEqual(to_compare, expected_values) def _create_document_for_tax_totals_test(self, lines_data): """ Creates and returns a new record of a model defining a tax_totals_json field and using the related widget. By default, this function creates an invoice, but it is overridden in sale and purchase to create respectively a sale.order or a purchase.order. This way, we can test the invoice_tax_totals from both these models in the same way as account.move's. :param lines_data: a list of tuple (amount, taxes), where amount is a base amount, and taxes a recordset of account.tax objects corresponding to the taxes to apply on this amount. Each element of the list corresponds to a line of the document (invoice line, PO line, SO line). """ invoice_lines_vals = [ (0, 0, { 'name': 'line', 'account_id': self.company_data['default_account_revenue'].id, 'price_unit': amount, 'tax_ids': [(6, 0, taxes.ids)], }) for amount, taxes in lines_data] return self.env['account.move'].create({ 'move_type': 'out_invoice', 'partner_id': self.partner_a.id, 'invoice_date': '2019-01-01', 'invoice_line_ids': invoice_lines_vals, }) def test_multiple_tax_lines(self): tax_10 = self.env['account.tax'].create({ 'name': "tax_10", 'amount_type': 'percent', 'amount': 10.0, 'tax_group_id': self.tax_group1.id, }) tax_20 = self.env['account.tax'].create({ 'name': "tax_20", 'amount_type': 'percent', 'amount': 20.0, 'tax_group_id': self.tax_group2.id, }) document = self._create_document_for_tax_totals_test([ (1000, tax_10 + tax_20), (1000, tax_10), (1000, tax_20), ]) self.assertTaxTotals(document, { 'amount_total': 3600, 'amount_untaxed': 3000, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': self.tax_group1.name, 'tax_group_amount': 200, 'tax_group_base_amount': 2000, 'tax_group_id': self.tax_group1.id, }, { 'tax_group_name': self.tax_group2.name, 'tax_group_amount': 400, 'tax_group_base_amount': 2000, 'tax_group_id': self.tax_group2.id, }, ], }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 3000, } ] }) # Same but both are sharing the same tax group. tax_20.tax_group_id = self.tax_group1 document.invalidate_cache(['tax_totals_json']) self.assertTaxTotals(document, { 'amount_total': 3600, 'amount_untaxed': 3000, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': self.tax_group1.name, 'tax_group_amount': 600, 'tax_group_base_amount': 3000, 'tax_group_id': self.tax_group1.id, }, ], }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 3000, } ] }) def test_zero_tax_lines(self): tax_0 = self.env['account.tax'].create({ 'name': "tax_0", 'amount_type': 'percent', 'amount': 0.0, }) document = self._create_document_for_tax_totals_test([ (1000, tax_0), ]) self.assertTaxTotals(document, { 'amount_total': 1000, 'amount_untaxed': 1000, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': tax_0.tax_group_id.name, 'tax_group_amount': 0, 'tax_group_base_amount': 1000, 'tax_group_id': tax_0.tax_group_id.id, }, ], }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 1000, } ] }) def test_tax_affect_base_1(self): tax_10 = self.env['account.tax'].create({ 'name': "tax_10", 'amount_type': 'percent', 'amount': 10.0, 'tax_group_id': self.tax_group1.id, 'price_include': True, 'include_base_amount': True, }) tax_20 = self.env['account.tax'].create({ 'name': "tax_20", 'amount_type': 'percent', 'amount': 20.0, 'tax_group_id': self.tax_group2.id, }) document = self._create_document_for_tax_totals_test([ (1100, tax_10 + tax_20), (1100, tax_10), (1000, tax_20), ]) self.assertTaxTotals(document, { 'amount_total': 3620, 'amount_untaxed': 3000, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': self.tax_group1.name, 'tax_group_amount': 200, 'tax_group_base_amount': 2000, 'tax_group_id': self.tax_group1.id, }, { 'tax_group_name': self.tax_group2.name, 'tax_group_amount': 420, 'tax_group_base_amount': 2100, 'tax_group_id': self.tax_group2.id, }, ], }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 3000, } ] }) # Same but both are sharing the same tax group. tax_20.tax_group_id = self.tax_group1 document.invalidate_cache(['tax_totals_json']) self.assertTaxTotals(document, { 'amount_total': 3620, 'amount_untaxed': 3000, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': self.tax_group1.name, 'tax_group_amount': 620, 'tax_group_base_amount': 3000, 'tax_group_id': self.tax_group1.id, }, ], }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 3000, } ] }) def test_tax_affect_base_2(self): tax_10 = self.env['account.tax'].create({ 'name': "tax_10", 'amount_type': 'percent', 'amount': 10.0, 'tax_group_id': self.tax_group1.id, 'include_base_amount': True, }) tax_20 = self.env['account.tax'].create({ 'name': "tax_20", 'amount_type': 'percent', 'amount': 20.0, 'tax_group_id': self.tax_group1.id, }) tax_30 = self.env['account.tax'].create({ 'name': "tax_30", 'amount_type': 'percent', 'amount': 30.0, 'tax_group_id': self.tax_group2.id, 'include_base_amount': True, }) document = self._create_document_for_tax_totals_test([ (1000, tax_10 + tax_20), (1000, tax_30 + tax_10), ]) self.assertTaxTotals(document, { 'amount_total': 2750, 'amount_untaxed': 2000, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': self.tax_group1.name, 'tax_group_amount': 450, 'tax_group_base_amount': 2300, 'tax_group_id': self.tax_group1.id, }, { 'tax_group_name': self.tax_group2.name, 'tax_group_amount': 300, 'tax_group_base_amount': 1000, 'tax_group_id': self.tax_group2.id, }, ], }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 2000, } ] }) # Same but both are sharing the same tax group. tax_30.tax_group_id = self.tax_group1 document.invalidate_cache(['tax_totals_json']) self.assertTaxTotals(document, { 'amount_total': 2750, 'amount_untaxed': 2000, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': self.tax_group1.name, 'tax_group_amount': 750, 'tax_group_base_amount': 2000, 'tax_group_id': self.tax_group1.id, }, ], }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 2000, } ] }) def test_subtotals_basic(self): tax_10 = self.env['account.tax'].create({ 'name': "tax_10", 'amount_type': 'percent', 'amount': 10.0, 'tax_group_id': self.tax_group_sub1.id, }) tax_25 = self.env['account.tax'].create({ 'name': "tax_25", 'amount_type': 'percent', 'amount': 25.0, 'tax_group_id': self.tax_group_sub2.id, }) tax_42 = self.env['account.tax'].create({ 'name': "tax_42", 'amount_type': 'percent', 'amount': 42.0, 'tax_group_id': self.tax_group1.id, }) document = self._create_document_for_tax_totals_test([ (1000, tax_10), (1000, tax_25), (100, tax_42), (200, tax_42 + tax_10 + tax_25), ]) self.assertTaxTotals(document, { 'amount_total': 2846, 'amount_untaxed': 2300, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': self.tax_group1.name, 'tax_group_amount': 126, 'tax_group_base_amount': 300, 'tax_group_id': self.tax_group1.id, }, ], 'PRE GROUP 1': [ { 'tax_group_name': self.tax_group_sub1.name, 'tax_group_amount': 120, 'tax_group_base_amount': 1200, 'tax_group_id': self.tax_group_sub1.id, }, ], 'PRE GROUP 2': [ { 'tax_group_name': self.tax_group_sub2.name, 'tax_group_amount': 300, 'tax_group_base_amount': 1200, 'tax_group_id': self.tax_group_sub2.id, }, ] }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 2300, }, { 'name': "PRE GROUP 1", 'amount': 2426, }, { 'name': "PRE GROUP 2", 'amount': 2546, }, ], }) def test_after_total_mix(self): tax_10 = self.env['account.tax'].create({ 'name': "tax_10", 'amount_type': 'percent', 'amount': 10.0, 'tax_group_id': self.tax_group_sub3.id, }) tax_25 = self.env['account.tax'].create({ 'name': "tax_25", 'amount_type': 'percent', 'amount': -25.0, 'tax_group_id': self.tax_group_sub2.id, }) tax_42 = self.env['account.tax'].create({ 'name': "tax_42", 'amount_type': 'percent', 'amount': 42.0, 'tax_group_id': self.tax_group_sub1.id, }) tax_30 = self.env['account.tax'].create({ 'name': "tax_30", 'amount_type': 'percent', 'amount': 30.0, 'tax_group_id': self.tax_group1.id, }) document = self._create_document_for_tax_totals_test([ (100, tax_10), (100, tax_25 + tax_42 + tax_30), (200, tax_10 + tax_25), (1000, tax_30), (100, tax_30 + tax_10) ]) self.assertTaxTotals(document, { 'amount_total': 1867, 'amount_untaxed': 1500, 'allow_tax_edition': False, 'groups_by_subtotal': { 'Untaxed Amount': [ { 'tax_group_name': self.tax_group1.name, 'tax_group_amount': 360, 'tax_group_base_amount': 1200, 'tax_group_id': self.tax_group1.id, }, ], 'PRE GROUP 1': [ { 'tax_group_name': self.tax_group_sub1.name, 'tax_group_amount': 42, 'tax_group_base_amount': 100, 'tax_group_id': self.tax_group_sub1.id, }, { 'tax_group_name': self.tax_group_sub3.name, 'tax_group_amount': 40, 'tax_group_base_amount': 400, 'tax_group_id': self.tax_group_sub3.id, }, ], 'PRE GROUP 2': [ { 'tax_group_name': self.tax_group_sub2.name, 'tax_group_amount': -75, 'tax_group_base_amount': 300, 'tax_group_id': self.tax_group_sub2.id, }, ], }, 'subtotals': [ { 'name': "Untaxed Amount", 'amount': 1500, }, { 'name': "PRE GROUP 1", 'amount': 1860, }, { 'name': "PRE GROUP 2", 'amount': 1942, }, ], })
32.930712
17,585
2,921
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.addons.account.tests.common import AccountTestInvoicingCommon from odoo.tests import tagged @tagged('post_install', '-at_install') class TestSettings(AccountTestInvoicingCommon): def test_switch_taxB2B_taxB2C(self): """ Since having users both in the tax B2B and tax B2C groups raise, modifications of the settings must be done in the right order; otherwise it is impossible to change the settings. """ # at each setting change, all users should be removed from one group and added to the other # so picking an arbitrary witness should be equivalent to checking that everything worked. config = self.env['res.config.settings'].create({}) self.switch_tax_settings(config) def switch_tax_settings(self, config): config.show_line_subtotals_tax_selection = "tax_excluded" config._onchange_sale_tax() config.flush() config.execute() self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_excluded'), True) self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_included'), False) config.show_line_subtotals_tax_selection = "tax_included" config._onchange_sale_tax() config.flush() config.execute() self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_excluded'), False) self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_included'), True) config.show_line_subtotals_tax_selection = "tax_excluded" config._onchange_sale_tax() config.flush() config.execute() self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_excluded'), True) self.assertEqual(self.env.user.has_group('account.group_show_line_subtotals_tax_included'), False) def test_switch_taxB2B_taxB2C_multicompany(self): """ Contrarily to the (apparently reasonable) assumption that adding users to group and removing them was symmetrical, it may not be the case if one is done in SQL and the other via the ORM. Because the latter automatically takes into account record rules that might make some users invisible. This one is identical to the previous, except that we do the actions with a non-superuser user, and in a new company with one user in common with another company which has a different taxB2X setting. """ user = self.env.ref('base.user_admin') company = self.env['res.company'].create({'name': 'oobO'}) user.write({'company_ids': [(4, company.id)], 'company_id': company.id}) Settings = self.env['res.config.settings'].with_user(user.id) config = Settings.create({}) self.switch_tax_settings(config)
48.683333
2,921
1,088
py
PYTHON
15.0
from odoo import models, fields, _ from odoo.exceptions import UserError class ValidateAccountMove(models.TransientModel): _name = "validate.account.move" _description = "Validate Account Move" force_post = fields.Boolean(string="Force", help="Entries in the future are set to be auto-posted by default. Check this checkbox to post them now.") def validate_move(self): if self._context.get('active_model') == 'account.move': domain = [('id', 'in', self._context.get('active_ids', [])), ('state', '=', 'draft')] elif self._context.get('active_model') == 'account.journal': domain = [('journal_id', '=', self._context.get('active_id')), ('state', '=', 'draft')] else: raise UserError(_("Missing 'active_model' in context.")) moves = self.env['account.move'].search(domain).filtered('line_ids') if not moves: raise UserError(_('There are no journal items in the draft state to post.')) moves._post(not self.force_post) return {'type': 'ir.actions.act_window_close'}
47.304348
1,088
529
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models class AccountCommonJournalReport(models.TransientModel): _name = 'account.common.journal.report' _description = 'Common Journal Report' _inherit = "account.common.report" amount_currency = fields.Boolean('With Currency', help="Print Report with the currency column if the currency differs from the company currency.") def pre_print_report(self, data): data['form'].update({'amount_currency': self.amount_currency}) return data
35.266667
529
336
py
PYTHON
15.0
from odoo import models class BaseDocumentLayout(models.TransientModel): _inherit = 'base.document.layout' def document_layout_save(self): res = super(BaseDocumentLayout, self).document_layout_save() for wizard in self: wizard.company_id.action_save_onboarding_invoice_layout() return res
30.545455
336
2,099
py
PYTHON
15.0
from odoo import models, fields, api, _ from odoo.exceptions import UserError class CashBox(models.TransientModel): _register = False name = fields.Char(string='Reason', required=True) # Attention, we don't set a domain, because there is a journal_type key # in the context of the action amount = fields.Float(string='Amount', digits=0, required=True) def run(self): context = dict(self._context or {}) active_model = context.get('active_model', False) active_ids = context.get('active_ids', []) records = self.env[active_model].browse(active_ids) return self._run(records) def _run(self, records): for box in self: for record in records: if not record.journal_id: raise UserError(_("Please check that the field 'Journal' is set on the Bank Statement")) if not record.journal_id.company_id.transfer_account_id: raise UserError(_("Please check that the field 'Transfer Account' is set on the company.")) box._create_bank_statement_line(record) return {} def _create_bank_statement_line(self, record): for box in self: if record.state == 'confirm': raise UserError(_("You cannot put/take money in/out for a bank statement which is closed.")) values = box._calculate_values_for_statement_line(record) self.env['account.bank.statement.line'].sudo().create(values) class CashBoxOut(CashBox): _name = 'cash.box.out' _description = 'Cash Box Out' def _calculate_values_for_statement_line(self, record): if not record.journal_id.company_id.transfer_account_id: raise UserError(_("You have to define an 'Internal Transfer Account' in your cash register's journal.")) amount = self.amount or 0.0 return { 'date': record.date, 'statement_id': record.id, 'journal_id': record.journal_id.id, 'amount': amount, 'payment_ref': self.name, }
39.603774
2,099
427
py
PYTHON
15.0
from odoo import models, api class AccountUnreconcile(models.TransientModel): _name = "account.unreconcile" _description = "Account Unreconcile" def trans_unrec(self): context = dict(self._context or {}) if context.get('active_ids', False): self.env['account.move.line'].browse(context.get('active_ids')).remove_move_reconcile() return {'type': 'ir.actions.act_window_close'}
35.583333
427
845
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import fields, models class AccountPrintJournal(models.TransientModel): _inherit = "account.common.journal.report" _name = "account.print.journal" _description = "Account Print Journal" sort_selection = fields.Selection([('date', 'Date'), ('move_name', 'Journal Entry Number'),], 'Entries Sorted by', required=True, default='move_name') journal_ids = fields.Many2many('account.journal', string='Journals', required=True, default=lambda self: self.env['account.journal'].search([('type', 'in', ['sale', 'purchase'])])) def _print_report(self, data): data = self.pre_print_report(data) data['form'].update({'sort_selection': self.sort_selection}) return self.env.ref('account.action_report_journal').with_context(landscape=True).report_action(self, data=data)
49.705882
845
7,622
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api from odoo.tools.translate import _ from odoo.exceptions import UserError class AccountMoveReversal(models.TransientModel): """ Account move reversal wizard, it cancel an account move by reversing it. """ _name = 'account.move.reversal' _description = 'Account Move Reversal' _check_company_auto = True move_ids = fields.Many2many('account.move', 'account_move_reversal_move', 'reversal_id', 'move_id', domain=[('state', '=', 'posted')]) new_move_ids = fields.Many2many('account.move', 'account_move_reversal_new_move', 'reversal_id', 'new_move_id') date_mode = fields.Selection(selection=[ ('custom', 'Specific'), ('entry', 'Journal Entry Date') ], required=True, default='custom') date = fields.Date(string='Reversal date', default=fields.Date.context_today) reason = fields.Char(string='Reason') refund_method = fields.Selection(selection=[ ('refund', 'Partial Refund'), ('cancel', 'Full Refund'), ('modify', 'Full refund and new draft invoice') ], string='Credit Method', required=True, help='Choose how you want to credit this invoice. You cannot "modify" nor "cancel" if the invoice is already reconciled.') journal_id = fields.Many2one( comodel_name='account.journal', string='Use Specific Journal', required=True, compute='_compute_journal_id', readonly=False, store=True, check_company=True, help='If empty, uses the journal of the journal entry to be reversed.', ) company_id = fields.Many2one('res.company', required=True, readonly=True) available_journal_ids = fields.Many2many('account.journal', compute='_compute_available_journal_ids') country_code = fields.Char(related='company_id.country_id.code') # computed fields residual = fields.Monetary(compute="_compute_from_moves") currency_id = fields.Many2one('res.currency', compute="_compute_from_moves") move_type = fields.Char(compute="_compute_from_moves") @api.depends('move_ids') def _compute_journal_id(self): for record in self: if record.journal_id: record.journal_id = record.journal_id else: journals = record.move_ids.journal_id.filtered(lambda x: x.active) record.journal_id = journals[0] if journals else None @api.depends('move_ids') def _compute_available_journal_ids(self): for record in self: if record.move_ids: record.available_journal_ids = self.env['account.journal'].search([ ('company_id', '=', record.company_id.id), ('type', 'in', record.move_ids.journal_id.mapped('type')), ]) else: record.available_journal_ids = self.env['account.journal'].search([('company_id', '=', record.company_id.id)]) @api.constrains('journal_id', 'move_ids') def _check_journal_type(self): for record in self: if record.journal_id.type not in record.move_ids.journal_id.mapped('type'): raise UserError(_('Journal should be the same type as the reversed entry.')) @api.model def default_get(self, fields): res = super(AccountMoveReversal, self).default_get(fields) move_ids = self.env['account.move'].browse(self.env.context['active_ids']) if self.env.context.get('active_model') == 'account.move' else self.env['account.move'] if any(move.state != "posted" for move in move_ids): raise UserError(_('You can only reverse posted moves.')) if 'company_id' in fields: res['company_id'] = move_ids.company_id.id or self.env.company.id if 'move_ids' in fields: res['move_ids'] = [(6, 0, move_ids.ids)] if 'refund_method' in fields: res['refund_method'] = (len(move_ids) > 1 or move_ids.move_type == 'entry') and 'cancel' or 'refund' return res @api.depends('move_ids') def _compute_from_moves(self): for record in self: move_ids = record.move_ids._origin record.residual = len(move_ids) == 1 and move_ids.amount_residual or 0 record.currency_id = len(move_ids.currency_id) == 1 and move_ids.currency_id or False record.move_type = move_ids.move_type if len(move_ids) == 1 else (any(move.move_type in ('in_invoice', 'out_invoice') for move in move_ids) and 'some_invoice' or False) def _prepare_default_reversal(self, move): reverse_date = self.date if self.date_mode == 'custom' else move.date return { 'ref': _('Reversal of: %(move_name)s, %(reason)s', move_name=move.name, reason=self.reason) if self.reason else _('Reversal of: %s', move.name), 'date': reverse_date, 'invoice_date': move.is_invoice(include_receipts=True) and (self.date or move.date) or False, 'journal_id': self.journal_id.id, 'invoice_payment_term_id': None, 'invoice_user_id': move.invoice_user_id.id, 'auto_post': True if reverse_date > fields.Date.context_today(self) else False, } def reverse_moves(self): self.ensure_one() moves = self.move_ids # Create default values. default_values_list = [] for move in moves: default_values_list.append(self._prepare_default_reversal(move)) batches = [ [self.env['account.move'], [], True], # Moves to be cancelled by the reverses. [self.env['account.move'], [], False], # Others. ] for move, default_vals in zip(moves, default_values_list): is_auto_post = bool(default_vals.get('auto_post')) is_cancel_needed = not is_auto_post and self.refund_method in ('cancel', 'modify') batch_index = 0 if is_cancel_needed else 1 batches[batch_index][0] |= move batches[batch_index][1].append(default_vals) # Handle reverse method. moves_to_redirect = self.env['account.move'] for moves, default_values_list, is_cancel_needed in batches: new_moves = moves._reverse_moves(default_values_list, cancel=is_cancel_needed) if self.refund_method == 'modify': moves_vals_list = [] for move in moves.with_context(include_business_fields=True): moves_vals_list.append(move.copy_data({'date': self.date if self.date_mode == 'custom' else move.date})[0]) new_moves = self.env['account.move'].create(moves_vals_list) moves_to_redirect |= new_moves self.new_move_ids = moves_to_redirect # Create action. action = { 'name': _('Reverse Moves'), 'type': 'ir.actions.act_window', 'res_model': 'account.move', } if len(moves_to_redirect) == 1: action.update({ 'view_mode': 'form', 'res_id': moves_to_redirect.id, 'context': {'default_move_type': moves_to_redirect.move_type}, }) else: action.update({ 'view_mode': 'tree,form', 'domain': [('id', 'in', moves_to_redirect.ids)], }) if len(set(moves_to_redirect.mapped('move_type'))) == 1: action['context'] = {'default_move_type': moves_to_redirect.mapped('move_type').pop()} return action
46.193939
7,622
24,881
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import UserError, ValidationError from odoo.tools.misc import format_date, formatLang from collections import defaultdict from itertools import groupby import json class AutomaticEntryWizard(models.TransientModel): _name = 'account.automatic.entry.wizard' _description = 'Create Automatic Entries' # General action = fields.Selection([('change_period', 'Change Period'), ('change_account', 'Change Account')], required=True) move_data = fields.Text(compute="_compute_move_data", help="JSON value of the moves to be created") preview_move_data = fields.Text(compute="_compute_preview_move_data", help="JSON value of the data to be displayed in the previewer") move_line_ids = fields.Many2many('account.move.line') date = fields.Date(required=True, default=lambda self: fields.Date.context_today(self)) company_id = fields.Many2one('res.company', required=True, readonly=True) company_currency_id = fields.Many2one('res.currency', related='company_id.currency_id') percentage = fields.Float("Percentage", compute='_compute_percentage', readonly=False, store=True, help="Percentage of each line to execute the action on.") total_amount = fields.Monetary(compute='_compute_total_amount', store=True, readonly=False, currency_field='company_currency_id', help="Total amount impacted by the automatic entry.") journal_id = fields.Many2one('account.journal', required=True, readonly=False, string="Journal", domain="[('company_id', '=', company_id), ('type', '=', 'general')]", compute="_compute_journal_id", inverse="_inverse_journal_id", help="Journal where to create the entry.") # change period account_type = fields.Selection([('income', 'Revenue'), ('expense', 'Expense')], compute='_compute_account_type', store=True) expense_accrual_account = fields.Many2one('account.account', readonly=False, domain="[('company_id', '=', company_id)," "('internal_type', 'not in', ('receivable', 'payable'))," "('is_off_balance', '=', False)]", compute="_compute_expense_accrual_account", inverse="_inverse_expense_accrual_account", ) revenue_accrual_account = fields.Many2one('account.account', readonly=False, domain="[('company_id', '=', company_id)," "('internal_type', 'not in', ('receivable', 'payable'))," "('is_off_balance', '=', False)]", compute="_compute_revenue_accrual_account", inverse="_inverse_revenue_accrual_account", ) # change account destination_account_id = fields.Many2one(string="To", comodel_name='account.account', help="Account to transfer to.") display_currency_helper = fields.Boolean(string="Currency Conversion Helper", compute='_compute_display_currency_helper', help="Technical field. Used to indicate whether or not to display the currency conversion tooltip. The tooltip informs a currency conversion will be performed with the transfer.") @api.depends('company_id') def _compute_expense_accrual_account(self): for record in self: record.expense_accrual_account = record.company_id.expense_accrual_account_id def _inverse_expense_accrual_account(self): for record in self: record.company_id.sudo().expense_accrual_account_id = record.expense_accrual_account @api.depends('company_id') def _compute_revenue_accrual_account(self): for record in self: record.revenue_accrual_account = record.company_id.revenue_accrual_account_id def _inverse_revenue_accrual_account(self): for record in self: record.company_id.sudo().revenue_accrual_account_id = record.revenue_accrual_account @api.depends('company_id') def _compute_journal_id(self): for record in self: record.journal_id = record.company_id.automatic_entry_default_journal_id def _inverse_journal_id(self): for record in self: record.company_id.sudo().automatic_entry_default_journal_id = record.journal_id @api.constrains('percentage', 'action') def _constraint_percentage(self): for record in self: if not (0.0 < record.percentage <= 100.0) and record.action == 'change_period': raise UserError(_("Percentage must be between 0 and 100")) @api.depends('percentage', 'move_line_ids') def _compute_total_amount(self): for record in self: record.total_amount = (record.percentage or 100) * sum(record.move_line_ids.mapped('balance')) / 100 @api.depends('total_amount', 'move_line_ids') def _compute_percentage(self): for record in self: total = (sum(record.move_line_ids.mapped('balance')) or record.total_amount) if total != 0: record.percentage = min((record.total_amount / total) * 100, 100) # min() to avoid value being slightly over 100 due to rounding error else: record.percentage = 100 @api.depends('move_line_ids') def _compute_account_type(self): for record in self: record.account_type = 'income' if sum(record.move_line_ids.mapped('balance')) < 0 else 'expense' @api.depends('destination_account_id') def _compute_display_currency_helper(self): for record in self: record.display_currency_helper = bool(record.destination_account_id.currency_id) @api.constrains('date', 'move_line_ids') def _check_date(self): for wizard in self: if wizard.move_line_ids.move_id._get_violated_lock_dates(wizard.date, False): raise ValidationError(_("The date selected is protected by a lock date")) if wizard.action == 'change_period': for move in wizard.move_line_ids.move_id: if move._get_violated_lock_dates(move.date, False): raise ValidationError(_("The date of some related entries is protected by a lock date")) @api.model def default_get(self, fields): res = super().default_get(fields) if not set(fields) & set(['move_line_ids', 'company_id']): return res if self.env.context.get('active_model') != 'account.move.line' or not self.env.context.get('active_ids'): raise UserError(_('This can only be used on journal items')) move_line_ids = self.env['account.move.line'].browse(self.env.context['active_ids']) res['move_line_ids'] = [(6, 0, move_line_ids.ids)] if any(move.state != 'posted' for move in move_line_ids.mapped('move_id')): raise UserError(_('You can only change the period/account for posted journal items.')) if any(move_line.reconciled for move_line in move_line_ids): raise UserError(_('You can only change the period/account for items that are not yet reconciled.')) if any(line.company_id != move_line_ids[0].company_id for line in move_line_ids): raise UserError(_('You cannot use this wizard on journal entries belonging to different companies.')) res['company_id'] = move_line_ids[0].company_id.id allowed_actions = set(dict(self._fields['action'].selection)) if self.env.context.get('default_action'): allowed_actions = {self.env.context['default_action']} if any(line.account_id.user_type_id != move_line_ids[0].account_id.user_type_id for line in move_line_ids): allowed_actions.discard('change_period') if not allowed_actions: raise UserError(_('No possible action found with the selected lines.')) res['action'] = allowed_actions.pop() return res def _get_move_dict_vals_change_account(self): line_vals = [] # Group data from selected move lines counterpart_balances = defaultdict(lambda: defaultdict(lambda: 0)) grouped_source_lines = defaultdict(lambda: self.env['account.move.line']) for line in self.move_line_ids.filtered(lambda x: x.account_id != self.destination_account_id): counterpart_currency = line.currency_id counterpart_amount_currency = line.amount_currency if self.destination_account_id.currency_id and self.destination_account_id.currency_id != self.company_id.currency_id: counterpart_currency = self.destination_account_id.currency_id counterpart_amount_currency = self.company_id.currency_id._convert(line.balance, self.destination_account_id.currency_id, self.company_id, line.date) counterpart_balances[(line.partner_id, counterpart_currency)]['amount_currency'] += counterpart_amount_currency counterpart_balances[(line.partner_id, counterpart_currency)]['balance'] += line.balance grouped_source_lines[(line.partner_id, line.currency_id, line.account_id)] += line # Generate counterpart lines' vals for (counterpart_partner, counterpart_currency), counterpart_vals in counterpart_balances.items(): source_accounts = self.move_line_ids.mapped('account_id') counterpart_label = len(source_accounts) == 1 and _("Transfer from %s", source_accounts.display_name) or _("Transfer counterpart") if not counterpart_currency.is_zero(counterpart_vals['amount_currency']): line_vals.append({ 'name': counterpart_label, 'debit': counterpart_vals['balance'] > 0 and self.company_id.currency_id.round(counterpart_vals['balance']) or 0, 'credit': counterpart_vals['balance'] < 0 and self.company_id.currency_id.round(-counterpart_vals['balance']) or 0, 'account_id': self.destination_account_id.id, 'partner_id': counterpart_partner.id or None, 'amount_currency': counterpart_currency.round((counterpart_vals['balance'] < 0 and -1 or 1) * abs(counterpart_vals['amount_currency'])) or 0, 'currency_id': counterpart_currency.id, }) # Generate change_account lines' vals for (partner, currency, account), lines in grouped_source_lines.items(): account_balance = sum(line.balance for line in lines) if not self.company_id.currency_id.is_zero(account_balance): account_amount_currency = currency.round(sum(line.amount_currency for line in lines)) line_vals.append({ 'name': _('Transfer to %s', self.destination_account_id.display_name or _('[Not set]')), 'debit': account_balance < 0 and self.company_id.currency_id.round(-account_balance) or 0, 'credit': account_balance > 0 and self.company_id.currency_id.round(account_balance) or 0, 'account_id': account.id, 'partner_id': partner.id or None, 'currency_id': currency.id, 'amount_currency': (account_balance > 0 and -1 or 1) * abs(account_amount_currency), }) return [{ 'currency_id': self.journal_id.currency_id.id or self.journal_id.company_id.currency_id.id, 'move_type': 'entry', 'journal_id': self.journal_id.id, 'date': fields.Date.to_string(self.date), 'ref': self.destination_account_id.display_name and _("Transfer entry to %s", self.destination_account_id.display_name or ''), 'line_ids': [(0, 0, line) for line in line_vals], }] def _get_move_dict_vals_change_period(self): # set the change_period account on the selected journal items accrual_account = self.revenue_accrual_account if self.account_type == 'income' else self.expense_accrual_account move_data = {'new_date': { 'currency_id': self.journal_id.currency_id.id or self.journal_id.company_id.currency_id.id, 'move_type': 'entry', 'line_ids': [], 'ref': _('Adjusting Entry'), 'date': fields.Date.to_string(self.date), 'journal_id': self.journal_id.id, }} # complete the account.move data for date, grouped_lines in groupby(self.move_line_ids, lambda m: m.move_id.date): grouped_lines = list(grouped_lines) amount = sum(l.balance for l in grouped_lines) move_data[date] = { 'currency_id': self.journal_id.currency_id.id or self.journal_id.company_id.currency_id.id, 'move_type': 'entry', 'line_ids': [], 'ref': self._format_strings(_('Adjusting Entry of {date} ({percent:.2f}% recognized on {new_date})'), grouped_lines[0].move_id, amount), 'date': fields.Date.to_string(date), 'journal_id': self.journal_id.id, } # compute the account.move.lines and the total amount per move for aml in self.move_line_ids: # account.move.line data reported_debit = aml.company_id.currency_id.round((self.percentage / 100) * aml.debit) reported_credit = aml.company_id.currency_id.round((self.percentage / 100) * aml.credit) reported_amount_currency = aml.currency_id.round((self.percentage / 100) * aml.amount_currency) move_data['new_date']['line_ids'] += [ (0, 0, { 'name': aml.name or '', 'debit': reported_debit, 'credit': reported_credit, 'amount_currency': reported_amount_currency, 'currency_id': aml.currency_id.id, 'account_id': aml.account_id.id, 'partner_id': aml.partner_id.id, }), (0, 0, { 'name': _('Adjusting Entry'), 'debit': reported_credit, 'credit': reported_debit, 'amount_currency': -reported_amount_currency, 'currency_id': aml.currency_id.id, 'account_id': accrual_account.id, 'partner_id': aml.partner_id.id, }), ] move_data[aml.move_id.date]['line_ids'] += [ (0, 0, { 'name': aml.name or '', 'debit': reported_credit, 'credit': reported_debit, 'amount_currency': -reported_amount_currency, 'currency_id': aml.currency_id.id, 'account_id': aml.account_id.id, 'partner_id': aml.partner_id.id, }), (0, 0, { 'name': _('Adjusting Entry'), 'debit': reported_debit, 'credit': reported_credit, 'amount_currency': reported_amount_currency, 'currency_id': aml.currency_id.id, 'account_id': accrual_account.id, 'partner_id': aml.partner_id.id, }), ] move_vals = [m for m in move_data.values()] return move_vals @api.depends('move_line_ids', 'journal_id', 'revenue_accrual_account', 'expense_accrual_account', 'percentage', 'date', 'account_type', 'action', 'destination_account_id') def _compute_move_data(self): for record in self: if record.action == 'change_period': if any(line.account_id.user_type_id != record.move_line_ids[0].account_id.user_type_id for line in record.move_line_ids): raise UserError(_('All accounts on the lines must be of the same type.')) if record.action == 'change_period': record.move_data = json.dumps(record._get_move_dict_vals_change_period()) elif record.action == 'change_account': record.move_data = json.dumps(record._get_move_dict_vals_change_account()) @api.depends('move_data') def _compute_preview_move_data(self): for record in self: preview_columns = [ {'field': 'account_id', 'label': _('Account')}, {'field': 'name', 'label': _('Label')}, {'field': 'debit', 'label': _('Debit'), 'class': 'text-right text-nowrap'}, {'field': 'credit', 'label': _('Credit'), 'class': 'text-right text-nowrap'}, ] if record.action == 'change_account': preview_columns[2:2] = [{'field': 'partner_id', 'label': _('Partner')}] move_vals = json.loads(record.move_data) preview_vals = [] for move in move_vals[:4]: preview_vals += [self.env['account.move']._move_dict_to_preview_vals(move, record.company_id.currency_id)] preview_discarded = max(0, len(move_vals) - len(preview_vals)) record.preview_move_data = json.dumps({ 'groups_vals': preview_vals, 'options': { 'discarded_number': _("%d moves", preview_discarded) if preview_discarded else False, 'columns': preview_columns, }, }) def do_action(self): move_vals = json.loads(self.move_data) if self.action == 'change_period': return self._do_action_change_period(move_vals) elif self.action == 'change_account': return self._do_action_change_account(move_vals) def _do_action_change_period(self, move_vals): accrual_account = self.revenue_accrual_account if self.account_type == 'income' else self.expense_accrual_account created_moves = self.env['account.move'].create(move_vals) created_moves._post() destination_move = created_moves[0] destination_move_offset = 0 destination_messages = [] accrual_move_messages = defaultdict(lambda: []) accrual_move_offsets = defaultdict(int) for move in self.move_line_ids.move_id: amount = sum((self.move_line_ids._origin & move.line_ids).mapped('balance')) accrual_move = created_moves[1:].filtered(lambda m: m.date == move.date) if accrual_account.reconcile and accrual_move.state == 'posted' and destination_move.state == 'posted': destination_move_lines = destination_move.mapped('line_ids').filtered(lambda line: line.account_id == accrual_account)[destination_move_offset:destination_move_offset+2] destination_move_offset += 2 accrual_move_lines = accrual_move.mapped('line_ids').filtered(lambda line: line.account_id == accrual_account)[accrual_move_offsets[accrual_move]:accrual_move_offsets[accrual_move]+2] accrual_move_offsets[accrual_move] += 2 (accrual_move_lines + destination_move_lines).filtered(lambda line: not line.currency_id.is_zero(line.balance)).reconcile() move.message_post(body=self._format_strings(_('Adjusting Entries have been created for this invoice:<ul><li>%(link1)s cancelling ' '{percent:.2f}%% of {amount}</li><li>%(link0)s postponing it to {new_date}</li></ul>', link0=self._format_move_link(destination_move), link1=self._format_move_link(accrual_move), ), move, amount)) destination_messages += [self._format_strings(_('Adjusting Entry {link}: {percent:.2f}% of {amount} recognized from {date}'), move, amount)] accrual_move_messages[accrual_move] += [self._format_strings(_('Adjusting Entry for {link}: {percent:.2f}% of {amount} recognized on {new_date}'), move, amount)] destination_move.message_post(body='<br/>\n'.join(destination_messages)) for accrual_move, messages in accrual_move_messages.items(): accrual_move.message_post(body='<br/>\n'.join(messages)) # open the generated entries action = { 'name': _('Generated Entries'), 'domain': [('id', 'in', created_moves.ids)], 'res_model': 'account.move', 'view_mode': 'tree,form', 'type': 'ir.actions.act_window', 'views': [(self.env.ref('account.view_move_tree').id, 'tree'), (False, 'form')], } if len(created_moves) == 1: action.update({'view_mode': 'form', 'res_id': created_moves.id}) return action def _do_action_change_account(self, move_vals): new_move = self.env['account.move'].create(move_vals) new_move._post() # Group lines grouped_lines = defaultdict(lambda: self.env['account.move.line']) destination_lines = self.move_line_ids.filtered(lambda x: x.account_id == self.destination_account_id) for line in self.move_line_ids - destination_lines: grouped_lines[(line.partner_id, line.currency_id, line.account_id)] += line # Reconcile for (partner, currency, account), lines in grouped_lines.items(): if account.reconcile: to_reconcile = lines + new_move.line_ids.filtered(lambda x: x.account_id == account and x.partner_id == partner and x.currency_id == currency) to_reconcile.reconcile() if destination_lines and self.destination_account_id.reconcile: to_reconcile = destination_lines + new_move.line_ids.filtered(lambda x: x.account_id == self.destination_account_id and x.partner_id == partner and x.currency_id == currency) to_reconcile.reconcile() # Log the operation on source moves acc_transfer_per_move = defaultdict(lambda: defaultdict(lambda: 0)) # dict(move, dict(account, balance)) for line in self.move_line_ids: acc_transfer_per_move[line.move_id][line.account_id] += line.balance for move, balances_per_account in acc_transfer_per_move.items(): message_to_log = self._format_transfer_source_log(balances_per_account, new_move) if message_to_log: move.message_post(body=message_to_log) # Log on target move as well new_move.message_post(body=self._format_new_transfer_move_log(acc_transfer_per_move)) return { 'name': _("Transfer"), 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'account.move', 'res_id': new_move.id, } # Transfer utils def _format_new_transfer_move_log(self, acc_transfer_per_move): format = _("<li>{amount} ({debit_credit}) from {link}, <strong>%(account_source_name)s</strong></li>") rslt = _("This entry transfers the following amounts to <strong>%(destination)s</strong> <ul>", destination=self.destination_account_id.display_name) for move, balances_per_account in acc_transfer_per_move.items(): for account, balance in balances_per_account.items(): if account != self.destination_account_id: # Otherwise, logging it here is confusing for the user rslt += self._format_strings(format, move, balance) % {'account_source_name': account.display_name} rslt += '</ul>' return rslt def _format_transfer_source_log(self, balances_per_account, transfer_move): transfer_format = _("<li>{amount} ({debit_credit}) from <strong>%s</strong> were transferred to <strong>{account_target_name}</strong> by {link}</li>") content = '' for account, balance in balances_per_account.items(): if account != self.destination_account_id: content += self._format_strings(transfer_format, transfer_move, balance) % account.display_name return content and '<ul>' + content + '</ul>' or None def _format_move_link(self, move): move_link_format = "<a href=# data-oe-model=account.move data-oe-id={move_id}>{move_name}</a>" return move_link_format.format(move_id=move.id, move_name=move.name) def _format_strings(self, string, move, amount): return string.format( percent=self.percentage, name=move.name, id=move.id, amount=formatLang(self.env, abs(amount), currency_obj=self.company_id.currency_id), debit_credit=amount < 0 and _('C') or _('D'), link=self._format_move_link(move), date=format_date(self.env, move.date), new_date=self.date and format_date(self.env, self.date) or _('[Not set]'), account_target_name=self.destination_account_id.display_name, )
55.168514
24,881
34,477
py
PYTHON
15.0
# -*- coding: utf-8 -*- from collections import defaultdict from lxml import etree from odoo import models, fields, api, _ from odoo.exceptions import UserError from odoo.tools import float_compare, frozendict class AccountPaymentRegister(models.TransientModel): _name = 'account.payment.register' _description = 'Register Payment' # == Business fields == payment_date = fields.Date(string="Payment Date", required=True, default=fields.Date.context_today) amount = fields.Monetary(currency_field='currency_id', store=True, readonly=False, compute='_compute_amount') communication = fields.Char(string="Memo", store=True, readonly=False, compute='_compute_communication') group_payment = fields.Boolean(string="Group Payments", store=True, readonly=False, compute='_compute_group_payment', help="Only one payment will be created by partner (bank)/ currency.") currency_id = fields.Many2one('res.currency', string='Currency', store=True, readonly=False, compute='_compute_currency_id', help="The payment's currency.") journal_id = fields.Many2one('account.journal', store=True, readonly=False, compute='_compute_journal_id', domain="[('company_id', '=', company_id), ('type', 'in', ('bank', 'cash'))]") available_partner_bank_ids = fields.Many2many( comodel_name='res.partner.bank', compute='_compute_available_partner_bank_ids', ) partner_bank_id = fields.Many2one( comodel_name='res.partner.bank', string="Recipient Bank Account", readonly=False, store=True, compute='_compute_partner_bank_id', domain="[('id', 'in', available_partner_bank_ids)]", ) company_currency_id = fields.Many2one('res.currency', string="Company Currency", related='company_id.currency_id') # == Fields given through the context == line_ids = fields.Many2many('account.move.line', 'account_payment_register_move_line_rel', 'wizard_id', 'line_id', string="Journal items", readonly=True, copy=False,) payment_type = fields.Selection([ ('outbound', 'Send Money'), ('inbound', 'Receive Money'), ], string='Payment Type', store=True, copy=False, compute='_compute_from_lines') partner_type = fields.Selection([ ('customer', 'Customer'), ('supplier', 'Vendor'), ], store=True, copy=False, compute='_compute_from_lines') source_amount = fields.Monetary( string="Amount to Pay (company currency)", store=True, copy=False, currency_field='company_currency_id', compute='_compute_from_lines') source_amount_currency = fields.Monetary( string="Amount to Pay (foreign currency)", store=True, copy=False, currency_field='source_currency_id', compute='_compute_from_lines') source_currency_id = fields.Many2one('res.currency', string='Source Currency', store=True, copy=False, compute='_compute_from_lines', help="The payment's currency.") can_edit_wizard = fields.Boolean(store=True, copy=False, compute='_compute_from_lines', help="Technical field used to indicate the user can edit the wizard content such as the amount.") can_group_payments = fields.Boolean(store=True, copy=False, compute='_compute_from_lines', help="Technical field used to indicate the user can see the 'group_payments' box.") company_id = fields.Many2one('res.company', store=True, copy=False, compute='_compute_from_lines') partner_id = fields.Many2one('res.partner', string="Customer/Vendor", store=True, copy=False, ondelete='restrict', compute='_compute_from_lines') # == Payment methods fields == payment_method_line_id = fields.Many2one('account.payment.method.line', string='Payment Method', readonly=False, store=True, compute='_compute_payment_method_line_id', domain="[('id', 'in', available_payment_method_line_ids)]", help="Manual: Pay or Get paid by any method outside of Odoo.\n" "Payment Acquirers: Each payment acquirer has its own Payment Method. Request a transaction on/to a card thanks to a payment token saved by the partner when buying or subscribing online.\n" "Check: Pay bills by check and print it from Odoo.\n" "Batch Deposit: Collect several customer checks at once generating and submitting a batch deposit to your bank. Module account_batch_payment is necessary.\n" "SEPA Credit Transfer: Pay in the SEPA zone by submitting a SEPA Credit Transfer file to your bank. Module account_sepa is necessary.\n" "SEPA Direct Debit: Get paid in the SEPA zone thanks to a mandate your partner will have granted to you. Module account_sepa is necessary.\n") available_payment_method_line_ids = fields.Many2many('account.payment.method.line', compute='_compute_payment_method_line_fields') hide_payment_method_line = fields.Boolean( compute='_compute_payment_method_line_fields', help="Technical field used to hide the payment method if the selected journal has only one available which is 'manual'") # == Payment difference fields == payment_difference = fields.Monetary( compute='_compute_payment_difference') payment_difference_handling = fields.Selection([ ('open', 'Keep open'), ('reconcile', 'Mark as fully paid'), ], default='open', string="Payment Difference Handling") writeoff_account_id = fields.Many2one('account.account', string="Difference Account", copy=False, domain="[('deprecated', '=', False), ('company_id', '=', company_id)]") writeoff_label = fields.Char(string='Journal Item Label', default='Write-Off', help='Change label of the counterpart that will hold the payment difference') # == Display purpose fields == show_partner_bank_account = fields.Boolean( compute='_compute_show_require_partner_bank', help="Technical field used to know whether the field `partner_bank_id` needs to be displayed or not in the payments form views") require_partner_bank_account = fields.Boolean( compute='_compute_show_require_partner_bank', help="Technical field used to know whether the field `partner_bank_id` needs to be required or not in the payments form views") country_code = fields.Char(related='company_id.account_fiscal_country_id.code', readonly=True) # ------------------------------------------------------------------------- # HELPERS # ------------------------------------------------------------------------- @api.model def _get_batch_communication(self, batch_result): ''' Helper to compute the communication based on the batch. :param batch_result: A batch returned by '_get_batches'. :return: A string representing a communication to be set on payment. ''' labels = set(line.name or line.move_id.ref or line.move_id.name for line in batch_result['lines']) return ' '.join(sorted(labels)) @api.model def _get_batch_journal(self, batch_result): """ Helper to compute the journal based on the batch. :param batch_result: A batch returned by '_get_batches'. :return: An account.journal record. """ payment_values = batch_result['payment_values'] foreign_currency_id = payment_values['currency_id'] partner_bank_id = payment_values['partner_bank_id'] currency_domain = [('currency_id', '=', foreign_currency_id)] partner_bank_domain = [('bank_account_id', '=', partner_bank_id)] default_domain = [ ('type', 'in', ('bank', 'cash')), ('company_id', '=', batch_result['lines'].company_id.id), ] if partner_bank_id: extra_domains = ( currency_domain + partner_bank_domain, partner_bank_domain, currency_domain, [], ) else: extra_domains = ( currency_domain, [], ) for extra_domain in extra_domains: journal = self.env['account.journal'].search(default_domain + extra_domain, limit=1) if journal: return journal return self.env['account.journal'] @api.model def _get_batch_available_partner_banks(self, batch_result, journal): payment_values = batch_result['payment_values'] company = batch_result['lines'].company_id # A specific bank account is set on the journal. The user must use this one. if payment_values['payment_type'] == 'inbound': # Receiving money on a bank account linked to the journal. return journal.bank_account_id else: # Sending money to a bank account owned by a partner. return batch_result['lines'].partner_id.bank_ids.filtered(lambda x: x.company_id.id in (False, company.id))._origin @api.model def _get_line_batch_key(self, line): ''' Turn the line passed as parameter to a dictionary defining on which way the lines will be grouped together. :return: A python dictionary. ''' move = line.move_id partner_bank_account = self.env['res.partner.bank'] if move.is_invoice(include_receipts=True): partner_bank_account = move.partner_bank_id._origin return { 'partner_id': line.partner_id.id, 'account_id': line.account_id.id, 'currency_id': line.currency_id.id, 'partner_bank_id': partner_bank_account.id, 'partner_type': 'customer' if line.account_internal_type == 'receivable' else 'supplier', } def _get_batches(self): ''' Group the account.move.line linked to the wizard together. Lines are grouped if they share 'partner_id','account_id','currency_id' & 'partner_type' and if 0 or 1 partner_bank_id can be determined for the group. :return: A list of batches, each one containing: * payment_values: A dictionary of payment values. * moves: An account.move recordset. ''' self.ensure_one() lines = self.line_ids._origin if len(lines.company_id) > 1: raise UserError(_("You can't create payments for entries belonging to different companies.")) if not lines: raise UserError(_("You can't open the register payment wizard without at least one receivable/payable line.")) batches = defaultdict(lambda: {'lines': self.env['account.move.line']}) for line in lines: batch_key = self._get_line_batch_key(line) serialized_key = '-'.join(str(v) for v in batch_key.values()) vals = batches[serialized_key] vals['payment_values'] = batch_key vals['lines'] += line # Compute 'payment_type'. for vals in batches.values(): lines = vals['lines'] balance = sum(lines.mapped('balance')) vals['payment_values']['payment_type'] = 'inbound' if balance > 0.0 else 'outbound' return list(batches.values()) @api.model def _get_wizard_values_from_batch(self, batch_result): ''' Extract values from the batch passed as parameter (see '_get_batches') to be mounted in the wizard view. :param batch_result: A batch returned by '_get_batches'. :return: A dictionary containing valid fields ''' payment_values = batch_result['payment_values'] lines = batch_result['lines'] company = lines[0].company_id source_amount = abs(sum(lines.mapped('amount_residual'))) if payment_values['currency_id'] == company.currency_id.id: source_amount_currency = source_amount else: source_amount_currency = abs(sum(lines.mapped('amount_residual_currency'))) return { 'company_id': company.id, 'partner_id': payment_values['partner_id'], 'partner_type': payment_values['partner_type'], 'payment_type': payment_values['payment_type'], 'source_currency_id': payment_values['currency_id'], 'source_amount': source_amount, 'source_amount_currency': source_amount_currency, } # ------------------------------------------------------------------------- # COMPUTE METHODS # ------------------------------------------------------------------------- @api.depends('line_ids') def _compute_from_lines(self): ''' Load initial values from the account.moves passed through the context. ''' for wizard in self: batches = wizard._get_batches() batch_result = batches[0] wizard_values_from_batch = wizard._get_wizard_values_from_batch(batch_result) if len(batches) == 1: # == Single batch to be mounted on the view == wizard.update(wizard_values_from_batch) wizard.can_edit_wizard = True wizard.can_group_payments = len(batch_result['lines']) != 1 else: # == Multiple batches: The wizard is not editable == wizard.update({ 'company_id': batches[0]['lines'][0].company_id.id, 'partner_id': False, 'partner_type': False, 'payment_type': wizard_values_from_batch['payment_type'], 'source_currency_id': False, 'source_amount': False, 'source_amount_currency': False, }) wizard.can_edit_wizard = False wizard.can_group_payments = any(len(batch_result['lines']) != 1 for batch_result in batches) @api.depends('can_edit_wizard') def _compute_communication(self): # The communication can't be computed in '_compute_from_lines' because # it's a compute editable field and then, should be computed in a separated method. for wizard in self: if wizard.can_edit_wizard: batches = wizard._get_batches() wizard.communication = wizard._get_batch_communication(batches[0]) else: wizard.communication = False @api.depends('can_edit_wizard') def _compute_group_payment(self): for wizard in self: if wizard.can_edit_wizard: batches = wizard._get_batches() wizard.group_payment = len(batches[0]['lines'].move_id) == 1 else: wizard.group_payment = False @api.depends('journal_id') def _compute_currency_id(self): for wizard in self: wizard.currency_id = wizard.journal_id.currency_id or wizard.source_currency_id or wizard.company_id.currency_id @api.depends('can_edit_wizard', 'company_id') def _compute_journal_id(self): for wizard in self: if wizard.can_edit_wizard: batch = wizard._get_batches()[0] wizard.journal_id = wizard._get_batch_journal(batch) else: wizard.journal_id = self.env['account.journal'].search([ ('type', 'in', ('bank', 'cash')), ('company_id', '=', wizard.company_id.id), ], limit=1) @api.depends('can_edit_wizard', 'journal_id') def _compute_available_partner_bank_ids(self): for wizard in self: if wizard.can_edit_wizard: batch = wizard._get_batches()[0] wizard.available_partner_bank_ids = wizard._get_batch_available_partner_banks(batch, wizard.journal_id) else: wizard.available_partner_bank_ids = None @api.depends('journal_id', 'available_partner_bank_ids') def _compute_partner_bank_id(self): for wizard in self: if wizard.can_edit_wizard: batch = wizard._get_batches()[0] partner_bank_id = batch['payment_values']['partner_bank_id'] available_partner_banks = wizard.available_partner_bank_ids._origin if partner_bank_id and partner_bank_id in available_partner_banks.ids: wizard.partner_bank_id = self.env['res.partner.bank'].browse(partner_bank_id) else: wizard.partner_bank_id = available_partner_banks[:1] else: wizard.partner_bank_id = None @api.depends('payment_type', 'journal_id', 'currency_id') def _compute_payment_method_line_fields(self): for wizard in self: wizard.available_payment_method_line_ids = wizard.journal_id._get_available_payment_method_lines(wizard.payment_type) if wizard.payment_method_line_id.id not in wizard.available_payment_method_line_ids.ids: # In some cases, we could be linked to a payment method line that has been unlinked from the journal. # In such cases, we want to show it on the payment. wizard.hide_payment_method_line = False else: wizard.hide_payment_method_line = len(wizard.available_payment_method_line_ids) == 1 \ and wizard.available_payment_method_line_ids.code == 'manual' @api.depends('payment_type', 'journal_id') def _compute_payment_method_line_id(self): for wizard in self: available_payment_method_lines = wizard.journal_id._get_available_payment_method_lines(wizard.payment_type) # Select the first available one by default. if available_payment_method_lines: wizard.payment_method_line_id = available_payment_method_lines[0]._origin else: wizard.payment_method_line_id = False @api.depends('payment_method_line_id') def _compute_show_require_partner_bank(self): """ Computes if the destination bank account must be displayed in the payment form view. By default, it won't be displayed but some modules might change that, depending on the payment type.""" for wizard in self: wizard.show_partner_bank_account = wizard.payment_method_line_id.code in self.env['account.payment']._get_method_codes_using_bank_account() wizard.require_partner_bank_account = wizard.payment_method_line_id.code in self.env['account.payment']._get_method_codes_needing_bank_account() @api.depends('source_amount', 'source_amount_currency', 'source_currency_id', 'company_id', 'currency_id', 'payment_date') def _compute_amount(self): for wizard in self: if wizard.source_currency_id == wizard.currency_id: # Same currency. wizard.amount = wizard.source_amount_currency else: wizard.amount = wizard.source_currency_id._convert(wizard.source_amount_currency, wizard.currency_id, wizard.company_id, wizard.payment_date or fields.Date.today()) @api.depends('amount') def _compute_payment_difference(self): for wizard in self: if wizard.source_currency_id == wizard.currency_id: # Same currency. wizard.payment_difference = wizard.source_amount_currency - wizard.amount elif wizard.currency_id == wizard.company_id.currency_id: # Payment expressed on the company's currency. wizard.payment_difference = wizard.source_amount - wizard.amount else: # Foreign currency on payment different than the one set on the journal entries. amount_payment_currency = wizard.company_id.currency_id._convert(wizard.source_amount, wizard.currency_id, wizard.company_id, wizard.payment_date or fields.Date.today()) wizard.payment_difference = amount_payment_currency - wizard.amount # ------------------------------------------------------------------------- # LOW-LEVEL METHODS # ------------------------------------------------------------------------- @api.model def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): # OVERRIDE to add the 'available_partner_bank_ids' field dynamically inside the view. # TO BE REMOVED IN MASTER res = super().fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) if view_type == 'form': form_view = self.env.ref('account.view_account_payment_register_form') tree = etree.fromstring(res['arch']) if res.get('view_id') == form_view.id and len(tree.xpath("//field[@name='available_partner_bank_ids']")) == 0: # Don't force people to update the account module. arch_tree = etree.fromstring(form_view.arch) if arch_tree.tag == 'form': arch_tree.insert(0, etree.Element('field', attrib={ 'name': 'available_partner_bank_ids', 'invisible': '1', })) form_view.sudo().write({'arch': etree.tostring(arch_tree, encoding='unicode')}) return super().fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) return res @api.model def default_get(self, fields_list): # OVERRIDE res = super().default_get(fields_list) if 'line_ids' in fields_list and 'line_ids' not in res: # Retrieve moves to pay from the context. if self._context.get('active_model') == 'account.move': lines = self.env['account.move'].browse(self._context.get('active_ids', [])).line_ids elif self._context.get('active_model') == 'account.move.line': lines = self.env['account.move.line'].browse(self._context.get('active_ids', [])) else: raise UserError(_( "The register payment wizard should only be called on account.move or account.move.line records." )) if 'journal_id' in res and not self.env['account.journal'].browse(res['journal_id'])\ .filtered_domain([('company_id', '=', lines.company_id.id), ('type', 'in', ('bank', 'cash'))]): # default can be inherited from the list view, should be computed instead del res['journal_id'] # Keep lines having a residual amount to pay. available_lines = self.env['account.move.line'] for line in lines: if line.move_id.state != 'posted': raise UserError(_("You can only register payment for posted journal entries.")) if line.account_internal_type not in ('receivable', 'payable'): continue if line.currency_id: if line.currency_id.is_zero(line.amount_residual_currency): continue else: if line.company_currency_id.is_zero(line.amount_residual): continue available_lines |= line # Check. if not available_lines: raise UserError(_("You can't register a payment because there is nothing left to pay on the selected journal items.")) if len(lines.company_id) > 1: raise UserError(_("You can't create payments for entries belonging to different companies.")) if len(set(available_lines.mapped('account_internal_type'))) > 1: raise UserError(_("You can't register payments for journal items being either all inbound, either all outbound.")) res['line_ids'] = [(6, 0, available_lines.ids)] return res # ------------------------------------------------------------------------- # BUSINESS METHODS # ------------------------------------------------------------------------- def _create_payment_vals_from_wizard(self): payment_vals = { 'date': self.payment_date, 'amount': self.amount, 'payment_type': self.payment_type, 'partner_type': self.partner_type, 'ref': self.communication, 'journal_id': self.journal_id.id, 'currency_id': self.currency_id.id, 'partner_id': self.partner_id.id, 'partner_bank_id': self.partner_bank_id.id, 'payment_method_line_id': self.payment_method_line_id.id, 'destination_account_id': self.line_ids[0].account_id.id } if not self.currency_id.is_zero(self.payment_difference) and self.payment_difference_handling == 'reconcile': payment_vals['write_off_line_vals'] = { 'name': self.writeoff_label, 'amount': self.payment_difference, 'account_id': self.writeoff_account_id.id, } return payment_vals def _create_payment_vals_from_batch(self, batch_result): batch_values = self._get_wizard_values_from_batch(batch_result) if batch_values['payment_type'] == 'inbound': partner_bank_id = self.journal_id.bank_account_id.id else: partner_bank_id = batch_result['payment_values']['partner_bank_id'] payment_method_line = self.payment_method_line_id if batch_values['payment_type'] != payment_method_line.payment_type: payment_method_line = self.journal_id._get_available_payment_method_lines(batch_values['payment_type'])[:1] return { 'date': self.payment_date, 'amount': batch_values['source_amount_currency'], 'payment_type': batch_values['payment_type'], 'partner_type': batch_values['partner_type'], 'ref': self._get_batch_communication(batch_result), 'journal_id': self.journal_id.id, 'currency_id': batch_values['source_currency_id'], 'partner_id': batch_values['partner_id'], 'partner_bank_id': partner_bank_id, 'payment_method_line_id': payment_method_line.id, 'destination_account_id': batch_result['lines'][0].account_id.id } def _init_payments(self, to_process, edit_mode=False): """ Create the payments. :param to_process: A list of python dictionary, one for each payment to create, containing: * create_vals: The values used for the 'create' method. * to_reconcile: The journal items to perform the reconciliation. * batch: A python dict containing everything you want about the source journal items to which a payment will be created (see '_get_batches'). :param edit_mode: Is the wizard in edition mode. """ payments = self.env['account.payment'].create([x['create_vals'] for x in to_process]) for payment, vals in zip(payments, to_process): vals['payment'] = payment # If payments are made using a currency different than the source one, ensure the balance match exactly in # order to fully paid the source journal items. # For example, suppose a new currency B having a rate 100:1 regarding the company currency A. # If you try to pay 12.15A using 0.12B, the computed balance will be 12.00A for the payment instead of 12.15A. if edit_mode: lines = vals['to_reconcile'] # Batches are made using the same currency so making 'lines.currency_id' is ok. if payment.currency_id != lines.currency_id: liquidity_lines, counterpart_lines, writeoff_lines = payment._seek_for_lines() source_balance = abs(sum(lines.mapped('amount_residual'))) if liquidity_lines[0].balance: payment_rate = liquidity_lines[0].amount_currency / liquidity_lines[0].balance else: payment_rate = 0.0 source_balance_converted = abs(source_balance) * payment_rate # Translate the balance into the payment currency is order to be able to compare them. # In case in both have the same value (12.15 * 0.01 ~= 0.12 in our example), it means the user # attempt to fully paid the source lines and then, we need to manually fix them to get a perfect # match. payment_balance = abs(sum(counterpart_lines.mapped('balance'))) payment_amount_currency = abs(sum(counterpart_lines.mapped('amount_currency'))) if not payment.currency_id.is_zero(source_balance_converted - payment_amount_currency): continue delta_balance = source_balance - payment_balance # Balance are already the same. if self.company_currency_id.is_zero(delta_balance): continue # Fix the balance but make sure to peek the liquidity and counterpart lines first. debit_lines = (liquidity_lines + counterpart_lines).filtered('debit') credit_lines = (liquidity_lines + counterpart_lines).filtered('credit') if debit_lines and credit_lines: payment.move_id.write({'line_ids': [ (1, debit_lines[0].id, {'debit': debit_lines[0].debit + delta_balance}), (1, credit_lines[0].id, {'credit': credit_lines[0].credit + delta_balance}), ]}) return payments def _post_payments(self, to_process, edit_mode=False): """ Post the newly created payments. :param to_process: A list of python dictionary, one for each payment to create, containing: * create_vals: The values used for the 'create' method. * to_reconcile: The journal items to perform the reconciliation. * batch: A python dict containing everything you want about the source journal items to which a payment will be created (see '_get_batches'). :param edit_mode: Is the wizard in edition mode. """ payments = self.env['account.payment'] for vals in to_process: payments |= vals['payment'] payments.action_post() def _reconcile_payments(self, to_process, edit_mode=False): """ Reconcile the payments. :param to_process: A list of python dictionary, one for each payment to create, containing: * create_vals: The values used for the 'create' method. * to_reconcile: The journal items to perform the reconciliation. * batch: A python dict containing everything you want about the source journal items to which a payment will be created (see '_get_batches'). :param edit_mode: Is the wizard in edition mode. """ domain = [ ('parent_state', '=', 'posted'), ('account_internal_type', 'in', ('receivable', 'payable')), ('reconciled', '=', False), ] for vals in to_process: payment_lines = vals['payment'].line_ids.filtered_domain(domain) lines = vals['to_reconcile'] for account in payment_lines.account_id: (payment_lines + lines)\ .filtered_domain([('account_id', '=', account.id), ('reconciled', '=', False)])\ .reconcile() def _create_payments(self): self.ensure_one() batches = self._get_batches() edit_mode = self.can_edit_wizard and (len(batches[0]['lines']) == 1 or self.group_payment) to_process = [] if edit_mode: payment_vals = self._create_payment_vals_from_wizard() to_process.append({ 'create_vals': payment_vals, 'to_reconcile': batches[0]['lines'], 'batch': batches[0], }) else: # Don't group payments: Create one batch per move. if not self.group_payment: new_batches = [] for batch_result in batches: for line in batch_result['lines']: new_batches.append({ **batch_result, 'payment_values': { **batch_result['payment_values'], 'payment_type': 'inbound' if line.balance > 0 else 'outbound' }, 'lines': line, }) batches = new_batches for batch_result in batches: to_process.append({ 'create_vals': self._create_payment_vals_from_batch(batch_result), 'to_reconcile': batch_result['lines'], 'batch': batch_result, }) payments = self._init_payments(to_process, edit_mode=edit_mode) self._post_payments(to_process, edit_mode=edit_mode) self._reconcile_payments(to_process, edit_mode=edit_mode) return payments def action_create_payments(self): payments = self._create_payments() if self._context.get('dont_redirect_to_payments'): return True action = { 'name': _('Payments'), 'type': 'ir.actions.act_window', 'res_model': 'account.payment', 'context': {'create': False}, } if len(payments) == 1: action.update({ 'view_mode': 'form', 'res_id': payments.id, }) else: action.update({ 'view_mode': 'tree,form', 'domain': [('id', 'in', payments.ids)], }) return action
49.112536
34,477
7,498
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.addons.mail.wizard.mail_compose_message import _reopen from odoo.exceptions import UserError from odoo.tools.misc import get_lang class AccountInvoiceSend(models.TransientModel): _name = 'account.invoice.send' _inherits = {'mail.compose.message':'composer_id'} _description = 'Account Invoice Send' is_email = fields.Boolean('Email', default=lambda self: self.env.company.invoice_is_email) invoice_without_email = fields.Text(compute='_compute_invoice_without_email', string='invoice(s) that will not be sent') is_print = fields.Boolean('Print', default=lambda self: self.env.company.invoice_is_print) printed = fields.Boolean('Is Printed', default=False) invoice_ids = fields.Many2many('account.move', 'account_move_account_invoice_send_rel', string='Invoices') composer_id = fields.Many2one('mail.compose.message', string='Composer', required=True, ondelete='cascade') template_id = fields.Many2one( 'mail.template', 'Use template', index=True, domain="[('model', '=', 'account.move')]" ) # View fields move_types = fields.Char( string='Move types', compute='_compute_move_types', readonly=True, help='Technical field containing a textual representation of the selected move types, ' 'if multiple. It is used to inform the user in the window in such case.') @api.model def default_get(self, fields): res = super(AccountInvoiceSend, self).default_get(fields) res_ids = self._context.get('active_ids') invoices = self.env['account.move'].browse(res_ids).filtered(lambda move: move.is_invoice(include_receipts=True)) if not invoices: raise UserError(_("You can only send invoices.")) composer = self.env['mail.compose.message'].create({ 'composition_mode': 'comment' if len(res_ids) == 1 else 'mass_mail', }) res.update({ 'invoice_ids': res_ids, 'composer_id': composer.id, }) return res @api.onchange('invoice_ids') def _compute_composition_mode(self): for wizard in self: wizard.composer_id.composition_mode = 'comment' if len(wizard.invoice_ids) == 1 else 'mass_mail' @api.onchange('invoice_ids') def _compute_move_types(self): for wizard in self: move_types = False if len(wizard.invoice_ids) > 1: moves = self.env['account.move'].browse(self.env.context.get('active_ids')) # Get the move types of all selected moves and see if there is more than one of them. # If so, we'll display a warning on the next window about it. move_types_set = set(m.type_name for m in moves) if len(move_types_set) > 1: move_types = ', '.join(move_types_set) wizard.move_types = move_types @api.onchange('template_id') def onchange_template_id(self): for wizard in self: if wizard.composer_id: wizard.composer_id.template_id = wizard.template_id.id wizard._compute_composition_mode() wizard.composer_id._onchange_template_id_wrapper() @api.onchange('is_email') def onchange_is_email(self): if self.is_email: res_ids = self._context.get('active_ids') if not self.composer_id: self.composer_id = self.env['mail.compose.message'].create({ 'composition_mode': 'comment' if len(res_ids) == 1 else 'mass_mail', 'template_id': self.template_id.id }) else: self.composer_id.composition_mode = 'comment' if len(res_ids) == 1 else 'mass_mail' self.composer_id.template_id = self.template_id.id self._compute_composition_mode() self.composer_id._onchange_template_id_wrapper() @api.onchange('is_email') def _compute_invoice_without_email(self): for wizard in self: if wizard.is_email and len(wizard.invoice_ids) > 1: invoices = self.env['account.move'].search([ ('id', 'in', self.env.context.get('active_ids')), ('partner_id.email', '=', False) ]) if invoices: wizard.invoice_without_email = "%s\n%s" % ( _("The following invoice(s) will not be sent by email, because the customers don't have email address."), "\n".join([i.name for i in invoices]) ) else: wizard.invoice_without_email = False else: wizard.invoice_without_email = False def _send_email(self): if self.is_email: # with_context : we don't want to reimport the file we just exported. self.composer_id.with_context(no_new_invoice=True, mail_notify_author=self.env.user.partner_id in self.composer_id.partner_ids, mailing_document_based=True, )._action_send_mail() if self.env.context.get('mark_invoice_as_sent'): #Salesman send posted invoice, without the right to write #but they should have the right to change this flag self.mapped('invoice_ids').sudo().write({'is_move_sent': True}) def _print_document(self): """ to override for each type of models that will use this composer.""" self.ensure_one() action = self.invoice_ids.action_invoice_print() action.update({'close_on_report_download': True}) return action def send_and_print_action(self): self.ensure_one() # Send the mails in the correct language by splitting the ids per lang. # This should ideally be fixed in mail_compose_message, so when a fix is made there this whole commit should be reverted. # basically self.body (which could be manually edited) extracts self.template_id, # which is then not translated for each customer. if self.composition_mode == 'mass_mail' and self.template_id: active_ids = self.env.context.get('active_ids', self.res_id) active_records = self.env[self.model].browse(active_ids) langs = active_records.mapped('partner_id.lang') default_lang = get_lang(self.env) for lang in (set(langs) or [default_lang]): active_ids_lang = active_records.filtered(lambda r: r.partner_id.lang == lang).ids self_lang = self.with_context(active_ids=active_ids_lang, lang=lang) self_lang.onchange_template_id() self_lang._send_email() else: self._send_email() if self.is_print: return self._print_document() return {'type': 'ir.actions.act_window_close'} def save_as_template(self): self.ensure_one() self.composer_id.action_save_as_template() self.template_id = self.composer_id.template_id.id action = _reopen(self, self.id, self.model, context=self._context) action.update({'name': _('Send Invoice')}) return action
46
7,498
2,435
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.tools.misc import get_lang class AccountCommonReport(models.TransientModel): _name = "account.common.report" _description = "Account Common Report" company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company) journal_ids = fields.Many2many( comodel_name='account.journal', string='Journals', required=True, default=lambda self: self.env['account.journal'].search([('company_id', '=', self.company_id.id)]), domain="[('company_id', '=', company_id)]", ) date_from = fields.Date(string='Start Date') date_to = fields.Date(string='End Date') target_move = fields.Selection([('posted', 'All Posted Entries'), ('all', 'All Entries'), ], string='Target Moves', required=True, default='posted') @api.onchange('company_id') def _onchange_company_id(self): if self.company_id: self.journal_ids = self.env['account.journal'].search( [('company_id', '=', self.company_id.id)]) else: self.journal_ids = self.env['account.journal'].search([]) def _build_contexts(self, data): result = {} result['journal_ids'] = 'journal_ids' in data['form'] and data['form']['journal_ids'] or False result['state'] = 'target_move' in data['form'] and data['form']['target_move'] or '' result['date_from'] = data['form']['date_from'] or False result['date_to'] = data['form']['date_to'] or False result['strict_range'] = True if result['date_from'] else False result['company_id'] = data['form']['company_id'][0] or False return result def _print_report(self, data): raise NotImplementedError() def check_report(self): self.ensure_one() data = {} data['ids'] = self.env.context.get('active_ids', []) data['model'] = self.env.context.get('active_model', 'ir.ui.menu') data['form'] = self.read(['date_from', 'date_to', 'journal_ids', 'target_move', 'company_id'])[0] used_context = self._build_contexts(data) data['form']['used_context'] = dict(used_context, lang=get_lang(self.env).code) return self.with_context(discard_logo_check=True)._print_report(data)
45.092593
2,435
7,602
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from datetime import date, timedelta from odoo import _, api, fields, models from odoo.exceptions import ValidationError class FinancialYearOpeningWizard(models.TransientModel): _name = 'account.financial.year.op' _description = 'Opening Balance of Financial Year' company_id = fields.Many2one(comodel_name='res.company', required=True) opening_move_posted = fields.Boolean(string='Opening Move Posted', compute='_compute_opening_move_posted') opening_date = fields.Date(string='Opening Date', required=True, related='company_id.account_opening_date', help="Date from which the accounting is managed in Odoo. It is the date of the opening entry.", readonly=False) fiscalyear_last_day = fields.Integer(related="company_id.fiscalyear_last_day", required=True, readonly=False, help="The last day of the month will be used if the chosen day doesn't exist.") fiscalyear_last_month = fields.Selection(related="company_id.fiscalyear_last_month", readonly=False, required=True, help="The last day of the month will be used if the chosen day doesn't exist.") @api.depends('company_id.account_opening_move_id') def _compute_opening_move_posted(self): for record in self: record.opening_move_posted = record.company_id.opening_move_posted() @api.constrains('fiscalyear_last_day', 'fiscalyear_last_month') def _check_fiscalyear(self): # We try if the date exists in 2020, which is a leap year. # We do not define the constrain on res.company, since the recomputation of the related # fields is done one field at a time. for wiz in self: try: date(2020, int(wiz.fiscalyear_last_month), wiz.fiscalyear_last_day) except ValueError: raise ValidationError( _('Incorrect fiscal year date: day is out of range for month. Month: %s; Day: %s') % (wiz.fiscalyear_last_month, wiz.fiscalyear_last_day) ) def write(self, vals): # Amazing workaround: non-stored related fields on company are a BAD idea since the 3 fields # must follow the constraint '_check_fiscalyear_last_day'. The thing is, in case of related # fields, the inverse write is done one value at a time, and thus the constraint is verified # one value at a time... so it is likely to fail. for wiz in self: wiz.company_id.write({ 'fiscalyear_last_day': vals.get('fiscalyear_last_day') or wiz.company_id.fiscalyear_last_day, 'fiscalyear_last_month': vals.get('fiscalyear_last_month') or wiz.company_id.fiscalyear_last_month, 'account_opening_date': vals.get('opening_date') or wiz.company_id.account_opening_date, }) wiz.company_id.account_opening_move_id.write({ 'date': fields.Date.from_string(vals.get('opening_date') or wiz.company_id.account_opening_date) - timedelta(days=1), }) vals.pop('opening_date', None) vals.pop('fiscalyear_last_day', None) vals.pop('fiscalyear_last_month', None) return super().write(vals) def action_save_onboarding_fiscal_year(self): self.env.company.sudo().set_onboarding_step_done('account_setup_fy_data_state') class SetupBarBankConfigWizard(models.TransientModel): _inherits = {'res.partner.bank': 'res_partner_bank_id'} _name = 'account.setup.bank.manual.config' _description = 'Bank setup manual config' _check_company_auto = True res_partner_bank_id = fields.Many2one(comodel_name='res.partner.bank', ondelete='cascade', required=True) new_journal_name = fields.Char(default=lambda self: self.linked_journal_id.name, inverse='set_linked_journal_id', required=True, help='Will be used to name the Journal related to this bank account') linked_journal_id = fields.Many2one(string="Journal", comodel_name='account.journal', inverse='set_linked_journal_id', compute="_compute_linked_journal_id", check_company=True, domain="[('type','=','bank'), ('bank_account_id', '=', False), ('company_id', '=', company_id)]") bank_bic = fields.Char(related='bank_id.bic', readonly=False, string="Bic") num_journals_without_account = fields.Integer(default=lambda self: self._number_unlinked_journal()) def _number_unlinked_journal(self): return self.env['account.journal'].search([('type', '=', 'bank'), ('bank_account_id', '=', False), ('id', '!=', self.default_linked_journal_id())], count=True) @api.onchange('acc_number') def _onchange_acc_number(self): for record in self: record.new_journal_name = record.acc_number @api.model def create(self, vals): """ This wizard is only used to setup an account for the current active company, so we always inject the corresponding partner when creating the model. """ vals['partner_id'] = self.env.company.partner_id.id vals['new_journal_name'] = vals['acc_number'] # If no bank has been selected, but we have a bic, we are using it to find or create the bank if not vals['bank_id'] and vals['bank_bic']: vals['bank_id'] = self.env['res.bank'].search([('bic', '=', vals['bank_bic'])], limit=1).id \ or self.env['res.bank'].create({'name': vals['bank_bic'], 'bic': vals['bank_bic']}).id return super(SetupBarBankConfigWizard, self).create(vals) @api.onchange('linked_journal_id') def _onchange_new_journal_related_data(self): for record in self: if record.linked_journal_id: record.new_journal_name = record.linked_journal_id.name @api.depends('journal_id') # Despite its name, journal_id is actually a One2many field def _compute_linked_journal_id(self): for record in self: record.linked_journal_id = record.journal_id and record.journal_id[0] or record.default_linked_journal_id() def default_linked_journal_id(self): default = self.env['account.journal'].search([('type', '=', 'bank'), ('bank_account_id', '=', False)], limit=1) return default[:1].id def set_linked_journal_id(self): """ Called when saving the wizard. """ for record in self: selected_journal = record.linked_journal_id if not selected_journal: new_journal_code = self.env['account.journal'].get_next_bank_cash_default_code('bank', self.env.company) company = self.env.company selected_journal = self.env['account.journal'].create({ 'name': record.new_journal_name, 'code': new_journal_code, 'type': 'bank', 'company_id': company.id, 'bank_account_id': record.res_partner_bank_id.id, }) else: selected_journal.bank_account_id = record.res_partner_bank_id.id selected_journal.name = record.new_journal_name def validate(self): """ Called by the validation button of this wizard. Serves as an extension hook in account_bank_statement_import. """ self.linked_journal_id.mark_bank_setup_as_done_action()
52.791667
7,602
7,431
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import UserError from odoo.tools.date_utils import get_month, get_fiscal_year from odoo.tools.misc import format_date import re from collections import defaultdict import json class ReSequenceWizard(models.TransientModel): _name = 'account.resequence.wizard' _description = 'Remake the sequence of Journal Entries.' sequence_number_reset = fields.Char(compute='_compute_sequence_number_reset') first_date = fields.Date(help="Date (inclusive) from which the numbers are resequenced.") end_date = fields.Date(help="Date (inclusive) to which the numbers are resequenced. If not set, all Journal Entries up to the end of the period are resequenced.") first_name = fields.Char(compute="_compute_first_name", readonly=False, store=True, required=True, string="First New Sequence") ordering = fields.Selection([('keep', 'Keep current order'), ('date', 'Reorder by accounting date')], required=True, default='keep') move_ids = fields.Many2many('account.move') new_values = fields.Text(compute='_compute_new_values') preview_moves = fields.Text(compute='_compute_preview_moves') @api.model def default_get(self, fields_list): values = super(ReSequenceWizard, self).default_get(fields_list) if 'move_ids' not in fields_list: return values active_move_ids = self.env['account.move'] if self.env.context['active_model'] == 'account.move' and 'active_ids' in self.env.context: active_move_ids = self.env['account.move'].browse(self.env.context['active_ids']) if len(active_move_ids.journal_id) > 1: raise UserError(_('You can only resequence items from the same journal')) move_types = set(active_move_ids.mapped('move_type')) if ( active_move_ids.journal_id.refund_sequence and ('in_refund' in move_types or 'out_refund' in move_types) and len(move_types) > 1 ): raise UserError(_('The sequences of this journal are different for Invoices and Refunds but you selected some of both types.')) values['move_ids'] = [(6, 0, active_move_ids.ids)] return values @api.depends('first_name') def _compute_sequence_number_reset(self): for record in self: record.sequence_number_reset = record.move_ids[0]._deduce_sequence_number_reset(record.first_name) @api.depends('move_ids') def _compute_first_name(self): self.first_name = "" for record in self: if record.move_ids: record.first_name = min(record.move_ids._origin.mapped(lambda move: move.name or "")) @api.depends('new_values', 'ordering') def _compute_preview_moves(self): """Reduce the computed new_values to a smaller set to display in the preview.""" for record in self: new_values = sorted(json.loads(record.new_values).values(), key=lambda x: x['server-date'], reverse=True) changeLines = [] in_elipsis = 0 previous_line = None for i, line in enumerate(new_values): if i < 3 or i == len(new_values) - 1 or line['new_by_name'] != line['new_by_date'] \ or (self.sequence_number_reset == 'year' and line['server-date'][0:4] != previous_line['server-date'][0:4])\ or (self.sequence_number_reset == 'month' and line['server-date'][0:7] != previous_line['server-date'][0:7]): if in_elipsis: changeLines.append({'id': 'other_' + str(line['id']), 'current_name': _('... (%s other)', in_elipsis), 'new_by_name': '...', 'new_by_date': '...', 'date': '...'}) in_elipsis = 0 changeLines.append(line) else: in_elipsis += 1 previous_line = line record.preview_moves = json.dumps({ 'ordering': record.ordering, 'changeLines': changeLines, }) @api.depends('first_name', 'move_ids', 'sequence_number_reset') def _compute_new_values(self): """Compute the proposed new values. Sets a json string on new_values representing a dictionary thats maps account.move ids to a disctionay containing the name if we execute the action, and information relative to the preview widget. """ def _get_move_key(move_id): if self.sequence_number_reset == 'year': return move_id.date.year elif self.sequence_number_reset == 'month': return (move_id.date.year, move_id.date.month) return 'default' self.new_values = "{}" for record in self.filtered('first_name'): moves_by_period = defaultdict(lambda: record.env['account.move']) for move in record.move_ids._origin: # Sort the moves by period depending on the sequence number reset moves_by_period[_get_move_key(move)] += move seq_format, format_values = record.move_ids[0]._get_sequence_format_param(record.first_name) new_values = {} for j, period_recs in enumerate(moves_by_period.values()): # compute the new values period by period for move in period_recs: new_values[move.id] = { 'id': move.id, 'current_name': move.name, 'state': move.state, 'date': format_date(self.env, move.date), 'server-date': str(move.date), } new_name_list = [seq_format.format(**{ **format_values, 'year': period_recs[0].date.year % (10 ** format_values['year_length']), 'month': period_recs[0].date.month, 'seq': i + (format_values['seq'] if j == (len(moves_by_period)-1) else 1), }) for i in range(len(period_recs))] # For all the moves of this period, assign the name by increasing initial name for move, new_name in zip(period_recs.sorted(lambda m: (m.sequence_prefix, m.sequence_number)), new_name_list): new_values[move.id]['new_by_name'] = new_name # For all the moves of this period, assign the name by increasing date for move, new_name in zip(period_recs.sorted(lambda m: (m.date, m.name or "", m.id)), new_name_list): new_values[move.id]['new_by_date'] = new_name record.new_values = json.dumps(new_values) def resequence(self): new_values = json.loads(self.new_values) if self.move_ids.journal_id and self.move_ids.journal_id.restrict_mode_hash_table: if self.ordering == 'date': raise UserError(_('You can not reorder sequence by date when the journal is locked with a hash.')) self.env['account.move'].browse(int(k) for k in new_values.keys()).name = False for move_id in self.move_ids: if str(move_id.id) in new_values: if self.ordering == 'keep': move_id.name = new_values[str(move_id.id)]['new_by_name'] else: move_id.name = new_values[str(move_id.id)]['new_by_date']
51.604167
7,431
6,234
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _, Command import base64 from datetime import timedelta class AccountTourUploadBill(models.TransientModel): _name = 'account.tour.upload.bill' _description = 'Account tour upload bill' attachment_ids = fields.Many2many( comodel_name='ir.attachment', relation='account_tour_upload_bill_ir_attachments_rel', string='Attachments') selection = fields.Selection( selection=lambda self: self._selection_values(), default="sample" ) preview_invoice = fields.Html( compute="_compute_preview_invoice", string="Invoice Preview", translate=True, ) def _compute_preview_invoice(self): invoice_date = fields.Date.today() - timedelta(days=12) addr = [x for x in [ self.env.company.street, self.env.company.street2, ' '.join([x for x in [self.env.company.state_id.name, self.env.company.zip] if x]), self.env.company.country_id.name, ] if x] ref = 'INV/%s/0001' % invoice_date.strftime('%Y/%m') html = self.env.ref('account.bill_preview')._render({ 'company_name': self.env.company.name, 'company_street_address': addr, 'invoice_name': 'Invoice ' + ref, 'invoice_ref': ref, 'invoice_date': invoice_date, 'invoice_due_date': invoice_date + timedelta(days=30), }) for record in self: record.preview_invoice = html def _selection_values(self): journal_alias = self.env['account.journal'] \ .search([('type', '=', 'purchase'), ('company_id', '=', self.env.company.id)], limit=1) values = [('sample', _('Try a sample vendor bill')), ('upload', _('Upload your own bill'))] if journal_alias.alias_name and journal_alias.alias_domain: values.append(('email', _('Or send a bill to %s@%s', journal_alias.alias_name, journal_alias.alias_domain))) return values def _action_list_view_bill(self, bill_ids=[]): context = dict(self._context) context['default_move_type'] = 'in_invoice' return { 'name': _('Generated Documents'), 'domain': [('id', 'in', bill_ids)], 'view_mode': 'tree,form', 'res_model': 'account.move', 'views': [[False, "tree"], [False, "form"]], 'type': 'ir.actions.act_window', 'context': context } def apply(self): if self._context.get('active_model') == 'account.journal' and self._context.get('active_ids'): purchase_journal = self.env['account.journal'].browse(self._context['active_ids']) else: purchase_journal = self.env['account.journal'].search([('type', '=', 'purchase')], limit=1) if self.selection == 'upload': return purchase_journal.with_context(default_journal_id=purchase_journal.id, default_move_type='in_invoice').create_invoice_from_attachment(attachment_ids=self.attachment_ids.ids) elif self.selection == 'sample': bodies = self.env['ir.actions.report']._prepare_html(self.preview_invoice)[0] sample_pdf = self.env['ir.actions.report']._run_wkhtmltopdf(bodies) invoice_date = fields.Date.today() - timedelta(days=12) attachment = self.env['ir.attachment'].create({ 'type': 'binary', 'name': 'INV-%s-0001.pdf' % invoice_date.strftime('%Y-%m'), 'res_model': 'mail.compose.message', 'datas': base64.encodebytes(sample_pdf), }) partner = self.env['res.partner'].search([('name', '=', 'Deco Addict')], limit=1) if not partner: partner = self.env['res.partner'].create({ 'name': 'Deco Addict', 'is_company': True, }) bill = self.env['account.move'].create({ 'move_type': 'in_invoice', 'partner_id': partner.id, 'ref': 'INV/%s/0001' % invoice_date.strftime('%Y/%m'), 'invoice_date': invoice_date, 'invoice_date_due': invoice_date + timedelta(days=30), 'journal_id': purchase_journal.id, 'invoice_line_ids': [ Command.create({ 'name': "[FURN_8999] Three-Seat Sofa", 'quantity': 5, 'price_unit': 1500, }), Command.create({ 'name': "[FURN_8220] Four Person Desk", 'quantity': 5, 'price_unit': 2350, }) ], }) bill.with_context(no_new_invoice=True).message_post(attachment_ids=[attachment.id]) return self._action_list_view_bill(bill.ids) else: email_alias = '%s@%s' % (purchase_journal.alias_name, purchase_journal.alias_domain) new_wizard = self.env['account.tour.upload.bill.email.confirm'].create({'email_alias': email_alias}) view_id = self.env.ref('account.account_tour_upload_bill_email_confirm').id return { 'type': 'ir.actions.act_window', 'name': _('Confirm'), 'view_mode': 'form', 'res_model': 'account.tour.upload.bill.email.confirm', 'target': 'new', 'res_id': new_wizard.id, 'views': [[view_id, 'form']], } class AccountTourUploadBillEmailConfirm(models.TransientModel): _name = 'account.tour.upload.bill.email.confirm' _description = 'Account tour upload bill email confirm' email_alias = fields.Char(readonly=True) def apply(self): purchase_journal = self.env['account.journal'].search([('type', '=', 'purchase')], limit=1) bill_ids = self.env['account.move'].search([('journal_id', '=', purchase_journal.id)]).ids return self.env['account.tour.upload.bill']._action_list_view_bill(bill_ids)
43.291667
6,234
3,838
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models, fields, api class TaxAdjustments(models.TransientModel): _name = 'tax.adjustments.wizard' _description = 'Tax Adjustments Wizard' def _get_default_journal(self): return self.env['account.journal'].search([('type', '=', 'general')], limit=1).id def _domain_tax_report(self): fiscal_country_ids = self.env['account.fiscal.position'].search([('company_id', '=', self.env.company.id), ('foreign_vat', '!=', False)]).country_id.ids return [('tag_name', '!=', None), '|', ('report_id.country_id', '=', self.env.company.country_id.id), ('report_id.country_id', 'in', fiscal_country_ids)] reason = fields.Char(string='Justification', required=True) journal_id = fields.Many2one('account.journal', string='Journal', required=True, default=_get_default_journal, domain=[('type', '=', 'general')]) date = fields.Date(required=True, default=fields.Date.context_today) debit_account_id = fields.Many2one('account.account', string='Debit account', required=True, domain="[('deprecated', '=', False), ('is_off_balance', '=', False)]") credit_account_id = fields.Many2one('account.account', string='Credit account', required=True, domain="[('deprecated', '=', False), ('is_off_balance', '=', False)]") amount = fields.Monetary(currency_field='company_currency_id', required=True) adjustment_type = fields.Selection([('debit', 'Applied on debit journal item'), ('credit', 'Applied on credit journal item')], string="Adjustment Type", required=True) tax_report_line_id = fields.Many2one(string="Report Line", comodel_name='account.tax.report.line', required=True, help="The report line to make an adjustment for.", domain=_domain_tax_report) company_currency_id = fields.Many2one('res.currency', readonly=True, default=lambda x: x.env.company.currency_id) report_id = fields.Many2one(string="Report", related='tax_report_line_id.report_id') def create_move(self): move_line_vals = [] is_debit = self.adjustment_type == 'debit' sign_multiplier = (self.amount<0 and -1 or 1) * (self.adjustment_type == 'credit' and -1 or 1) filter_lambda = (sign_multiplier < 0) and (lambda x: x.tax_negate) or (lambda x: not x.tax_negate) adjustment_tag = self.tax_report_line_id.tag_ids.filtered(filter_lambda) # Vals for the amls corresponding to the ajustment tag move_line_vals.append((0, 0, { 'name': self.reason, 'debit': is_debit and abs(self.amount) or 0, 'credit': not is_debit and abs(self.amount) or 0, 'account_id': is_debit and self.debit_account_id.id or self.credit_account_id.id, 'tax_tag_ids': [(6, False, [adjustment_tag.id])], })) # Vals for the counterpart line move_line_vals.append((0, 0, { 'name': self.reason, 'debit': not is_debit and abs(self.amount) or 0, 'credit': is_debit and abs(self.amount) or 0, 'account_id': is_debit and self.credit_account_id.id or self.debit_account_id.id, })) # Create the move vals = { 'journal_id': self.journal_id.id, 'date': self.date, 'state': 'draft', 'line_ids': move_line_vals, } move = self.env['account.move'].create(vals) move._post() # Return an action opening the created move result = self.env['ir.actions.act_window']._for_xml_id('account.action_move_line_form') result['views'] = [(False, 'form')] result['res_id'] = move.id return result
54.056338
3,838
12,130
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from dateutil.relativedelta import relativedelta import json from odoo import models, fields, api, _, Command from odoo.tools import format_date from odoo.exceptions import UserError from odoo.tools import date_utils from odoo.tools.misc import formatLang class AccruedExpenseRevenue(models.TransientModel): _name = 'account.accrued.orders.wizard' _description = 'Accrued Orders Wizard' def _get_account_domain(self): if self.env.context.get('active_model') == 'purchase.order': return [('user_type_id', '=', self.env.ref('account.data_account_type_current_liabilities').id), ('company_id', '=', self._get_default_company())] else: return [('user_type_id', '=', self.env.ref('account.data_account_type_current_assets').id), ('company_id', '=', self._get_default_company())] def _get_default_company(self): if not self._context.get('active_model'): return orders = self.env[self._context['active_model']].browse(self._context['active_ids']) return orders and orders[0].company_id.id def _get_default_journal(self): return self.env['account.journal'].search([('company_id', '=', self.env.company.id), ('type', '=', 'general')], limit=1) def _get_default_date(self): return date_utils.get_month(fields.Date.context_today(self))[0] - relativedelta(days=1) company_id = fields.Many2one('res.company', default=_get_default_company) journal_id = fields.Many2one( comodel_name='account.journal', compute='_compute_journal_id', domain="[('type', '=', 'general'), ('company_id', '=', company_id)]", readonly=False, required=True, default=_get_default_journal, check_company=True, company_dependent=True, string='Journal', ) date = fields.Date(default=_get_default_date, required=True) reversal_date = fields.Date( compute="_compute_reversal_date", required=True, readonly=False, ) amount = fields.Monetary(string='Amount', help="Specify an arbitrary value that will be accrued on a \ default account for the entire order, regardless of the products on the different lines.") currency_id = fields.Many2one(related='company_id.currency_id', string='Company Currency', readonly=True, store=True, help='Utility field to express amount currency') account_id = fields.Many2one( comodel_name='account.account', required=True, string='Accrual Account', check_company=True, domain=_get_account_domain, ) preview_data = fields.Text(compute='_compute_preview_data') display_amount = fields.Boolean(compute='_compute_display_amount') @api.depends('date', 'amount') def _compute_display_amount(self): single_order = len(self._context['active_ids']) == 1 for record in self: preview_data = json.loads(self.preview_data) lines = preview_data.get('groups_vals', [])[0].get('items_vals', []) record.display_amount = record.amount or (single_order and not lines) @api.depends('date') def _compute_reversal_date(self): for record in self: if not record.reversal_date or record.reversal_date <= record.date: record.reversal_date = record.date + relativedelta(days=1) else: record.reversal_date = record.reversal_date @api.depends('company_id') def _compute_journal_id(self): journal = self.env['account.journal'].search( [('type', '=', 'general'), ('company_id', '=', self.company_id.id)], limit=1 ) for record in self: record.journal_id = journal @api.depends('date', 'journal_id', 'account_id', 'amount') def _compute_preview_data(self): for record in self: preview_vals = [self.env['account.move']._move_dict_to_preview_vals( record._compute_move_vals()[0], record.company_id.currency_id, )] preview_columns = [ {'field': 'account_id', 'label': _('Account')}, {'field': 'name', 'label': _('Label')}, {'field': 'debit', 'label': _('Debit'), 'class': 'text-right text-nowrap'}, {'field': 'credit', 'label': _('Credit'), 'class': 'text-right text-nowrap'}, ] record.preview_data = json.dumps({ 'groups_vals': preview_vals, 'options': { 'columns': preview_columns, }, }) def _compute_move_vals(self): def _get_aml_vals(order, balance, amount_currency, account_id, label=""): if not is_purchase: balance *= -1 amount_currency *= -1 values = { 'name': label, 'debit': balance if balance > 0 else 0.0, 'credit': balance * -1 if balance < 0 else 0.0, 'account_id': account_id, } if len(order) == 1 and self.company_id.currency_id != order.currency_id: values.update({ 'amount_currency': amount_currency, 'currency_id': order.currency_id.id, }) return values def _ellipsis(string, size): if len(string) > size: return string[0:size - 3] + '...' return string self.ensure_one() move_lines = [] is_purchase = self.env.context.get('active_model') == 'purchase.order' orders = self.env[self._context['active_model']].with_company(self.company_id).browse(self._context['active_ids']) if orders.filtered(lambda o: o.company_id != self.company_id): raise UserError(_('Entries can only be created for a single company at a time.')) orders_with_entries = [] fnames = [] total_balance = 0.0 for order in orders: if len(orders) == 1 and self.amount and order.order_line: total_balance = self.amount order_line = order.order_line[0] if is_purchase: account = order_line.product_id.property_account_expense_id or order_line.product_id.categ_id.property_account_expense_categ_id else: account = order_line.product_id.property_account_income_id or order_line.product_id.categ_id.property_account_income_categ_id values = _get_aml_vals(order, self.amount, 0, account.id, label=_('Manual entry')) move_lines.append(Command.create(values)) else: other_currency = self.company_id.currency_id != order.currency_id rate = order.currency_id._get_rates(self.company_id, self.date).get(order.currency_id.id) if other_currency else 1.0 # create a virtual order that will allow to recompute the qty delivered/received (and dependancies) # without actually writing anything on the real record (field is computed and stored) o = order.new(origin=order) if is_purchase: o.order_line.with_context(accrual_entry_date=self.date)._compute_qty_received() o.order_line.with_context(accrual_entry_date=self.date)._compute_qty_invoiced() else: o.order_line.with_context(accrual_entry_date=self.date)._compute_qty_delivered() o.order_line.with_context(accrual_entry_date=self.date)._compute_qty_invoiced() o.order_line.with_context(accrual_entry_date=self.date)._compute_untaxed_amount_invoiced() o.order_line.with_context(accrual_entry_date=self.date)._get_to_invoice_qty() lines = o.order_line.filtered( lambda l: l.display_type not in ['line_section', 'line_note'] and fields.Float.compare( l.qty_to_invoice, 0, precision_rounding=l.product_uom.rounding, ) == 1 ) for order_line in lines: if is_purchase: account = order_line.product_id.property_account_expense_id or order_line.product_id.categ_id.property_account_expense_categ_id amount = self.company_id.currency_id.round(order_line.qty_to_invoice * order_line.price_unit / rate) amount_currency = order_line.currency_id.round(order_line.qty_to_invoice * order_line.price_unit) fnames = ['qty_to_invoice', 'qty_received', 'qty_invoiced', 'invoice_lines'] label = _('%s - %s; %s Billed, %s Received at %s each', order.name, _ellipsis(order_line.name, 20), order_line.qty_invoiced, order_line.qty_received, formatLang(self.env, order_line.price_unit, currency_obj=order.currency_id)) else: account = order_line.product_id.property_account_income_id or order_line.product_id.categ_id.property_account_income_categ_id amount = self.company_id.currency_id.round(order_line.untaxed_amount_to_invoice / rate) amount_currency = order_line.untaxed_amount_to_invoice fnames = ['qty_to_invoice', 'untaxed_amount_to_invoice', 'qty_invoiced', 'qty_delivered', 'invoice_lines'] label = _('%s - %s; %s Invoiced, %s Delivered at %s each', order.name, _ellipsis(order_line.name, 20), order_line.qty_invoiced, order_line.qty_delivered, formatLang(self.env, order_line.price_unit, currency_obj=order.currency_id)) values = _get_aml_vals(order, amount, amount_currency, account.id, label=label) move_lines.append(Command.create(values)) total_balance += amount # must invalidate cache or o can mess when _create_invoices().action_post() of original order after this order.order_line.invalidate_cache(fnames=fnames) if not self.company_id.currency_id.is_zero(total_balance): # globalized counterpart for the whole orders selection values = _get_aml_vals(orders, -total_balance, 0.0, self.account_id.id, label=_('Accrued total')) move_lines.append(Command.create(values)) move_type = _('Expense') if is_purchase else _('Revenue') move_vals = { 'ref': _('Accrued %s entry as of %s', move_type, format_date(self.env, self.date)), 'journal_id': self.journal_id.id, 'date': self.date, 'line_ids': move_lines, } return move_vals, orders_with_entries def create_entries(self): self.ensure_one() if self.reversal_date <= self.date: raise UserError(_('Reversal date must be posterior to date.')) move_vals, orders_with_entries = self._compute_move_vals() move = self.env['account.move'].create(move_vals) move._post() reverse_move = move._reverse_moves(default_values_list=[{ 'ref': _('Reversal of: %s', move.ref), 'date': self.reversal_date, }]) reverse_move._post() for order in orders_with_entries: body = _('Accrual entry created on %s: <a href=# data-oe-model=account.move data-oe-id=%d>%s</a>.\ And its <a href=# data-oe-model=account.move data-oe-id=%d>reverse entry</a>.') % ( self.date, move.id, move.name, reverse_move.id, ) order.message_post(body=body) return { 'name': _('Accrual Moves'), 'type': 'ir.actions.act_window', 'res_model': 'account.move', 'view_mode': 'tree,form', 'domain': [('id', 'in', (move.id, reverse_move.id))], }
50.966387
12,130
1,628
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models, _ from odoo.exceptions import AccessError class Digest(models.Model): _inherit = 'digest.digest' kpi_account_total_revenue = fields.Boolean('Revenue') kpi_account_total_revenue_value = fields.Monetary(compute='_compute_kpi_account_total_revenue_value') def _compute_kpi_account_total_revenue_value(self): if not self.env.user.has_group('account.group_account_invoice'): raise AccessError(_("Do not have access, skip this data for user's digest email")) for record in self: start, end, company = record._get_kpi_compute_parameters() self._cr.execute(''' SELECT -SUM(line.balance) FROM account_move_line line JOIN account_move move ON move.id = line.move_id JOIN account_account account ON account.id = line.account_id WHERE line.company_id = %s AND line.date > %s::DATE AND line.date <= %s::DATE AND account.internal_group = 'income' AND move.state = 'posted' ''', [company.id, start, end]) query_res = self._cr.fetchone() record.kpi_account_total_revenue_value = query_res and query_res[0] or 0.0 def _compute_kpis_actions(self, company, user): res = super(Digest, self)._compute_kpis_actions(company, user) res['kpi_account_total_revenue'] = 'account.action_move_out_invoice_type&menu_id=%s' % self.env.ref('account.menu_finance').id return res
47.882353
1,628
1,406
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, _ from odoo.exceptions import UserError from odoo.release import series from odoo.tools import parse_version class IrModuleModule(models.Model): _inherit = "ir.module.module" def write(self, values): """ Warn the user about updating account if they try to install account_reports with an out of date module A change in stable added a dependency between account_reports and a template update in account. It could cause a traceback when updating account_reports, or account_accountant with an out of date account module. This will inform the user about what to do in such case, by asking him to update invoicing. """ mod_names = self.mapped('name') new_state = values.get('state') if new_state in ('to upgrade', 'to install') and 'account_reports' in mod_names and 'account' not in mod_names: invoicing_mod = self.env.ref('base.module_account') # Do not install or update account_report if account version is not >= 1.2, and we are not also installing/updating it if parse_version(invoicing_mod.latest_version) < parse_version(f'{series}.1.2') and invoicing_mod.state not in ('to install', 'to upgrade'): raise UserError(_("Please update the Invoicing module before continuing.")) return super().write(values)
54.076923
1,406
6,802
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, exceptions, fields, models, _ from odoo.exceptions import UserError, ValidationError from dateutil.relativedelta import relativedelta class AccountPaymentTerm(models.Model): _name = "account.payment.term" _description = "Payment Terms" _order = "sequence, id" def _default_line_ids(self): return [(0, 0, {'value': 'balance', 'value_amount': 0.0, 'sequence': 9, 'days': 0, 'option': 'day_after_invoice_date'})] name = fields.Char(string='Payment Terms', translate=True, required=True) active = fields.Boolean(default=True, help="If the active field is set to False, it will allow you to hide the payment terms without removing it.") note = fields.Html(string='Description on the Invoice', translate=True) line_ids = fields.One2many('account.payment.term.line', 'payment_id', string='Terms', copy=True, default=_default_line_ids) company_id = fields.Many2one('res.company', string='Company') sequence = fields.Integer(required=True, default=10) @api.constrains('line_ids') def _check_lines(self): for terms in self: payment_term_lines = terms.line_ids.sorted() if payment_term_lines and payment_term_lines[-1].value != 'balance': raise ValidationError(_('The last line of a Payment Term should have the Balance type.')) lines = terms.line_ids.filtered(lambda r: r.value == 'balance') if len(lines) > 1: raise ValidationError(_('A Payment Term should have only one line of type Balance.')) def compute(self, value, date_ref=False, currency=None): self.ensure_one() date_ref = date_ref or fields.Date.context_today(self) amount = value sign = value < 0 and -1 or 1 result = [] if not currency and self.env.context.get('currency_id'): currency = self.env['res.currency'].browse(self.env.context['currency_id']) elif not currency: currency = self.env.company.currency_id for line in self.line_ids: if line.value == 'fixed': amt = sign * currency.round(line.value_amount) elif line.value == 'percent': amt = currency.round(value * (line.value_amount / 100.0)) elif line.value == 'balance': amt = currency.round(amount) next_date = fields.Date.from_string(date_ref) if line.option == 'day_after_invoice_date': next_date += relativedelta(days=line.days) if line.day_of_the_month > 0: months_delta = (line.day_of_the_month < next_date.day) and 1 or 0 next_date += relativedelta(day=line.day_of_the_month, months=months_delta) elif line.option == 'after_invoice_month': next_first_date = next_date + relativedelta(day=1, months=1) # Getting 1st of next month next_date = next_first_date + relativedelta(days=line.days - 1) elif line.option == 'day_following_month': next_date += relativedelta(day=line.days, months=1) elif line.option == 'day_current_month': next_date += relativedelta(day=line.days, months=0) result.append((fields.Date.to_string(next_date), amt)) amount -= amt amount = sum(amt for _, amt in result) dist = currency.round(value - amount) if dist: last_date = result and result[-1][0] or fields.Date.context_today(self) result.append((last_date, dist)) return sorted(result, key=lambda k: k[0]) @api.ondelete(at_uninstall=False) def _unlink_except_referenced_terms(self): if self.env['account.move'].search([('invoice_payment_term_id', 'in', self.ids)]): raise UserError(_('You can not delete payment terms as other records still reference it. However, you can archive it.')) def unlink(self): for terms in self: self.env['ir.property'].sudo().search( [('value_reference', 'in', ['account.payment.term,%s'%payment_term.id for payment_term in terms])] ).unlink() return super(AccountPaymentTerm, self).unlink() class AccountPaymentTermLine(models.Model): _name = "account.payment.term.line" _description = "Payment Terms Line" _order = "sequence, id" value = fields.Selection([ ('balance', 'Balance'), ('percent', 'Percent'), ('fixed', 'Fixed Amount') ], string='Type', required=True, default='balance', help="Select here the kind of valuation related to this payment terms line.") value_amount = fields.Float(string='Value', digits='Payment Terms', help="For percent enter a ratio between 0-100.") days = fields.Integer(string='Number of Days', required=True, default=0) day_of_the_month = fields.Integer(string='Day of the month', help="Day of the month on which the invoice must come to its term. If zero or negative, this value will be ignored, and no specific day will be set. If greater than the last day of a month, this number will instead select the last day of this month.") option = fields.Selection([ ('day_after_invoice_date', "days after the invoice date"), ('after_invoice_month', "days after the end of the invoice month"), ('day_following_month', "of the following month"), ('day_current_month', "of the current month"), ], default='day_after_invoice_date', required=True, string='Options' ) payment_id = fields.Many2one('account.payment.term', string='Payment Terms', required=True, index=True, ondelete='cascade') sequence = fields.Integer(default=10, help="Gives the sequence order when displaying a list of payment terms lines.") @api.constrains('value', 'value_amount') def _check_percent(self): for term_line in self: if term_line.value == 'percent' and (term_line.value_amount < 0.0 or term_line.value_amount > 100.0): raise ValidationError(_('Percentages on the Payment Terms lines must be between 0 and 100.')) @api.constrains('days') def _check_days(self): for term_line in self: if term_line.option in ('day_following_month', 'day_current_month') and term_line.days <= 0: raise ValidationError(_("The day of the month used for this term must be strictly positive.")) elif term_line.days < 0: raise ValidationError(_("The number of days used for a payment term cannot be negative.")) @api.onchange('option') def _onchange_option(self): if self.option in ('day_current_month', 'day_following_month'): self.days = 0
53.140625
6,802
41,715
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.osv import expression from odoo.tools.float_utils import float_round as round from odoo.exceptions import UserError, ValidationError import math import logging TYPE_TAX_USE = [ ('sale', 'Sales'), ('purchase', 'Purchases'), ('none', 'None'), ] class AccountTaxGroup(models.Model): _name = 'account.tax.group' _description = 'Tax Group' _order = 'sequence asc' name = fields.Char(required=True, translate=True) sequence = fields.Integer(default=10) property_tax_payable_account_id = fields.Many2one('account.account', company_dependent=True, string='Tax current account (payable)') property_tax_receivable_account_id = fields.Many2one('account.account', company_dependent=True, string='Tax current account (receivable)') property_advance_tax_payment_account_id = fields.Many2one('account.account', company_dependent=True, string='Advance Tax payment account') country_id = fields.Many2one(string="Country", comodel_name='res.country', help="The country for which this tax group is applicable.") preceding_subtotal = fields.Char( string="Preceding Subtotal", help="If set, this value will be used on documents as the label of a subtotal excluding this tax group before displaying it. " \ "If not set, the tax group will be displayed after the 'Untaxed amount' subtotal.", ) @api.model def _check_misconfigured_tax_groups(self, company, countries): """ Searches the tax groups used on the taxes from company in countries that don't have at least a tax payable account, a tax receivable account or an advance tax payment account. :return: A boolean telling whether or not there are misconfigured groups for any of these countries, in this company """ # This cannot be refactored to check for misconfigured groups instead # because of an ORM limitation with search on property fields: # searching on property = False also returns the properties using the default value, # even if it's non-empty. # (introduced here https://github.com/odoo/odoo/pull/6044) all_configured_groups_ids = self.with_company(company)._search([ ('property_tax_payable_account_id', '!=', False), ('property_tax_receivable_account_id', '!=', False), ]) return bool(self.env['account.tax'].search([ ('company_id', '=', company.id), ('tax_group_id', 'not in', all_configured_groups_ids), ('country_id', 'in', countries.ids), ], limit=1)) class AccountTax(models.Model): _name = 'account.tax' _description = 'Tax' _order = 'sequence,id' _check_company_auto = True @api.model def _default_tax_group(self): return self.env.ref('account.tax_group_taxes') name = fields.Char(string='Tax Name', required=True) type_tax_use = fields.Selection(TYPE_TAX_USE, string='Tax Type', required=True, default="sale", help="Determines where the tax is selectable. Note : 'None' means a tax can't be used by itself, however it can still be used in a group. 'adjustment' is used to perform tax adjustment.") tax_scope = fields.Selection([('service', 'Services'), ('consu', 'Goods')], string="Tax Scope", help="Restrict the use of taxes to a type of product.") amount_type = fields.Selection(default='percent', string="Tax Computation", required=True, selection=[('group', 'Group of Taxes'), ('fixed', 'Fixed'), ('percent', 'Percentage of Price'), ('division', 'Percentage of Price Tax Included')], help=""" - Group of Taxes: The tax is a set of sub taxes. - Fixed: The tax amount stays the same whatever the price. - Percentage of Price: The tax amount is a % of the price: e.g 100 * (1 + 10%) = 110 (not price included) e.g 110 / (1 + 10%) = 100 (price included) - Percentage of Price Tax Included: The tax amount is a division of the price: e.g 180 / (1 - 10%) = 200 (not price included) e.g 200 * (1 - 10%) = 180 (price included) """) active = fields.Boolean(default=True, help="Set active to false to hide the tax without removing it.") company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company) children_tax_ids = fields.Many2many('account.tax', 'account_tax_filiation_rel', 'parent_tax', 'child_tax', check_company=True, string='Children Taxes') sequence = fields.Integer(required=True, default=1, help="The sequence field is used to define order in which the tax lines are applied.") amount = fields.Float(required=True, digits=(16, 4), default=0.0) description = fields.Char(string='Label on Invoices') price_include = fields.Boolean(string='Included in Price', default=False, help="Check this if the price you use on the product and invoices includes this tax.") include_base_amount = fields.Boolean(string='Affect Base of Subsequent Taxes', default=False, help="If set, taxes with a higher sequence than this one will be affected by it, provided they accept it.") is_base_affected = fields.Boolean( string="Base Affected by Previous Taxes", default=True, help="If set, taxes with a lower sequence might affect this one, provided they try to do it.") analytic = fields.Boolean(string="Include in Analytic Cost", help="If set, the amount computed by this tax will be assigned to the same analytic account as the invoice line (if any)") tax_group_id = fields.Many2one('account.tax.group', string="Tax Group", default=_default_tax_group, required=True, domain="[('country_id', 'in', (country_id, False))]") # Technical field to make the 'tax_exigibility' field invisible if the same named field is set to false in 'res.company' model hide_tax_exigibility = fields.Boolean(string='Hide Use Cash Basis Option', related='company_id.tax_exigibility', readonly=True) tax_exigibility = fields.Selection( [('on_invoice', 'Based on Invoice'), ('on_payment', 'Based on Payment'), ], string='Tax Exigibility', default='on_invoice', help="Based on Invoice: the tax is due as soon as the invoice is validated.\n" "Based on Payment: the tax is due as soon as the payment of the invoice is received.") cash_basis_transition_account_id = fields.Many2one(string="Cash Basis Transition Account", check_company=True, domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", comodel_name='account.account', help="Account used to transition the tax amount for cash basis taxes. It will contain the tax amount as long as the original invoice has not been reconciled ; at reconciliation, this amount cancelled on this account and put on the regular tax account.") invoice_repartition_line_ids = fields.One2many(string="Distribution for Invoices", comodel_name="account.tax.repartition.line", inverse_name="invoice_tax_id", copy=True, help="Distribution when the tax is used on an invoice") refund_repartition_line_ids = fields.One2many(string="Distribution for Refund Invoices", comodel_name="account.tax.repartition.line", inverse_name="refund_tax_id", copy=True, help="Distribution when the tax is used on a refund") country_id = fields.Many2one(string="Country", comodel_name='res.country', required=True, help="The country for which this tax is applicable.") country_code = fields.Char(related='country_id.code', readonly=True) _sql_constraints = [ ('name_company_uniq', 'unique(name, company_id, type_tax_use, tax_scope)', 'Tax names must be unique !'), ] @api.constrains('tax_group_id') def validate_tax_group_id(self): for record in self: if record.tax_group_id.country_id and record.tax_group_id.country_id != record.country_id: raise ValidationError(_("The tax group must have the same country_id as the tax using it.")) @api.model def default_get(self, fields_list): # company_id is added so that we are sure to fetch a default value from it to use in repartition lines, below rslt = super(AccountTax, self).default_get(fields_list + ['company_id']) company_id = rslt.get('company_id') company = self.env['res.company'].browse(company_id) if 'country_id' in fields_list: rslt['country_id'] = company.account_fiscal_country_id.id if 'refund_repartition_line_ids' in fields_list: rslt['refund_repartition_line_ids'] = [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0, 'tag_ids': [], 'company_id': company_id}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 100.0, 'tag_ids': [], 'company_id': company_id}), ] if 'invoice_repartition_line_ids' in fields_list: rslt['invoice_repartition_line_ids'] = [ (0, 0, {'repartition_type': 'base', 'factor_percent': 100.0, 'tag_ids': [], 'company_id': company_id}), (0, 0, {'repartition_type': 'tax', 'factor_percent': 100.0, 'tag_ids': [], 'company_id': company_id}), ] return rslt def _check_repartition_lines(self, lines): self.ensure_one() base_line = lines.filtered(lambda x: x.repartition_type == 'base') if len(base_line) != 1: raise ValidationError(_("Invoice and credit note distribution should each contain exactly one line for the base.")) @api.constrains('invoice_repartition_line_ids', 'refund_repartition_line_ids') def _validate_repartition_lines(self): for record in self: # if the tax is an aggregation of its sub-taxes (group) it can have no repartition lines if record.amount_type == 'group' and \ not record.invoice_repartition_line_ids and \ not record.refund_repartition_line_ids: continue invoice_repartition_line_ids = record.invoice_repartition_line_ids.sorted() refund_repartition_line_ids = record.refund_repartition_line_ids.sorted() record._check_repartition_lines(invoice_repartition_line_ids) record._check_repartition_lines(refund_repartition_line_ids) if len(invoice_repartition_line_ids) != len(refund_repartition_line_ids): raise ValidationError(_("Invoice and credit note distribution should have the same number of lines.")) if not invoice_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax') or \ not refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'tax'): raise ValidationError(_("Invoice and credit note repartition should have at least one tax repartition line.")) index = 0 while index < len(invoice_repartition_line_ids): inv_rep_ln = invoice_repartition_line_ids[index] ref_rep_ln = refund_repartition_line_ids[index] if inv_rep_ln.repartition_type != ref_rep_ln.repartition_type or inv_rep_ln.factor_percent != ref_rep_ln.factor_percent: raise ValidationError(_("Invoice and credit note distribution should match (same percentages, in the same order).")) index += 1 @api.constrains('children_tax_ids', 'type_tax_use') def _check_children_scope(self): for tax in self: if not tax._check_m2m_recursion('children_tax_ids'): raise ValidationError(_("Recursion found for tax '%s'.") % (tax.name,)) if any(child.type_tax_use not in ('none', tax.type_tax_use) or child.tax_scope != tax.tax_scope for child in tax.children_tax_ids): raise ValidationError(_('The application scope of taxes in a group must be either the same as the group or left empty.')) @api.constrains('company_id') def _check_company_consistency(self): if not self: return self.flush(['company_id']) self._cr.execute(''' SELECT line.id FROM account_move_line line JOIN account_tax tax ON tax.id = line.tax_line_id WHERE line.tax_line_id IN %s AND line.company_id != tax.company_id UNION ALL SELECT line.id FROM account_move_line_account_tax_rel tax_rel JOIN account_tax tax ON tax.id = tax_rel.account_tax_id JOIN account_move_line line ON line.id = tax_rel.account_move_line_id WHERE tax_rel.account_tax_id IN %s AND line.company_id != tax.company_id ''', [tuple(self.ids)] * 2) if self._cr.fetchone(): raise UserError(_("You can't change the company of your tax since there are some journal items linked to it.")) @api.returns('self', lambda value: value.id) def copy(self, default=None): default = dict(default or {}) if 'name' not in default: default['name'] = _("%s (Copy)") % self.name return super(AccountTax, self).copy(default=default) def name_get(self): name_list = [] type_tax_use = dict(self._fields['type_tax_use']._description_selection(self.env)) tax_scope = dict(self._fields['tax_scope']._description_selection(self.env)) for record in self: name = record.name if self._context.get('append_type_to_tax_name'): name += ' (%s)' % type_tax_use.get(record.type_tax_use) if record.tax_scope: name += ' (%s)' % tax_scope.get(record.tax_scope) name_list += [(record.id, name)] return name_list @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): """ Returns a list of tuples containing id, name, as internally it is called {def name_get} result format: {[(id, name), (id, name), ...]} """ args = args or [] if operator == 'ilike' and not (name or '').strip(): domain = [] else: connector = '&' if operator in expression.NEGATIVE_TERM_OPERATORS else '|' domain = [connector, ('description', operator, name), ('name', operator, name)] return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid) @api.model def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None): context = self._context or {} if context.get('move_type'): if context.get('move_type') in ('out_invoice', 'out_refund'): args += [('type_tax_use', '=', 'sale')] elif context.get('move_type') in ('in_invoice', 'in_refund'): args += [('type_tax_use', '=', 'purchase')] if context.get('journal_id'): journal = self.env['account.journal'].browse(context.get('journal_id')) if journal.type in ('sale', 'purchase'): args += [('type_tax_use', '=', journal.type)] return super(AccountTax, self)._search(args, offset, limit, order, count=count, access_rights_uid=access_rights_uid) @api.onchange('amount') def onchange_amount(self): if self.amount_type in ('percent', 'division') and self.amount != 0.0 and not self.description: self.description = "{0:.4g}%".format(self.amount) @api.onchange('amount_type') def onchange_amount_type(self): if self.amount_type != 'group': self.children_tax_ids = [(5,)] if self.amount_type == 'group': self.description = None @api.onchange('price_include') def onchange_price_include(self): if self.price_include: self.include_base_amount = True def _compute_amount(self, base_amount, price_unit, quantity=1.0, product=None, partner=None): """ Returns the amount of a single tax. base_amount is the actual amount on which the tax is applied, which is price_unit * quantity eventually affected by previous taxes (if tax is include_base_amount XOR price_include) """ self.ensure_one() if self.amount_type == 'fixed': # Use copysign to take into account the sign of the base amount which includes the sign # of the quantity and the sign of the price_unit # Amount is the fixed price for the tax, it can be negative # Base amount included the sign of the quantity and the sign of the unit price and when # a product is returned, it can be done either by changing the sign of quantity or by changing the # sign of the price unit. # When the price unit is equal to 0, the sign of the quantity is absorbed in base_amount then # a "else" case is needed. if base_amount: return math.copysign(quantity, base_amount) * self.amount else: return quantity * self.amount price_include = self._context.get('force_price_include', self.price_include) # base * (1 + tax_amount) = new_base if self.amount_type == 'percent' and not price_include: return base_amount * self.amount / 100 # <=> new_base = base / (1 + tax_amount) if self.amount_type == 'percent' and price_include: return base_amount - (base_amount / (1 + self.amount / 100)) # base / (1 - tax_amount) = new_base if self.amount_type == 'division' and not price_include: return base_amount / (1 - self.amount / 100) - base_amount if (1 - self.amount / 100) else 0.0 # <=> new_base * (1 - tax_amount) = base if self.amount_type == 'division' and price_include: return base_amount - (base_amount * (self.amount / 100)) # default value for custom amount_type return 0.0 def json_friendly_compute_all(self, price_unit, currency_id=None, quantity=1.0, product_id=None, partner_id=None, is_refund=False, include_caba_tags=False): """ Called by the reconciliation to compute taxes on writeoff during bank reconciliation """ if currency_id: currency_id = self.env['res.currency'].browse(currency_id) if product_id: product_id = self.env['product.product'].browse(product_id) if partner_id: partner_id = self.env['res.partner'].browse(partner_id) # We first need to find out whether this tax computation is made for a refund tax_type = self and self[0].type_tax_use if self._context.get('manual_reco_widget'): is_refund = is_refund or (tax_type == 'sale' and price_unit > 0) or (tax_type == 'purchase' and price_unit < 0) else: is_refund = is_refund or (tax_type == 'sale' and price_unit < 0) or (tax_type == 'purchase' and price_unit > 0) rslt = self.with_context(caba_no_transition_account=True)\ .compute_all(price_unit, currency=currency_id, quantity=quantity, product=product_id, partner=partner_id, is_refund=is_refund, include_caba_tags=include_caba_tags) return rslt def flatten_taxes_hierarchy(self, create_map=False): # Flattens the taxes contained in this recordset, returning all the # children at the bottom of the hierarchy, in a recordset, ordered by sequence. # Eg. considering letters as taxes and alphabetic order as sequence : # [G, B([A, D, F]), E, C] will be computed as [A, D, F, C, E, G] # If create_map is True, an additional value is returned, a dictionary # mapping each child tax to its parent group all_taxes = self.env['account.tax'] groups_map = {} for tax in self.sorted(key=lambda r: r.sequence): if tax.amount_type == 'group': flattened_children = tax.children_tax_ids.flatten_taxes_hierarchy() all_taxes += flattened_children for flat_child in flattened_children: groups_map[flat_child] = tax else: all_taxes += tax if create_map: return all_taxes, groups_map return all_taxes def get_tax_tags(self, is_refund, repartition_type): rep_lines = self.mapped(is_refund and 'refund_repartition_line_ids' or 'invoice_repartition_line_ids') return rep_lines.filtered(lambda x: x.repartition_type == repartition_type).mapped('tag_ids') def compute_all(self, price_unit, currency=None, quantity=1.0, product=None, partner=None, is_refund=False, handle_price_include=True, include_caba_tags=False): """ Returns all information required to apply taxes (in self + their children in case of a tax group). We consider the sequence of the parent for group of taxes. Eg. considering letters as taxes and alphabetic order as sequence : [G, B([A, D, F]), E, C] will be computed as [A, D, F, C, E, G] 'handle_price_include' is used when we need to ignore all tax included in price. If False, it means the amount passed to this method will be considered as the base of all computations. RETURN: { 'total_excluded': 0.0, # Total without taxes 'total_included': 0.0, # Total with taxes 'total_void' : 0.0, # Total with those taxes, that don't have an account set 'taxes': [{ # One dict for each tax in self and their children 'id': int, 'name': str, 'amount': float, 'sequence': int, 'account_id': int, 'refund_account_id': int, 'analytic': boolean, }], } """ if not self: company = self.env.company else: company = self[0].company_id # 1) Flatten the taxes. taxes, groups_map = self.flatten_taxes_hierarchy(create_map=True) # 2) Deal with the rounding methods if not currency: currency = company.currency_id # By default, for each tax, tax amount will first be computed # and rounded at the 'Account' decimal precision for each # PO/SO/invoice line and then these rounded amounts will be # summed, leading to the total amount for that tax. But, if the # company has tax_calculation_rounding_method = round_globally, # we still follow the same method, but we use a much larger # precision when we round the tax amount for each line (we use # the 'Account' decimal precision + 5), and that way it's like # rounding after the sum of the tax amounts of each line prec = currency.rounding # In some cases, it is necessary to force/prevent the rounding of the tax and the total # amounts. For example, in SO/PO line, we don't want to round the price unit at the # precision of the currency. # The context key 'round' allows to force the standard behavior. round_tax = False if company.tax_calculation_rounding_method == 'round_globally' else True if 'round' in self.env.context: round_tax = bool(self.env.context['round']) if not round_tax: prec *= 1e-5 # 3) Iterate the taxes in the reversed sequence order to retrieve the initial base of the computation. # tax | base | amount | # /\ ---------------------------- # || tax_1 | XXXX | | <- we are looking for that, it's the total_excluded # || tax_2 | .. | | # || tax_3 | .. | | # || ... | .. | .. | # ---------------------------- def recompute_base(base_amount, fixed_amount, percent_amount, division_amount): # Recompute the new base amount based on included fixed/percent amounts and the current base amount. # Example: # tax | amount | type | price_include | # ----------------------------------------------- # tax_1 | 10% | percent | t # tax_2 | 15 | fix | t # tax_3 | 20% | percent | t # tax_4 | 10% | division | t # ----------------------------------------------- # if base_amount = 145, the new base is computed as: # (145 - 15) / (1.0 + 30%) * 90% = 130 / 1.3 * 90% = 90 return (base_amount - fixed_amount) / (1.0 + percent_amount / 100.0) * (100 - division_amount) / 100 # The first/last base must absolutely be rounded to work in round globally. # Indeed, the sum of all taxes ('taxes' key in the result dictionary) must be strictly equals to # 'price_included' - 'price_excluded' whatever the rounding method. # # Example using the global rounding without any decimals: # Suppose two invoice lines: 27000 and 10920, both having a 19% price included tax. # # Line 1 Line 2 # ----------------------------------------------------------------------- # total_included: 27000 10920 # tax: 27000 / 1.19 = 4310.924 10920 / 1.19 = 1743.529 # total_excluded: 22689.076 9176.471 # # If the rounding of the total_excluded isn't made at the end, it could lead to some rounding issues # when summing the tax amounts, e.g. on invoices. # In that case: # - amount_untaxed will be 22689 + 9176 = 31865 # - amount_tax will be 4310.924 + 1743.529 = 6054.453 ~ 6054 # - amount_total will be 31865 + 6054 = 37919 != 37920 = 27000 + 10920 # # By performing a rounding at the end to compute the price_excluded amount, the amount_tax will be strictly # equals to 'price_included' - 'price_excluded' after rounding and then: # Line 1: sum(taxes) = 27000 - 22689 = 4311 # Line 2: sum(taxes) = 10920 - 2176 = 8744 # amount_tax = 4311 + 8744 = 13055 # amount_total = 31865 + 13055 = 37920 base = currency.round(price_unit * quantity) # For the computation of move lines, we could have a negative base value. # In this case, compute all with positive values and negate them at the end. sign = 1 if currency.is_zero(base): sign = self._context.get('force_sign', 1) elif base < 0: sign = -1 if base < 0: base = -base # Store the totals to reach when using price_include taxes (only the last price included in row) total_included_checkpoints = {} i = len(taxes) - 1 store_included_tax_total = True # Keep track of the accumulated included fixed/percent amount. incl_fixed_amount = incl_percent_amount = incl_division_amount = 0 # Store the tax amounts we compute while searching for the total_excluded cached_tax_amounts = {} if handle_price_include: for tax in reversed(taxes): tax_repartition_lines = ( is_refund and tax.refund_repartition_line_ids or tax.invoice_repartition_line_ids ).filtered(lambda x: x.repartition_type == "tax") sum_repartition_factor = sum(tax_repartition_lines.mapped("factor")) if tax.include_base_amount: base = recompute_base(base, incl_fixed_amount, incl_percent_amount, incl_division_amount) incl_fixed_amount = incl_percent_amount = incl_division_amount = 0 store_included_tax_total = True if tax.price_include or self._context.get('force_price_include'): if tax.amount_type == 'percent': incl_percent_amount += tax.amount * sum_repartition_factor elif tax.amount_type == 'division': incl_division_amount += tax.amount * sum_repartition_factor elif tax.amount_type == 'fixed': incl_fixed_amount += abs(quantity) * tax.amount * sum_repartition_factor else: # tax.amount_type == other (python) tax_amount = tax._compute_amount(base, sign * price_unit, quantity, product, partner) * sum_repartition_factor incl_fixed_amount += tax_amount # Avoid unecessary re-computation cached_tax_amounts[i] = tax_amount # In case of a zero tax, do not store the base amount since the tax amount will # be zero anyway. Group and Python taxes have an amount of zero, so do not take # them into account. if store_included_tax_total and ( tax.amount or tax.amount_type not in ("percent", "division", "fixed") ): total_included_checkpoints[i] = base store_included_tax_total = False i -= 1 total_excluded = currency.round(recompute_base(base, incl_fixed_amount, incl_percent_amount, incl_division_amount)) # 4) Iterate the taxes in the sequence order to compute missing tax amounts. # Start the computation of accumulated amounts at the total_excluded value. base = total_included = total_void = total_excluded # Flag indicating the checkpoint used in price_include to avoid rounding issue must be skipped since the base # amount has changed because we are currently mixing price-included and price-excluded include_base_amount # taxes. skip_checkpoint = False # Get product tags, account.account.tag objects that need to be injected in all # the tax_tag_ids of all the move lines created by the compute all for this product. product_tag_ids = product.account_tag_ids.ids if product else [] taxes_vals = [] i = 0 cumulated_tax_included_amount = 0 for tax in taxes: price_include = self._context.get('force_price_include', tax.price_include) if price_include or tax.is_base_affected: tax_base_amount = base else: tax_base_amount = total_excluded tax_repartition_lines = (is_refund and tax.refund_repartition_line_ids or tax.invoice_repartition_line_ids).filtered(lambda x: x.repartition_type == 'tax') sum_repartition_factor = sum(tax_repartition_lines.mapped('factor')) #compute the tax_amount if not skip_checkpoint and price_include and total_included_checkpoints.get(i) is not None and sum_repartition_factor != 0: # We know the total to reach for that tax, so we make a substraction to avoid any rounding issues tax_amount = total_included_checkpoints[i] - (base + cumulated_tax_included_amount) cumulated_tax_included_amount = 0 else: tax_amount = tax.with_context(force_price_include=False)._compute_amount( tax_base_amount, sign * price_unit, quantity, product, partner) # Round the tax_amount multiplied by the computed repartition lines factor. tax_amount = round(tax_amount, precision_rounding=prec) factorized_tax_amount = round(tax_amount * sum_repartition_factor, precision_rounding=prec) if price_include and total_included_checkpoints.get(i) is None: cumulated_tax_included_amount += factorized_tax_amount # If the tax affects the base of subsequent taxes, its tax move lines must # receive the base tags and tag_ids of these taxes, so that the tax report computes # the right total subsequent_taxes = self.env['account.tax'] subsequent_tags = self.env['account.account.tag'] if tax.include_base_amount: subsequent_taxes = taxes[i+1:].filtered('is_base_affected') taxes_for_subsequent_tags = subsequent_taxes if not include_caba_tags: taxes_for_subsequent_tags = subsequent_taxes.filtered(lambda x: x.tax_exigibility != 'on_payment') subsequent_tags = taxes_for_subsequent_tags.get_tax_tags(is_refund, 'base') # Compute the tax line amounts by multiplying each factor with the tax amount. # Then, spread the tax rounding to ensure the consistency of each line independently with the factorized # amount. E.g: # # Suppose a tax having 4 x 50% repartition line applied on a tax amount of 0.03 with 2 decimal places. # The factorized_tax_amount will be 0.06 (200% x 0.03). However, each line taken independently will compute # 50% * 0.03 = 0.01 with rounding. It means there is 0.06 - 0.04 = 0.02 as total_rounding_error to dispatch # in lines as 2 x 0.01. repartition_line_amounts = [round(tax_amount * line.factor, precision_rounding=prec) for line in tax_repartition_lines] total_rounding_error = round(factorized_tax_amount - sum(repartition_line_amounts), precision_rounding=prec) nber_rounding_steps = int(abs(total_rounding_error / currency.rounding)) rounding_error = round(nber_rounding_steps and total_rounding_error / nber_rounding_steps or 0.0, precision_rounding=prec) for repartition_line, line_amount in zip(tax_repartition_lines, repartition_line_amounts): if nber_rounding_steps: line_amount += rounding_error nber_rounding_steps -= 1 if not include_caba_tags and tax.tax_exigibility == 'on_payment': repartition_line_tags = self.env['account.account.tag'] else: repartition_line_tags = repartition_line.tag_ids taxes_vals.append({ 'id': tax.id, 'name': partner and tax.with_context(lang=partner.lang).name or tax.name, 'amount': sign * line_amount, 'base': round(sign * tax_base_amount, precision_rounding=prec), 'sequence': tax.sequence, 'account_id': tax.cash_basis_transition_account_id.id if tax.tax_exigibility == 'on_payment' \ and not self._context.get('caba_no_transition_account')\ else repartition_line.account_id.id, 'analytic': tax.analytic, 'price_include': price_include, 'tax_exigibility': tax.tax_exigibility, 'tax_repartition_line_id': repartition_line.id, 'group': groups_map.get(tax), 'tag_ids': (repartition_line_tags + subsequent_tags).ids + product_tag_ids, 'tax_ids': subsequent_taxes.ids, }) if not repartition_line.account_id: total_void += line_amount # Affect subsequent taxes if tax.include_base_amount: base += factorized_tax_amount if not price_include: skip_checkpoint = True total_included += factorized_tax_amount i += 1 base_taxes_for_tags = taxes if not include_caba_tags: base_taxes_for_tags = base_taxes_for_tags.filtered(lambda x: x.tax_exigibility != 'on_payment') base_rep_lines = base_taxes_for_tags.mapped(is_refund and 'refund_repartition_line_ids' or 'invoice_repartition_line_ids').filtered(lambda x: x.repartition_type == 'base') return { 'base_tags': base_rep_lines.tag_ids.ids + product_tag_ids, 'taxes': taxes_vals, 'total_excluded': sign * total_excluded, 'total_included': sign * currency.round(total_included), 'total_void': sign * currency.round(total_void), } @api.model def _fix_tax_included_price(self, price, prod_taxes, line_taxes): """Subtract tax amount from price when corresponding "price included" taxes do not apply""" # FIXME get currency in param? prod_taxes = prod_taxes._origin line_taxes = line_taxes._origin incl_tax = prod_taxes.filtered(lambda tax: tax not in line_taxes and tax.price_include) if incl_tax: return incl_tax.compute_all(price)['total_excluded'] return price @api.model def _fix_tax_included_price_company(self, price, prod_taxes, line_taxes, company_id): if company_id: #To keep the same behavior as in _compute_tax_id prod_taxes = prod_taxes.filtered(lambda tax: tax.company_id == company_id) line_taxes = line_taxes.filtered(lambda tax: tax.company_id == company_id) return self._fix_tax_included_price(price, prod_taxes, line_taxes) class AccountTaxRepartitionLine(models.Model): _name = "account.tax.repartition.line" _description = "Tax Repartition Line" _order = 'sequence, repartition_type, id' _check_company_auto = True factor_percent = fields.Float(string="%", required=True, help="Factor to apply on the account move lines generated from this distribution line, in percents") factor = fields.Float(string="Factor Ratio", compute="_compute_factor", help="Factor to apply on the account move lines generated from this distribution line") repartition_type = fields.Selection(string="Based On", selection=[('base', 'Base'), ('tax', 'of tax')], required=True, default='tax', help="Base on which the factor will be applied.") account_id = fields.Many2one(string="Account", comodel_name='account.account', domain="[('deprecated', '=', False), ('company_id', '=', company_id), ('internal_type', 'not in', ('receivable', 'payable'))]", check_company=True, help="Account on which to post the tax amount") tag_ids = fields.Many2many(string="Tax Grids", comodel_name='account.account.tag', domain=[('applicability', '=', 'taxes')], copy=True) invoice_tax_id = fields.Many2one(comodel_name='account.tax', ondelete='cascade', check_company=True, help="The tax set to apply this distribution on invoices. Mutually exclusive with refund_tax_id") refund_tax_id = fields.Many2one(comodel_name='account.tax', ondelete='cascade', check_company=True, help="The tax set to apply this distribution on refund invoices. Mutually exclusive with invoice_tax_id") tax_id = fields.Many2one(comodel_name='account.tax', compute='_compute_tax_id') company_id = fields.Many2one(string="Company", comodel_name='res.company', compute="_compute_company", store=True, help="The company this distribution line belongs to.") sequence = fields.Integer(string="Sequence", default=1, help="The order in which distribution lines are displayed and matched. For refunds to work properly, invoice distribution lines should be arranged in the same order as the credit note distribution lines they correspond to.") use_in_tax_closing = fields.Boolean(string="Tax Closing Entry", default=True) @api.onchange('account_id', 'repartition_type') def _on_change_account_id(self): if not self.account_id or self.repartition_type == 'base': self.use_in_tax_closing = False else: self.use_in_tax_closing = self.account_id.internal_group not in ('income', 'expense') @api.constrains('invoice_tax_id', 'refund_tax_id') def validate_tax_template_link(self): for record in self: if record.invoice_tax_id and record.refund_tax_id: raise ValidationError(_("Tax distribution lines should apply to either invoices or refunds, not both at the same time. invoice_tax_id and refund_tax_id should not be set together.")) @api.constrains('invoice_tax_id', 'refund_tax_id', 'tag_ids') def validate_tags_country(self): for record in self: if record.tag_ids.country_id and record.tax_id.country_id != record.tag_ids.country_id: raise ValidationError(_("A tax should only use tags from its country. You should use another tax and a fiscal position if you wish to uses the tags from foreign tax reports.")) @api.depends('factor_percent') def _compute_factor(self): for record in self: record.factor = record.factor_percent / 100.0 @api.depends('invoice_tax_id.company_id', 'refund_tax_id.company_id') def _compute_company(self): for record in self: record.company_id = record.invoice_tax_id and record.invoice_tax_id.company_id.id or record.refund_tax_id.company_id.id @api.depends('invoice_tax_id', 'refund_tax_id') def _compute_tax_id(self): for record in self: record.tax_id = record.invoice_tax_id or record.refund_tax_id @api.onchange('repartition_type') def _onchange_repartition_type(self): if self.repartition_type == 'base': self.account_id = None
54.888158
41,715
303,617
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, Command, _ from odoo.exceptions import RedirectWarning, UserError, ValidationError, AccessError from odoo.tools import float_compare, float_is_zero, date_utils, email_split, email_re, html_escape, is_html_empty from odoo.tools.misc import formatLang, format_date, get_lang from odoo.osv import expression from datetime import date, timedelta from collections import defaultdict from contextlib import contextmanager from itertools import zip_longest from hashlib import sha256 from json import dumps import ast import json import re import warnings MAX_HASH_VERSION = 2 def calc_check_digits(number): """Calculate the extra digits that should be appended to the number to make it a valid number. Source: python-stdnum iso7064.mod_97_10.calc_check_digits """ number_base10 = ''.join(str(int(x, 36)) for x in number) checksum = int(number_base10) % 97 return '%02d' % ((98 - 100 * checksum) % 97) PAYMENT_STATE_SELECTION = [ ('not_paid', 'Not Paid'), ('in_payment', 'In Payment'), ('paid', 'Paid'), ('partial', 'Partially Paid'), ('reversed', 'Reversed'), ('invoicing_legacy', 'Invoicing App Legacy'), ] class AccountMove(models.Model): _name = "account.move" _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin', 'sequence.mixin'] _description = "Journal Entry" _order = 'date desc, name desc, id desc' _mail_post_access = 'read' _check_company_auto = True _sequence_index = "journal_id" def init(self): super().init() self.env.cr.execute(""" CREATE INDEX IF NOT EXISTS account_move_to_check_idx ON account_move(journal_id) WHERE to_check = true; CREATE INDEX IF NOT EXISTS account_move_payment_idx ON account_move(journal_id, state, payment_state, move_type, date); """) @property def _sequence_monthly_regex(self): return self.journal_id.sequence_override_regex or super()._sequence_monthly_regex @property def _sequence_yearly_regex(self): return self.journal_id.sequence_override_regex or super()._sequence_yearly_regex @property def _sequence_fixed_regex(self): return self.journal_id.sequence_override_regex or super()._sequence_fixed_regex @api.model def _search_default_journal(self, journal_types): company_id = self._context.get('default_company_id', self.env.company.id) domain = [('company_id', '=', company_id), ('type', 'in', journal_types)] journal = None if self._context.get('default_currency_id'): currency_domain = domain + [('currency_id', '=', self._context['default_currency_id'])] journal = self.env['account.journal'].search(currency_domain, limit=1) if not journal: journal = self.env['account.journal'].search(domain, limit=1) if not journal: company = self.env['res.company'].browse(company_id) error_msg = _( "No journal could be found in company %(company_name)s for any of those types: %(journal_types)s", company_name=company.display_name, journal_types=', '.join(journal_types), ) raise UserError(error_msg) return journal @api.model def _get_default_journal(self): ''' Get the default journal. It could either be passed through the context using the 'default_journal_id' key containing its id, either be determined by the default type. ''' move_type = self._context.get('default_move_type', 'entry') if move_type in self.get_sale_types(include_receipts=True): journal_types = ['sale'] elif move_type in self.get_purchase_types(include_receipts=True): journal_types = ['purchase'] else: journal_types = self._context.get('default_move_journal_types', ['general']) if self._context.get('default_journal_id'): journal = self.env['account.journal'].browse(self._context['default_journal_id']) if move_type != 'entry' and journal.type not in journal_types: raise UserError(_( "Cannot create an invoice of type %(move_type)s with a journal having %(journal_type)s as type.", move_type=move_type, journal_type=journal.type, )) else: journal = self._search_default_journal(journal_types) return journal # TODO remove in master @api.model def _get_default_invoice_date(self): warnings.warn("Method '_get_default_invoice_date()' is deprecated and has been removed.", DeprecationWarning) return fields.Date.context_today(self) if self._context.get('default_move_type', 'entry') in self.get_purchase_types(include_receipts=True) else False @api.model def _get_default_currency(self): ''' Get the default currency from either the journal, either the default journal's company. ''' journal = self._get_default_journal() return journal.currency_id or journal.company_id.currency_id @api.model def _get_default_invoice_incoterm(self): ''' Get the default incoterm for invoice. ''' return self.env.company.incoterm_id # ==== Business fields ==== name = fields.Char(string='Number', copy=False, compute='_compute_name', readonly=False, store=True, index=True, tracking=True) highest_name = fields.Char(compute='_compute_highest_name') show_name_warning = fields.Boolean(store=False) date = fields.Date( string='Date', required=True, index=True, readonly=True, states={'draft': [('readonly', False)]}, copy=False, tracking=True, default=fields.Date.context_today ) ref = fields.Char(string='Reference', copy=False, tracking=True) narration = fields.Html(string='Terms and Conditions', compute='_compute_narration', store=True, readonly=False) state = fields.Selection(selection=[ ('draft', 'Draft'), ('posted', 'Posted'), ('cancel', 'Cancelled'), ], string='Status', required=True, readonly=True, copy=False, tracking=True, default='draft') posted_before = fields.Boolean(help="Technical field for knowing if the move has been posted before", copy=False) move_type = fields.Selection(selection=[ ('entry', 'Journal Entry'), ('out_invoice', 'Customer Invoice'), ('out_refund', 'Customer Credit Note'), ('in_invoice', 'Vendor Bill'), ('in_refund', 'Vendor Credit Note'), ('out_receipt', 'Sales Receipt'), ('in_receipt', 'Purchase Receipt'), ], string='Type', required=True, store=True, index=True, readonly=True, tracking=True, default="entry", change_default=True) type_name = fields.Char('Type Name', compute='_compute_type_name') to_check = fields.Boolean(string='To Check', default=False, tracking=True, help='If this checkbox is ticked, it means that the user was not sure of all the related information at the time of the creation of the move and that the move needs to be checked again.') journal_id = fields.Many2one('account.journal', string='Journal', required=True, readonly=True, states={'draft': [('readonly', False)]}, check_company=True, domain="[('id', 'in', suitable_journal_ids)]", default=_get_default_journal) suitable_journal_ids = fields.Many2many('account.journal', compute='_compute_suitable_journal_ids') company_id = fields.Many2one(comodel_name='res.company', string='Company', store=True, readonly=True, compute='_compute_company_id') company_currency_id = fields.Many2one(string='Company Currency', readonly=True, related='company_id.currency_id') currency_id = fields.Many2one('res.currency', store=True, readonly=True, tracking=True, required=True, states={'draft': [('readonly', False)]}, string='Currency', default=_get_default_currency) line_ids = fields.One2many('account.move.line', 'move_id', string='Journal Items', copy=True, readonly=True, states={'draft': [('readonly', False)]}) partner_id = fields.Many2one('res.partner', readonly=True, tracking=True, states={'draft': [('readonly', False)]}, check_company=True, string='Partner', change_default=True, ondelete='restrict') commercial_partner_id = fields.Many2one('res.partner', string='Commercial Entity', store=True, readonly=True, compute='_compute_commercial_partner_id', ondelete='restrict') country_code = fields.Char(related='company_id.account_fiscal_country_id.code', readonly=True) user_id = fields.Many2one(string='User', related='invoice_user_id', help='Technical field used to fit the generic behavior in mail templates.') is_move_sent = fields.Boolean( readonly=True, default=False, copy=False, tracking=True, help="It indicates that the invoice/payment has been sent.", ) partner_bank_id = fields.Many2one('res.partner.bank', string='Recipient Bank', help='Bank Account Number to which the invoice will be paid. A Company bank account if this is a Customer Invoice or Vendor Credit Note, otherwise a Partner bank account number.', check_company=True) payment_reference = fields.Char(string='Payment Reference', index=True, copy=False, compute='_compute_payment_reference', store=True, readonly=False, help="The payment reference to set on journal items.") payment_id = fields.Many2one( index=True, comodel_name='account.payment', string="Payment", copy=False, check_company=True) statement_line_id = fields.Many2one( comodel_name='account.bank.statement.line', string="Statement Line", copy=False, check_company=True) statement_id = fields.Many2one( related='statement_line_id.statement_id', copy=False, readonly=True, help="Technical field used to open the linked bank statement from the edit button in a group by view," " or via the smart button on journal entries.") # === Amount fields === amount_untaxed = fields.Monetary(string='Untaxed Amount', store=True, readonly=True, tracking=True, compute='_compute_amount') amount_tax = fields.Monetary(string='Tax', store=True, readonly=True, compute='_compute_amount') amount_total = fields.Monetary(string='Total', store=True, readonly=True, compute='_compute_amount', inverse='_inverse_amount_total') amount_residual = fields.Monetary(string='Amount Due', store=True, compute='_compute_amount') amount_untaxed_signed = fields.Monetary(string='Untaxed Amount Signed', store=True, readonly=True, compute='_compute_amount', currency_field='company_currency_id') amount_tax_signed = fields.Monetary(string='Tax Signed', store=True, readonly=True, compute='_compute_amount', currency_field='company_currency_id') amount_total_signed = fields.Monetary(string='Total Signed', store=True, readonly=True, compute='_compute_amount', currency_field='company_currency_id') amount_total_in_currency_signed = fields.Monetary(string='Total in Currency Signed', store=True, readonly=True, compute='_compute_amount', currency_field='currency_id') amount_residual_signed = fields.Monetary(string='Amount Due Signed', store=True, compute='_compute_amount', currency_field='company_currency_id') tax_totals_json = fields.Char( string="Invoice Totals JSON", compute='_compute_tax_totals_json', readonly=False, help='Edit Tax amounts if you encounter rounding issues.') payment_state = fields.Selection(PAYMENT_STATE_SELECTION, string="Payment Status", store=True, readonly=True, copy=False, tracking=True, compute='_compute_amount') # ==== Cash basis feature fields ==== tax_cash_basis_rec_id = fields.Many2one( 'account.partial.reconcile', string='Tax Cash Basis Entry of', help="Technical field used to keep track of the tax cash basis reconciliation. " "This is needed when cancelling the source: it will post the inverse journal entry to cancel that part too.") tax_cash_basis_origin_move_id = fields.Many2one( comodel_name='account.move', string="Cash Basis Origin", readonly=1, index=True, help="The journal entry from which this tax cash basis journal entry has been created.") tax_cash_basis_created_move_ids = fields.One2many( string="Cash Basis Entries", comodel_name='account.move', inverse_name='tax_cash_basis_origin_move_id', help="The cash basis entries created from the taxes on this entry, when reconciling its lines." ) always_tax_exigible = fields.Boolean( compute='_compute_always_tax_exigible', store=True, readonly=False, help="Technical field used by cash basis taxes, telling the lines of the move are always exigible. " "This happens if the move contains no payable or receivable line.") # ==== Auto-post feature fields ==== auto_post = fields.Boolean(string='Post Automatically', default=False, copy=False, help='If this checkbox is ticked, this entry will be automatically posted at its date.') # ==== Reverse feature fields ==== reversed_entry_id = fields.Many2one('account.move', string="Reversal of", readonly=True, copy=False, check_company=True, index=True) reversal_move_id = fields.One2many('account.move', 'reversed_entry_id') # ========================================================= # Invoice related fields # ========================================================= # ==== Business fields ==== fiscal_position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position', readonly=True, states={'draft': [('readonly', False)]}, check_company=True, domain="[('company_id', '=', company_id)]", ondelete="restrict", help="Fiscal positions are used to adapt taxes and accounts for particular customers or sales orders/invoices. " "The default value comes from the customer.") invoice_user_id = fields.Many2one('res.users', copy=False, tracking=True, string='Salesperson', default=lambda self: self.env.user) invoice_date = fields.Date(string='Invoice/Bill Date', readonly=True, index=True, copy=False, states={'draft': [('readonly', False)]}) invoice_date_due = fields.Date(string='Due Date', readonly=True, index=True, copy=False, states={'draft': [('readonly', False)]}) invoice_origin = fields.Char(string='Origin', readonly=True, tracking=True, help="The document(s) that generated the invoice.") invoice_payment_term_id = fields.Many2one('account.payment.term', string='Payment Terms', check_company=True, readonly=True, states={'draft': [('readonly', False)]}) # /!\ invoice_line_ids is just a subset of line_ids. invoice_line_ids = fields.One2many('account.move.line', 'move_id', string='Invoice lines', copy=False, readonly=True, domain=[('exclude_from_invoice_tab', '=', False)], states={'draft': [('readonly', False)]}) invoice_incoterm_id = fields.Many2one('account.incoterms', string='Incoterm', default=_get_default_invoice_incoterm, help='International Commercial Terms are a series of predefined commercial terms used in international transactions.') display_qr_code = fields.Boolean(string="Display QR-code", compute='_compute_display_qr_code') qr_code_method = fields.Selection(string="Payment QR-code", copy=False, selection=lambda self: self.env['res.partner.bank'].get_available_qr_methods_in_sequence(), help="Type of QR-code to be generated for the payment of this invoice, when printing it. If left blank, the first available and usable method will be used.") # ==== Payment widget fields ==== invoice_outstanding_credits_debits_widget = fields.Text(groups="account.group_account_invoice,account.group_account_readonly", compute='_compute_payments_widget_to_reconcile_info') invoice_has_outstanding = fields.Boolean(groups="account.group_account_invoice,account.group_account_readonly", compute='_compute_payments_widget_to_reconcile_info') invoice_payments_widget = fields.Text(groups="account.group_account_invoice,account.group_account_readonly", compute='_compute_payments_widget_reconciled_info') # ==== Vendor bill fields ==== invoice_vendor_bill_id = fields.Many2one('account.move', store=False, check_company=True, string='Vendor Bill', help="Auto-complete from a past bill.") invoice_source_email = fields.Char(string='Source Email', tracking=True) invoice_partner_display_name = fields.Char(compute='_compute_invoice_partner_display_info', store=True) # ==== Cash rounding fields ==== invoice_cash_rounding_id = fields.Many2one('account.cash.rounding', string='Cash Rounding Method', readonly=True, states={'draft': [('readonly', False)]}, help='Defines the smallest coinage of the currency that can be used to pay by cash.') # ==== Display purpose fields ==== invoice_filter_type_domain = fields.Char(compute='_compute_invoice_filter_type_domain', help="Technical field used to have a dynamic domain on journal / taxes in the form view.") bank_partner_id = fields.Many2one('res.partner', help='Technical field to get the domain on the bank', compute='_compute_bank_partner_id') invoice_has_matching_suspense_amount = fields.Boolean(compute='_compute_has_matching_suspense_amount', groups='account.group_account_invoice,account.group_account_readonly', help="Technical field used to display an alert on invoices if there is at least a matching amount in any supsense account.") tax_lock_date_message = fields.Char( compute='_compute_tax_lock_date_message', help="Technical field used to display a message when the invoice's accounting date is prior of the tax lock date.") display_inactive_currency_warning = fields.Boolean( compute="_compute_display_inactive_currency_warning", help="Technical field used for tracking the status of the currency") tax_country_id = fields.Many2one(comodel_name='res.country', compute='_compute_tax_country_id', help="Technical field to filter the available taxes depending on the fiscal country and fiscal position.") tax_country_code = fields.Char(compute="_compute_tax_country_code") # Technical field to hide Reconciled Entries stat button has_reconciled_entries = fields.Boolean(compute="_compute_has_reconciled_entries") show_reset_to_draft_button = fields.Boolean(compute='_compute_show_reset_to_draft_button') # ==== Hash Fields ==== restrict_mode_hash_table = fields.Boolean(related='journal_id.restrict_mode_hash_table') secure_sequence_number = fields.Integer(string="Inalteralbility No Gap Sequence #", readonly=True, copy=False, index=True) inalterable_hash = fields.Char(string="Inalterability Hash", readonly=True, copy=False) string_to_hash = fields.Char(compute='_compute_string_to_hash', readonly=True) @api.model def _field_will_change(self, record, vals, field_name): if field_name not in vals: return False field = record._fields[field_name] if field.type == 'many2one': return record[field_name].id != vals[field_name] if field.type == 'many2many': current_ids = set(record[field_name].ids) after_write_ids = set(record.new({field_name: vals[field_name]})[field_name].ids) return current_ids != after_write_ids if field.type == 'one2many': return True if field.type == 'monetary' and record[field.get_currency_field(record)]: return not record[field.get_currency_field(record)].is_zero(record[field_name] - vals[field_name]) if field.type == 'float': record_value = field.convert_to_cache(record[field_name], record) to_write_value = field.convert_to_cache(vals[field_name], record) return record_value != to_write_value return record[field_name] != vals[field_name] @api.model def _cleanup_write_orm_values(self, record, vals): cleaned_vals = dict(vals) for field_name, value in vals.items(): if not self._field_will_change(record, vals, field_name): del cleaned_vals[field_name] return cleaned_vals # ------------------------------------------------------------------------- # ONCHANGE METHODS # ------------------------------------------------------------------------- def _get_accounting_date(self, invoice_date, has_tax): """Get correct accounting date for previous periods, taking tax lock date into account. When registering an invoice in the past, we still want the sequence to be increasing. We then take the last day of the period, depending on the sequence format. If there is a tax lock date and there are taxes involved, we register the invoice at the last date of the first open period. :param invoice_date (datetime.date): The invoice date :param has_tax (bool): Iff any taxes are involved in the lines of the invoice :return (datetime.date): """ lock_dates = self._get_violated_lock_dates(invoice_date, has_tax) today = fields.Date.today() highest_name = self.highest_name or self._get_last_sequence(relaxed=True, lock=False) number_reset = self._deduce_sequence_number_reset(highest_name) if lock_dates: invoice_date = lock_dates[-1][0] + timedelta(days=1) if self.is_sale_document(include_receipts=True): if lock_dates: if not highest_name or number_reset == 'month': return min(today, date_utils.get_month(invoice_date)[1]) elif number_reset == 'year': return min(today, date_utils.end_of(invoice_date, 'year')) else: if not highest_name or number_reset == 'month': if (today.year, today.month) > (invoice_date.year, invoice_date.month): return date_utils.get_month(invoice_date)[1] else: return max(invoice_date, today) elif number_reset == 'year': if today.year > invoice_date.year: return date(invoice_date.year, 12, 31) else: return max(invoice_date, today) return invoice_date def _get_violated_lock_dates(self, invoice_date, has_tax): """Get all the lock dates affecting the current invoice_date. :param invoice_date: The invoice date :param has_tax: If any taxes are involved in the lines of the invoice :return: a list of tuples containing the lock dates affecting this move, ordered chronologically. """ locks = [] user_lock_date = self.company_id._get_user_fiscal_lock_date() if invoice_date and user_lock_date and invoice_date <= user_lock_date: locks.append((user_lock_date, _('user'))) tax_lock_date = self.company_id.tax_lock_date if invoice_date and tax_lock_date and has_tax and invoice_date <= tax_lock_date: locks.append((tax_lock_date, _('tax'))) locks.sort() return locks @api.onchange('invoice_date', 'highest_name', 'company_id') def _onchange_invoice_date(self): if self.invoice_date: if not self.invoice_payment_term_id and (not self.invoice_date_due or self.invoice_date_due < self.invoice_date): self.invoice_date_due = self.invoice_date accounting_date = self.invoice_date if not self.is_sale_document(include_receipts=True): accounting_date = self._get_accounting_date(self.invoice_date, self._affect_tax_report()) if accounting_date != self.date: self.date = accounting_date self._onchange_currency() else: self._onchange_recompute_dynamic_lines() @api.onchange('journal_id') def _onchange_journal(self): if self.journal_id and self.journal_id.currency_id: new_currency = self.journal_id.currency_id if new_currency != self.currency_id: self.currency_id = new_currency self._onchange_currency() if self.state == 'draft' and self._get_last_sequence(lock=False) and self.name and self.name != '/': self.name = '/' @api.onchange('partner_id') def _onchange_partner_id(self): self = self.with_company(self.journal_id.company_id) warning = {} if self.partner_id: rec_account = self.partner_id.property_account_receivable_id pay_account = self.partner_id.property_account_payable_id if not rec_account and not pay_account: action = self.env.ref('account.action_account_config') msg = _('Cannot find a chart of accounts for this company, You should configure it. \nPlease go to Account Configuration.') raise RedirectWarning(msg, action.id, _('Go to the configuration panel')) p = self.partner_id if p.invoice_warn == 'no-message' and p.parent_id: p = p.parent_id if p.invoice_warn and p.invoice_warn != 'no-message': # Block if partner only has warning but parent company is blocked if p.invoice_warn != 'block' and p.parent_id and p.parent_id.invoice_warn == 'block': p = p.parent_id warning = { 'title': _("Warning for %s", p.name), 'message': p.invoice_warn_msg } if p.invoice_warn == 'block': self.partner_id = False return {'warning': warning} if self.is_sale_document(include_receipts=True) and self.partner_id: self.invoice_payment_term_id = self.partner_id.property_payment_term_id or self.invoice_payment_term_id new_term_account = self.partner_id.commercial_partner_id.property_account_receivable_id elif self.is_purchase_document(include_receipts=True) and self.partner_id: self.invoice_payment_term_id = self.partner_id.property_supplier_payment_term_id or self.invoice_payment_term_id new_term_account = self.partner_id.commercial_partner_id.property_account_payable_id else: new_term_account = None for line in self.line_ids: line.partner_id = self.partner_id.commercial_partner_id if new_term_account and line.account_id.user_type_id.type in ('receivable', 'payable'): line.account_id = new_term_account self._compute_bank_partner_id() bank_ids = self.bank_partner_id.bank_ids.filtered(lambda bank: bank.company_id is False or bank.company_id == self.company_id) self.partner_bank_id = bank_ids and bank_ids[0] # Find the new fiscal position. delivery_partner_id = self._get_invoice_delivery_partner_id() self.fiscal_position_id = self.env['account.fiscal.position'].get_fiscal_position( self.partner_id.id, delivery_id=delivery_partner_id) self._recompute_dynamic_lines() if warning: return {'warning': warning} @api.onchange('date', 'currency_id') def _onchange_currency(self): currency = self.currency_id or self.company_id.currency_id if self.is_invoice(include_receipts=True): for line in self._get_lines_onchange_currency(): line.currency_id = currency line._onchange_currency() else: for line in self.line_ids: line._onchange_currency() self._recompute_dynamic_lines(recompute_tax_base_amount=True) @api.onchange('payment_reference') def _onchange_payment_reference(self): for line in self.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')): line.name = self.payment_reference or '' @api.onchange('invoice_vendor_bill_id') def _onchange_invoice_vendor_bill(self): if self.invoice_vendor_bill_id: # Copy invoice lines. for line in self.invoice_vendor_bill_id.invoice_line_ids: copied_vals = line.copy_data()[0] copied_vals['move_id'] = self.id new_line = self.env['account.move.line'].new(copied_vals) new_line.recompute_tax_line = True # Copy payment terms. self.invoice_payment_term_id = self.invoice_vendor_bill_id.invoice_payment_term_id # Copy currency. if self.currency_id != self.invoice_vendor_bill_id.currency_id: self.currency_id = self.invoice_vendor_bill_id.currency_id self._onchange_currency() # Reset self.invoice_vendor_bill_id = False self._recompute_dynamic_lines() @api.onchange('invoice_line_ids') def _onchange_invoice_line_ids(self): current_invoice_lines = self.line_ids.filtered(lambda line: not line.exclude_from_invoice_tab) others_lines = self.line_ids - current_invoice_lines if others_lines and current_invoice_lines - self.invoice_line_ids: others_lines[0].recompute_tax_line = True self.line_ids = others_lines + self.invoice_line_ids self._onchange_recompute_dynamic_lines() @api.onchange('line_ids', 'invoice_payment_term_id', 'invoice_date_due', 'invoice_cash_rounding_id', 'invoice_vendor_bill_id') def _onchange_recompute_dynamic_lines(self): self._recompute_dynamic_lines() @api.onchange('tax_totals_json') def _onchange_tax_totals_json(self): """ This method is triggered by the tax group widget. It allows modifying the right move lines depending on the tax group whose amount got edited. """ for move in self: if not move.is_invoice(include_receipts=True): continue invoice_totals = json.loads(move.tax_totals_json) for amount_by_group_list in invoice_totals['groups_by_subtotal'].values(): for amount_by_group in amount_by_group_list: tax_lines = move.line_ids.filtered(lambda line: line.tax_group_id.id == amount_by_group['tax_group_id']) if tax_lines: first_tax_line = tax_lines[0] tax_group_old_amount = sum(tax_lines.mapped('amount_currency')) sign = -1 if move.is_inbound() else 1 delta_amount = tax_group_old_amount * sign - amount_by_group['tax_group_amount'] if not move.currency_id.is_zero(delta_amount): first_tax_line.amount_currency = first_tax_line.amount_currency - delta_amount * sign # We have to trigger the on change manually because we don"t change the value of # amount_currency in the view. first_tax_line._onchange_amount_currency() move._recompute_dynamic_lines() @api.onchange('invoice_cash_rounding_id') def _onchange_invoice_cash_rounding_id(self): for move in self: if move.invoice_cash_rounding_id.strategy == 'add_invoice_line' and not move.invoice_cash_rounding_id.profit_account_id: return {'warning':{ 'title': _("Warning for Cash Rounding Method: %s", move.invoice_cash_rounding_id.name), 'message': _("You must specify the Profit Account (company dependent)") }} @api.model def _get_tax_grouping_key_from_tax_line(self, tax_line): ''' Create the dictionary based on a tax line that will be used as key to group taxes together. /!\ Must be consistent with '_get_tax_grouping_key_from_base_line'. :param tax_line: An account.move.line being a tax line (with 'tax_repartition_line_id' set then). :return: A dictionary containing all fields on which the tax will be grouped. ''' return { 'tax_repartition_line_id': tax_line.tax_repartition_line_id.id, 'group_tax_id': tax_line.group_tax_id.id, 'account_id': tax_line.account_id.id, 'currency_id': tax_line.currency_id.id, 'analytic_tag_ids': [(6, 0, tax_line.tax_line_id.analytic and tax_line.analytic_tag_ids.ids or [])], 'analytic_account_id': tax_line.tax_line_id.analytic and tax_line.analytic_account_id.id, 'tax_ids': [(6, 0, tax_line.tax_ids.ids)], 'tax_tag_ids': [(6, 0, tax_line.tax_tag_ids.ids)], 'partner_id': tax_line.partner_id.id, } @api.model def _get_tax_grouping_key_from_base_line(self, base_line, tax_vals): ''' Create the dictionary based on a base line that will be used as key to group taxes together. /!\ Must be consistent with '_get_tax_grouping_key_from_tax_line'. :param base_line: An account.move.line being a base line (that could contains something in 'tax_ids'). :param tax_vals: An element of compute_all(...)['taxes']. :return: A dictionary containing all fields on which the tax will be grouped. ''' tax_repartition_line = self.env['account.tax.repartition.line'].browse(tax_vals['tax_repartition_line_id']) account = base_line._get_default_tax_account(tax_repartition_line) or base_line.account_id return { 'tax_repartition_line_id': tax_vals['tax_repartition_line_id'], 'group_tax_id': tax_vals['group'].id if tax_vals['group'] else False, 'account_id': account.id, 'currency_id': base_line.currency_id.id, 'analytic_tag_ids': [(6, 0, tax_vals['analytic'] and base_line.analytic_tag_ids.ids or [])], 'analytic_account_id': tax_vals['analytic'] and base_line.analytic_account_id.id, 'tax_ids': [(6, 0, tax_vals['tax_ids'])], 'tax_tag_ids': [(6, 0, tax_vals['tag_ids'])], 'partner_id': base_line.partner_id.id, } def _get_tax_force_sign(self): """ The sign must be forced to a negative sign in case the balance is on credit to avoid negatif taxes amount. Example - Customer Invoice : Fixed Tax | unit price | discount | amount_tax | amount_total | ------------------------------------------------------------------------- 0.67 | 115 | 100% | - 0.67 | 0 -------------------------------------------------------------------------""" self.ensure_one() return -1 if self.move_type in ('out_invoice', 'in_refund', 'out_receipt') else 1 def _preprocess_taxes_map(self, taxes_map): """ Useful in case we want to pre-process taxes_map """ return taxes_map def _recompute_tax_lines(self, recompute_tax_base_amount=False, tax_rep_lines_to_recompute=None): """ Compute the dynamic tax lines of the journal entry. :param recompute_tax_base_amount: Flag forcing only the recomputation of the `tax_base_amount` field. """ self.ensure_one() in_draft_mode = self != self._origin def _serialize_tax_grouping_key(grouping_dict): ''' Serialize the dictionary values to be used in the taxes_map. :param grouping_dict: The values returned by '_get_tax_grouping_key_from_tax_line' or '_get_tax_grouping_key_from_base_line'. :return: A string representing the values. ''' return '-'.join(str(v) for v in grouping_dict.values()) def _compute_base_line_taxes(base_line): ''' Compute taxes amounts both in company currency / foreign currency as the ratio between amount_currency & balance could not be the same as the expected currency rate. The 'amount_currency' value will be set on compute_all(...)['taxes'] in multi-currency. :param base_line: The account.move.line owning the taxes. :return: The result of the compute_all method. ''' move = base_line.move_id if move.is_invoice(include_receipts=True): handle_price_include = True sign = -1 if move.is_inbound() else 1 quantity = base_line.quantity is_refund = move.move_type in ('out_refund', 'in_refund') price_unit_wo_discount = sign * base_line.price_unit * (1 - (base_line.discount / 100.0)) else: handle_price_include = False quantity = 1.0 tax_type = base_line.tax_ids[0].type_tax_use if base_line.tax_ids else None is_refund = (tax_type == 'sale' and base_line.debit) or (tax_type == 'purchase' and base_line.credit) price_unit_wo_discount = base_line.amount_currency return base_line.tax_ids._origin.with_context(force_sign=move._get_tax_force_sign()).compute_all( price_unit_wo_discount, currency=base_line.currency_id, quantity=quantity, product=base_line.product_id, partner=base_line.partner_id, is_refund=is_refund, handle_price_include=handle_price_include, include_caba_tags=move.always_tax_exigible, ) taxes_map = {} # ==== Add tax lines ==== to_remove = self.env['account.move.line'] for line in self.line_ids.filtered('tax_repartition_line_id'): grouping_dict = self._get_tax_grouping_key_from_tax_line(line) grouping_key = _serialize_tax_grouping_key(grouping_dict) if grouping_key in taxes_map: # A line with the same key does already exist, we only need one # to modify it; we have to drop this one. to_remove += line else: taxes_map[grouping_key] = { 'tax_line': line, 'amount': 0.0, 'tax_base_amount': 0.0, 'grouping_dict': False, } if not recompute_tax_base_amount: self.line_ids -= to_remove # ==== Mount base lines ==== for line in self.line_ids.filtered(lambda line: not line.tax_repartition_line_id): # Don't call compute_all if there is no tax. if not line.tax_ids: if not recompute_tax_base_amount: line.tax_tag_ids = [(5, 0, 0)] continue compute_all_vals = _compute_base_line_taxes(line) # Assign tags on base line if not recompute_tax_base_amount: line.tax_tag_ids = compute_all_vals['base_tags'] or [(5, 0, 0)] for tax_vals in compute_all_vals['taxes']: grouping_dict = self._get_tax_grouping_key_from_base_line(line, tax_vals) grouping_key = _serialize_tax_grouping_key(grouping_dict) tax_repartition_line = self.env['account.tax.repartition.line'].browse(tax_vals['tax_repartition_line_id']) tax = tax_repartition_line.invoice_tax_id or tax_repartition_line.refund_tax_id taxes_map_entry = taxes_map.setdefault(grouping_key, { 'tax_line': None, 'amount': 0.0, 'tax_base_amount': 0.0, 'grouping_dict': False, }) taxes_map_entry['amount'] += tax_vals['amount'] taxes_map_entry['tax_base_amount'] += self._get_base_amount_to_display(tax_vals['base'], tax_repartition_line, tax_vals['group']) taxes_map_entry['grouping_dict'] = grouping_dict # ==== Pre-process taxes_map ==== taxes_map = self._preprocess_taxes_map(taxes_map) # ==== Process taxes_map ==== for taxes_map_entry in taxes_map.values(): # The tax line is no longer used in any base lines, drop it. if taxes_map_entry['tax_line'] and not taxes_map_entry['grouping_dict']: if not recompute_tax_base_amount: self.line_ids -= taxes_map_entry['tax_line'] continue currency = self.env['res.currency'].browse(taxes_map_entry['grouping_dict']['currency_id']) # Don't create tax lines with zero balance. if currency.is_zero(taxes_map_entry['amount']): if taxes_map_entry['tax_line'] and not recompute_tax_base_amount: self.line_ids -= taxes_map_entry['tax_line'] continue # tax_base_amount field is expressed using the company currency. tax_base_amount = currency._convert(taxes_map_entry['tax_base_amount'], self.company_currency_id, self.company_id, self.date or fields.Date.context_today(self)) # Recompute only the tax_base_amount. if recompute_tax_base_amount: if taxes_map_entry['tax_line']: taxes_map_entry['tax_line'].tax_base_amount = tax_base_amount continue balance = currency._convert( taxes_map_entry['amount'], self.company_currency_id, self.company_id, self.date or fields.Date.context_today(self), ) amount_currency = currency.round(taxes_map_entry['amount']) sign = -1 if self.is_inbound() else 1 to_write_on_line = { 'amount_currency': amount_currency, 'currency_id': taxes_map_entry['grouping_dict']['currency_id'], 'debit': balance > 0.0 and balance or 0.0, 'credit': balance < 0.0 and -balance or 0.0, 'tax_base_amount': tax_base_amount, 'price_total': sign * amount_currency, 'price_subtotal': sign * amount_currency, } if taxes_map_entry['tax_line']: # Update an existing tax line. if tax_rep_lines_to_recompute and taxes_map_entry['tax_line'].tax_repartition_line_id not in tax_rep_lines_to_recompute: continue taxes_map_entry['tax_line'].update(to_write_on_line) else: # Create a new tax line. create_method = in_draft_mode and self.env['account.move.line'].new or self.env['account.move.line'].create tax_repartition_line_id = taxes_map_entry['grouping_dict']['tax_repartition_line_id'] tax_repartition_line = self.env['account.tax.repartition.line'].browse(tax_repartition_line_id) if tax_rep_lines_to_recompute and tax_repartition_line not in tax_rep_lines_to_recompute: continue tax = tax_repartition_line.invoice_tax_id or tax_repartition_line.refund_tax_id taxes_map_entry['tax_line'] = create_method({ **to_write_on_line, 'name': tax.name, 'move_id': self.id, 'company_id': self.company_id.id, 'company_currency_id': self.company_currency_id.id, 'tax_base_amount': tax_base_amount, 'exclude_from_invoice_tab': True, **taxes_map_entry['grouping_dict'], }) if in_draft_mode: taxes_map_entry['tax_line'].update(taxes_map_entry['tax_line']._get_fields_onchange_balance(force_computation=True)) @api.model def _get_base_amount_to_display(self, base_amount, tax_rep_ln, parent_tax_group=None): """ The base amount returned for taxes by compute_all has is the balance of the base line. For inbound operations, positive sign is on credit, so we need to invert the sign of this amount before displaying it. """ source_tax = parent_tax_group or tax_rep_ln.invoice_tax_id or tax_rep_ln.refund_tax_id if (tax_rep_ln.invoice_tax_id and source_tax.type_tax_use == 'sale') \ or (tax_rep_ln.refund_tax_id and source_tax.type_tax_use == 'purchase'): return -base_amount return base_amount def _recompute_cash_rounding_lines(self): ''' Handle the cash rounding feature on invoices. In some countries, the smallest coins do not exist. For example, in Switzerland, there is no coin for 0.01 CHF. For this reason, if invoices are paid in cash, you have to round their total amount to the smallest coin that exists in the currency. For the CHF, the smallest coin is 0.05 CHF. There are two strategies for the rounding: 1) Add a line on the invoice for the rounding: The cash rounding line is added as a new invoice line. 2) Add the rounding in the biggest tax amount: The cash rounding line is added as a new tax line on the tax having the biggest balance. ''' self.ensure_one() in_draft_mode = self != self._origin def _compute_cash_rounding(self, total_amount_currency): ''' Compute the amount differences due to the cash rounding. :param self: The current account.move record. :param total_amount_currency: The invoice's total in invoice's currency. :return: The amount differences both in company's currency & invoice's currency. ''' difference = self.invoice_cash_rounding_id.compute_difference(self.currency_id, total_amount_currency) if self.currency_id == self.company_id.currency_id: diff_amount_currency = diff_balance = difference else: diff_amount_currency = difference diff_balance = self.currency_id._convert(diff_amount_currency, self.company_id.currency_id, self.company_id, self.date) return diff_balance, diff_amount_currency def _apply_cash_rounding(self, diff_balance, diff_amount_currency, cash_rounding_line): ''' Apply the cash rounding. :param self: The current account.move record. :param diff_balance: The computed balance to set on the new rounding line. :param diff_amount_currency: The computed amount in invoice's currency to set on the new rounding line. :param cash_rounding_line: The existing cash rounding line. :return: The newly created rounding line. ''' rounding_line_vals = { 'debit': diff_balance > 0.0 and diff_balance or 0.0, 'credit': diff_balance < 0.0 and -diff_balance or 0.0, 'quantity': 1.0, 'amount_currency': diff_amount_currency, 'partner_id': self.partner_id.id, 'move_id': self.id, 'currency_id': self.currency_id.id, 'company_id': self.company_id.id, 'company_currency_id': self.company_id.currency_id.id, 'is_rounding_line': True, 'sequence': 9999, } if self.invoice_cash_rounding_id.strategy == 'biggest_tax': biggest_tax_line = None for tax_line in self.line_ids.filtered('tax_repartition_line_id'): if not biggest_tax_line or tax_line.price_subtotal > biggest_tax_line.price_subtotal: biggest_tax_line = tax_line # No tax found. if not biggest_tax_line: return rounding_line_vals.update({ 'name': _('%s (rounding)', biggest_tax_line.name), 'account_id': biggest_tax_line.account_id.id, 'tax_repartition_line_id': biggest_tax_line.tax_repartition_line_id.id, 'tax_tag_ids': [(6, 0, biggest_tax_line.tax_tag_ids.ids)], 'exclude_from_invoice_tab': True, }) elif self.invoice_cash_rounding_id.strategy == 'add_invoice_line': if diff_balance > 0.0 and self.invoice_cash_rounding_id.loss_account_id: account_id = self.invoice_cash_rounding_id.loss_account_id.id else: account_id = self.invoice_cash_rounding_id.profit_account_id.id rounding_line_vals.update({ 'name': self.invoice_cash_rounding_id.name, 'account_id': account_id, }) # Create or update the cash rounding line. if cash_rounding_line: cash_rounding_line.update({ 'amount_currency': rounding_line_vals['amount_currency'], 'debit': rounding_line_vals['debit'], 'credit': rounding_line_vals['credit'], 'account_id': rounding_line_vals['account_id'], }) else: create_method = in_draft_mode and self.env['account.move.line'].new or self.env['account.move.line'].create cash_rounding_line = create_method(rounding_line_vals) if in_draft_mode: cash_rounding_line.update(cash_rounding_line._get_fields_onchange_balance(force_computation=True)) existing_cash_rounding_line = self.line_ids.filtered(lambda line: line.is_rounding_line) # The cash rounding has been removed. if not self.invoice_cash_rounding_id: self.line_ids -= existing_cash_rounding_line return # The cash rounding strategy has changed. if self.invoice_cash_rounding_id and existing_cash_rounding_line: strategy = self.invoice_cash_rounding_id.strategy old_strategy = 'biggest_tax' if existing_cash_rounding_line.tax_line_id else 'add_invoice_line' if strategy != old_strategy: self.line_ids -= existing_cash_rounding_line existing_cash_rounding_line = self.env['account.move.line'] others_lines = self.line_ids.filtered(lambda line: line.account_id.user_type_id.type not in ('receivable', 'payable')) others_lines -= existing_cash_rounding_line total_amount_currency = sum(others_lines.mapped('amount_currency')) diff_balance, diff_amount_currency = _compute_cash_rounding(self, total_amount_currency) # The invoice is already rounded. if self.currency_id.is_zero(diff_balance) and self.currency_id.is_zero(diff_amount_currency): self.line_ids -= existing_cash_rounding_line return _apply_cash_rounding(self, diff_balance, diff_amount_currency, existing_cash_rounding_line) def _recompute_payment_terms_lines(self): ''' Compute the dynamic payment term lines of the journal entry.''' self.ensure_one() self = self.with_company(self.company_id) in_draft_mode = self != self._origin today = fields.Date.context_today(self) self = self.with_company(self.journal_id.company_id) def _get_payment_terms_computation_date(self): ''' Get the date from invoice that will be used to compute the payment terms. :param self: The current account.move record. :return: A datetime.date object. ''' if self.invoice_payment_term_id: return self.invoice_date or today else: return self.invoice_date_due or self.invoice_date or today def _get_payment_terms_account(self, payment_terms_lines): ''' Get the account from invoice that will be set as receivable / payable account. :param self: The current account.move record. :param payment_terms_lines: The current payment terms lines. :return: An account.account record. ''' if payment_terms_lines: # Retrieve account from previous payment terms lines in order to allow the user to set a custom one. return payment_terms_lines[0].account_id elif self.partner_id: # Retrieve account from partner. if self.is_sale_document(include_receipts=True): return self.partner_id.property_account_receivable_id else: return self.partner_id.property_account_payable_id else: # Search new account. domain = [ ('company_id', '=', self.company_id.id), ('internal_type', '=', 'receivable' if self.move_type in ('out_invoice', 'out_refund', 'out_receipt') else 'payable'), ('deprecated', '=', False), ] return self.env['account.account'].search(domain, limit=1) def _compute_payment_terms(self, date, total_balance, total_amount_currency): ''' Compute the payment terms. :param self: The current account.move record. :param date: The date computed by '_get_payment_terms_computation_date'. :param total_balance: The invoice's total in company's currency. :param total_amount_currency: The invoice's total in invoice's currency. :return: A list <to_pay_company_currency, to_pay_invoice_currency, due_date>. ''' if self.invoice_payment_term_id: to_compute = self.invoice_payment_term_id.compute(total_balance, date_ref=date, currency=self.company_id.currency_id) if self.currency_id == self.company_id.currency_id: # Single-currency. return [(b[0], b[1], b[1]) for b in to_compute] else: # Multi-currencies. to_compute_currency = self.invoice_payment_term_id.compute(total_amount_currency, date_ref=date, currency=self.currency_id) return [(b[0], b[1], ac[1]) for b, ac in zip(to_compute, to_compute_currency)] else: return [(fields.Date.to_string(date), total_balance, total_amount_currency)] def _compute_diff_payment_terms_lines(self, existing_terms_lines, account, to_compute): ''' Process the result of the '_compute_payment_terms' method and creates/updates corresponding invoice lines. :param self: The current account.move record. :param existing_terms_lines: The current payment terms lines. :param account: The account.account record returned by '_get_payment_terms_account'. :param to_compute: The list returned by '_compute_payment_terms'. ''' # As we try to update existing lines, sort them by due date. existing_terms_lines = existing_terms_lines.sorted(lambda line: line.date_maturity or today) existing_terms_lines_index = 0 # Recompute amls: update existing line or create new one for each payment term. new_terms_lines = self.env['account.move.line'] for date_maturity, balance, amount_currency in to_compute: currency = self.journal_id.company_id.currency_id if currency and currency.is_zero(balance) and len(to_compute) > 1: continue if existing_terms_lines_index < len(existing_terms_lines): # Update existing line. candidate = existing_terms_lines[existing_terms_lines_index] existing_terms_lines_index += 1 candidate.update({ 'date_maturity': date_maturity, 'amount_currency': -amount_currency, 'debit': balance < 0.0 and -balance or 0.0, 'credit': balance > 0.0 and balance or 0.0, }) else: # Create new line. create_method = in_draft_mode and self.env['account.move.line'].new or self.env['account.move.line'].create candidate = create_method({ 'name': self.payment_reference or '', 'debit': balance < 0.0 and -balance or 0.0, 'credit': balance > 0.0 and balance or 0.0, 'quantity': 1.0, 'amount_currency': -amount_currency, 'date_maturity': date_maturity, 'move_id': self.id, 'currency_id': self.currency_id.id, 'account_id': account.id, 'partner_id': self.commercial_partner_id.id, 'exclude_from_invoice_tab': True, }) new_terms_lines += candidate if in_draft_mode: candidate.update(candidate._get_fields_onchange_balance(force_computation=True)) return new_terms_lines existing_terms_lines = self.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) others_lines = self.line_ids.filtered(lambda line: line.account_id.user_type_id.type not in ('receivable', 'payable')) company_currency_id = (self.company_id or self.env.company).currency_id total_balance = sum(others_lines.mapped(lambda l: company_currency_id.round(l.balance))) total_amount_currency = sum(others_lines.mapped('amount_currency')) if not others_lines: self.line_ids -= existing_terms_lines return computation_date = _get_payment_terms_computation_date(self) account = _get_payment_terms_account(self, existing_terms_lines) to_compute = _compute_payment_terms(self, computation_date, total_balance, total_amount_currency) new_terms_lines = _compute_diff_payment_terms_lines(self, existing_terms_lines, account, to_compute) # Remove old terms lines that are no longer needed. self.line_ids -= existing_terms_lines - new_terms_lines if new_terms_lines: self.payment_reference = new_terms_lines[-1].name or '' self.invoice_date_due = new_terms_lines[-1].date_maturity def _recompute_dynamic_lines(self, recompute_all_taxes=False, recompute_tax_base_amount=False): ''' Recompute all lines that depend on others. For example, tax lines depends on base lines (lines having tax_ids set). This is also the case of cash rounding lines that depend on base lines or tax lines depending on the cash rounding strategy. When a payment term is set, this method will auto-balance the move with payment term lines. :param recompute_all_taxes: Force the computation of taxes. If set to False, the computation will be done or not depending on the field 'recompute_tax_line' in lines. ''' for invoice in self: # Dispatch lines and pre-compute some aggregated values like taxes. expected_tax_rep_lines = set() current_tax_rep_lines = set() inv_recompute_all_taxes = recompute_all_taxes for line in invoice.line_ids: if line.recompute_tax_line: inv_recompute_all_taxes = True line.recompute_tax_line = False if line.tax_repartition_line_id: current_tax_rep_lines.add(line.tax_repartition_line_id._origin) elif line.tax_ids: if invoice.is_invoice(include_receipts=True): is_refund = invoice.move_type in ('out_refund', 'in_refund') else: tax_type = line.tax_ids[0].type_tax_use is_refund = (tax_type == 'sale' and line.debit) or (tax_type == 'purchase' and line.credit) taxes = line.tax_ids._origin.flatten_taxes_hierarchy().filtered( lambda tax: ( tax.amount_type == 'fixed' and not invoice.company_id.currency_id.is_zero(tax.amount) or not float_is_zero(tax.amount, precision_digits=4) ) ) if is_refund: tax_rep_lines = taxes.refund_repartition_line_ids._origin.filtered(lambda x: x.repartition_type == "tax") else: tax_rep_lines = taxes.invoice_repartition_line_ids._origin.filtered(lambda x: x.repartition_type == "tax") for tax_rep_line in tax_rep_lines: expected_tax_rep_lines.add(tax_rep_line) delta_tax_rep_lines = expected_tax_rep_lines - current_tax_rep_lines # Compute taxes. if inv_recompute_all_taxes: invoice._recompute_tax_lines() elif recompute_tax_base_amount: invoice._recompute_tax_lines(recompute_tax_base_amount=True) elif delta_tax_rep_lines and not self._context.get('move_reverse_cancel'): invoice._recompute_tax_lines(tax_rep_lines_to_recompute=delta_tax_rep_lines) if invoice.is_invoice(include_receipts=True): # Compute cash rounding. invoice._recompute_cash_rounding_lines() # Compute payment terms. invoice._recompute_payment_terms_lines() # Only synchronize one2many in onchange. if invoice != invoice._origin: invoice.invoice_line_ids = invoice.line_ids.filtered(lambda line: not line.exclude_from_invoice_tab) @api.depends('journal_id') def _compute_company_id(self): for move in self: move.company_id = move.journal_id.company_id or move.company_id or self.env.company def _get_lines_onchange_currency(self): # Override needed for COGS return self.line_ids def onchange(self, values, field_name, field_onchange): # OVERRIDE # As the dynamic lines in this model are quite complex, we need to ensure some computations are done exactly # at the beginning / at the end of the onchange mechanism. So, the onchange recursivity is disabled. return super(AccountMove, self.with_context(recursive_onchanges=False)).onchange(values, field_name, field_onchange) # ------------------------------------------------------------------------- # COMPUTE METHODS # ------------------------------------------------------------------------- @api.depends('company_id', 'invoice_filter_type_domain') def _compute_suitable_journal_ids(self): for m in self: journal_type = m.invoice_filter_type_domain or 'general' company_id = m.company_id.id or self.env.company.id domain = [('company_id', '=', company_id), ('type', '=', journal_type)] m.suitable_journal_ids = self.env['account.journal'].search(domain) @api.depends('posted_before', 'state', 'journal_id', 'date') def _compute_name(self): def journal_key(move): return (move.journal_id, move.journal_id.refund_sequence and move.move_type) def date_key(move): return (move.date.year, move.date.month) grouped = defaultdict( # key: journal_id, move_type lambda: defaultdict( # key: first adjacent (date.year, date.month) lambda: { 'records': self.env['account.move'], 'format': False, 'format_values': False, 'reset': False } ) ) self = self.sorted(lambda m: (m.date, m.ref or '', m.id)) # Group the moves by journal and month for move in self: move_has_name = move.name and move.name != '/' if move_has_name or move.state != 'posted': try: if not move.posted_before: # The move was never posted, so the name can potentially be changed. move._constrains_date_sequence() # Either the move was posted before, or the name already matches the date (or no name or date). # We can skip recalculating the name when either # - the move already has a name, or # - the move has no name, but is in a period with other moves (so name should be `/`), or # - the move has (temporarily) no date set if ( move_has_name and move.posted_before or not move_has_name and move._get_last_sequence(lock=False) or not move.date ): continue except ValidationError: # The move was never posted and the current name doesn't match the date. We should calculate the # name later on, unless ... if move._get_last_sequence(lock=False): # ... we are in a period already containing moves: reset the name to `/` (draft) move.name = '/' continue group = grouped[journal_key(move)][date_key(move)] if not group['records']: # Compute all the values needed to sequence this whole group move._set_next_sequence() group['format'], group['format_values'] = move._get_sequence_format_param(move.name) group['reset'] = move._deduce_sequence_number_reset(move.name) group['records'] += move # Fusion the groups depending on the sequence reset and the format used because `seq` is # the same counter for multiple groups that might be spread in multiple months. final_batches = [] for journal_group in grouped.values(): journal_group_changed = True for date_group in journal_group.values(): if ( journal_group_changed or final_batches[-1]['format'] != date_group['format'] or dict(final_batches[-1]['format_values'], seq=0) != dict(date_group['format_values'], seq=0) ): final_batches += [date_group] journal_group_changed = False elif date_group['reset'] == 'never': final_batches[-1]['records'] += date_group['records'] elif ( date_group['reset'] == 'year' and final_batches[-1]['records'][0].date.year == date_group['records'][0].date.year ): final_batches[-1]['records'] += date_group['records'] else: final_batches += [date_group] # Give the name based on previously computed values for batch in final_batches: for move in batch['records']: move.name = batch['format'].format(**batch['format_values']) batch['format_values']['seq'] += 1 batch['records']._compute_split_sequence() self.filtered(lambda m: not m.name).name = '/' @api.depends('journal_id', 'date') def _compute_highest_name(self): for record in self: record.highest_name = record._get_last_sequence(lock=False) @api.onchange('name', 'highest_name') def _onchange_name_warning(self): if self.name and self.name != '/' and self.name <= (self.highest_name or ''): self.show_name_warning = True else: self.show_name_warning = False origin_name = self._origin.name if not origin_name or origin_name == '/': origin_name = self.highest_name if self.name and self.name != '/' and origin_name and origin_name != '/': new_format, new_format_values = self._get_sequence_format_param(self.name) origin_format, origin_format_values = self._get_sequence_format_param(origin_name) if ( new_format != origin_format or dict(new_format_values, seq=0) != dict(origin_format_values, seq=0) ): changed = _( "It was previously '%(previous)s' and it is now '%(current)s'.", previous=origin_name, current=self.name, ) reset = self._deduce_sequence_number_reset(self.name) if reset == 'month': detected = _( "The sequence will restart at 1 at the start of every month.\n" "The year detected here is '%(year)s' and the month is '%(month)s'.\n" "The incrementing number in this case is '%(formatted_seq)s'." ) elif reset == 'year': detected = _( "The sequence will restart at 1 at the start of every year.\n" "The year detected here is '%(year)s'.\n" "The incrementing number in this case is '%(formatted_seq)s'." ) else: detected = _( "The sequence will never restart.\n" "The incrementing number in this case is '%(formatted_seq)s'." ) new_format_values['formatted_seq'] = "{seq:0{seq_length}d}".format(**new_format_values) detected = detected % new_format_values return {'warning': { 'title': _("The sequence format has changed."), 'message': "%s\n\n%s" % (changed, detected) }} @api.depends('state') def _compute_payment_reference(self): for move in self.filtered(lambda m: ( m.state == 'posted' and m._auto_compute_invoice_reference() )): move.payment_reference = move._get_invoice_computed_reference() def _get_last_sequence_domain(self, relaxed=False): self.ensure_one() if not self.date or not self.journal_id: return "WHERE FALSE", {} where_string = "WHERE journal_id = %(journal_id)s AND name != '/'" param = {'journal_id': self.journal_id.id} if not relaxed: domain = [('journal_id', '=', self.journal_id.id), ('id', '!=', self.id or self._origin.id), ('name', 'not in', ('/', '', False))] if self.journal_id.refund_sequence: refund_types = ('out_refund', 'in_refund') domain += [('move_type', 'in' if self.move_type in refund_types else 'not in', refund_types)] reference_move_name = self.search(domain + [('date', '<=', self.date)], order='date desc', limit=1).name if not reference_move_name: reference_move_name = self.search(domain, order='date asc', limit=1).name sequence_number_reset = self._deduce_sequence_number_reset(reference_move_name) if sequence_number_reset == 'year': where_string += " AND date_trunc('year', date::timestamp without time zone) = date_trunc('year', %(date)s) " param['date'] = self.date param['anti_regex'] = re.sub(r"\?P<\w+>", "?:", self._sequence_monthly_regex.split('(?P<seq>')[0]) + '$' elif sequence_number_reset == 'month': where_string += " AND date_trunc('month', date::timestamp without time zone) = date_trunc('month', %(date)s) " param['date'] = self.date else: param['anti_regex'] = re.sub(r"\?P<\w+>", "?:", self._sequence_yearly_regex.split('(?P<seq>')[0]) + '$' if param.get('anti_regex') and not self.journal_id.sequence_override_regex: where_string += " AND sequence_prefix !~ %(anti_regex)s " if self.journal_id.refund_sequence: if self.move_type in ('out_refund', 'in_refund'): where_string += " AND move_type IN ('out_refund', 'in_refund') " else: where_string += " AND move_type NOT IN ('out_refund', 'in_refund') " return where_string, param def _get_starting_sequence(self): self.ensure_one() if self.journal_id.type == 'sale': starting_sequence = "%s/%04d/00000" % (self.journal_id.code, self.date.year) else: starting_sequence = "%s/%04d/%02d/0000" % (self.journal_id.code, self.date.year, self.date.month) if self.journal_id.refund_sequence and self.move_type in ('out_refund', 'in_refund'): starting_sequence = "R" + starting_sequence return starting_sequence @api.depends('move_type') def _compute_type_name(self): type_name_mapping = {k: v for k, v in self._fields['move_type']._description_selection(self.env)} replacements = {'out_invoice': _('Invoice'), 'out_refund': _('Credit Note')} for record in self: name = type_name_mapping[record.move_type] record.type_name = replacements.get(record.move_type, name) @api.depends('move_type') def _compute_invoice_filter_type_domain(self): for move in self: if move.is_sale_document(include_receipts=True): move.invoice_filter_type_domain = 'sale' elif move.is_purchase_document(include_receipts=True): move.invoice_filter_type_domain = 'purchase' else: move.invoice_filter_type_domain = False @api.depends('partner_id') def _compute_commercial_partner_id(self): for move in self: move.commercial_partner_id = move.partner_id.commercial_partner_id @api.depends('commercial_partner_id') def _compute_bank_partner_id(self): for move in self: if move.is_inbound(): move.bank_partner_id = move.company_id.partner_id else: move.bank_partner_id = move.commercial_partner_id @api.model def _get_invoice_in_payment_state(self): ''' Hook to give the state when the invoice becomes fully paid. This is necessary because the users working with only invoicing don't want to see the 'in_payment' state. Then, this method will be overridden in the accountant module to enable the 'in_payment' state. ''' return 'paid' @api.depends( 'line_ids.matched_debit_ids.debit_move_id.move_id.payment_id.is_matched', 'line_ids.matched_debit_ids.debit_move_id.move_id.line_ids.amount_residual', 'line_ids.matched_debit_ids.debit_move_id.move_id.line_ids.amount_residual_currency', 'line_ids.matched_credit_ids.credit_move_id.move_id.payment_id.is_matched', 'line_ids.matched_credit_ids.credit_move_id.move_id.line_ids.amount_residual', 'line_ids.matched_credit_ids.credit_move_id.move_id.line_ids.amount_residual_currency', 'line_ids.debit', 'line_ids.credit', 'line_ids.currency_id', 'line_ids.amount_currency', 'line_ids.amount_residual', 'line_ids.amount_residual_currency', 'line_ids.payment_id.state', 'line_ids.full_reconcile_id') def _compute_amount(self): in_invoices = self.filtered(lambda m: m.move_type == 'in_invoice') out_invoices = self.filtered(lambda m: m.move_type == 'out_invoice') entries = self.filtered(lambda m: m.move_type == 'entry') reversed_mapping = defaultdict(lambda: self.env['account.move']) if in_invoices or out_invoices or entries: for reverse_move in self.env['account.move'].search([ ('state', '=', 'posted'), '|', '|', '&', ('reversed_entry_id', 'in', in_invoices.ids), ('move_type', '=', 'in_refund'), '&', ('reversed_entry_id', 'in', out_invoices.ids), ('move_type', '=', 'out_refund'), '&', ('reversed_entry_id', 'in', entries.ids), ('move_type', '=', 'entry'), ]): reversed_mapping[reverse_move.reversed_entry_id] += reverse_move caba_mapping = defaultdict(lambda: self.env['account.move']) caba_company_ids = self.company_id.filtered(lambda c: c.tax_exigibility) if caba_company_ids: reverse_moves_ids = [move.id for moves in reversed_mapping.values() for move in moves] for caba_move in self.env['account.move'].search([ ('tax_cash_basis_origin_move_id', 'in', self.ids + reverse_moves_ids), ('state', '=', 'posted'), ('move_type', '=', 'entry'), ('company_id', 'in', caba_company_ids.ids) ]): caba_mapping[caba_move.tax_cash_basis_origin_move_id] += caba_move for move in self: if move.payment_state == 'invoicing_legacy': # invoicing_legacy state is set via SQL when setting setting field # invoicing_switch_threshold (defined in account_accountant). # The only way of going out of this state is through this setting, # so we don't recompute it here. move.payment_state = move.payment_state continue total_untaxed = 0.0 total_untaxed_currency = 0.0 total_tax = 0.0 total_tax_currency = 0.0 total_to_pay = 0.0 total_residual = 0.0 total_residual_currency = 0.0 total = 0.0 total_currency = 0.0 currencies = move._get_lines_onchange_currency().currency_id for line in move.line_ids: if move._payment_state_matters(): # === Invoices === if not line.exclude_from_invoice_tab: # Untaxed amount. total_untaxed += line.balance total_untaxed_currency += line.amount_currency total += line.balance total_currency += line.amount_currency elif line.tax_line_id: # Tax amount. total_tax += line.balance total_tax_currency += line.amount_currency total += line.balance total_currency += line.amount_currency elif line.account_id.user_type_id.type in ('receivable', 'payable'): # Residual amount. total_to_pay += line.balance total_residual += line.amount_residual total_residual_currency += line.amount_residual_currency else: # === Miscellaneous journal entry === if line.debit: total += line.balance total_currency += line.amount_currency if move.move_type == 'entry' or move.is_outbound(): sign = 1 else: sign = -1 move.amount_untaxed = sign * (total_untaxed_currency if len(currencies) == 1 else total_untaxed) move.amount_tax = sign * (total_tax_currency if len(currencies) == 1 else total_tax) move.amount_total = sign * (total_currency if len(currencies) == 1 else total) move.amount_residual = -sign * (total_residual_currency if len(currencies) == 1 else total_residual) move.amount_untaxed_signed = -total_untaxed move.amount_tax_signed = -total_tax move.amount_total_signed = abs(total) if move.move_type == 'entry' else -total move.amount_residual_signed = total_residual move.amount_total_in_currency_signed = abs(move.amount_total) if move.move_type == 'entry' else -(sign * move.amount_total) currency = currencies if len(currencies) == 1 else move.company_id.currency_id # Compute 'payment_state'. new_pmt_state = 'not_paid' if move.move_type != 'entry' else False if move._payment_state_matters() and move.state == 'posted': if currency.is_zero(move.amount_residual): reconciled_payments = move._get_reconciled_payments() if not reconciled_payments or all(payment.is_matched for payment in reconciled_payments): new_pmt_state = 'paid' else: new_pmt_state = move._get_invoice_in_payment_state() elif currency.compare_amounts(total_to_pay, total_residual) != 0: new_pmt_state = 'partial' if new_pmt_state == 'paid' and move.move_type in ('in_invoice', 'out_invoice', 'entry'): reverse_moves = reversed_mapping[move] caba_moves = caba_mapping[move] for reverse_move in reverse_moves: caba_moves |= caba_mapping[reverse_move] # We only set 'reversed' state in cas of 1 to 1 full reconciliation with a reverse entry; otherwise, we use the regular 'paid' state # We ignore potentials cash basis moves reconciled because the transition account of the tax is reconcilable reverse_moves_full_recs = reverse_moves.mapped('line_ids.full_reconcile_id') if reverse_moves_full_recs.mapped('reconciled_line_ids.move_id').filtered(lambda x: x not in (caba_moves + reverse_moves + reverse_moves_full_recs.mapped('exchange_move_id'))) == move: new_pmt_state = 'reversed' move.payment_state = new_pmt_state def _inverse_amount_total(self): for move in self: if len(move.line_ids) != 2 or move.is_invoice(include_receipts=True): continue to_write = [] amount_currency = abs(move.amount_total) balance = move.currency_id._convert(amount_currency, move.company_currency_id, move.company_id, move.date) for line in move.line_ids: if not line.currency_id.is_zero(balance - abs(line.balance)): to_write.append((1, line.id, { 'debit': line.balance > 0.0 and balance or 0.0, 'credit': line.balance < 0.0 and balance or 0.0, 'amount_currency': line.balance > 0.0 and amount_currency or -amount_currency, })) move.write({'line_ids': to_write}) def _get_domain_matching_suspense_moves(self): self.ensure_one() domain = self.env['account.move.line']._get_suspense_moves_domain() domain += ['|', ('partner_id', '=?', self.partner_id.id), ('partner_id', '=', False)] if self.is_inbound(): domain.append(('balance', '=', -self.amount_residual)) else: domain.append(('balance', '=', self.amount_residual)) return domain def _compute_has_matching_suspense_amount(self): for r in self: res = False if r.state == 'posted' and r.is_invoice() and r.payment_state == 'not_paid': domain = r._get_domain_matching_suspense_moves() #there are more than one but less than 5 suspense moves matching the residual amount if (0 < self.env['account.move.line'].search_count(domain) < 5): domain2 = [ ('payment_state', '=', 'not_paid'), ('state', '=', 'posted'), ('amount_residual', '=', r.amount_residual), ('move_type', '=', r.move_type)] #there are less than 5 other open invoices of the same type with the same residual if self.env['account.move'].search_count(domain2) < 5: res = True r.invoice_has_matching_suspense_amount = res @api.depends('partner_id', 'invoice_source_email', 'partner_id.name') def _compute_invoice_partner_display_info(self): for move in self: vendor_display_name = move.partner_id.display_name if not vendor_display_name: if move.invoice_source_email: vendor_display_name = _('@From: %(email)s', email=move.invoice_source_email) else: vendor_display_name = _('#Created by: %s', move.sudo().create_uid.name or self.env.user.name) move.invoice_partner_display_name = vendor_display_name @api.depends('currency_id') def _compute_display_inactive_currency_warning(self): for move in self.with_context(active_test=False): move.display_inactive_currency_warning = move.currency_id and not move.currency_id.active def _compute_payments_widget_to_reconcile_info(self): for move in self: move.invoice_outstanding_credits_debits_widget = json.dumps(False) move.invoice_has_outstanding = False if move.state != 'posted' \ or move.payment_state not in ('not_paid', 'partial') \ or not move.is_invoice(include_receipts=True): continue pay_term_lines = move.line_ids\ .filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) domain = [ ('account_id', 'in', pay_term_lines.account_id.ids), ('parent_state', '=', 'posted'), ('partner_id', '=', move.commercial_partner_id.id), ('reconciled', '=', False), '|', ('amount_residual', '!=', 0.0), ('amount_residual_currency', '!=', 0.0), ] payments_widget_vals = {'outstanding': True, 'content': [], 'move_id': move.id} if move.is_inbound(): domain.append(('balance', '<', 0.0)) payments_widget_vals['title'] = _('Outstanding credits') else: domain.append(('balance', '>', 0.0)) payments_widget_vals['title'] = _('Outstanding debits') for line in self.env['account.move.line'].search(domain): if line.currency_id == move.currency_id: # Same foreign currency. amount = abs(line.amount_residual_currency) else: # Different foreign currencies. amount = move.company_currency_id._convert( abs(line.amount_residual), move.currency_id, move.company_id, line.date, ) if move.currency_id.is_zero(amount): continue payments_widget_vals['content'].append({ 'journal_name': line.ref or line.move_id.name, 'amount': amount, 'currency': move.currency_id.symbol, 'id': line.id, 'move_id': line.move_id.id, 'position': move.currency_id.position, 'digits': [69, move.currency_id.decimal_places], 'date': fields.Date.to_string(line.date), 'account_payment_id': line.payment_id.id, }) if not payments_widget_vals['content']: continue move.invoice_outstanding_credits_debits_widget = json.dumps(payments_widget_vals) move.invoice_has_outstanding = True def _get_reconciled_info_JSON_values(self): self.ensure_one() reconciled_vals = [] for partial, amount, counterpart_line in self._get_reconciled_invoices_partials(): reconciled_vals.append(self._get_reconciled_vals(partial, amount, counterpart_line)) return reconciled_vals def _get_reconciled_vals(self, partial, amount, counterpart_line): if counterpart_line.move_id.ref: reconciliation_ref = '%s (%s)' % (counterpart_line.move_id.name, counterpart_line.move_id.ref) else: reconciliation_ref = counterpart_line.move_id.name return { 'name': counterpart_line.name, 'journal_name': counterpart_line.journal_id.name, 'amount': amount, 'currency': self.currency_id.symbol, 'digits': [69, self.currency_id.decimal_places], 'position': self.currency_id.position, 'date': counterpart_line.date, 'payment_id': counterpart_line.id, 'partial_id': partial.id, 'account_payment_id': counterpart_line.payment_id.id, 'payment_method_name': counterpart_line.payment_id.payment_method_line_id.name, 'move_id': counterpart_line.move_id.id, 'ref': reconciliation_ref, } @api.depends('move_type', 'line_ids.amount_residual') def _compute_payments_widget_reconciled_info(self): for move in self: payments_widget_vals = {'title': _('Less Payment'), 'outstanding': False, 'content': []} if move.state == 'posted' and move.is_invoice(include_receipts=True): payments_widget_vals['content'] = move._get_reconciled_info_JSON_values() if payments_widget_vals['content']: move.invoice_payments_widget = json.dumps(payments_widget_vals, default=date_utils.json_default) else: move.invoice_payments_widget = json.dumps(False) @api.depends('line_ids.amount_currency', 'line_ids.tax_base_amount', 'line_ids.tax_line_id', 'partner_id', 'currency_id', 'amount_total', 'amount_untaxed') def _compute_tax_totals_json(self): """ Computed field used for custom widget's rendering. Only set on invoices. """ for move in self: if not move.is_invoice(include_receipts=True): # Non-invoice moves don't support that field (because of multicurrency: all lines of the invoice share the same currency) move.tax_totals_json = None continue tax_lines_data = move._prepare_tax_lines_data_for_totals_from_invoice() move.tax_totals_json = json.dumps({ **self._get_tax_totals(move.partner_id, tax_lines_data, move.amount_total, move.amount_untaxed, move.currency_id), 'allow_tax_edition': move.is_purchase_document(include_receipts=True) and move.state == 'draft', }) def _prepare_tax_lines_data_for_totals_from_invoice(self, tax_line_id_filter=None, tax_ids_filter=None): """ Prepares data to be passed as tax_lines_data parameter of _get_tax_totals() from an invoice. NOTE: tax_line_id_filter and tax_ids_filter are used in l10n_latam to restrict the taxes with consider in the totals. :param tax_line_id_filter: a function(aml, tax) returning true if tax should be considered on tax move line aml. :param tax_ids_filter: a function(aml, taxes) returning true if taxes should be considered on base move line aml. :return: A list of dict in the format described in _get_tax_totals's tax_lines_data's docstring. """ self.ensure_one() tax_line_id_filter = tax_line_id_filter or (lambda aml, tax: True) tax_ids_filter = tax_ids_filter or (lambda aml, tax: True) balance_multiplicator = -1 if self.is_inbound() else 1 tax_lines_data = [] for line in self.line_ids: if line.tax_line_id and tax_line_id_filter(line, line.tax_line_id): tax_lines_data.append({ 'line_key': 'tax_line_%s' % line.id, 'tax_amount': line.amount_currency * balance_multiplicator, 'tax': line.tax_line_id, }) if line.tax_ids: for base_tax in line.tax_ids.flatten_taxes_hierarchy(): if tax_ids_filter(line, base_tax): tax_lines_data.append({ 'line_key': 'base_line_%s' % line.id, 'base_amount': line.amount_currency * balance_multiplicator, 'tax': base_tax, 'tax_affecting_base': line.tax_line_id, }) return tax_lines_data @api.model def _prepare_tax_lines_data_for_totals_from_object(self, object_lines, tax_results_function): """ Prepares data to be passed as tax_lines_data parameter of _get_tax_totals() from any object using taxes. This helper is intended for purchase.order and sale.order, as a common function centralizing their behavior. :param object_lines: A list of records corresponding to the sub-objects generating the tax totals (sale.order.line or purchase.order.line, for example) :param tax_results_function: A function to be called to get the results of the tax computation for a line in object_lines. It takes the object line as its only parameter and returns a dict in the same format as account.tax's compute_all (most probably after calling it with the right parameters). :return: A list of dict in the format described in _get_tax_totals's tax_lines_data's docstring. """ tax_lines_data = [] for line in object_lines: tax_results = tax_results_function(line) for tax_result in tax_results['taxes']: current_tax = self.env['account.tax'].browse(tax_result['id']) # Tax line tax_lines_data.append({ 'line_key': f"tax_line_{line.id}_{tax_result['id']}", 'tax_amount': tax_result['amount'], 'tax': current_tax, }) # Base for this tax line tax_lines_data.append({ 'line_key': 'base_line_%s' % line.id, 'base_amount': tax_results['total_excluded'], 'tax': current_tax, }) # Base for the taxes whose base is affected by this tax line if tax_result['tax_ids']: affected_taxes = self.env['account.tax'].browse(tax_result['tax_ids']) for affected_tax in affected_taxes: tax_lines_data.append({ 'line_key': 'affecting_base_line_%s_%s' % (line.id, tax_result['id']), 'base_amount': tax_result['amount'], 'tax': affected_tax, 'tax_affecting_base': current_tax, }) return tax_lines_data @api.model def _get_tax_totals(self, partner, tax_lines_data, amount_total, amount_untaxed, currency): """ Compute the tax totals for the provided data. :param partner: The partner to compute totals for :param tax_lines_data: All the data about the base and tax lines as a list of dictionaries. Each dictionary represents an amount that needs to be added to either a tax base or amount. A tax amount looks like: { 'line_key': unique identifier, 'tax_amount': the amount computed for this tax 'tax': the account.tax object this tax line was made from } For base amounts: { 'line_key': unique identifier, 'base_amount': the amount to add to the base of the tax 'tax': the tax basing itself on this amount 'tax_affecting_base': (optional key) the tax whose tax line is having the impact denoted by 'base_amount' on the base of the tax, in case of taxes affecting the base of subsequent ones. } :param amount_total: Total amount, with taxes. :param amount_untaxed: Total amount without taxes. :param currency: The currency in which the amounts are computed. :return: A dictionary in the following form: { 'amount_total': The total amount to be displayed on the document, including every total types. 'amount_untaxed': The untaxed amount to be displayed on the document. 'formatted_amount_total': Same as amount_total, but as a string formatted accordingly with partner's locale. 'formatted_amount_untaxed': Same as amount_untaxed, but as a string formatted accordingly with partner's locale. 'allow_tax_edition': True if the user should have the ability to manually edit the tax amounts by group to fix rounding errors. 'groups_by_subtotals': A dictionary formed liked {'subtotal': groups_data} Where total_type is a subtotal name defined on a tax group, or the default one: 'Untaxed Amount'. And groups_data is a list of dict in the following form: { 'tax_group_name': The name of the tax groups this total is made for. 'tax_group_amount': The total tax amount in this tax group. 'tax_group_base_amount': The base amount for this tax group. 'formatted_tax_group_amount': Same as tax_group_amount, but as a string formatted accordingly with partner's locale. 'formatted_tax_group_base_amount': Same as tax_group_base_amount, but as a string formatted accordingly with partner's locale. 'tax_group_id': The id of the tax group corresponding to this dict. 'group_key': A unique key identifying this total dict, } 'subtotals': A list of dictionaries in the following form, one for each subtotal in groups_by_subtotals' keys { 'name': The name of the subtotal 'amount': The total amount for this subtotal, summing all the tax groups belonging to preceding subtotals and the base amount 'formatted_amount': Same as amount, but as a string formatted accordingly with partner's locale. } } """ account_tax = self.env['account.tax'] grouped_taxes = defaultdict(lambda: defaultdict(lambda: {'base_amount': 0.0, 'tax_amount': 0.0, 'base_line_keys': set()})) subtotal_priorities = {} for line_data in tax_lines_data: tax_group = line_data['tax'].tax_group_id # Update subtotals priorities if tax_group.preceding_subtotal: subtotal_title = tax_group.preceding_subtotal new_priority = tax_group.sequence else: # When needed, the default subtotal is always the most prioritary subtotal_title = _("Untaxed Amount") new_priority = 0 if subtotal_title not in subtotal_priorities or new_priority < subtotal_priorities[subtotal_title]: subtotal_priorities[subtotal_title] = new_priority # Update tax data tax_group_vals = grouped_taxes[subtotal_title][tax_group] if 'base_amount' in line_data: # Base line if tax_group == line_data.get('tax_affecting_base', account_tax).tax_group_id: # In case the base has a tax_line_id belonging to the same group as the base tax, # the base for the group will be computed by the base tax's original line (the one with tax_ids and no tax_line_id) continue if line_data['line_key'] not in tax_group_vals['base_line_keys']: # If the base line hasn't been taken into account yet, at its amount to the base total. tax_group_vals['base_line_keys'].add(line_data['line_key']) tax_group_vals['base_amount'] += line_data['base_amount'] else: # Tax line tax_group_vals['tax_amount'] += line_data['tax_amount'] # Compute groups_by_subtotal groups_by_subtotal = {} for subtotal_title, groups in grouped_taxes.items(): groups_vals = [{ 'tax_group_name': group.name, 'tax_group_amount': amounts['tax_amount'], 'tax_group_base_amount': amounts['base_amount'], 'formatted_tax_group_amount': formatLang(self.env, amounts['tax_amount'], currency_obj=currency), 'formatted_tax_group_base_amount': formatLang(self.env, amounts['base_amount'], currency_obj=currency), 'tax_group_id': group.id, 'group_key': '%s-%s' %(subtotal_title, group.id), } for group, amounts in sorted(groups.items(), key=lambda l: l[0].sequence)] groups_by_subtotal[subtotal_title] = groups_vals # Compute subtotals subtotals_list = [] # List, so that we preserve their order previous_subtotals_tax_amount = 0 for subtotal_title in sorted((sub for sub in subtotal_priorities), key=lambda x: subtotal_priorities[x]): subtotal_value = amount_untaxed + previous_subtotals_tax_amount subtotals_list.append({ 'name': subtotal_title, 'amount': subtotal_value, 'formatted_amount': formatLang(self.env, subtotal_value, currency_obj=currency), }) subtotal_tax_amount = sum(group_val['tax_group_amount'] for group_val in groups_by_subtotal[subtotal_title]) previous_subtotals_tax_amount += subtotal_tax_amount # Assign json-formatted result to the field return { 'amount_total': amount_total, 'amount_untaxed': amount_untaxed, 'formatted_amount_total': formatLang(self.env, amount_total, currency_obj=currency), 'formatted_amount_untaxed': formatLang(self.env, amount_untaxed, currency_obj=currency), 'groups_by_subtotal': groups_by_subtotal, 'subtotals': subtotals_list, 'allow_tax_edition': False, } @api.depends('date', 'line_ids.debit', 'line_ids.credit', 'line_ids.tax_line_id', 'line_ids.tax_ids', 'line_ids.tax_tag_ids') def _compute_tax_lock_date_message(self): for move in self: invoice_date = move.invoice_date or fields.Date.context_today(move) accounting_date = move.date or fields.Date.context_today(move) affects_tax_report = move._affect_tax_report() lock_dates = move._get_violated_lock_dates(accounting_date, affects_tax_report) if lock_dates: accounting_date = move._get_accounting_date(invoice_date, affects_tax_report) lock_date, lock_type = lock_dates[-1] tax_lock_date_message = _( "The accounting date being set prior to the %(lock_type)s lock date %(lock_date)s," " it will be changed to %(accounting_date)s upon posting.", lock_type=lock_type, lock_date=format_date(move.env, lock_date), accounting_date=format_date(move.env, accounting_date)) for lock_date, lock_type in lock_dates[:-1]: tax_lock_date_message += _(" The %(lock_type)s lock date is set on %(lock_date)s.", lock_type=lock_type, lock_date=format_date(move.env, lock_date)) move.tax_lock_date_message = tax_lock_date_message else: move.tax_lock_date_message = False @api.depends('line_ids.account_id.internal_type') def _compute_always_tax_exigible(self): for record in self: # We need to check is_invoice as well because always_tax_exigible is used to # set the tags as well, during the encoding. So, if no receivable/payable # line has been created yet, the invoice would be detected as always exigible, # and set the tags on some lines ; which would be wrong. record.always_tax_exigible = not record.is_invoice(True) \ and not record._collect_tax_cash_basis_values() @api.depends('restrict_mode_hash_table', 'state') def _compute_show_reset_to_draft_button(self): for move in self: move.show_reset_to_draft_button = not move.restrict_mode_hash_table and move.state in ('posted', 'cancel') @api.depends('company_id.account_fiscal_country_id', 'fiscal_position_id.country_id', 'fiscal_position_id.foreign_vat') def _compute_tax_country_id(self): for record in self: if record.fiscal_position_id.foreign_vat: record.tax_country_id = record.fiscal_position_id.country_id else: record.tax_country_id = record.company_id.account_fiscal_country_id @api.depends('tax_country_id.code') def _compute_tax_country_code(self): for record in self: record.tax_country_code = record.tax_country_id.code # ------------------------------------------------------------------------- # BUSINESS MODELS SYNCHRONIZATION # ------------------------------------------------------------------------- def _synchronize_business_models(self, changed_fields): ''' Ensure the consistency between: account.payment & account.move account.bank.statement.line & account.move The idea is to call the method performing the synchronization of the business models regarding their related journal entries. To avoid cycling, the 'skip_account_move_synchronization' key is used through the context. :param changed_fields: A set containing all modified fields on account.move. ''' if self._context.get('skip_account_move_synchronization'): return self_sudo = self.sudo() self_sudo.payment_id._synchronize_from_moves(changed_fields) self_sudo.statement_line_id._synchronize_from_moves(changed_fields) # ------------------------------------------------------------------------- # CONSTRAINT METHODS # ------------------------------------------------------------------------- @api.constrains('name', 'journal_id', 'state') def _check_unique_sequence_number(self): moves = self.filtered(lambda move: move.state == 'posted') if not moves: return self.flush(['name', 'journal_id', 'move_type', 'state']) # /!\ Computed stored fields are not yet inside the database. self._cr.execute(''' SELECT move2.id, move2.name FROM account_move move INNER JOIN account_move move2 ON move2.name = move.name AND move2.journal_id = move.journal_id AND move2.move_type = move.move_type AND move2.id != move.id WHERE move.id IN %s AND move2.state = 'posted' ''', [tuple(moves.ids)]) res = self._cr.fetchall() if res: raise ValidationError(_('Posted journal entry must have an unique sequence number per company.\n' 'Problematic numbers: %s\n') % ', '.join(r[1] for r in res)) @api.constrains('ref', 'move_type', 'partner_id', 'journal_id', 'invoice_date', 'state') def _check_duplicate_supplier_reference(self): moves = self.filtered(lambda move: move.state == 'posted' and move.is_purchase_document() and move.ref) if not moves: return self.env["account.move"].flush([ "ref", "move_type", "invoice_date", "journal_id", "company_id", "partner_id", "commercial_partner_id", ]) self.env["account.journal"].flush(["company_id"]) self.env["res.partner"].flush(["commercial_partner_id"]) # /!\ Computed stored fields are not yet inside the database. self._cr.execute(''' SELECT move2.id FROM account_move move JOIN account_journal journal ON journal.id = move.journal_id JOIN res_partner partner ON partner.id = move.partner_id INNER JOIN account_move move2 ON move2.ref = move.ref AND move2.company_id = journal.company_id AND move2.commercial_partner_id = partner.commercial_partner_id AND move2.move_type = move.move_type AND (move.invoice_date is NULL OR move2.invoice_date = move.invoice_date) AND move2.id != move.id WHERE move.id IN %s ''', [tuple(moves.ids)]) duplicated_moves = self.browse([r[0] for r in self._cr.fetchall()]) if duplicated_moves: raise ValidationError(_('Duplicated vendor reference detected. You probably encoded twice the same vendor bill/credit note:\n%s') % "\n".join( duplicated_moves.mapped(lambda m: "%(partner)s - %(ref)s - %(date)s" % { 'ref': m.ref, 'partner': m.partner_id.display_name, 'date': format_date(self.env, m.invoice_date), }) )) def _check_balanced(self): ''' Assert the move is fully balanced debit = credit. An error is raised if it's not the case. ''' moves = self.filtered(lambda move: move.line_ids) if not moves: return # /!\ As this method is called in create / write, we can't make the assumption the computed stored fields # are already done. Then, this query MUST NOT depend of computed stored fields (e.g. balance). # It happens as the ORM makes the create with the 'no_recompute' statement. self.env['account.move.line'].flush(self.env['account.move.line']._fields) self.env['account.move'].flush(['journal_id']) self._cr.execute(''' SELECT line.move_id, ROUND(SUM(line.debit - line.credit), currency.decimal_places) FROM account_move_line line JOIN account_move move ON move.id = line.move_id JOIN account_journal journal ON journal.id = move.journal_id JOIN res_company company ON company.id = journal.company_id JOIN res_currency currency ON currency.id = company.currency_id WHERE line.move_id IN %s GROUP BY line.move_id, currency.decimal_places HAVING ROUND(SUM(line.debit - line.credit), currency.decimal_places) != 0.0; ''', [tuple(self.ids)]) query_res = self._cr.fetchall() if query_res: ids = [res[0] for res in query_res] sums = [res[1] for res in query_res] raise UserError(_("Cannot create unbalanced journal entry. Ids: %s\nDifferences debit - credit: %s") % (ids, sums)) def _check_fiscalyear_lock_date(self): for move in self: lock_date = move.company_id._get_user_fiscal_lock_date() if move.date <= lock_date: if self.user_has_groups('account.group_account_manager'): message = _("You cannot add/modify entries prior to and inclusive of the lock date %s.", format_date(self.env, lock_date)) else: message = _("You cannot add/modify entries prior to and inclusive of the lock date %s. Check the company settings or ask someone with the 'Adviser' role", format_date(self.env, lock_date)) raise UserError(message) return True @api.constrains('move_type', 'journal_id') def _check_journal_type(self): for record in self: journal_type = record.journal_id.type if record.is_sale_document() and journal_type != 'sale' or record.is_purchase_document() and journal_type != 'purchase': raise ValidationError(_("The chosen journal has a type that is not compatible with your invoice type. Sales operations should go to 'sale' journals, and purchase operations to 'purchase' ones.")) @api.constrains('line_ids', 'fiscal_position_id', 'company_id') def _validate_taxes_country(self): """ By playing with the fiscal position in the form view, it is possible to keep taxes on the invoices from a different country than the one allowed by the fiscal country or the fiscal position. This contrains ensure such account.move cannot be kept, as they could generate inconsistencies in the reports. """ self._compute_tax_country_id() # We need to ensure this field has been computed, as we use it in our check for record in self: amls = record.line_ids impacted_countries = amls.tax_ids.country_id | amls.tax_line_id.country_id | amls.tax_tag_ids.country_id if impacted_countries and impacted_countries != record.tax_country_id: if record.fiscal_position_id and impacted_countries != record.fiscal_position_id.country_id: raise ValidationError(_("This entry contains taxes that are not compatible with your fiscal position. Check the country set in fiscal position and in your tax configuration.")) raise ValidationError(_("This entry contains one or more taxes that are incompatible with your fiscal country. Check company fiscal country in the settings and tax country in taxes configuration.")) # ------------------------------------------------------------------------- # LOW-LEVEL METHODS # ------------------------------------------------------------------------- def _move_autocomplete_invoice_lines_values(self): ''' This method recomputes dynamic lines on the current journal entry that include taxes, cash rounding and payment terms lines. ''' self.ensure_one() invoice_lines = self.line_ids.filtered(lambda x: not x.exclude_from_invoice_tab and not x.display_type and not x._origin) cached_vals_list = [dict(x._cache) for x in invoice_lines] for cached_vals, line in zip(cached_vals_list, invoice_lines): # Shortcut to load the demo data. # Doing line.account_id triggers a default_get(['account_id']) that could returns a result. # A section / note must not have an account_id set. if not line._cache.get('account_id') and not line._origin: line.account_id = line._get_computed_account() or self.journal_id.default_account_id if line.product_id and not line._cache.get('name'): line.name = line._get_computed_name() # Compute the account before the partner_id # In case account_followup is installed # Setting the partner will get the account_id in cache # If the account_id is not in cache, it will trigger the default value # Which is wrong in some case # It's better to set the account_id before the partner_id # Ensure related fields are well copied. if line.partner_id != self.partner_id.commercial_partner_id: line.partner_id = self.partner_id.commercial_partner_id line.date = self.date line.recompute_tax_line = True line.currency_id = self.currency_id for k, v in cached_vals.items(): field = line._fields[k] if field.compute and not field.readonly: line[k] = v self.line_ids._onchange_price_subtotal() self._recompute_dynamic_lines(recompute_all_taxes=True) values = self._convert_to_write(self._cache) values.pop('invoice_line_ids', None) return values @api.model def _move_autocomplete_invoice_lines_create(self, vals_list): ''' During the create of an account.move with only 'invoice_line_ids' set and not 'line_ids', this method is called to auto compute accounting lines of the invoice. In that case, accounts will be retrieved and taxes, cash rounding and payment terms will be computed. At the end, the values will contains all accounting lines in 'line_ids' and the moves should be balanced. :param vals_list: The list of values passed to the 'create' method. :return: Modified list of values. ''' new_vals_list = [] for vals in vals_list: vals = dict(vals) if vals.get('invoice_date') and not vals.get('date'): vals['date'] = vals['invoice_date'] default_move_type = vals.get('move_type') or self._context.get('default_move_type') ctx_vals = {} if default_move_type: ctx_vals['default_move_type'] = default_move_type if vals.get('journal_id'): ctx_vals['default_journal_id'] = vals['journal_id'] # reorder the companies in the context so that the company of the journal # (which will be the company of the move) is the main one, ensuring all # property fields are read with the correct company journal_company = self.env['account.journal'].browse(vals['journal_id']).company_id allowed_companies = self._context.get('allowed_company_ids', journal_company.ids) reordered_companies = sorted(allowed_companies, key=lambda cid: cid != journal_company.id) ctx_vals['allowed_company_ids'] = reordered_companies self_ctx = self.with_context(**ctx_vals) vals = self_ctx._add_missing_default_values(vals) is_invoice = vals.get('move_type') in self.get_invoice_types(include_receipts=True) if 'line_ids' in vals: vals.pop('invoice_line_ids', None) new_vals_list.append(vals) continue if is_invoice and 'invoice_line_ids' in vals: vals['line_ids'] = vals['invoice_line_ids'] vals.pop('invoice_line_ids', None) move = self_ctx.new(vals) new_vals_list.append(move._move_autocomplete_invoice_lines_values()) return new_vals_list def _move_autocomplete_invoice_lines_write(self, vals): ''' During the write of an account.move with only 'invoice_line_ids' set and not 'line_ids', this method is called to auto compute accounting lines of the invoice. In that case, accounts will be retrieved and taxes, cash rounding and payment terms will be computed. At the end, the values will contains all accounting lines in 'line_ids' and the moves should be balanced. :param vals_list: A python dict representing the values to write. :return: True if the auto-completion did something, False otherwise. ''' enable_autocomplete = 'invoice_line_ids' in vals and 'line_ids' not in vals and True or False if not enable_autocomplete: return False vals['line_ids'] = vals.pop('invoice_line_ids') for invoice in self: invoice_new = invoice.with_context( default_move_type=invoice.move_type, default_journal_id=invoice.journal_id.id, default_partner_id=invoice.partner_id.id, default_currency_id=invoice.currency_id.id, ).new(origin=invoice) invoice_new.update(vals) values = invoice_new._move_autocomplete_invoice_lines_values() values.pop('invoice_line_ids', None) invoice.write(values) return True @api.returns('self', lambda value: value.id) def copy(self, default=None): default = dict(default or {}) if (fields.Date.to_date(default.get('date')) or self.date) <= self.company_id._get_user_fiscal_lock_date(): default['date'] = self.company_id._get_user_fiscal_lock_date() + timedelta(days=1) if self.move_type == 'entry': default['partner_id'] = False if not self.journal_id.active: default['journal_id'] = self.with_context( default_company_id=self.company_id.id, default_move_type=self.move_type, )._get_default_journal().id copied_am = super().copy(default) copied_am._message_log(body=_( 'This entry has been duplicated from <a href=# data-oe-model=account.move data-oe-id=%(id)d>%(title)s</a>', id=self.id, title=html_escape(self.display_name) )) if copied_am.is_invoice(include_receipts=True): # Make sure to recompute payment terms. This could be necessary if the date is different for example. # Also, this is necessary when creating a credit note because the current invoice is copied. if copied_am.currency_id != self.company_id.currency_id: copied_am.with_context(check_move_validity=False)._onchange_currency() copied_am._check_balanced() copied_am._recompute_payment_terms_lines() return copied_am @api.model_create_multi def create(self, vals_list): # OVERRIDE if any('state' in vals and vals.get('state') == 'posted' for vals in vals_list): raise UserError(_('You cannot create a move already in the posted state. Please create a draft move and post it after.')) vals_list = self._move_autocomplete_invoice_lines_create(vals_list) return super(AccountMove, self).create(vals_list) def write(self, vals): for move in self: if (move.restrict_mode_hash_table and move.state == "posted" and set(vals).intersection(move._get_integrity_hash_fields())): raise UserError(_("You cannot edit the following fields due to restrict mode being activated on the journal: %s.") % ', '.join(move._get_integrity_hash_fields())) if (move.restrict_mode_hash_table and move.inalterable_hash and 'inalterable_hash' in vals) or (move.secure_sequence_number and 'secure_sequence_number' in vals): raise UserError(_('You cannot overwrite the values ensuring the inalterability of the accounting.')) if (move.posted_before and 'journal_id' in vals and move.journal_id.id != vals['journal_id']): raise UserError(_('You cannot edit the journal of an account move if it has been posted once.')) if (move.name and move.name != '/' and move.sequence_number not in (0, 1) and 'journal_id' in vals and move.journal_id.id != vals['journal_id']): raise UserError(_('You cannot edit the journal of an account move if it already has a sequence number assigned.')) # You can't change the date or name of a move being inside a locked period. if move.state == "posted" and ( ('name' in vals and move.name != vals['name']) or ('date' in vals and move.date != vals['date']) ): move._check_fiscalyear_lock_date() move.line_ids._check_tax_lock_date() # You can't post subtract a move to a locked period. if 'state' in vals and move.state == 'posted' and vals['state'] != 'posted': move._check_fiscalyear_lock_date() move.line_ids._check_tax_lock_date() if move.journal_id.sequence_override_regex and vals.get('name') and vals['name'] != '/' and not re.match(move.journal_id.sequence_override_regex, vals['name']): if not self.env.user.has_group('account.group_account_manager'): raise UserError(_('The Journal Entry sequence is not conform to the current format. Only the Advisor can change it.')) move.journal_id.sequence_override_regex = False if self._move_autocomplete_invoice_lines_write(vals): res = True else: vals.pop('invoice_line_ids', None) res = super(AccountMove, self.with_context(check_move_validity=False, skip_account_move_synchronization=True)).write(vals) # You can't change the date of a not-locked move to a locked period. # You can't post a new journal entry inside a locked period. if 'date' in vals or 'state' in vals: posted_move = self.filtered(lambda m: m.state == 'posted') posted_move._check_fiscalyear_lock_date() posted_move.line_ids._check_tax_lock_date() if ('state' in vals and vals.get('state') == 'posted'): for move in self.filtered(lambda m: m.restrict_mode_hash_table and not(m.secure_sequence_number or m.inalterable_hash)).sorted(lambda m: (m.date, m.ref or '', m.id)): new_number = move.journal_id.secure_sequence_id.next_by_id() vals_hashing = {'secure_sequence_number': new_number, 'inalterable_hash': move._get_new_hash(new_number)} res |= super(AccountMove, move).write(vals_hashing) # Ensure the move is still well balanced. if 'line_ids' in vals and self._context.get('check_move_validity', True): self._check_balanced() self._synchronize_business_models(set(vals.keys())) return res @api.ondelete(at_uninstall=False) def _unlink_forbid_parts_of_chain(self): """ Moves with a sequence number can only be deleted if they are the last element of a chain of sequence. If they are not, deleting them would create a gap. If the user really wants to do this, he still can explicitly empty the 'name' field of the move; but we discourage that practice. """ if not self._context.get('force_delete') and not self.filtered(lambda move: move.name != '/')._is_end_of_seq_chain(): raise UserError(_( "You cannot delete this entry, as it has already consumed a sequence number and is not the last one in the chain. You should probably revert it instead." )) def unlink(self): self.line_ids.unlink() return super(AccountMove, self).unlink() @api.depends('name', 'state') def name_get(self): result = [] for move in self: if self._context.get('name_groupby'): name = '**%s**, %s' % (format_date(self.env, move.date), move._get_move_display_name()) if move.ref: name += ' (%s)' % move.ref if move.partner_id.name: name += ' - %s' % move.partner_id.name else: name = move._get_move_display_name(show_ref=True) result.append((move.id, name)) return result def _creation_subtype(self): # OVERRIDE if self.move_type in ('out_invoice', 'out_receipt'): return self.env.ref('account.mt_invoice_created') else: return super(AccountMove, self)._creation_subtype() def _track_subtype(self, init_values): # OVERRIDE to add custom subtype depending of the state. self.ensure_one() if not self.is_invoice(include_receipts=True): if self.payment_id and 'state' in init_values: self.payment_id.message_track(['state'], {self.payment_id.id: init_values}) return super(AccountMove, self)._track_subtype(init_values) if 'payment_state' in init_values and self.payment_state == 'paid': return self.env.ref('account.mt_invoice_paid') elif 'state' in init_values and self.state == 'posted' and self.is_sale_document(include_receipts=True): return self.env.ref('account.mt_invoice_validated') return super(AccountMove, self)._track_subtype(init_values) def _creation_message(self): # OVERRIDE if not self.is_invoice(include_receipts=True): return super()._creation_message() return { 'out_invoice': _('Invoice Created'), 'out_refund': _('Credit Note Created'), 'in_invoice': _('Vendor Bill Created'), 'in_refund': _('Refund Created'), 'out_receipt': _('Sales Receipt Created'), 'in_receipt': _('Purchase Receipt Created'), }[self.move_type] # ------------------------------------------------------------------------- # RECONCILIATION METHODS # ------------------------------------------------------------------------- def _collect_tax_cash_basis_values(self): ''' Collect all information needed to create the tax cash basis journal entries: - Determine if a tax cash basis journal entry is needed. - Compute the lines to be processed and the amounts needed to compute a percentage. :return: A dictionary: * move: The current account.move record passed as parameter. * to_process_lines: A tuple (caba_treatment, line) where: - caba_treatment is either 'tax' or 'base', depending on what should be considered on the line when generating the caba entry. For example, a line with tax_ids=caba and tax_line_id=non_caba will have a 'base' caba treatment, as we only want to treat its base part in the caba entry (the tax part is already exigible on the invoice) - line is an account.move.line record being not exigible on the tax report. * currency: The currency on which the percentage has been computed. * total_balance: sum(payment_term_lines.mapped('balance'). * total_residual: sum(payment_term_lines.mapped('amount_residual'). * total_amount_currency: sum(payment_term_lines.mapped('amount_currency'). * total_residual_currency: sum(payment_term_lines.mapped('amount_residual_currency'). * is_fully_paid: A flag indicating the current move is now fully paid. ''' self.ensure_one() values = { 'move': self, 'to_process_lines': [], 'total_balance': 0.0, 'total_residual': 0.0, 'total_amount_currency': 0.0, 'total_residual_currency': 0.0, } currencies = set() has_term_lines = False for line in self.line_ids: if line.account_internal_type in ('receivable', 'payable'): sign = 1 if line.balance > 0.0 else -1 currencies.add(line.currency_id) has_term_lines = True values['total_balance'] += sign * line.balance values['total_residual'] += sign * line.amount_residual values['total_amount_currency'] += sign * line.amount_currency values['total_residual_currency'] += sign * line.amount_residual_currency elif line.tax_line_id.tax_exigibility == 'on_payment': values['to_process_lines'].append(('tax', line)) currencies.add(line.currency_id) elif 'on_payment' in line.tax_ids.flatten_taxes_hierarchy().mapped('tax_exigibility'): values['to_process_lines'].append(('base', line)) currencies.add(line.currency_id) if not values['to_process_lines'] or not has_term_lines: return None # Compute the currency on which made the percentage. if len(currencies) == 1: values['currency'] = list(currencies)[0] else: # Don't support the case where there is multiple involved currencies. return None # Determine whether the move is now fully paid. values['is_fully_paid'] = self.company_id.currency_id.is_zero(values['total_residual']) \ or values['currency'].is_zero(values['total_residual_currency']) return values # ------------------------------------------------------------------------- # BUSINESS METHODS # ------------------------------------------------------------------------- @api.model def get_invoice_types(self, include_receipts=False): return ['out_invoice', 'out_refund', 'in_refund', 'in_invoice'] + (include_receipts and ['out_receipt', 'in_receipt'] or []) def _payment_state_matters(self): ''' Determines when new_pmt_state must be upated. Method created to allow overrides. :return: Boolean ''' self.ensure_one() return self.is_invoice(include_receipts=True) def is_invoice(self, include_receipts=False): return self.move_type in self.get_invoice_types(include_receipts) @api.model def get_sale_types(self, include_receipts=False): return ['out_invoice', 'out_refund'] + (include_receipts and ['out_receipt'] or []) def is_sale_document(self, include_receipts=False): return self.move_type in self.get_sale_types(include_receipts) @api.model def get_purchase_types(self, include_receipts=False): return ['in_invoice', 'in_refund'] + (include_receipts and ['in_receipt'] or []) def is_purchase_document(self, include_receipts=False): return self.move_type in self.get_purchase_types(include_receipts) @api.model def get_inbound_types(self, include_receipts=True): return ['out_invoice', 'in_refund'] + (include_receipts and ['out_receipt'] or []) def is_inbound(self, include_receipts=True): return self.move_type in self.get_inbound_types(include_receipts) @api.model def get_outbound_types(self, include_receipts=True): return ['in_invoice', 'out_refund'] + (include_receipts and ['in_receipt'] or []) def is_outbound(self, include_receipts=True): return self.move_type in self.get_outbound_types(include_receipts) def _affect_tax_report(self): return any(line._affect_tax_report() for line in self.line_ids) def _get_invoice_reference_euro_invoice(self): """ This computes the reference based on the RF Creditor Reference. The data of the reference is the database id number of the invoice. For instance, if an invoice is issued with id 43, the check number is 07 so the reference will be 'RF07 43'. """ self.ensure_one() base = self.id check_digits = calc_check_digits('{}RF'.format(base)) reference = 'RF{} {}'.format(check_digits, " ".join(["".join(x) for x in zip_longest(*[iter(str(base))]*4, fillvalue="")])) return reference def _get_invoice_reference_euro_partner(self): """ This computes the reference based on the RF Creditor Reference. The data of the reference is the user defined reference of the partner or the database id number of the parter. For instance, if an invoice is issued for the partner with internal reference 'food buyer 654', the digits will be extracted and used as the data. This will lead to a check number equal to 00 and the reference will be 'RF00 654'. If no reference is set for the partner, its id in the database will be used. """ self.ensure_one() partner_ref = self.partner_id.ref partner_ref_nr = re.sub('\D', '', partner_ref or '')[-21:] or str(self.partner_id.id)[-21:] partner_ref_nr = partner_ref_nr[-21:] check_digits = calc_check_digits('{}RF'.format(partner_ref_nr)) reference = 'RF{} {}'.format(check_digits, " ".join(["".join(x) for x in zip_longest(*[iter(partner_ref_nr)]*4, fillvalue="")])) return reference def _get_invoice_reference_odoo_invoice(self): """ This computes the reference based on the Odoo format. We simply return the number of the invoice, defined on the journal sequence. """ self.ensure_one() return self.name def _get_invoice_reference_odoo_partner(self): """ This computes the reference based on the Odoo format. The data used is the reference set on the partner or its database id otherwise. For instance if the reference of the customer is 'dumb customer 97', the reference will be 'CUST/dumb customer 97'. """ ref = self.partner_id.ref or str(self.partner_id.id) prefix = _('CUST') return '%s/%s' % (prefix, ref) def _get_invoice_computed_reference(self): self.ensure_one() if self.journal_id.invoice_reference_type == 'none': return '' else: ref_function = getattr(self, '_get_invoice_reference_{}_{}'.format(self.journal_id.invoice_reference_model, self.journal_id.invoice_reference_type)) if ref_function: return ref_function() else: raise UserError(_('The combination of reference model and reference type on the journal is not implemented')) def _get_move_display_name(self, show_ref=False): ''' Helper to get the display name of an invoice depending of its type. :param show_ref: A flag indicating of the display name must include or not the journal entry reference. :return: A string representing the invoice. ''' self.ensure_one() name = '' if self.state == 'draft': name += { 'out_invoice': _('Draft Invoice'), 'out_refund': _('Draft Credit Note'), 'in_invoice': _('Draft Bill'), 'in_refund': _('Draft Vendor Credit Note'), 'out_receipt': _('Draft Sales Receipt'), 'in_receipt': _('Draft Purchase Receipt'), 'entry': _('Draft Entry'), }[self.move_type] name += ' ' if not self.name or self.name == '/': name += '(* %s)' % str(self.id) else: name += self.name return name + (show_ref and self.ref and ' (%s%s)' % (self.ref[:50], '...' if len(self.ref) > 50 else '') or '') def _get_invoice_delivery_partner_id(self): ''' Hook allowing to retrieve the right delivery address depending of installed modules. :return: A res.partner record's id representing the delivery address. ''' self.ensure_one() return self.partner_id.address_get(['delivery'])['delivery'] def _get_reconciled_payments(self): """Helper used to retrieve the reconciled payments on this journal entry""" reconciled_lines = self.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) reconciled_amls = reconciled_lines.mapped('matched_debit_ids.debit_move_id') + \ reconciled_lines.mapped('matched_credit_ids.credit_move_id') return reconciled_amls.move_id.payment_id def _get_reconciled_statement_lines(self): """Helper used to retrieve the reconciled payments on this journal entry""" reconciled_lines = self.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) reconciled_amls = reconciled_lines.mapped('matched_debit_ids.debit_move_id') + \ reconciled_lines.mapped('matched_credit_ids.credit_move_id') return reconciled_amls.move_id.statement_line_id def _get_reconciled_invoices(self): """Helper used to retrieve the reconciled payments on this journal entry""" reconciled_lines = self.line_ids.filtered(lambda line: line.account_id.user_type_id.type in ('receivable', 'payable')) reconciled_amls = reconciled_lines.mapped('matched_debit_ids.debit_move_id') + \ reconciled_lines.mapped('matched_credit_ids.credit_move_id') return reconciled_amls.move_id.filtered(lambda move: move.is_invoice(include_receipts=True)) def _get_reconciled_invoices_partials(self): ''' Helper to retrieve the details about reconciled invoices. :return A list of tuple (partial, amount, invoice_line). ''' self.ensure_one() pay_term_lines = self.line_ids\ .filtered(lambda line: line.account_internal_type in ('receivable', 'payable')) invoice_partials = [] for partial in pay_term_lines.matched_debit_ids: invoice_partials.append((partial, partial.credit_amount_currency, partial.debit_move_id)) for partial in pay_term_lines.matched_credit_ids: invoice_partials.append((partial, partial.debit_amount_currency, partial.credit_move_id)) return invoice_partials def _reverse_move_vals(self, default_values, cancel=True): ''' Reverse values passed as parameter being the copied values of the original journal entry. For example, debit / credit must be switched. The tax lines must be edited in case of refunds. :param default_values: A copy_date of the original journal entry. :param cancel: A flag indicating the reverse is made to cancel the original journal entry. :return: The updated default_values. ''' self.ensure_one() def compute_tax_repartition_lines_mapping(move_vals): ''' Computes and returns a mapping between the current repartition lines to the new expected one. :param move_vals: The newly created invoice as a python dictionary to be passed to the 'create' method. :return: A map invoice_repartition_line => refund_repartition_line. ''' # invoice_repartition_line => refund_repartition_line mapping = {} for line_command in move_vals.get('line_ids', []): line_vals = line_command[2] # (0, 0, {...}) if line_vals.get('tax_line_id'): # Tax line. tax_ids = [line_vals['tax_line_id']] elif line_vals.get('tax_ids') and line_vals['tax_ids'][0][2]: # Base line. tax_ids = line_vals['tax_ids'][0][2] else: continue for tax in self.env['account.tax'].browse(tax_ids).flatten_taxes_hierarchy(): for inv_rep_line, ref_rep_line in zip(tax.invoice_repartition_line_ids, tax.refund_repartition_line_ids): mapping[inv_rep_line] = ref_rep_line return mapping move_vals = self.with_context(include_business_fields=True).copy_data(default=default_values)[0] is_refund = False if move_vals['move_type'] in ('out_refund', 'in_refund'): is_refund = True elif move_vals['move_type'] == 'entry': base_lines = self.line_ids.filtered(lambda line: line.tax_ids) tax_type = set(base_lines.tax_ids.mapped('type_tax_use')) if tax_type == {'sale'} and sum(base_lines.mapped('debit')) == 0: is_refund = True elif tax_type == {'purchase'} and sum(base_lines.mapped('credit')) == 0: is_refund = True tax_repartition_lines_mapping = compute_tax_repartition_lines_mapping(move_vals) if is_refund else {} for line_command in move_vals.get('line_ids', []): line_vals = line_command[2] # (0, 0, {...}) # ==== Inverse debit / credit / amount_currency ==== amount_currency = -line_vals.get('amount_currency', 0.0) balance = line_vals['credit'] - line_vals['debit'] if 'tax_tag_invert' in line_vals and not self.tax_cash_basis_origin_move_id: # This is an editable computed field; we want to it recompute itself del line_vals['tax_tag_invert'] line_vals.update({ 'amount_currency': amount_currency, 'debit': balance > 0.0 and balance or 0.0, 'credit': balance < 0.0 and -balance or 0.0, }) if not is_refund or self.tax_cash_basis_origin_move_id: # We don't map tax repartition for non-refund operations, nor for cash basis entries. # Indeed, cancelling a cash basis entry usually happens when unreconciling and invoice, # in which case we always want the reverse entry to totally cancel the original one, keeping the same accounts, # tags and repartition lines continue # ==== Map tax repartition lines ==== if line_vals.get('tax_repartition_line_id'): # Tax line. invoice_repartition_line = self.env['account.tax.repartition.line'].browse(line_vals['tax_repartition_line_id']) # CABA taxes should not generate tax grids on reverse move. if invoice_repartition_line.invoice_tax_id.tax_exigibility == 'on_payment': continue if invoice_repartition_line not in tax_repartition_lines_mapping: raise UserError(_("It seems that the taxes have been modified since the creation of the journal entry. You should create the credit note manually instead.")) refund_repartition_line = tax_repartition_lines_mapping[invoice_repartition_line] # Find the right account. account_id = self.env['account.move.line']._get_default_tax_account(refund_repartition_line).id if not account_id: if not invoice_repartition_line.account_id: # Keep the current account as the current one comes from the base line. account_id = line_vals['account_id'] else: tax = invoice_repartition_line.invoice_tax_id base_line = self.line_ids.filtered(lambda line: tax in line.tax_ids.flatten_taxes_hierarchy())[0] account_id = base_line.account_id.id tags = refund_repartition_line.tag_ids if line_vals.get('tax_ids'): subsequent_taxes = self.env['account.tax'].browse(line_vals['tax_ids'][0][2]) tags += subsequent_taxes.refund_repartition_line_ids.filtered(lambda x: x.repartition_type == 'base').tag_ids line_vals.update({ 'tax_repartition_line_id': refund_repartition_line.id, 'account_id': account_id, 'tax_tag_ids': [(6, 0, tags.ids)], }) elif line_vals.get('tax_ids') and line_vals['tax_ids'][0][2]: # Base line. taxes = self.env['account.tax'].browse(line_vals['tax_ids'][0][2]).flatten_taxes_hierarchy() # CABA taxes should not generate tax grids on reverse move. taxes = taxes.filtered(lambda t: t.tax_exigibility != 'on_payment') if not taxes: continue invoice_repartition_lines = taxes\ .mapped('invoice_repartition_line_ids')\ .filtered(lambda line: line.repartition_type == 'base') refund_repartition_lines = invoice_repartition_lines\ .mapped(lambda line: tax_repartition_lines_mapping[line]) line_vals['tax_tag_ids'] = [(6, 0, refund_repartition_lines.mapped('tag_ids').ids)] return move_vals def _reverse_moves(self, default_values_list=None, cancel=False): ''' Reverse a recordset of account.move. If cancel parameter is true, the reconcilable or liquidity lines of each original move will be reconciled with its reverse's. :param default_values_list: A list of default values to consider per move. ('type' & 'reversed_entry_id' are computed in the method). :return: An account.move recordset, reverse of the current self. ''' if not default_values_list: default_values_list = [{} for move in self] if cancel: lines = self.mapped('line_ids') # Avoid maximum recursion depth. if lines: lines.remove_move_reconcile() reverse_type_map = { 'entry': 'entry', 'out_invoice': 'out_refund', 'out_refund': 'entry', 'in_invoice': 'in_refund', 'in_refund': 'entry', 'out_receipt': 'entry', 'in_receipt': 'entry', } move_vals_list = [] for move, default_values in zip(self, default_values_list): default_values.update({ 'move_type': reverse_type_map[move.move_type], 'reversed_entry_id': move.id, }) move_vals_list.append(move.with_context(move_reverse_cancel=cancel)._reverse_move_vals(default_values, cancel=cancel)) reverse_moves = self.env['account.move'].create(move_vals_list) for move, reverse_move in zip(self, reverse_moves.with_context(check_move_validity=False, move_reverse_cancel=cancel)): # Update amount_currency if the date has changed. if move.date != reverse_move.date: for line in reverse_move.line_ids: if line.currency_id: line._onchange_currency() reverse_move._recompute_dynamic_lines(recompute_all_taxes=False) reverse_moves._check_balanced() # Reconcile moves together to cancel the previous one. if cancel: reverse_moves.with_context(move_reverse_cancel=cancel)._post(soft=False) for move, reverse_move in zip(self, reverse_moves): group = defaultdict(list) for line in (move.line_ids + reverse_move.line_ids).filtered(lambda l: not l.reconciled): group[(line.account_id, line.currency_id)].append(line.id) for (account, dummy), line_ids in group.items(): if account.reconcile or account.internal_type == 'liquidity': self.env['account.move.line'].browse(line_ids).with_context(move_reverse_cancel=cancel).reconcile() return reverse_moves def _action_invoice_ready_to_be_sent(self): """ Hook allowing custom code when an invoice becomes ready to be sent by mail to the customer. For example, when an EDI document must be sent to the government and be signed by it. """ pass def _is_ready_to_be_sent(self): """ Helper telling if a journal entry is ready to be sent by mail to the customer. :return: True if the invoice is ready, False otherwise. """ self.ensure_one() return True @contextmanager def _send_only_when_ready(self): moves_not_ready = self.filtered(lambda x: not x._is_ready_to_be_sent()) try: yield finally: moves_now_ready = moves_not_ready.filtered(lambda x: x._is_ready_to_be_sent()) if moves_now_ready: moves_now_ready._action_invoice_ready_to_be_sent() def open_reconcile_view(self): return self.line_ids.open_reconcile_view() def open_bank_statement_view(self): return { 'type': 'ir.actions.act_window', 'res_model': 'account.bank.statement', 'view_mode': 'form', 'res_id': self.statement_id.id, 'views': [(False, 'form')], } def open_payment_view(self): return { 'type': 'ir.actions.act_window', 'res_model': 'account.payment', 'view_mode': 'form', 'res_id': self.payment_id.id, 'views': [(False, 'form')], } def open_created_caba_entries(self): self.ensure_one() return { 'type': 'ir.actions.act_window', 'name': _("Cash Basis Entries"), 'res_model': 'account.move', 'view_mode': 'form', 'domain': [('id', 'in', self.tax_cash_basis_created_move_ids.ids)], 'views': [(self.env.ref('account.view_move_tree').id, 'tree'), (False, 'form')], } @api.model def message_new(self, msg_dict, custom_values=None): # OVERRIDE # Add custom behavior when receiving a new invoice through the mail's gateway. if (custom_values or {}).get('move_type', 'entry') not in ('out_invoice', 'in_invoice'): return super().message_new(msg_dict, custom_values=custom_values) company = self.env['res.company'].browse(custom_values['company_id']) if custom_values.get('company_id') else self.env.company def is_internal_partner(partner): # Helper to know if the partner is an internal one. return partner == company.partner_id or (partner.user_ids and all(user.has_group('base.group_user') for user in partner.user_ids)) extra_domain = False if custom_values.get('company_id'): extra_domain = ['|', ('company_id', '=', custom_values['company_id']), ('company_id', '=', False)] # Search for partners in copy. cc_mail_addresses = email_split(msg_dict.get('cc', '')) followers = [partner for partner in self._mail_find_partner_from_emails(cc_mail_addresses, extra_domain) if partner] # Search for partner that sent the mail. from_mail_addresses = email_split(msg_dict.get('from', '')) senders = partners = [partner for partner in self._mail_find_partner_from_emails(from_mail_addresses, extra_domain) if partner] # Search for partners using the user. if not senders: senders = partners = list(self._mail_search_on_user(from_mail_addresses)) if partners: # Check we are not in the case when an internal user forwarded the mail manually. if is_internal_partner(partners[0]): # Search for partners in the mail's body. body_mail_addresses = set(email_re.findall(msg_dict.get('body'))) partners = [ partner for partner in self._mail_find_partner_from_emails(body_mail_addresses, extra_domain) if not is_internal_partner(partner) and partner.company_id.id in (False, company.id) ] # Little hack: Inject the mail's subject in the body. if msg_dict.get('subject') and msg_dict.get('body'): msg_dict['body'] = '<div><div><h3>%s</h3></div>%s</div>' % (msg_dict['subject'], msg_dict['body']) # Create the invoice. values = { 'name': '/', # we have to give the name otherwise it will be set to the mail's subject 'invoice_source_email': from_mail_addresses[0], 'partner_id': partners and partners[0].id or False, } move_ctx = self.with_context(default_move_type=custom_values['move_type'], default_journal_id=custom_values['journal_id']) move = super(AccountMove, move_ctx).message_new(msg_dict, custom_values=values) move._compute_name() # because the name is given, we need to recompute in case it is the first invoice of the journal # Assign followers. all_followers_ids = set(partner.id for partner in followers + senders + partners if is_internal_partner(partner)) move.message_subscribe(list(all_followers_ids)) return move def post(self): warnings.warn( "RedirectWarning method 'post()' is a deprecated alias to 'action_post()' or _post()", DeprecationWarning, stacklevel=2 ) return self.action_post() def _post(self, soft=True): """Post/Validate the documents. Posting the documents will give it a number, and check that the document is complete (some fields might not be required if not posted but are required otherwise). If the journal is locked with a hash table, it will be impossible to change some fields afterwards. :param soft (bool): if True, future documents are not immediately posted, but are set to be auto posted automatically at the set accounting date. Nothing will be performed on those documents before the accounting date. :return Model<account.move>: the documents that have been posted """ if soft: future_moves = self.filtered(lambda move: move.date > fields.Date.context_today(self)) future_moves.auto_post = True for move in future_moves: msg = _('This move will be posted at the accounting date: %(date)s', date=format_date(self.env, move.date)) move.message_post(body=msg) to_post = self - future_moves else: to_post = self # `user_has_group` won't be bypassed by `sudo()` since it doesn't change the user anymore. if not self.env.su and not self.env.user.has_group('account.group_account_invoice'): raise AccessError(_("You don't have the access rights to post an invoice.")) for move in to_post: if move.partner_bank_id and not move.partner_bank_id.active: raise UserError(_("The recipient bank account link to this invoice is archived.\nSo you cannot confirm the invoice.")) if move.state == 'posted': raise UserError(_('The entry %s (id %s) is already posted.') % (move.name, move.id)) if not move.line_ids.filtered(lambda line: not line.display_type): raise UserError(_('You need to add a line before posting.')) if move.auto_post and move.date > fields.Date.context_today(self): date_msg = move.date.strftime(get_lang(self.env).date_format) raise UserError(_("This move is configured to be auto-posted on %s", date_msg)) if not move.journal_id.active: raise UserError(_( "You cannot post an entry in an archived journal (%(journal)s)", journal=move.journal_id.display_name, )) if not move.partner_id: if move.is_sale_document(): raise UserError(_("The field 'Customer' is required, please complete it to validate the Customer Invoice.")) elif move.is_purchase_document(): raise UserError(_("The field 'Vendor' is required, please complete it to validate the Vendor Bill.")) if move.is_invoice(include_receipts=True) and float_compare(move.amount_total, 0.0, precision_rounding=move.currency_id.rounding) < 0: raise UserError(_("You cannot validate an invoice with a negative total amount. You should create a credit note instead. Use the action menu to transform it into a credit note or refund.")) if move.display_inactive_currency_warning: raise UserError(_("You cannot validate an invoice with an inactive currency: %s", move.currency_id.name)) if move.line_ids.account_id.filtered(lambda account: account.deprecated): raise UserError(_("A line of this move is using a deprecated account, you cannot post it.")) # Handle case when the invoice_date is not set. In that case, the invoice_date is set at today and then, # lines are recomputed accordingly. # /!\ 'check_move_validity' must be there since the dynamic lines will be recomputed outside the 'onchange' # environment. if not move.invoice_date: if move.is_sale_document(include_receipts=True): move.invoice_date = fields.Date.context_today(self) move.with_context(check_move_validity=False)._onchange_invoice_date() elif move.is_purchase_document(include_receipts=True): raise UserError(_("The Bill/Refund date is required to validate this document.")) # When the accounting date is prior to a lock date, change it automatically upon posting. # /!\ 'check_move_validity' must be there since the dynamic lines will be recomputed outside the 'onchange' # environment. affects_tax_report = move._affect_tax_report() lock_dates = move._get_violated_lock_dates(move.date, affects_tax_report) if lock_dates: move.date = move._get_accounting_date(move.invoice_date or move.date, affects_tax_report) if move.move_type and move.move_type != 'entry': move.with_context(check_move_validity=False)._onchange_currency() # Create the analytic lines in batch is faster as it leads to less cache invalidation. to_post.mapped('line_ids').create_analytic_lines() for move in to_post: # Fix inconsistencies that may occure if the OCR has been editing the invoice at the same time of a user. We force the # partner on the lines to be the same as the one on the move, because that's the only one the user can see/edit. wrong_lines = move.is_invoice() and move.line_ids.filtered(lambda aml: aml.partner_id != move.commercial_partner_id and not aml.display_type) if wrong_lines: wrong_lines.write({'partner_id': move.commercial_partner_id.id}) to_post.write({ 'state': 'posted', 'posted_before': True, }) for move in to_post: move.message_subscribe([p.id for p in [move.partner_id] if p not in move.sudo().message_partner_ids]) for move in to_post: if move.is_sale_document() \ and move.journal_id.sale_activity_type_id \ and (move.journal_id.sale_activity_user_id or move.invoice_user_id).id not in (self.env.ref('base.user_root').id, False): move.activity_schedule( date_deadline=min((date for date in move.line_ids.mapped('date_maturity') if date), default=move.date), activity_type_id=move.journal_id.sale_activity_type_id.id, summary=move.journal_id.sale_activity_note, user_id=move.journal_id.sale_activity_user_id.id or move.invoice_user_id.id, ) customer_count, supplier_count = defaultdict(int), defaultdict(int) for move in to_post: if move.is_sale_document(): customer_count[move.partner_id] += 1 elif move.is_purchase_document(): supplier_count[move.partner_id] += 1 for partner, count in customer_count.items(): (partner | partner.commercial_partner_id)._increase_rank('customer_rank', count) for partner, count in supplier_count.items(): (partner | partner.commercial_partner_id)._increase_rank('supplier_rank', count) # Trigger action for paid invoices in amount is zero to_post.filtered( lambda m: m.is_invoice(include_receipts=True) and m.currency_id.is_zero(m.amount_total) ).action_invoice_paid() # Force balance check since nothing prevents another module to create an incorrect entry. # This is performed at the very end to avoid flushing fields before the whole processing. to_post._check_balanced() return to_post def _auto_compute_invoice_reference(self): ''' Hook to be overridden to set custom conditions for auto-computed invoice references. :return True if the move should get a auto-computed reference else False :rtype bool ''' self.ensure_one() return self.move_type == 'out_invoice' and not self.payment_reference def action_reverse(self): action = self.env["ir.actions.actions"]._for_xml_id("account.action_view_account_move_reversal") if self.is_invoice(): action['name'] = _('Credit Note') return action def action_post(self): moves_with_payments = self.filtered('payment_id') other_moves = self - moves_with_payments if moves_with_payments: moves_with_payments.payment_id.action_post() if other_moves: other_moves._post(soft=False) return False def js_assign_outstanding_line(self, line_id): ''' Called by the 'payment' widget to reconcile a suggested journal item to the present invoice. :param line_id: The id of the line to reconcile with the current invoice. ''' self.ensure_one() lines = self.env['account.move.line'].browse(line_id) lines += self.line_ids.filtered(lambda line: line.account_id == lines[0].account_id and not line.reconciled) return lines.reconcile() def js_remove_outstanding_partial(self, partial_id): ''' Called by the 'payment' widget to remove a reconciled entry to the present invoice. :param partial_id: The id of an existing partial reconciled with the current invoice. ''' self.ensure_one() partial = self.env['account.partial.reconcile'].browse(partial_id) return partial.unlink() def button_set_checked(self): for move in self: move.to_check = False def button_draft(self): AccountMoveLine = self.env['account.move.line'] excluded_move_ids = [] if self._context.get('suspense_moves_mode'): excluded_move_ids = AccountMoveLine.search(AccountMoveLine._get_suspense_moves_domain() + [('move_id', 'in', self.ids)]).mapped('move_id').ids for move in self: if move in move.line_ids.mapped('full_reconcile_id.exchange_move_id'): raise UserError(_('You cannot reset to draft an exchange difference journal entry.')) if move.tax_cash_basis_rec_id or move.tax_cash_basis_origin_move_id: # If the reconciliation was undone, move.tax_cash_basis_rec_id will be empty; # but we still don't want to allow setting the caba entry to draft # (it'll have been reversed automatically, so no manual intervention is required), # so we also check tax_cash_basis_origin_move_id, which stays unchanged # (we need both, as tax_cash_basis_origin_move_id did not exist in older versions). raise UserError(_('You cannot reset to draft a tax cash basis journal entry.')) if move.restrict_mode_hash_table and move.state == 'posted' and move.id not in excluded_move_ids: raise UserError(_('You cannot modify a posted entry of this journal because it is in strict mode.')) # We remove all the analytics entries for this journal move.mapped('line_ids.analytic_line_ids').unlink() self.mapped('line_ids').remove_move_reconcile() self.write({'state': 'draft', 'is_move_sent': False}) def button_cancel(self): self.write({'auto_post': False, 'state': 'cancel'}) def _get_mail_template(self): """ :return: the correct mail template based on the current move type """ return ( 'account.email_template_edi_credit_note' if all(move.move_type == 'out_refund' for move in self) else 'account.email_template_edi_invoice' ) def action_send_and_print(self): return { 'name': _('Send Invoice'), 'res_model': 'account.invoice.send', 'view_mode': 'form', 'context': { 'default_template_id': self.env.ref(self._get_mail_template()).id, 'mark_invoice_as_sent': True, 'active_model': 'account.move', # Setting both active_id and active_ids is required, mimicking how direct call to # ir.actions.act_window works 'active_id': self.ids[0], 'active_ids': self.ids, 'custom_layout': 'mail.mail_notification_paynow', }, 'target': 'new', 'type': 'ir.actions.act_window', } def action_invoice_sent(self): """ Open a window to compose an email, with the edi invoice template message loaded by default """ self.ensure_one() template = self.env.ref(self._get_mail_template(), raise_if_not_found=False) lang = False if template: lang = template._render_lang(self.ids)[self.id] if not lang: lang = get_lang(self.env).code compose_form = self.env.ref('account.account_invoice_send_wizard_form', raise_if_not_found=False) ctx = dict( default_model='account.move', default_res_id=self.id, # For the sake of consistency we need a default_res_model if # default_res_id is set. Not renaming default_model as it can # create many side-effects. default_res_model='account.move', default_use_template=bool(template), default_template_id=template and template.id or False, default_composition_mode='comment', mark_invoice_as_sent=True, custom_layout="mail.mail_notification_paynow", model_description=self.with_context(lang=lang).type_name, force_email=True, active_ids=self.ids, ) report_action = { 'name': _('Send Invoice'), 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'account.invoice.send', 'views': [(compose_form.id, 'form')], 'view_id': compose_form.id, 'target': 'new', 'context': ctx, } if self.env.is_admin() and not self.env.company.external_report_layout_id and not self.env.context.get('discard_logo_check'): return self.env['ir.actions.report']._action_configure_external_report_layout(report_action) return report_action def _get_integrity_hash_fields(self): # Use the latest hash version by default, but keep the old one for backward compatibility when generating the integrity report. hash_version = self._context.get('hash_version', MAX_HASH_VERSION) if hash_version == 1: return ['date', 'journal_id', 'company_id'] elif hash_version == MAX_HASH_VERSION: return ['name', 'date', 'journal_id', 'company_id'] raise NotImplementedError(f"hash_version={hash_version} doesn't exist") def _get_integrity_hash_fields_and_subfields(self): return self._get_integrity_hash_fields() + [f'line_ids.{subfield}' for subfield in self.line_ids._get_integrity_hash_fields()] def _get_new_hash(self, secure_seq_number): """ Returns the hash to write on journal entries when they get posted""" self.ensure_one() #get the only one exact previous move in the securisation sequence prev_move = self.sudo().search([('state', '=', 'posted'), ('company_id', '=', self.company_id.id), ('journal_id', '=', self.journal_id.id), ('secure_sequence_number', '!=', 0), ('secure_sequence_number', '=', int(secure_seq_number) - 1)]) if prev_move and len(prev_move) != 1: raise UserError( _('An error occurred when computing the inalterability. Impossible to get the unique previous posted journal entry.')) #build and return the hash return self._compute_hash(prev_move.inalterable_hash if prev_move else u'') def _compute_hash(self, previous_hash): """ Computes the hash of the browse_record given as self, based on the hash of the previous record in the company's securisation sequence given as parameter""" self.ensure_one() hash_string = sha256((previous_hash + self.string_to_hash).encode('utf-8')) return hash_string.hexdigest() @api.depends(lambda self: self._get_integrity_hash_fields_and_subfields()) @api.depends_context('hash_version') def _compute_string_to_hash(self): def _getattrstring(obj, field_str): field_value = obj[field_str] if obj._fields[field_str].type == 'many2one': field_value = field_value.id return str(field_value) for move in self: values = {} for field in move._get_integrity_hash_fields(): values[field] = _getattrstring(move, field) for line in move.line_ids: for field in line._get_integrity_hash_fields(): k = 'line_%d_%s' % (line.id, field) values[k] = _getattrstring(line, field) #make the json serialization canonical # (https://tools.ietf.org/html/draft-staykov-hu-json-canonical-form-00) move.string_to_hash = dumps(values, sort_keys=True, ensure_ascii=True, indent=None, separators=(',',':')) def action_invoice_print(self): """ Print the invoice and mark it as sent, so that we can see more easily the next step of the workflow """ if any(not move.is_invoice(include_receipts=True) for move in self): raise UserError(_("Only invoices could be printed.")) self.filtered(lambda inv: not inv.is_move_sent).write({'is_move_sent': True}) if self.user_has_groups('account.group_account_invoice'): return self.env.ref('account.account_invoices').report_action(self) else: return self.env.ref('account.account_invoices_without_payment').report_action(self) def action_invoice_paid(self): ''' Hook to be overrided called when the invoice moves to the paid state. ''' pass def action_register_payment(self): ''' Open the account.payment.register wizard to pay the selected journal entries. :return: An action opening the account.payment.register wizard. ''' return { 'name': _('Register Payment'), 'res_model': 'account.payment.register', 'view_mode': 'form', 'context': { 'active_model': 'account.move', 'active_ids': self.ids, }, 'target': 'new', 'type': 'ir.actions.act_window', } def action_switch_invoice_into_refund_credit_note(self): if any(move.move_type not in ('in_invoice', 'out_invoice') for move in self): raise ValidationError(_("This action isn't available for this document.")) for move in self: reversed_move = move._reverse_move_vals({}, False) new_invoice_line_ids = [] for cmd, virtualid, line_vals in reversed_move['line_ids']: if not line_vals['exclude_from_invoice_tab']: new_invoice_line_ids.append((0, 0,line_vals)) if move.amount_total < 0: # Inverse all invoice_line_ids for cmd, virtualid, line_vals in new_invoice_line_ids: line_vals.update({ 'quantity' : -line_vals['quantity'], 'amount_currency' : -line_vals['amount_currency'], 'debit' : line_vals['credit'], 'credit' : line_vals['debit'] }) move.write({ 'move_type': move.move_type.replace('invoice', 'refund'), 'invoice_line_ids' : [(5, 0, 0)], 'partner_bank_id': False, }) move.write({'invoice_line_ids' : new_invoice_line_ids}) def _get_report_base_filename(self): return self._get_move_display_name() def _get_name_invoice_report(self): """ This method need to be inherit by the localizations if they want to print a custom invoice report instead of the default one. For example please review the l10n_ar module """ self.ensure_one() return 'account.report_invoice_document' def preview_invoice(self): self.ensure_one() return { 'type': 'ir.actions.act_url', 'target': 'self', 'url': self.get_portal_url(), } def _compute_access_url(self): super(AccountMove, self)._compute_access_url() for move in self.filtered(lambda move: move.is_invoice()): move.access_url = '/my/invoices/%s' % (move.id) @api.depends('line_ids') def _compute_has_reconciled_entries(self): for move in self: move.has_reconciled_entries = len(move.line_ids._reconciled_lines()) > 1 @api.depends('company_id') def _compute_display_qr_code(self): for record in self: record.display_qr_code = ( record.move_type in ('out_invoice', 'out_receipt', 'in_invoice', 'in_receipt') and record.company_id.qr_code ) def action_view_reverse_entry(self): # DEPRECATED: REMOVED IN MASTER self.ensure_one() # Create action. action = { 'name': _('Reverse Moves'), 'type': 'ir.actions.act_window', 'res_model': 'account.move', } reverse_entries = self.env['account.move'].search([('reversed_entry_id', '=', self.id)]) if len(reverse_entries) == 1: action.update({ 'view_mode': 'form', 'res_id': reverse_entries.id, }) else: action.update({ 'view_mode': 'tree', 'domain': [('id', 'in', reverse_entries.ids)], }) return action @api.model def _autopost_draft_entries(self): ''' This method is called from a cron job. It is used to post entries such as those created by the module account_asset. ''' records = self.search([ ('state', '=', 'draft'), ('date', '<=', fields.Date.context_today(self)), ('auto_post', '=', True), ]) for ids in self._cr.split_for_in_conditions(records.ids, size=1000): self.browse(ids)._post() if not self.env.registry.in_test_mode(): self._cr.commit() # offer the possibility to duplicate thanks to a button instead of a hidden menu, which is more visible def action_duplicate(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("account.action_move_journal_line") action['context'] = dict(self.env.context) action['context']['form_view_initial_mode'] = 'edit' action['context']['view_no_maturity'] = False action['views'] = [(self.env.ref('account.view_move_form').id, 'form')] action['res_id'] = self.copy().id return action def action_activate_currency(self): self.currency_id.filtered(lambda currency: not currency.active).write({'active': True}) @api.model def _move_dict_to_preview_vals(self, move_vals, currency_id=None): preview_vals = { 'group_name': "%s, %s" % (format_date(self.env, move_vals['date']) or _('[Not set]'), move_vals['ref']), 'items_vals': move_vals['line_ids'], } for line in preview_vals['items_vals']: if 'partner_id' in line[2]: # sudo is needed to compute display_name in a multi companies environment line[2]['partner_id'] = self.env['res.partner'].browse(line[2]['partner_id']).sudo().display_name line[2]['account_id'] = self.env['account.account'].browse(line[2]['account_id']).display_name or _('Destination Account') line[2]['debit'] = currency_id and formatLang(self.env, line[2]['debit'], currency_obj=currency_id) or line[2]['debit'] line[2]['credit'] = currency_id and formatLang(self.env, line[2]['credit'], currency_obj=currency_id) or line[2]['debit'] return preview_vals def generate_qr_code(self): """ Generates and returns a QR-code generation URL for this invoice, raising an error message if something is misconfigured. The chosen QR generation method is the one set in qr_method field if there is one, or the first eligible one found. If this search had to be performed and and eligible method was found, qr_method field is set to this method before returning the URL. If no eligible QR method could be found, we return None. """ self.ensure_one() if not self.display_qr_code: return None qr_code_method = self.qr_code_method if qr_code_method: # If the user set a qr code generator manually, we check that we can use it if not self.partner_bank_id._eligible_for_qr_code(self.qr_code_method, self.partner_id, self.currency_id): raise UserError(_("The chosen QR-code type is not eligible for this invoice.")) else: # Else we find one that's eligible and assign it to the invoice for candidate_method, candidate_name in self.env['res.partner.bank'].get_available_qr_methods_in_sequence(): if self.partner_bank_id._eligible_for_qr_code(candidate_method, self.partner_id, self.currency_id): qr_code_method = candidate_method break if not qr_code_method: # No eligible method could be found; we can't generate the QR-code return None unstruct_ref = self.ref if self.ref else self.name rslt = self.partner_bank_id.build_qr_code_base64(self.amount_residual, unstruct_ref, self.payment_reference, self.currency_id, self.partner_id, qr_code_method, silent_errors=False) # We only set qr_code_method after generating the url; otherwise, it # could be set even in case of a failure in the QR code generation # (which would change the field, but not refresh UI, making the displayed data inconsistent with db) self.qr_code_method = qr_code_method return rslt def _message_post_after_hook(self, new_message, message_values): # OVERRIDE # When posting a message, check the attachment to see if it's an invoice and update with the imported data. res = super()._message_post_after_hook(new_message, message_values) attachments = new_message.attachment_ids if len(self) != 1 or not attachments or self.env.context.get('no_new_invoice') or not self.is_invoice(include_receipts=True): return res odoobot = self.env.ref('base.partner_root') if attachments and self.state != 'draft': self.message_post(body=_('The invoice is not a draft, it was not updated from the attachment.'), message_type='comment', subtype_xmlid='mail.mt_note', author_id=odoobot.id) return res if attachments and self.line_ids: self.message_post(body=_('The invoice already contains lines, it was not updated from the attachment.'), message_type='comment', subtype_xmlid='mail.mt_note', author_id=odoobot.id) return res decoders = self.env['account.move']._get_update_invoice_from_attachment_decoders(self) for decoder in sorted(decoders, key=lambda d: d[0]): # start with message_main_attachment_id, that way if OCR is installed, only that one will be parsed. # this is based on the fact that the ocr will be the last decoder. for attachment in attachments.sorted(lambda x: x != self.message_main_attachment_id): invoice = decoder[1](attachment, self) if invoice: return res return res def _get_create_invoice_from_attachment_decoders(self): """ Returns a list of method that are able to create an invoice from an attachment and a priority. :returns: A list of tuples (priority, method) where method takes an attachment as parameter. """ return [] def _get_update_invoice_from_attachment_decoders(self, invoice): """ Returns a list of method that are able to create an invoice from an attachment and a priority. :param invoice: The invoice on which to update the data. :returns: A list of tuples (priority, method) where method takes an attachment as parameter. """ return [] @api.depends('move_type', 'partner_id', 'company_id') def _compute_narration(self): use_invoice_terms = self.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms') for move in self: if not move.is_sale_document(include_receipts=True): continue if not use_invoice_terms: move.narration = False else: lang = move.partner_id.lang or self.env.user.lang if not move.company_id.terms_type == 'html': narration = move.company_id.with_context(lang=lang).invoice_terms if not is_html_empty(move.company_id.invoice_terms) else '' else: baseurl = self.env.company.get_base_url() + '/terms' context = {'lang': lang} narration = _('Terms & Conditions: %s', baseurl) del context move.narration = narration or False def _notify_get_groups(self, msg_vals=None): """ Give access button to users and portal customer as portal is integrated in account. Customer and portal group have probably no right to see the document so they don't have the access button. """ groups = super(AccountMove, self)._notify_get_groups(msg_vals=msg_vals) self.ensure_one() if self.move_type != 'entry': for group_name, _group_method, group_data in groups: if group_name in ('portal_customer', 'customer'): group_data['has_button_access'] = True # 'notification_is_customer' is used to determine whether the group should be sent the access_token group_data['notification_is_customer'] = True return groups def _is_downpayment(self): ''' Return true if the invoice is a downpayment. Down-payments can be created from a sale order. This method is overridden in the sale order module. ''' return False class AccountMoveLine(models.Model): _name = "account.move.line" _description = "Journal Item" _order = "date desc, move_name desc, id" _check_company_auto = True # ==== Business fields ==== move_id = fields.Many2one('account.move', string='Journal Entry', index=True, required=True, readonly=True, auto_join=True, ondelete="cascade", check_company=True, help="The move of this entry line.") move_name = fields.Char(string='Number', related='move_id.name', store=True, index=True) date = fields.Date(related='move_id.date', store=True, readonly=True, index=True, copy=False, group_operator='min') ref = fields.Char(related='move_id.ref', store=True, copy=False, index=True, readonly=True) parent_state = fields.Selection(related='move_id.state', store=True, readonly=True) journal_id = fields.Many2one(related='move_id.journal_id', store=True, index=True, copy=False) company_id = fields.Many2one(related='move_id.company_id', store=True, readonly=True) company_currency_id = fields.Many2one(related='company_id.currency_id', string='Company Currency', readonly=True, store=True, help='Utility field to express amount currency') account_id = fields.Many2one('account.account', string='Account', index=True, ondelete="cascade", domain="[('deprecated', '=', False), ('company_id', '=', 'company_id'),('is_off_balance', '=', False)]", check_company=True, tracking=True) account_internal_type = fields.Selection(related='account_id.user_type_id.type', string="Internal Type", readonly=True) account_internal_group = fields.Selection(related='account_id.user_type_id.internal_group', string="Internal Group", readonly=True) account_root_id = fields.Many2one(related='account_id.root_id', string="Account Root", store=True, readonly=True) sequence = fields.Integer(default=10) name = fields.Char(string='Label', tracking=True, compute='_compute_name', store=True, readonly=False) quantity = fields.Float(string='Quantity', default=lambda self: 0 if self._context.get('default_display_type') else 1.0, digits='Product Unit of Measure', help="The optional quantity expressed by this line, eg: number of product sold. " "The quantity is not a legal requirement but is very useful for some reports.") price_unit = fields.Float(string='Unit Price', digits='Product Price') discount = fields.Float(string='Discount (%)', digits='Discount', default=0.0) debit = fields.Monetary(string='Debit', default=0.0, currency_field='company_currency_id') credit = fields.Monetary(string='Credit', default=0.0, currency_field='company_currency_id') balance = fields.Monetary(string='Balance', store=True, currency_field='company_currency_id', compute='_compute_balance', help="Technical field holding the debit - credit in order to open meaningful graph views from reports") cumulated_balance = fields.Monetary(string='Cumulated Balance', store=False, currency_field='company_currency_id', compute='_compute_cumulated_balance', help="Cumulated balance depending on the domain and the order chosen in the view.") amount_currency = fields.Monetary(string='Amount in Currency', store=True, copy=True, help="The amount expressed in an optional other currency if it is a multi-currency entry.") price_subtotal = fields.Monetary(string='Subtotal', store=True, readonly=True, currency_field='currency_id') price_total = fields.Monetary(string='Total', store=True, readonly=True, currency_field='currency_id') reconciled = fields.Boolean(compute='_compute_amount_residual', store=True) blocked = fields.Boolean(string='No Follow-up', default=False, help="You can check this box to mark this journal item as a litigation with the associated partner") date_maturity = fields.Date(string='Due Date', index=True, tracking=True, help="This field is used for payable and receivable journal entries. You can put the limit date for the payment of this line.") currency_id = fields.Many2one('res.currency', string='Currency', required=True) partner_id = fields.Many2one('res.partner', string='Partner', ondelete='restrict') product_uom_id = fields.Many2one('uom.uom', string='Unit of Measure', domain="[('category_id', '=', product_uom_category_id)]", ondelete="restrict") product_id = fields.Many2one('product.product', string='Product', ondelete='restrict') product_uom_category_id = fields.Many2one('uom.category', related='product_id.uom_id.category_id') # ==== Origin fields ==== reconcile_model_id = fields.Many2one('account.reconcile.model', string="Reconciliation Model", copy=False, readonly=True, check_company=True) payment_id = fields.Many2one('account.payment', index=True, store=True, string="Originator Payment", related='move_id.payment_id', help="The payment that created this entry") statement_line_id = fields.Many2one('account.bank.statement.line', index=True, store=True, string="Originator Statement Line", related='move_id.statement_line_id', help="The statement line that created this entry") statement_id = fields.Many2one(related='statement_line_id.statement_id', store=True, index=True, copy=False, help="The bank statement used for bank reconciliation") # ==== Tax fields ==== tax_ids = fields.Many2many( comodel_name='account.tax', string="Taxes", context={'active_test': False}, check_company=True, help="Taxes that apply on the base amount") group_tax_id = fields.Many2one( comodel_name='account.tax', string="Originator Group of Taxes", index=True, help="The group of taxes that generated this tax line", ) tax_line_id = fields.Many2one('account.tax', string='Originator Tax', ondelete='restrict', store=True, compute='_compute_tax_line_id', help="Indicates that this journal item is a tax line") tax_group_id = fields.Many2one(related='tax_line_id.tax_group_id', string='Originator tax group', readonly=True, store=True, help='technical field for widget tax-group-custom-field') tax_base_amount = fields.Monetary(string="Base Amount", store=True, readonly=True, currency_field='company_currency_id') tax_repartition_line_id = fields.Many2one(comodel_name='account.tax.repartition.line', string="Originator Tax Distribution Line", ondelete='restrict', readonly=True, check_company=True, help="Tax distribution line that caused the creation of this move line, if any") tax_tag_ids = fields.Many2many(string="Tags", comodel_name='account.account.tag', ondelete='restrict', context={'active_test': False}, help="Tags assigned to this line by the tax creating it, if any. It determines its impact on financial reports.", tracking=True) tax_audit = fields.Char(string="Tax Audit String", compute="_compute_tax_audit", store=True, help="Computed field, listing the tax grids impacted by this line, and the amount it applies to each of them.") tax_tag_invert = fields.Boolean(string="Invert Tags", compute='_compute_tax_tag_invert', store=True, readonly=False, help="Technical field. True if the balance of this move line needs to be " "inverted when computing its total for each tag (for sales invoices, for example).") # ==== Reconciliation fields ==== amount_residual = fields.Monetary(string='Residual Amount', store=True, currency_field='company_currency_id', compute='_compute_amount_residual', help="The residual amount on a journal item expressed in the company currency.") amount_residual_currency = fields.Monetary(string='Residual Amount in Currency', store=True, compute='_compute_amount_residual', help="The residual amount on a journal item expressed in its currency (possibly not the company currency).") full_reconcile_id = fields.Many2one('account.full.reconcile', string="Matching", copy=False, index=True, readonly=True) matched_debit_ids = fields.One2many('account.partial.reconcile', 'credit_move_id', string='Matched Debits', help='Debit journal items that are matched with this journal item.', readonly=True) matched_credit_ids = fields.One2many('account.partial.reconcile', 'debit_move_id', string='Matched Credits', help='Credit journal items that are matched with this journal item.', readonly=True) matching_number = fields.Char(string="Matching #", compute='_compute_matching_number', store=True, help="Matching number for this line, 'P' if it is only partially reconcile, or the name of the full reconcile if it exists.") # ==== Analytic fields ==== analytic_line_ids = fields.One2many('account.analytic.line', 'move_id', string='Analytic lines') analytic_account_id = fields.Many2one('account.analytic.account', string='Analytic Account', index=True, compute="_compute_analytic_account_id", store=True, readonly=False, check_company=True, copy=True) analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags', compute="_compute_analytic_tag_ids", store=True, readonly=False, check_company=True, copy=True) # ==== Onchange / display purpose fields ==== recompute_tax_line = fields.Boolean(store=False, readonly=True, help="Technical field used to know on which lines the taxes must be recomputed.") display_type = fields.Selection([ ('line_section', 'Section'), ('line_note', 'Note'), ], default=False, help="Technical field for UX purpose.") is_rounding_line = fields.Boolean(help="Technical field used to retrieve the cash rounding line.") exclude_from_invoice_tab = fields.Boolean(help="Technical field used to exclude some lines from the invoice_line_ids tab in the form view.") _sql_constraints = [ ( 'check_credit_debit', 'CHECK(credit + debit>=0 AND credit * debit=0)', 'Wrong credit or debit value in accounting entry !' ), ( 'check_accountable_required_fields', "CHECK(COALESCE(display_type IN ('line_section', 'line_note'), 'f') OR account_id IS NOT NULL)", "Missing required account on accountable invoice line." ), ( 'check_non_accountable_fields_null', "CHECK(display_type NOT IN ('line_section', 'line_note') OR (amount_currency = 0 AND debit = 0 AND credit = 0 AND account_id IS NULL))", "Forbidden unit price, account and quantity on non-accountable invoice line" ), ( 'check_amount_currency_balance_sign', '''CHECK( ( (currency_id != company_currency_id) AND ( (debit - credit <= 0 AND amount_currency <= 0) OR (debit - credit >= 0 AND amount_currency >= 0) ) ) OR ( currency_id = company_currency_id AND ROUND(debit - credit - amount_currency, 2) = 0 ) )''', "The amount expressed in the secondary currency must be positive when account is debited and negative when " "account is credited. If the currency is the same as the one from the company, this amount must strictly " "be equal to the balance." ), ] # ------------------------------------------------------------------------- # HELPERS # ------------------------------------------------------------------------- @api.model def _get_default_line_name(self, document, amount, currency, date, partner=None): ''' Helper to construct a default label to set on journal items. E.g. Vendor Reimbursement $ 1,555.00 - Azure Interior - 05/14/2020. :param document: A string representing the type of the document. :param amount: The document's amount. :param currency: The document's currency. :param date: The document's date. :param partner: The optional partner. :return: A string. ''' values = ['%s %s' % (document, formatLang(self.env, amount, currency_obj=currency))] if partner: values.append(partner.display_name) values.append(format_date(self.env, fields.Date.to_string(date))) return ' - '.join(values) @api.model def _get_default_tax_account(self, repartition_line): tax = repartition_line.invoice_tax_id or repartition_line.refund_tax_id if tax.tax_exigibility == 'on_payment': account = tax.cash_basis_transition_account_id else: account = repartition_line.account_id return account def _get_integrity_hash_fields(self): # Use the new hash version by default, but keep the old one for backward compatibility when generating the integrity report. hash_version = self._context.get('hash_version', MAX_HASH_VERSION) if hash_version == 1: return ['debit', 'credit', 'account_id', 'partner_id'] elif hash_version == MAX_HASH_VERSION: return ['name', 'debit', 'credit', 'account_id', 'partner_id'] raise NotImplementedError(f"hash_version={hash_version} doesn't exist") def _get_computed_name(self): self.ensure_one() if not self.product_id: return '' if self.partner_id.lang: product = self.product_id.with_context(lang=self.partner_id.lang) else: product = self.product_id values = [] if product.partner_ref: values.append(product.partner_ref) if self.journal_id.type == 'sale': if product.description_sale: values.append(product.description_sale) elif self.journal_id.type == 'purchase': if product.description_purchase: values.append(product.description_purchase) return '\n'.join(values) def _get_computed_price_unit(self): ''' Helper to get the default price unit based on the product by taking care of the taxes set on the product and the fiscal position. :return: The price unit. ''' self.ensure_one() if not self.product_id: return 0.0 if self.move_id.is_sale_document(include_receipts=True): document_type = 'sale' elif self.move_id.is_purchase_document(include_receipts=True): document_type = 'purchase' else: document_type = 'other' return self.product_id._get_tax_included_unit_price( self.move_id.company_id, self.move_id.currency_id, self.move_id.date, document_type, fiscal_position=self.move_id.fiscal_position_id, product_uom=self.product_uom_id ) def _get_computed_account(self): self.ensure_one() self = self.with_company(self.move_id.journal_id.company_id) if not self.product_id: return fiscal_position = self.move_id.fiscal_position_id accounts = self.product_id.product_tmpl_id.get_product_accounts(fiscal_pos=fiscal_position) if self.move_id.is_sale_document(include_receipts=True): # Out invoice. return accounts['income'] or self.account_id elif self.move_id.is_purchase_document(include_receipts=True): # In invoice. return accounts['expense'] or self.account_id def _get_computed_taxes(self): self.ensure_one() if self.move_id.is_sale_document(include_receipts=True): # Out invoice. if self.product_id.taxes_id: tax_ids = self.product_id.taxes_id.filtered(lambda tax: tax.company_id == self.move_id.company_id) else: tax_ids = self.account_id.tax_ids.filtered(lambda tax: tax.type_tax_use == 'sale') if not tax_ids and not self.exclude_from_invoice_tab: tax_ids = self.move_id.company_id.account_sale_tax_id elif self.move_id.is_purchase_document(include_receipts=True): # In invoice. if self.product_id.supplier_taxes_id: tax_ids = self.product_id.supplier_taxes_id.filtered(lambda tax: tax.company_id == self.move_id.company_id) else: tax_ids = self.account_id.tax_ids.filtered(lambda tax: tax.type_tax_use == 'purchase') if not tax_ids and not self.exclude_from_invoice_tab: tax_ids = self.move_id.company_id.account_purchase_tax_id else: # Miscellaneous operation. tax_ids = self.account_id.tax_ids if self.company_id and tax_ids: tax_ids = tax_ids.filtered(lambda tax: tax.company_id == self.company_id) return tax_ids def _get_computed_uom(self): self.ensure_one() if self.product_id: return self.product_id.uom_id return False def _set_price_and_tax_after_fpos(self): self.ensure_one() # Manage the fiscal position after that and adapt the price_unit. # E.g. mapping a price-included-tax to a price-excluded-tax must # remove the tax amount from the price_unit. # However, mapping a price-included tax to another price-included tax must preserve the balance but # adapt the price_unit to the new tax. # E.g. mapping a 10% price-included tax to a 20% price-included tax for a price_unit of 110 should preserve # 100 as balance but set 120 as price_unit. if self.tax_ids and self.move_id.fiscal_position_id and self.move_id.fiscal_position_id.tax_ids: price_subtotal = self._get_price_total_and_subtotal()['price_subtotal'] self.tax_ids = self.move_id.fiscal_position_id.map_tax(self.tax_ids._origin) accounting_vals = self._get_fields_onchange_subtotal( price_subtotal=price_subtotal, currency=self.move_id.company_currency_id) amount_currency = accounting_vals['amount_currency'] business_vals = self._get_fields_onchange_balance(amount_currency=amount_currency) if 'price_unit' in business_vals: self.price_unit = business_vals['price_unit'] @api.depends('product_id', 'account_id', 'partner_id', 'date') def _compute_analytic_account_id(self): for record in self: if not record.exclude_from_invoice_tab or not record.move_id.is_invoice(include_receipts=True): rec = self.env['account.analytic.default'].account_get( product_id=record.product_id.id, partner_id=record.partner_id.commercial_partner_id.id or record.move_id.partner_id.commercial_partner_id.id, account_id=record.account_id.id, user_id=record.env.uid, date=record.date, company_id=record.move_id.company_id.id ) if rec: record.analytic_account_id = rec.analytic_id @api.depends('product_id', 'account_id', 'partner_id', 'date') def _compute_analytic_tag_ids(self): for record in self: if not record.exclude_from_invoice_tab or not record.move_id.is_invoice(include_receipts=True): rec = self.env['account.analytic.default'].account_get( product_id=record.product_id.id, partner_id=record.partner_id.commercial_partner_id.id or record.move_id.partner_id.commercial_partner_id.id, account_id=record.account_id.id, user_id=record.env.uid, date=record.date, company_id=record.move_id.company_id.id ) if rec: record.analytic_tag_ids = rec.analytic_tag_ids @api.depends('move_id.payment_reference') def _compute_name(self): for line in self.filtered(lambda l: not l.name and l.account_id.user_type_id.type in ('receivable', 'payable')): line.name = line.move_id.payment_reference def _get_price_total_and_subtotal(self, price_unit=None, quantity=None, discount=None, currency=None, product=None, partner=None, taxes=None, move_type=None): self.ensure_one() return self._get_price_total_and_subtotal_model( price_unit=self.price_unit if price_unit is None else price_unit, quantity=self.quantity if quantity is None else quantity, discount=self.discount if discount is None else discount, currency=self.currency_id if currency is None else currency, product=self.product_id if product is None else product, partner=self.partner_id if partner is None else partner, taxes=self.tax_ids if taxes is None else taxes, move_type=self.move_id.move_type if move_type is None else move_type, ) @api.model def _get_price_total_and_subtotal_model(self, price_unit, quantity, discount, currency, product, partner, taxes, move_type): ''' This method is used to compute 'price_total' & 'price_subtotal'. :param price_unit: The current price unit. :param quantity: The current quantity. :param discount: The current discount. :param currency: The line's currency. :param product: The line's product. :param partner: The line's partner. :param taxes: The applied taxes. :param move_type: The type of the move. :return: A dictionary containing 'price_subtotal' & 'price_total'. ''' res = {} # Compute 'price_subtotal'. line_discount_price_unit = price_unit * (1 - (discount / 100.0)) subtotal = quantity * line_discount_price_unit # Compute 'price_total'. if taxes: taxes_res = taxes._origin.with_context(force_sign=1).compute_all(line_discount_price_unit, quantity=quantity, currency=currency, product=product, partner=partner, is_refund=move_type in ('out_refund', 'in_refund')) res['price_subtotal'] = taxes_res['total_excluded'] res['price_total'] = taxes_res['total_included'] else: res['price_total'] = res['price_subtotal'] = subtotal #In case of multi currency, round before it's use for computing debit credit if currency: res = {k: currency.round(v) for k, v in res.items()} return res def _get_fields_onchange_subtotal(self, price_subtotal=None, move_type=None, currency=None, company=None, date=None): self.ensure_one() return self._get_fields_onchange_subtotal_model( price_subtotal=self.price_subtotal if price_subtotal is None else price_subtotal, move_type=self.move_id.move_type if move_type is None else move_type, currency=self.currency_id if currency is None else currency, company=self.move_id.company_id if company is None else company, date=self.move_id.date if date is None else date, ) @api.model def _get_fields_onchange_subtotal_model(self, price_subtotal, move_type, currency, company, date): ''' This method is used to recompute the values of 'amount_currency', 'debit', 'credit' due to a change made in some business fields (affecting the 'price_subtotal' field). :param price_subtotal: The untaxed amount. :param move_type: The type of the move. :param currency: The line's currency. :param company: The move's company. :param date: The move's date. :return: A dictionary containing 'debit', 'credit', 'amount_currency'. ''' if move_type in self.move_id.get_outbound_types(): sign = 1 elif move_type in self.move_id.get_inbound_types(): sign = -1 else: sign = 1 amount_currency = price_subtotal * sign balance = currency._convert(amount_currency, company.currency_id, company, date or fields.Date.context_today(self)) return { 'amount_currency': amount_currency, 'currency_id': currency.id, 'debit': balance > 0.0 and balance or 0.0, 'credit': balance < 0.0 and -balance or 0.0, } def _get_fields_onchange_balance(self, quantity=None, discount=None, amount_currency=None, move_type=None, currency=None, taxes=None, price_subtotal=None, force_computation=False): self.ensure_one() return self._get_fields_onchange_balance_model( quantity=self.quantity if quantity is None else quantity, discount=self.discount if discount is None else discount, amount_currency=self.amount_currency if amount_currency is None else amount_currency, move_type=self.move_id.move_type if move_type is None else move_type, currency=(self.currency_id or self.move_id.currency_id) if currency is None else currency, taxes=self.tax_ids if taxes is None else taxes, price_subtotal=self.price_subtotal if price_subtotal is None else price_subtotal, force_computation=force_computation, ) @api.model def _get_fields_onchange_balance_model(self, quantity, discount, amount_currency, move_type, currency, taxes, price_subtotal, force_computation=False): ''' This method is used to recompute the values of 'quantity', 'discount', 'price_unit' due to a change made in some accounting fields such as 'balance'. This method is a bit complex as we need to handle some special cases. For example, setting a positive balance with a 100% discount. :param quantity: The current quantity. :param discount: The current discount. :param amount_currency: The new balance in line's currency. :param move_type: The type of the move. :param currency: The currency. :param taxes: The applied taxes. :param price_subtotal: The price_subtotal. :return: A dictionary containing 'quantity', 'discount', 'price_unit'. ''' if move_type in self.move_id.get_outbound_types(): sign = 1 elif move_type in self.move_id.get_inbound_types(): sign = -1 else: sign = 1 amount_currency *= sign # Avoid rounding issue when dealing with price included taxes. For example, when the price_unit is 2300.0 and # a 5.5% price included tax is applied on it, a balance of 2300.0 / 1.055 = 2180.094 ~ 2180.09 is computed. # However, when triggering the inverse, 2180.09 + (2180.09 * 0.055) = 2180.09 + 119.90 = 2299.99 is computed. # To avoid that, set the price_subtotal at the balance if the difference between them looks like a rounding # issue. if not force_computation and currency.is_zero(amount_currency - price_subtotal): return {} taxes = taxes.flatten_taxes_hierarchy() if taxes and any(tax.price_include for tax in taxes): # Inverse taxes. E.g: # # Price Unit | Taxes | Originator Tax |Price Subtotal | Price Total # ----------------------------------------------------------------------------------- # 110 | 10% incl, 5% | | 100 | 115 # 10 | | 10% incl | 10 | 10 # 5 | | 5% | 5 | 5 # # When setting the balance to -200, the expected result is: # # Price Unit | Taxes | Originator Tax |Price Subtotal | Price Total # ----------------------------------------------------------------------------------- # 220 | 10% incl, 5% | | 200 | 230 # 20 | | 10% incl | 20 | 20 # 10 | | 5% | 10 | 10 force_sign = -1 if move_type in ('out_invoice', 'in_refund', 'out_receipt') else 1 taxes_res = taxes._origin.with_context(force_sign=force_sign).compute_all(amount_currency, currency=currency, handle_price_include=False) for tax_res in taxes_res['taxes']: tax = self.env['account.tax'].browse(tax_res['id']) if tax.price_include: amount_currency += tax_res['amount'] discount_factor = 1 - (discount / 100.0) if amount_currency and discount_factor: # discount != 100% vals = { 'quantity': quantity or 1.0, 'price_unit': amount_currency / discount_factor / (quantity or 1.0), } elif amount_currency and not discount_factor: # discount == 100% vals = { 'quantity': quantity or 1.0, 'discount': 0.0, 'price_unit': amount_currency / (quantity or 1.0), } elif not discount_factor: # balance of line is 0, but discount == 100% so we display the normal unit_price vals = {} else: # balance is 0, so unit price is 0 as well vals = {'price_unit': 0.0} return vals @api.model def _get_tax_exigible_domain(self): """ Returns a domain to be used to identify the move lines that are allowed to be taken into account in the tax report. """ return [ # Lines on moves without any payable or receivable line are always exigible '|', ('move_id.always_tax_exigible', '=', True), # Lines with only tags are always exigible '|', '&', ('tax_line_id', '=', False), ('tax_ids', '=', False), # Lines from CABA entries are always exigible '|', ('move_id.tax_cash_basis_rec_id', '!=', False), # Lines from non-CABA taxes are always exigible '|', ('tax_line_id.tax_exigibility', '!=', 'on_payment'), ('tax_ids.tax_exigibility', '!=', 'on_payment'), # So: exigible if at least one tax from tax_ids isn't on_payment ] def belongs_to_refund(self): """ Tells whether or not this move line corresponds to a refund operation. """ self.ensure_one() if self.tax_repartition_line_id: return self.tax_repartition_line_id.refund_tax_id elif self.move_id.move_type == 'entry': tax_type = self.tax_ids[0].type_tax_use if self.tax_ids else None return (tax_type == 'sale' and self.debit) or (tax_type == 'purchase' and self.credit) return self.move_id.move_type in ('in_refund', 'out_refund') def _get_invoiced_qty_per_product(self): qties = defaultdict(float) for aml in self: qty = aml.product_uom_id._compute_quantity(aml.quantity, aml.product_id.uom_id) if aml.move_id.move_type == 'out_invoice': qties[aml.product_id] += qty elif aml.move_id.move_type == 'out_refund': qties[aml.product_id] -= qty return qties # ------------------------------------------------------------------------- # ONCHANGE METHODS # ------------------------------------------------------------------------- @api.onchange('amount_currency', 'currency_id', 'debit', 'credit', 'tax_ids', 'account_id', 'price_unit', 'quantity') def _onchange_mark_recompute_taxes(self): ''' Recompute the dynamic onchange based on taxes. If the edited line is a tax line, don't recompute anything as the user must be able to set a custom value. ''' for line in self: if not line.tax_repartition_line_id: line.recompute_tax_line = True @api.onchange('analytic_account_id', 'analytic_tag_ids') def _onchange_mark_recompute_taxes_analytic(self): ''' Trigger tax recomputation only when some taxes with analytics ''' for line in self: if not line.tax_repartition_line_id and any(tax.analytic for tax in line.tax_ids): line.recompute_tax_line = True @api.onchange('product_id') def _onchange_product_id(self): for line in self: if not line.product_id or line.display_type in ('line_section', 'line_note'): continue line.name = line._get_computed_name() line.account_id = line._get_computed_account() taxes = line._get_computed_taxes() if taxes and line.move_id.fiscal_position_id: taxes = line.move_id.fiscal_position_id.map_tax(taxes) line.tax_ids = taxes line.product_uom_id = line._get_computed_uom() line.price_unit = line._get_computed_price_unit() @api.onchange('product_uom_id') def _onchange_uom_id(self): ''' Recompute the 'price_unit' depending of the unit of measure. ''' if self.display_type in ('line_section', 'line_note'): return taxes = self._get_computed_taxes() if taxes and self.move_id.fiscal_position_id: taxes = self.move_id.fiscal_position_id.map_tax(taxes) self.tax_ids = taxes self.price_unit = self._get_computed_price_unit() @api.onchange('account_id') def _onchange_account_id(self): ''' Recompute 'tax_ids' based on 'account_id'. /!\ Don't remove existing taxes if there is no explicit taxes set on the account. ''' for line in self: if not line.display_type and (line.account_id.tax_ids or not line.tax_ids): taxes = line._get_computed_taxes() if taxes and line.move_id.fiscal_position_id: taxes = line.move_id.fiscal_position_id.map_tax(taxes) line.tax_ids = taxes def _onchange_balance(self): for line in self: if line.currency_id == line.move_id.company_id.currency_id: line.amount_currency = line.balance else: continue if not line.move_id.is_invoice(include_receipts=True): continue line.update(line._get_fields_onchange_balance()) @api.onchange('debit') def _onchange_debit(self): if self.debit: self.credit = 0.0 self._onchange_balance() @api.onchange('credit') def _onchange_credit(self): if self.credit: self.debit = 0.0 self._onchange_balance() @api.onchange('amount_currency') def _onchange_amount_currency(self): for line in self: company = line.move_id.company_id balance = line.currency_id._convert(line.amount_currency, company.currency_id, company, line.move_id.date or fields.Date.context_today(line)) line.debit = balance if balance > 0.0 else 0.0 line.credit = -balance if balance < 0.0 else 0.0 if not line.move_id.is_invoice(include_receipts=True): continue line.update(line._get_fields_onchange_balance()) line.update(line._get_price_total_and_subtotal()) @api.onchange('quantity', 'discount', 'price_unit', 'tax_ids') def _onchange_price_subtotal(self): for line in self: if not line.move_id.is_invoice(include_receipts=True): continue line.update(line._get_price_total_and_subtotal()) line.update(line._get_fields_onchange_subtotal()) @api.onchange('currency_id') def _onchange_currency(self): for line in self: company = line.move_id.company_id if line.move_id.is_invoice(include_receipts=True): line._onchange_price_subtotal() elif not line.move_id.reversed_entry_id: balance = line.currency_id._convert(line.amount_currency, company.currency_id, company, line.move_id.date or fields.Date.context_today(line)) line.debit = balance if balance > 0.0 else 0.0 line.credit = -balance if balance < 0.0 else 0.0 # ------------------------------------------------------------------------- # COMPUTE METHODS # ------------------------------------------------------------------------- @api.depends('full_reconcile_id.name', 'matched_debit_ids', 'matched_credit_ids') def _compute_matching_number(self): for record in self: if record.full_reconcile_id: record.matching_number = record.full_reconcile_id.name elif record.matched_debit_ids or record.matched_credit_ids: record.matching_number = 'P' else: record.matching_number = None @api.depends('debit', 'credit') def _compute_balance(self): for line in self: line.balance = line.debit - line.credit @api.model def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None): def to_tuple(t): return tuple(map(to_tuple, t)) if isinstance(t, (list, tuple)) else t # Make an explicit order because we will need to reverse it order = (order or self._order) + ', id' # Add the domain and order by in order to compute the cumulated balance in _compute_cumulated_balance return super(AccountMoveLine, self.with_context(domain_cumulated_balance=to_tuple(domain or []), order_cumulated_balance=order)).search_read(domain, fields, offset, limit, order) @api.model def fields_get(self, allfields=None, attributes=None): res = super().fields_get(allfields, attributes) if res.get('cumulated_balance'): res['cumulated_balance']['exportable'] = False return res @api.depends_context('order_cumulated_balance', 'domain_cumulated_balance') def _compute_cumulated_balance(self): if not self.env.context.get('order_cumulated_balance'): # We do not come from search_read, so we are not in a list view, so it doesn't make any sense to compute the cumulated balance self.cumulated_balance = 0 return # get the where clause query = self._where_calc(list(self.env.context.get('domain_cumulated_balance') or [])) order_string = ", ".join(self._generate_order_by_inner(self._table, self.env.context.get('order_cumulated_balance'), query, reverse_direction=True)) from_clause, where_clause, where_clause_params = query.get_sql() sql = """ SELECT account_move_line.id, SUM(account_move_line.balance) OVER ( ORDER BY %(order_by)s ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) FROM %(from)s WHERE %(where)s """ % {'from': from_clause, 'where': where_clause or 'TRUE', 'order_by': order_string} self.env.cr.execute(sql, where_clause_params) result = {r[0]: r[1] for r in self.env.cr.fetchall()} for record in self: record.cumulated_balance = result[record.id] @api.depends('debit', 'credit', 'amount_currency', 'account_id', 'currency_id', 'parent_state', 'company_id', 'matched_debit_ids', 'matched_credit_ids') def _compute_amount_residual(self): """ Computes the residual amount of a move line from a reconcilable account in the company currency and the line's currency. This amount will be 0 for fully reconciled lines or lines from a non-reconcilable account, the original line amount for unreconciled lines, and something in-between for partially reconciled lines. """ for line in self: if line.id and (line.account_id.reconcile or line.account_id.internal_type == 'liquidity'): reconciled_balance = sum(line.matched_credit_ids.mapped('amount')) \ - sum(line.matched_debit_ids.mapped('amount')) reconciled_amount_currency = sum(line.matched_credit_ids.mapped('debit_amount_currency'))\ - sum(line.matched_debit_ids.mapped('credit_amount_currency')) line.amount_residual = line.balance - reconciled_balance if line.currency_id: line.amount_residual_currency = line.amount_currency - reconciled_amount_currency else: line.amount_residual_currency = 0.0 line.reconciled = ( line.company_currency_id.is_zero(line.amount_residual) and (not line.currency_id or line.currency_id.is_zero(line.amount_residual_currency)) and (line.matched_debit_ids or line.matched_credit_ids) ) else: # Must not have any reconciliation since the line is not eligible for that. line.amount_residual = 0.0 line.amount_residual_currency = 0.0 line.reconciled = False @api.depends('tax_repartition_line_id.invoice_tax_id', 'tax_repartition_line_id.refund_tax_id') def _compute_tax_line_id(self): """ tax_line_id is computed as the tax linked to the repartition line creating the move. """ for record in self: rep_line = record.tax_repartition_line_id # A constraint on account.tax.repartition.line ensures both those fields are mutually exclusive record.tax_line_id = rep_line.invoice_tax_id or rep_line.refund_tax_id @api.depends('move_id.move_type', 'tax_ids', 'tax_repartition_line_id', 'debit', 'credit', 'tax_tag_ids') def _compute_tax_tag_invert(self): for record in self: if not record.tax_repartition_line_id and not record.tax_ids : # Invoices imported from other softwares might only have kept the tags, not the taxes. record.tax_tag_invert = record.tax_tag_ids and record.move_id.is_inbound() elif record.move_id.move_type == 'entry': # For misc operations, cash basis entries and write-offs from the bank reconciliation widget rep_line = record.tax_repartition_line_id if rep_line: tax_type = (rep_line.refund_tax_id or rep_line.invoice_tax_id).type_tax_use is_refund = bool(rep_line.refund_tax_id) elif record.tax_ids: tax_type = record.tax_ids[0].type_tax_use is_refund = (tax_type == 'sale' and record.debit) or (tax_type == 'purchase' and record.credit) record.tax_tag_invert = (tax_type == 'purchase' and is_refund) or (tax_type == 'sale' and not is_refund) else: # For invoices with taxes record.tax_tag_invert = record.move_id.is_inbound() @api.depends('tax_tag_ids', 'debit', 'credit', 'journal_id', 'tax_tag_invert') def _compute_tax_audit(self): separator = ' ' for record in self: currency = record.company_id.currency_id audit_str = '' for tag in record.tax_tag_ids: tag_amount = (record.tax_tag_invert and -1 or 1) * (tag.tax_negate and -1 or 1) * record.balance if tag.tax_report_line_ids: #Then, the tag comes from a report line, and hence has a + or - sign (also in its name) for report_line in tag.tax_report_line_ids: audit_str += separator if audit_str else '' audit_str += report_line.tag_name + ': ' + formatLang(self.env, tag_amount, currency_obj=currency) else: # Then, it's a financial tag (sign is always +, and never shown in tag name) audit_str += separator if audit_str else '' audit_str += tag.name + ': ' + formatLang(self.env, tag_amount, currency_obj=currency) record.tax_audit = audit_str # ------------------------------------------------------------------------- # CONSTRAINT METHODS # ------------------------------------------------------------------------- @api.constrains('account_id', 'journal_id') def _check_constrains_account_id_journal_id(self): for line in self.filtered(lambda x: x.display_type not in ('line_section', 'line_note')): account = line.account_id journal = line.move_id.journal_id if account.deprecated: raise UserError(_('The account %s (%s) is deprecated.') % (account.name, account.code)) account_currency = account.currency_id if account_currency and account_currency != line.company_currency_id and account_currency != line.currency_id: raise UserError(_('The account selected on your journal entry forces to provide a secondary currency. You should remove the secondary currency on the account.')) if account.allowed_journal_ids and journal not in account.allowed_journal_ids: raise UserError(_('You cannot use this account (%s) in this journal, check the field \'Allowed Journals\' on the related account.', account.display_name)) if account in (journal.default_account_id, journal.suspense_account_id): continue is_account_control_ok = not journal.account_control_ids or account in journal.account_control_ids is_type_control_ok = not journal.type_control_ids or account.user_type_id in journal.type_control_ids if not is_account_control_ok or not is_type_control_ok: raise UserError(_("You cannot use this account (%s) in this journal, check the section 'Control-Access' under " "tab 'Advanced Settings' on the related journal.", account.display_name)) @api.constrains('account_id', 'tax_ids', 'tax_line_id', 'reconciled') def _check_off_balance(self): for line in self: if line.account_id.internal_group == 'off_balance': if any(a.internal_group != line.account_id.internal_group for a in line.move_id.line_ids.account_id): raise UserError(_('If you want to use "Off-Balance Sheet" accounts, all the accounts of the journal entry must be of this type')) if line.tax_ids or line.tax_line_id: raise UserError(_('You cannot use taxes on lines with an Off-Balance account')) if line.reconciled: raise UserError(_('Lines from "Off-Balance Sheet" accounts cannot be reconciled')) @api.constrains('product_uom_id') def _check_product_uom_category_id(self): for line in self: if line.product_uom_id and line.product_id and line.product_uom_id.category_id != line.product_id.product_tmpl_id.uom_id.category_id: raise UserError(_( "The Unit of Measure (UoM) '%s' you have selected for product '%s', " "is incompatible with its category : %s.", line.product_uom_id.name, line.product_id.name, line.product_id.product_tmpl_id.uom_id.category_id.name )) def _affect_tax_report(self): self.ensure_one() return self.tax_ids or self.tax_line_id or self.tax_tag_ids.filtered(lambda x: x.applicability == "taxes") def _check_tax_lock_date(self): for line in self.filtered(lambda l: l.move_id.state == 'posted'): move = line.move_id if move.company_id.tax_lock_date and move.date <= move.company_id.tax_lock_date and line._affect_tax_report(): raise UserError(_("The operation is refused as it would impact an already issued tax statement. " "Please change the journal entry date or the tax lock date set in the settings (%s) to proceed.") % format_date(self.env, move.company_id.tax_lock_date)) def _check_reconciliation(self): for line in self: if line.matched_debit_ids or line.matched_credit_ids: raise UserError(_("You cannot do this modification on a reconciled journal entry. " "You can just change some non legal fields or you must unreconcile first.\n" "Journal Entry (id): %s (%s)") % (line.move_id.name, line.move_id.id)) @api.constrains('tax_ids', 'tax_repartition_line_id') def _check_caba_non_caba_shared_tags(self): """ When mixing cash basis and non cash basis taxes, it is important that those taxes don't share tags on the repartition creating a single account.move.line. Shared tags in this context cannot work, as the tags would need to be present on both the invoice and cash basis move, leading to the same base amount to be taken into account twice; which is wrong.This is why we don't support that. A workaround may be provided by the use of a group of taxes, whose children are type_tax_use=None, and only one of them uses the common tag. Note that taxes of the same exigibility are allowed to share tags. """ def get_base_repartition(base_aml, taxes): if not taxes: return self.env['account.tax.repartition.line'] is_refund = base_aml.belongs_to_refund() repartition_field = is_refund and 'refund_repartition_line_ids' or 'invoice_repartition_line_ids' return taxes.mapped(repartition_field) for aml in self: caba_taxes = aml.tax_ids.filtered(lambda x: x.tax_exigibility == 'on_payment') non_caba_taxes = aml.tax_ids - caba_taxes caba_base_tags = get_base_repartition(aml, caba_taxes).filtered(lambda x: x.repartition_type == 'base').tag_ids non_caba_base_tags = get_base_repartition(aml, non_caba_taxes).filtered(lambda x: x.repartition_type == 'base').tag_ids common_tags = caba_base_tags & non_caba_base_tags if not common_tags: # When a tax is affecting another one with different tax exigibility, tags cannot be shared either. tax_tags = aml.tax_repartition_line_id.tag_ids comparison_tags = non_caba_base_tags if aml.tax_repartition_line_id.tax_id.tax_exigibility == 'on_payment' else caba_base_tags common_tags = tax_tags & comparison_tags if common_tags: raise ValidationError(_("Taxes exigible on payment and on invoice cannot be mixed on the same journal item if they share some tag.")) # ------------------------------------------------------------------------- # LOW-LEVEL METHODS # ------------------------------------------------------------------------- def init(self): """ change index on partner_id to a multi-column index on (partner_id, ref), the new index will behave in the same way when we search on partner_id, with the addition of being optimal when having a query that will search on partner_id and ref at the same time (which is the case when we open the bank reconciliation widget) """ cr = self._cr cr.execute('DROP INDEX IF EXISTS account_move_line_partner_id_index') cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', ('account_move_line_partner_id_ref_idx',)) if not cr.fetchone(): cr.execute('CREATE INDEX account_move_line_partner_id_ref_idx ON account_move_line (partner_id, ref)') @api.model_create_multi def create(self, vals_list): # OVERRIDE ACCOUNTING_FIELDS = ('debit', 'credit', 'amount_currency') BUSINESS_FIELDS = ('price_unit', 'quantity', 'discount', 'tax_ids') for vals in vals_list: move = self.env['account.move'].browse(vals['move_id']) vals.setdefault('company_currency_id', move.company_id.currency_id.id) # important to bypass the ORM limitation where monetary fields are not rounded; more info in the commit message # Ensure balance == amount_currency in case of missing currency or same currency as the one from the # company. currency_id = vals.get('currency_id') or move.company_id.currency_id.id if currency_id == move.company_id.currency_id.id: balance = vals.get('debit', 0.0) - vals.get('credit', 0.0) vals.update({ 'currency_id': currency_id, 'amount_currency': balance, }) else: vals['amount_currency'] = vals.get('amount_currency', 0.0) if move.is_invoice(include_receipts=True): currency = move.currency_id partner = self.env['res.partner'].browse(vals.get('partner_id')) taxes = self.new({'tax_ids': vals.get('tax_ids', [])}).tax_ids tax_ids = set(taxes.ids) taxes = self.env['account.tax'].browse(tax_ids) # Ensure consistency between accounting & business fields. # As we can't express such synchronization as computed fields without cycling, we need to do it both # in onchange and in create/write. So, if something changed in accounting [resp. business] fields, # business [resp. accounting] fields are recomputed. if any(vals.get(field) for field in ACCOUNTING_FIELDS): price_subtotal = self._get_price_total_and_subtotal_model( vals.get('price_unit', 0.0), vals.get('quantity', 0.0), vals.get('discount', 0.0), currency, self.env['product.product'].browse(vals.get('product_id')), partner, taxes, move.move_type, ).get('price_subtotal', 0.0) vals.update(self._get_fields_onchange_balance_model( vals.get('quantity', 0.0), vals.get('discount', 0.0), vals['amount_currency'], move.move_type, currency, taxes, price_subtotal )) vals.update(self._get_price_total_and_subtotal_model( vals.get('price_unit', 0.0), vals.get('quantity', 0.0), vals.get('discount', 0.0), currency, self.env['product.product'].browse(vals.get('product_id')), partner, taxes, move.move_type, )) elif any(vals.get(field) for field in BUSINESS_FIELDS): vals.update(self._get_price_total_and_subtotal_model( vals.get('price_unit', 0.0), vals.get('quantity', 0.0), vals.get('discount', 0.0), currency, self.env['product.product'].browse(vals.get('product_id')), partner, taxes, move.move_type, )) vals.update(self._get_fields_onchange_subtotal_model( vals['price_subtotal'], move.move_type, currency, move.company_id, move.date, )) lines = super(AccountMoveLine, self).create(vals_list) moves = lines.mapped('move_id') if self._context.get('check_move_validity', True): moves._check_balanced() moves.filtered(lambda m: m.state == 'posted')._check_fiscalyear_lock_date() lines.filtered(lambda l: l.parent_state == 'posted')._check_tax_lock_date() moves._synchronize_business_models({'line_ids'}) return lines def write(self, vals): # OVERRIDE ACCOUNTING_FIELDS = ('debit', 'credit', 'amount_currency') BUSINESS_FIELDS = ('price_unit', 'quantity', 'discount', 'tax_ids') PROTECTED_FIELDS_TAX_LOCK_DATE = ['debit', 'credit', 'tax_line_id', 'tax_ids', 'tax_tag_ids'] PROTECTED_FIELDS_LOCK_DATE = PROTECTED_FIELDS_TAX_LOCK_DATE + ['account_id', 'journal_id', 'amount_currency', 'currency_id', 'partner_id'] PROTECTED_FIELDS_RECONCILIATION = ('account_id', 'date', 'debit', 'credit', 'amount_currency', 'currency_id') account_to_write = self.env['account.account'].browse(vals['account_id']) if 'account_id' in vals else None # Check writing a deprecated account. if account_to_write and account_to_write.deprecated: raise UserError(_('You cannot use a deprecated account.')) inalterable_fields = set(self._get_integrity_hash_fields()).union({'inalterable_hash', 'secure_sequence_number'}) hashed_moves = self.move_id.filtered('inalterable_hash') violated_fields = set(vals) & inalterable_fields if hashed_moves and violated_fields: raise UserError(_( "You cannot edit the following fields: %s.\n" "The following entries are already hashed:\n%s", ', '.join(f['string'] for f in self.fields_get(violated_fields).values()), '\n'.join(hashed_moves.mapped('name')), )) for line in self: if line.parent_state == 'posted': if any(key in vals for key in ('tax_ids', 'tax_line_id')): raise UserError(_('You cannot modify the taxes related to a posted journal item, you should reset the journal entry to draft to do so.')) # Check the lock date. if line.parent_state == 'posted' and any(self.env['account.move']._field_will_change(line, vals, field_name) for field_name in PROTECTED_FIELDS_LOCK_DATE): line.move_id._check_fiscalyear_lock_date() # Check the tax lock date. if line.parent_state == 'posted' and any(self.env['account.move']._field_will_change(line, vals, field_name) for field_name in PROTECTED_FIELDS_TAX_LOCK_DATE): line._check_tax_lock_date() # Check the reconciliation. if any(self.env['account.move']._field_will_change(line, vals, field_name) for field_name in PROTECTED_FIELDS_RECONCILIATION): line._check_reconciliation() # Check switching receivable / payable accounts. if account_to_write: account_type = line.account_id.user_type_id.type if line.move_id.is_sale_document(include_receipts=True): if (account_type == 'receivable' and account_to_write.user_type_id.type != account_type) \ or (account_type != 'receivable' and account_to_write.user_type_id.type == 'receivable'): raise UserError(_("You can only set an account having the receivable type on payment terms lines for customer invoice.")) if line.move_id.is_purchase_document(include_receipts=True): if (account_type == 'payable' and account_to_write.user_type_id.type != account_type) \ or (account_type != 'payable' and account_to_write.user_type_id.type == 'payable'): raise UserError(_("You can only set an account having the payable type on payment terms lines for vendor bill.")) # Tracking stuff can be skipped for perfs using tracking_disable context key if not self.env.context.get('tracking_disable', False): # Get all tracked fields (without related fields because these fields must be manage on their own model) tracking_fields = [] for value in vals: field = self._fields[value] if hasattr(field, 'related') and field.related: continue # We don't want to track related field. if hasattr(field, 'tracking') and field.tracking: tracking_fields.append(value) ref_fields = self.env['account.move.line'].fields_get(tracking_fields) # Get initial values for each line move_initial_values = {} for line in self.filtered(lambda l: l.move_id.posted_before): # Only lines with posted once move. for field in tracking_fields: # Group initial values by move_id if line.move_id.id not in move_initial_values: move_initial_values[line.move_id.id] = {} move_initial_values[line.move_id.id].update({field: line[field]}) result = True for line in self: cleaned_vals = line.move_id._cleanup_write_orm_values(line, vals) if not cleaned_vals: continue # Auto-fill amount_currency if working in single-currency. if 'currency_id' not in cleaned_vals \ and line.currency_id == line.company_currency_id \ and any(field_name in cleaned_vals for field_name in ('debit', 'credit')): cleaned_vals.update({ 'amount_currency': vals.get('debit', 0.0) - vals.get('credit', 0.0), }) result |= super(AccountMoveLine, line).write(cleaned_vals) if not line.move_id.is_invoice(include_receipts=True): continue # Ensure consistency between accounting & business fields. # As we can't express such synchronization as computed fields without cycling, we need to do it both # in onchange and in create/write. So, if something changed in accounting [resp. business] fields, # business [resp. accounting] fields are recomputed. if any(field in cleaned_vals for field in ACCOUNTING_FIELDS): price_subtotal = line._get_price_total_and_subtotal().get('price_subtotal', 0.0) to_write = line._get_fields_onchange_balance(price_subtotal=price_subtotal) to_write.update(line._get_price_total_and_subtotal( price_unit=to_write.get('price_unit', line.price_unit), quantity=to_write.get('quantity', line.quantity), discount=to_write.get('discount', line.discount), )) result |= super(AccountMoveLine, line).write(to_write) elif any(field in cleaned_vals for field in BUSINESS_FIELDS): to_write = line._get_price_total_and_subtotal() to_write.update(line._get_fields_onchange_subtotal( price_subtotal=to_write['price_subtotal'], )) result |= super(AccountMoveLine, line).write(to_write) # Check total_debit == total_credit in the related moves. if self._context.get('check_move_validity', True): self.mapped('move_id')._check_balanced() self.mapped('move_id')._synchronize_business_models({'line_ids'}) if not self.env.context.get('tracking_disable', False): # Log changes to move lines on each move for move_id, modified_lines in move_initial_values.items(): for line in self.filtered(lambda l: l.move_id.id == move_id): tracking_value_ids = line._mail_track(ref_fields, modified_lines)[1] if tracking_value_ids: msg = f"{html_escape(_('Journal Item'))} <a href=# data-oe-model=account.move.line data-oe-id={line.id}>#{line.id}</a> {html_escape(_('updated'))}" line.move_id._message_log( body=msg, tracking_value_ids=tracking_value_ids ) return result def _valid_field_parameter(self, field, name): # I can't even return name == 'tracking' or super()._valid_field_parameter(field, name) @api.ondelete(at_uninstall=False) def _unlink_except_posted(self): # Prevent deleting lines on posted entries if not self._context.get('force_delete') and any(m.state == 'posted' for m in self.move_id): raise UserError(_('You cannot delete an item linked to a posted entry.')) def unlink(self): moves = self.mapped('move_id') # Check the lines are not reconciled (partially or not). self._check_reconciliation() # Check the lock date. moves._check_fiscalyear_lock_date() # Check the tax lock date. self._check_tax_lock_date() res = super(AccountMoveLine, self).unlink() # Check total_debit == total_credit in the related moves. if self._context.get('check_move_validity', True): moves._check_balanced() return res @api.model def default_get(self, default_fields): # OVERRIDE values = super(AccountMoveLine, self).default_get(default_fields) if 'account_id' in default_fields and not values.get('account_id') \ and (self._context.get('journal_id') or self._context.get('default_journal_id')) \ and self._context.get('default_move_type') in ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt'): # Fill missing 'account_id'. journal = self.env['account.journal'].browse(self._context.get('default_journal_id') or self._context['journal_id']) values['account_id'] = journal.default_account_id.id elif self._context.get('line_ids') and any(field_name in default_fields for field_name in ('debit', 'credit', 'account_id', 'partner_id')): move = self.env['account.move'].new({'line_ids': self._context['line_ids']}) # Suggest default value for debit / credit to balance the journal entry. balance = sum(line['debit'] - line['credit'] for line in move.line_ids) # if we are here, line_ids is in context, so journal_id should also be. journal = self.env['account.journal'].browse(self._context.get('default_journal_id') or self._context['journal_id']) currency = journal.exists() and journal.company_id.currency_id if currency: balance = currency.round(balance) if balance < 0.0: values.update({'debit': -balance}) if balance > 0.0: values.update({'credit': balance}) # Suggest default value for 'partner_id'. if 'partner_id' in default_fields and not values.get('partner_id'): if len(move.line_ids[-2:]) == 2 and move.line_ids[-1].partner_id == move.line_ids[-2].partner_id != False: values['partner_id'] = move.line_ids[-2:].mapped('partner_id').id # Suggest default value for 'account_id'. if 'account_id' in default_fields and not values.get('account_id'): if len(move.line_ids[-2:]) == 2 and move.line_ids[-1].account_id == move.line_ids[-2].account_id != False: values['account_id'] = move.line_ids[-2:].mapped('account_id').id if values.get('display_type') or self.display_type: values.pop('account_id', None) return values @api.depends('ref', 'move_id') def name_get(self): result = [] for line in self: name = line.move_id.name or '' if line.ref: name += " (%s)" % line.ref name += (line.name or line.product_id.display_name) and (' ' + (line.name or line.product_id.display_name)) or '' result.append((line.id, name)) return result @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): if operator == 'ilike': domain = ['|', '|', ('name', 'ilike', name), ('move_id', 'ilike', name), ('product_id', 'ilike', name)] return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid) return super()._name_search(name, args=args, operator=operator, limit=limit, name_get_uid=name_get_uid) @api.model def invalidate_cache(self, fnames=None, ids=None): # Invalidate cache of related moves if fnames is None or 'move_id' in fnames: field = self._fields['move_id'] lines = self.env.cache.get_records(self, field) if ids is None else self.browse(ids) move_ids = {id_ for id_ in self.env.cache.get_values(lines, field) if id_} if move_ids: self.env['account.move'].invalidate_cache(ids=move_ids) return super().invalidate_cache(fnames=fnames, ids=ids) # ------------------------------------------------------------------------- # TRACKING METHODS # ------------------------------------------------------------------------- def _mail_track(self, tracked_fields, initial): changes, tracking_value_ids = super()._mail_track(tracked_fields, initial) if len(changes) > len(tracking_value_ids): for i, changed_field in enumerate(changes): if tracked_fields[changed_field]['type'] in ['one2many', 'many2many']: field = self.env['ir.model.fields']._get(self._name, changed_field) vals = { 'field': field.id, 'field_desc': field.field_description, 'field_type': field.ttype, 'tracking_sequence': field.tracking, 'old_value_char': ', '.join(initial[changed_field].mapped('name')), 'new_value_char': ', '.join(self[changed_field].mapped('name')), } tracking_value_ids.insert(i, Command.create(vals)) return changes, tracking_value_ids # ------------------------------------------------------------------------- # RECONCILIATION # ------------------------------------------------------------------------- def _prepare_reconciliation_partials(self): ''' Prepare the partials on the current journal items to perform the reconciliation. /!\ The order of records in self is important because the journal items will be reconciled using this order. :return: A recordset of account.partial.reconcile. ''' def fix_remaining_cent(currency, abs_residual, partial_amount): if abs_residual - currency.rounding <= partial_amount <= abs_residual + currency.rounding: return abs_residual else: return partial_amount debit_lines = iter(self.filtered(lambda line: line.balance > 0.0 or line.amount_currency > 0.0 and not line.reconciled)) credit_lines = iter(self.filtered(lambda line: line.balance < 0.0 or line.amount_currency < 0.0 and not line.reconciled)) void_lines = iter(self.filtered(lambda line: not line.balance and not line.amount_currency and not line.reconciled)) debit_line = None credit_line = None debit_amount_residual = 0.0 debit_amount_residual_currency = 0.0 credit_amount_residual = 0.0 credit_amount_residual_currency = 0.0 debit_line_currency = None credit_line_currency = None partials_vals_list = [] while True: # Move to the next available debit line. if not debit_line: debit_line = next(debit_lines, None) or next(void_lines, None) if not debit_line: break debit_amount_residual = debit_line.amount_residual if debit_line.currency_id: debit_amount_residual_currency = debit_line.amount_residual_currency debit_line_currency = debit_line.currency_id else: debit_amount_residual_currency = debit_amount_residual debit_line_currency = debit_line.company_currency_id # Move to the next available credit line. if not credit_line: credit_line = next(void_lines, None) or next(credit_lines, None) if not credit_line: break credit_amount_residual = credit_line.amount_residual if credit_line.currency_id: credit_amount_residual_currency = credit_line.amount_residual_currency credit_line_currency = credit_line.currency_id else: credit_amount_residual_currency = credit_amount_residual credit_line_currency = credit_line.company_currency_id min_amount_residual = min(debit_amount_residual, -credit_amount_residual) if debit_line_currency == credit_line_currency: # Reconcile on the same currency. min_amount_residual_currency = min(debit_amount_residual_currency, -credit_amount_residual_currency) min_debit_amount_residual_currency = min_amount_residual_currency min_credit_amount_residual_currency = min_amount_residual_currency else: # Reconcile on the company's currency. min_debit_amount_residual_currency = credit_line.company_currency_id._convert( min_amount_residual, debit_line.currency_id, credit_line.company_id, credit_line.date, ) min_debit_amount_residual_currency = fix_remaining_cent( debit_line.currency_id, debit_amount_residual_currency, min_debit_amount_residual_currency, ) min_credit_amount_residual_currency = debit_line.company_currency_id._convert( min_amount_residual, credit_line.currency_id, debit_line.company_id, debit_line.date, ) min_credit_amount_residual_currency = fix_remaining_cent( credit_line.currency_id, -credit_amount_residual_currency, min_credit_amount_residual_currency, ) debit_amount_residual -= min_amount_residual debit_amount_residual_currency -= min_debit_amount_residual_currency credit_amount_residual += min_amount_residual credit_amount_residual_currency += min_credit_amount_residual_currency partials_vals_list.append({ 'amount': min_amount_residual, 'debit_amount_currency': min_debit_amount_residual_currency, 'credit_amount_currency': min_credit_amount_residual_currency, 'debit_move_id': debit_line.id, 'credit_move_id': credit_line.id, }) has_debit_residual_left = not debit_line.company_currency_id.is_zero(debit_amount_residual) and debit_amount_residual > 0.0 has_credit_residual_left = not credit_line.company_currency_id.is_zero(credit_amount_residual) and credit_amount_residual < 0.0 has_debit_residual_curr_left = not debit_line_currency.is_zero(debit_amount_residual_currency) and debit_amount_residual_currency > 0.0 has_credit_residual_curr_left = not credit_line_currency.is_zero(credit_amount_residual_currency) and credit_amount_residual_currency < 0.0 if debit_line_currency == credit_line_currency: # The debit line is now fully reconciled because: # - either amount_residual & amount_residual_currency are at 0. # - either the credit_line is not an exchange difference one. if not has_debit_residual_curr_left and (has_credit_residual_curr_left or not has_debit_residual_left): debit_line = None # The credit line is now fully reconciled because: # - either amount_residual & amount_residual_currency are at 0. # - either the debit is not an exchange difference one. if not has_credit_residual_curr_left and (has_debit_residual_curr_left or not has_credit_residual_left): credit_line = None else: # The debit line is now fully reconciled since amount_residual is 0. if not has_debit_residual_left: debit_line = None # The credit line is now fully reconciled since amount_residual is 0. if not has_credit_residual_left: credit_line = None return partials_vals_list def _create_exchange_difference_move(self): ''' Create the exchange difference journal entry on the current journal items. :return: An account.move record. ''' def _add_lines_to_exchange_difference_vals(lines, exchange_diff_move_vals): ''' Generate the exchange difference values used to create the journal items in order to fix the residual amounts and add them into 'exchange_diff_move_vals'. 1) When reconciled on the same foreign currency, the journal items are fully reconciled regarding this currency but it could be not the case of the balance that is expressed using the company's currency. In that case, we need to create exchange difference journal items to ensure this residual amount reaches zero. 2) When reconciled on the company currency but having different foreign currencies, the journal items are fully reconciled regarding the company currency but it's not always the case for the foreign currencies. In that case, the exchange difference journal items are created to ensure this residual amount in foreign currency reaches zero. :param lines: The account.move.lines to which fix the residual amounts. :param exchange_diff_move_vals: The current vals of the exchange difference journal entry. :return: A list of pair <line, sequence> to perform the reconciliation at the creation of the exchange difference move where 'line' is the account.move.line to which the 'sequence'-th exchange difference line will be reconciled with. ''' journal = self.env['account.journal'].browse(exchange_diff_move_vals['journal_id']) to_reconcile = [] for line in lines: exchange_diff_move_vals['date'] = max(exchange_diff_move_vals['date'], line.date) if not line.company_currency_id.is_zero(line.amount_residual): # amount_residual_currency == 0 and amount_residual has to be fixed. if line.amount_residual > 0.0: exchange_line_account = journal.company_id.expense_currency_exchange_account_id else: exchange_line_account = journal.company_id.income_currency_exchange_account_id elif line.currency_id and not line.currency_id.is_zero(line.amount_residual_currency): # amount_residual == 0 and amount_residual_currency has to be fixed. if line.amount_residual_currency > 0.0: exchange_line_account = journal.company_id.expense_currency_exchange_account_id else: exchange_line_account = journal.company_id.income_currency_exchange_account_id else: continue sequence = len(exchange_diff_move_vals['line_ids']) exchange_diff_move_vals['line_ids'] += [ (0, 0, { 'name': _('Currency exchange rate difference'), 'debit': -line.amount_residual if line.amount_residual < 0.0 else 0.0, 'credit': line.amount_residual if line.amount_residual > 0.0 else 0.0, 'amount_currency': -line.amount_residual_currency, 'account_id': line.account_id.id, 'currency_id': line.currency_id.id, 'partner_id': line.partner_id.id, 'sequence': sequence, }), (0, 0, { 'name': _('Currency exchange rate difference'), 'debit': line.amount_residual if line.amount_residual > 0.0 else 0.0, 'credit': -line.amount_residual if line.amount_residual < 0.0 else 0.0, 'amount_currency': line.amount_residual_currency, 'account_id': exchange_line_account.id, 'currency_id': line.currency_id.id, 'partner_id': line.partner_id.id, 'sequence': sequence + 1, }), ] to_reconcile.append((line, sequence)) return to_reconcile def _add_cash_basis_lines_to_exchange_difference_vals(lines, exchange_diff_move_vals): ''' Generate the exchange difference values used to create the journal items in order to fix the cash basis lines using the transfer account in a multi-currencies environment when this account is not a reconcile one. When the tax cash basis journal entries are generated and all involved transfer account set on taxes are all reconcilable, the account balance will be reset to zero by the exchange difference journal items generated above. However, this mechanism will not work if there is any transfer accounts that are not reconcile and we are generating the cash basis journal items in a foreign currency. In that specific case, we need to generate extra journal items at the generation of the exchange difference journal entry to ensure this balance is reset to zero and then, will not appear on the tax report leading to erroneous tax base amount / tax amount. :param lines: The account.move.lines to which fix the residual amounts. :param exchange_diff_move_vals: The current vals of the exchange difference journal entry. ''' for move in lines.move_id: account_vals_to_fix = {} move_values = move._collect_tax_cash_basis_values() # The cash basis doesn't need to be handle for this move because there is another payment term # line that is not yet fully paid. if not move_values or not move_values['is_fully_paid']: continue # ========================================================================== # Add the balance of all tax lines of the current move in order in order # to compute the residual amount for each of them. # ========================================================================== for caba_treatment, line in move_values['to_process_lines']: vals = { 'currency_id': line.currency_id.id, 'partner_id': line.partner_id.id, 'tax_ids': [(6, 0, line.tax_ids.ids)], 'tax_tag_ids': [(6, 0, line.tax_tag_ids.ids)], 'debit': line.debit, 'credit': line.credit, } if caba_treatment == 'tax' and not line.reconciled: # Tax line. grouping_key = self.env['account.partial.reconcile']._get_cash_basis_tax_line_grouping_key_from_record(line) if grouping_key in account_vals_to_fix: debit = account_vals_to_fix[grouping_key]['debit'] + vals['debit'] credit = account_vals_to_fix[grouping_key]['credit'] + vals['credit'] balance = debit - credit account_vals_to_fix[grouping_key].update({ 'debit': balance if balance > 0 else 0, 'credit': -balance if balance < 0 else 0, 'tax_base_amount': account_vals_to_fix[grouping_key]['tax_base_amount'] + line.tax_base_amount, }) else: account_vals_to_fix[grouping_key] = { **vals, 'account_id': line.account_id.id, 'tax_base_amount': line.tax_base_amount, 'tax_repartition_line_id': line.tax_repartition_line_id.id, } elif caba_treatment == 'base': # Base line. account_to_fix = line.company_id.account_cash_basis_base_account_id if not account_to_fix: continue grouping_key = self.env['account.partial.reconcile']._get_cash_basis_base_line_grouping_key_from_record(line, account=account_to_fix) if grouping_key not in account_vals_to_fix: account_vals_to_fix[grouping_key] = { **vals, 'account_id': account_to_fix.id, } else: # Multiple base lines could share the same key, if the same # cash basis tax is used alone on several lines of the invoices account_vals_to_fix[grouping_key]['debit'] += vals['debit'] account_vals_to_fix[grouping_key]['credit'] += vals['credit'] # ========================================================================== # Subtract the balance of all previously generated cash basis journal entries # in order to retrieve the residual balance of each involved transfer account. # ========================================================================== cash_basis_moves = self.env['account.move'].search([('tax_cash_basis_origin_move_id', '=', move.id)]) for line in cash_basis_moves.line_ids: grouping_key = None if line.tax_repartition_line_id: # Tax line. grouping_key = self.env['account.partial.reconcile']._get_cash_basis_tax_line_grouping_key_from_record( line, account=line.tax_line_id.cash_basis_transition_account_id, ) elif line.tax_ids: # Base line. grouping_key = self.env['account.partial.reconcile']._get_cash_basis_base_line_grouping_key_from_record( line, account=line.company_id.account_cash_basis_base_account_id, ) if grouping_key not in account_vals_to_fix: continue account_vals_to_fix[grouping_key]['debit'] -= line.debit account_vals_to_fix[grouping_key]['credit'] -= line.credit # ========================================================================== # Generate the exchange difference journal items: # - to reset the balance of all transfer account to zero. # - fix rounding issues on the tax account/base tax account. # ========================================================================== for values in account_vals_to_fix.values(): balance = values['debit'] - values['credit'] if move.company_currency_id.is_zero(balance): continue if values.get('tax_repartition_line_id'): # Tax line. tax_repartition_line = self.env['account.tax.repartition.line'].browse(values['tax_repartition_line_id']) account = tax_repartition_line.account_id or self.env['account.account'].browse(values['account_id']) sequence = len(exchange_diff_move_vals['line_ids']) exchange_diff_move_vals['line_ids'] += [ (0, 0, { **values, 'name': _('Currency exchange rate difference (cash basis)'), 'debit': balance if balance > 0.0 else 0.0, 'credit': -balance if balance < 0.0 else 0.0, 'account_id': account.id, 'sequence': sequence, }), (0, 0, { **values, 'name': _('Currency exchange rate difference (cash basis)'), 'debit': -balance if balance < 0.0 else 0.0, 'credit': balance if balance > 0.0 else 0.0, 'account_id': values['account_id'], 'tax_ids': [], 'tax_tag_ids': [], 'tax_repartition_line_id': False, 'sequence': sequence + 1, }), ] else: # Base line. sequence = len(exchange_diff_move_vals['line_ids']) exchange_diff_move_vals['line_ids'] += [ (0, 0, { **values, 'name': _('Currency exchange rate difference (cash basis)'), 'debit': balance if balance > 0.0 else 0.0, 'credit': -balance if balance < 0.0 else 0.0, 'sequence': sequence, }), (0, 0, { **values, 'name': _('Currency exchange rate difference (cash basis)'), 'debit': -balance if balance < 0.0 else 0.0, 'credit': balance if balance > 0.0 else 0.0, 'tax_ids': [], 'tax_tag_ids': [], 'sequence': sequence + 1, }), ] if not self: return self.env['account.move'] company = self[0].company_id journal = company.currency_exchange_journal_id exchange_diff_move_vals = { 'move_type': 'entry', 'date': date.min, 'journal_id': journal.id, 'line_ids': [], 'always_tax_exigible': True, # Enforce exigibility in case some cash basis adjustments were made in this exchange difference } # Fix residual amounts. to_reconcile = _add_lines_to_exchange_difference_vals(self, exchange_diff_move_vals) # Fix cash basis entries. # If we are fully reversing the entry, no need to fix anything since the journal entry # is exactly the mirror of the source journal entry. is_cash_basis_needed = self[0].account_internal_type in ('receivable', 'payable') if is_cash_basis_needed and not self._context.get('move_reverse_cancel'): _add_cash_basis_lines_to_exchange_difference_vals(self, exchange_diff_move_vals) # ========================================================================== # Create move and reconcile. # ========================================================================== if exchange_diff_move_vals['line_ids']: # Check the configuration of the exchange difference journal. if not journal: raise UserError(_("You should configure the 'Exchange Gain or Loss Journal' in your company settings, to manage automatically the booking of accounting entries related to differences between exchange rates.")) if not journal.company_id.expense_currency_exchange_account_id: raise UserError(_("You should configure the 'Loss Exchange Rate Account' in your company settings, to manage automatically the booking of accounting entries related to differences between exchange rates.")) if not journal.company_id.income_currency_exchange_account_id.id: raise UserError(_("You should configure the 'Gain Exchange Rate Account' in your company settings, to manage automatically the booking of accounting entries related to differences between exchange rates.")) exchange_diff_move_vals['date'] = max(exchange_diff_move_vals['date'], company._get_user_fiscal_lock_date() + timedelta(days=1)) exchange_move = self.env['account.move'].create(exchange_diff_move_vals) else: return None # Reconcile lines to the newly created exchange difference journal entry by creating more partials. partials_vals_list = [] for source_line, sequence in to_reconcile: exchange_diff_line = exchange_move.line_ids[sequence] if source_line.company_currency_id.is_zero(source_line.amount_residual): exchange_field = 'amount_residual_currency' else: exchange_field = 'amount_residual' if exchange_diff_line[exchange_field] > 0.0: debit_line = exchange_diff_line credit_line = source_line else: debit_line = source_line credit_line = exchange_diff_line partials_vals_list.append({ 'amount': abs(source_line.amount_residual), 'debit_amount_currency': abs(debit_line.amount_residual_currency), 'credit_amount_currency': abs(credit_line.amount_residual_currency), 'debit_move_id': debit_line.id, 'credit_move_id': credit_line.id, }) self.env['account.partial.reconcile'].create(partials_vals_list) return exchange_move def reconcile(self): ''' Reconcile the current move lines all together. :return: A dictionary representing a summary of what has been done during the reconciliation: * partials: A recorset of all account.partial.reconcile created during the reconciliation. * full_reconcile: An account.full.reconcile record created when there is nothing left to reconcile in the involved lines. * tax_cash_basis_moves: An account.move recordset representing the tax cash basis journal entries. ''' results = {} if not self: return results # List unpaid invoices not_paid_invoices = self.move_id.filtered( lambda move: move.is_invoice(include_receipts=True) and move.payment_state not in ('paid', 'in_payment') ) # ==== Check the lines can be reconciled together ==== company = None account = None for line in self: if line.reconciled: raise UserError(_("You are trying to reconcile some entries that are already reconciled.")) if not line.account_id.reconcile and line.account_id.internal_type != 'liquidity': raise UserError(_("Account %s does not allow reconciliation. First change the configuration of this account to allow it.") % line.account_id.display_name) if line.move_id.state != 'posted': raise UserError(_('You can only reconcile posted entries.')) if company is None: company = line.company_id elif line.company_id != company: raise UserError(_("Entries doesn't belong to the same company: %s != %s") % (company.display_name, line.company_id.display_name)) if account is None: account = line.account_id elif line.account_id != account: raise UserError(_("Entries are not from the same account: %s != %s") % (account.display_name, line.account_id.display_name)) sorted_lines = self.sorted(key=lambda line: (line.date_maturity or line.date, line.currency_id)) # ==== Collect all involved lines through the existing reconciliation ==== involved_lines = sorted_lines involved_partials = self.env['account.partial.reconcile'] current_lines = involved_lines current_partials = involved_partials while current_lines: current_partials = (current_lines.matched_debit_ids + current_lines.matched_credit_ids) - current_partials involved_partials += current_partials current_lines = (current_partials.debit_move_id + current_partials.credit_move_id) - current_lines involved_lines += current_lines # ==== Create partials ==== partials = self.env['account.partial.reconcile'].create(sorted_lines._prepare_reconciliation_partials()) # Track newly created partials. results['partials'] = partials involved_partials += partials # ==== Create entries for cash basis taxes ==== is_cash_basis_needed = account.company_id.tax_exigibility and account.user_type_id.type in ('receivable', 'payable') if is_cash_basis_needed and not self._context.get('move_reverse_cancel'): tax_cash_basis_moves = partials._create_tax_cash_basis_moves() results['tax_cash_basis_moves'] = tax_cash_basis_moves # ==== Check if a full reconcile is needed ==== if involved_lines[0].currency_id and all(line.currency_id == involved_lines[0].currency_id for line in involved_lines): is_full_needed = all(line.currency_id.is_zero(line.amount_residual_currency) for line in involved_lines) else: is_full_needed = all(line.company_currency_id.is_zero(line.amount_residual) for line in involved_lines) if is_full_needed: # ==== Create the exchange difference move ==== if self._context.get('no_exchange_difference'): exchange_move = None else: exchange_move = involved_lines._create_exchange_difference_move() if exchange_move: exchange_move_lines = exchange_move.line_ids.filtered(lambda line: line.account_id == account) # Track newly created lines. involved_lines += exchange_move_lines # Track newly created partials. exchange_diff_partials = exchange_move_lines.matched_debit_ids \ + exchange_move_lines.matched_credit_ids involved_partials += exchange_diff_partials results['partials'] += exchange_diff_partials exchange_move._post(soft=False) # ==== Create the full reconcile ==== results['full_reconcile'] = self.env['account.full.reconcile'].create({ 'exchange_move_id': exchange_move and exchange_move.id, 'partial_reconcile_ids': [(6, 0, involved_partials.ids)], 'reconciled_line_ids': [(6, 0, involved_lines.ids)], }) # Trigger action for paid invoices not_paid_invoices\ .filtered(lambda move: move.payment_state in ('paid', 'in_payment'))\ .action_invoice_paid() return results def remove_move_reconcile(self): """ Undo a reconciliation """ (self.matched_debit_ids + self.matched_credit_ids).unlink() def _copy_data_extend_business_fields(self, values): ''' Hook allowing copying business fields under certain conditions. E.g. The link to the sale order lines must be preserved in case of a refund. ''' self.ensure_one() def copy_data(self, default=None): res = super(AccountMoveLine, self).copy_data(default=default) for line, values in zip(self, res): # Don't copy the name of a payment term line. if line.move_id.is_invoice() and line.account_id.user_type_id.type in ('receivable', 'payable'): values['name'] = '' # Don't copy restricted fields of notes if line.display_type in ('line_section', 'line_note'): values['amount_currency'] = 0 values['debit'] = 0 values['credit'] = 0 values['account_id'] = False if self._context.get('include_business_fields'): line._copy_data_extend_business_fields(values) return res # ------------------------------------------------------------------------- # MISC # ------------------------------------------------------------------------- def _get_analytic_tag_ids(self): self.ensure_one() return self.analytic_tag_ids.filtered(lambda r: not r.active_analytic_distribution).ids def create_analytic_lines(self): """ Create analytic items upon validation of an account.move.line having an analytic account or an analytic distribution. """ lines_to_create_analytic_entries = self.env['account.move.line'] analytic_line_vals = [] for obj_line in self: for tag in obj_line.analytic_tag_ids.filtered('active_analytic_distribution'): for distribution in tag.analytic_distribution_ids: analytic_line_vals.append(obj_line._prepare_analytic_distribution_line(distribution)) if obj_line.analytic_account_id: lines_to_create_analytic_entries |= obj_line # create analytic entries in batch if lines_to_create_analytic_entries: analytic_line_vals += lines_to_create_analytic_entries._prepare_analytic_line() self.env['account.analytic.line'].create(analytic_line_vals) def _prepare_analytic_line(self): """ Prepare the values used to create() an account.analytic.line upon validation of an account.move.line having an analytic account. This method is intended to be extended in other modules. :return list of values to create analytic.line :rtype list """ result = [] for move_line in self: amount = (move_line.credit or 0.0) - (move_line.debit or 0.0) default_name = move_line.name or (move_line.ref or '/' + ' -- ' + (move_line.partner_id and move_line.partner_id.name or '/')) category = 'other' if move_line.move_id.is_sale_document(): category = 'invoice' elif move_line.move_id.is_purchase_document(): category = 'vendor_bill' result.append({ 'name': default_name, 'date': move_line.date, 'account_id': move_line.analytic_account_id.id, 'group_id': move_line.analytic_account_id.group_id.id, 'tag_ids': [(6, 0, move_line._get_analytic_tag_ids())], 'unit_amount': move_line.quantity, 'product_id': move_line.product_id and move_line.product_id.id or False, 'product_uom_id': move_line.product_uom_id and move_line.product_uom_id.id or False, 'amount': amount, 'general_account_id': move_line.account_id.id, 'ref': move_line.ref, 'move_id': move_line.id, 'user_id': move_line.move_id.invoice_user_id.id or self._uid, 'partner_id': move_line.partner_id.id, 'company_id': move_line.analytic_account_id.company_id.id or move_line.move_id.company_id.id, 'category': category, }) return result def _prepare_analytic_distribution_line(self, distribution): """ Prepare the values used to create() an account.analytic.line upon validation of an account.move.line having analytic tags with analytic distribution. """ self.ensure_one() amount = -self.balance * distribution.percentage / 100.0 default_name = self.name or (self.ref or '/' + ' -- ' + (self.partner_id and self.partner_id.name or '/')) return { 'name': default_name, 'date': self.date, 'account_id': distribution.account_id.id, 'group_id': distribution.account_id.group_id.id, 'partner_id': self.partner_id.id, 'tag_ids': [(6, 0, [distribution.tag_id.id] + self._get_analytic_tag_ids())], 'unit_amount': self.quantity, 'product_id': self.product_id and self.product_id.id or False, 'product_uom_id': self.product_uom_id and self.product_uom_id.id or False, 'amount': amount, 'general_account_id': self.account_id.id, 'ref': self.ref, 'move_id': self.id, 'user_id': self.move_id.invoice_user_id.id or self._uid, 'company_id': distribution.account_id.company_id.id or self.company_id.id or self.env.company.id, 'category': 'invoice' if self.move_id.is_sale_document() else 'vendor_bill' if self.move_id.is_purchase_document() else 'other', } @api.model def _query_get(self, domain=None): self.check_access_rights('read') context = dict(self._context or {}) domain = domain or [] if not isinstance(domain, (list, tuple)): domain = ast.literal_eval(domain) date_field = 'date' if context.get('aged_balance'): date_field = 'date_maturity' if context.get('date_to'): domain += [(date_field, '<=', context['date_to'])] if context.get('date_from'): if not context.get('strict_range'): domain += ['|', (date_field, '>=', context['date_from']), ('account_id.user_type_id.include_initial_balance', '=', True)] elif context.get('initial_bal'): domain += [(date_field, '<', context['date_from'])] else: domain += [(date_field, '>=', context['date_from'])] if context.get('journal_ids'): domain += [('journal_id', 'in', context['journal_ids'])] state = context.get('state') if state and state.lower() != 'all': domain += [('parent_state', '=', state)] if context.get('company_id'): domain += [('company_id', '=', context['company_id'])] elif context.get('allowed_company_ids'): domain += [('company_id', 'in', self.env.companies.ids)] else: domain += [('company_id', '=', self.env.company.id)] if context.get('reconcile_date'): domain += ['|', ('reconciled', '=', False), '|', ('matched_debit_ids.max_date', '>', context['reconcile_date']), ('matched_credit_ids.max_date', '>', context['reconcile_date'])] if context.get('account_tag_ids'): domain += [('account_id.tag_ids', 'in', context['account_tag_ids'].ids)] if context.get('account_ids'): domain += [('account_id', 'in', context['account_ids'].ids)] if context.get('analytic_tag_ids'): domain += [('analytic_tag_ids', 'in', context['analytic_tag_ids'].ids)] if context.get('analytic_account_ids'): domain += [('analytic_account_id', 'in', context['analytic_account_ids'].ids)] if context.get('partner_ids'): domain += [('partner_id', 'in', context['partner_ids'].ids)] if context.get('partner_categories'): domain += [('partner_id.category_id', 'in', context['partner_categories'].ids)] where_clause = "" where_clause_params = [] tables = '' if domain: domain.append(('display_type', 'not in', ('line_section', 'line_note'))) domain.append(('parent_state', '!=', 'cancel')) query = self._where_calc(domain) # Wrap the query with 'company_id IN (...)' to avoid bypassing company access rights. self._apply_ir_rules(query) tables, where_clause, where_clause_params = query.get_sql() return tables, where_clause, where_clause_params def _reconciled_lines(self): ids = [] for aml in self.filtered('account_id.reconcile'): ids.extend([r.debit_move_id.id for r in aml.matched_debit_ids] if aml.credit > 0 else [r.credit_move_id.id for r in aml.matched_credit_ids]) ids.append(aml.id) return ids def open_reconcile_view(self): action = self.env['ir.actions.act_window']._for_xml_id('account.action_account_moves_all_a') ids = self._reconciled_lines() action['domain'] = [('id', 'in', ids)] return action def action_automatic_entry(self): action = self.env['ir.actions.act_window']._for_xml_id('account.account_automatic_entry_wizard_action') # Force the values of the move line in the context to avoid issues ctx = dict(self.env.context) ctx.pop('active_id', None) ctx.pop('default_journal_id', None) ctx['active_ids'] = self.ids ctx['active_model'] = 'account.move.line' action['context'] = ctx return action @api.model def _get_suspense_moves_domain(self): return [ ('move_id.to_check', '=', True), ('full_reconcile_id', '=', False), ('statement_line_id', '!=', False), ] def _get_attachment_domains(self): self.ensure_one() domains = [[('res_model', '=', 'account.move'), ('res_id', '=', self.move_id.id)]] if self.statement_id: domains.append([('res_model', '=', 'account.bank.statement'), ('res_id', '=', self.statement_id.id)]) if self.payment_id: domains.append([('res_model', '=', 'account.payment'), ('res_id', '=', self.payment_id.id)]) return domains def _get_downpayment_lines(self): ''' Return the downpayment move lines associated with the move line. This method is overridden in the sale order module. ''' return self.env['account.move.line']
52.140993
303,617
3,922
py
PYTHON
15.0
# -*- coding: utf-8 -*- from PyPDF2.utils import PdfStreamError, PdfReadError from zlib import error as zlib_error from odoo import models, _ from odoo.exceptions import UserError from odoo.tools import pdf class IrActionsReport(models.Model): _inherit = 'ir.actions.report' def retrieve_attachment(self, record): # get the original bills through the message_main_attachment_id field of the record if self.report_name == 'account.report_original_vendor_bill' and record.message_main_attachment_id: if record.message_main_attachment_id.mimetype == 'application/pdf' or \ record.message_main_attachment_id.mimetype.startswith('image'): return record.message_main_attachment_id return super(IrActionsReport, self).retrieve_attachment(record) def _post_pdf(self, save_in_attachment, pdf_content=None, res_ids=None): # don't include the generated dummy report if self.report_name == 'account.report_original_vendor_bill': pdf_content = None res_ids = None if not save_in_attachment: raise UserError(_("No original vendor bills could be found for any of the selected vendor bills.")) return super(IrActionsReport, self)._post_pdf(save_in_attachment, pdf_content=pdf_content, res_ids=res_ids) def _postprocess_pdf_report(self, record, buffer): # don't save the 'account.report_original_vendor_bill' report as it's just a mean to print existing attachments if self.report_name == 'account.report_original_vendor_bill': return None res = super(IrActionsReport, self)._postprocess_pdf_report(record, buffer) if self.model == 'account.move' and record.state == 'posted' and record.is_sale_document(include_receipts=True): attachment = self.retrieve_attachment(record) if attachment: attachment.register_as_main_attachment(force=False) return res def _render_qweb_pdf(self, res_ids=None, data=None): # Overridden so that the print > invoices actions raises an error # when trying to print a miscellaneous operation instead of an invoice. # + append context data with the display_name_in_footer parameter if self.model == 'account.move' and res_ids: invoice_reports = (self.env.ref('account.account_invoices_without_payment'), self.env.ref('account.account_invoices')) if self in invoice_reports: if self.env['ir.config_parameter'].sudo().get_param('account.display_name_in_footer'): data = data and dict(data) or {} data.update({'display_name_in_footer': True}) moves = self.env['account.move'].browse(res_ids) if any(not move.is_invoice(include_receipts=True) for move in moves): raise UserError(_("Only invoices could be printed.")) return super()._render_qweb_pdf(res_ids=res_ids, data=data) def _retrieve_stream_from_attachment(self, attachment): # Overridden in order to add a banner in the upper right corner of the exported Vendor Bill PDF. stream = super()._retrieve_stream_from_attachment(attachment) vendor_bill_export = self.env.ref('account.action_account_original_vendor_bill') if self == vendor_bill_export and attachment.mimetype == 'application/pdf': record = self.env[attachment.res_model].browse(attachment.res_id) try: return pdf.add_banner(stream, record.name, logo=True) except (ValueError, PdfStreamError, PdfReadError, TypeError, zlib_error): record._message_log(body=_( "There was an error when trying to add the banner to the original PDF.\n" "Please make sure the source file is valid." )) return stream
56.028571
3,922
34,156
py
PYTHON
15.0
# -*- coding: utf-8 -*- from datetime import timedelta, datetime, date import calendar from dateutil.relativedelta import relativedelta from odoo.addons.account.models.account_move import MAX_HASH_VERSION from odoo import fields, models, api, _ from odoo.exceptions import ValidationError, UserError, RedirectWarning from odoo.tools.mail import is_html_empty from odoo.tools.misc import format_date from odoo.tools.float_utils import float_round, float_is_zero from odoo.tests.common import Form MONTH_SELECTION = [ ('1', 'January'), ('2', 'February'), ('3', 'March'), ('4', 'April'), ('5', 'May'), ('6', 'June'), ('7', 'July'), ('8', 'August'), ('9', 'September'), ('10', 'October'), ('11', 'November'), ('12', 'December'), ] ONBOARDING_STEP_STATES = [ ('not_done', "Not done"), ('just_done', "Just done"), ('done', "Done"), ] DASHBOARD_ONBOARDING_STATES = ONBOARDING_STEP_STATES + [('closed', 'Closed')] class ResCompany(models.Model): _inherit = "res.company" #TODO check all the options/fields are in the views (settings + company form view) fiscalyear_last_day = fields.Integer(default=31, required=True) fiscalyear_last_month = fields.Selection(MONTH_SELECTION, default='12', required=True) period_lock_date = fields.Date(string="Lock Date for Non-Advisers", help="Only users with the 'Adviser' role can edit accounts prior to and inclusive of this date. Use it for period locking inside an open fiscal year, for example.") fiscalyear_lock_date = fields.Date(string="Lock Date", help="No users, including Advisers, can edit accounts prior to and inclusive of this date. Use it for fiscal year locking for example.") tax_lock_date = fields.Date("Tax Lock Date", help="No users can edit journal entries related to a tax prior and inclusive of this date.") transfer_account_id = fields.Many2one('account.account', domain=lambda self: [('reconcile', '=', True), ('user_type_id.id', '=', self.env.ref('account.data_account_type_current_assets').id), ('deprecated', '=', False)], string="Inter-Banks Transfer Account", help="Intermediary account used when moving money from a liquidity account to another") expects_chart_of_accounts = fields.Boolean(string='Expects a Chart of Accounts', default=True) chart_template_id = fields.Many2one('account.chart.template', help='The chart template for the company (if any)') bank_account_code_prefix = fields.Char(string='Prefix of the bank accounts') cash_account_code_prefix = fields.Char(string='Prefix of the cash accounts') default_cash_difference_income_account_id = fields.Many2one('account.account', string="Cash Difference Income Account") default_cash_difference_expense_account_id = fields.Many2one('account.account', string="Cash Difference Expense Account") account_journal_suspense_account_id = fields.Many2one('account.account', string='Journal Suspense Account') account_journal_payment_debit_account_id = fields.Many2one('account.account', string='Journal Outstanding Receipts Account') account_journal_payment_credit_account_id = fields.Many2one('account.account', string='Journal Outstanding Payments Account') transfer_account_code_prefix = fields.Char(string='Prefix of the transfer accounts') account_sale_tax_id = fields.Many2one('account.tax', string="Default Sale Tax") account_purchase_tax_id = fields.Many2one('account.tax', string="Default Purchase Tax") tax_calculation_rounding_method = fields.Selection([ ('round_per_line', 'Round per Line'), ('round_globally', 'Round Globally'), ], default='round_per_line', string='Tax Calculation Rounding Method') currency_exchange_journal_id = fields.Many2one('account.journal', string="Exchange Gain or Loss Journal", domain=[('type', '=', 'general')]) income_currency_exchange_account_id = fields.Many2one( comodel_name='account.account', string="Gain Exchange Rate Account", domain=lambda self: "[('internal_type', '=', 'other'), ('deprecated', '=', False), ('company_id', '=', id), \ ('user_type_id', 'in', %s)]" % [self.env.ref('account.data_account_type_revenue').id, self.env.ref('account.data_account_type_other_income').id]) expense_currency_exchange_account_id = fields.Many2one( comodel_name='account.account', string="Loss Exchange Rate Account", domain=lambda self: "[('internal_type', '=', 'other'), ('deprecated', '=', False), ('company_id', '=', id), \ ('user_type_id', '=', %s)]" % self.env.ref('account.data_account_type_expenses').id) anglo_saxon_accounting = fields.Boolean(string="Use anglo-saxon accounting") property_stock_account_input_categ_id = fields.Many2one('account.account', string="Input Account for Stock Valuation") property_stock_account_output_categ_id = fields.Many2one('account.account', string="Output Account for Stock Valuation") property_stock_valuation_account_id = fields.Many2one('account.account', string="Account Template for Stock Valuation") bank_journal_ids = fields.One2many('account.journal', 'company_id', domain=[('type', '=', 'bank')], string='Bank Journals') incoterm_id = fields.Many2one('account.incoterms', string='Default incoterm', help='International Commercial Terms are a series of predefined commercial terms used in international transactions.') qr_code = fields.Boolean(string='Display QR-code on invoices') invoice_is_email = fields.Boolean('Email by default', default=True) invoice_is_print = fields.Boolean('Print by default', default=True) #Fields of the setup step for opening move account_opening_move_id = fields.Many2one(string='Opening Journal Entry', comodel_name='account.move', help="The journal entry containing the initial balance of all this company's accounts.") account_opening_journal_id = fields.Many2one(string='Opening Journal', comodel_name='account.journal', related='account_opening_move_id.journal_id', help="Journal where the opening entry of this company's accounting has been posted.", readonly=False) account_opening_date = fields.Date(string='Opening Entry', default=lambda self: fields.Date.context_today(self).replace(month=1, day=1), required=True, help="That is the date of the opening entry.") # Fields marking the completion of a setup step account_setup_bank_data_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding bank data step", default='not_done') account_setup_fy_data_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding fiscal year step", default='not_done') account_setup_coa_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding charts of account step", default='not_done') account_setup_taxes_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding Taxes step", default='not_done') account_onboarding_invoice_layout_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding invoice layout step", default='not_done') account_onboarding_create_invoice_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding create invoice step", default='not_done') account_onboarding_sale_tax_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding sale tax step", default='not_done') # account dashboard onboarding account_invoice_onboarding_state = fields.Selection(DASHBOARD_ONBOARDING_STATES, string="State of the account invoice onboarding panel", default='not_done') account_dashboard_onboarding_state = fields.Selection(DASHBOARD_ONBOARDING_STATES, string="State of the account dashboard onboarding panel", default='not_done') invoice_terms = fields.Html(string='Default Terms and Conditions', translate=True) terms_type = fields.Selection([('plain', 'Add a Note'), ('html', 'Add a link to a Web Page')], string='Terms & Conditions format', default='plain') invoice_terms_html = fields.Html(string='Default Terms and Conditions as a Web page', translate=True, sanitize_attributes=False, compute='_compute_invoice_terms_html', store=True, readonly=False) account_setup_bill_state = fields.Selection(ONBOARDING_STEP_STATES, string="State of the onboarding bill step", default='not_done') # Needed in the Point of Sale account_default_pos_receivable_account_id = fields.Many2one('account.account', string="Default PoS Receivable Account") # Accrual Accounting expense_accrual_account_id = fields.Many2one('account.account', help="Account used to move the period of an expense", domain="[('internal_group', '=', 'liability'), ('internal_type', 'not in', ('receivable', 'payable')), ('company_id', '=', id)]") revenue_accrual_account_id = fields.Many2one('account.account', help="Account used to move the period of a revenue", domain="[('internal_group', '=', 'asset'), ('internal_type', 'not in', ('receivable', 'payable')), ('company_id', '=', id)]") automatic_entry_default_journal_id = fields.Many2one('account.journal', help="Journal used by default for moving the period of an entry", domain="[('type', '=', 'general')]") # Technical field to hide country specific fields in company form view country_code = fields.Char(related='country_id.code') # Taxes account_fiscal_country_id = fields.Many2one( string="Fiscal Country", comodel_name='res.country', compute='compute_account_tax_fiscal_country', store=True, readonly=False, help="The country to use the tax reports from for this company") account_enabled_tax_country_ids = fields.Many2many( string="l10n-used countries", comodel_name='res.country', compute='_compute_account_enabled_tax_country_ids', help="Technical field containing the countries for which this company is using tax-related features" "(hence the ones for which l10n modules need to show tax-related fields).") # Cash basis taxes tax_exigibility = fields.Boolean(string='Use Cash Basis') tax_cash_basis_journal_id = fields.Many2one( comodel_name='account.journal', string="Cash Basis Journal") account_cash_basis_base_account_id = fields.Many2one( comodel_name='account.account', domain=[('deprecated', '=', False)], string="Base Tax Received Account", help="Account that will be set on lines created in cash basis journal entry and used to keep track of the " "tax base amount.") @api.constrains('account_opening_move_id', 'fiscalyear_last_day', 'fiscalyear_last_month') def _check_fiscalyear_last_day(self): # if the user explicitly chooses the 29th of February we allow it: # there is no "fiscalyear_last_year" so we do not know his intentions. for rec in self: if rec.fiscalyear_last_day == 29 and rec.fiscalyear_last_month == '2': continue if rec.account_opening_date: year = rec.account_opening_date.year else: year = datetime.now().year max_day = calendar.monthrange(year, int(rec.fiscalyear_last_month))[1] if rec.fiscalyear_last_day > max_day: raise ValidationError(_("Invalid fiscal year last day")) @api.depends('country_id') def compute_account_tax_fiscal_country(self): for record in self: record.account_fiscal_country_id = record.country_id @api.depends('account_fiscal_country_id') def _compute_account_enabled_tax_country_ids(self): for record in self: foreign_vat_fpos = self.env['account.fiscal.position'].search([('company_id', '=', record.id), ('foreign_vat', '!=', False)]) record.account_enabled_tax_country_ids = foreign_vat_fpos.country_id + record.account_fiscal_country_id @api.depends('terms_type') def _compute_invoice_terms_html(self): term_template = self.env.ref("account.account_default_terms_and_conditions", False) if not term_template: return for company in self.filtered(lambda company: is_html_empty(company.invoice_terms_html) and company.terms_type == 'html'): company.invoice_terms_html = term_template._render({'company_name': company.name, 'company_country': company.country_id.name}, engine='ir.qweb') def get_and_update_account_invoice_onboarding_state(self): """ This method is called on the controller rendering method and ensures that the animations are displayed only one time. """ return self.get_and_update_onbarding_state( 'account_invoice_onboarding_state', self.get_account_invoice_onboarding_steps_states_names() ) # YTI FIXME: Define only one method that returns {'account': [], 'sale': [], ...} def get_account_invoice_onboarding_steps_states_names(self): """ Necessary to add/edit steps from other modules (payment acquirer in this case). """ return [ 'base_onboarding_company_state', 'account_onboarding_invoice_layout_state', 'account_onboarding_create_invoice_state', ] def get_and_update_account_dashboard_onboarding_state(self): """ This method is called on the controller rendering method and ensures that the animations are displayed only one time. """ return self.get_and_update_onbarding_state( 'account_dashboard_onboarding_state', self.get_account_dashboard_onboarding_steps_states_names() ) def get_account_dashboard_onboarding_steps_states_names(self): """ Necessary to add/edit steps from other modules (account_winbooks_import in this case). """ return [ 'account_setup_bank_data_state', 'account_setup_fy_data_state', 'account_setup_coa_state', 'account_setup_taxes_state', ] def get_new_account_code(self, current_code, old_prefix, new_prefix): digits = len(current_code) return new_prefix + current_code.replace(old_prefix, '', 1).lstrip('0').rjust(digits-len(new_prefix), '0') def reflect_code_prefix_change(self, old_code, new_code): accounts = self.env['account.account'].search([('code', 'like', old_code), ('internal_type', '=', 'liquidity'), ('company_id', '=', self.id)], order='code asc') for account in accounts: if account.code.startswith(old_code): account.write({'code': self.get_new_account_code(account.code, old_code, new_code)}) def _validate_fiscalyear_lock(self, values): if values.get('fiscalyear_lock_date'): draft_entries = self.env['account.move'].search([ ('company_id', 'in', self.ids), ('state', '=', 'draft'), ('date', '<=', values['fiscalyear_lock_date'])]) if draft_entries: error_msg = _('There are still unposted entries in the period you want to lock. You should either post or delete them.') action_error = { 'view_mode': 'tree', 'name': _('Unposted Entries'), 'res_model': 'account.move', 'type': 'ir.actions.act_window', 'domain': [('id', 'in', draft_entries.ids)], 'search_view_id': [self.env.ref('account.view_account_move_filter').id, 'search'], 'views': [[self.env.ref('account.view_move_tree').id, 'list'], [self.env.ref('account.view_move_form').id, 'form']], } raise RedirectWarning(error_msg, action_error, _('Show unposted entries')) unreconciled_statement_lines = self.env['account.bank.statement.line'].search([ ('company_id', 'in', self.ids), ('is_reconciled', '=', False), ('date', '<=', values['fiscalyear_lock_date']), ('move_id.state', 'in', ('draft', 'posted')), ]) if unreconciled_statement_lines: error_msg = _("There are still unreconciled bank statement lines in the period you want to lock." "You should either reconcile or delete them.") action_error = { 'type': 'ir.actions.client', 'tag': 'bank_statement_reconciliation_view', 'context': {'statement_line_ids': unreconciled_statement_lines.ids, 'company_ids': self.ids}, } raise RedirectWarning(error_msg, action_error, _('Show Unreconciled Bank Statement Line')) def _get_user_fiscal_lock_date(self): """Get the fiscal lock date for this company depending on the user""" self.ensure_one() lock_date = max(self.period_lock_date or date.min, self.fiscalyear_lock_date or date.min) if self.user_has_groups('account.group_account_manager'): lock_date = self.fiscalyear_lock_date or date.min return lock_date def write(self, values): #restrict the closing of FY if there are still unposted entries self._validate_fiscalyear_lock(values) # Reflect the change on accounts for company in self: if values.get('bank_account_code_prefix'): new_bank_code = values.get('bank_account_code_prefix') or company.bank_account_code_prefix company.reflect_code_prefix_change(company.bank_account_code_prefix, new_bank_code) if values.get('cash_account_code_prefix'): new_cash_code = values.get('cash_account_code_prefix') or company.cash_account_code_prefix company.reflect_code_prefix_change(company.cash_account_code_prefix, new_cash_code) #forbid the change of currency_id if there are already some accounting entries existing if 'currency_id' in values and values['currency_id'] != company.currency_id.id: if self.env['account.move.line'].search([('company_id', '=', company.id)]): raise UserError(_('You cannot change the currency of the company since some journal items already exist')) return super(ResCompany, self).write(values) @api.model def setting_init_bank_account_action(self): """ Called by the 'Bank Accounts' button of the setup bar.""" view_id = self.env.ref('account.setup_bank_account_wizard').id return {'type': 'ir.actions.act_window', 'name': _('Create a Bank Account'), 'res_model': 'account.setup.bank.manual.config', 'target': 'new', 'view_mode': 'form', 'views': [[view_id, 'form']], } @api.model def setting_init_fiscal_year_action(self): """ Called by the 'Fiscal Year Opening' button of the setup bar.""" company = self.env.company company.create_op_move_if_non_existant() new_wizard = self.env['account.financial.year.op'].create({'company_id': company.id}) view_id = self.env.ref('account.setup_financial_year_opening_form').id return { 'type': 'ir.actions.act_window', 'name': _('Accounting Periods'), 'view_mode': 'form', 'res_model': 'account.financial.year.op', 'target': 'new', 'res_id': new_wizard.id, 'views': [[view_id, 'form']], } @api.model def setting_chart_of_accounts_action(self): """ Called by the 'Chart of Accounts' button of the setup bar.""" company = self.env.company company.sudo().set_onboarding_step_done('account_setup_coa_state') # If an opening move has already been posted, we open the tree view showing all the accounts if company.opening_move_posted(): return 'account.action_account_form' # Otherwise, we create the opening move company.create_op_move_if_non_existant() # Then, we open will open a custom tree view allowing to edit opening balances of the account view_id = self.env.ref('account.init_accounts_tree').id # Hide the current year earnings account as it is automatically computed domain = [('user_type_id', '!=', self.env.ref('account.data_unaffected_earnings').id), ('company_id','=', company.id)] return { 'type': 'ir.actions.act_window', 'name': _('Chart of Accounts'), 'res_model': 'account.account', 'view_mode': 'tree', 'limit': 99999999, 'search_view_id': [self.env.ref('account.view_account_search').id], 'views': [[view_id, 'list']], 'domain': domain, } @api.model def create_op_move_if_non_existant(self): """ Creates an empty opening move in 'draft' state for the current company if there wasn't already one defined. For this, the function needs at least one journal of type 'general' to exist (required by account.move). """ self.ensure_one() if not self.account_opening_move_id: default_journal = self.env['account.journal'].search([('type', '=', 'general'), ('company_id', '=', self.id)], limit=1) if not default_journal: raise UserError(_("Please install a chart of accounts or create a miscellaneous journal before proceeding.")) opening_date = self.account_opening_date - timedelta(days=1) self.account_opening_move_id = self.env['account.move'].create({ 'ref': _('Opening Journal Entry'), 'company_id': self.id, 'journal_id': default_journal.id, 'date': opening_date, }) def opening_move_posted(self): """ Returns true if this company has an opening account move and this move is posted.""" return bool(self.account_opening_move_id) and self.account_opening_move_id.state == 'posted' def get_unaffected_earnings_account(self): """ Returns the unaffected earnings account for this company, creating one if none has yet been defined. """ unaffected_earnings_type = self.env.ref("account.data_unaffected_earnings") account = self.env['account.account'].search([('company_id', '=', self.id), ('user_type_id', '=', unaffected_earnings_type.id)]) if account: return account[0] # Do not assume '999999' doesn't exist since the user might have created such an account # manually. code = 999999 while self.env['account.account'].search([('code', '=', str(code)), ('company_id', '=', self.id)]): code -= 1 return self.env['account.account'].create({ 'code': str(code), 'name': _('Undistributed Profits/Losses'), 'user_type_id': unaffected_earnings_type.id, 'company_id': self.id, }) def get_opening_move_differences(self, opening_move_lines): currency = self.currency_id balancing_move_line = opening_move_lines.filtered(lambda x: x.account_id == self.get_unaffected_earnings_account()) debits_sum = credits_sum = 0.0 for line in opening_move_lines: if line != balancing_move_line: #skip the autobalancing move line debits_sum += line.debit credits_sum += line.credit difference = abs(debits_sum - credits_sum) debit_diff = (debits_sum > credits_sum) and float_round(difference, precision_rounding=currency.rounding) or 0.0 credit_diff = (debits_sum < credits_sum) and float_round(difference, precision_rounding=currency.rounding) or 0.0 return debit_diff, credit_diff def _auto_balance_opening_move(self): """ Checks the opening_move of this company. If it has not been posted yet and is unbalanced, balances it with a automatic account.move.line in the current year earnings account. """ if self.account_opening_move_id and self.account_opening_move_id.state == 'draft': balancing_account = self.get_unaffected_earnings_account() currency = self.currency_id balancing_move_line = self.account_opening_move_id.line_ids.filtered(lambda x: x.account_id == balancing_account) # There could be multiple lines if we imported the balance from unaffected earnings account too if len(balancing_move_line) > 1: self.with_context(check_move_validity=False).account_opening_move_id.line_ids -= balancing_move_line[1:] balancing_move_line = balancing_move_line[0] debit_diff, credit_diff = self.get_opening_move_differences(self.account_opening_move_id.line_ids) if float_is_zero(debit_diff + credit_diff, precision_rounding=currency.rounding): if balancing_move_line: # zero difference and existing line : delete the line self.account_opening_move_id.line_ids -= balancing_move_line else: if balancing_move_line: # Non-zero difference and existing line : edit the line balancing_move_line.write({'debit': credit_diff, 'credit': debit_diff}) else: # Non-zero difference and no existing line : create a new line self.env['account.move.line'].create({ 'name': _('Automatic Balancing Line'), 'move_id': self.account_opening_move_id.id, 'account_id': balancing_account.id, 'debit': credit_diff, 'credit': debit_diff, }) @api.model def action_close_account_invoice_onboarding(self): """ Mark the invoice onboarding panel as closed. """ self.env.company.account_invoice_onboarding_state = 'closed' @api.model def action_close_account_dashboard_onboarding(self): """ Mark the dashboard onboarding panel as closed. """ self.env.company.account_dashboard_onboarding_state = 'closed' @api.model def action_open_account_onboarding_sale_tax(self): """ Onboarding step for the invoice layout. """ action = self.env["ir.actions.actions"]._for_xml_id("account.action_open_account_onboarding_sale_tax") action['res_id'] = self.env.company.id return action @api.model def action_open_account_onboarding_create_invoice(self): action = self.env["ir.actions.actions"]._for_xml_id("account.action_open_account_onboarding_create_invoice") return action @api.model def action_open_taxes_onboarding(self): """ Called by the 'Taxes' button of the setup bar.""" company = self.env.company company.sudo().set_onboarding_step_done('account_setup_taxes_state') view_id_list = self.env.ref('account.view_tax_tree').id view_id_form = self.env.ref('account.view_tax_form').id return { 'type': 'ir.actions.act_window', 'name': _('Taxes'), 'res_model': 'account.tax', 'target': 'current', 'views': [[view_id_list, 'list'], [view_id_form, 'form']], 'context': {'search_default_sale': True, 'search_default_purchase': True, 'active_test': False}, } def action_save_onboarding_invoice_layout(self): """ Set the onboarding step as done """ if bool(self.external_report_layout_id): self.set_onboarding_step_done('account_onboarding_invoice_layout_state') def action_save_onboarding_sale_tax(self): """ Set the onboarding step as done """ self.set_onboarding_step_done('account_onboarding_sale_tax_state') def get_chart_of_accounts_or_fail(self): account = self.env['account.account'].search([('company_id', '=', self.id)], limit=1) if len(account) == 0: action = self.env.ref('account.action_account_config') msg = _( "We cannot find a chart of accounts for this company, you should configure it. \n" "Please go to Account Configuration and select or install a fiscal localization.") raise RedirectWarning(msg, action.id, _("Go to the configuration panel")) return account @api.model def _action_check_hash_integrity(self): return self.env.ref('account.action_report_account_hash_integrity').report_action(self.id) def _check_hash_integrity(self): """Checks that all posted moves have still the same data as when they were posted and raises an error with the result. """ if not self.env.user.has_group('account.group_account_user'): raise UserError(_('Please contact your accountant to print the Hash integrity result.')) def build_move_info(move): return(move.name, move.inalterable_hash, fields.Date.to_string(move.date)) journals = self.env['account.journal'].search([('company_id', '=', self.id)]) results_by_journal = { 'results': [], 'printing_date': format_date(self.env, fields.Date.to_string(fields.Date.context_today(self))) } for journal in journals: rslt = { 'journal_name': journal.name, 'journal_code': journal.code, 'restricted_by_hash_table': journal.restrict_mode_hash_table and 'V' or 'X', 'msg_cover': '', 'first_hash': 'None', 'first_move_name': 'None', 'first_move_date': 'None', 'last_hash': 'None', 'last_move_name': 'None', 'last_move_date': 'None', } if not journal.restrict_mode_hash_table: rslt.update({'msg_cover': _('This journal is not in strict mode.')}) results_by_journal['results'].append(rslt) continue # We need the `sudo()` to ensure that all the moves are searched, no matter the user's access rights. # This is required in order to generate consistent hashs. # It is not an issue, since the data is only used to compute a hash and not to return the actual values. all_moves_count = self.env['account.move'].sudo().search_count([('state', '=', 'posted'), ('journal_id', '=', journal.id)]) moves = self.env['account.move'].sudo().search([('state', '=', 'posted'), ('journal_id', '=', journal.id), ('secure_sequence_number', '!=', 0)], order="secure_sequence_number ASC") if not moves: rslt.update({ 'msg_cover': _('There isn\'t any journal entry flagged for data inalterability yet for this journal.'), }) results_by_journal['results'].append(rslt) continue previous_hash = u'' start_move_info = [] hash_corrupted = False current_hash_version = 1 for move in moves: computed_hash = move.with_context(hash_version=current_hash_version)._compute_hash(previous_hash=previous_hash) while move.inalterable_hash != computed_hash and current_hash_version < MAX_HASH_VERSION: current_hash_version += 1 computed_hash = move.with_context(hash_version=current_hash_version)._compute_hash(previous_hash=previous_hash) if move.inalterable_hash != computed_hash: rslt.update({'msg_cover': _('Corrupted data on journal entry with id %s.', move.id)}) results_by_journal['results'].append(rslt) hash_corrupted = True break if not previous_hash: #save the date and sequence number of the first move hashed start_move_info = build_move_info(move) previous_hash = move.inalterable_hash end_move_info = build_move_info(move) if hash_corrupted: continue rslt.update({ 'first_move_name': start_move_info[0], 'first_hash': start_move_info[1], 'first_move_date': format_date(self.env, start_move_info[2]), 'last_move_name': end_move_info[0], 'last_hash': end_move_info[1], 'last_move_date': format_date(self.env, end_move_info[2]), }) if len(moves) == all_moves_count: rslt.update({'msg_cover': _('All entries are hashed.')}) else: rslt.update({'msg_cover': _('Entries are hashed from %s (%s)') % (start_move_info[0], format_date(self.env, start_move_info[2]))}) results_by_journal['results'].append(rslt) return results_by_journal def compute_fiscalyear_dates(self, current_date): """ The role of this method is to provide a fallback when account_accounting is not installed. As the fiscal year is irrelevant when account_accounting is not installed, this method returns the calendar year. :param current_date: A datetime.date/datetime.datetime object. :return: A dictionary containing: * date_from * date_to """ return {'date_from': datetime(year=current_date.year, month=1, day=1).date(), 'date_to': datetime(year=current_date.year, month=12, day=31).date()}
54.82504
34,156
59,497
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, Command, tools, _ from odoo.tools import float_compare, float_is_zero from odoo.osv.expression import get_unaccent_wrapper from odoo.exceptions import UserError, ValidationError import re from math import copysign from collections import defaultdict from dateutil.relativedelta import relativedelta class AccountReconcileModelPartnerMapping(models.Model): _name = 'account.reconcile.model.partner.mapping' _description = 'Partner mapping for reconciliation models' model_id = fields.Many2one(comodel_name='account.reconcile.model', readonly=True, required=True, ondelete='cascade') partner_id = fields.Many2one(comodel_name='res.partner', string="Partner", required=True, ondelete='cascade') payment_ref_regex = fields.Char(string="Find Text in Label") narration_regex = fields.Char(string="Find Text in Notes") @api.constrains('narration_regex', 'payment_ref_regex') def validate_regex(self): for record in self: if not (record.narration_regex or record.payment_ref_regex): raise ValidationError(_("Please set at least one of the match texts to create a partner mapping.")) try: if record.payment_ref_regex: current_regex = record.payment_ref_regex re.compile(record.payment_ref_regex) if record.narration_regex: current_regex = record.narration_regex re.compile(record.narration_regex) except re.error: raise ValidationError(_("The following regular expression is invalid to create a partner mapping: %s") % current_regex) class AccountReconcileModelLine(models.Model): _name = 'account.reconcile.model.line' _description = 'Rules for the reconciliation model' _order = 'sequence, id' _check_company_auto = True model_id = fields.Many2one('account.reconcile.model', readonly=True, ondelete='cascade') allow_payment_tolerance = fields.Boolean(related='model_id.allow_payment_tolerance') payment_tolerance_param = fields.Float(related='model_id.payment_tolerance_param') rule_type = fields.Selection(related='model_id.rule_type') company_id = fields.Many2one(related='model_id.company_id', store=True) sequence = fields.Integer(required=True, default=10) account_id = fields.Many2one('account.account', string='Account', ondelete='cascade', domain="[('deprecated', '=', False), ('company_id', '=', company_id), ('is_off_balance', '=', False)]", required=True, check_company=True) journal_id = fields.Many2one('account.journal', string='Journal', ondelete='cascade', domain="[('type', '=', 'general'), ('company_id', '=', company_id)]", help="This field is ignored in a bank statement reconciliation.", check_company=True) label = fields.Char(string='Journal Item Label') amount_type = fields.Selection([ ('fixed', 'Fixed'), ('percentage', 'Percentage of balance'), ('percentage_st_line', 'Percentage of statement line'), ('regex', 'From label'), ], required=True, default='percentage') show_force_tax_included = fields.Boolean(compute='_compute_show_force_tax_included', help='Technical field used to show the force tax included button') force_tax_included = fields.Boolean(string='Tax Included in Price', help='Force the tax to be managed as a price included tax.') amount = fields.Float(string="Float Amount", compute='_compute_float_amount', store=True, help="Technical shortcut to parse the amount to a float") amount_string = fields.Char(string="Amount", default='100', required=True, help="""Value for the amount of the writeoff line * Percentage: Percentage of the balance, between 0 and 100. * Fixed: The fixed value of the writeoff. The amount will count as a debit if it is negative, as a credit if it is positive. * From Label: There is no need for regex delimiter, only the regex is needed. For instance if you want to extract the amount from\nR:9672938 10/07 AX 9415126318 T:5L:NA BRT: 3358,07 C:\nYou could enter\nBRT: ([\d,]+)""") tax_ids = fields.Many2many('account.tax', string='Taxes', ondelete='restrict', check_company=True) analytic_account_id = fields.Many2one('account.analytic.account', string='Analytic Account', ondelete='set null', check_company=True) analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags', check_company=True, relation='account_reconcile_model_analytic_tag_rel') @api.onchange('tax_ids') def _onchange_tax_ids(self): # Multiple taxes with force_tax_included results in wrong computation, so we # only allow to set the force_tax_included field if we have one tax selected if len(self.tax_ids) != 1: self.force_tax_included = False @api.depends('tax_ids') def _compute_show_force_tax_included(self): for record in self: record.show_force_tax_included = False if len(record.tax_ids) != 1 else True @api.onchange('amount_type') def _onchange_amount_type(self): self.amount_string = '' if self.amount_type in ('percentage', 'percentage_st_line'): self.amount_string = '100' elif self.amount_type == 'regex': self.amount_string = '([\d,]+)' @api.depends('amount_string') def _compute_float_amount(self): for record in self: try: record.amount = float(record.amount_string) except ValueError: record.amount = 0 @api.constrains('amount_string') def _validate_amount(self): for record in self: if record.amount_type == 'fixed' and record.amount == 0: raise UserError(_("The amount is not a number")) if record.amount_type == 'percentage_st_line' and record.amount == 0: raise UserError(_("Balance percentage can't be 0")) if record.amount_type == 'percentage' and record.amount == 0: raise UserError(_("Statement line percentage can't be 0")) if record.amount_type == 'regex': try: re.compile(record.amount_string) except re.error: raise UserError(_('The regex is not valid')) class AccountReconcileModel(models.Model): _name = 'account.reconcile.model' _description = 'Preset to create journal entries during a invoices and payments matching' _inherit = ['mail.thread'] _order = 'sequence, id' _check_company_auto = True # Base fields. active = fields.Boolean(default=True) name = fields.Char(string='Name', required=True) sequence = fields.Integer(required=True, default=10) company_id = fields.Many2one( comodel_name='res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company) rule_type = fields.Selection(selection=[ ('writeoff_button', 'Button to generate counterpart entry'), ('writeoff_suggestion', 'Rule to suggest counterpart entry'), ('invoice_matching', 'Rule to match invoices/bills'), ], string='Type', default='writeoff_button', required=True, tracking=True) auto_reconcile = fields.Boolean(string='Auto-validate', tracking=True, help='Validate the statement line automatically (reconciliation based on your rule).') to_check = fields.Boolean(string='To Check', default=False, help='This matching rule is used when the user is not certain of all the information of the counterpart.') matching_order = fields.Selection( selection=[ ('old_first', 'Oldest first'), ('new_first', 'Newest first'), ], required=True, default='old_first', tracking=True, ) # ===== Conditions ===== match_text_location_label = fields.Boolean( default=True, help="Search in the Statement's Label to find the Invoice/Payment's reference", tracking=True, ) match_text_location_note = fields.Boolean( default=False, help="Search in the Statement's Note to find the Invoice/Payment's reference", tracking=True, ) match_text_location_reference = fields.Boolean( default=False, help="Search in the Statement's Reference to find the Invoice/Payment's reference", tracking=True, ) match_journal_ids = fields.Many2many('account.journal', string='Journals Availability', domain="[('type', 'in', ('bank', 'cash')), ('company_id', '=', company_id)]", check_company=True, help='The reconciliation model will only be available from the selected journals.') match_nature = fields.Selection(selection=[ ('amount_received', 'Received'), ('amount_paid', 'Paid'), ('both', 'Paid/Received') ], string='Amount Type', required=True, default='both', tracking=True, help='''The reconciliation model will only be applied to the selected transaction type: * Amount Received: Only applied when receiving an amount. * Amount Paid: Only applied when paying an amount. * Amount Paid/Received: Applied in both cases.''') match_amount = fields.Selection(selection=[ ('lower', 'Is Lower Than'), ('greater', 'Is Greater Than'), ('between', 'Is Between'), ], string='Amount Condition', tracking=True, help='The reconciliation model will only be applied when the amount being lower than, greater than or between specified amount(s).') match_amount_min = fields.Float(string='Amount Min Parameter', tracking=True) match_amount_max = fields.Float(string='Amount Max Parameter', tracking=True) match_label = fields.Selection(selection=[ ('contains', 'Contains'), ('not_contains', 'Not Contains'), ('match_regex', 'Match Regex'), ], string='Label', tracking=True, help='''The reconciliation model will only be applied when the label: * Contains: The proposition label must contains this string (case insensitive). * Not Contains: Negation of "Contains". * Match Regex: Define your own regular expression.''') match_label_param = fields.Char(string='Label Parameter', tracking=True) match_note = fields.Selection(selection=[ ('contains', 'Contains'), ('not_contains', 'Not Contains'), ('match_regex', 'Match Regex'), ], string='Note', tracking=True, help='''The reconciliation model will only be applied when the note: * Contains: The proposition note must contains this string (case insensitive). * Not Contains: Negation of "Contains". * Match Regex: Define your own regular expression.''') match_note_param = fields.Char(string='Note Parameter', tracking=True) match_transaction_type = fields.Selection(selection=[ ('contains', 'Contains'), ('not_contains', 'Not Contains'), ('match_regex', 'Match Regex'), ], string='Transaction Type', tracking=True, help='''The reconciliation model will only be applied when the transaction type: * Contains: The proposition transaction type must contains this string (case insensitive). * Not Contains: Negation of "Contains". * Match Regex: Define your own regular expression.''') match_transaction_type_param = fields.Char(string='Transaction Type Parameter', tracking=True) match_same_currency = fields.Boolean(string='Same Currency', default=True, tracking=True, help='Restrict to propositions having the same currency as the statement line.') allow_payment_tolerance = fields.Boolean( string="Payment Tolerance", default=True, tracking=True, help="Difference accepted in case of underpayment.", ) payment_tolerance_param = fields.Float( string="Gap", compute='_compute_payment_tolerance_param', readonly=False, store=True, tracking=True, help="The sum of total residual amount propositions matches the statement line amount under this amount/percentage.", ) payment_tolerance_type = fields.Selection( selection=[('percentage', "in percentage"), ('fixed_amount', "in amount")], default='percentage', required=True, tracking=True, help="The sum of total residual amount propositions and the statement line amount allowed gap type.", ) match_partner = fields.Boolean(string='Partner should be set', tracking=True, help='The reconciliation model will only be applied when a customer/vendor is set.') match_partner_ids = fields.Many2many('res.partner', string='Only Those Partners', help='The reconciliation model will only be applied to the selected customers/vendors.') match_partner_category_ids = fields.Many2many('res.partner.category', string='Only Those Partner Categories', help='The reconciliation model will only be applied to the selected customer/vendor categories.') line_ids = fields.One2many('account.reconcile.model.line', 'model_id', copy=True) partner_mapping_line_ids = fields.One2many(string="Partner Mapping Lines", comodel_name='account.reconcile.model.partner.mapping', inverse_name='model_id', help="The mapping uses regular expressions.\n" "- To Match the text at the beginning of the line (in label or notes), simply fill in your text.\n" "- To Match the text anywhere (in label or notes), put your text between .*\n" " e.g: .*N°48748 abc123.*") past_months_limit = fields.Integer( string="Search Months Limit", default=18, tracking=True, help="Number of months in the past to consider entries from when applying this model.", ) decimal_separator = fields.Char( default=lambda self: self.env['res.lang']._lang_get(self.env.user.lang).decimal_point, tracking=True, help="Every character that is nor a digit nor this separator will be removed from the matching string", ) show_decimal_separator = fields.Boolean(compute='_compute_show_decimal_separator', help="Technical field to decide if we should show the decimal separator for the regex matching field.") number_entries = fields.Integer(string='Number of entries related to this model', compute='_compute_number_entries') def action_reconcile_stat(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("account.action_move_journal_line") self._cr.execute(''' SELECT ARRAY_AGG(DISTINCT move_id) FROM account_move_line WHERE reconcile_model_id = %s ''', [self.id]) action.update({ 'context': {}, 'domain': [('id', 'in', self._cr.fetchone()[0])], 'help': """<p class="o_view_nocontent_empty_folder">{}</p>""".format(_('This reconciliation model has created no entry so far')), }) return action def _compute_number_entries(self): data = self.env['account.move.line'].read_group([('reconcile_model_id', 'in', self.ids)], ['reconcile_model_id'], 'reconcile_model_id') mapped_data = dict([(d['reconcile_model_id'][0], d['reconcile_model_id_count']) for d in data]) for model in self: model.number_entries = mapped_data.get(model.id, 0) @api.depends('line_ids.amount_type') def _compute_show_decimal_separator(self): for record in self: record.show_decimal_separator = any(l.amount_type == 'regex' for l in record.line_ids) @api.depends('payment_tolerance_param', 'payment_tolerance_type') def _compute_payment_tolerance_param(self): for record in self: if record.payment_tolerance_type == 'percentage': record.payment_tolerance_param = min(100.0, max(0.0, record.payment_tolerance_param)) else: record.payment_tolerance_param = max(0.0, record.payment_tolerance_param) @api.constrains('allow_payment_tolerance', 'payment_tolerance_param', 'payment_tolerance_type') def _check_payment_tolerance_param(self): for record in self: if record.allow_payment_tolerance: if record.payment_tolerance_type == 'percentage' and not 0 <= record.payment_tolerance_param <= 100: raise ValidationError(_("A payment tolerance defined as a percentage should always be between 0 and 100")) elif record.payment_tolerance_type == 'fixed_amount' and record.payment_tolerance_param < 0: raise ValidationError(_("A payment tolerance defined as an amount should always be higher than 0")) #################################################### # RECONCILIATION PROCESS #################################################### def _get_taxes_move_lines_dict(self, tax, base_line_dict, statement_line=None): ''' Get move.lines dict (to be passed to the create()) corresponding to a tax. :param tax: An account.tax record. :param base_line_dict: A dict representing the move.line containing the base amount. :return: A list of dict representing move.lines to be created corresponding to the tax. ''' self.ensure_one() balance = base_line_dict['balance'] tax_type = tax.type_tax_use if statement_line: is_refund = (tax_type == 'sale' and balance > 0) or (tax_type == 'purchase' and balance < 0) else: is_refund = (tax_type == 'sale' and balance < 0) or (tax_type == 'purchase' and balance > 0) res = tax.compute_all(balance, is_refund=is_refund) new_aml_dicts = [] for tax_res in res['taxes']: tax = self.env['account.tax'].browse(tax_res['id']) balance = tax_res['amount'] name = ' '.join([x for x in [base_line_dict.get('name', ''), tax_res['name']] if x]) new_aml_dicts.append({ 'account_id': tax_res['account_id'] or base_line_dict['account_id'], 'journal_id': base_line_dict.get('journal_id', False), 'name': name, 'partner_id': base_line_dict.get('partner_id'), 'balance': balance, 'debit': balance > 0 and balance or 0, 'credit': balance < 0 and -balance or 0, 'analytic_account_id': tax.analytic and base_line_dict['analytic_account_id'], 'analytic_tag_ids': tax.analytic and base_line_dict['analytic_tag_ids'], 'tax_repartition_line_id': tax_res['tax_repartition_line_id'], 'tax_ids': [(6, 0, tax_res['tax_ids'])], 'tax_tag_ids': [(6, 0, tax_res['tag_ids'])], 'currency_id': False, 'reconcile_model_id': self.id, }) # Handle price included taxes. base_balance = tax_res['base'] base_line_dict.update({ 'balance': base_balance, 'debit': base_balance > 0 and base_balance or 0, 'credit': base_balance < 0 and -base_balance or 0, }) base_line_dict['tax_tag_ids'] = [(6, 0, res['base_tags'])] return new_aml_dicts def _get_write_off_move_lines_dict(self, st_line, residual_balance, partner_id): ''' Get move.lines dict (to be passed to the create()) corresponding to the reconciliation model's write-off lines. :param st_line: An account.bank.statement.line record.(possibly empty, if performing manual reconciliation) :param residual_balance: The residual balance of the statement line. :return: A list of dict representing move.lines to be created corresponding to the write-off lines. ''' self.ensure_one() if self.rule_type == 'invoice_matching' and (not self.allow_payment_tolerance or self.payment_tolerance_param == 0): return [] if st_line: currency = st_line.foreign_currency_id or st_line.currency_id matched_candidates_values = self._process_matched_candidates_data(st_line) st_line_residual = matched_candidates_values['balance_sign'] * matched_candidates_values['residual_balance_curr'] else: currency = self.company_id.currency_id # No statement line if any(x.amount_type == 'percentage_st_line' for x in self.line_ids): return [] lines_vals_list = [] for line in self.line_ids: if line.amount_type == 'percentage': balance = currency.round(residual_balance * (line.amount / 100.0)) elif line.amount_type == 'percentage_st_line': if st_line: balance = currency.round(st_line_residual * (line.amount / 100.0)) else: balance = 0.0 elif line.amount_type == 'regex': match = re.search(line.amount_string, st_line.payment_ref) if match: sign = 1 if residual_balance > 0.0 else -1 try: extracted_match_group = re.sub(r'[^\d' + self.decimal_separator + ']', '', match.group(1)) extracted_balance = float(extracted_match_group.replace(self.decimal_separator, '.')) balance = copysign(extracted_balance * sign, residual_balance) except ValueError: balance = 0 else: balance = 0 elif line.amount_type == 'fixed': balance = currency.round(line.amount * (1 if residual_balance > 0.0 else -1)) if currency.is_zero(balance): continue writeoff_line = { 'name': line.label or st_line.payment_ref, 'balance': balance, 'debit': balance > 0 and balance or 0, 'credit': balance < 0 and -balance or 0, 'account_id': line.account_id.id, 'currency_id': currency.id, 'analytic_account_id': line.analytic_account_id.id, 'analytic_tag_ids': [(6, 0, line.analytic_tag_ids.ids)], 'reconcile_model_id': self.id, 'journal_id': line.journal_id.id, 'tax_ids': [], } lines_vals_list.append(writeoff_line) residual_balance -= balance if line.tax_ids: taxes = line.tax_ids detected_fiscal_position = self.env['account.fiscal.position'].get_fiscal_position(partner_id) if detected_fiscal_position: taxes = detected_fiscal_position.map_tax(taxes) writeoff_line['tax_ids'] += [Command.set(taxes.ids)] # Multiple taxes with force_tax_included results in wrong computation, so we # only allow to set the force_tax_included field if we have one tax selected if line.force_tax_included: taxes = taxes[0].with_context(force_price_include=True) tax_vals_list = self._get_taxes_move_lines_dict(taxes, writeoff_line, statement_line=st_line) lines_vals_list += tax_vals_list if not line.force_tax_included: for tax_line in tax_vals_list: residual_balance -= tax_line['balance'] return lines_vals_list #################################################### # RECONCILIATION CRITERIA #################################################### def _apply_rules(self, st_lines, excluded_ids=None, partner_map=None): ''' Apply criteria to get candidates for all reconciliation models. This function is called in enterprise by the reconciliation widget to match the statement lines with the available candidates (using the reconciliation models). :param st_lines: Account.bank.statement.lines recordset. :param excluded_ids: Account.move.lines to exclude. :param partner_map: Dict mapping each line with new partner eventually. :return: A dict mapping each statement line id with: * aml_ids: A list of account.move.line ids. * model: An account.reconcile.model record (optional). * status: 'reconciled' if the lines has been already reconciled, 'write_off' if the write-off must be applied on the statement line. ''' # This functions uses SQL to compute its results. We need to flush before doing anything more. for model_name in ('account.bank.statement', 'account.bank.statement.line', 'account.move', 'account.move.line', 'res.company', 'account.journal', 'account.account'): self.env[model_name].flush(self.env[model_name]._fields) results = {line.id: {'aml_ids': []} for line in st_lines} available_models = self.filtered(lambda m: m.rule_type != 'writeoff_button').sorted() aml_ids_to_exclude = set() # Keep track of already processed amls. reconciled_amls_ids = set() # Keep track of already reconciled amls. # First associate with each rec models all the statement lines for which it is applicable lines_with_partner_per_model = defaultdict(lambda: []) # Exclude already in the statement line associated account move lines excluded_ids = excluded_ids or [] + st_lines.move_id.line_ids.ids for st_line in st_lines: # Statement lines created in old versions could have a residual amount of zero. In that case, don't try to # match anything. if not st_line.amount_residual: continue mapped_partner = (partner_map and partner_map.get(st_line.id) and self.env['res.partner'].browse(partner_map[st_line.id])) or st_line.partner_id for rec_model in available_models: partner = mapped_partner or rec_model._get_partner_from_mapping(st_line) if rec_model._is_applicable_for(st_line, partner): lines_with_partner_per_model[rec_model].append((st_line, partner)) # Execute only one SQL query for each model (for performance) matched_lines = self.env['account.bank.statement.line'] for rec_model in available_models: # We filter the lines for this model, in case a previous one has already found something for them filtered_st_lines_with_partner = [x for x in lines_with_partner_per_model[rec_model] if x[0] not in matched_lines] if not filtered_st_lines_with_partner: # No unreconciled statement line for this model continue all_model_candidates = rec_model._get_candidates(filtered_st_lines_with_partner, excluded_ids) for st_line, partner in filtered_st_lines_with_partner: candidates = all_model_candidates[st_line.id] if candidates: model_rslt, new_reconciled_aml_ids, new_treated_aml_ids = rec_model._get_rule_result(st_line, candidates, aml_ids_to_exclude, reconciled_amls_ids, partner) if model_rslt: # We inject the selected partner (possibly coming from the rec model) model_rslt['partner']= partner results[st_line.id] = model_rslt reconciled_amls_ids |= new_reconciled_aml_ids aml_ids_to_exclude |= new_treated_aml_ids matched_lines += st_line return results def _is_applicable_for(self, st_line, partner): """ Returns true iff this reconciliation model can be used to search for matches for the provided statement line and partner. """ self.ensure_one() # Filter on journals, amount nature, amount and partners # All the conditions defined in this block are non-match conditions. if ((self.match_journal_ids and st_line.move_id.journal_id not in self.match_journal_ids) or (self.match_nature == 'amount_received' and st_line.amount < 0) or (self.match_nature == 'amount_paid' and st_line.amount > 0) or (self.match_amount == 'lower' and abs(st_line.amount) >= self.match_amount_max) or (self.match_amount == 'greater' and abs(st_line.amount) <= self.match_amount_min) or (self.match_amount == 'between' and (abs(st_line.amount) > self.match_amount_max or abs(st_line.amount) < self.match_amount_min)) or (self.match_partner and not partner) or (self.match_partner and self.match_partner_ids and partner not in self.match_partner_ids) or (self.match_partner and self.match_partner_category_ids and not (partner.category_id & self.match_partner_category_ids)) ): return False # Filter on label, note and transaction_type for record, rule_field, record_field in [(st_line, 'label', 'payment_ref'), (st_line.move_id, 'note', 'narration'), (st_line, 'transaction_type', 'transaction_type')]: rule_term = (self['match_' + rule_field + '_param'] or '').lower() record_term = (record[record_field] or '').lower() # This defines non-match conditions if ((self['match_' + rule_field] == 'contains' and rule_term not in record_term) or (self['match_' + rule_field] == 'not_contains' and rule_term in record_term) or (self['match_' + rule_field] == 'match_regex' and not re.match(rule_term, record_term)) ): return False return True def _get_candidates(self, st_lines_with_partner, excluded_ids): """ Returns the match candidates for this rule, with respect to the provided parameters. :param st_lines_with_partner: A list of tuples (statement_line, partner), associating each statement line to treate with the corresponding partner, given by the partner map :param excluded_ids: a set containing the ids of the amls to ignore during the search (because they already been matched by another rule) """ self.ensure_one() # On big databases, it is possible that some setups will create huge queries when trying to apply reconciliation models. # In such cases, this query might take a very long time to run, essentially eating up all the available CPU, and proof # impossible to kill, because of the type of operations ran by SQL. To alleviate that, we introduce the config parameter below, # which essentially allows cutting the list of statement lines to match into slices, and running the matching in multiple queries. # This way, we avoid server overload, giving the ability to kill the process if takes too long. slice_size = len(st_lines_with_partner) slice_size_param = self.env['ir.config_parameter'].sudo().get_param('account.reconcile_model_forced_slice_size') if slice_size_param: converted_param = int(slice_size_param) if converted_param > 0: slice_size = converted_param treatment_slices = [] slice_start = 0 while slice_start < len(st_lines_with_partner): slice_end = slice_start + slice_size treatment_slices.append(st_lines_with_partner[slice_start:slice_end]) slice_start = slice_end treatment_map = { 'invoice_matching': lambda rec_model, slice: rec_model._get_invoice_matching_query(slice, excluded_ids), 'writeoff_suggestion': lambda rec_model, slice: rec_model._get_writeoff_suggestion_query(slice, excluded_ids), } rslt = defaultdict(lambda: []) for treatment_slice in treatment_slices: query_generator = treatment_map[self.rule_type] query, params = query_generator(self, treatment_slice) self._cr.execute(query, params) for candidate_dict in self._cr.dictfetchall(): rslt[candidate_dict['id']].append(candidate_dict) return rslt def _get_invoice_matching_query(self, st_lines_with_partner, excluded_ids): ''' Returns the query applying the current invoice_matching reconciliation model to the provided statement lines. :param st_lines_with_partner: A list of tuples (statement_line, partner), associating each statement line to treate with the corresponding partner, given by the partner map :param excluded_ids: Account.move.lines to exclude. :return: (query, params) ''' self.ensure_one() if self.rule_type != 'invoice_matching': raise UserError(_('Programmation Error: Can\'t call _get_invoice_matching_query() for different rules than \'invoice_matching\'')) unaccent = get_unaccent_wrapper(self._cr) # N.B: 'communication_flag' is there to distinguish invoice matching through the number/reference # (higher priority) from invoice matching using the partner (lower priority). query = r''' SELECT st_line.id AS id, aml.id AS aml_id, aml.currency_id AS aml_currency_id, aml.date_maturity AS aml_date_maturity, aml.amount_residual AS aml_amount_residual, aml.amount_residual_currency AS aml_amount_residual_currency, ''' + self._get_select_communication_flag() + r''' AS communication_flag, ''' + self._get_select_payment_reference_flag() + r''' AS payment_reference_flag FROM account_bank_statement_line st_line JOIN account_move st_line_move ON st_line_move.id = st_line.move_id JOIN res_company company ON company.id = st_line_move.company_id , account_move_line aml LEFT JOIN account_move move ON move.id = aml.move_id AND move.state = 'posted' LEFT JOIN account_account account ON account.id = aml.account_id LEFT JOIN res_partner aml_partner ON aml.partner_id = aml_partner.id LEFT JOIN account_payment payment ON payment.move_id = move.id WHERE aml.company_id = st_line_move.company_id AND move.state = 'posted' AND account.reconcile IS TRUE AND aml.reconciled IS FALSE ''' # Add conditions to handle each of the statement lines we want to match st_lines_queries = [] for st_line, partner in st_lines_with_partner: # In case we don't have any partner for this line, we try assigning one with the rule mapping if st_line.amount > 0: st_line_subquery = r"aml.balance > 0" else: st_line_subquery = r"aml.balance < 0" if self.match_same_currency: st_line_subquery += r" AND COALESCE(aml.currency_id, company.currency_id) = %s" % (st_line.foreign_currency_id.id or st_line.move_id.currency_id.id) if partner: st_line_subquery += r" AND aml.partner_id = %s" % partner.id else: st_line_fields_consideration = [ (self.match_text_location_label, 'st_line.payment_ref'), (self.match_text_location_note, 'st_line_move.narration'), (self.match_text_location_reference, 'st_line_move.ref'), ] no_partner_query = " OR ".join([ r""" ( substring(REGEXP_REPLACE(""" + sql_field + """, '[^0-9\s]', '', 'g'), '\S(?:.*\S)*') != '' AND ( (""" + self._get_select_communication_flag() + """) OR (""" + self._get_select_payment_reference_flag() + """) ) ) OR ( /* We also match statement lines without partners with amls whose partner's name's parts (splitting on space) are all present within the payment_ref, in any order, with any characters between them. */ aml_partner.name IS NOT NULL AND """ + unaccent(sql_field) + r""" ~* ('^' || ( SELECT string_agg(concat('(?=.*\m', chunk[1], '\M)'), '') FROM regexp_matches(""" + unaccent("aml_partner.name") + r""", '\w{3,}', 'g') AS chunk )) ) """ for consider_field, sql_field in st_line_fields_consideration if consider_field ]) if no_partner_query: st_line_subquery += " AND " + no_partner_query st_lines_queries.append(r"st_line.id = %s AND (%s)" % (st_line.id, st_line_subquery)) query += r" AND (%s) " % " OR ".join(st_lines_queries) params = {} # If this reconciliation model defines a past_months_limit, we add a condition # to the query to only search on move lines that are younger than this limit. if self.past_months_limit: date_limit = fields.Date.context_today(self) - relativedelta(months=self.past_months_limit) query += " AND aml.date >= %(aml_date_limit)s" params['aml_date_limit'] = date_limit # Filter out excluded account.move.line. if excluded_ids: query += ' AND aml.id NOT IN %(excluded_aml_ids)s' params['excluded_aml_ids'] = tuple(excluded_ids) if self.matching_order == 'new_first': query += ' ORDER BY aml_date_maturity DESC, aml_id DESC' else: query += ' ORDER BY aml_date_maturity ASC, aml_id ASC' return query, params def _get_select_communication_flag(self): self.ensure_one() # Determine a matching or not with the statement line communication using the aml.name, move.name or move.ref. st_ref_list = [] if self.match_text_location_label: st_ref_list += ['st_line.payment_ref'] if self.match_text_location_note: st_ref_list += ['st_line_move.narration'] if self.match_text_location_reference: st_ref_list += ['st_line_move.ref'] st_ref = " || ' ' || ".join( "COALESCE(%s, '')" % st_ref_name for st_ref_name in st_ref_list ) if not st_ref: return "FALSE" statement_compare = r"""( {move_field} IS NOT NULL AND substring(REGEXP_REPLACE({move_field}, '[^0-9\s]', '', 'g'), '\S(?:.*\S)*') != '' AND ( regexp_split_to_array(substring(REGEXP_REPLACE({move_field}, '[^0-9\s]', '', 'g'), '\S(?:.*\S)*'),'\s+') && regexp_split_to_array(substring(REGEXP_REPLACE({st_ref}, '[^0-9\s]', '', 'g'), '\S(?:.*\S)*'), '\s+') ) )""" return " OR ".join( statement_compare.format(move_field=field, st_ref=st_ref) for field in ['aml.name', 'move.name', 'move.ref'] ) def _get_select_payment_reference_flag(self): # Determine a matching or not with the statement line communication using the move.payment_reference. st_ref_list = [] if self.match_text_location_label: st_ref_list += ['st_line.payment_ref'] if self.match_text_location_note: st_ref_list += ['st_line_move.narration'] if self.match_text_location_reference: st_ref_list += ['st_line_move.ref'] if not st_ref_list: return "FALSE" # payment_reference is not used on account.move for payments; ref is used instead return r'''((move.payment_reference IS NOT NULL OR (payment.id IS NOT NULL AND move.ref IS NOT NULL)) AND ({}))'''.format( ' OR '.join( rf"regexp_replace(CASE WHEN payment.id IS NULL THEN move.payment_reference ELSE move.ref END, '\s+', '', 'g') = regexp_replace({st_ref}, '\s+', '', 'g')" for st_ref in st_ref_list ) ) def _get_partner_from_mapping(self, st_line): """Find partner with mapping defined on model. For invoice matching rules, matches the statement line against each regex defined in partner mapping, and returns the partner corresponding to the first one matching. :param st_line (Model<account.bank.statement.line>): The statement line that needs a partner to be found :return Model<res.partner>: The partner found from the mapping. Can be empty an empty recordset if there was nothing found from the mapping or if the function is not applicable. """ self.ensure_one() if self.rule_type not in ('invoice_matching', 'writeoff_suggestion'): return self.env['res.partner'] for partner_mapping in self.partner_mapping_line_ids: match_payment_ref = re.match(partner_mapping.payment_ref_regex, st_line.payment_ref) if partner_mapping.payment_ref_regex else True match_narration = re.match(partner_mapping.narration_regex, tools.html2plaintext(st_line.narration or '').rstrip()) if partner_mapping.narration_regex else True if match_payment_ref and match_narration: return partner_mapping.partner_id return self.env['res.partner'] def _get_writeoff_suggestion_query(self, st_lines_with_partner, excluded_ids=None): ''' Returns the query applying the current writeoff_suggestion reconciliation model to the provided statement lines. :param st_lines_with_partner: A list of tuples (statement_line, partner), associating each statement line to treate with the corresponding partner, given by the partner map :param excluded_ids: Account.move.lines to exclude. :return: (query, params) ''' self.ensure_one() if self.rule_type != 'writeoff_suggestion': raise UserError(_("Programmation Error: Can't call _get_writeoff_suggestion_query() for different rules than 'writeoff_suggestion'")) query = ''' SELECT st_line.id AS id FROM account_bank_statement_line st_line WHERE st_line.id IN %(st_line_ids)s ''' params = { 'st_line_ids': tuple(st_line.id for (st_line, partner) in st_lines_with_partner), } return query, params def _get_rule_result(self, st_line, candidates, aml_ids_to_exclude, reconciled_amls_ids, partner_map): """ Get the result of a rule from the list of available candidates, depending on the other reconciliations performed by previous rules. """ self.ensure_one() if self.rule_type == 'invoice_matching': return self._get_invoice_matching_rule_result(st_line, candidates, aml_ids_to_exclude, reconciled_amls_ids, partner_map) elif self.rule_type == 'writeoff_suggestion': return self._get_writeoff_suggestion_rule_result(st_line, partner_map), set(), set() else: return None, set(), set() def _get_invoice_matching_rule_result(self, st_line, candidates, aml_ids_to_exclude, reconciled_amls_ids, partner): new_reconciled_aml_ids = set() new_treated_aml_ids = set() candidates, priorities = self._filter_candidates(candidates, aml_ids_to_exclude, reconciled_amls_ids) st_line_currency = st_line.foreign_currency_id or st_line.currency_id candidate_currencies = set(candidate['aml_currency_id'] for candidate in candidates) kept_candidates = candidates if candidate_currencies == {st_line_currency.id}: kept_candidates = [] sum_kept_candidates = 0 for candidate in candidates: candidate_residual = candidate['aml_amount_residual_currency'] if st_line_currency.compare_amounts(candidate_residual, -st_line.amount_residual) == 0: # Special case: the amounts are the same, submit the line directly. kept_candidates = [candidate] break elif st_line_currency.compare_amounts(abs(sum_kept_candidates), abs(st_line.amount_residual)) < 0: # Candidates' and statement line's balances have the same sign, thanks to _get_invoice_matching_query. # We hence can compare their absolute value without any issue. # Here, we still have room for other candidates ; so we add the current one to the list we keep. # Then, we continue iterating, even if there is no room anymore, just in case one of the following candidates # is an exact match, which would then be preferred on the current candidates. kept_candidates.append(candidate) sum_kept_candidates += candidate_residual # It is possible kept_candidates now contain less different priorities; update them kept_candidates_by_priority = self._sort_reconciliation_candidates_by_priority(kept_candidates, aml_ids_to_exclude, reconciled_amls_ids) priorities = set(kept_candidates_by_priority.keys()) # We check the amount criteria of the reconciliation model, and select the # kept_candidates if they pass the verification. matched_candidates_values = self._process_matched_candidates_data(st_line, kept_candidates) status = self._check_rule_propositions(matched_candidates_values) if 'rejected' in status: rslt = None else: rslt = { 'model': self, 'aml_ids': [candidate['aml_id'] for candidate in kept_candidates], } new_treated_aml_ids = set(rslt['aml_ids']) # Create write-off lines (in company's currency). if 'allow_write_off' in status: residual_balance_after_rec = matched_candidates_values['residual_balance_curr'] + matched_candidates_values['candidates_balance_curr'] writeoff_vals_list = self._get_write_off_move_lines_dict( st_line, matched_candidates_values['balance_sign'] * residual_balance_after_rec, partner.id, ) if writeoff_vals_list: rslt['status'] = 'write_off' rslt['write_off_vals'] = writeoff_vals_list else: writeoff_vals_list = [] # Reconcile. if 'allow_auto_reconcile' in status: # Process auto-reconciliation. We only do that for the first two priorities, if they are not matched elsewhere. aml_ids = [candidate['aml_id'] for candidate in kept_candidates] lines_vals_list = [{'id': aml_id} for aml_id in aml_ids] if lines_vals_list and priorities & {1, 3} and self.auto_reconcile: # Ensure this will not raise an error if case of missing account to create an open balance. dummy, open_balance_vals = st_line._prepare_reconciliation(lines_vals_list + writeoff_vals_list) if not open_balance_vals or open_balance_vals.get('account_id'): if not st_line.partner_id and partner: st_line.partner_id = partner st_line.reconcile(lines_vals_list + writeoff_vals_list, allow_partial=True) rslt['status'] = 'reconciled' rslt['reconciled_lines'] = st_line.line_ids new_reconciled_aml_ids = new_treated_aml_ids return rslt, new_reconciled_aml_ids, new_treated_aml_ids def _process_matched_candidates_data(self, statement_line, candidates=None): """ Simulate the reconciliation of the statement line with the candidates and compute some useful data to perform all the matching rules logic. :param statement_line: An account.bank.statement.line record. :param candidates: Fetched account.move.lines from query (dict). :return: A python dict containing: * currency: The currency of the transaction. * statement_line: The statement line matching the candidates. * candidates: Fetched account.move.lines from query (dict). * reconciliation_overview: The computed reconciliation from '_prepare_reconciliation'. * open_balance_vals: The open balance returned by '_prepare_reconciliation'. * balance_sign: The sign applied to the balance to make amounts always positive. * residual_balance: The residual balance of the statement line before reconciling anything, always positive and expressed in company's currency. * candidates_balance: The balance of candidates lines expressed in company's currency. * residual_balance_curr: The residual balance of the statement line before reconciling anything, always positive and expressed in transaction's currency. * candidates_balance_curr: The balance of candidates lines expressed in transaction's currency. """ candidates = candidates or [] reconciliation_overview, open_balance_vals = statement_line._prepare_reconciliation([{ 'currency_id': aml['aml_currency_id'], 'amount_residual': aml['aml_amount_residual'], 'amount_residual_currency': aml['aml_amount_residual_currency'], } for aml in candidates]) # Compute 'residual_balance', the remaining amount to reconcile of the statement line expressed in the # transaction currency. liquidity_lines, suspense_lines, dummy = statement_line._seek_for_lines() if statement_line.to_check: stl_residual_balance = -liquidity_lines.balance stl_residual_balance_curr = -liquidity_lines.amount_currency elif suspense_lines.account_id.reconcile: stl_residual_balance = sum(suspense_lines.mapped('amount_residual')) stl_residual_balance_curr = sum(suspense_lines.mapped('amount_residual_currency')) else: stl_residual_balance = sum(suspense_lines.mapped('balance')) stl_residual_balance_curr = sum(suspense_lines.mapped('amount_currency')) # Compute 'reconciled_balance', the total reconciled amount to be reconciled by the candidates. candidates_balance = 0.0 candidates_balance_curr = 0.0 for reconciliation_vals in reconciliation_overview: line_vals = reconciliation_vals['line_vals'] candidates_balance -= line_vals['debit'] - line_vals['credit'] if line_vals['currency_id']: candidates_balance_curr -= line_vals['amount_currency'] else: candidates_balance_curr -= line_vals['debit'] - line_vals['credit'] # Sign amount to ease computation. Multiplying any amount from the statement line makes it positive. balance_sign = 1 if stl_residual_balance > 0.0 else -1 return { 'currency': statement_line.foreign_currency_id or statement_line.currency_id, 'statement_line': statement_line, 'candidates': candidates, 'reconciliation_overview': reconciliation_overview, 'open_balance_vals': open_balance_vals, 'balance_sign': balance_sign, 'residual_balance': balance_sign * stl_residual_balance, 'candidates_balance': balance_sign * candidates_balance, 'residual_balance_curr': balance_sign * stl_residual_balance_curr, 'candidates_balance_curr': balance_sign * candidates_balance_curr, } def _check_rule_propositions(self, matched_candidates_values): """ Check restrictions that can't be handled for each move.line separately. Note: Only used by models having a type equals to 'invoice_matching'. :param matched_candidates_values: The values computed by '_process_matched_candidates_data'. :return: A string representing what to do with the candidates: * rejected: Reject candidates. * allow_write_off: Allow to generate the write-off from the reconcile model lines if specified. * allow_auto_reconcile: Allow to automatically reconcile entries if 'auto_validate' is enabled. """ candidates = matched_candidates_values['candidates'] currency = matched_candidates_values['currency'] if not self.allow_payment_tolerance: return {'allow_write_off', 'allow_auto_reconcile'} if not candidates: return {'rejected'} # The statement line will be fully reconciled. residual_balance_after_rec = matched_candidates_values['residual_balance_curr'] + matched_candidates_values['candidates_balance_curr'] if currency.is_zero(residual_balance_after_rec): return {'allow_auto_reconcile'} # The payment amount is higher than the sum of invoices. # In that case, don't check the tolerance and don't try to generate any write-off. if residual_balance_after_rec > 0.0: return {'allow_auto_reconcile'} # No tolerance, reject the candidates. if self.payment_tolerance_param == 0: return {'rejected'} # If the tolerance is expressed as a fixed amount, check the residual payment amount doesn't exceed the # tolerance. if self.payment_tolerance_type == 'fixed_amount' and -residual_balance_after_rec <= self.payment_tolerance_param: return {'allow_write_off', 'allow_auto_reconcile'} # The tolerance is expressed as a percentage between 0 and 100.0. reconciled_percentage_left = (residual_balance_after_rec / matched_candidates_values['candidates_balance_curr']) * 100.0 if self.payment_tolerance_type == 'percentage' and reconciled_percentage_left <= self.payment_tolerance_param: return {'allow_write_off', 'allow_auto_reconcile'} return {'rejected'} def _filter_candidates(self, candidates, aml_ids_to_exclude, reconciled_amls_ids): """ Sorts reconciliation candidates by priority and filters them so that only the most prioritary are kept. """ candidates_by_priority = self._sort_reconciliation_candidates_by_priority(candidates, aml_ids_to_exclude, reconciled_amls_ids) # This can happen if the candidates were already reconciled at this point if not candidates_by_priority: return [], set() max_priority = min(candidates_by_priority.keys()) filtered_candidates = candidates_by_priority[max_priority] filtered_priorities = {max_priority,} if max_priority in (1, 3, 5): # We also keep the already proposed values of the same priority level proposed_priority = max_priority + 1 filtered_candidates += candidates_by_priority[proposed_priority] if candidates_by_priority[proposed_priority]: filtered_priorities.add(proposed_priority) return filtered_candidates, filtered_priorities def _sort_reconciliation_candidates_by_priority(self, candidates, already_proposed_aml_ids, already_reconciled_aml_ids): """ Sorts the provided candidates and returns a mapping of candidates by priority (1 being the highest). The priorities are defined as follows: 1: payment_reference_flag is true, so the move's payment_reference field matches the statement line's. 2: Same as 1, but the candidates have already been proposed for a previous statement line 3: communication_flag is true, so either the move's ref, move's name or aml's name match the statement line's payment reference. 4: Same as 3, but the candidates have already been proposed for a previous statement line 5: candidates proposed by the query, but no match with the statement line's payment ref could be found. 6: Same as 5, but the candidates have already been proposed for a previous statement line """ candidates_by_priority = defaultdict(lambda: []) for candidate in filter(lambda x: x['aml_id'] not in already_reconciled_aml_ids, candidates): if candidate['payment_reference_flag']: priority = 1 elif candidate['communication_flag']: priority = 3 else: priority = 5 if candidate['aml_id'] in already_proposed_aml_ids: # So, priorities 2, 4 and 6 are created here priority += 1 candidates_by_priority[priority].append(candidate) return candidates_by_priority def _get_writeoff_suggestion_rule_result(self, st_line, partner): # Create write-off lines. matched_candidates_values = self._process_matched_candidates_data(st_line) residual_balance_after_rec = matched_candidates_values['residual_balance_curr'] + matched_candidates_values['candidates_balance_curr'] writeoff_vals_list = self._get_write_off_move_lines_dict( st_line, matched_candidates_values['balance_sign'] * residual_balance_after_rec, partner.id, ) rslt = { 'model': self, 'status': 'write_off', 'aml_ids': [], 'write_off_vals': writeoff_vals_list, } # Process auto-reconciliation. if writeoff_vals_list and self.auto_reconcile: if not st_line.partner_id and partner: st_line.partner_id = partner st_line.reconcile(writeoff_vals_list) rslt['status'] = 'reconciled' rslt['reconciled_lines'] = st_line.line_ids return rslt
52.744681
59,496
4,224
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class AccountAnalyticDefault(models.Model): _name = "account.analytic.default" _description = "Analytic Distribution" _rec_name = "analytic_id" _order = "sequence" sequence = fields.Integer(string='Sequence', help="Gives the sequence order when displaying a list of analytic distribution") analytic_id = fields.Many2one('account.analytic.account', string='Analytic Account') analytic_tag_ids = fields.Many2many('account.analytic.tag', string='Analytic Tags') product_id = fields.Many2one('product.product', string='Product', ondelete='cascade', help="Select a product which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this product, it will automatically take this as an analytic account)") partner_id = fields.Many2one('res.partner', string='Partner', ondelete='cascade', help="Select a partner which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this partner, it will automatically take this as an analytic account)") account_id = fields.Many2one('account.account', string='Account', ondelete='cascade', help="Select an accounting account which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this account, it will automatically take this as an analytic account)") user_id = fields.Many2one('res.users', string='User', ondelete='cascade', help="Select a user which will use analytic account specified in analytic default.") company_id = fields.Many2one('res.company', string='Company', ondelete='cascade', help="Select a company which will use analytic account specified in analytic default (e.g. create new customer invoice or Sales order if we select this company, it will automatically take this as an analytic account)") date_start = fields.Date(string='Start Date', help="Default start date for this Analytic Account.") date_stop = fields.Date(string='End Date', help="Default end date for this Analytic Account.") @api.constrains('analytic_id', 'analytic_tag_ids') def _check_account_or_tags(self): if any(not default.analytic_id and not any(tag.analytic_distribution_ids for tag in default.analytic_tag_ids) for default in self ): raise ValidationError(_('An analytic default requires an analytic account or an analytic tag used for analytic distribution.')) @api.model def account_get(self, product_id=None, partner_id=None, account_id=None, user_id=None, date=None, company_id=None): domain = [] if product_id: domain += ['|', ('product_id', '=', product_id)] domain += [('product_id', '=', False)] if partner_id: domain += ['|', ('partner_id', '=', partner_id)] domain += [('partner_id', '=', False)] if account_id: domain += ['|', ('account_id', '=', account_id)] domain += [('account_id', '=', False)] if company_id: domain += ['|', ('company_id', '=', company_id)] domain += [('company_id', '=', False)] if user_id: domain += ['|', ('user_id', '=', user_id)] domain += [('user_id', '=', False)] if date: domain += ['|', ('date_start', '<=', date), ('date_start', '=', False)] domain += ['|', ('date_stop', '>=', date), ('date_stop', '=', False)] best_index = -1 res = self.env['account.analytic.default'] for rec in self.search(domain): index = 0 if rec.product_id: index += 1 if rec.partner_id: index += 1 if rec.account_id: index += 1 if rec.company_id: index += 1 if rec.user_id: index += 1 if rec.date_start: index += 1 if rec.date_stop: index += 1 if index > best_index: res = rec best_index = index return res
62.117647
4,224
757
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class AccountIncoterms(models.Model): _name = 'account.incoterms' _description = 'Incoterms' name = fields.Char( 'Name', required=True, translate=True, help="Incoterms are series of sales terms. They are used to divide transaction costs and responsibilities between buyer and seller and reflect state-of-the-art transportation practices.") code = fields.Char( 'Code', size=3, required=True, help="Incoterm Standard Code") active = fields.Boolean( 'Active', default=True, help="By unchecking the active field, you may hide an INCOTERM you will not use.")
39.842105
757
29,461
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. import time import logging from psycopg2 import sql, DatabaseError from odoo import api, fields, models, _ from odoo.tools import DEFAULT_SERVER_DATETIME_FORMAT from odoo.exceptions import ValidationError, UserError from odoo.addons.base.models.res_partner import WARNING_MESSAGE, WARNING_HELP _logger = logging.getLogger(__name__) class AccountFiscalPosition(models.Model): _name = 'account.fiscal.position' _description = 'Fiscal Position' _order = 'sequence' sequence = fields.Integer() name = fields.Char(string='Fiscal Position', required=True) active = fields.Boolean(default=True, help="By unchecking the active field, you may hide a fiscal position without deleting it.") company_id = fields.Many2one( comodel_name='res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company) account_ids = fields.One2many('account.fiscal.position.account', 'position_id', string='Account Mapping', copy=True) tax_ids = fields.One2many('account.fiscal.position.tax', 'position_id', string='Tax Mapping', copy=True) note = fields.Html('Notes', translate=True, help="Legal mentions that have to be printed on the invoices.") auto_apply = fields.Boolean(string='Detect Automatically', help="Apply automatically this fiscal position.") vat_required = fields.Boolean(string='VAT required', help="Apply only if partner has a VAT number.") company_country_id = fields.Many2one(string="Company Country", related='company_id.account_fiscal_country_id') country_id = fields.Many2one('res.country', string='Country', help="Apply only if delivery country matches.") country_group_id = fields.Many2one('res.country.group', string='Country Group', help="Apply only if delivery country matches the group.") state_ids = fields.Many2many('res.country.state', string='Federal States') zip_from = fields.Char(string='Zip Range From') zip_to = fields.Char(string='Zip Range To') # To be used in hiding the 'Federal States' field('attrs' in view side) when selected 'Country' has 0 states. states_count = fields.Integer(compute='_compute_states_count') foreign_vat = fields.Char(string="Foreign Tax ID", help="The tax ID of your company in the region mapped by this fiscal position.") foreign_vat_header_mode = fields.Selection( selection=[('templates_found', "Templates Found"), ('no_template', "No Template")], compute='_compute_foreign_vat_header_mode', help="Technical field used to display a banner on top of foreign vat fiscal positions, " "in order to ease the instantiation of foreign taxes when possible." ) def _compute_states_count(self): for position in self: position.states_count = len(position.country_id.state_ids) @api.depends('foreign_vat', 'country_id') def _compute_foreign_vat_header_mode(self): for record in self: if not record.foreign_vat or not record.country_id: record.foreign_vat_header_mode = None continue if self.env['account.tax'].search([('country_id', '=', record.country_id.id)], limit=1): record.foreign_vat_header_mode = None elif self.env['account.tax.template'].search([('chart_template_id.country_id', '=', record.country_id.id)], limit=1): record.foreign_vat_header_mode = 'templates_found' else: record.foreign_vat_header_mode = 'no_template' @api.constrains('zip_from', 'zip_to') def _check_zip(self): for position in self: if position.zip_from and position.zip_to and position.zip_from > position.zip_to: raise ValidationError(_('Invalid "Zip Range", please configure it properly.')) @api.constrains('country_id', 'state_ids', 'foreign_vat') def _validate_foreign_vat_country(self): for record in self: if record.foreign_vat: if record.country_id == record.company_id.account_fiscal_country_id: if record.foreign_vat == record.company_id.vat: raise ValidationError(_("You cannot create a fiscal position within your fiscal country with the same VAT number as the main one set on your company.")) if not record.state_ids: if record.company_id.account_fiscal_country_id.state_ids: raise ValidationError(_("You cannot create a fiscal position with a foreign VAT within your fiscal country without assigning it a state.")) else: raise ValidationError(_("You cannot create a fiscal position with a foreign VAT within your fiscal country.")) similar_fpos_domain = [ ('foreign_vat', '!=', False), ('country_id', '=', record.country_id.id), ('company_id', '=', record.company_id.id), ('id', '!=', record.id), ] if record.state_ids: similar_fpos_domain.append(('state_ids', 'in', record.state_ids.ids)) similar_fpos_count = self.env['account.fiscal.position'].search_count(similar_fpos_domain) if similar_fpos_count: raise ValidationError(_("A fiscal position with a foreign VAT already exists in this region.")) def map_tax(self, taxes): if not self: return taxes result = self.env['account.tax'] for tax in taxes: taxes_correspondance = self.tax_ids.filtered(lambda t: t.tax_src_id == tax._origin) result |= taxes_correspondance.tax_dest_id if taxes_correspondance else tax return result def map_account(self, account): for pos in self.account_ids: if pos.account_src_id == account: return pos.account_dest_id return account def map_accounts(self, accounts): """ Receive a dictionary having accounts in values and try to replace those accounts accordingly to the fiscal position. """ ref_dict = {} for line in self.account_ids: ref_dict[line.account_src_id] = line.account_dest_id for key, acc in accounts.items(): if acc in ref_dict: accounts[key] = ref_dict[acc] return accounts @api.onchange('country_id') def _onchange_country_id(self): if self.country_id: self.zip_from = self.zip_to = self.country_group_id = False self.state_ids = [(5,)] self.states_count = len(self.country_id.state_ids) @api.onchange('country_group_id') def _onchange_country_group_id(self): if self.country_group_id: self.zip_from = self.zip_to = self.country_id = False self.state_ids = [(5,)] @api.model def _convert_zip_values(self, zip_from='', zip_to=''): max_length = max(len(zip_from), len(zip_to)) if zip_from.isdigit(): zip_from = zip_from.rjust(max_length, '0') if zip_to.isdigit(): zip_to = zip_to.rjust(max_length, '0') return zip_from, zip_to @api.model def create(self, vals): zip_from = vals.get('zip_from') zip_to = vals.get('zip_to') if zip_from and zip_to: vals['zip_from'], vals['zip_to'] = self._convert_zip_values(zip_from, zip_to) return super(AccountFiscalPosition, self).create(vals) def write(self, vals): zip_from = vals.get('zip_from') zip_to = vals.get('zip_to') if zip_from or zip_to: for rec in self: vals['zip_from'], vals['zip_to'] = self._convert_zip_values(zip_from or rec.zip_from, zip_to or rec.zip_to) return super(AccountFiscalPosition, self).write(vals) @api.model def _get_fpos_by_region(self, country_id=False, state_id=False, zipcode=False, vat_required=False): if not country_id: return False base_domain = [ ('auto_apply', '=', True), ('vat_required', '=', vat_required), ('company_id', 'in', [self.env.company.id, False]), ] null_state_dom = state_domain = [('state_ids', '=', False)] null_zip_dom = zip_domain = [('zip_from', '=', False), ('zip_to', '=', False)] null_country_dom = [('country_id', '=', False), ('country_group_id', '=', False)] if zipcode: zip_domain = [('zip_from', '<=', zipcode), ('zip_to', '>=', zipcode)] if state_id: state_domain = [('state_ids', '=', state_id)] domain_country = base_domain + [('country_id', '=', country_id)] domain_group = base_domain + [('country_group_id.country_ids', '=', country_id)] # Build domain to search records with exact matching criteria fpos = self.search(domain_country + state_domain + zip_domain, limit=1) # return records that fit the most the criteria, and fallback on less specific fiscal positions if any can be found if not fpos and state_id: fpos = self.search(domain_country + null_state_dom + zip_domain, limit=1) if not fpos and zipcode: fpos = self.search(domain_country + state_domain + null_zip_dom, limit=1) if not fpos and state_id and zipcode: fpos = self.search(domain_country + null_state_dom + null_zip_dom, limit=1) # fallback: country group with no state/zip range if not fpos: fpos = self.search(domain_group + null_state_dom + null_zip_dom, limit=1) if not fpos: # Fallback on catchall (no country, no group) fpos = self.search(base_domain + null_country_dom, limit=1) return fpos @api.model def get_fiscal_position(self, partner_id, delivery_id=None): """ :return: fiscal position found (recordset) :rtype: :class:`account.fiscal.position` """ if not partner_id: return self.env['account.fiscal.position'] # This can be easily overridden to apply more complex fiscal rules PartnerObj = self.env['res.partner'] partner = PartnerObj.browse(partner_id) delivery = PartnerObj.browse(delivery_id) company = self.env.company eu_country_codes = set(self.env.ref('base.europe').country_ids.mapped('code')) intra_eu = vat_exclusion = False if company.vat and partner.vat: intra_eu = company.vat[:2] in eu_country_codes and partner.vat[:2] in eu_country_codes vat_exclusion = company.vat[:2] == partner.vat[:2] # If company and partner have the same vat prefix (and are both within the EU), use invoicing if not delivery or (intra_eu and vat_exclusion): delivery = partner # partner manually set fiscal position always win if delivery.property_account_position_id or partner.property_account_position_id: return delivery.property_account_position_id or partner.property_account_position_id # First search only matching VAT positions vat_required = bool(partner.vat) fp = self._get_fpos_by_region(delivery.country_id.id, delivery.state_id.id, delivery.zip, vat_required) # Then if VAT required found no match, try positions that do not require it if not fp and vat_required: fp = self._get_fpos_by_region(delivery.country_id.id, delivery.state_id.id, delivery.zip, False) return fp or self.env['account.fiscal.position'] def action_create_foreign_taxes(self): self.ensure_one() self.env['account.tax.template']._try_instantiating_foreign_taxes(self.country_id, self.company_id) class AccountFiscalPositionTax(models.Model): _name = 'account.fiscal.position.tax' _description = 'Tax Mapping of Fiscal Position' _rec_name = 'position_id' _check_company_auto = True position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position', required=True, ondelete='cascade') company_id = fields.Many2one('res.company', string='Company', related='position_id.company_id', store=True) tax_src_id = fields.Many2one('account.tax', string='Tax on Product', required=True, check_company=True) tax_dest_id = fields.Many2one('account.tax', string='Tax to Apply', check_company=True) _sql_constraints = [ ('tax_src_dest_uniq', 'unique (position_id,tax_src_id,tax_dest_id)', 'A tax fiscal position could be defined only one time on same taxes.') ] class AccountFiscalPositionAccount(models.Model): _name = 'account.fiscal.position.account' _description = 'Accounts Mapping of Fiscal Position' _rec_name = 'position_id' _check_company_auto = True position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position', required=True, ondelete='cascade') company_id = fields.Many2one('res.company', string='Company', related='position_id.company_id', store=True) account_src_id = fields.Many2one('account.account', string='Account on Product', check_company=True, required=True, domain="[('deprecated', '=', False), ('company_id', '=', company_id)]") account_dest_id = fields.Many2one('account.account', string='Account to Use Instead', check_company=True, required=True, domain="[('deprecated', '=', False), ('company_id', '=', company_id)]") _sql_constraints = [ ('account_src_dest_uniq', 'unique (position_id,account_src_id,account_dest_id)', 'An account fiscal position could be defined only one time on same accounts.') ] class ResPartner(models.Model): _name = 'res.partner' _inherit = 'res.partner' @api.depends_context('company') def _credit_debit_get(self): tables, where_clause, where_params = self.env['account.move.line'].with_context(state='posted', company_id=self.env.company.id)._query_get() where_params = [tuple(self.ids)] + where_params if where_clause: where_clause = 'AND ' + where_clause self._cr.execute("""SELECT account_move_line.partner_id, act.type, SUM(account_move_line.amount_residual) FROM """ + tables + """ LEFT JOIN account_account a ON (account_move_line.account_id=a.id) LEFT JOIN account_account_type act ON (a.user_type_id=act.id) WHERE act.type IN ('receivable','payable') AND account_move_line.partner_id IN %s AND account_move_line.reconciled IS NOT TRUE """ + where_clause + """ GROUP BY account_move_line.partner_id, act.type """, where_params) treated = self.browse() for pid, type, val in self._cr.fetchall(): partner = self.browse(pid) if type == 'receivable': partner.credit = val if partner not in treated: partner.debit = False treated |= partner elif type == 'payable': partner.debit = -val if partner not in treated: partner.credit = False treated |= partner remaining = (self - treated) remaining.debit = False remaining.credit = False def _asset_difference_search(self, account_type, operator, operand): if operator not in ('<', '=', '>', '>=', '<='): return [] if type(operand) not in (float, int): return [] sign = 1 if account_type == 'payable': sign = -1 res = self._cr.execute(''' SELECT partner.id FROM res_partner partner LEFT JOIN account_move_line aml ON aml.partner_id = partner.id JOIN account_move move ON move.id = aml.move_id RIGHT JOIN account_account acc ON aml.account_id = acc.id WHERE acc.internal_type = %s AND NOT acc.deprecated AND acc.company_id = %s AND move.state = 'posted' GROUP BY partner.id HAVING %s * COALESCE(SUM(aml.amount_residual), 0) ''' + operator + ''' %s''', (account_type, self.env.company.id, sign, operand)) res = self._cr.fetchall() if not res: return [('id', '=', '0')] return [('id', 'in', [r[0] for r in res])] @api.model def _credit_search(self, operator, operand): return self._asset_difference_search('receivable', operator, operand) @api.model def _debit_search(self, operator, operand): return self._asset_difference_search('payable', operator, operand) def _invoice_total(self): self.total_invoiced = 0 if not self.ids: return True all_partners_and_children = {} all_partner_ids = [] for partner in self.filtered('id'): # price_total is in the company currency all_partners_and_children[partner] = self.with_context(active_test=False).search([('id', 'child_of', partner.id)]).ids all_partner_ids += all_partners_and_children[partner] domain = [ ('partner_id', 'in', all_partner_ids), ('state', 'not in', ['draft', 'cancel']), ('move_type', 'in', ('out_invoice', 'out_refund')), ] price_totals = self.env['account.invoice.report'].read_group(domain, ['price_subtotal'], ['partner_id']) for partner, child_ids in all_partners_and_children.items(): partner.total_invoiced = sum(price['price_subtotal'] for price in price_totals if price['partner_id'][0] in child_ids) def _compute_journal_item_count(self): AccountMoveLine = self.env['account.move.line'] for partner in self: partner.journal_item_count = AccountMoveLine.search_count([('partner_id', '=', partner.id)]) def _compute_has_unreconciled_entries(self): for partner in self: # Avoid useless work if has_unreconciled_entries is not relevant for this partner if not partner.active or not partner.is_company and partner.parent_id: partner.has_unreconciled_entries = False continue self.env.cr.execute( """ SELECT 1 FROM( SELECT p.last_time_entries_checked AS last_time_entries_checked, MAX(l.write_date) AS max_date FROM account_move_line l RIGHT JOIN account_account a ON (a.id = l.account_id) RIGHT JOIN res_partner p ON (l.partner_id = p.id) WHERE p.id = %s AND EXISTS ( SELECT 1 FROM account_move_line l WHERE l.account_id = a.id AND l.partner_id = p.id AND l.amount_residual > 0 ) AND EXISTS ( SELECT 1 FROM account_move_line l WHERE l.account_id = a.id AND l.partner_id = p.id AND l.amount_residual < 0 ) GROUP BY p.last_time_entries_checked ) as s WHERE (last_time_entries_checked IS NULL OR max_date > last_time_entries_checked) """, (partner.id,)) partner.has_unreconciled_entries = self.env.cr.rowcount == 1 def mark_as_reconciled(self): self.env['account.partial.reconcile'].check_access_rights('write') return self.sudo().write({'last_time_entries_checked': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) def _get_company_currency(self): for partner in self: if partner.company_id: partner.currency_id = partner.sudo().company_id.currency_id else: partner.currency_id = self.env.company.currency_id credit = fields.Monetary(compute='_credit_debit_get', search=_credit_search, string='Total Receivable', help="Total amount this customer owes you.") debit = fields.Monetary(compute='_credit_debit_get', search=_debit_search, string='Total Payable', help="Total amount you have to pay to this vendor.") debit_limit = fields.Monetary('Payable Limit') total_invoiced = fields.Monetary(compute='_invoice_total', string="Total Invoiced", groups='account.group_account_invoice,account.group_account_readonly') currency_id = fields.Many2one('res.currency', compute='_get_company_currency', readonly=True, string="Currency", help='Utility field to express amount currency') journal_item_count = fields.Integer(compute='_compute_journal_item_count', string="Journal Items") property_account_payable_id = fields.Many2one('account.account', company_dependent=True, string="Account Payable", domain="[('internal_type', '=', 'payable'), ('deprecated', '=', False), ('company_id', '=', current_company_id)]", help="This account will be used instead of the default one as the payable account for the current partner", required=True) property_account_receivable_id = fields.Many2one('account.account', company_dependent=True, string="Account Receivable", domain="[('internal_type', '=', 'receivable'), ('deprecated', '=', False), ('company_id', '=', current_company_id)]", help="This account will be used instead of the default one as the receivable account for the current partner", required=True) property_account_position_id = fields.Many2one('account.fiscal.position', company_dependent=True, string="Fiscal Position", domain="[('company_id', '=', current_company_id)]", help="The fiscal position determines the taxes/accounts used for this contact.") property_payment_term_id = fields.Many2one('account.payment.term', company_dependent=True, string='Customer Payment Terms', domain="[('company_id', 'in', [current_company_id, False])]", help="This payment term will be used instead of the default one for sales orders and customer invoices") property_supplier_payment_term_id = fields.Many2one('account.payment.term', company_dependent=True, string='Vendor Payment Terms', domain="[('company_id', 'in', [current_company_id, False])]", help="This payment term will be used instead of the default one for purchase orders and vendor bills") ref_company_ids = fields.One2many('res.company', 'partner_id', string='Companies that refers to partner') has_unreconciled_entries = fields.Boolean(compute='_compute_has_unreconciled_entries', help="The partner has at least one unreconciled debit and credit since last time the invoices & payments matching was performed.") last_time_entries_checked = fields.Datetime( string='Latest Invoices & Payments Matching Date', readonly=True, copy=False, help='Last time the invoices & payments matching was performed for this partner. ' 'It is set either if there\'s not at least an unreconciled debit and an unreconciled credit ' 'or if you click the "Done" button.') invoice_ids = fields.One2many('account.move', 'partner_id', string='Invoices', readonly=True, copy=False) contract_ids = fields.One2many('account.analytic.account', 'partner_id', string='Partner Contracts', readonly=True) bank_account_count = fields.Integer(compute='_compute_bank_count', string="Bank") trust = fields.Selection([('good', 'Good Debtor'), ('normal', 'Normal Debtor'), ('bad', 'Bad Debtor')], string='Degree of trust you have in this debtor', default='normal', company_dependent=True) invoice_warn = fields.Selection(WARNING_MESSAGE, 'Invoice', help=WARNING_HELP, default="no-message") invoice_warn_msg = fields.Text('Message for Invoice') # Computed fields to order the partners as suppliers/customers according to the # amount of their generated incoming/outgoing account moves supplier_rank = fields.Integer(default=0, copy=False) customer_rank = fields.Integer(default=0, copy=False) def _get_name_search_order_by_fields(self): res = super()._get_name_search_order_by_fields() partner_search_mode = self.env.context.get('res_partner_search_mode') if not partner_search_mode in ('customer', 'supplier'): return res order_by_field = 'COALESCE(res_partner.%s, 0) DESC,' if partner_search_mode == 'customer': field = 'customer_rank' else: field = 'supplier_rank' order_by_field = order_by_field % field return '%s, %s' % (res, order_by_field % field) if res else order_by_field def _compute_bank_count(self): bank_data = self.env['res.partner.bank'].read_group([('partner_id', 'in', self.ids)], ['partner_id'], ['partner_id']) mapped_data = dict([(bank['partner_id'][0], bank['partner_id_count']) for bank in bank_data]) for partner in self: partner.bank_account_count = mapped_data.get(partner.id, 0) def _find_accounting_partner(self, partner): ''' Find the partner for which the accounting entries will be created ''' return partner.commercial_partner_id @api.model def _commercial_fields(self): return super(ResPartner, self)._commercial_fields() + \ ['debit_limit', 'property_account_payable_id', 'property_account_receivable_id', 'property_account_position_id', 'property_payment_term_id', 'property_supplier_payment_term_id', 'last_time_entries_checked'] def action_view_partner_invoices(self): self.ensure_one() action = self.env["ir.actions.actions"]._for_xml_id("account.action_move_out_invoice_type") all_child = self.with_context(active_test=False).search([('id', 'child_of', self.ids)]) action['domain'] = [ ('move_type', 'in', ('out_invoice', 'out_refund')), ('partner_id', 'in', all_child.ids) ] action['context'] = {'default_move_type': 'out_invoice', 'move_type': 'out_invoice', 'journal_type': 'sale', 'search_default_unpaid': 1} return action def can_edit_vat(self): ''' Can't edit `vat` if there is (non draft) issued invoices. ''' can_edit_vat = super(ResPartner, self).can_edit_vat() if not can_edit_vat: return can_edit_vat has_invoice = self.env['account.move'].search([ ('move_type', 'in', ['out_invoice', 'out_refund']), ('partner_id', 'child_of', self.commercial_partner_id.id), ('state', '=', 'posted') ], limit=1) return can_edit_vat and not (bool(has_invoice)) @api.model_create_multi def create(self, vals_list): search_partner_mode = self.env.context.get('res_partner_search_mode') is_customer = search_partner_mode == 'customer' is_supplier = search_partner_mode == 'supplier' if search_partner_mode: for vals in vals_list: if is_customer and 'customer_rank' not in vals: vals['customer_rank'] = 1 elif is_supplier and 'supplier_rank' not in vals: vals['supplier_rank'] = 1 return super().create(vals_list) @api.ondelete(at_uninstall=False) def _unlink_if_partner_in_account_move(self): """ Prevent the deletion of a partner "Individual", child of a company if: - partner in 'account.move' - state: all states (draft and posted) """ moves = self.sudo().env['account.move'].search_count([ ('partner_id', 'in', self.ids), ('state', 'in', ['draft', 'posted']), ]) if moves: raise UserError(_("The partner cannot be deleted because it is used in Accounting")) def _increase_rank(self, field, n=1): if self.ids and field in ['customer_rank', 'supplier_rank']: try: with self.env.cr.savepoint(flush=False): query = sql.SQL(""" SELECT {field} FROM res_partner WHERE ID IN %(partner_ids)s FOR UPDATE NOWAIT; UPDATE res_partner SET {field} = {field} + %(n)s WHERE id IN %(partner_ids)s """).format(field=sql.Identifier(field)) self.env.cr.execute(query, {'partner_ids': tuple(self.ids), 'n': n}) for partner in self: self.env.cache.remove(partner, partner._fields[field]) except DatabaseError as e: if e.pgcode == '55P03': _logger.debug('Another transaction already locked partner rows. Cannot update partner ranks.') else: raise e
50.360684
29,461
51,147
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, Command, fields, models, _ from odoo.osv import expression from odoo.exceptions import UserError, ValidationError from odoo.addons.base.models.res_bank import sanitize_account_number from odoo.tools import remove_accents import logging import re import warnings _logger = logging.getLogger(__name__) class AccountJournalGroup(models.Model): _name = 'account.journal.group' _description = "Account Journal Group" _check_company_auto = True name = fields.Char("Journal Group", required=True, translate=True) company_id = fields.Many2one('res.company', required=True, default=lambda self: self.env.company) excluded_journal_ids = fields.Many2many('account.journal', string="Excluded Journals", domain="[('company_id', '=', company_id)]", check_company=True) sequence = fields.Integer(default=10) class AccountJournal(models.Model): _name = "account.journal" _description = "Journal" _order = 'sequence, type, code' _inherit = ['mail.thread', 'mail.activity.mixin'] _check_company_auto = True def _default_inbound_payment_methods(self): return self.env.ref('account.account_payment_method_manual_in') def _default_outbound_payment_methods(self): return self.env.ref('account.account_payment_method_manual_out') def __get_bank_statements_available_sources(self): return [('undefined', _('Undefined Yet'))] def _get_bank_statements_available_sources(self): return self.__get_bank_statements_available_sources() def _default_invoice_reference_model(self): """Get the invoice reference model according to the company's country.""" country_code = self.env.company.country_id.code country_code = country_code and country_code.lower() if country_code: for model in self._fields['invoice_reference_model'].get_values(self.env): if model.startswith(country_code): return model return 'odoo' name = fields.Char(string='Journal Name', required=True) code = fields.Char(string='Short Code', size=5, required=True, help="Shorter name used for display. The journal entries of this journal will also be named using this prefix by default.") active = fields.Boolean(default=True, help="Set active to false to hide the Journal without removing it.") type = fields.Selection([ ('sale', 'Sales'), ('purchase', 'Purchase'), ('cash', 'Cash'), ('bank', 'Bank'), ('general', 'Miscellaneous'), ], required=True, inverse='_inverse_type', help="Select 'Sale' for customer invoices journals.\n"\ "Select 'Purchase' for vendor bills journals.\n"\ "Select 'Cash' or 'Bank' for journals that are used in customer or vendor payments.\n"\ "Select 'General' for miscellaneous operations journals.") type_control_ids = fields.Many2many('account.account.type', 'journal_account_type_control_rel', 'journal_id', 'type_id', string='Allowed account types') account_control_ids = fields.Many2many('account.account', 'journal_account_control_rel', 'journal_id', 'account_id', string='Allowed accounts', check_company=True, domain="[('deprecated', '=', False), ('company_id', '=', company_id), ('is_off_balance', '=', False)]") default_account_type = fields.Many2one('account.account.type', compute="_compute_default_account_type") default_account_id = fields.Many2one( comodel_name='account.account', check_company=True, copy=False, ondelete='restrict', string='Default Account', domain="[('deprecated', '=', False), ('company_id', '=', company_id)," "'|', ('user_type_id', '=', default_account_type), ('user_type_id', 'in', type_control_ids)," "('user_type_id.type', 'not in', ('receivable', 'payable'))]") suspense_account_id = fields.Many2one( comodel_name='account.account', check_company=True, ondelete='restrict', readonly=False, store=True, compute='_compute_suspense_account_id', help="Bank statements transactions will be posted on the suspense account until the final reconciliation " "allowing finding the right account.", string='Suspense Account', domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), \ ('user_type_id.type', 'not in', ('receivable', 'payable')), \ ('user_type_id', '=', %s)]" % self.env.ref('account.data_account_type_current_assets').id) restrict_mode_hash_table = fields.Boolean(string="Lock Posted Entries with Hash", help="If ticked, the accounting entry or invoice receives a hash as soon as it is posted and cannot be modified anymore.") sequence = fields.Integer(help='Used to order Journals in the dashboard view', default=10) invoice_reference_type = fields.Selection(string='Communication Type', required=True, selection=[('none', 'Open'), ('partner', 'Based on Customer'), ('invoice', 'Based on Invoice')], default='invoice', help='You can set here the default communication that will appear on customer invoices, once validated, to help the customer to refer to that particular invoice when making the payment.') invoice_reference_model = fields.Selection(string='Communication Standard', required=True, selection=[('odoo', 'Odoo'), ('euro', 'European')], default=_default_invoice_reference_model, help="You can choose different models for each type of reference. The default one is the Odoo reference.") #groups_id = fields.Many2many('res.groups', 'account_journal_group_rel', 'journal_id', 'group_id', string='Groups') currency_id = fields.Many2one('res.currency', help='The currency used to enter statement', string="Currency") company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, index=True, default=lambda self: self.env.company, help="Company related to this journal") country_code = fields.Char(related='company_id.account_fiscal_country_id.code', readonly=True) refund_sequence = fields.Boolean(string='Dedicated Credit Note Sequence', help="Check this box if you don't want to share the same sequence for invoices and credit notes made from this journal", default=False) sequence_override_regex = fields.Text(help="Technical field used to enforce complex sequence composition that the system would normally misunderstand.\n"\ "This is a regex that can include all the following capture groups: prefix1, year, prefix2, month, prefix3, seq, suffix.\n"\ "The prefix* groups are the separators between the year, month and the actual increasing sequence number (seq).\n"\ "e.g: ^(?P<prefix1>.*?)(?P<year>\d{4})(?P<prefix2>\D*?)(?P<month>\d{2})(?P<prefix3>\D+?)(?P<seq>\d+)(?P<suffix>\D*?)$") inbound_payment_method_line_ids = fields.One2many( comodel_name='account.payment.method.line', domain=[('payment_type', '=', 'inbound')], compute='_compute_inbound_payment_method_line_ids', store=True, readonly=False, string='Inbound Payment Methods', inverse_name='journal_id', copy=False, check_company=True, help="Manual: Get paid by any method outside of Odoo.\n" "Payment Acquirers: Each payment acquirer has its own Payment Method. Request a transaction on/to a card thanks to a payment token saved by the partner when buying or subscribing online.\n" "Batch Deposit: Collect several customer checks at once generating and submitting a batch deposit to your bank. Module account_batch_payment is necessary.\n" "SEPA Direct Debit: Get paid in the SEPA zone thanks to a mandate your partner will have granted to you. Module account_sepa is necessary.\n" ) outbound_payment_method_line_ids = fields.One2many( comodel_name='account.payment.method.line', domain=[('payment_type', '=', 'outbound')], compute='_compute_outbound_payment_method_line_ids', store=True, readonly=False, string='Outbound Payment Methods', inverse_name='journal_id', copy=False, check_company=True, help="Manual: Pay by any method outside of Odoo.\n" "Check: Pay bills by check and print it from Odoo.\n" "SEPA Credit Transfer: Pay in the SEPA zone by submitting a SEPA Credit Transfer file to your bank. Module account_sepa is necessary.\n" ) profit_account_id = fields.Many2one( comodel_name='account.account', check_company=True, help="Used to register a profit when the ending balance of a cash register differs from what the system computes", string='Profit Account', domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), \ ('user_type_id.type', 'not in', ('receivable', 'payable')), \ ('user_type_id', 'in', %s)]" % [self.env.ref('account.data_account_type_revenue').id, self.env.ref('account.data_account_type_other_income').id]) loss_account_id = fields.Many2one( comodel_name='account.account', check_company=True, help="Used to register a loss when the ending balance of a cash register differs from what the system computes", string='Loss Account', domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), \ ('user_type_id.type', 'not in', ('receivable', 'payable')), \ ('user_type_id', '=', %s)]" % self.env.ref('account.data_account_type_expenses').id) # Bank journals fields company_partner_id = fields.Many2one('res.partner', related='company_id.partner_id', string='Account Holder', readonly=True, store=False) bank_account_id = fields.Many2one('res.partner.bank', string="Bank Account", ondelete='restrict', copy=False, check_company=True, domain="[('partner_id','=', company_partner_id), '|', ('company_id', '=', False), ('company_id', '=', company_id)]") bank_statements_source = fields.Selection(selection=_get_bank_statements_available_sources, string='Bank Feeds', default='undefined', help="Defines how the bank statements will be registered") bank_acc_number = fields.Char(related='bank_account_id.acc_number', readonly=False) bank_id = fields.Many2one('res.bank', related='bank_account_id.bank_id', readonly=False) # Sale journals fields sale_activity_type_id = fields.Many2one('mail.activity.type', string='Schedule Activity', default=False, help="Activity will be automatically scheduled on payment due date, improving collection process.") sale_activity_user_id = fields.Many2one('res.users', string="Activity User", help="Leave empty to assign the Salesperson of the invoice.") sale_activity_note = fields.Text('Activity Summary') # alias configuration for journals alias_id = fields.Many2one('mail.alias', string='Email Alias', help="Send one separate email for each invoice.\n\n" "Any file extension will be accepted.\n\n" "Only PDF and XML files will be interpreted by Odoo", copy=False) alias_domain = fields.Char('Alias domain', compute='_compute_alias_domain') alias_name = fields.Char('Alias Name', copy=False, compute='_compute_alias_name', inverse='_inverse_type', help="It creates draft invoices and bills by sending an email.", readonly=False) journal_group_ids = fields.Many2many('account.journal.group', domain="[('company_id', '=', company_id)]", check_company=True, string="Journal Groups") secure_sequence_id = fields.Many2one('ir.sequence', help='Sequence to use to ensure the securisation of data', check_company=True, readonly=True, copy=False) available_payment_method_ids = fields.Many2many( comodel_name='account.payment.method', compute='_compute_available_payment_method_ids' ) selected_payment_method_codes = fields.Char( compute='_compute_selected_payment_method_codes', help='Technical field used to hide or show payment method options if needed.' ) _sql_constraints = [ ('code_company_uniq', 'unique (code, company_id)', 'Journal codes must be unique per company.'), ] @api.depends('outbound_payment_method_line_ids', 'inbound_payment_method_line_ids') def _compute_available_payment_method_ids(self): """ Compute the available payment methods id by respecting the following rules: Methods of mode 'unique' cannot be used twice on the same company Methods of mode 'multi' cannot be used twice on the same journal """ method_information = self.env['account.payment.method']._get_payment_method_information() pay_methods = self.env['account.payment.method'].search([('code', 'in', list(method_information.keys()))]) pay_method_by_code = {x.code + x.payment_type: x for x in pay_methods} unique_pay_methods = [k for k, v in method_information.items() if v['mode'] == 'unique'] pay_methods_by_company = {} pay_methods_by_journal = {} if unique_pay_methods: self._cr.execute(''' SELECT journal.id, journal.company_id, ARRAY_AGG(DISTINCT apm.id) FROM account_payment_method_line apml JOIN account_journal journal ON journal.id = apml.journal_id JOIN account_payment_method apm ON apm.id = apml.payment_method_id WHERE apm.code IN %s GROUP BY journal.id, journal.company_id ''', [tuple(unique_pay_methods)]) for journal_id, company_id, payment_method_ids in self._cr.fetchall(): pay_methods_by_company[company_id] = set(payment_method_ids) pay_methods_by_journal[journal_id] = set(payment_method_ids) pay_method_ids_commands_x_journal = {j: [Command.clear()] for j in self} for payment_type in ('inbound', 'outbound'): for code, vals in method_information.items(): payment_method = pay_method_by_code.get(code + payment_type) if not payment_method: continue # Get the domain of the journals on which the current method is usable. method_domain = payment_method._get_payment_method_domain() for journal in self.filtered_domain(method_domain): protected_pay_method_ids = pay_methods_by_company.get(journal.company_id._origin.id, set()) \ - pay_methods_by_journal.get(journal._origin.id, set()) if payment_type == 'inbound': lines = journal.inbound_payment_method_line_ids else: lines = journal.outbound_payment_method_line_ids already_used = payment_method in lines.payment_method_id is_protected = payment_method.id in protected_pay_method_ids if vals['mode'] == 'unique' and (already_used or is_protected): continue # Only the manual payment method can be used multiple time on a single journal. if payment_method.code != "manual" and already_used: continue pay_method_ids_commands_x_journal[journal].append(Command.link(payment_method.id)) for journal, pay_method_ids_commands in pay_method_ids_commands_x_journal.items(): journal.available_payment_method_ids = pay_method_ids_commands @api.depends('type') def _compute_default_account_type(self): default_account_id_types = { 'bank': 'account.data_account_type_liquidity', 'cash': 'account.data_account_type_liquidity', 'sale': 'account.data_account_type_revenue', 'purchase': 'account.data_account_type_expenses' } for journal in self: if journal.type in default_account_id_types: journal.default_account_type = self.env.ref(default_account_id_types[journal.type]).id else: journal.default_account_type = False @api.depends('type', 'currency_id') def _compute_inbound_payment_method_line_ids(self): for journal in self: pay_method_line_ids_commands = [Command.clear()] if journal.type in ('bank', 'cash'): default_methods = journal._default_inbound_payment_methods() pay_method_line_ids_commands += [Command.create({ 'name': pay_method.name, 'payment_method_id': pay_method.id, }) for pay_method in default_methods] journal.inbound_payment_method_line_ids = pay_method_line_ids_commands @api.depends('type', 'currency_id') def _compute_outbound_payment_method_line_ids(self): for journal in self: pay_method_line_ids_commands = [Command.clear()] if journal.type in ('bank', 'cash'): default_methods = journal._default_outbound_payment_methods() pay_method_line_ids_commands += [Command.create({ 'name': pay_method.name, 'payment_method_id': pay_method.id, }) for pay_method in default_methods] journal.outbound_payment_method_line_ids = pay_method_line_ids_commands @api.depends('outbound_payment_method_line_ids', 'inbound_payment_method_line_ids') def _compute_selected_payment_method_codes(self): """ Set the selected payment method as a list of comma separated codes like: ,manual,check_printing,... These will be then used to display or not payment method specific fields in the view. """ for journal in self: codes = [line.code for line in journal.inbound_payment_method_line_ids + journal.outbound_payment_method_line_ids if line.code] journal.selected_payment_method_codes = ',' + ','.join(codes) + ',' @api.depends('company_id', 'type') def _compute_suspense_account_id(self): for journal in self: if journal.type not in ('bank', 'cash'): journal.suspense_account_id = False elif journal.suspense_account_id: journal.suspense_account_id = journal.suspense_account_id elif journal.company_id.account_journal_suspense_account_id: journal.suspense_account_id = journal.company_id.account_journal_suspense_account_id else: journal.suspense_account_id = False def _inverse_type(self): for record in self: record._update_mail_alias() @api.depends('name') def _compute_alias_domain(self): self.alias_domain = self.env["ir.config_parameter"].sudo().get_param("mail.catchall.domain") @api.depends('alias_id') def _compute_alias_name(self): for record in self: record.alias_name = record.alias_id.alias_name @api.constrains('type_control_ids') def _constrains_type_control_ids(self): self.env['account.move.line'].flush(['account_id', 'journal_id']) self.flush(['type_control_ids']) self._cr.execute(""" SELECT aml.id FROM account_move_line aml WHERE aml.journal_id in (%s) AND EXISTS (SELECT 1 FROM journal_account_type_control_rel rel WHERE rel.journal_id = aml.journal_id) AND NOT EXISTS (SELECT 1 FROM account_account acc JOIN journal_account_type_control_rel rel ON acc.user_type_id = rel.type_id WHERE acc.id = aml.account_id AND rel.journal_id = aml.journal_id) AND aml.display_type IS NULL """, tuple(self.ids)) if self._cr.fetchone(): raise ValidationError(_('Some journal items already exist in this journal but with accounts from different types than the allowed ones.')) @api.constrains('account_control_ids') def _constrains_account_control_ids(self): self.env['account.move.line'].flush(['account_id', 'journal_id']) self.flush(['account_control_ids']) self._cr.execute(""" SELECT aml.id FROM account_move_line aml WHERE aml.journal_id in (%s) AND EXISTS (SELECT 1 FROM journal_account_control_rel rel WHERE rel.journal_id = aml.journal_id) AND NOT EXISTS (SELECT 1 FROM journal_account_control_rel rel WHERE rel.account_id = aml.account_id AND rel.journal_id = aml.journal_id) AND aml.display_type IS NULL """, tuple(self.ids)) if self._cr.fetchone(): raise ValidationError(_('Some journal items already exist in this journal but with other accounts than the allowed ones.')) @api.constrains('type', 'bank_account_id') def _check_bank_account(self): for journal in self: if journal.type == 'bank' and journal.bank_account_id: if journal.bank_account_id.company_id and journal.bank_account_id.company_id != journal.company_id: raise ValidationError(_('The bank account of a bank journal must belong to the same company (%s).', journal.company_id.name)) # A bank account can belong to a customer/supplier, in which case their partner_id is the customer/supplier. # Or they are part of a bank journal and their partner_id must be the company's partner_id. if journal.bank_account_id.partner_id != journal.company_id.partner_id: raise ValidationError(_('The holder of a journal\'s bank account must be the company (%s).', journal.company_id.name)) @api.constrains('company_id') def _check_company_consistency(self): if not self: return self.flush(['company_id']) self._cr.execute(''' SELECT move.id FROM account_move move JOIN account_journal journal ON journal.id = move.journal_id WHERE move.journal_id IN %s AND move.company_id != journal.company_id ''', [tuple(self.ids)]) if self._cr.fetchone(): raise UserError(_("You can't change the company of your journal since there are some journal entries linked to it.")) @api.constrains('type', 'default_account_id') def _check_type_default_account_id_type(self): for journal in self: if journal.type in ('sale', 'purchase') and journal.default_account_id.user_type_id.type in ('receivable', 'payable'): raise ValidationError(_("The type of the journal's default credit/debit account shouldn't be 'receivable' or 'payable'.")) @api.constrains('inbound_payment_method_line_ids', 'outbound_payment_method_line_ids') def _check_payment_method_line_ids_multiplicity(self): """ Check and ensure that the payment method lines multiplicity is respected. """ method_info = self.env['account.payment.method']._get_payment_method_information() unique_codes = tuple(code for code, info in method_info.items() if info.get('mode') == 'unique') if not unique_codes: return self.flush(['inbound_payment_method_line_ids', 'outbound_payment_method_line_ids', 'company_id']) self.env['account.payment.method.line'].flush(['payment_method_id', 'journal_id']) self.env['account.payment.method'].flush(['code']) if unique_codes: self._cr.execute(''' SELECT apm.id FROM account_payment_method apm JOIN account_payment_method_line apml on apm.id = apml.payment_method_id JOIN account_journal journal on journal.id = apml.journal_id JOIN res_company company on journal.company_id = company.id WHERE apm.code in %s GROUP BY company.id, apm.id HAVING array_length(array_agg(journal.id), 1) > 1; ''', [unique_codes]) method_ids = [res[0] for res in self._cr.fetchall()] if method_ids: methods = self.env['account.payment.method'].browse(method_ids) raise ValidationError(_("Some payment methods supposed to be unique already exists somewhere else.\n" "(%s)", ', '.join([method.display_name for method in methods]))) @api.constrains('active') def _check_auto_post_draft_entries(self): # constraint should be tested just after archiving a journal, but shouldn't be raised when unarchiving a journal containing draft entries for journal in self.filtered(lambda j: not j.active): pending_moves = self.env['account.move'].search([ ('journal_id', '=', journal.id), ('state', '=', 'draft') ], limit=1) if pending_moves: raise ValidationError(_("You can not archive a journal containing draft journal entries.\n\n" "To proceed:\n" "1/ click on the top-right button 'Journal Entries' from this journal form\n" "2/ then filter on 'Draft' entries\n" "3/ select them all and post or delete them through the action menu")) @api.onchange('type') def _onchange_type(self): self.refund_sequence = self.type in ('sale', 'purchase') def _get_alias_values(self, type, alias_name=None): """ This function verifies that the user-given mail alias (or its fallback) doesn't contain non-ascii chars. The fallbacks are the journal's name, code, or type - these are suffixed with the company's name or id (in case the company's name is not ascii either). """ def get_company_suffix(): if self.company_id != self.env.ref('base.main_company'): try: remove_accents(self.company_id.name).encode('ascii') return '-' + str(self.company_id.name) except UnicodeEncodeError: return '-' + str(self.company_id.id) return '' if not alias_name: alias_name = self.name alias_name += get_company_suffix() try: remove_accents(alias_name).encode('ascii') except UnicodeEncodeError: try: remove_accents(self.code).encode('ascii') safe_alias_name = self.code except UnicodeEncodeError: safe_alias_name = self.type safe_alias_name += get_company_suffix() _logger.warning("Cannot use '%s' as email alias, fallback to '%s'", alias_name, safe_alias_name) alias_name = safe_alias_name return { 'alias_defaults': {'move_type': type == 'purchase' and 'in_invoice' or 'out_invoice', 'company_id': self.company_id.id, 'journal_id': self.id}, 'alias_parent_thread_id': self.id, 'alias_name': alias_name, } def unlink(self): bank_accounts = self.env['res.partner.bank'].browse() for bank_account in self.mapped('bank_account_id'): accounts = self.search([('bank_account_id', '=', bank_account.id)]) if accounts <= self: bank_accounts += bank_account self.mapped('alias_id').sudo().unlink() ret = super(AccountJournal, self).unlink() bank_accounts.unlink() return ret @api.returns('self', lambda value: value.id) def copy(self, default=None): default = dict(default or {}) # Find a unique code for the copied journal read_codes = self.env['account.journal'].with_context(active_test=False).search_read([('company_id', '=', self.company_id.id)], ['code']) all_journal_codes = {code_data['code'] for code_data in read_codes} copy_code = self.code code_prefix = re.sub(r'\d+', '', self.code).strip() counter = 1 while counter <= len(all_journal_codes) and copy_code in all_journal_codes: counter_str = str(counter) copy_prefix = code_prefix[:self._fields['code'].size - len(counter_str)] copy_code = ("%s%s" % (copy_prefix, counter_str)) counter += 1 if counter > len(all_journal_codes): # Should never happen, but put there just in case. raise UserError(_("Could not compute any code for the copy automatically. Please create it manually.")) default.update( code=copy_code, name=_("%s (copy)") % (self.name or '')) return super(AccountJournal, self).copy(default) def _update_mail_alias(self, vals=None): if vals is not None: warnings.warn( '`vals` is a deprecated argument of `_update_mail_alias`', DeprecationWarning, stacklevel=2 ) self.ensure_one() if self.type in ('purchase', 'sale'): alias_values = self._get_alias_values(type=self.type, alias_name=self.alias_name) if self.alias_id: self.alias_id.sudo().write(alias_values) else: alias_values['alias_model_id'] = self.env['ir.model']._get('account.move').id alias_values['alias_parent_model_id'] = self.env['ir.model']._get('account.journal').id self.alias_id = self.env['mail.alias'].sudo().create(alias_values) elif self.alias_id: self.alias_id.unlink() def write(self, vals): for journal in self: company = journal.company_id if ('company_id' in vals and journal.company_id.id != vals['company_id']): if self.env['account.move'].search([('journal_id', '=', journal.id)], limit=1): raise UserError(_('This journal already contains items, therefore you cannot modify its company.')) company = self.env['res.company'].browse(vals['company_id']) if journal.bank_account_id.company_id and journal.bank_account_id.company_id != company: journal.bank_account_id.write({ 'company_id': company.id, 'partner_id': company.partner_id.id, }) if 'currency_id' in vals: if journal.bank_account_id: journal.bank_account_id.currency_id = vals['currency_id'] if 'bank_account_id' in vals: if not vals.get('bank_account_id'): raise UserError(_('You cannot remove the bank account from the journal once set.')) else: bank_account = self.env['res.partner.bank'].browse(vals['bank_account_id']) if bank_account.partner_id != company.partner_id: raise UserError(_("The partners of the journal's company and the related bank account mismatch.")) if 'restrict_mode_hash_table' in vals and not vals.get('restrict_mode_hash_table'): journal_entry = self.env['account.move'].sudo().search([('journal_id', '=', self.id), ('state', '=', 'posted'), ('secure_sequence_number', '!=', 0)], limit=1) if journal_entry: field_string = self._fields['restrict_mode_hash_table'].get_description(self.env)['string'] raise UserError(_("You cannot modify the field %s of a journal that already has accounting entries.", field_string)) result = super(AccountJournal, self).write(vals) # Ensure the liquidity accounts are sharing the same foreign currency. if 'currency_id' in vals: for journal in self.filtered(lambda journal: journal.type in ('bank', 'cash')): journal.default_account_id.currency_id = journal.currency_id # Create the bank_account_id if necessary if 'bank_acc_number' in vals: for journal in self.filtered(lambda r: r.type == 'bank' and not r.bank_account_id): journal.set_bank_account(vals.get('bank_acc_number'), vals.get('bank_id')) for record in self: if record.restrict_mode_hash_table and not record.secure_sequence_id: record._create_secure_sequence(['secure_sequence_id']) return result @api.model def get_next_bank_cash_default_code(self, journal_type, company): journal_code_base = (journal_type == 'cash' and 'CSH' or 'BNK') journals = self.env['account.journal'].with_context(active_test=False).search([('code', 'like', journal_code_base + '%'), ('company_id', '=', company.id)]) for num in range(1, 100): # journal_code has a maximal size of 5, hence we can enforce the boundary num < 100 journal_code = journal_code_base + str(num) if journal_code not in journals.mapped('code'): return journal_code @api.model def _prepare_liquidity_account_vals(self, company, code, vals): return { 'name': vals.get('name'), 'code': code, 'user_type_id': self.env.ref('account.data_account_type_liquidity').id, 'currency_id': vals.get('currency_id'), 'company_id': company.id, } @api.model def _fill_missing_values(self, vals): journal_type = vals.get('type') # 'type' field is required. if not journal_type: return # === Fill missing company === company = self.env['res.company'].browse(vals['company_id']) if vals.get('company_id') else self.env.company vals['company_id'] = company.id # Don't get the digits on 'chart_template_id' since the chart template could be a custom one. random_account = self.env['account.account'].search([('company_id', '=', company.id)], limit=1) digits = len(random_account.code) if random_account else 6 liquidity_type = self.env.ref('account.data_account_type_liquidity') current_assets_type = self.env.ref('account.data_account_type_current_assets') if journal_type in ('bank', 'cash'): has_liquidity_accounts = vals.get('default_account_id') has_profit_account = vals.get('profit_account_id') has_loss_account = vals.get('loss_account_id') if journal_type == 'bank': liquidity_account_prefix = company.bank_account_code_prefix or '' else: liquidity_account_prefix = company.cash_account_code_prefix or company.bank_account_code_prefix or '' # === Fill missing name === vals['name'] = vals.get('name') or vals.get('bank_acc_number') # === Fill missing code === if 'code' not in vals: vals['code'] = self.get_next_bank_cash_default_code(journal_type, company) if not vals['code']: raise UserError(_("Cannot generate an unused journal code. Please fill the 'Shortcode' field.")) # === Fill missing accounts === if not has_liquidity_accounts: default_account_code = self.env['account.account']._search_new_account_code(company, digits, liquidity_account_prefix) default_account_vals = self._prepare_liquidity_account_vals(company, default_account_code, vals) vals['default_account_id'] = self.env['account.account'].create(default_account_vals).id if journal_type in ('cash', 'bank') and not has_profit_account: vals['profit_account_id'] = company.default_cash_difference_income_account_id.id if journal_type in ('cash', 'bank') and not has_loss_account: vals['loss_account_id'] = company.default_cash_difference_expense_account_id.id # === Fill missing refund_sequence === if 'refund_sequence' not in vals: vals['refund_sequence'] = vals['type'] in ('sale', 'purchase') @api.model def create(self, vals): # OVERRIDE self._fill_missing_values(vals) journal = super(AccountJournal, self.with_context(mail_create_nolog=True)).create(vals) # Create the bank_account_id if necessary if journal.type == 'bank' and not journal.bank_account_id and vals.get('bank_acc_number'): journal.set_bank_account(vals.get('bank_acc_number'), vals.get('bank_id')) return journal def set_bank_account(self, acc_number, bank_id=None): """ Create a res.partner.bank (if not exists) and set it as value of the field bank_account_id """ self.ensure_one() res_partner_bank = self.env['res.partner.bank'].search([('sanitized_acc_number', '=', sanitize_account_number(acc_number)), ('company_id', '=', self.company_id.id)], limit=1) if res_partner_bank: self.bank_account_id = res_partner_bank.id else: self.bank_account_id = self.env['res.partner.bank'].create({ 'acc_number': acc_number, 'bank_id': bank_id, 'company_id': self.company_id.id, 'currency_id': self.currency_id.id, 'partner_id': self.company_id.partner_id.id, }).id def name_get(self): res = [] for journal in self: name = journal.name if journal.currency_id and journal.currency_id != journal.company_id.currency_id: name = "%s (%s)" % (name, journal.currency_id.name) res += [(journal.id, name)] return res @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): args = args or [] if operator == 'ilike' and not (name or '').strip(): domain = [] else: connector = '&' if operator in expression.NEGATIVE_TERM_OPERATORS else '|' domain = [connector, ('code', operator, name), ('name', operator, name)] return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid) def action_configure_bank_journal(self): """ This function is called by the "configure" button of bank journals, visible on dashboard if no bank statement source has been defined yet """ # We simply call the setup bar function. return self.env['res.company'].setting_init_bank_account_action() def _create_invoice_from_attachment(self, attachment_ids=None): """ Create invoices from the attachments (for instance a Factur-X XML file) """ attachments = self.env['ir.attachment'].browse(attachment_ids) if not attachments: raise UserError(_("No attachment was provided")) invoices = self.env['account.move'] for attachment in attachments: decoders = self.env['account.move']._get_create_invoice_from_attachment_decoders() invoice = False for decoder in sorted(decoders, key=lambda d: d[0]): invoice = decoder[1](attachment) if invoice: break if not invoice: invoice = self.env['account.move'].create({}) invoice.with_context(no_new_invoice=True).message_post(attachment_ids=[attachment.id]) attachment.write({'res_model': 'account.move', 'res_id': invoice.id}) invoices += invoice return invoices def create_invoice_from_attachment(self, attachment_ids=None): """ Create invoices from the attachments (for instance a Factur-X XML file) and redirect the user to the newly created invoice(s). :param attachment_ids: list of attachment ids :return: action to open the created invoices """ invoices = self._create_invoice_from_attachment(attachment_ids) action_vals = { 'name': _('Generated Documents'), 'domain': [('id', 'in', invoices.ids)], 'res_model': 'account.move', 'type': 'ir.actions.act_window', 'context': self._context } if len(invoices) == 1: action_vals.update({ 'views': [[False, "form"]], 'view_mode': 'form', 'res_id': invoices[0].id, }) else: action_vals.update({ 'views': [[False, "tree"], [False, "kanban"], [False, "form"]], 'view_mode': 'tree, kanban, form', }) return action_vals def _create_secure_sequence(self, sequence_fields): """This function creates a no_gap sequence on each journal in self that will ensure a unique number is given to all posted account.move in such a way that we can always find the previous move of a journal entry on a specific journal. """ for journal in self: vals_write = {} for seq_field in sequence_fields: if not journal[seq_field]: vals = { 'name': _('Securisation of %s - %s') % (seq_field, journal.name), 'code': 'SECUR%s-%s' % (journal.id, seq_field), 'implementation': 'no_gap', 'prefix': '', 'suffix': '', 'padding': 0, 'company_id': journal.company_id.id} seq = self.env['ir.sequence'].create(vals) vals_write[seq_field] = seq.id if vals_write: journal.write(vals_write) # ------------------------------------------------------------------------- # REPORTING METHODS # ------------------------------------------------------------------------- def _get_journal_bank_account_balance(self, domain=None): ''' Get the bank balance of the current journal by filtering the journal items using the journal's accounts. /!\ The current journal is not part of the applied domain. This is the expected behavior since we only want a logic based on accounts. :param domain: An additional domain to be applied on the account.move.line model. :return: Tuple having balance expressed in journal's currency along with the total number of move lines having the same account as of the journal's default account. ''' self.ensure_one() self.env['account.move.line'].check_access_rights('read') if not self.default_account_id: return 0.0, 0 domain = (domain or []) + [ ('account_id', 'in', tuple(self.default_account_id.ids)), ('display_type', 'not in', ('line_section', 'line_note')), ('parent_state', '!=', 'cancel'), ] query = self.env['account.move.line']._where_calc(domain) tables, where_clause, where_params = query.get_sql() query = ''' SELECT COUNT(account_move_line.id) AS nb_lines, COALESCE(SUM(account_move_line.balance), 0.0), COALESCE(SUM(account_move_line.amount_currency), 0.0) FROM ''' + tables + ''' WHERE ''' + where_clause + ''' ''' company_currency = self.company_id.currency_id journal_currency = self.currency_id if self.currency_id and self.currency_id != company_currency else False self._cr.execute(query, where_params) nb_lines, balance, amount_currency = self._cr.fetchone() return amount_currency if journal_currency else balance, nb_lines def _get_journal_inbound_outstanding_payment_accounts(self): """ :return: A recordset with all the account.account used by this journal for inbound transactions. """ self.ensure_one() account_ids = set() for line in self.inbound_payment_method_line_ids: account_ids.add(line.payment_account_id.id or self.company_id.account_journal_payment_debit_account_id.id) return self.env['account.account'].browse(account_ids) def _get_journal_outbound_outstanding_payment_accounts(self): """ :return: A recordset with all the account.account used by this journal for outbound transactions. """ self.ensure_one() account_ids = set() for line in self.outbound_payment_method_line_ids: account_ids.add(line.payment_account_id.id or self.company_id.account_journal_payment_credit_account_id.id) return self.env['account.account'].browse(account_ids) def _get_journal_outstanding_payments_account_balance(self, domain=None, date=None): ''' Get the outstanding payments balance of the current journal by filtering the journal items using the journal's accounts. :param domain: An additional domain to be applied on the account.move.line model. :param date: The date to be used when performing the currency conversions. :return: The balance expressed in the journal's currency. ''' self.ensure_one() self.env['account.move.line'].check_access_rights('read') conversion_date = date or fields.Date.context_today(self) accounts = self._get_journal_inbound_outstanding_payment_accounts().union(self._get_journal_outbound_outstanding_payment_accounts()) if not accounts: return 0.0, 0 # Allow user managing payments without any statement lines. # In that case, the user manages transactions only using the register payment wizard. if self.default_account_id in accounts: return 0.0, 0 domain = (domain or []) + [ ('account_id', 'in', tuple(accounts.ids)), ('display_type', 'not in', ('line_section', 'line_note')), ('parent_state', '!=', 'cancel'), ('reconciled', '=', False), ('journal_id', '=', self.id), ] query = self.env['account.move.line']._where_calc(domain) tables, where_clause, where_params = query.get_sql() self._cr.execute(''' SELECT COUNT(account_move_line.id) AS nb_lines, account_move_line.currency_id, account.reconcile AS is_account_reconcile, SUM(account_move_line.amount_residual) AS amount_residual, SUM(account_move_line.balance) AS balance, SUM(account_move_line.amount_residual_currency) AS amount_residual_currency, SUM(account_move_line.amount_currency) AS amount_currency FROM ''' + tables + ''' JOIN account_account account ON account.id = account_move_line.account_id WHERE ''' + where_clause + ''' GROUP BY account_move_line.currency_id, account.reconcile ''', where_params) company_currency = self.company_id.currency_id journal_currency = self.currency_id if self.currency_id and self.currency_id != company_currency else False balance_currency = journal_currency or company_currency total_balance = 0.0 nb_lines = 0 for res in self._cr.dictfetchall(): nb_lines += res['nb_lines'] amount_currency = res['amount_residual_currency'] if res['is_account_reconcile'] else res['amount_currency'] balance = res['amount_residual'] if res['is_account_reconcile'] else res['balance'] if res['currency_id'] and journal_currency and res['currency_id'] == journal_currency.id: total_balance += amount_currency elif journal_currency: total_balance += company_currency._convert(balance, balance_currency, self.company_id, conversion_date) else: total_balance += balance return total_balance, nb_lines def _get_last_bank_statement(self, domain=None): ''' Retrieve the last bank statement created using this journal. :param domain: An additional domain to be applied on the account.bank.statement model. :return: An account.bank.statement record or an empty recordset. ''' self.ensure_one() last_statement_domain = (domain or []) + [('journal_id', '=', self.id)] last_statement = self.env['account.bank.statement'].search(last_statement_domain, order='date desc, id desc', limit=1) return last_statement def _get_available_payment_method_lines(self, payment_type): """ This getter is here to allow filtering the payment method lines if needed in other modules. It does NOT serve as a general getter to get the lines. For example, it'll be extended to filter out lines from inactive payment acquirers in the payment module. :param payment_type: either inbound or outbound, used to know which lines to return :return: Either the inbound or outbound payment method lines """ if not self: return self.env['account.payment.method.line'] self.ensure_one() if payment_type == 'inbound': return self.inbound_payment_method_line_ids else: return self.outbound_payment_method_line_ids def _is_payment_method_available(self, payment_method_code): """ Check if the payment method is available on this journal. """ self.ensure_one() pm_info = self.env['account.payment.method']._get_payment_method_information().get(payment_method_code) if not pm_info: return False currency_ids = pm_info.get('currency_ids') country_id = pm_info.get('country_id') domain = pm_info.get('domain', [('type', 'in', ('bank', 'cash'))]) journal_types = next(right for left, operator, right in domain if left == 'type' and operator in ('in', '=')) journal_currency_id = self.currency_id.id or self.company_id.currency_id.id if currency_ids and journal_currency_id not in currency_ids: return False if country_id and self.company_id.account_fiscal_country_id.id != country_id: return False if self.type not in journal_types: return False return True
52.51232
51,147
7,537
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.osv import expression from odoo.exceptions import UserError class AccountPaymentMethod(models.Model): _name = "account.payment.method" _description = "Payment Methods" name = fields.Char(required=True, translate=True) code = fields.Char(required=True) # For internal identification payment_type = fields.Selection(selection=[('inbound', 'Inbound'), ('outbound', 'Outbound')], required=True) _sql_constraints = [ ('name_code_unique', 'unique (code, payment_type)', 'The combination code/payment type already exists!'), ] @api.model_create_multi def create(self, vals_list): payment_methods = super().create(vals_list) methods_info = self._get_payment_method_information() for method in payment_methods: information = methods_info.get(method.code, {}) if information.get('mode') == 'multi': method_domain = method._get_payment_method_domain() journals = self.env['account.journal'].search(method_domain) self.env['account.payment.method.line'].create([{ 'name': method.name, 'payment_method_id': method.id, 'journal_id': journal.id } for journal in journals]) return payment_methods def _get_payment_method_domain(self): """ :return: The domain specyfying which journal can accomodate this payment method. """ self.ensure_one() information = self._get_payment_method_information().get(self.code) currency_ids = information.get('currency_ids') country_id = information.get('country_id') default_domain = [('type', 'in', ('bank', 'cash'))] domains = [information.get('domain', default_domain)] if currency_ids: domains += [expression.OR([ [('currency_id', '=', False), ('company_id.currency_id', 'in', currency_ids)], [('currency_id', 'in', currency_ids)]], )] if country_id: domains += [[('company_id.account_fiscal_country_id', '=', country_id)]] return expression.AND(domains) @api.model def _get_payment_method_information(self): """ Contains details about how to initialize a payment method with the code x. The contained info are: mode: Either unique if we only want one of them at a single time (payment acquirers for example) or multi if we want the method on each journal fitting the domain. domain: The domain defining the eligible journals. currency_id: The id of the currency necessary on the journal (or company) for it to be eligible. country_id: The id of the country needed on the company for it to be eligible. hidden: If set to true, the method will not be automatically added to the journal, and will not be selectable by the user. """ return { 'manual': {'mode': 'multi', 'domain': [('type', 'in', ('bank', 'cash'))]}, } @api.model def _get_sdd_payment_method_code(self): """ TO OVERRIDE This hook will be used to return the list of sdd payment method codes """ return [] class AccountPaymentMethodLine(models.Model): _name = "account.payment.method.line" _description = "Payment Methods" _order = 'sequence, id' # == Business fields == name = fields.Char(compute='_compute_name', readonly=False, store=True) sequence = fields.Integer(default=10) payment_method_id = fields.Many2one( string='Payment Method', comodel_name='account.payment.method', domain="[('payment_type', '=?', payment_type), ('id', 'in', available_payment_method_ids)]", required=True ) payment_account_id = fields.Many2one( comodel_name='account.account', check_company=True, copy=False, ondelete='restrict', domain=lambda self: "[('deprecated', '=', False), " "('company_id', '=', company_id), " "('user_type_id.type', 'not in', ('receivable', 'payable')), " "'|', ('user_type_id', '=', %s), ('id', '=', parent.default_account_id)]" % self.env.ref('account.data_account_type_current_assets').id ) journal_id = fields.Many2one(comodel_name='account.journal', ondelete="cascade") # == Display purpose fields == code = fields.Char(related='payment_method_id.code') payment_type = fields.Selection(related='payment_method_id.payment_type') company_id = fields.Many2one(related='journal_id.company_id') available_payment_method_ids = fields.Many2many(related='journal_id.available_payment_method_ids') @api.depends('payment_method_id.name') def _compute_name(self): for method in self: if not method.name: method.name = method.payment_method_id.name @api.constrains('name') def _ensure_unique_name_for_journal(self): self.flush(['name']) self._cr.execute(''' SELECT apml.name, apm.payment_type FROM account_payment_method_line apml JOIN account_payment_method apm ON apml.payment_method_id = apm.id WHERE apml.journal_id IS NOT NULL GROUP BY apml.name, journal_id, apm.payment_type HAVING count(apml.id) > 1 ''') res = self._cr.fetchall() if res: (name, payment_type) = res[0] raise UserError(_("You can't have two payment method lines of the same payment type (%s) " "and with the same name (%s) on a single journal.", payment_type, name)) def unlink(self): """ Payment method lines which are used in a payment should not be deleted from the database, only the link betweend them and the journals must be broken. """ unused_payment_method_lines = self for line in self: payment_count = self.env['account.payment'].search_count([('payment_method_line_id', '=', line.id)]) if payment_count > 0: unused_payment_method_lines -= line (self - unused_payment_method_lines).write({'journal_id': False}) return super(AccountPaymentMethodLine, unused_payment_method_lines).unlink() @api.model def _auto_toggle_account_to_reconcile(self, account_id): """ Automatically toggle the account to reconcile if allowed. :param account_id: The id of an account.account. """ account = self.env['account.account'].browse(account_id) if not account.reconcile and account.internal_type != 'liquidity' and account.internal_group != 'off_balance': account.reconcile = True @api.model_create_multi def create(self, vals_list): # OVERRIDE for vals in vals_list: if vals.get('payment_account_id'): self._auto_toggle_account_to_reconcile(vals['payment_account_id']) return super().create(vals_list) def write(self, vals): # OVERRIDE if vals.get('payment_account_id'): self._auto_toggle_account_to_reconcile(vals['payment_account_id']) return super().write(vals)
41.412088
7,537
9,183
py
PYTHON
15.0
# -*- coding: utf-8 -*- import base64 from odoo import api, models, fields, _ from odoo.exceptions import UserError from odoo.tools.image import image_data_uri import werkzeug import werkzeug.exceptions class ResPartnerBank(models.Model): _inherit = 'res.partner.bank' def _build_qr_code_vals(self, amount, free_communication, structured_communication, currency, debtor_partner, qr_method=None, silent_errors=True): """ Returns the QR-code vals needed to generate the QR-code report link to pay this account with the given parameters, or None if no QR-code could be generated. :param amount: The amount to be paid :param free_communication: Free communication to add to the payment when generating one with the QR-code :param structured_communication: Structured communication to add to the payment when generating one with the QR-code :param currency: The currency in which amount is expressed :param debtor_partner: The partner to which this QR-code is aimed (so the one who will have to pay) :param qr_method: The QR generation method to be used to make the QR-code. If None, the first one giving a result will be used. :param silent_errors: If true, forbids errors to be raised if some tested QR-code format can't be generated because of incorrect data. """ if not self: return None self.ensure_one() if not currency: raise UserError(_("Currency must always be provided in order to generate a QR-code")) available_qr_methods = self.get_available_qr_methods_in_sequence() candidate_methods = qr_method and [(qr_method, dict(available_qr_methods)[qr_method])] or available_qr_methods for candidate_method, candidate_name in candidate_methods: if self._eligible_for_qr_code(candidate_method, debtor_partner, currency): error_message = self._check_for_qr_code_errors(candidate_method, amount, currency, debtor_partner, free_communication, structured_communication) if not error_message: return { 'qr_method': candidate_method, 'amount': amount, 'currency': currency, 'debtor_partner': debtor_partner, 'free_communication': free_communication, 'structured_communication': structured_communication, } elif not silent_errors: error_header = _("The following error prevented '%s' QR-code to be generated though it was detected as eligible: ", candidate_name) raise UserError( error_header + error_message) return None def build_qr_code_url(self, amount, free_communication, structured_communication, currency, debtor_partner, qr_method=None, silent_errors=True): vals = self._build_qr_code_vals(amount, free_communication, structured_communication, currency, debtor_partner, qr_method, silent_errors) if vals: return self._get_qr_code_url( vals['qr_method'], vals['amount'], vals['currency'], vals['debtor_partner'], vals['free_communication'], vals['structured_communication'], ) return None def build_qr_code_base64(self, amount, free_communication, structured_communication, currency, debtor_partner, qr_method=None, silent_errors=True): vals = self._build_qr_code_vals(amount, free_communication, structured_communication, currency, debtor_partner, qr_method, silent_errors) if vals: return self._get_qr_code_base64( vals['qr_method'], vals['amount'], vals['currency'], vals['debtor_partner'], vals['free_communication'], vals['structured_communication'] ) return None def _get_qr_vals(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication): return None def _get_qr_code_generation_params(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication): return None def _get_qr_code_url(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication): """ Hook for extension, to support the different QR generation methods. This function uses the provided qr_method to try generation a QR-code for the given data. It it succeeds, it returns the report URL to make this QR-code; else None. :param qr_method: The QR generation method to be used to make the QR-code. :param amount: The amount to be paid :param currency: The currency in which amount is expressed :param debtor_partner: The partner to which this QR-code is aimed (so the one who will have to pay) :param free_communication: Free communication to add to the payment when generating one with the QR-code :param structured_communication: Structured communication to add to the payment when generating one with the QR-code """ # pylint: disable=E1137 # (PyLint doesn't get that we are not assigning to None here) params = self._get_qr_code_generation_params(qr_method, amount, currency, debtor_partner, free_communication, structured_communication) if params: params['type'] = params.pop('barcode_type') return '/report/barcode/?' + werkzeug.urls.url_encode(params) return None def _get_qr_code_base64(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication): """ Hook for extension, to support the different QR generation methods. This function uses the provided qr_method to try generation a QR-code for the given data. It it succeeds, it returns QR code in base64 url; else None. :param qr_method: The QR generation method to be used to make the QR-code. :param amount: The amount to be paid :param currency: The currency in which amount is expressed :param debtor_partner: The partner to which this QR-code is aimed (so the one who will have to pay) :param free_communication: Free communication to add to the payment when generating one with the QR-code :param structured_communication: Structured communication to add to the payment when generating one with the QR-code """ # pylint: disable=E1137 # pylint: disable=E1134 # (PyLint doesn't get that we are not assigning to None here) params = self._get_qr_code_generation_params(qr_method, amount, currency, debtor_partner, free_communication, structured_communication) if params: try: barcode = self.env['ir.actions.report'].barcode(**params) except (ValueError, AttributeError): raise werkzeug.exceptions.HTTPException(description='Cannot convert into barcode.') return image_data_uri(base64.b64encode(barcode)) return None @api.model def _get_available_qr_methods(self): """ Returns the QR-code generation methods that are available on this db, in the form of a list of (code, name, sequence) elements, where 'code' is a unique string identifier, 'name' the name to display to the user to designate the method, and 'sequence' is a positive integer indicating the order in which those mehtods need to be checked, to avoid shadowing between them (lower sequence means more prioritary). """ return [] @api.model def get_available_qr_methods_in_sequence(self): """ Same as _get_available_qr_methods but without returning the sequence, and using it directly to order the returned list. """ all_available = self._get_available_qr_methods() all_available.sort(key=lambda x: x[2]) return [(code, name) for (code, name, sequence) in all_available] def _eligible_for_qr_code(self, qr_method, debtor_partner, currency): """ Tells whether or not the criteria to apply QR-generation method qr_method are met for a payment on this account, in the given currency, by debtor_partner. This does not impeach generation errors, it only checks that this type of QR-code *should be* possible to generate. Consistency of the required field needs then to be checked by _check_for_qr_code_errors(). """ return False def _check_for_qr_code_errors(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication): """ Checks the data before generating a QR-code for the specified qr_method (this method must have been checked for eligbility by _eligible_for_qr_code() first). Returns None if no error was found, or a string describing the first error encountered so that it can be reported to the user. """ return None
54.017647
9,183
38,580
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _, tools from odoo.osv import expression from odoo.exceptions import UserError, ValidationError class AccountAccountType(models.Model): _name = "account.account.type" _description = "Account Type" name = fields.Char(string='Account Type', required=True, translate=True) include_initial_balance = fields.Boolean(string="Bring Accounts Balance Forward", help="Used in reports to know if we should consider journal items from the beginning of time instead of from the fiscal year only. Account types that should be reset to zero at each new fiscal year (like expenses, revenue..) should not have this option set.") type = fields.Selection([ ('other', 'Regular'), ('receivable', 'Receivable'), ('payable', 'Payable'), ('liquidity', 'Liquidity'), ], required=True, default='other', help="The 'Internal Type' is used for features available on "\ "different types of accounts: liquidity type is for cash or bank accounts"\ ", payable/receivable is for vendor/customer accounts.") internal_group = fields.Selection([ ('equity', 'Equity'), ('asset', 'Asset'), ('liability', 'Liability'), ('income', 'Income'), ('expense', 'Expense'), ('off_balance', 'Off Balance'), ], string="Internal Group", required=True, help="The 'Internal Group' is used to filter accounts based on the internal group set on the account type.") note = fields.Text(string='Description') class AccountAccount(models.Model): _name = "account.account" _inherit = ['mail.thread'] _description = "Account" _order = "is_off_balance, code, company_id" _check_company_auto = True @api.constrains('internal_type', 'reconcile') def _check_reconcile(self): for account in self: if account.internal_type in ('receivable', 'payable') and account.reconcile == False: raise ValidationError(_('You cannot have a receivable/payable account that is not reconcilable. (account code: %s)', account.code)) @api.constrains('user_type_id') def _check_user_type_id_unique_current_year_earning(self): data_unaffected_earnings = self.env.ref('account.data_unaffected_earnings') result = self.read_group([('user_type_id', '=', data_unaffected_earnings.id)], ['company_id'], ['company_id']) for res in result: if res.get('company_id_count', 0) >= 2: account_unaffected_earnings = self.search([('company_id', '=', res['company_id'][0]), ('user_type_id', '=', data_unaffected_earnings.id)]) raise ValidationError(_('You cannot have more than one account with "Current Year Earnings" as type. (accounts: %s)', [a.code for a in account_unaffected_earnings])) name = fields.Char(string="Account Name", required=True, index=True, tracking=True) currency_id = fields.Many2one('res.currency', string='Account Currency', help="Forces all moves for this account to have this account currency.", tracking=True) code = fields.Char(size=64, required=True, index=True, tracking=True) deprecated = fields.Boolean(index=True, default=False, tracking=True) used = fields.Boolean(compute='_compute_used', search='_search_used') user_type_id = fields.Many2one('account.account.type', string='Type', required=True, tracking=True, help="Account Type is used for information purpose, to generate country-specific legal reports, and set the rules to close a fiscal year and generate opening entries.") internal_type = fields.Selection(related='user_type_id.type', string="Internal Type", store=True, readonly=True) internal_group = fields.Selection(related='user_type_id.internal_group', string="Internal Group", store=True, readonly=True) #has_unreconciled_entries = fields.Boolean(compute='_compute_has_unreconciled_entries', # help="The account has at least one unreconciled debit and credit since last time the invoices & payments matching was performed.") reconcile = fields.Boolean(string='Allow Reconciliation', default=False, tracking=True, help="Check this box if this account allows invoices & payments matching of journal items.") tax_ids = fields.Many2many('account.tax', 'account_account_tax_default_rel', 'account_id', 'tax_id', string='Default Taxes', check_company=True, context={'append_type_to_tax_name': True}) note = fields.Text('Internal Notes', tracking=True) company_id = fields.Many2one('res.company', string='Company', required=True, readonly=True, default=lambda self: self.env.company) tag_ids = fields.Many2many('account.account.tag', 'account_account_account_tag', string='Tags', help="Optional tags you may want to assign for custom reporting") group_id = fields.Many2one('account.group', compute='_compute_account_group', store=True, readonly=True, help="Account prefixes can determine account groups.") root_id = fields.Many2one('account.root', compute='_compute_account_root', store=True) allowed_journal_ids = fields.Many2many('account.journal', string="Allowed Journals", help="Define in which journals this account can be used. If empty, can be used in all journals.") opening_debit = fields.Monetary(string="Opening Debit", compute='_compute_opening_debit_credit', inverse='_set_opening_debit', help="Opening debit value for this account.") opening_credit = fields.Monetary(string="Opening Credit", compute='_compute_opening_debit_credit', inverse='_set_opening_credit', help="Opening credit value for this account.") opening_balance = fields.Monetary(string="Opening Balance", compute='_compute_opening_debit_credit', help="Opening balance value for this account.") is_off_balance = fields.Boolean(compute='_compute_is_off_balance', default=False, store=True, readonly=True) current_balance = fields.Float(compute='_compute_current_balance') related_taxes_amount = fields.Integer(compute='_compute_related_taxes_amount') _sql_constraints = [ ('code_company_uniq', 'unique (code,company_id)', 'The code of the account must be unique per company !') ] @api.constrains('reconcile', 'internal_group', 'tax_ids') def _constrains_reconcile(self): for record in self: if record.internal_group == 'off_balance': if record.reconcile: raise UserError(_('An Off-Balance account can not be reconcilable')) if record.tax_ids: raise UserError(_('An Off-Balance account can not have taxes')) @api.constrains('allowed_journal_ids') def _constrains_allowed_journal_ids(self): self.env['account.move.line'].flush(['account_id', 'journal_id']) self.flush(['allowed_journal_ids']) self._cr.execute(""" SELECT aml.id FROM account_move_line aml WHERE aml.account_id in %s AND EXISTS (SELECT 1 FROM account_account_account_journal_rel WHERE account_account_id = aml.account_id) AND NOT EXISTS (SELECT 1 FROM account_account_account_journal_rel WHERE account_account_id = aml.account_id AND account_journal_id = aml.journal_id) """, [tuple(self.ids)]) ids = self._cr.fetchall() if ids: raise ValidationError(_('Some journal items already exist with this account but in other journals than the allowed ones.')) @api.constrains('currency_id') def _check_journal_consistency(self): ''' Ensure the currency set on the journal is the same as the currency set on the linked accounts. ''' if not self: return self.env['account.account'].flush(['currency_id']) self.env['account.journal'].flush([ 'currency_id', 'default_account_id', 'suspense_account_id', ]) self.env['account.payment.method'].flush(['payment_type']) self.env['account.payment.method.line'].flush(['payment_method_id', 'payment_account_id']) self._cr.execute(''' SELECT account.id, journal.id FROM account_journal journal JOIN res_company company ON company.id = journal.company_id JOIN account_account account ON account.id = journal.default_account_id WHERE journal.currency_id IS NOT NULL AND journal.currency_id != company.currency_id AND account.currency_id != journal.currency_id AND account.id IN %(accounts)s UNION ALL SELECT account.id, journal.id FROM account_journal journal JOIN res_company company ON company.id = journal.company_id JOIN account_payment_method_line apml ON apml.journal_id = journal.id JOIN account_payment_method apm on apm.id = apml.payment_method_id JOIN account_account account ON account.id = COALESCE(apml.payment_account_id, company.account_journal_payment_debit_account_id) WHERE journal.currency_id IS NOT NULL AND journal.currency_id != company.currency_id AND account.currency_id != journal.currency_id AND apm.payment_type = 'inbound' AND account.id IN %(accounts)s UNION ALL SELECT account.id, journal.id FROM account_journal journal JOIN res_company company ON company.id = journal.company_id JOIN account_payment_method_line apml ON apml.journal_id = journal.id JOIN account_payment_method apm on apm.id = apml.payment_method_id JOIN account_account account ON account.id = COALESCE(apml.payment_account_id, company.account_journal_payment_credit_account_id) WHERE journal.currency_id IS NOT NULL AND journal.currency_id != company.currency_id AND account.currency_id != journal.currency_id AND apm.payment_type = 'outbound' AND account.id IN %(accounts)s ''', { 'accounts': tuple(self.ids) }) res = self._cr.fetchone() if res: account = self.env['account.account'].browse(res[0]) journal = self.env['account.journal'].browse(res[1]) raise ValidationError(_( "The foreign currency set on the journal '%(journal)s' and the account '%(account)s' must be the same.", journal=journal.display_name, account=account.display_name )) @api.constrains('company_id') def _check_company_consistency(self): if not self: return self.flush(['company_id']) self._cr.execute(''' SELECT line.id FROM account_move_line line JOIN account_account account ON account.id = line.account_id WHERE line.account_id IN %s AND line.company_id != account.company_id ''', [tuple(self.ids)]) if self._cr.fetchone(): raise UserError(_("You can't change the company of your account since there are some journal items linked to it.")) @api.constrains('user_type_id') def _check_user_type_id_sales_purchase_journal(self): if not self: return self.flush(['user_type_id']) self._cr.execute(''' SELECT account.id FROM account_account account JOIN account_account_type acc_type ON account.user_type_id = acc_type.id JOIN account_journal journal ON journal.default_account_id = account.id WHERE account.id IN %s AND acc_type.type IN ('receivable', 'payable') AND journal.type IN ('sale', 'purchase') LIMIT 1; ''', [tuple(self.ids)]) if self._cr.fetchone(): raise ValidationError(_("The account is already in use in a 'sale' or 'purchase' journal. This means that the account's type couldn't be 'receivable' or 'payable'.")) @api.constrains('reconcile') def _check_used_as_journal_default_debit_credit_account(self): accounts = self.filtered(lambda a: not a.reconcile) if not accounts: return self.flush(['reconcile']) self.env['account.payment.method.line'].flush(['journal_id', 'payment_account_id']) self._cr.execute(''' SELECT journal.id FROM account_journal journal JOIN res_company company on journal.company_id = company.id LEFT JOIN account_payment_method_line apml ON journal.id = apml.journal_id WHERE ( company.account_journal_payment_credit_account_id IN %(accounts)s AND company.account_journal_payment_credit_account_id != journal.default_account_id ) OR ( company.account_journal_payment_debit_account_id in %(accounts)s AND company.account_journal_payment_debit_account_id != journal.default_account_id ) OR ( apml.payment_account_id IN %(accounts)s AND apml.payment_account_id != journal.default_account_id ) ''', { 'accounts': tuple(accounts.ids), }) rows = self._cr.fetchall() if rows: journals = self.env['account.journal'].browse([r[0] for r in rows]) raise ValidationError(_( "This account is configured in %(journal_names)s journal(s) (ids %(journal_ids)s) as payment debit or credit account. This means that this account's type should be reconcilable.", journal_names=journals.mapped('display_name'), journal_ids=journals.ids )) @api.depends('code') def _compute_account_root(self): # this computes the first 2 digits of the account. # This field should have been a char, but the aim is to use it in a side panel view with hierarchy, and it's only supported by many2one fields so far. # So instead, we make it a many2one to a psql view with what we need as records. for record in self: record.root_id = (ord(record.code[0]) * 1000 + ord(record.code[1:2] or '\x00')) if record.code else False @api.depends('code') def _compute_account_group(self): if self.ids: self.env['account.group']._adapt_accounts_for_account_groups(self) else: self.group_id = False def _search_used(self, operator, value): if operator not in ['=', '!='] or not isinstance(value, bool): raise UserError(_('Operation not supported')) if operator != '=': value = not value self._cr.execute(""" SELECT id FROM account_account account WHERE EXISTS (SELECT * FROM account_move_line aml WHERE aml.account_id = account.id LIMIT 1) """) return [('id', 'in' if value else 'not in', [r[0] for r in self._cr.fetchall()])] def _compute_used(self): ids = set(self._search_used('=', True)[0][2]) for record in self: record.used = record.id in ids @api.model def _search_new_account_code(self, company, digits, prefix): for num in range(1, 10000): new_code = str(prefix.ljust(digits - 1, '0')) + str(num) rec = self.search([('code', '=', new_code), ('company_id', '=', company.id)], limit=1) if not rec: return new_code raise UserError(_('Cannot generate an unused account code.')) def _compute_current_balance(self): balances = { read['account_id'][0]: read['balance'] for read in self.env['account.move.line'].read_group( domain=[('account_id', 'in', self.ids), ('parent_state', '=', 'posted')], fields=['balance', 'account_id'], groupby=['account_id'], ) } for record in self: record.current_balance = balances.get(record.id, 0) def _compute_related_taxes_amount(self): for record in self: record.related_taxes_amount = self.env['account.tax'].search_count([ '|', ('invoice_repartition_line_ids.account_id', '=', record.id), ('refund_repartition_line_ids.account_id', '=', record.id), ]) def _compute_opening_debit_credit(self): self.opening_debit = 0 self.opening_credit = 0 self.opening_balance = 0 if not self.ids: return self.env.cr.execute(""" SELECT line.account_id, SUM(line.balance) AS balance, SUM(line.debit) AS debit, SUM(line.credit) AS credit FROM account_move_line line JOIN res_company comp ON comp.id = line.company_id WHERE line.move_id = comp.account_opening_move_id AND line.account_id IN %s GROUP BY line.account_id """, [tuple(self.ids)]) result = {r['account_id']: r for r in self.env.cr.dictfetchall()} for record in self: res = result.get(record.id) or {'debit': 0, 'credit': 0, 'balance': 0} record.opening_debit = res['debit'] record.opening_credit = res['credit'] record.opening_balance = res['balance'] @api.depends('internal_group') def _compute_is_off_balance(self): for account in self: account.is_off_balance = account.internal_group == "off_balance" def _set_opening_debit(self): for record in self: record._set_opening_debit_credit(record.opening_debit, 'debit') def _set_opening_credit(self): for record in self: record._set_opening_debit_credit(record.opening_credit, 'credit') def _set_opening_debit_credit(self, amount, field): """ Generic function called by both opening_debit and opening_credit's inverse function. 'Amount' parameter is the value to be set, and field either 'debit' or 'credit', depending on which one of these two fields got assigned. """ self.company_id.create_op_move_if_non_existant() opening_move = self.company_id.account_opening_move_id if opening_move.state == 'draft': # check whether we should create a new move line or modify an existing one account_op_lines = self.env['account.move.line'].search([('account_id', '=', self.id), ('move_id','=', opening_move.id), (field,'!=', False), (field,'!=', 0.0)]) # 0.0 condition important for import if account_op_lines: op_aml_debit = sum(account_op_lines.mapped('debit')) op_aml_credit = sum(account_op_lines.mapped('credit')) # There might be more than one line on this account if the opening entry was manually edited # If so, we need to merge all those lines into one before modifying its balance opening_move_line = account_op_lines[0] if len(account_op_lines) > 1: merge_write_cmd = [(1, opening_move_line.id, {'debit': op_aml_debit, 'credit': op_aml_credit, 'partner_id': None ,'name': _("Opening balance")})] unlink_write_cmd = [(2, line.id) for line in account_op_lines[1:]] opening_move.write({'line_ids': merge_write_cmd + unlink_write_cmd}) if amount: # modify the line opening_move_line.with_context(check_move_validity=False)[field] = amount else: # delete the line (no need to keep a line with value = 0) opening_move_line.with_context(check_move_validity=False).unlink() elif amount: # create a new line, as none existed before self.env['account.move.line'].with_context(check_move_validity=False).create({ 'name': _('Opening balance'), field: amount, 'move_id': opening_move.id, 'account_id': self.id, }) # Then, we automatically balance the opening move, to make sure it stays valid if not 'import_file' in self.env.context: # When importing a file, avoid recomputing the opening move for each account and do it at the end, for better performances self.company_id._auto_balance_opening_move() @api.model def default_get(self, default_fields): """If we're creating a new account through a many2one, there are chances that we typed the account code instead of its name. In that case, switch both fields values. """ if 'name' not in default_fields and 'code' not in default_fields: return super().default_get(default_fields) default_name = self._context.get('default_name') default_code = self._context.get('default_code') if default_name and not default_code: try: default_code = int(default_name) except ValueError: pass if default_code: default_name = False contextual_self = self.with_context(default_name=default_name, default_code=default_code) return super(AccountAccount, contextual_self).default_get(default_fields) @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): args = args or [] domain = [] if name: if operator in ('=', '!='): domain = ['|', ('code', '=', name.split(' ')[0]), ('name', operator, name)] else: domain = ['|', ('code', '=ilike', name.split(' ')[0] + '%'), ('name', operator, name)] if operator in expression.NEGATIVE_TERM_OPERATORS: domain = ['&', '!'] + domain[1:] return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid) @api.onchange('user_type_id') def _onchange_user_type_id(self): self.reconcile = self.internal_type in ('receivable', 'payable') if self.internal_type == 'liquidity': self.reconcile = False elif self.internal_group == 'off_balance': self.reconcile = False self.tax_ids = False def name_get(self): result = [] for account in self: name = account.code + ' ' + account.name result.append((account.id, name)) return result @api.returns('self', lambda value: value.id) def copy(self, default=None): default = dict(default or {}) if default.get('code', False): return super(AccountAccount, self).copy(default) try: default['code'] = (str(int(self.code) + 10) or '').zfill(len(self.code)) default.setdefault('name', _("%s (copy)") % (self.name or '')) while self.env['account.account'].search([('code', '=', default['code']), ('company_id', '=', default.get('company_id', False) or self.company_id.id)], limit=1): default['code'] = (str(int(default['code']) + 10) or '') default['name'] = _("%s (copy)") % (self.name or '') except ValueError: default['code'] = _("%s (copy)") % (self.code or '') default['name'] = self.name return super(AccountAccount, self).copy(default) @api.model def load(self, fields, data): """ Overridden for better performances when importing a list of account with opening debit/credit. In that case, the auto-balance is postpone until the whole file has been imported. """ rslt = super(AccountAccount, self).load(fields, data) if 'import_file' in self.env.context: companies = self.search([('id', 'in', rslt['ids'])]).mapped('company_id') for company in companies: company._auto_balance_opening_move() return rslt def _toggle_reconcile_to_true(self): '''Toggle the `reconcile´ boolean from False -> True Note that: lines with debit = credit = amount_currency = 0 are set to `reconciled´ = True ''' if not self.ids: return None query = """ UPDATE account_move_line SET reconciled = CASE WHEN debit = 0 AND credit = 0 AND amount_currency = 0 THEN true ELSE false END, amount_residual = (debit-credit), amount_residual_currency = amount_currency WHERE full_reconcile_id IS NULL and account_id IN %s """ self.env.cr.execute(query, [tuple(self.ids)]) def _toggle_reconcile_to_false(self): '''Toggle the `reconcile´ boolean from True -> False Note that it is disallowed if some lines are partially reconciled. ''' if not self.ids: return None partial_lines_count = self.env['account.move.line'].search_count([ ('account_id', 'in', self.ids), ('full_reconcile_id', '=', False), ('|'), ('matched_debit_ids', '!=', False), ('matched_credit_ids', '!=', False), ]) if partial_lines_count > 0: raise UserError(_('You cannot switch an account to prevent the reconciliation ' 'if some partial reconciliations are still pending.')) query = """ UPDATE account_move_line SET amount_residual = 0, amount_residual_currency = 0 WHERE full_reconcile_id IS NULL AND account_id IN %s """ self.env.cr.execute(query, [tuple(self.ids)]) def write(self, vals): # Do not allow changing the company_id when account_move_line already exist if vals.get('company_id', False): move_lines = self.env['account.move.line'].search([('account_id', 'in', self.ids)], limit=1) for account in self: if (account.company_id.id != vals['company_id']) and move_lines: raise UserError(_('You cannot change the owner company of an account that already contains journal items.')) if 'reconcile' in vals: if vals['reconcile']: self.filtered(lambda r: not r.reconcile)._toggle_reconcile_to_true() else: self.filtered(lambda r: r.reconcile)._toggle_reconcile_to_false() if vals.get('currency_id'): for account in self: if self.env['account.move.line'].search_count([('account_id', '=', account.id), ('currency_id', 'not in', (False, vals['currency_id']))]): raise UserError(_('You cannot set a currency on this account as it already has some journal entries having a different foreign currency.')) return super(AccountAccount, self).write(vals) @api.ondelete(at_uninstall=False) def _unlink_except_contains_journal_items(self): if self.env['account.move.line'].search([('account_id', 'in', self.ids)], limit=1): raise UserError(_('You cannot perform this action on an account that contains journal items.')) @api.ondelete(at_uninstall=False) def _unlink_except_account_set_on_customer(self): #Checking whether the account is set as a property to any Partner or not values = ['account.account,%s' % (account_id,) for account_id in self.ids] partner_prop_acc = self.env['ir.property'].sudo().search([('value_reference', 'in', values)], limit=1) if partner_prop_acc: account_name = partner_prop_acc.get_by_record().display_name raise UserError( _('You cannot remove/deactivate the account %s which is set on a customer or vendor.', account_name) ) def action_read_account(self): self.ensure_one() return { 'name': self.display_name, 'type': 'ir.actions.act_window', 'view_type': 'form', 'view_mode': 'form', 'res_model': 'account.account', 'res_id': self.id, } def action_duplicate_accounts(self): for account in self.browse(self.env.context['active_ids']): account.copy() def action_open_related_taxes(self): related_taxes_ids = self.env['account.tax'].search([ '|', ('invoice_repartition_line_ids.account_id', '=', self.id), ('refund_repartition_line_ids.account_id', '=', self.id), ]).ids return { 'type': 'ir.actions.act_window', 'name': _('Taxes'), 'res_model': 'account.tax', 'view_type': 'list', 'view_mode': 'list', 'views': [[False, 'list'], [False, 'form']], 'domain': [('id', 'in', related_taxes_ids)], } class AccountGroup(models.Model): _name = "account.group" _description = 'Account Group' _parent_store = True _order = 'code_prefix_start' parent_id = fields.Many2one('account.group', index=True, ondelete='cascade', readonly=True) parent_path = fields.Char(index=True) name = fields.Char(required=True) code_prefix_start = fields.Char() code_prefix_end = fields.Char() company_id = fields.Many2one('res.company', required=True, readonly=True, default=lambda self: self.env.company) _sql_constraints = [ ( 'check_length_prefix', 'CHECK(char_length(COALESCE(code_prefix_start, \'\')) = char_length(COALESCE(code_prefix_end, \'\')))', 'The length of the starting and the ending code prefix must be the same' ), ] @api.onchange('code_prefix_start') def _onchange_code_prefix_start(self): if not self.code_prefix_end or self.code_prefix_end < self.code_prefix_start: self.code_prefix_end = self.code_prefix_start @api.onchange('code_prefix_end') def _onchange_code_prefix_end(self): if not self.code_prefix_start or self.code_prefix_start > self.code_prefix_end: self.code_prefix_start = self.code_prefix_end def name_get(self): result = [] for group in self: prefix = group.code_prefix_start and str(group.code_prefix_start) if prefix and group.code_prefix_end != group.code_prefix_start: prefix += '-' + str(group.code_prefix_end) name = (prefix and (prefix + ' ') or '') + group.name result.append((group.id, name)) return result @api.model def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None): args = args or [] if operator == 'ilike' and not (name or '').strip(): domain = [] else: criteria_operator = ['|'] if operator not in expression.NEGATIVE_TERM_OPERATORS else ['&', '!'] domain = criteria_operator + [('code_prefix_start', '=ilike', name + '%'), ('name', operator, name)] return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid) @api.constrains('code_prefix_start', 'code_prefix_end') def _constraint_prefix_overlap(self): self.env['account.group'].flush() query = """ SELECT other.id FROM account_group this JOIN account_group other ON char_length(other.code_prefix_start) = char_length(this.code_prefix_start) AND other.id != this.id AND other.company_id = this.company_id AND ( other.code_prefix_start <= this.code_prefix_start AND this.code_prefix_start <= other.code_prefix_end OR other.code_prefix_start >= this.code_prefix_start AND this.code_prefix_end >= other.code_prefix_start ) WHERE this.id IN %(ids)s """ self.env.cr.execute(query, {'ids': tuple(self.ids)}) res = self.env.cr.fetchall() if res: raise ValidationError(_('Account Groups with the same granularity can\'t overlap')) @api.model_create_multi def create(self, vals_list): for vals in vals_list: if 'code_prefix_start' in vals and not vals.get('code_prefix_end'): vals['code_prefix_end'] = vals['code_prefix_start'] res_ids = super(AccountGroup, self).create(vals_list) res_ids._adapt_accounts_for_account_groups() res_ids._adapt_parent_account_group() return res_ids def write(self, vals): res = super(AccountGroup, self).write(vals) if 'code_prefix_start' in vals or 'code_prefix_end' in vals: self._adapt_accounts_for_account_groups() self._adapt_parent_account_group() return res def unlink(self): for record in self: account_ids = self.env['account.account'].search([('group_id', '=', record.id)]) account_ids.write({'group_id': record.parent_id.id}) children_ids = self.env['account.group'].search([('parent_id', '=', record.id)]) children_ids.write({'parent_id': record.parent_id.id}) super(AccountGroup, self).unlink() def _adapt_accounts_for_account_groups(self, account_ids=None): """Ensure consistency between accounts and account groups. Find and set the most specific group matching the code of the account. The most specific is the one with the longest prefixes and with the starting prefix being smaller than the account code and the ending prefix being greater. """ company_ids = account_ids.company_id.ids if account_ids else self.company_id.ids account_ids = account_ids.ids if account_ids else [] if not company_ids and not account_ids: return self.env['account.group'].flush(self.env['account.group']._fields) self.env['account.account'].flush(self.env['account.account']._fields) account_where_clause = '' where_params = [tuple(company_ids)] if account_ids: account_where_clause = 'AND account.id IN %s' where_params.append(tuple(account_ids)) self._cr.execute(f''' WITH candidates_account_groups AS ( SELECT account.id AS account_id, ARRAY_AGG(agroup.id ORDER BY char_length(agroup.code_prefix_start) DESC, agroup.id) AS group_ids FROM account_account account LEFT JOIN account_group agroup ON agroup.code_prefix_start <= LEFT(account.code, char_length(agroup.code_prefix_start)) AND agroup.code_prefix_end >= LEFT(account.code, char_length(agroup.code_prefix_end)) AND agroup.company_id = account.company_id WHERE account.company_id IN %s {account_where_clause} GROUP BY account.id ) UPDATE account_account SET group_id = rel.group_ids[1] FROM candidates_account_groups rel WHERE account_account.id = rel.account_id ''', where_params) self.env['account.account'].invalidate_cache(fnames=['group_id']) def _adapt_parent_account_group(self): """Ensure consistency of the hierarchy of account groups. Find and set the most specific parent for each group. The most specific is the one with the longest prefixes and with the starting prefix being smaller than the child prefixes and the ending prefix being greater. """ if not self: return self.env['account.group'].flush(self.env['account.group']._fields) query = """ WITH relation AS ( SELECT DISTINCT FIRST_VALUE(parent.id) OVER (PARTITION BY child.id ORDER BY child.id, char_length(parent.code_prefix_start) DESC) AS parent_id, child.id AS child_id FROM account_group parent JOIN account_group child ON char_length(parent.code_prefix_start) < char_length(child.code_prefix_start) AND parent.code_prefix_start <= LEFT(child.code_prefix_start, char_length(parent.code_prefix_start)) AND parent.code_prefix_end >= LEFT(child.code_prefix_end, char_length(parent.code_prefix_end)) AND parent.id != child.id AND parent.company_id = child.company_id WHERE child.company_id IN %(company_ids)s ) UPDATE account_group child SET parent_id = relation.parent_id FROM relation WHERE child.id = relation.child_id; """ self.env.cr.execute(query, {'company_ids': tuple(self.company_id.ids)}) self.env['account.group'].invalidate_cache(fnames=['parent_id']) self.env['account.group'].search([('company_id', 'in', self.company_id.ids)])._parent_store_update() class AccountRoot(models.Model): _name = 'account.root' _description = 'Account codes first 2 digits' _auto = False name = fields.Char() parent_id = fields.Many2one('account.root') company_id = fields.Many2one('res.company') def init(self): tools.drop_view_if_exists(self.env.cr, self._table) self.env.cr.execute(''' CREATE OR REPLACE VIEW %s AS ( SELECT DISTINCT ASCII(code) * 1000 + ASCII(SUBSTRING(code,2,1)) AS id, LEFT(code,2) AS name, ASCII(code) AS parent_id, company_id FROM account_account WHERE code IS NOT NULL UNION ALL SELECT DISTINCT ASCII(code) AS id, LEFT(code,1) AS name, NULL::int AS parent_id, company_id FROM account_account WHERE code IS NOT NULL )''' % (self._table,) )
48.342105
38,577
626
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo.exceptions import ValidationError from odoo import api, fields, models, _ class ResPartnerBank(models.Model): _inherit = "res.partner.bank" journal_id = fields.One2many('account.journal', 'bank_account_id', domain=[('type', '=', 'bank')], string='Account Journal', readonly=True, help="The accounting journal corresponding to this bank account.") @api.constrains('journal_id') def _check_journal_id(self): for bank in self: if len(bank.journal_id) > 1: raise ValidationError(_('A bank account can belong to only one journal.'))
39.125
626
1,438
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import models class MailThread(models.AbstractModel): _inherit = 'mail.thread' def _message_post_process_attachments(self, attachments, attachment_ids, message_values): """ This method extension ensures that, when using the "Send & Print" feature, if the user adds an attachment, the latter will be linked to the record. """ record = self.env.context.get('attached_to') # link mail.compose.message attachments to attached_to if record and record._name == 'account.move': message_values['model'] = record._name message_values['res_id'] = record.id res = super()._message_post_process_attachments(attachments, attachment_ids, message_values) # link account.invoice.send attachments to attached_to model = message_values['model'] res_id = message_values['res_id'] att_ids = [att[1] for att in res.get('attachment_ids') or []] if att_ids and model == 'account.move': filtered_attachment_ids = self.env['ir.attachment'].sudo().browse(att_ids).filtered( lambda a: a.res_model in ('account.invoice.send',) and a.create_uid.id == self._uid) if filtered_attachment_ids: filtered_attachment_ids.write({'res_model': model, 'res_id': res_id}) return res
53.259259
1,438
50,078
py
PYTHON
15.0
# -*- coding: utf-8 -*- from lxml import etree from odoo import models, fields, api, Command, _ from odoo.exceptions import UserError, ValidationError class AccountPayment(models.Model): _name = "account.payment" _inherits = {'account.move': 'move_id'} _inherit = ['mail.thread', 'mail.activity.mixin'] _description = "Payments" _order = "date desc, name desc" _check_company_auto = True def _get_default_journal(self): ''' Retrieve the default journal for the account.payment. /!\ This method will not override the method in 'account.move' because the ORM doesn't allow overriding methods using _inherits. Then, this method will be called manually in 'create' and 'new'. :return: An account.journal record. ''' return self.env['account.move']._search_default_journal(('bank', 'cash')) # == Business fields == move_id = fields.Many2one( comodel_name='account.move', string='Journal Entry', required=True, readonly=True, ondelete='cascade', check_company=True) is_reconciled = fields.Boolean(string="Is Reconciled", store=True, compute='_compute_reconciliation_status', help="Technical field indicating if the payment is already reconciled.") is_matched = fields.Boolean(string="Is Matched With a Bank Statement", store=True, compute='_compute_reconciliation_status', help="Technical field indicating if the payment has been matched with a statement line.") available_partner_bank_ids = fields.Many2many( comodel_name='res.partner.bank', compute='_compute_available_partner_bank_ids', ) partner_bank_id = fields.Many2one('res.partner.bank', string="Recipient Bank Account", readonly=False, store=True, tracking=True, compute='_compute_partner_bank_id', domain="[('id', 'in', available_partner_bank_ids)]", check_company=True) is_internal_transfer = fields.Boolean(string="Internal Transfer", readonly=False, store=True, tracking=True, compute="_compute_is_internal_transfer") qr_code = fields.Char(string="QR Code", compute="_compute_qr_code", help="QR-code report URL to use to generate the QR-code to scan with a banking app to perform this payment.") paired_internal_transfer_payment_id = fields.Many2one('account.payment', help="When an internal transfer is posted, a paired payment is created. " "They are cross referenced trough this field", copy=False) # == Payment methods fields == payment_method_line_id = fields.Many2one('account.payment.method.line', string='Payment Method', readonly=False, store=True, copy=False, compute='_compute_payment_method_line_id', domain="[('id', 'in', available_payment_method_line_ids)]", help="Manual: Pay or Get paid by any method outside of Odoo.\n" "Payment Acquirers: Each payment acquirer has its own Payment Method. Request a transaction on/to a card thanks to a payment token saved by the partner when buying or subscribing online.\n" "Check: Pay bills by check and print it from Odoo.\n" "Batch Deposit: Collect several customer checks at once generating and submitting a batch deposit to your bank. Module account_batch_payment is necessary.\n" "SEPA Credit Transfer: Pay in the SEPA zone by submitting a SEPA Credit Transfer file to your bank. Module account_sepa is necessary.\n" "SEPA Direct Debit: Get paid in the SEPA zone thanks to a mandate your partner will have granted to you. Module account_sepa is necessary.\n") available_payment_method_line_ids = fields.Many2many('account.payment.method.line', compute='_compute_payment_method_line_fields') hide_payment_method_line = fields.Boolean( compute='_compute_payment_method_line_fields', help="Technical field used to hide the payment method if the selected journal has only one available which is 'manual'") payment_method_id = fields.Many2one( related='payment_method_line_id.payment_method_id', string="Method", tracking=True, store=True ) # == Synchronized fields with the account.move.lines == amount = fields.Monetary(currency_field='currency_id') payment_type = fields.Selection([ ('outbound', 'Send'), ('inbound', 'Receive'), ], string='Payment Type', default='inbound', required=True, tracking=True) partner_type = fields.Selection([ ('customer', 'Customer'), ('supplier', 'Vendor'), ], default='customer', tracking=True, required=True) payment_reference = fields.Char(string="Payment Reference", copy=False, tracking=True, help="Reference of the document used to issue this payment. Eg. check number, file name, etc.") currency_id = fields.Many2one('res.currency', string='Currency', store=True, readonly=False, compute='_compute_currency_id', help="The payment's currency.") partner_id = fields.Many2one( comodel_name='res.partner', string="Customer/Vendor", store=True, readonly=False, ondelete='restrict', compute='_compute_partner_id', domain="['|', ('parent_id','=', False), ('is_company','=', True)]", tracking=True, check_company=True) outstanding_account_id = fields.Many2one( comodel_name='account.account', string="Outstanding Account", store=True, compute='_compute_outstanding_account_id', check_company=True) destination_account_id = fields.Many2one( comodel_name='account.account', string='Destination Account', store=True, readonly=False, compute='_compute_destination_account_id', domain="[('user_type_id.type', 'in', ('receivable', 'payable')), ('company_id', '=', company_id)]", check_company=True) destination_journal_id = fields.Many2one( comodel_name='account.journal', string='Destination Journal', domain="[('type', 'in', ('bank','cash')), ('company_id', '=', company_id), ('id', '!=', journal_id)]", check_company=True, ) # == Stat buttons == reconciled_invoice_ids = fields.Many2many('account.move', string="Reconciled Invoices", compute='_compute_stat_buttons_from_reconciliation', help="Invoices whose journal items have been reconciled with these payments.") reconciled_invoices_count = fields.Integer(string="# Reconciled Invoices", compute="_compute_stat_buttons_from_reconciliation") reconciled_invoices_type = fields.Selection( [('credit_note', 'Credit Note'), ('invoice', 'Invoice')], compute='_compute_stat_buttons_from_reconciliation', help="Technical field used to determine label 'invoice' or 'credit note' in view") reconciled_bill_ids = fields.Many2many('account.move', string="Reconciled Bills", compute='_compute_stat_buttons_from_reconciliation', help="Invoices whose journal items have been reconciled with these payments.") reconciled_bills_count = fields.Integer(string="# Reconciled Bills", compute="_compute_stat_buttons_from_reconciliation") reconciled_statement_ids = fields.Many2many('account.bank.statement', string="Reconciled Statements", compute='_compute_stat_buttons_from_reconciliation', help="Statements matched to this payment") reconciled_statements_count = fields.Integer(string="# Reconciled Statements", compute="_compute_stat_buttons_from_reconciliation") # == Display purpose fields == payment_method_code = fields.Char( related='payment_method_line_id.code', help="Technical field used to adapt the interface to the payment type selected.") show_partner_bank_account = fields.Boolean( compute='_compute_show_require_partner_bank', help="Technical field used to know whether the field `partner_bank_id` needs to be displayed or not in the payments form views") require_partner_bank_account = fields.Boolean( compute='_compute_show_require_partner_bank', help="Technical field used to know whether the field `partner_bank_id` needs to be required or not in the payments form views") country_code = fields.Char(related='company_id.account_fiscal_country_id.code') amount_signed = fields.Monetary( currency_field='currency_id', compute='_compute_amount_signed', tracking=True, help='Negative value of amount field if payment_type is outbound') amount_company_currency_signed = fields.Monetary( currency_field='company_currency_id', compute='_compute_amount_company_currency_signed') _sql_constraints = [ ( 'check_amount_not_negative', 'CHECK(amount >= 0.0)', "The payment amount cannot be negative.", ), ] # ------------------------------------------------------------------------- # HELPERS # ------------------------------------------------------------------------- def _seek_for_lines(self): ''' Helper used to dispatch the journal items between: - The lines using the temporary liquidity account. - The lines using the counterpart account. - The lines being the write-off lines. :return: (liquidity_lines, counterpart_lines, writeoff_lines) ''' self.ensure_one() liquidity_lines = self.env['account.move.line'] counterpart_lines = self.env['account.move.line'] writeoff_lines = self.env['account.move.line'] for line in self.move_id.line_ids: if line.account_id in self._get_valid_liquidity_accounts(): liquidity_lines += line elif line.account_id.internal_type in ('receivable', 'payable') or line.partner_id == line.company_id.partner_id: counterpart_lines += line else: writeoff_lines += line return liquidity_lines, counterpart_lines, writeoff_lines def _get_valid_liquidity_accounts(self): return ( self.journal_id.default_account_id, self.payment_method_line_id.payment_account_id, self.journal_id.company_id.account_journal_payment_debit_account_id, self.journal_id.company_id.account_journal_payment_credit_account_id, self.journal_id.inbound_payment_method_line_ids.payment_account_id, self.journal_id.outbound_payment_method_line_ids.payment_account_id, ) def _prepare_payment_display_name(self): ''' Hook method for inherit When you want to set a new name for payment, you can extend this method ''' return { 'outbound-customer': _("Customer Reimbursement"), 'inbound-customer': _("Customer Payment"), 'outbound-supplier': _("Vendor Payment"), 'inbound-supplier': _("Vendor Reimbursement"), } def _prepare_move_line_default_vals(self, write_off_line_vals=None): ''' Prepare the dictionary to create the default account.move.lines for the current payment. :param write_off_line_vals: Optional dictionary to create a write-off account.move.line easily containing: * amount: The amount to be added to the counterpart amount. * name: The label to set on the line. * account_id: The account on which create the write-off. :return: A list of python dictionary to be passed to the account.move.line's 'create' method. ''' self.ensure_one() write_off_line_vals = write_off_line_vals or {} if not self.outstanding_account_id: raise UserError(_( "You can't create a new payment without an outstanding payments/receipts account set either on the company or the %s payment method in the %s journal.", self.payment_method_line_id.name, self.journal_id.display_name)) # Compute amounts. write_off_amount_currency = write_off_line_vals.get('amount', 0.0) if self.payment_type == 'inbound': # Receive money. liquidity_amount_currency = self.amount elif self.payment_type == 'outbound': # Send money. liquidity_amount_currency = -self.amount write_off_amount_currency *= -1 else: liquidity_amount_currency = write_off_amount_currency = 0.0 write_off_balance = self.currency_id._convert( write_off_amount_currency, self.company_id.currency_id, self.company_id, self.date, ) liquidity_balance = self.currency_id._convert( liquidity_amount_currency, self.company_id.currency_id, self.company_id, self.date, ) counterpart_amount_currency = -liquidity_amount_currency - write_off_amount_currency counterpart_balance = -liquidity_balance - write_off_balance currency_id = self.currency_id.id if self.is_internal_transfer: if self.payment_type == 'inbound': liquidity_line_name = _('Transfer to %s', self.journal_id.name) else: # payment.payment_type == 'outbound': liquidity_line_name = _('Transfer from %s', self.journal_id.name) else: liquidity_line_name = self.payment_reference # Compute a default label to set on the journal items. payment_display_name = self._prepare_payment_display_name() default_line_name = self.env['account.move.line']._get_default_line_name( _("Internal Transfer") if self.is_internal_transfer else payment_display_name['%s-%s' % (self.payment_type, self.partner_type)], self.amount, self.currency_id, self.date, partner=self.partner_id, ) line_vals_list = [ # Liquidity line. { 'name': liquidity_line_name or default_line_name, 'date_maturity': self.date, 'amount_currency': liquidity_amount_currency, 'currency_id': currency_id, 'debit': liquidity_balance if liquidity_balance > 0.0 else 0.0, 'credit': -liquidity_balance if liquidity_balance < 0.0 else 0.0, 'partner_id': self.partner_id.id, 'account_id': self.outstanding_account_id.id, }, # Receivable / Payable. { 'name': self.payment_reference or default_line_name, 'date_maturity': self.date, 'amount_currency': counterpart_amount_currency, 'currency_id': currency_id, 'debit': counterpart_balance if counterpart_balance > 0.0 else 0.0, 'credit': -counterpart_balance if counterpart_balance < 0.0 else 0.0, 'partner_id': self.partner_id.id, 'account_id': self.destination_account_id.id, }, ] if not self.currency_id.is_zero(write_off_amount_currency): # Write-off line. line_vals_list.append({ 'name': write_off_line_vals.get('name') or default_line_name, 'amount_currency': write_off_amount_currency, 'currency_id': currency_id, 'debit': write_off_balance if write_off_balance > 0.0 else 0.0, 'credit': -write_off_balance if write_off_balance < 0.0 else 0.0, 'partner_id': self.partner_id.id, 'account_id': write_off_line_vals.get('account_id'), }) return line_vals_list # ------------------------------------------------------------------------- # COMPUTE METHODS # ------------------------------------------------------------------------- @api.depends('move_id.line_ids.amount_residual', 'move_id.line_ids.amount_residual_currency', 'move_id.line_ids.account_id') def _compute_reconciliation_status(self): ''' Compute the field indicating if the payments are already reconciled with something. This field is used for display purpose (e.g. display the 'reconcile' button redirecting to the reconciliation widget). ''' for pay in self: liquidity_lines, counterpart_lines, writeoff_lines = pay._seek_for_lines() if not pay.currency_id or not pay.id: pay.is_reconciled = False pay.is_matched = False elif pay.currency_id.is_zero(pay.amount): pay.is_reconciled = True pay.is_matched = True else: residual_field = 'amount_residual' if pay.currency_id == pay.company_id.currency_id else 'amount_residual_currency' if pay.journal_id.default_account_id and pay.journal_id.default_account_id in liquidity_lines.account_id: # Allow user managing payments without any statement lines by using the bank account directly. # In that case, the user manages transactions only using the register payment wizard. pay.is_matched = True else: pay.is_matched = pay.currency_id.is_zero(sum(liquidity_lines.mapped(residual_field))) reconcile_lines = (counterpart_lines + writeoff_lines).filtered(lambda line: line.account_id.reconcile) pay.is_reconciled = pay.currency_id.is_zero(sum(reconcile_lines.mapped(residual_field))) @api.model def _get_method_codes_using_bank_account(self): return ['manual'] @api.model def _get_method_codes_needing_bank_account(self): return [] @api.depends('payment_method_code') def _compute_show_require_partner_bank(self): """ Computes if the destination bank account must be displayed in the payment form view. By default, it won't be displayed but some modules might change that, depending on the payment type.""" for payment in self: payment.show_partner_bank_account = payment.payment_method_code in self._get_method_codes_using_bank_account() payment.require_partner_bank_account = payment.state == 'draft' and payment.payment_method_code in self._get_method_codes_needing_bank_account() @api.depends('amount_total_signed', 'payment_type') def _compute_amount_company_currency_signed(self): for payment in self: liquidity_lines = payment._seek_for_lines()[0] payment.amount_company_currency_signed = sum(liquidity_lines.mapped('balance')) @api.depends('amount', 'payment_type') def _compute_amount_signed(self): for payment in self: if payment.payment_type == 'outbound': payment.amount_signed = -payment.amount else: payment.amount_signed = payment.amount @api.depends('partner_id', 'company_id', 'payment_type', 'destination_journal_id', 'is_internal_transfer') def _compute_available_partner_bank_ids(self): for pay in self: if pay.payment_type == 'inbound': pay.available_partner_bank_ids = pay.journal_id.bank_account_id elif pay.is_internal_transfer: pay.available_partner_bank_ids = pay.destination_journal_id.bank_account_id else: pay.available_partner_bank_ids = pay.partner_id.bank_ids\ .filtered(lambda x: x.company_id.id in (False, pay.company_id.id))._origin @api.depends('available_partner_bank_ids', 'journal_id') def _compute_partner_bank_id(self): ''' The default partner_bank_id will be the first available on the partner. ''' for pay in self: pay.partner_bank_id = pay.available_partner_bank_ids[:1]._origin @api.depends('partner_id', 'journal_id', 'destination_journal_id') def _compute_is_internal_transfer(self): for payment in self: payment.is_internal_transfer = payment.partner_id \ and payment.partner_id == payment.journal_id.company_id.partner_id \ and payment.destination_journal_id @api.depends('available_payment_method_line_ids') def _compute_payment_method_line_id(self): ''' Compute the 'payment_method_line_id' field. This field is not computed in '_compute_payment_method_line_fields' because it's a stored editable one. ''' for pay in self: available_payment_method_lines = pay.available_payment_method_line_ids # Select the first available one by default. if pay.payment_method_line_id in available_payment_method_lines: pay.payment_method_line_id = pay.payment_method_line_id elif available_payment_method_lines: pay.payment_method_line_id = available_payment_method_lines[0]._origin else: pay.payment_method_line_id = False @api.depends('payment_type', 'journal_id', 'currency_id') def _compute_payment_method_line_fields(self): for pay in self: pay.available_payment_method_line_ids = pay.journal_id._get_available_payment_method_lines(pay.payment_type) to_exclude = pay._get_payment_method_codes_to_exclude() if to_exclude: pay.available_payment_method_line_ids = pay.available_payment_method_line_ids.filtered(lambda x: x.code not in to_exclude) if pay.payment_method_line_id.id not in pay.available_payment_method_line_ids.ids: # In some cases, we could be linked to a payment method line that has been unlinked from the journal. # In such cases, we want to show it on the payment. pay.hide_payment_method_line = False else: pay.hide_payment_method_line = len(pay.available_payment_method_line_ids) == 1 and pay.available_payment_method_line_ids.code == 'manual' def _get_payment_method_codes_to_exclude(self): # can be overriden to exclude payment methods based on the payment characteristics self.ensure_one() return [] @api.depends('journal_id') def _compute_currency_id(self): for pay in self: pay.currency_id = pay.journal_id.currency_id or pay.journal_id.company_id.currency_id @api.depends('is_internal_transfer') def _compute_partner_id(self): for pay in self: if pay.is_internal_transfer: pay.partner_id = pay.journal_id.company_id.partner_id elif pay.partner_id == pay.journal_id.company_id.partner_id: pay.partner_id = False else: pay.partner_id = pay.partner_id @api.depends('journal_id', 'payment_type', 'payment_method_line_id') def _compute_outstanding_account_id(self): for pay in self: if pay.payment_type == 'inbound': pay.outstanding_account_id = (pay.payment_method_line_id.payment_account_id or pay.journal_id.company_id.account_journal_payment_debit_account_id) elif pay.payment_type == 'outbound': pay.outstanding_account_id = (pay.payment_method_line_id.payment_account_id or pay.journal_id.company_id.account_journal_payment_credit_account_id) else: pay.outstanding_account_id = False @api.depends('journal_id', 'partner_id', 'partner_type', 'is_internal_transfer') def _compute_destination_account_id(self): self.destination_account_id = False for pay in self: if pay.is_internal_transfer: pay.destination_account_id = pay.journal_id.company_id.transfer_account_id elif pay.partner_type == 'customer': # Receive money from invoice or send money to refund it. if pay.partner_id: pay.destination_account_id = pay.partner_id.with_company(pay.company_id).property_account_receivable_id else: pay.destination_account_id = self.env['account.account'].search([ ('company_id', '=', pay.company_id.id), ('internal_type', '=', 'receivable'), ('deprecated', '=', False), ], limit=1) elif pay.partner_type == 'supplier': # Send money to pay a bill or receive money to refund it. if pay.partner_id: pay.destination_account_id = pay.partner_id.with_company(pay.company_id).property_account_payable_id else: pay.destination_account_id = self.env['account.account'].search([ ('company_id', '=', pay.company_id.id), ('internal_type', '=', 'payable'), ('deprecated', '=', False), ], limit=1) @api.depends('partner_bank_id', 'amount', 'ref', 'currency_id', 'journal_id', 'move_id.state', 'payment_method_line_id', 'payment_type') def _compute_qr_code(self): for pay in self: if pay.state in ('draft', 'posted') \ and pay.partner_bank_id \ and pay.payment_method_line_id.code == 'manual' \ and pay.payment_type == 'outbound' \ and pay.currency_id: if pay.partner_bank_id: qr_code = pay.partner_bank_id.build_qr_code_base64(pay.amount, pay.ref, pay.ref, pay.currency_id, pay.partner_id) else: qr_code = None if qr_code: pay.qr_code = ''' <br/> <img class="border border-dark rounded" src="{qr_code}"/> <br/> <strong class="text-center">{txt}</strong> '''.format(txt = _('Scan me with your banking app.'), qr_code = qr_code) continue pay.qr_code = None @api.depends('move_id.line_ids.matched_debit_ids', 'move_id.line_ids.matched_credit_ids') def _compute_stat_buttons_from_reconciliation(self): ''' Retrieve the invoices reconciled to the payments through the reconciliation (account.partial.reconcile). ''' stored_payments = self.filtered('id') if not stored_payments: self.reconciled_invoice_ids = False self.reconciled_invoices_count = 0 self.reconciled_invoices_type = '' self.reconciled_bill_ids = False self.reconciled_bills_count = 0 self.reconciled_statement_ids = False self.reconciled_statements_count = 0 return self.env['account.payment'].flush(fnames=['move_id', 'outstanding_account_id']) self.env['account.move'].flush(fnames=['move_type', 'payment_id', 'statement_line_id']) self.env['account.move.line'].flush(fnames=['move_id', 'account_id', 'statement_line_id']) self.env['account.partial.reconcile'].flush(fnames=['debit_move_id', 'credit_move_id']) self._cr.execute(''' SELECT payment.id, ARRAY_AGG(DISTINCT invoice.id) AS invoice_ids, invoice.move_type FROM account_payment payment JOIN account_move move ON move.id = payment.move_id JOIN account_move_line line ON line.move_id = move.id JOIN account_partial_reconcile part ON part.debit_move_id = line.id OR part.credit_move_id = line.id JOIN account_move_line counterpart_line ON part.debit_move_id = counterpart_line.id OR part.credit_move_id = counterpart_line.id JOIN account_move invoice ON invoice.id = counterpart_line.move_id JOIN account_account account ON account.id = line.account_id WHERE account.internal_type IN ('receivable', 'payable') AND payment.id IN %(payment_ids)s AND line.id != counterpart_line.id AND invoice.move_type in ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt') GROUP BY payment.id, invoice.move_type ''', { 'payment_ids': tuple(stored_payments.ids) }) query_res = self._cr.dictfetchall() self.reconciled_invoice_ids = self.reconciled_invoices_count = False self.reconciled_bill_ids = self.reconciled_bills_count = False for res in query_res: pay = self.browse(res['id']) if res['move_type'] in self.env['account.move'].get_sale_types(True): pay.reconciled_invoice_ids += self.env['account.move'].browse(res.get('invoice_ids', [])) pay.reconciled_invoices_count = len(res.get('invoice_ids', [])) else: pay.reconciled_bill_ids += self.env['account.move'].browse(res.get('invoice_ids', [])) pay.reconciled_bills_count = len(res.get('invoice_ids', [])) self._cr.execute(''' SELECT payment.id, ARRAY_AGG(DISTINCT counterpart_line.statement_id) AS statement_ids FROM account_payment payment JOIN account_move move ON move.id = payment.move_id JOIN account_move_line line ON line.move_id = move.id JOIN account_account account ON account.id = line.account_id JOIN account_partial_reconcile part ON part.debit_move_id = line.id OR part.credit_move_id = line.id JOIN account_move_line counterpart_line ON part.debit_move_id = counterpart_line.id OR part.credit_move_id = counterpart_line.id WHERE account.id = payment.outstanding_account_id AND payment.id IN %(payment_ids)s AND line.id != counterpart_line.id AND counterpart_line.statement_id IS NOT NULL GROUP BY payment.id ''', { 'payment_ids': tuple(stored_payments.ids) }) query_res = dict((payment_id, statement_ids) for payment_id, statement_ids in self._cr.fetchall()) for pay in self: statement_ids = query_res.get(pay.id, []) pay.reconciled_statement_ids = [(6, 0, statement_ids)] pay.reconciled_statements_count = len(statement_ids) if len(pay.reconciled_invoice_ids.mapped('move_type')) == 1 and pay.reconciled_invoice_ids[0].move_type == 'out_refund': pay.reconciled_invoices_type = 'credit_note' else: pay.reconciled_invoices_type = 'invoice' # ------------------------------------------------------------------------- # ONCHANGE METHODS # ------------------------------------------------------------------------- @api.onchange('posted_before', 'state', 'journal_id', 'date') def _onchange_journal_date(self): # Before the record is created, the move_id doesn't exist yet, and the name will not be # recomputed correctly if we change the journal or the date, leading to inconsitencies if not self.move_id: self.name = False @api.onchange('journal_id') def _onchange_journal(self): self.move_id._onchange_journal() # ------------------------------------------------------------------------- # CONSTRAINT METHODS # ------------------------------------------------------------------------- @api.constrains('payment_method_line_id') def _check_payment_method_line_id(self): ''' Ensure the 'payment_method_line_id' field is not null. Can't be done using the regular 'required=True' because the field is a computed editable stored one. ''' for pay in self: if not pay.payment_method_line_id: raise ValidationError(_("Please define a payment method line on your payment.")) # ------------------------------------------------------------------------- # LOW-LEVEL METHODS # ------------------------------------------------------------------------- @api.model def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False): # OVERRIDE to add the 'available_partner_bank_ids' field dynamically inside the view. # TO BE REMOVED IN MASTER res = super().fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) if view_type == 'form': form_view_id = self.env['ir.model.data']._xmlid_to_res_id('account.view_account_payment_form') if res.get('view_id') == form_view_id: tree = etree.fromstring(res['arch']) if len(tree.xpath("//field[@name='available_partner_bank_ids']")) == 0: # Don't force people to update the account module. form_view = self.env.ref('account.view_account_payment_form') arch_tree = etree.fromstring(form_view.arch) if arch_tree.tag == 'form': arch_tree.insert(0, etree.Element('field', attrib={ 'name': 'available_partner_bank_ids', 'invisible': '1', })) form_view.sudo().write({'arch': etree.tostring(arch_tree, encoding='unicode')}) return super().fields_view_get(view_id=view_id, view_type=view_type, toolbar=toolbar, submenu=submenu) return res @api.model_create_multi def create(self, vals_list): # OVERRIDE write_off_line_vals_list = [] for vals in vals_list: # Hack to add a custom write-off line. write_off_line_vals_list.append(vals.pop('write_off_line_vals', None)) # Force the move_type to avoid inconsistency with residual 'default_move_type' inside the context. vals['move_type'] = 'entry' # Force the computation of 'journal_id' since this field is set on account.move but must have the # bank/cash type. if 'journal_id' not in vals: vals['journal_id'] = self._get_default_journal().id # Since 'currency_id' is a computed editable field, it will be computed later. # Prevent the account.move to call the _get_default_currency method that could raise # the 'Please define an accounting miscellaneous journal in your company' error. if 'currency_id' not in vals: journal = self.env['account.journal'].browse(vals['journal_id']) vals['currency_id'] = journal.currency_id.id or journal.company_id.currency_id.id payments = super().create(vals_list) for i, pay in enumerate(payments): write_off_line_vals = write_off_line_vals_list[i] # Write payment_id on the journal entry plus the fields being stored in both models but having the same # name, e.g. partner_bank_id. The ORM is currently not able to perform such synchronization and make things # more difficult by creating related fields on the fly to handle the _inherits. # Then, when partner_bank_id is in vals, the key is consumed by account.payment but is never written on # account.move. to_write = {'payment_id': pay.id} for k, v in vals_list[i].items(): if k in self._fields and self._fields[k].store and k in pay.move_id._fields and pay.move_id._fields[k].store: to_write[k] = v if 'line_ids' not in vals_list[i]: to_write['line_ids'] = [(0, 0, line_vals) for line_vals in pay._prepare_move_line_default_vals(write_off_line_vals=write_off_line_vals)] pay.move_id.write(to_write) return payments def write(self, vals): # OVERRIDE res = super().write(vals) self._synchronize_to_moves(set(vals.keys())) return res def unlink(self): # OVERRIDE to unlink the inherited account.move (move_id field) as well. moves = self.with_context(force_delete=True).move_id res = super().unlink() moves.unlink() return res @api.depends('move_id.name') def name_get(self): return [(payment.id, payment.move_id.name != '/' and payment.move_id.name or _('Draft Payment')) for payment in self] # ------------------------------------------------------------------------- # SYNCHRONIZATION account.payment <-> account.move # ------------------------------------------------------------------------- def _synchronize_from_moves(self, changed_fields): ''' Update the account.payment regarding its related account.move. Also, check both models are still consistent. :param changed_fields: A set containing all modified fields on account.move. ''' if self._context.get('skip_account_move_synchronization'): return for pay in self.with_context(skip_account_move_synchronization=True): # After the migration to 14.0, the journal entry could be shared between the account.payment and the # account.bank.statement.line. In that case, the synchronization will only be made with the statement line. if pay.move_id.statement_line_id: continue move = pay.move_id move_vals_to_write = {} payment_vals_to_write = {} if 'journal_id' in changed_fields: if pay.journal_id.type not in ('bank', 'cash'): raise UserError(_("A payment must always belongs to a bank or cash journal.")) if 'line_ids' in changed_fields: all_lines = move.line_ids liquidity_lines, counterpart_lines, writeoff_lines = pay._seek_for_lines() if len(liquidity_lines) != 1: raise UserError(_( "Journal Entry %s is not valid. In order to proceed, the journal items must " "include one and only one outstanding payments/receipts account.", move.display_name, )) if len(counterpart_lines) != 1: raise UserError(_( "Journal Entry %s is not valid. In order to proceed, the journal items must " "include one and only one receivable/payable account (with an exception of " "internal transfers).", move.display_name, )) if writeoff_lines and len(writeoff_lines.account_id) != 1: raise UserError(_( "Journal Entry %s is not valid. In order to proceed, " "all optional journal items must share the same account.", move.display_name, )) if any(line.currency_id != all_lines[0].currency_id for line in all_lines): raise UserError(_( "Journal Entry %s is not valid. In order to proceed, the journal items must " "share the same currency.", move.display_name, )) if any(line.partner_id != all_lines[0].partner_id for line in all_lines): raise UserError(_( "Journal Entry %s is not valid. In order to proceed, the journal items must " "share the same partner.", move.display_name, )) if counterpart_lines.account_id.user_type_id.type == 'receivable': partner_type = 'customer' else: partner_type = 'supplier' liquidity_amount = liquidity_lines.amount_currency move_vals_to_write.update({ 'currency_id': liquidity_lines.currency_id.id, 'partner_id': liquidity_lines.partner_id.id, }) payment_vals_to_write.update({ 'amount': abs(liquidity_amount), 'partner_type': partner_type, 'currency_id': liquidity_lines.currency_id.id, 'destination_account_id': counterpart_lines.account_id.id, 'partner_id': liquidity_lines.partner_id.id, }) if liquidity_amount > 0.0: payment_vals_to_write.update({'payment_type': 'inbound'}) elif liquidity_amount < 0.0: payment_vals_to_write.update({'payment_type': 'outbound'}) move.write(move._cleanup_write_orm_values(move, move_vals_to_write)) pay.write(move._cleanup_write_orm_values(pay, payment_vals_to_write)) def _synchronize_to_moves(self, changed_fields): ''' Update the account.move regarding the modified account.payment. :param changed_fields: A list containing all modified fields on account.payment. ''' if self._context.get('skip_account_move_synchronization'): return if not any(field_name in changed_fields for field_name in ( 'date', 'amount', 'payment_type', 'partner_type', 'payment_reference', 'is_internal_transfer', 'currency_id', 'partner_id', 'destination_account_id', 'partner_bank_id', 'journal_id' )): return for pay in self.with_context(skip_account_move_synchronization=True): liquidity_lines, counterpart_lines, writeoff_lines = pay._seek_for_lines() # Make sure to preserve the write-off amount. # This allows to create a new payment with custom 'line_ids'. if liquidity_lines and counterpart_lines and writeoff_lines: counterpart_amount = sum(counterpart_lines.mapped('amount_currency')) writeoff_amount = sum(writeoff_lines.mapped('amount_currency')) # To be consistent with the payment_difference made in account.payment.register, # 'writeoff_amount' needs to be signed regarding the 'amount' field before the write. # Since the write is already done at this point, we need to base the computation on accounting values. if (counterpart_amount > 0.0) == (writeoff_amount > 0.0): sign = -1 else: sign = 1 writeoff_amount = abs(writeoff_amount) * sign write_off_line_vals = { 'name': writeoff_lines[0].name, 'amount': writeoff_amount, 'account_id': writeoff_lines[0].account_id.id, } else: write_off_line_vals = {} line_vals_list = pay._prepare_move_line_default_vals(write_off_line_vals=write_off_line_vals) line_ids_commands = [ Command.update(liquidity_lines.id, line_vals_list[0]) if liquidity_lines else Command.create(line_vals_list[0]), Command.update(counterpart_lines.id, line_vals_list[1]) if counterpart_lines else Command.create(line_vals_list[1]) ] for line in writeoff_lines: line_ids_commands.append((2, line.id)) for extra_line_vals in line_vals_list[2:]: line_ids_commands.append((0, 0, extra_line_vals)) # Update the existing journal items. # If dealing with multiple write-off lines, they are dropped and a new one is generated. pay.move_id.write({ 'partner_id': pay.partner_id.id, 'currency_id': pay.currency_id.id, 'partner_bank_id': pay.partner_bank_id.id, 'line_ids': line_ids_commands, }) def _create_paired_internal_transfer_payment(self): ''' When an internal transfer is posted, a paired payment is created with opposite payment_type and swapped journal_id & destination_journal_id. Both payments liquidity transfer lines are then reconciled. ''' for payment in self: paired_payment = payment.copy({ 'journal_id': payment.destination_journal_id.id, 'destination_journal_id': payment.journal_id.id, 'payment_type': payment.payment_type == 'outbound' and 'inbound' or 'outbound', 'move_id': None, 'ref': payment.ref, 'paired_internal_transfer_payment_id': payment.id, 'date': payment.date, }) paired_payment.move_id._post(soft=False) payment.paired_internal_transfer_payment_id = paired_payment body = _('This payment has been created from <a href=# data-oe-model=account.payment data-oe-id=%d>%s</a>') % (payment.id, payment.name) paired_payment.message_post(body=body) body = _('A second payment has been created: <a href=# data-oe-model=account.payment data-oe-id=%d>%s</a>') % (paired_payment.id, paired_payment.name) payment.message_post(body=body) lines = (payment.move_id.line_ids + paired_payment.move_id.line_ids).filtered( lambda l: l.account_id == payment.destination_account_id and not l.reconciled) lines.reconcile() # ------------------------------------------------------------------------- # BUSINESS METHODS # ------------------------------------------------------------------------- def mark_as_sent(self): self.write({'is_move_sent': True}) def unmark_as_sent(self): self.write({'is_move_sent': False}) def action_post(self): ''' draft -> posted ''' self.move_id._post(soft=False) self.filtered( lambda pay: pay.is_internal_transfer and not pay.paired_internal_transfer_payment_id )._create_paired_internal_transfer_payment() def action_cancel(self): ''' draft -> cancelled ''' self.move_id.button_cancel() def action_draft(self): ''' posted -> draft ''' self.move_id.button_draft() def button_open_invoices(self): ''' Redirect the user to the invoice(s) paid by this payment. :return: An action on account.move. ''' self.ensure_one() action = { 'name': _("Paid Invoices"), 'type': 'ir.actions.act_window', 'res_model': 'account.move', 'context': {'create': False}, } if len(self.reconciled_invoice_ids) == 1: action.update({ 'view_mode': 'form', 'res_id': self.reconciled_invoice_ids.id, }) else: action.update({ 'view_mode': 'list,form', 'domain': [('id', 'in', self.reconciled_invoice_ids.ids)], }) return action def button_open_bills(self): ''' Redirect the user to the bill(s) paid by this payment. :return: An action on account.move. ''' self.ensure_one() action = { 'name': _("Paid Bills"), 'type': 'ir.actions.act_window', 'res_model': 'account.move', 'context': {'create': False}, } if len(self.reconciled_bill_ids) == 1: action.update({ 'view_mode': 'form', 'res_id': self.reconciled_bill_ids.id, }) else: action.update({ 'view_mode': 'list,form', 'domain': [('id', 'in', self.reconciled_bill_ids.ids)], }) return action def button_open_statements(self): ''' Redirect the user to the statement line(s) reconciled to this payment. :return: An action on account.move. ''' self.ensure_one() action = { 'name': _("Matched Statements"), 'type': 'ir.actions.act_window', 'res_model': 'account.bank.statement', 'context': {'create': False}, } if len(self.reconciled_statement_ids) == 1: action.update({ 'view_mode': 'form', 'res_id': self.reconciled_statement_ids.id, }) else: action.update({ 'view_mode': 'list,form', 'domain': [('id', 'in', self.reconciled_statement_ids.ids)], }) return action def button_open_journal_entry(self): ''' Redirect the user to this payment journal. :return: An action on account.move. ''' self.ensure_one() return { 'name': _("Journal Entry"), 'type': 'ir.actions.act_window', 'res_model': 'account.move', 'context': {'create': False}, 'view_mode': 'form', 'res_id': self.move_id.id, } def action_open_destination_journal(self): ''' Redirect the user to this destination journal. :return: An action on account.move. ''' self.ensure_one() action = { 'name': _("Destination journal"), 'type': 'ir.actions.act_window', 'res_model': 'account.journal', 'context': {'create': False}, 'view_mode': 'form', 'target': 'new', 'res_id': self.destination_journal_id.id, } return action
48.013423
50,078
29,471
py
PYTHON
15.0
import json from datetime import datetime, timedelta from babel.dates import format_datetime, format_date from odoo import models, api, _, fields from odoo.osv import expression from odoo.release import version from odoo.tools import DEFAULT_SERVER_DATE_FORMAT as DF from odoo.tools.misc import formatLang, format_date as odoo_format_date, get_lang import random import ast class account_journal(models.Model): _inherit = "account.journal" def _kanban_dashboard(self): for journal in self: journal.kanban_dashboard = json.dumps(journal.get_journal_dashboard_datas()) def _kanban_dashboard_graph(self): for journal in self: if (journal.type in ['sale', 'purchase']): journal.kanban_dashboard_graph = json.dumps(journal.get_bar_graph_datas()) elif (journal.type in ['cash', 'bank']): journal.kanban_dashboard_graph = json.dumps(journal.get_line_graph_datas()) else: journal.kanban_dashboard_graph = False def _get_json_activity_data(self): for journal in self: activities = [] # search activity on move on the journal sql_query = ''' SELECT act.id, act.res_id, act.res_model, act.summary, act_type.name as act_type_name, act_type.category as activity_category, act.date_deadline, m.date, m.ref, CASE WHEN act.date_deadline < CURRENT_DATE THEN 'late' ELSE 'future' END as status FROM account_move m LEFT JOIN mail_activity act ON act.res_id = m.id LEFT JOIN mail_activity_type act_type ON act.activity_type_id = act_type.id WHERE act.res_model = 'account.move' AND m.journal_id = %s ''' self.env.cr.execute(sql_query, (journal.id,)) for activity in self.env.cr.dictfetchall(): act = { 'id': activity.get('id'), 'res_id': activity.get('res_id'), 'res_model': activity.get('res_model'), 'status': activity.get('status'), 'name': (activity.get('summary') or activity.get('act_type_name')), 'activity_category': activity.get('activity_category'), 'date': odoo_format_date(self.env, activity.get('date_deadline')) } if activity.get('activity_category') == 'tax_report' and activity.get('res_model') == 'account.move': act['name'] = activity.get('ref') activities.append(act) journal.json_activity_data = json.dumps({'activities': activities}) kanban_dashboard = fields.Text(compute='_kanban_dashboard') kanban_dashboard_graph = fields.Text(compute='_kanban_dashboard_graph') json_activity_data = fields.Text(compute='_get_json_activity_data') show_on_dashboard = fields.Boolean(string='Show journal on dashboard', help="Whether this journal should be displayed on the dashboard or not", default=True) color = fields.Integer("Color Index", default=0) entries_count = fields.Integer(compute='_compute_entries_count') def _compute_entries_count(self): res = { r['journal_id'][0]: r['journal_id_count'] for r in self.env['account.move'].read_group( domain=[('journal_id', 'in', self.ids)], fields=['journal_id'], groupby=['journal_id'], ) } for journal in self: journal.entries_count = res.get(journal.id, 0) def _graph_title_and_key(self): if self.type in ['sale', 'purchase']: return ['', _('Residual amount')] elif self.type == 'cash': return ['', _('Cash: Balance')] elif self.type == 'bank': return ['', _('Bank: Balance')] # Below method is used to get data of bank and cash statemens def get_line_graph_datas(self): """Computes the data used to display the graph for bank and cash journals in the accounting dashboard""" currency = self.currency_id or self.company_id.currency_id def build_graph_data(date, amount): #display date in locale format name = format_date(date, 'd LLLL Y', locale=locale) short_name = format_date(date, 'd MMM', locale=locale) return {'x':short_name,'y': amount, 'name':name} self.ensure_one() BankStatement = self.env['account.bank.statement'] data = [] today = datetime.today() last_month = today + timedelta(days=-30) locale = get_lang(self.env).code #starting point of the graph is the last statement last_stmt = self._get_last_bank_statement(domain=[('state', 'in', ['posted', 'confirm'])]) last_balance = last_stmt and last_stmt.balance_end_real or 0 data.append(build_graph_data(today, last_balance)) #then we subtract the total amount of bank statement lines per day to get the previous points #(graph is drawn backward) date = today amount = last_balance query = ''' SELECT move.date, sum(st_line.amount) as amount FROM account_bank_statement_line st_line JOIN account_move move ON move.id = st_line.move_id WHERE move.journal_id = %s AND move.date > %s AND move.date <= %s GROUP BY move.date ORDER BY move.date desc ''' self.env.cr.execute(query, (self.id, last_month, today)) query_result = self.env.cr.dictfetchall() for val in query_result: date = val['date'] if date != today.strftime(DF): # make sure the last point in the graph is today data[:0] = [build_graph_data(date, amount)] amount = currency.round(amount - val['amount']) # make sure the graph starts 1 month ago if date.strftime(DF) != last_month.strftime(DF): data[:0] = [build_graph_data(last_month, amount)] [graph_title, graph_key] = self._graph_title_and_key() color = '#875A7B' if 'e' in version else '#7c7bad' is_sample_data = not last_stmt and len(query_result) == 0 if is_sample_data: data = [] for i in range(30, 0, -5): current_date = today + timedelta(days=-i) data.append(build_graph_data(current_date, random.randint(-5, 15))) return [{'values': data, 'title': graph_title, 'key': graph_key, 'area': True, 'color': color, 'is_sample_data': is_sample_data}] def get_bar_graph_datas(self): data = [] today = fields.Date.today() data.append({'label': _('Due'), 'value':0.0, 'type': 'past'}) day_of_week = int(format_datetime(today, 'e', locale=get_lang(self.env).code)) first_day_of_week = today + timedelta(days=-day_of_week+1) for i in range(-1,4): if i==0: label = _('This Week') elif i==3: label = _('Not Due') else: start_week = first_day_of_week + timedelta(days=i*7) end_week = start_week + timedelta(days=6) if start_week.month == end_week.month: label = str(start_week.day) + '-' + str(end_week.day) + ' ' + format_date(end_week, 'MMM', locale=get_lang(self.env).code) else: label = format_date(start_week, 'd MMM', locale=get_lang(self.env).code) + '-' + format_date(end_week, 'd MMM', locale=get_lang(self.env).code) data.append({'label':label,'value':0.0, 'type': 'past' if i<0 else 'future'}) # Build SQL query to find amount aggregated by week (select_sql_clause, query_args) = self._get_bar_graph_select_query() query = '' start_date = (first_day_of_week + timedelta(days=-7)) weeks = [] for i in range(0,6): if i == 0: query += "("+select_sql_clause+" and invoice_date_due < '"+start_date.strftime(DF)+"')" weeks.append((start_date.min, start_date)) elif i == 5: query += " UNION ALL ("+select_sql_clause+" and invoice_date_due >= '"+start_date.strftime(DF)+"')" weeks.append((start_date, start_date.max)) else: next_date = start_date + timedelta(days=7) query += " UNION ALL ("+select_sql_clause+" and invoice_date_due >= '"+start_date.strftime(DF)+"' and invoice_date_due < '"+next_date.strftime(DF)+"')" weeks.append((start_date, next_date)) start_date = next_date # Ensure results returned by postgres match the order of data list self.env.cr.execute(query, query_args) query_results = self.env.cr.dictfetchall() is_sample_data = True for index in range(0, len(query_results)): if query_results[index].get('aggr_date') != None: is_sample_data = False aggr_date = query_results[index]['aggr_date'] week_index = next(i for i in range(0, len(weeks)) if weeks[i][0] <= aggr_date < weeks[i][1]) data[week_index]['value'] = query_results[index].get('total') [graph_title, graph_key] = self._graph_title_and_key() if is_sample_data: for index in range(0, len(query_results)): data[index]['type'] = 'o_sample_data' # we use unrealistic values for the sample data data[index]['value'] = random.randint(0, 20) graph_key = _('Sample data') return [{'values': data, 'title': graph_title, 'key': graph_key, 'is_sample_data': is_sample_data}] def _get_bar_graph_select_query(self): """ Returns a tuple containing the base SELECT SQL query used to gather the bar graph's data as its first element, and the arguments dictionary for it as its second. """ sign = '' if self.type == 'sale' else '-' return (''' SELECT ''' + sign + ''' + SUM(move.amount_residual_signed) AS total, MIN(invoice_date_due) AS aggr_date FROM account_move move WHERE move.journal_id = %(journal_id)s AND move.state = 'posted' AND move.payment_state in ('not_paid', 'partial') AND move.move_type IN %(invoice_types)s ''', { 'invoice_types': tuple(self.env['account.move'].get_invoice_types(True)), 'journal_id': self.id }) def get_journal_dashboard_datas(self): currency = self.currency_id or self.company_id.currency_id number_to_reconcile = number_to_check = last_balance = 0 has_at_least_one_statement = False bank_account_balance = nb_lines_bank_account_balance = 0 outstanding_pay_account_balance = nb_lines_outstanding_pay_account_balance = 0 title = '' number_draft = number_waiting = number_late = to_check_balance = 0 sum_draft = sum_waiting = sum_late = 0.0 if self.type in ('bank', 'cash'): last_statement = self._get_last_bank_statement( domain=[('state', 'in', ['posted', 'confirm'])]) last_balance = last_statement.balance_end has_at_least_one_statement = bool(last_statement) bank_account_balance, nb_lines_bank_account_balance = self._get_journal_bank_account_balance( domain=[('parent_state', '=', 'posted')]) outstanding_pay_account_balance, nb_lines_outstanding_pay_account_balance = self._get_journal_outstanding_payments_account_balance( domain=[('parent_state', '=', 'posted')]) self._cr.execute(''' SELECT COUNT(st_line.id) FROM account_bank_statement_line st_line JOIN account_move st_line_move ON st_line_move.id = st_line.move_id JOIN account_bank_statement st ON st_line.statement_id = st.id WHERE st_line_move.journal_id IN %s AND st.state = 'posted' AND NOT st_line.is_reconciled ''', [tuple(self.ids)]) number_to_reconcile = self.env.cr.fetchone()[0] to_check_ids = self.to_check_ids() number_to_check = len(to_check_ids) to_check_balance = sum([r.amount for r in to_check_ids]) #TODO need to check if all invoices are in the same currency than the journal!!!! elif self.type in ['sale', 'purchase']: title = _('Bills to pay') if self.type == 'purchase' else _('Invoices owed to you') self.env['account.move'].flush(['amount_residual', 'currency_id', 'move_type', 'invoice_date', 'company_id', 'journal_id', 'date', 'state', 'payment_state']) (query, query_args) = self._get_open_bills_to_pay_query() self.env.cr.execute(query, query_args) query_results_to_pay = self.env.cr.dictfetchall() (query, query_args) = self._get_draft_bills_query() self.env.cr.execute(query, query_args) query_results_drafts = self.env.cr.dictfetchall() (query, query_args) = self._get_late_bills_query() self.env.cr.execute(query, query_args) late_query_results = self.env.cr.dictfetchall() curr_cache = {} (number_waiting, sum_waiting) = self._count_results_and_sum_amounts(query_results_to_pay, currency, curr_cache=curr_cache) (number_draft, sum_draft) = self._count_results_and_sum_amounts(query_results_drafts, currency, curr_cache=curr_cache) (number_late, sum_late) = self._count_results_and_sum_amounts(late_query_results, currency, curr_cache=curr_cache) read = self.env['account.move'].read_group([('journal_id', '=', self.id), ('to_check', '=', True)], ['amount_total_signed'], 'journal_id', lazy=False) if read: number_to_check = read[0]['__count'] to_check_balance = read[0]['amount_total_signed'] elif self.type == 'general': read = self.env['account.move'].read_group([('journal_id', '=', self.id), ('to_check', '=', True)], ['amount_total_signed'], 'journal_id', lazy=False) if read: number_to_check = read[0]['__count'] to_check_balance = read[0]['amount_total_signed'] is_sample_data = self.kanban_dashboard_graph and any(data.get('is_sample_data', False) for data in json.loads(self.kanban_dashboard_graph)) return { 'number_to_check': number_to_check, 'to_check_balance': formatLang(self.env, to_check_balance, currency_obj=currency), 'number_to_reconcile': number_to_reconcile, 'account_balance': formatLang(self.env, currency.round(bank_account_balance), currency_obj=currency), 'has_at_least_one_statement': has_at_least_one_statement, 'nb_lines_bank_account_balance': nb_lines_bank_account_balance, 'outstanding_pay_account_balance': formatLang(self.env, currency.round(outstanding_pay_account_balance), currency_obj=currency), 'nb_lines_outstanding_pay_account_balance': nb_lines_outstanding_pay_account_balance, 'last_balance': formatLang(self.env, currency.round(last_balance) + 0.0, currency_obj=currency), 'number_draft': number_draft, 'number_waiting': number_waiting, 'number_late': number_late, 'sum_draft': formatLang(self.env, currency.round(sum_draft) + 0.0, currency_obj=currency), 'sum_waiting': formatLang(self.env, currency.round(sum_waiting) + 0.0, currency_obj=currency), 'sum_late': formatLang(self.env, currency.round(sum_late) + 0.0, currency_obj=currency), 'currency_id': currency.id, 'bank_statements_source': self.bank_statements_source, 'title': title, 'is_sample_data': is_sample_data, 'company_count': len(self.env.companies) } def _get_open_bills_to_pay_query(self): """ Returns a tuple containing the SQL query used to gather the open bills data as its first element, and the arguments dictionary to use to run it as its second. """ return (''' SELECT (CASE WHEN move.move_type IN ('out_refund', 'in_refund') THEN -1 ELSE 1 END) * move.amount_residual AS amount_total, %(sign)s * amount_residual_signed AS amount_total_company, move.currency_id AS currency, move.move_type, move.invoice_date, move.company_id FROM account_move move WHERE move.journal_id = %(journal_id)s AND move.state = 'posted' AND move.payment_state in ('not_paid', 'partial') AND move.move_type IN ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt'); ''', { 'sign': 1 if self.type == 'sale' else -1, 'journal_id': self.id, }) def _get_draft_bills_query(self): """ Returns a tuple containing as its first element the SQL query used to gather the bills in draft state data, and the arguments dictionary to use to run it as its second. """ return (''' SELECT (CASE WHEN move.move_type IN ('out_refund', 'in_refund') THEN -1 ELSE 1 END) * move.amount_total AS amount_total, %(sign)s * amount_residual_signed AS amount_total_company, move.currency_id AS currency, move.move_type, move.invoice_date, move.company_id FROM account_move move WHERE move.journal_id = %(journal_id)s AND move.state = 'draft' AND move.payment_state in ('not_paid', 'partial') AND move.move_type IN ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt'); ''', { 'sign': 1 if self.type == 'sale' else -1, 'journal_id': self.id, }) def _get_late_bills_query(self): return """ SELECT (CASE WHEN move_type IN ('out_refund', 'in_refund') THEN -1 ELSE 1 END) * amount_residual AS amount_total, %(sign)s * amount_residual_signed AS amount_total_company, currency_id AS currency, move_type, invoice_date, company_id FROM account_move move WHERE journal_id = %(journal_id)s AND invoice_date_due < %(today)s AND state = 'posted' AND payment_state in ('not_paid', 'partial') AND move_type IN ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt'); """, { 'sign': 1 if self.type == 'sale' else -1, 'journal_id': self.id, 'today': fields.Date.context_today(self) } def _count_results_and_sum_amounts(self, results_dict, target_currency, curr_cache=None): """ Loops on a query result to count the total number of invoices and sum their amount_total field (expressed in the given target currency). amount_total must be signed ! """ rslt_count = 0 rslt_sum = 0.0 # Create a cache with currency rates to avoid unnecessary SQL requests. Do not copy # curr_cache on purpose, so the dictionary is modified and can be re-used for subsequent # calls of the method. curr_cache = {} if curr_cache is None else curr_cache for result in results_dict: cur = self.env['res.currency'].browse(result.get('currency')) company = self.env['res.company'].browse(result.get('company_id')) or self.env.company rslt_count += 1 date = result.get('invoice_date') or fields.Date.context_today(self) if cur == target_currency: amount = result.get('amount_total', 0) or 0 elif company.currency_id == target_currency and result.get('amount_total_company'): amount = result.get('amount_total_company') or 0 else: key = (cur, target_currency, company, date) # Using setdefault will call _get_conversion_rate, so we explicitly check the # existence of the key in the cache instead. if key not in curr_cache: curr_cache[key] = self.env['res.currency']._get_conversion_rate(*key) amount = curr_cache[key] * (result.get('amount_total') or 0) rslt_sum += target_currency.round(amount) return (rslt_count, rslt_sum) def action_create_new(self): ctx = self._context.copy() ctx['default_journal_id'] = self.id if self.type == 'sale': ctx['default_move_type'] = 'out_refund' if ctx.get('refund') else 'out_invoice' elif self.type == 'purchase': ctx['default_move_type'] = 'in_refund' if ctx.get('refund') else 'in_invoice' else: ctx['default_move_type'] = 'entry' ctx['view_no_maturity'] = True return { 'name': _('Create invoice/bill'), 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'account.move', 'view_id': self.env.ref('account.view_move_form').id, 'context': ctx, } def create_cash_statement(self): ctx = self._context.copy() ctx.update({'journal_id': self.id, 'default_journal_id': self.id, 'default_journal_type': 'cash'}) open_statements = self.env['account.bank.statement'].search([('journal_id', '=', self.id), ('state', '=', 'open')]) action = { 'name': _('Create cash statement'), 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'account.bank.statement', 'context': ctx, } if len(open_statements) == 1: action.update({ 'view_mode': 'form', 'res_id': open_statements.id, }) elif len(open_statements) > 1: action.update({ 'view_mode': 'tree,form', 'domain': [('id', 'in', open_statements.ids)], }) return action def action_create_vendor_bill(self): """ This function is called by the "Import" button of Vendor Bills, visible on dashboard if no bill has been created yet. """ self.env.company.sudo().set_onboarding_step_done('account_setup_bill_state') new_wizard = self.env['account.tour.upload.bill'].create({}) view_id = self.env.ref('account.account_tour_upload_bill').id return { 'type': 'ir.actions.act_window', 'name': _('Import your first bill'), 'view_mode': 'form', 'res_model': 'account.tour.upload.bill', 'target': 'new', 'res_id': new_wizard.id, 'views': [[view_id, 'form']], } def to_check_ids(self): self.ensure_one() domain = self.env['account.move.line']._get_suspense_moves_domain() domain.append(('journal_id', '=', self.id)) statement_line_ids = self.env['account.move.line'].search(domain).mapped('statement_line_id') return statement_line_ids def _select_action_to_open(self): self.ensure_one() if self._context.get('action_name'): return self._context.get('action_name') elif self.type == 'bank': return 'action_bank_statement_tree' elif self.type == 'cash': return 'action_view_bank_statement_tree' elif self.type == 'sale': return 'action_move_out_invoice_type' elif self.type == 'purchase': return 'action_move_in_invoice_type' else: return 'action_move_journal_line' def open_action(self): """return action based on type for related journals""" self.ensure_one() action_name = self._select_action_to_open() # Set 'account.' prefix if missing. if not action_name.startswith("account."): action_name = 'account.%s' % action_name action = self.env["ir.actions.act_window"]._for_xml_id(action_name) context = self._context.copy() if 'context' in action and type(action['context']) == str: context.update(ast.literal_eval(action['context'])) else: context.update(action.get('context', {})) action['context'] = context action['context'].update({ 'default_journal_id': self.id, 'search_default_journal_id': self.id, }) domain_type_field = action['res_model'] == 'account.move.line' and 'move_id.move_type' or 'move_type' # The model can be either account.move or account.move.line # Override the domain only if the action was not explicitly specified in order to keep the # original action domain. if not self._context.get('action_name'): if self.type == 'sale': action['domain'] = [(domain_type_field, 'in', ('out_invoice', 'out_refund', 'out_receipt'))] elif self.type == 'purchase': action['domain'] = [(domain_type_field, 'in', ('in_invoice', 'in_refund', 'in_receipt', 'entry'))] return action def open_spend_money(self): return self.open_payments_action('outbound') def open_collect_money(self): return self.open_payments_action('inbound') def open_transfer_money(self): return self.open_payments_action('transfer') def open_payments_action(self, payment_type, mode='tree'): if payment_type == 'outbound': action_ref = 'account.action_account_payments_payable' elif payment_type == 'transfer': action_ref = 'account.action_account_payments_transfer' else: action_ref = 'account.action_account_payments' action = self.env['ir.actions.act_window']._for_xml_id(action_ref) action['context'] = dict(ast.literal_eval(action.get('context')), default_journal_id=self.id, search_default_journal_id=self.id) if payment_type == 'transfer': action['context'].update({ 'default_partner_id': self.company_id.partner_id.id, 'default_is_internal_transfer': True, }) if mode == 'form': action['views'] = [[False, 'form']] return action def open_action_with_context(self): action_name = self.env.context.get('action_name', False) if not action_name: return False ctx = dict(self.env.context, default_journal_id=self.id) if ctx.get('search_default_journal', False): ctx.update(search_default_journal_id=self.id) ctx['search_default_journal'] = False # otherwise it will do a useless groupby in bank statements ctx.pop('group_by', None) action = self.env['ir.actions.act_window']._for_xml_id(f"account.{action_name}") action['context'] = ctx if ctx.get('use_domain', False): action['domain'] = isinstance(ctx['use_domain'], list) and ctx['use_domain'] or ['|', ('journal_id', '=', self.id), ('journal_id', '=', False)] action['name'] = _( "%(action)s for journal %(journal)s", action=action["name"], journal=self.name, ) return action def create_bank_statement(self): """return action to create a bank statements. This button should be called only on journals with type =='bank'""" action = self.env["ir.actions.actions"]._for_xml_id("account.action_bank_statement_tree") action.update({ 'views': [[False, 'form']], 'context': "{'default_journal_id': " + str(self.id) + "}", }) return action def create_customer_payment(self): """return action to create a customer payment""" return self.open_payments_action('inbound', mode='form') def create_supplier_payment(self): """return action to create a supplier payment""" return self.open_payments_action('outbound', mode='form') def create_internal_transfer(self): """return action to create a internal transfer""" return self.open_payments_action('transfer', mode='form') ##################### # Setup Steps Stuff # ##################### def mark_bank_setup_as_done_action(self): """ Marks the 'bank setup' step as done in the setup bar and in the company.""" self.company_id.sudo().set_onboarding_step_done('account_setup_bank_data_state') def unmark_bank_setup_as_done_action(self): """ Marks the 'bank setup' step as not done in the setup bar and in the company.""" self.company_id.account_setup_bank_data_state = 'not_done'
47.457327
29,471
3,187
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, fields, _ from odoo.exceptions import UserError class ResCurrency(models.Model): _inherit = 'res.currency' display_rounding_warning = fields.Boolean(string="Display Rounding Warning", compute='_compute_display_rounding_warning', help="Technical field. Used to tell whether or not to display the rounding warning. The warning informs a rounding factor change might be dangerous on res.currency's form view.") @api.depends('rounding') def _compute_display_rounding_warning(self): for record in self: record.display_rounding_warning = record.id \ and record._origin.rounding != record.rounding \ and record._origin._has_accounting_entries() def write(self, vals): if 'rounding' in vals: rounding_val = vals['rounding'] for record in self: if (rounding_val > record.rounding or rounding_val == 0) and record._has_accounting_entries(): raise UserError(_("You cannot reduce the number of decimal places of a currency which has already been used to make accounting entries.")) return super(ResCurrency, self).write(vals) def _has_accounting_entries(self): """ Returns True iff this currency has been used to generate (hence, round) some move lines (either as their foreign currency, or as the main currency of their company). """ self.ensure_one() return bool(self.env['account.move.line'].search_count(['|', ('currency_id', '=', self.id), ('company_currency_id', '=', self.id)])) @api.model def _get_query_currency_table(self, options): ''' Construct the currency table as a mapping company -> rate to convert the amount to the user's company currency in a multi-company/multi-currency environment. The currency_table is a small postgresql table construct with VALUES. :param options: The report options. :return: The query representing the currency table. ''' user_company = self.env.company user_currency = user_company.currency_id if options.get('multi_company', False): companies = self.env.companies conversion_date = options['date']['date_to'] currency_rates = companies.mapped('currency_id')._get_rates(user_company, conversion_date) else: companies = user_company currency_rates = {user_currency.id: 1.0} conversion_rates = [] for company in companies: conversion_rates.extend(( company.id, currency_rates[user_company.currency_id.id] / currency_rates[company.currency_id.id], user_currency.decimal_places, )) query = '(VALUES %s) AS currency_table(company_id, rate, precision)' % ','.join('(%s, %s, %s)' for i in companies) return self.env.cr.mogrify(query, conversion_rates).decode(self.env.cr.connection.encoding)
48.287879
3,187
13,827
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import ValidationError from odoo.tools.misc import format_date from odoo.tools import frozendict import re from collections import defaultdict from psycopg2 import sql class SequenceMixin(models.AbstractModel): """Mechanism used to have an editable sequence number. Be careful of how you use this regarding the prefixes. More info in the docstring of _get_last_sequence. """ _name = 'sequence.mixin' _description = "Automatic sequence" _sequence_field = "name" _sequence_date_field = "date" _sequence_index = False _sequence_monthly_regex = r'^(?P<prefix1>.*?)(?P<year>((?<=\D)|(?<=^))((19|20|21)\d{2}|(\d{2}(?=\D))))(?P<prefix2>\D*?)(?P<month>(0[1-9]|1[0-2]))(?P<prefix3>\D+?)(?P<seq>\d*)(?P<suffix>\D*?)$' _sequence_yearly_regex = r'^(?P<prefix1>.*?)(?P<year>((?<=\D)|(?<=^))((19|20|21)?\d{2}))(?P<prefix2>\D+?)(?P<seq>\d*)(?P<suffix>\D*?)$' _sequence_fixed_regex = r'^(?P<prefix1>.*?)(?P<seq>\d{0,9})(?P<suffix>\D*?)$' sequence_prefix = fields.Char(compute='_compute_split_sequence', store=True) sequence_number = fields.Integer(compute='_compute_split_sequence', store=True) def init(self): # Add an index to optimise the query searching for the highest sequence number if not self._abstract and self._sequence_index: index_name = self._table + '_sequence_index' self.env.cr.execute('SELECT indexname FROM pg_indexes WHERE indexname = %s', (index_name,)) if not self.env.cr.fetchone(): self.env.cr.execute(sql.SQL(""" CREATE INDEX {index_name} ON {table} ({sequence_index}, sequence_prefix desc, sequence_number desc, {field}); CREATE INDEX {index2_name} ON {table} ({sequence_index}, id desc, sequence_prefix); """).format( sequence_index=sql.Identifier(self._sequence_index), index_name=sql.Identifier(index_name), index2_name=sql.Identifier(index_name + "2"), table=sql.Identifier(self._table), field=sql.Identifier(self._sequence_field), )) @api.constrains(lambda self: (self._sequence_field, self._sequence_date_field)) def _constrains_date_sequence(self): # Make it possible to bypass the constraint to allow edition of already messed up documents. # /!\ Do not use this to completely disable the constraint as it will make this mixin unreliable. constraint_date = fields.Date.to_date(self.env['ir.config_parameter'].sudo().get_param( 'sequence.mixin.constraint_start_date', '1970-01-01' )) for record in self: date = fields.Date.to_date(record[record._sequence_date_field]) sequence = record[record._sequence_field] if sequence and date and date > constraint_date: format_values = record._get_sequence_format_param(sequence)[1] if ( format_values['year'] and format_values['year'] != date.year % 10**len(str(format_values['year'])) or format_values['month'] and format_values['month'] != date.month ): raise ValidationError(_( "The %(date_field)s (%(date)s) doesn't match the sequence number of the related %(model)s (%(sequence)s)\n" "You will need to clear the %(model)s's %(sequence_field)s to proceed.\n" "In doing so, you might want to resequence your entries in order to maintain a continuous date-based sequence.", date=format_date(self.env, date), sequence=sequence, date_field=record._fields[record._sequence_date_field]._description_string(self.env), sequence_field=record._fields[record._sequence_field]._description_string(self.env), model=self.env['ir.model']._get(record._name).display_name, )) @api.depends(lambda self: [self._sequence_field]) def _compute_split_sequence(self): for record in self: sequence = record[record._sequence_field] or '' regex = re.sub(r"\?P<\w+>", "?:", record._sequence_fixed_regex.replace(r"?P<seq>", "")) # make the seq the only matching group matching = re.match(regex, sequence) record.sequence_prefix = sequence[:matching.start(1)] record.sequence_number = int(matching.group(1) or 0) @api.model def _deduce_sequence_number_reset(self, name): """Detect if the used sequence resets yearly, montly or never. :param name: the sequence that is used as a reference to detect the resetting periodicity. Typically, it is the last before the one you want to give a sequence. """ for regex, ret_val, requirements in [ (self._sequence_monthly_regex, 'month', ['seq', 'month', 'year']), (self._sequence_yearly_regex, 'year', ['seq', 'year']), (self._sequence_fixed_regex, 'never', ['seq']), ]: match = re.match(regex, name or '') if match: groupdict = match.groupdict() if all(req in groupdict for req in requirements): return ret_val raise ValidationError(_( 'The sequence regex should at least contain the seq grouping keys. For instance:\n' '^(?P<prefix1>.*?)(?P<seq>\d*)(?P<suffix>\D*?)$' )) def _get_last_sequence_domain(self, relaxed=False): """Get the sql domain to retreive the previous sequence number. This function should be overriden by models inheriting from this mixin. :param relaxed: see _get_last_sequence. :returns: tuple(where_string, where_params): with where_string: the entire SQL WHERE clause as a string. where_params: a dictionary containing the parameters to substitute at the execution of the query. """ self.ensure_one() return "", {} def _get_starting_sequence(self): """Get a default sequence number. This function should be overriden by models heriting from this mixin This number will be incremented so you probably want to start the sequence at 0. :return: string to use as the default sequence to increment """ self.ensure_one() return "00000000" def _get_last_sequence(self, relaxed=False, with_prefix=None, lock=True): """Retrieve the previous sequence. This is done by taking the number with the greatest alphabetical value within the domain of _get_last_sequence_domain. This means that the prefix has a huge importance. For instance, if you have INV/2019/0001 and INV/2019/0002, when you rename the last one to FACT/2019/0001, one might expect the next number to be FACT/2019/0002 but it will be INV/2019/0002 (again) because INV > FACT. Therefore, changing the prefix might not be convenient during a period, and would only work when the numbering makes a new start (domain returns by _get_last_sequence_domain is [], i.e: a new year). :param field_name: the field that contains the sequence. :param relaxed: this should be set to True when a previous request didn't find something without. This allows to find a pattern from a previous period, and try to adapt it for the new period. :param with_prefix: The sequence prefix to restrict the search on, if any. :return: the string of the previous sequence or None if there wasn't any. """ self.ensure_one() if self._sequence_field not in self._fields or not self._fields[self._sequence_field].store: raise ValidationError(_('%s is not a stored field', self._sequence_field)) where_string, param = self._get_last_sequence_domain(relaxed) if self.id or self.id.origin: where_string += " AND id != %(id)s " param['id'] = self.id or self.id.origin if with_prefix is not None: where_string += " AND sequence_prefix = %(with_prefix)s " param['with_prefix'] = with_prefix query = f""" SELECT {{field}} FROM {self._table} {where_string} AND sequence_prefix = (SELECT sequence_prefix FROM {self._table} {where_string} ORDER BY id DESC LIMIT 1) ORDER BY sequence_number DESC LIMIT 1 """ if lock: query = f""" UPDATE {self._table} SET write_date = write_date WHERE id = ( {query.format(field='id')} ) RETURNING {self._sequence_field}; """ else: query = query.format(field=self._sequence_field) self.flush([self._sequence_field, 'sequence_number', 'sequence_prefix']) self.env.cr.execute(query, param) return (self.env.cr.fetchone() or [None])[0] def _get_sequence_format_param(self, previous): """Get the python format and format values for the sequence. :param previous: the sequence we want to extract the format from :return tuple(format, format_values): format is the format string on which we should call .format() format_values is the dict of values to format the `format` string ``format.format(**format_values)`` should be equal to ``previous`` """ sequence_number_reset = self._deduce_sequence_number_reset(previous) regex = self._sequence_fixed_regex if sequence_number_reset == 'year': regex = self._sequence_yearly_regex elif sequence_number_reset == 'month': regex = self._sequence_monthly_regex format_values = re.match(regex, previous).groupdict() format_values['seq_length'] = len(format_values['seq']) format_values['year_length'] = len(format_values.get('year', '')) if not format_values.get('seq') and 'prefix1' in format_values and 'suffix' in format_values: # if we don't have a seq, consider we only have a prefix and not a suffix format_values['prefix1'] = format_values['suffix'] format_values['suffix'] = '' for field in ('seq', 'year', 'month'): format_values[field] = int(format_values.get(field) or 0) placeholders = re.findall(r'(prefix\d|seq|suffix\d?|year|month)', regex) format = ''.join( "{seq:0{seq_length}d}" if s == 'seq' else "{month:02d}" if s == 'month' else "{year:0{year_length}d}" if s == 'year' else "{%s}" % s for s in placeholders ) return format, format_values def _set_next_sequence(self): """Set the next sequence. This method ensures that the field is set both in the ORM and in the database. This is necessary because we use a database query to get the previous sequence, and we need that query to always be executed on the latest data. :param field_name: the field that contains the sequence. """ self.ensure_one() last_sequence = self._get_last_sequence() new = not last_sequence if new: last_sequence = self._get_last_sequence(relaxed=True) or self._get_starting_sequence() format, format_values = self._get_sequence_format_param(last_sequence) if new: format_values['seq'] = 0 format_values['year'] = self[self._sequence_date_field].year % (10 ** format_values['year_length']) format_values['month'] = self[self._sequence_date_field].month format_values['seq'] = format_values['seq'] + 1 self[self._sequence_field] = format.format(**format_values) self._compute_split_sequence() def _is_last_from_seq_chain(self): """Tells whether or not this element is the last one of the sequence chain. :return: True if it is the last element of the chain. """ last_sequence = self._get_last_sequence(with_prefix=self.sequence_prefix) if not last_sequence: return True seq_format, seq_format_values = self._get_sequence_format_param(last_sequence) seq_format_values['seq'] += 1 return seq_format.format(**seq_format_values) == self.name def _is_end_of_seq_chain(self): """Tells whether or not these elements are the last ones of the sequence chain. :return: True if self are the last elements of the chain. """ batched = defaultdict(lambda: {'last_rec': self.browse(), 'seq_list': []}) for record in self.filtered(lambda x: x[x._sequence_field]): format, format_values = record._get_sequence_format_param(record[record._sequence_field]) seq = format_values.pop('seq') batch = batched[(format, frozendict(format_values))] batch['seq_list'].append(seq) if batch['last_rec'].sequence_number <= record.sequence_number: batch['last_rec'] = record for values in batched.values(): # The sequences we are deleting are not sequential seq_list = values['seq_list'] if max(seq_list) - min(seq_list) != len(seq_list) - 1: return False # last_rec must have the highest number in the database record = values['last_rec'] if not record._is_last_from_seq_chain(): return False return True
48.346154
13,827
2,023
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, models, _ from odoo.exceptions import ValidationError class Users(models.Model): _inherit = "res.users" @api.constrains('groups_id') def _check_one_user_type(self): super(Users, self)._check_one_user_type() g1 = self.env.ref('account.group_show_line_subtotals_tax_included', False) g2 = self.env.ref('account.group_show_line_subtotals_tax_excluded', False) if not g1 or not g2: # A user cannot be in a non-existant group return for user in self: if user._has_multiple_groups([g1.id, g2.id]): raise ValidationError(_("A user cannot have both Tax B2B and Tax B2C.\n" "You should go in General Settings, and choose to display Product Prices\n" "either in 'Tax-Included' or in 'Tax-Excluded' mode\n" "(or switch twice the mode if you are already in the desired one).")) class GroupsView(models.Model): _inherit = 'res.groups' @api.model def get_application_groups(self, domain): # Overridden in order to remove 'Show Full Accounting Features' and # 'Show Full Accounting Features - Readonly' in the 'res.users' form view to prevent confusion group_account_user = self.env.ref('account.group_account_user', raise_if_not_found=False) if group_account_user and group_account_user.category_id.xml_id == 'base.module_category_hidden': domain += [('id', '!=', group_account_user.id)] group_account_readonly = self.env.ref('account.group_account_readonly', raise_if_not_found=False) if group_account_readonly and group_account_readonly.category_id.xml_id == 'base.module_category_hidden': domain += [('id', '!=', group_account_readonly.id)] return super().get_application_groups(domain)
47.046512
2,023
9,477
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import ValidationError from odoo.tools import format_amount ACCOUNT_DOMAIN = "['&', '&', '&', ('deprecated', '=', False), ('internal_type','=','other'), ('company_id', '=', current_company_id), ('is_off_balance', '=', False)]" class ProductCategory(models.Model): _inherit = "product.category" property_account_income_categ_id = fields.Many2one('account.account', company_dependent=True, string="Income Account", domain=ACCOUNT_DOMAIN, help="This account will be used when validating a customer invoice.") property_account_expense_categ_id = fields.Many2one('account.account', company_dependent=True, string="Expense Account", domain=ACCOUNT_DOMAIN, help="The expense is accounted for when a vendor bill is validated, except in anglo-saxon accounting with perpetual inventory valuation in which case the expense (Cost of Goods Sold account) is recognized at the customer invoice validation.") #---------------------------------------------------------- # Products #---------------------------------------------------------- class ProductTemplate(models.Model): _inherit = "product.template" taxes_id = fields.Many2many('account.tax', 'product_taxes_rel', 'prod_id', 'tax_id', help="Default taxes used when selling the product.", string='Customer Taxes', domain=[('type_tax_use', '=', 'sale')], default=lambda self: self.env.company.account_sale_tax_id) tax_string = fields.Char(compute='_compute_tax_string') supplier_taxes_id = fields.Many2many('account.tax', 'product_supplier_taxes_rel', 'prod_id', 'tax_id', string='Vendor Taxes', help='Default taxes used when buying the product.', domain=[('type_tax_use', '=', 'purchase')], default=lambda self: self.env.company.account_purchase_tax_id) property_account_income_id = fields.Many2one('account.account', company_dependent=True, string="Income Account", domain=ACCOUNT_DOMAIN, help="Keep this field empty to use the default value from the product category.") property_account_expense_id = fields.Many2one('account.account', company_dependent=True, string="Expense Account", domain=ACCOUNT_DOMAIN, help="Keep this field empty to use the default value from the product category. If anglo-saxon accounting with automated valuation method is configured, the expense account on the product category will be used.") account_tag_ids = fields.Many2many( string="Account Tags", comodel_name='account.account.tag', domain="[('applicability', '=', 'products')]", help="Tags to be set on the base and tax journal items created for this product.") def _get_product_accounts(self): return { 'income': self.property_account_income_id or self.categ_id.property_account_income_categ_id, 'expense': self.property_account_expense_id or self.categ_id.property_account_expense_categ_id } def _get_asset_accounts(self): res = {} res['stock_input'] = False res['stock_output'] = False return res def get_product_accounts(self, fiscal_pos=None): accounts = self._get_product_accounts() if not fiscal_pos: fiscal_pos = self.env['account.fiscal.position'] return fiscal_pos.map_accounts(accounts) @api.depends('taxes_id', 'list_price') def _compute_tax_string(self): for record in self: record.tax_string = record._construct_tax_string(record.list_price) def _construct_tax_string(self, price): currency = self.currency_id res = self.taxes_id.compute_all(price, product=self, partner=self.env['res.partner']) joined = [] included = res['total_included'] if currency.compare_amounts(included, price): joined.append(_('%s Incl. Taxes', format_amount(self.env, included, currency))) excluded = res['total_excluded'] if currency.compare_amounts(excluded, price): joined.append(_('%s Excl. Taxes', format_amount(self.env, excluded, currency))) if joined: tax_string = f"(= {', '.join(joined)})" else: tax_string = " " return tax_string @api.constrains('uom_id') def _check_uom_not_in_invoice(self): self.env['product.template'].flush(['uom_id']) self._cr.execute(""" SELECT prod_template.id FROM account_move_line line JOIN product_product prod_variant ON line.product_id = prod_variant.id JOIN product_template prod_template ON prod_variant.product_tmpl_id = prod_template.id JOIN uom_uom template_uom ON prod_template.uom_id = template_uom.id JOIN uom_category template_uom_cat ON template_uom.category_id = template_uom_cat.id JOIN uom_uom line_uom ON line.product_uom_id = line_uom.id JOIN uom_category line_uom_cat ON line_uom.category_id = line_uom_cat.id WHERE prod_template.id IN %s AND line.parent_state = 'posted' AND template_uom_cat.id != line_uom_cat.id LIMIT 1 """, [tuple(self.ids)]) if self._cr.fetchall(): raise ValidationError(_( "This product is already being used in posted Journal Entries.\n" "If you want to change its Unit of Measure, please archive this product and create a new one." )) class ProductProduct(models.Model): _inherit = "product.product" tax_string = fields.Char(compute='_compute_tax_string') def _get_product_accounts(self): return self.product_tmpl_id._get_product_accounts() @api.model def _get_tax_included_unit_price(self, company, currency, document_date, document_type, is_refund_document=False, product_uom=None, product_currency=None, product_price_unit=None, product_taxes=None, fiscal_position=None ): """ Helper to get the price unit from different models. This is needed to compute the same unit price in different models (sale order, account move, etc.) with same parameters. """ product = self assert document_type if product_uom is None: product_uom = product.uom_id if not product_currency: if document_type == 'sale': product_currency = product.currency_id elif document_type == 'purchase': product_currency = company.currency_id if product_price_unit is None: if document_type == 'sale': product_price_unit = product.with_company(company).lst_price elif document_type == 'purchase': product_price_unit = product.with_company(company).standard_price else: return 0.0 if product_taxes is None: if document_type == 'sale': product_taxes = product.taxes_id.filtered(lambda x: x.company_id == company) elif document_type == 'purchase': product_taxes = product.supplier_taxes_id.filtered(lambda x: x.company_id == company) # Apply unit of measure. if product_uom and product.uom_id != product_uom: product_price_unit = product.uom_id._compute_price(product_price_unit, product_uom) # Apply fiscal position. if product_taxes and fiscal_position: product_taxes_after_fp = fiscal_position.map_tax(product_taxes) flattened_taxes_after_fp = product_taxes_after_fp._origin.flatten_taxes_hierarchy() flattened_taxes_before_fp = product_taxes._origin.flatten_taxes_hierarchy() taxes_before_included = all(tax.price_include for tax in flattened_taxes_before_fp) if set(product_taxes.ids) != set(product_taxes_after_fp.ids) and taxes_before_included: taxes_res = flattened_taxes_before_fp.compute_all( product_price_unit, quantity=1.0, currency=currency, product=product, is_refund=is_refund_document, ) product_price_unit = taxes_res['total_excluded'] if any(tax.price_include for tax in flattened_taxes_after_fp): taxes_res = flattened_taxes_after_fp.compute_all( product_price_unit, quantity=1.0, currency=currency, product=product, is_refund=is_refund_document, handle_price_include=False, ) for tax_res in taxes_res['taxes']: tax = self.env['account.tax'].browse(tax_res['id']) if tax.price_include: product_price_unit += tax_res['amount'] # Apply currency rate. if currency != product_currency: product_price_unit = product_currency._convert(product_price_unit, currency, company, document_date) return product_price_unit @api.depends('lst_price', 'product_tmpl_id', 'taxes_id') def _compute_tax_string(self): for record in self: record.tax_string = record.product_tmpl_id._construct_tax_string(record.lst_price)
49.103627
9,477
14,036
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class ResConfigSettings(models.TransientModel): _inherit = 'res.config.settings' has_accounting_entries = fields.Boolean(compute='_compute_has_chart_of_accounts') currency_id = fields.Many2one('res.currency', related="company_id.currency_id", required=True, readonly=False, string='Currency', help="Main currency of the company.") currency_exchange_journal_id = fields.Many2one( comodel_name='account.journal', related='company_id.currency_exchange_journal_id', readonly=False, string="Currency Exchange Journal", domain="[('company_id', '=', company_id), ('type', '=', 'general')]", help='The accounting journal where automatic exchange differences will be registered') income_currency_exchange_account_id = fields.Many2one( comodel_name="account.account", related="company_id.income_currency_exchange_account_id", string="Gain Account", readonly=False, domain=lambda self: "[('internal_type', '=', 'other'), ('deprecated', '=', False), ('company_id', '=', company_id),\ ('user_type_id', 'in', %s)]" % [self.env.ref('account.data_account_type_revenue').id, self.env.ref('account.data_account_type_other_income').id]) expense_currency_exchange_account_id = fields.Many2one( comodel_name="account.account", related="company_id.expense_currency_exchange_account_id", string="Loss Account", readonly=False, domain=lambda self: "[('internal_type', '=', 'other'), ('deprecated', '=', False), ('company_id', '=', company_id),\ ('user_type_id', '=', %s)]" % self.env.ref('account.data_account_type_expenses').id) has_chart_of_accounts = fields.Boolean(compute='_compute_has_chart_of_accounts', string='Company has a chart of accounts') chart_template_id = fields.Many2one('account.chart.template', string='Template', default=lambda self: self.env.company.chart_template_id, domain="[('visible','=', True)]") sale_tax_id = fields.Many2one('account.tax', string="Default Sale Tax", related='company_id.account_sale_tax_id', readonly=False) purchase_tax_id = fields.Many2one('account.tax', string="Default Purchase Tax", related='company_id.account_purchase_tax_id', readonly=False) tax_calculation_rounding_method = fields.Selection( related='company_id.tax_calculation_rounding_method', string='Tax calculation rounding method', readonly=False) account_journal_suspense_account_id = fields.Many2one( comodel_name='account.account', string='Bank Suspense Account', readonly=False, related='company_id.account_journal_suspense_account_id', domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), ('user_type_id.type', 'not in', ('receivable', 'payable')), ('user_type_id', 'in', %s)]" % [self.env.ref('account.data_account_type_current_assets').id, self.env.ref('account.data_account_type_current_liabilities').id], help='Bank Transactions are posted immediately after import or synchronization. ' 'Their counterparty is the bank suspense account.\n' 'Reconciliation replaces the latter by the definitive account(s).') account_journal_payment_debit_account_id = fields.Many2one( comodel_name='account.account', string='Outstanding Receipts Account', readonly=False, related='company_id.account_journal_payment_debit_account_id', domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), ('user_type_id.type', 'not in', ('receivable', 'payable')), ('user_type_id', '=', %s)]" % self.env.ref('account.data_account_type_current_assets').id, help='Incoming payments are posted on an Outstanding Receipts Account. ' 'In the bank reconciliation widget, they appear as blue lines.\n' 'Bank transactions are then reconciled on the Outstanding Receipts Accounts rather than the Receivable ' 'Account.') account_journal_payment_credit_account_id = fields.Many2one( comodel_name='account.account', string='Outstanding Payments Account', readonly=False, related='company_id.account_journal_payment_credit_account_id', domain=lambda self: "[('deprecated', '=', False), ('company_id', '=', company_id), ('user_type_id.type', 'not in', ('receivable', 'payable')), ('user_type_id', '=', %s)]" % self.env.ref('account.data_account_type_current_assets').id, help='Outgoing Payments are posted on an Outstanding Payments Account. ' 'In the bank reconciliation widget, they appear as blue lines.\n' 'Bank transactions are then reconciled on the Outstanding Payments Account rather the Payable Account.') transfer_account_id = fields.Many2one('account.account', string="Internal Transfer Account", related='company_id.transfer_account_id', readonly=False, domain=lambda self: [ ('reconcile', '=', True), ('user_type_id.id', '=', self.env.ref('account.data_account_type_current_assets').id), ('deprecated', '=', False) ], help="Intermediary account used when moving from a liquidity account to another.") module_account_accountant = fields.Boolean(string='Accounting') group_analytic_tags = fields.Boolean(string='Analytic Tags', implied_group='analytic.group_analytic_tags') group_warning_account = fields.Boolean(string="Warnings in Invoices", implied_group='account.group_warning_account') group_cash_rounding = fields.Boolean(string="Cash Rounding", implied_group='account.group_cash_rounding') # group_show_line_subtotals_tax_excluded and group_show_line_subtotals_tax_included are opposite, # so we can assume exactly one of them will be set, and not the other. # We need both of them to coexist so we can take advantage of automatic group assignation. group_show_line_subtotals_tax_excluded = fields.Boolean( "Show line subtotals without taxes (B2B)", implied_group='account.group_show_line_subtotals_tax_excluded', group='base.group_portal,base.group_user,base.group_public') group_show_line_subtotals_tax_included = fields.Boolean( "Show line subtotals with taxes (B2C)", implied_group='account.group_show_line_subtotals_tax_included', group='base.group_portal,base.group_user,base.group_public') group_show_sale_receipts = fields.Boolean(string='Sale Receipt', implied_group='account.group_sale_receipts') group_show_purchase_receipts = fields.Boolean(string='Purchase Receipt', implied_group='account.group_purchase_receipts') show_line_subtotals_tax_selection = fields.Selection([ ('tax_excluded', 'Tax-Excluded'), ('tax_included', 'Tax-Included')], string="Line Subtotals Tax Display", required=True, default='tax_excluded', config_parameter='account.show_line_subtotals_tax_selection') module_account_budget = fields.Boolean(string='Budget Management') module_account_payment = fields.Boolean(string='Invoice Online Payment') module_account_reports = fields.Boolean("Dynamic Reports") module_account_check_printing = fields.Boolean("Allow check printing and deposits") module_account_batch_payment = fields.Boolean(string='Use batch payments', help='This allows you grouping payments into a single batch and eases the reconciliation process.\n' '-This installs the account_batch_payment module.') module_account_sepa = fields.Boolean(string='SEPA Credit Transfer (SCT)') module_account_sepa_direct_debit = fields.Boolean(string='Use SEPA Direct Debit') module_l10n_fr_fec_import = fields.Boolean("Import FEC files", help='Allows you to import FEC files.\n' '-This installs the l10n_fr_fec_import module.') module_account_bank_statement_import_qif = fields.Boolean("Import .qif files") module_account_bank_statement_import_ofx = fields.Boolean("Import in .ofx format") module_account_bank_statement_import_csv = fields.Boolean("Import in .csv format") module_account_bank_statement_import_camt = fields.Boolean("Import in CAMT.053 format") module_currency_rate_live = fields.Boolean(string="Automatic Currency Rates") module_account_intrastat = fields.Boolean(string='Intrastat') module_product_margin = fields.Boolean(string="Allow Product Margin") module_l10n_eu_oss = fields.Boolean(string="EU Intra-community Distance Selling") module_account_taxcloud = fields.Boolean(string="Account TaxCloud") module_account_invoice_extract = fields.Boolean(string="Bill Digitalization") module_snailmail_account = fields.Boolean(string="Snailmail") tax_exigibility = fields.Boolean(string='Cash Basis', related='company_id.tax_exigibility', readonly=False) tax_cash_basis_journal_id = fields.Many2one('account.journal', related='company_id.tax_cash_basis_journal_id', string="Tax Cash Basis Journal", readonly=False) account_cash_basis_base_account_id = fields.Many2one( comodel_name='account.account', string="Base Tax Received Account", readonly=False, related='company_id.account_cash_basis_base_account_id', domain=[('deprecated', '=', False)]) account_fiscal_country_id = fields.Many2one(string="Fiscal Country Code", related="company_id.account_fiscal_country_id", readonly=False, store=False) qr_code = fields.Boolean(string='Display SEPA QR-code', related='company_id.qr_code', readonly=False) invoice_is_print = fields.Boolean(string='Print', related='company_id.invoice_is_print', readonly=False) invoice_is_email = fields.Boolean(string='Send Email', related='company_id.invoice_is_email', readonly=False) incoterm_id = fields.Many2one('account.incoterms', string='Default incoterm', related='company_id.incoterm_id', help='International Commercial Terms are a series of predefined commercial terms used in international transactions.', readonly=False) invoice_terms = fields.Html(related='company_id.invoice_terms', string="Terms & Conditions", readonly=False) invoice_terms_html = fields.Html(related='company_id.invoice_terms_html', string="Terms & Conditions as a Web page", readonly=False) terms_type = fields.Selection( related='company_id.terms_type', readonly=False) preview_ready = fields.Boolean(string="Display preview button", compute='_compute_terms_preview') use_invoice_terms = fields.Boolean( string='Default Terms & Conditions', config_parameter='account.use_invoice_terms') # Technical field to hide country specific fields from accounting configuration country_code = fields.Char(related='company_id.account_fiscal_country_id.code', readonly=True) def set_values(self): super(ResConfigSettings, self).set_values() # install a chart of accounts for the given company (if required) if self.env.company == self.company_id and self.chart_template_id and self.chart_template_id != self.company_id.chart_template_id: self.chart_template_id._load(15.0, 15.0, self.env.company) @api.depends('company_id') def _compute_has_chart_of_accounts(self): self.has_chart_of_accounts = bool(self.company_id.chart_template_id) self.has_accounting_entries = self.env['account.chart.template'].existing_accounting(self.company_id) @api.onchange('show_line_subtotals_tax_selection') def _onchange_sale_tax(self): if self.show_line_subtotals_tax_selection == "tax_excluded": self.update({ 'group_show_line_subtotals_tax_included': False, 'group_show_line_subtotals_tax_excluded': True, }) else: self.update({ 'group_show_line_subtotals_tax_included': True, 'group_show_line_subtotals_tax_excluded': False, }) @api.onchange('group_analytic_accounting') def onchange_analytic_accounting(self): if self.group_analytic_accounting: self.module_account_accountant = True @api.onchange('module_account_budget') def onchange_module_account_budget(self): if self.module_account_budget: self.group_analytic_accounting = True @api.onchange('tax_exigibility') def _onchange_tax_exigibility(self): res = {} tax = self.env['account.tax'].search([ ('company_id', '=', self.env.company.id), ('tax_exigibility', '=', 'on_payment') ], limit=1) if not self.tax_exigibility and tax: self.tax_exigibility = True res['warning'] = { 'title': _('Error!'), 'message': _('You cannot disable this setting because some of your taxes are cash basis. ' 'Modify your taxes first before disabling this setting.') } return res @api.depends('terms_type') def _compute_terms_preview(self): for setting in self: # We display the preview button only if the terms_type is html in the setting but also on the company # to avoid landing on an error page (see terms.py controller) setting.preview_ready = self.env.company.terms_type == 'html' and setting.terms_type == 'html' def action_update_terms(self): self.ensure_one() return { 'name': _('Update Terms & Conditions'), 'type': 'ir.actions.act_window', 'view_mode': 'form', 'res_model': 'res.company', 'view_id': self.env.ref("account.res_company_view_form_terms", False).id, 'target': 'new', 'res_id': self.company_id.id, }
64.682028
14,036
25,975
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, models class AccountMoveLine(models.Model): _inherit = 'account.move.line' @api.model def _get_query_tax_details_from_domain(self, domain, fallback=True): """ Create the tax details sub-query based on the orm domain passed as parameter. :param domain: An orm domain on account.move.line. :param fallback: Fallback on an approximated mapping if the mapping failed. :return: A tuple <query, params>. """ self.env['account.move.line'].check_access_rights('read') query = self.env['account.move.line']._where_calc(domain) # Wrap the query with 'company_id IN (...)' to avoid bypassing company access rights. self.env['account.move.line']._apply_ir_rules(query) tables, where_clause, where_params = query.get_sql() return self._get_query_tax_details(tables, where_clause, where_params, fallback=fallback) @api.model def _get_query_tax_details(self, tables, where_clause, where_params, fallback=True): """ Create the tax details sub-query based on the orm domain passed as parameter. :param tables: The 'tables' query to inject after the FROM. :param where_clause: The 'where_clause' query computed based on an orm domain. :param where_params: The params to fill the 'where_clause' query. :param fallback: Fallback on an approximated mapping if the mapping failed. :return: A tuple <query, params>. """ group_taxes = self.env['account.tax'].search([('amount_type', '=', 'group')]) group_taxes_query_list = [] group_taxes_params = [] for group_tax in group_taxes: children_taxes = group_tax.children_tax_ids if not children_taxes: continue children_taxes_in_query = ','.join('%s' for dummy in children_taxes) group_taxes_query_list.append(f'WHEN tax.id = %s THEN ARRAY[{children_taxes_in_query}]') group_taxes_params.append(group_tax.id) group_taxes_params.extend(children_taxes.ids) if group_taxes_query_list: group_taxes_query = f'''UNNEST(CASE {' '.join(group_taxes_query_list)} ELSE ARRAY[tax.id] END)''' else: group_taxes_query = 'tax.id' if fallback: fallback_query = f''' UNION ALL SELECT account_move_line.id AS tax_line_id, base_line.id AS base_line_id, base_line.id AS src_line_id, base_line.balance AS base_amount, base_line.amount_currency AS base_amount_currency FROM {tables} LEFT JOIN base_tax_line_mapping ON base_tax_line_mapping.tax_line_id = account_move_line.id JOIN account_move_line_account_tax_rel tax_rel ON tax_rel.account_tax_id = COALESCE(account_move_line.group_tax_id, account_move_line.tax_line_id) JOIN account_move_line base_line ON base_line.id = tax_rel.account_move_line_id AND base_line.tax_repartition_line_id IS NULL AND base_line.move_id = account_move_line.move_id AND base_line.currency_id = account_move_line.currency_id WHERE base_tax_line_mapping.tax_line_id IS NULL AND {where_clause} ''' fallback_params = where_params else: fallback_query = '' fallback_params = [] return f''' /* As example to explain the different parts of the query, we'll consider a move with the following lines: Name Tax_line_id Tax_ids Debit Credit Base lines --------------------------------------------------------------------------------------------------- base_line_1 10_affect_base, 20 1000 base_line_2 10_affect_base, 5 2000 base_line_3 10_affect_base, 5 3000 tax_line_1 10_affect_base 20 100 base_line_1 tax_line_2 20 220 base_line_1 tax_line_3 10_affect_base 5 500 base_line_2/3 tax_line_4 5 275 base_line_2/3 */ WITH affecting_base_tax_ids AS ( /* This CTE builds a reference table based on the tax_ids field, with the following changes: - flatten the group of taxes - exclude the taxes having 'is_base_affected' set to False. Those allow to match only base_line_1 when finding the base lines of tax_line_1, as we need to find base lines having a 'affecting_base_tax_ids' ending with [10_affect_base, 20], not only containing '10_affect_base'. Otherwise, base_line_2/3 would also be matched. In our example, as all the taxes are set to be affected by previous ones affecting the base, the result is similar to the table 'account_move_line_account_tax_rel': Id Tax_ids ------------------------------------------- base_line_1 [10_affect_base, 20] base_line_2 [10_affect_base, 5] base_line_3 [10_affect_base, 5] */ SELECT sub.line_id AS id, ARRAY_AGG(sub.tax_id ORDER BY sub.sequence, sub.tax_id) AS tax_ids FROM ( SELECT tax_rel.account_move_line_id AS line_id, {group_taxes_query} AS tax_id, tax.sequence FROM {tables} JOIN account_move_line_account_tax_rel tax_rel ON account_move_line.id = tax_rel.account_move_line_id JOIN account_tax tax ON tax.id = tax_rel.account_tax_id WHERE tax.is_base_affected AND {where_clause} ) AS sub GROUP BY sub.line_id ), base_tax_line_mapping AS ( /* Create the mapping of each tax lines with their corresponding base lines. In the example, it will give the following values: base_line_id tax_line_id base_amount ------------------------------------------- base_line_1 tax_line_1 1000 base_line_1 tax_line_2 1000 base_line_2 tax_line_3 2000 base_line_2 tax_line_4 2000 base_line_3 tax_line_3 3000 base_line_3 tax_line_4 3000 */ SELECT account_move_line.id AS tax_line_id, base_line.id AS base_line_id, base_line.balance AS base_amount, base_line.amount_currency AS base_amount_currency FROM {tables} JOIN account_tax_repartition_line tax_rep ON tax_rep.id = account_move_line.tax_repartition_line_id JOIN account_tax tax ON tax.id = account_move_line.tax_line_id JOIN res_currency curr ON curr.id = account_move_line.currency_id JOIN res_currency comp_curr ON comp_curr.id = account_move_line.company_currency_id JOIN account_move_line_account_tax_rel tax_rel ON tax_rel.account_tax_id = COALESCE(account_move_line.group_tax_id, account_move_line.tax_line_id) JOIN account_move move ON move.id = account_move_line.move_id JOIN account_move_line base_line ON base_line.id = tax_rel.account_move_line_id AND base_line.tax_repartition_line_id IS NULL AND base_line.move_id = account_move_line.move_id AND ( move.move_type != 'entry' OR sign(account_move_line.balance) = sign(base_line.balance * tax.amount * tax_rep.factor_percent) ) AND COALESCE(base_line.partner_id, 0) = COALESCE(account_move_line.partner_id, 0) AND base_line.currency_id = account_move_line.currency_id AND ( COALESCE(tax_rep.account_id, base_line.account_id) = account_move_line.account_id OR (tax.tax_exigibility = 'on_payment' AND tax.cash_basis_transition_account_id IS NOT NULL) ) AND ( NOT tax.analytic OR (base_line.analytic_account_id IS NULL AND account_move_line.analytic_account_id IS NULL) OR base_line.analytic_account_id = account_move_line.analytic_account_id ) LEFT JOIN affecting_base_tax_ids tax_line_tax_ids ON tax_line_tax_ids.id = account_move_line.id JOIN affecting_base_tax_ids base_line_tax_ids ON base_line_tax_ids.id = base_line.id WHERE account_move_line.tax_repartition_line_id IS NOT NULL AND {where_clause} AND ( -- keeping only the rows from affecting_base_tax_lines that end with the same taxes applied (see comment in affecting_base_tax_ids) NOT tax.include_base_amount OR base_line_tax_ids.tax_ids[ARRAY_LENGTH(base_line_tax_ids.tax_ids, 1) - COALESCE(ARRAY_LENGTH(tax_line_tax_ids.tax_ids, 1), 0):ARRAY_LENGTH(base_line_tax_ids.tax_ids, 1)] = ARRAY[account_move_line.tax_line_id] || COALESCE(tax_line_tax_ids.tax_ids, ARRAY[]::INTEGER[]) ) ), tax_amount_affecting_base_to_dispatch AS ( /* Computes the total amount to dispatch in case of tax lines affecting the base of subsequent taxes. Such tax lines are an additional base amount for others lines, that will be truly dispatch in next CTE. In the example: - tax_line_1 is an additional base of 100.0 from base_line_1 for tax_line_2. - tax_line_3 is an additional base of 2/5 * 500.0 = 200.0 from base_line_2 for tax_line_4. - tax_line_3 is an additional base of 3/5 * 500.0 = 300.0 from base_line_3 for tax_line_4. src_line_id base_line_id tax_line_id total_base_amount ------------------------------------------------------------- tax_line_1 base_line_1 tax_line_2 1000 tax_line_3 base_line_2 tax_line_4 5000 tax_line_3 base_line_3 tax_line_4 5000 */ SELECT tax_line.id AS tax_line_id, base_line.id AS base_line_id, account_move_line.id AS src_line_id, tax_line.company_id, comp_curr.id AS company_currency_id, comp_curr.decimal_places AS comp_curr_prec, curr.id AS currency_id, curr.decimal_places AS curr_prec, tax_line.tax_line_id AS tax_id, base_line.balance AS base_amount, SUM( CASE WHEN tax.amount_type = 'fixed' THEN CASE WHEN base_line.balance < 0 THEN -1 ELSE 1 END * ABS(COALESCE(base_line.quantity, 1.0)) ELSE base_line.balance END ) OVER (PARTITION BY tax_line.id, account_move_line.id ORDER BY tax_line.tax_line_id, base_line.id) AS cumulated_base_amount, SUM( CASE WHEN tax.amount_type = 'fixed' THEN CASE WHEN base_line.balance < 0 THEN -1 ELSE 1 END * ABS(COALESCE(base_line.quantity, 1.0)) ELSE base_line.balance END ) OVER (PARTITION BY tax_line.id, account_move_line.id) AS total_base_amount, account_move_line.balance AS total_tax_amount, base_line.amount_currency AS base_amount_currency, SUM( CASE WHEN tax.amount_type = 'fixed' THEN CASE WHEN base_line.amount_currency < 0 THEN -1 ELSE 1 END * ABS(COALESCE(base_line.quantity, 1.0)) ELSE base_line.amount_currency END ) OVER (PARTITION BY tax_line.id, account_move_line.id ORDER BY tax_line.tax_line_id, base_line.id) AS cumulated_base_amount_currency, SUM( CASE WHEN tax.amount_type = 'fixed' THEN CASE WHEN base_line.amount_currency < 0 THEN -1 ELSE 1 END * ABS(COALESCE(base_line.quantity, 1.0)) ELSE base_line.amount_currency END ) OVER (PARTITION BY tax_line.id, account_move_line.id) AS total_base_amount_currency, account_move_line.amount_currency AS total_tax_amount_currency FROM {tables} JOIN account_tax tax_include_base_amount ON tax_include_base_amount.include_base_amount AND tax_include_base_amount.id = account_move_line.tax_line_id JOIN base_tax_line_mapping base_tax_line_mapping ON base_tax_line_mapping.tax_line_id = account_move_line.id JOIN account_move_line_account_tax_rel tax_rel ON tax_rel.account_move_line_id = base_tax_line_mapping.tax_line_id JOIN account_tax tax ON tax.id = tax_rel.account_tax_id JOIN base_tax_line_mapping tax_line_matching ON tax_line_matching.base_line_id = base_tax_line_mapping.base_line_id JOIN account_move_line tax_line ON tax_line.id = tax_line_matching.tax_line_id AND tax_line.tax_line_id = tax_rel.account_tax_id JOIN res_currency curr ON curr.id = tax_line.currency_id JOIN res_currency comp_curr ON comp_curr.id = tax_line.company_currency_id JOIN account_move_line base_line ON base_line.id = base_tax_line_mapping.base_line_id WHERE {where_clause} ), base_tax_matching_base_amounts AS ( /* Build here the full mapping tax lines <=> base lines containing the final base amounts. This is done in a 3-parts union. Note: src_line_id is used only to build a unique ID. */ /* PART 1: raw mapping computed in base_tax_line_mapping. */ SELECT tax_line_id, base_line_id, base_line_id AS src_line_id, base_amount, base_amount_currency FROM base_tax_line_mapping UNION ALL /* PART 2: Dispatch the tax amount of tax lines affecting the base of subsequent ones, using tax_amount_affecting_base_to_dispatch. This will effectively add the following rows: base_line_id tax_line_id src_line_id base_amount ------------------------------------------------------------- base_line_1 tax_line_2 tax_line_1 100 base_line_2 tax_line_4 tax_line_3 200 base_line_3 tax_line_4 tax_line_3 300 */ SELECT sub.tax_line_id, sub.base_line_id, sub.src_line_id, ROUND( COALESCE(SIGN(sub.cumulated_base_amount) * sub.total_tax_amount * ABS(sub.cumulated_base_amount) / NULLIF(sub.total_base_amount, 0.0), 0.0), sub.comp_curr_prec ) - LAG(ROUND( COALESCE(SIGN(sub.cumulated_base_amount) * sub.total_tax_amount * ABS(sub.cumulated_base_amount) / NULLIF(sub.total_base_amount, 0.0), 0.0), sub.comp_curr_prec ), 1, 0.0) OVER ( PARTITION BY sub.tax_line_id, sub.src_line_id ORDER BY sub.tax_id, sub.base_line_id ) AS base_amount, ROUND( COALESCE(SIGN(sub.cumulated_base_amount_currency) * sub.total_tax_amount_currency * ABS(sub.cumulated_base_amount_currency) / NULLIF(sub.total_base_amount_currency, 0.0), 0.0), sub.curr_prec ) - LAG(ROUND( COALESCE(SIGN(sub.cumulated_base_amount_currency) * sub.total_tax_amount_currency * ABS(sub.cumulated_base_amount_currency) / NULLIF(sub.total_base_amount_currency, 0.0), 0.0), sub.curr_prec ), 1, 0.0) OVER ( PARTITION BY sub.tax_line_id, sub.src_line_id ORDER BY sub.tax_id, sub.base_line_id ) AS base_amount_currency FROM tax_amount_affecting_base_to_dispatch sub JOIN account_move_line tax_line ON tax_line.id = sub.tax_line_id /* PART 3: In case of the matching failed because the configuration changed or some journal entries have been imported, construct a simple mapping as a fallback. This mapping is super naive and only build based on the 'tax_ids' and 'tax_line_id' fields, nothing else. Hence, the mapping will not be exact but will give an acceptable approximation. Skipped if the 'fallback' method parameter is False. */ {fallback_query} ), base_tax_matching_all_amounts AS ( /* Complete base_tax_matching_base_amounts with the tax amounts (prorata): base_line_id tax_line_id src_line_id base_amount tax_amount -------------------------------------------------------------------------- base_line_1 tax_line_1 base_line_1 1000 100 base_line_1 tax_line_2 base_line_1 1000 (1000 / 1100) * 220 = 200 base_line_1 tax_line_2 tax_line_1 100 (100 / 1100) * 220 = 20 base_line_2 tax_line_3 base_line_2 2000 (2000 / 5000) * 500 = 200 base_line_2 tax_line_4 base_line_2 2000 (2000 / 5500) * 275 = 100 base_line_2 tax_line_4 tax_line_3 200 (200 / 5500) * 275 = 10 base_line_3 tax_line_3 base_line_3 3000 (3000 / 5000) * 500 = 300 base_line_3 tax_line_4 base_line_3 3000 (3000 / 5500) * 275 = 150 base_line_3 tax_line_4 tax_line_3 300 (300 / 5500) * 275 = 15 */ SELECT sub.tax_line_id, sub.base_line_id, sub.src_line_id, tax_line.tax_line_id AS tax_id, tax_line.group_tax_id, tax_line.tax_repartition_line_id, tax_line.company_id, comp_curr.id AS company_currency_id, comp_curr.decimal_places AS comp_curr_prec, curr.id AS currency_id, curr.decimal_places AS curr_prec, ( tax.tax_exigibility != 'on_payment' OR tax_move.tax_cash_basis_rec_id IS NOT NULL OR tax_move.always_tax_exigible ) AS tax_exigible, base_line.account_id AS base_account_id, sub.base_amount, SUM( CASE WHEN tax.amount_type = 'fixed' THEN CASE WHEN base_line.balance < 0 THEN -1 ELSE 1 END * ABS(COALESCE(base_line.quantity, 1.0)) ELSE sub.base_amount END ) OVER (PARTITION BY tax_line.id ORDER BY tax_line.tax_line_id, sub.base_line_id, sub.src_line_id) AS cumulated_base_amount, SUM( CASE WHEN tax.amount_type = 'fixed' THEN CASE WHEN base_line.balance < 0 THEN -1 ELSE 1 END * ABS(COALESCE(base_line.quantity, 1.0)) ELSE sub.base_amount END ) OVER (PARTITION BY tax_line.id) AS total_base_amount, tax_line.balance AS total_tax_amount, sub.base_amount_currency, SUM( CASE WHEN tax.amount_type = 'fixed' THEN CASE WHEN base_line.amount_currency < 0 THEN -1 ELSE 1 END * ABS(COALESCE(base_line.quantity, 1.0)) ELSE sub.base_amount_currency END ) OVER (PARTITION BY tax_line.id ORDER BY tax_line.tax_line_id, sub.base_line_id, sub.src_line_id) AS cumulated_base_amount_currency, SUM( CASE WHEN tax.amount_type = 'fixed' THEN CASE WHEN base_line.amount_currency < 0 THEN -1 ELSE 1 END * ABS(COALESCE(base_line.quantity, 1.0)) ELSE sub.base_amount_currency END ) OVER (PARTITION BY tax_line.id) AS total_base_amount_currency, tax_line.amount_currency AS total_tax_amount_currency FROM base_tax_matching_base_amounts sub JOIN account_move_line tax_line ON tax_line.id = sub.tax_line_id JOIN account_move tax_move ON tax_move.id = tax_line.move_id JOIN account_move_line base_line ON base_line.id = sub.base_line_id JOIN account_tax tax ON tax.id = tax_line.tax_line_id JOIN res_currency curr ON curr.id = tax_line.currency_id JOIN res_currency comp_curr ON comp_curr.id = tax_line.company_currency_id ) /* Final select that makes sure to deal with rounding errors, using LAG to dispatch the last cents. */ SELECT sub.tax_line_id || '-' || sub.base_line_id || '-' || sub.src_line_id AS id, sub.base_line_id, sub.tax_line_id, sub.src_line_id, sub.tax_id, sub.group_tax_id, sub.tax_exigible, sub.base_account_id, sub.tax_repartition_line_id, sub.base_amount, COALESCE( ROUND( COALESCE(SIGN(sub.cumulated_base_amount) * sub.total_tax_amount * ABS(sub.cumulated_base_amount) / NULLIF(sub.total_base_amount, 0.0), 0.0), sub.comp_curr_prec ) - LAG(ROUND( COALESCE(SIGN(sub.cumulated_base_amount) * sub.total_tax_amount * ABS(sub.cumulated_base_amount) / NULLIF(sub.total_base_amount, 0.0), 0.0), sub.comp_curr_prec ), 1, 0.0) OVER ( PARTITION BY sub.tax_line_id ORDER BY sub.tax_id, sub.base_line_id ), 0.0 ) AS tax_amount, sub.base_amount_currency, COALESCE( ROUND( COALESCE(SIGN(sub.cumulated_base_amount_currency) * sub.total_tax_amount_currency * ABS(sub.cumulated_base_amount_currency) / NULLIF(sub.total_base_amount_currency, 0.0), 0.0), sub.curr_prec ) - LAG(ROUND( COALESCE(SIGN(sub.cumulated_base_amount_currency) * sub.total_tax_amount_currency * ABS(sub.cumulated_base_amount_currency) / NULLIF(sub.total_base_amount_currency, 0.0), 0.0), sub.curr_prec ), 1, 0.0) OVER ( PARTITION BY sub.tax_line_id ORDER BY sub.tax_id, sub.base_line_id ), 0.0 ) AS tax_amount_currency FROM base_tax_matching_all_amounts sub ''', group_taxes_params + where_params + where_params + where_params + fallback_params
52.054108
25,975
1,629
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class AccountAccountTag(models.Model): _name = 'account.account.tag' _description = 'Account Tag' name = fields.Char('Tag Name', required=True) applicability = fields.Selection([('accounts', 'Accounts'), ('taxes', 'Taxes'), ('products', 'Products')], required=True, default='accounts') color = fields.Integer('Color Index') active = fields.Boolean(default=True, help="Set active to false to hide the Account Tag without removing it.") tax_report_line_ids = fields.Many2many(string="Tax Report Lines", comodel_name='account.tax.report.line', relation='account_tax_report_line_tags_rel', help="The tax report lines using this tag") tax_negate = fields.Boolean(string="Negate Tax Balance", help="Check this box to negate the absolute value of the balance of the lines associated with this tag in tax report computation.") country_id = fields.Many2one(string="Country", comodel_name='res.country', help="Country for which this tag is available, when applied on taxes.") @api.model def _get_tax_tags(self, tag_name, country_id): """ Returns all the tax tags corresponding to the tag name given in parameter in the specified country. """ escaped_tag_name = tag_name.replace('\\', '\\\\').replace('%', '\%').replace('_', '\_') domain = [('name', '=like', '_' + escaped_tag_name), ('country_id', '=', country_id), ('applicability', '=', 'taxes')] return self.env['account.account.tag'].with_context(active_test=False).search(domain)
65.16
1,629
23,265
py
PYTHON
15.0
from odoo import api, fields, models, _ from odoo.exceptions import ValidationError from odoo.osv import expression class AccountTaxReport(models.Model): _name = "account.tax.report" _description = 'Account Tax Report' _order = 'country_id, name' name = fields.Char(string="Name", required=True, help="Name of this tax report") country_id = fields.Many2one(string="Country", comodel_name='res.country', required=True, default=lambda x: x.env.company.country_id.id, help="Country for which this report is available.") line_ids = fields.One2many(string="Report Lines", comodel_name='account.tax.report.line', inverse_name='report_id', help="Content of this tax report") root_line_ids = fields.One2many(string="Root Report Lines", comodel_name='account.tax.report.line', inverse_name='report_id', domain=[('parent_id', '=', None)], help="Subset of line_ids, containing the lines at the root of the report.") def write(self, vals): # Overridden so that we change the country _id of the existing tags # when writing the country_id of the report, or create new tags # for the new country if the tags are shared with some other report. if 'country_id' in vals: tags_cache = {} for record in self.filtered(lambda x: x.country_id.id != vals['country_id']): for line in record.line_ids: if line.tag_ids: #The tags for this country may have been created by a previous line in this loop cache_key = (vals['country_id'], line.tag_name) if cache_key not in tags_cache: tags_cache[cache_key] = self.env['account.account.tag']._get_tax_tags(line.tag_name, vals['country_id']) new_tags = tags_cache[cache_key] if len(new_tags) == 2: line._remove_tags_used_only_by_self() line.write({'tag_ids': [(6, 0, new_tags.ids)]}) elif line.mapped('tag_ids.tax_report_line_ids.report_id').filtered(lambda x: x not in self): line._remove_tags_used_only_by_self() line.write({'tag_ids': [(5, 0, 0)] + line._get_tags_create_vals(line.tag_name, vals['country_id'], existing_tag=new_tags)}) tags_cache[cache_key] = line.tag_ids else: line.tag_ids.write({'country_id': vals['country_id']}) return super(AccountTaxReport, self).write(vals) def copy(self, default=None): # Overridden from regular copy, since the ORM does not manage # the copy of the lines hierarchy properly (all the parent_id fields # need to be reassigned to the corresponding copies). copy_default = {k:v for k, v in default.items() if k != 'line_ids'} if default else None copied_report = super(AccountTaxReport, self).copy(default=copy_default) #This copies the report without its lines lines_map = {} # maps original lines to their copies (using ids) for line in self.get_lines_in_hierarchy(): copy = line.copy({'parent_id': lines_map.get(line.parent_id.id, None), 'report_id': copied_report.id}) lines_map[line.id] = copy.id return copied_report def get_lines_in_hierarchy(self): """ Returns an interator to the lines of this tax report, were parent lines ar all directly followed by their children. """ self.ensure_one() lines_to_treat = list(self.line_ids.filtered(lambda x: not x.parent_id)) # Used as a stack, whose index 0 is the top while lines_to_treat: to_yield = lines_to_treat[0] lines_to_treat = list(to_yield.children_line_ids) + lines_to_treat[1:] yield to_yield def get_checks_to_perform(self, amounts, carried_over): """ To override in localizations If value is a float, it will be formatted with format_value The line is not displayed if it is falsy (0, 0.0, False, ...) :param amounts: the mapping dictionary between codes and values :param carried_over: the mapping dictionary between codes and whether they are carried over :return: iterable of tuple (name, value) """ self.ensure_one() return [] def validate_country_id(self): for record in self: if any(line.tag_ids.mapped('country_id') != record.country_id for line in record.line_ids): raise ValidationError(_("The tags associated with tax report line objects should all have the same country set as the tax report containing these lines.")) class AccountTaxReportLine(models.Model): _name = "account.tax.report.line" _description = 'Account Tax Report Line' _order = 'sequence, id' _parent_store = True name = fields.Char(string="Name", required=True, help="Complete name for this report line, to be used in report.") tag_ids = fields.Many2many(string="Tags", comodel_name='account.account.tag', relation='account_tax_report_line_tags_rel', help="Tax tags populating this line") report_action_id = fields.Many2one(string="Report Action", comodel_name='ir.actions.act_window', help="The optional action to call when clicking on this line in accounting reports.") children_line_ids = fields.One2many(string="Children Lines", comodel_name='account.tax.report.line', inverse_name='parent_id', help="Lines that should be rendered as children of this one") parent_id = fields.Many2one(string="Parent Line", comodel_name='account.tax.report.line') sequence = fields.Integer(string='Sequence', required=True, help="Sequence determining the order of the lines in the report (smaller ones come first). This order is applied locally per section (so, children of the same line are always rendered one after the other).") parent_path = fields.Char(index=True) report_id = fields.Many2one(string="Tax Report", required=True, comodel_name='account.tax.report', ondelete='cascade', help="The parent tax report of this line") # helper to create tags (positive and negative) on report line creation tag_name = fields.Char(string="Tag Name", help="Short name for the tax grid corresponding to this report line. Leave empty if this report line should not correspond to any such grid.") # fields used in specific localization reports, where a report line isn't simply the given by the sum of account.move.line with selected tags code = fields.Char(string="Code", help="Optional unique code to refer to this line in total formulas") formula = fields.Char(string="Formula", help="Python expression used to compute the value of a total line. This field is mutually exclusive with tag_name, setting it turns the line to a total line. Tax report line codes can be used as variables in this expression to refer to the balance of the corresponding lines in the report. A formula cannot refer to another line using a formula.") # fields used to carry over amounts between periods # The selection should be filled in localizations using the system carry_over_condition_method = fields.Selection( selection=[ ('no_negative_amount_carry_over_condition', 'No negative amount'), ('always_carry_over_and_set_to_0', 'Always carry over and set to 0'), ], string="Method", help="The method used to determine if this line should be carried over." ) carry_over_destination_line_id = fields.Many2one( string="Destination", comodel_name="account.tax.report.line", domain="[('report_id', '=', report_id)]", help="The line to which the value of this line will be carried over to if needed." " If left empty the line will carry over to itself." ) carryover_line_ids = fields.One2many( string="Carryover lines", comodel_name='account.tax.carryover.line', inverse_name='tax_report_line_id', ) is_carryover_persistent = fields.Boolean( string="Persistent", help="Defines how this report line creates carry over lines when performing tax closing. " "If true, the amounts carried over will always be added on top of each other: " "for example, a report line with a balance of 10 with an existing carryover of 50 " "will add an additional 10 to it when doing the closing, making a total carryover of 60. " "If false, the total carried over amount will be forced to the total of this report line: " "a report line with a balance of 10 with an existing carryover of 50 will create a new " "carryover line of -40, so that the total carryover becomes 10.", default=True, ) is_carryover_used_in_balance = fields.Boolean( string="Used in line balance", help="If set, the carryover amount for this line will be used when calculating its balance in the report. " "This means that the carryover could affect other lines if they are using this one in their computation." ) @api.model def create(self, vals): # Manage tags tag_name = vals.get('tag_name', '') if tag_name and vals.get('report_id'): report = self.env['account.tax.report'].browse(vals['report_id']) country = report.country_id existing_tags = self.env['account.account.tag']._get_tax_tags(tag_name, country.id) if len(existing_tags) < 2: # We create new one(s) # We can have only one tag in case we archived it and deleted its unused complement sign vals['tag_ids'] = self._get_tags_create_vals(tag_name, country.id, existing_tag=existing_tags) else: # We connect the new report line to the already existing tags vals['tag_ids'] = [(6, 0, existing_tags.ids)] return super(AccountTaxReportLine, self).create(vals) @api.model def _get_tags_create_vals(self, tag_name, country_id, existing_tag=None): """ We create the plus and minus tags with tag_name. In case there is an existing_tag (which can happen if we deleted its unused complement sign) we only recreate the missing sign. """ minus_tag_vals = { 'name': '-' + tag_name, 'applicability': 'taxes', 'tax_negate': True, 'country_id': country_id, } plus_tag_vals = { 'name': '+' + tag_name, 'applicability': 'taxes', 'tax_negate': False, 'country_id': country_id, } res = [] if not existing_tag or not existing_tag.tax_negate: res.append((0, 0, minus_tag_vals)) if not existing_tag or existing_tag.tax_negate: res.append((0, 0, plus_tag_vals)) return res def write(self, vals): # If tag_name was set, but not tag_ids, we postpone the write of # tag_name, and perform it only after having generated/retrieved the tags. # Otherwise, tag_name and tags' name would not match, breaking # _validate_tags constaint. postponed_vals = {} if 'tag_name' in vals and 'tag_ids' not in vals: postponed_vals = {'tag_name': vals.pop('tag_name')} tag_name_postponed = postponed_vals['tag_name'] # if tag_name is posponed then we also postpone formula to avoid # breaking _validate_formula constraint if 'formula' in vals: postponed_vals['formula'] = vals.pop('formula') rslt = super(AccountTaxReportLine, self).write(vals) if postponed_vals: # If tag_name modification has been postponed, # we need to search for existing tags corresponding to the new tag name # (or create them if they don't exist yet) and assign them to the records records_by_country = {} for record in self.filtered(lambda x: x.tag_name != tag_name_postponed): records_by_country[record.report_id.country_id.id] = records_by_country.get(record.report_id.country_id.id, self.env['account.tax.report.line']) + record for country_id, records in records_by_country.items(): if tag_name_postponed: record_tag_names = records.mapped('tag_name') if len(record_tag_names) == 1 and record_tag_names[0]: # If all the records already have the same tag_name before writing, # we simply want to change the name of the existing tags to_update = records.mapped('tag_ids.tax_report_line_ids') tags_to_update = to_update.mapped('tag_ids') minus_child_tags = tags_to_update.filtered(lambda x: x.tax_negate) minus_child_tags.write({'name': '-' + tag_name_postponed}) plus_child_tags = tags_to_update.filtered(lambda x: not x.tax_negate) plus_child_tags.write({'name': '+' + tag_name_postponed}) super(AccountTaxReportLine, to_update).write(postponed_vals) else: existing_tags = self.env['account.account.tag']._get_tax_tags(tag_name_postponed, country_id) records_to_link = records tags_to_remove = self.env['account.account.tag'] if len(existing_tags) < 2 and records_to_link: # If the tag does not exist yet (or if we only have one of the two +/-), # we first create it by linking it to the first report line of the record set first_record = records_to_link[0] tags_to_remove += first_record.tag_ids first_record.write({**postponed_vals, 'tag_ids': [(5, 0, 0)] + self._get_tags_create_vals(tag_name_postponed, country_id, existing_tag=existing_tags)}) existing_tags = first_record.tag_ids records_to_link -= first_record # All the lines sharing their tags must always be synchronized, tags_to_remove += records_to_link.mapped('tag_ids') records_to_link = tags_to_remove.mapped('tax_report_line_ids') tags_to_remove.mapped('tax_report_line_ids')._remove_tags_used_only_by_self() records_to_link.write({**postponed_vals, 'tag_ids': [(2, tag.id) for tag in tags_to_remove] + [(6, 0, existing_tags.ids)]}) else: # tag_name was set empty, so we remove the tags on current lines # If some tags are still referenced by other report lines, # we keep them ; else, we delete them from DB line_tags = records.mapped('tag_ids') other_lines_same_tag = line_tags.mapped('tax_report_line_ids').filtered(lambda x: x not in records) if not other_lines_same_tag: self._delete_tags_from_taxes(line_tags.ids) orm_cmd_code = other_lines_same_tag and 3 or 2 records.write({**postponed_vals, 'tag_ids': [(orm_cmd_code, tag.id) for tag in line_tags]}) return rslt def unlink(self): self._remove_tags_used_only_by_self() children = self.mapped('children_line_ids') if children: children.unlink() return super(AccountTaxReportLine, self).unlink() def _remove_tags_used_only_by_self(self): """ Deletes and removes from taxes and move lines all the tags from the provided tax report lines that are not linked to any other tax report lines nor move lines. The tags that are used by at least one move line will be archived instead, to avoid loosing history. """ all_tags = self.mapped('tag_ids') tags_to_unlink = all_tags.filtered(lambda x: not (x.tax_report_line_ids - self)) self.write({'tag_ids': [(3, tag.id, 0) for tag in tags_to_unlink]}) for tag in tags_to_unlink: aml_using_tags = self.env['account.move.line'].sudo().search([('tax_tag_ids', 'in', tag.id)], limit=1) # if the tag is still referenced in move lines we archive the tag, else we delete it. if aml_using_tags: rep_lines_with_archived_tags = self.env['account.tax.repartition.line'].sudo().search([('tag_ids', 'in', tag.id)]) rep_lines_with_archived_tags.write({'tag_ids': [(3, tag.id)]}) tag.active = False else: self._delete_tags_from_taxes([tag.id]) @api.model def _delete_tags_from_taxes(self, tag_ids_to_delete): """ Based on a list of tag ids, removes them first from the repartition lines they are linked to, then deletes them from the account move lines, and finally unlink them. """ if not tag_ids_to_delete: # Nothing to do, then! return self.env.cr.execute(""" delete from account_account_tag_account_tax_repartition_line_rel where account_account_tag_id in %(tag_ids_to_delete)s; delete from account_account_tag_account_move_line_rel where account_account_tag_id in %(tag_ids_to_delete)s; """, {'tag_ids_to_delete': tuple(tag_ids_to_delete)}) self.env['account.move.line'].invalidate_cache(fnames=['tax_tag_ids']) self.env['account.tax.repartition.line'].invalidate_cache(fnames=['tag_ids']) self.env['account.account.tag'].browse(tag_ids_to_delete).unlink() @api.constrains('formula', 'tag_name') def _validate_formula(self): for record in self: if record.formula and record.tag_name: raise ValidationError(_("Tag name and formula are mutually exclusive, they should not be set together on the same tax report line.")) @api.constrains('tag_name', 'tag_ids') def _validate_tags(self): for record in self.filtered(lambda x: x.tag_ids): neg_tags = record.tag_ids.filtered(lambda x: x.tax_negate) pos_tags = record.tag_ids.filtered(lambda x: not x.tax_negate) if (len(neg_tags) > 1 or len(pos_tags) > 1): raise ValidationError(_("If tags are defined for a tax report line, only two are allowed on it: a positive and/or a negative one.")) if (neg_tags and neg_tags.name != '-'+record.tag_name) or (pos_tags and pos_tags.name != '+'+record.tag_name): raise ValidationError(_("The tags linked to a tax report line should always match its tag name.")) def action_view_carryover_lines(self, options): ''' Action when clicking on the "View carryover lines" in the carryover info popup. Takes into account the report options, to get the correct lines depending on the current company/companies. :return: An action showing the account.tax.carryover.lines for the current tax report line. ''' self.ensure_one() target = self._get_carryover_destination_line(options) domain = target._get_carryover_lines_domain(options) carryover_lines = self.env['account.tax.carryover.line'].search(domain) return { 'type': 'ir.actions.act_window', 'name': _('Carryover Lines For %s', target.name), 'res_model': 'account.tax.carryover.line', 'view_type': 'list', 'view_mode': 'list', 'views': [[self.env.ref('account.account_tax_carryover_line_tree').id, 'list'], [False, 'form']], 'domain': [('id', 'in', carryover_lines.ids)], } def _get_carryover_bounds(self, options, line_amount, carried_over_amount): """ Check if the line will be carried over, by checking the condition method set on the line. Do not override this method, but instead set your condition methods on each lines. :param options: The options of the reports :param line_amount: The amount on the line :param carried_over_amount: The amount carried over for this line :return: A tuple containing the lower and upper bounds from which the line will be carried over. E.g. (0, 42) : Lines which value is below 0 or above 42 will be carried over. E.g. (0, None) : Only lines which value is below 0 will be carried over. E.g. None : This line will never be carried over. """ self.ensure_one() # Carry over is disabled by default, but if there is a carry over condition method on the line we are # calling it first. That way we can have a default carryover condition for the whole report (carryover_bounds) # and specialized condition for specific lines if needed if self.carry_over_condition_method: condition_method = getattr(self, self.carry_over_condition_method, False) if condition_method: return condition_method(options, line_amount, carried_over_amount) return None def _get_carryover_lines_domain(self, options): """ :param options: The report options :return: The domain that can be used to search for carryover lines for this tax report line. Using this domain instead of directly accessing the lines ensure that we only pick the ones related to the companies affecting the tax report. """ self.ensure_one() domain = [('tax_report_line_id', '=', self.id)] if options.get('multi_company'): company_ids = [company['id'] for company in options['multi_company']] domain = expression.AND([domain, [('company_id', 'in', company_ids)]]) else: domain = expression.AND([domain, [('company_id', '=', self.env.company.id)]]) return domain def no_negative_amount_carry_over_condition(self, options, line_amount, carried_over_amount): # The bounds are (0, None). # Lines below 0 will be set to 0 and reduce the balance of the carryover. # Lines above 0 will never be carried over return (0, None) def always_carry_over_and_set_to_0(self, options, line_amount, carried_over_amount): # The bounds are (0, 0). # Lines below 0 will be set to 0 and reduce the balance of the carryover. # Lines above 0 will be set to 0 and increase the balance of the carryover. return (0, 0) def _get_carryover_destination_line(self, options): """ Return the destination line for the carryover for this tax report line. :param options: The options of the tax report. :return: The line on which we'll carryover this tax report line when closing the tax period. """ self.ensure_one() return self.carry_over_destination_line_id or self
54.870283
23,265
1,555
py
PYTHON
15.0
from odoo import api, fields, models, _ from odoo.exceptions import ValidationError class AccountTaxCarryoverLine(models.Model): _name = 'account.tax.carryover.line' _description = 'Tax carryover line' name = fields.Char(required=True) amount = fields.Float(required=True, default=0.0) date = fields.Date(required=True, default=fields.Date.context_today) tax_report_line_id = fields.Many2one( comodel_name='account.tax.report.line', string="Tax report line", ) tax_report_id = fields.Many2one(related='tax_report_line_id.report_id') tax_report_country_id = fields.Many2one(related='tax_report_id.country_id') company_id = fields.Many2one( comodel_name='res.company', string='Company', required=True, default=lambda self: self.env.company, ) foreign_vat_fiscal_position_id = fields.Many2one( comodel_name='account.fiscal.position', string="Fiscal position", help="The foreign fiscal position for which this carryover is made.", domain="[('company_id', '=', company_id), " "('country_id', '=', tax_report_country_id), " "('foreign_vat', '!=', False)]", ) @api.constrains('foreign_vat_fiscal_position_id') def _check_fiscal_position(self): if self.foreign_vat_fiscal_position_id and not self.foreign_vat_fiscal_position_id.country_id == self.tax_report_country_id: raise ValidationError(_("The country of the fiscal position must be this report line's report country."))
43.194444
1,555
1,717
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ class AccountFullReconcile(models.Model): _name = "account.full.reconcile" _description = "Full Reconcile" name = fields.Char(string='Number', required=True, copy=False, default=lambda self: self.env['ir.sequence'].next_by_code('account.reconcile')) partial_reconcile_ids = fields.One2many('account.partial.reconcile', 'full_reconcile_id', string='Reconciliation Parts') reconciled_line_ids = fields.One2many('account.move.line', 'full_reconcile_id', string='Matched Journal Items') exchange_move_id = fields.Many2one('account.move', index=True) def unlink(self): """ When removing a full reconciliation, we need to revert the eventual journal entries we created to book the fluctuation of the foreign currency's exchange rate. We need also to reconcile together the origin currency difference line and its reversal in order to completely cancel the currency difference entry on the partner account (otherwise it will still appear on the aged balance for example). """ # Avoid cyclic unlink calls when removing partials. if not self: return True moves_to_reverse = self.exchange_move_id res = super().unlink() # Reverse all exchange moves at once. if moves_to_reverse: default_values_list = [{ 'date': move._get_accounting_date(move.date, move._affect_tax_report()), 'ref': _('Reversal of: %s') % move.name, } for move in moves_to_reverse] moves_to_reverse._reverse_moves(default_values_list, cancel=True) return res
46.405405
1,717
97,695
py
PYTHON
15.0
# -*- coding: utf-8 -*- from collections import defaultdict from odoo.exceptions import AccessError from odoo import api, fields, models, _ from odoo import SUPERUSER_ID from odoo.exceptions import UserError, ValidationError from odoo.http import request from odoo.addons.account.models.account_tax import TYPE_TAX_USE from odoo.tools import html_escape import logging _logger = logging.getLogger(__name__) def migrate_set_tags_and_taxes_updatable(cr, registry, module): ''' This is a utility function used to manually set the flag noupdate to False on tags and account tax templates on localization modules that need migration (for example in case of VAT report improvements) ''' env = api.Environment(cr, SUPERUSER_ID, {}) xml_record_ids = env['ir.model.data'].search([ ('model', 'in', ['account.tax.template', 'account.account.tag']), ('module', 'like', module) ]).ids if xml_record_ids: cr.execute("update ir_model_data set noupdate = 'f' where id in %s", (tuple(xml_record_ids),)) def preserve_existing_tags_on_taxes(cr, registry, module): ''' This is a utility function used to preserve existing previous tags during upgrade of the module.''' env = api.Environment(cr, SUPERUSER_ID, {}) xml_records = env['ir.model.data'].search([('model', '=', 'account.account.tag'), ('module', 'like', module)]) if xml_records: cr.execute("update ir_model_data set noupdate = 't' where id in %s", [tuple(xml_records.ids)]) def update_taxes_from_templates(cr, chart_template_xmlid): """ This method will try to update taxes based on their template. Schematically there are three possible execution path: [do the template xmlid matches one tax xmlid ?] -NO--> we *create* a new tax based on the template values -YES-> [are the tax template and the matching tax similar enough (details see `_is_tax_and_template_same`) ?] -YES-> We *update* the existing tax's tag (and only tags). -NO--> We *create* a duplicated tax with template value, and related fiscal positions. This method is mainly used as a local upgrade script. Returns a list of tuple (template_id, tax_id) of newly created records. """ def _create_taxes_from_template(company, template2tax_mapping): """ Create a new taxes from templates. If an old tax already used the same xmlid, we remove the xmlid from it but don't modify anything else. :param company: the company of the tax to instantiate :param template2tax_mapping: a list of tuples (template, existing_tax) where existing_tax can be None :return: a list of tuples of ids (template.id, newly_created_tax.id) """ def _remove_xml_id(xml_id): module, name = xml_id.split('.', 1) env['ir.model.data'].search([('module', '=', module), ('name', '=', name)]).unlink() def _avoid_name_conflict(company, template): conflict_taxes = env['account.tax'].search([ ('name', '=', template.name), ('company_id', '=', company.id), ('type_tax_use', '=', template.type_tax_use), ('tax_scope', '=', template.tax_scope) ]) if conflict_taxes: for index, conflict_taxes in enumerate(conflict_taxes): conflict_taxes.name = f"[old{index if index > 0 else ''}] {conflict_taxes.name}" templates_to_create = env['account.tax.template'].with_context(active_test=False) for template, old_tax in template2tax_mapping: if old_tax: xml_id = old_tax.get_external_id().get(old_tax.id) if xml_id: _remove_xml_id(xml_id) _avoid_name_conflict(company, template) templates_to_create += template new_template2tax_company = templates_to_create._generate_tax(company, accounts_exist=True)['tax_template_to_tax'] return [(template.id, tax.id) for template, tax in new_template2tax_company.items()] def _update_taxes_from_template(template2tax_mapping): """ Update the taxes' tags (and only tags!) based on their corresponding template values. :param template2tax_mapping: a list of tuples (template, existing_taxes) """ for template, existing_tax in template2tax_mapping: tax_rep_lines = existing_tax.invoice_repartition_line_ids + existing_tax.refund_repartition_line_ids template_rep_lines = template.invoice_repartition_line_ids + template.refund_repartition_line_ids for tax_line, template_line in zip(tax_rep_lines, template_rep_lines): tags_to_add = template_line._get_tags_to_add() tags_to_unlink = tax_line.tag_ids if tags_to_add != tags_to_unlink: tax_line.write({'tag_ids': [(6, 0, tags_to_add.ids)]}) _cleanup_tags(tags_to_unlink) def _get_template_to_real_xmlid_mapping(model, templates): """ This function uses ir_model_data to return a mapping between the templates and the data, using their xmlid :returns: { company_id: { model.template.id1: model.id1, model.template.id2: model.id2 }, ... } """ template_xmlids = [xmlid.split('.', 1)[1] for xmlid in templates.get_external_id().values()] res = defaultdict(dict) if not template_xmlids: return res env['ir.model.data'].flush() env.cr.execute( """ SELECT substr(data.name, 0, strpos(data.name, '_'))::INTEGER AS data_company_id, template.res_id AS template_res_id, data.res_id AS data_res_id FROM ir_model_data data JOIN ir_model_data template ON template.name = substr(data.name, strpos(data.name, '_') + 1) WHERE data.model = %s AND template.name IN %s -- tax.name is of the form: {company_id}_{account.tax.template.name} """, [model, tuple(template_xmlids)], ) for company_id, template_id, model_id in env.cr.fetchall(): res[company_id][template_id] = model_id return res def _is_tax_and_template_same(template, tax): """ This function compares account.tax and account.tax.template repartition lines. A tax is considered the same as the template if they have the same: - amount_type - amount - repartition lines percentages in the same order """ if tax.amount_type == 'group': # if the amount_type is group we don't do checks on rep. lines nor amount return tax.amount_type == template.amount_type else: tax_rep_lines = tax.invoice_repartition_line_ids + tax.refund_repartition_line_ids template_rep_lines = template.invoice_repartition_line_ids + template.refund_repartition_line_ids return ( tax.amount_type == template.amount_type and tax.amount == template.amount and ( len(tax_rep_lines) == len(template_rep_lines) and all( rep_line_tax.factor_percent == rep_line_template.factor_percent for rep_line_tax, rep_line_template in zip(tax_rep_lines, template_rep_lines) ) ) ) def _cleanup_tags(tags): """ Checks if the tags are still used in taxes or move lines. If not we delete it. """ for tag in tags: tax_using_tag = env['account.tax.repartition.line'].sudo().search([('tag_ids', 'in', tag.id)], limit=1) aml_using_tag = env['account.move.line'].sudo().search([('tax_tag_ids', 'in', tag.id)], limit=1) report_line_using_tag = env['account.tax.report.line'].sudo().search([('tag_ids', 'in', tag.id)], limit=1) if not (aml_using_tag or tax_using_tag or report_line_using_tag): tag.unlink() def _update_fiscal_positions_from_templates(chart_template, new_tax_template_by_company, all_tax_templates): fp_templates = env['account.fiscal.position.template'].search([('chart_template_id', '=', chart_template.id)]) template2tax = _get_template_to_real_xmlid_mapping('account.tax', all_tax_templates) template2fp = _get_template_to_real_xmlid_mapping('account.fiscal.position', fp_templates) for company_id in new_tax_template_by_company: fp_tax_template_vals = [] template2fp_company = template2fp.get(company_id) for position_template in fp_templates: fp = env['account.fiscal.position'].browse(template2fp_company.get(position_template.id)) if template2fp_company else None if not fp: continue for position_tax in position_template.tax_ids: position_tax_template_exist = fp.tax_ids.filtered( lambda tax_fp: tax_fp.tax_src_id.id == template2tax.get(company_id).get(position_tax.tax_src_id.id) and tax_fp.tax_dest_id.id == (position_tax.tax_dest_id and template2tax.get(company_id).get(position_tax.tax_dest_id.id) or False) ) if not position_tax_template_exist and ( position_tax.tax_src_id in new_tax_template_by_company[company_id] or position_tax.tax_dest_id in new_tax_template_by_company[company_id] ): fp_tax_template_vals.append((position_tax, { 'tax_src_id': template2tax.get(company_id).get(position_tax.tax_src_id.id), 'tax_dest_id': position_tax.tax_dest_id and template2tax.get(company_id).get(position_tax.tax_dest_id.id) or False, 'position_id': fp.id, })) chart_template._create_records_with_xmlid('account.fiscal.position.tax', fp_tax_template_vals, env['res.company'].browse(company_id)) def _process_taxes_translations(chart_template, new_template_x_taxes): """ Retrieve translations for newly created taxes' name and description for languages of the chart_template. Those languages are the intersection of the spoken_languages of the chart_template and installed languages. """ if not new_template_x_taxes: return langs = chart_template._get_langs() if langs: template_ids, tax_ids = zip(*new_template_x_taxes) in_ids = env['account.tax.template'].browse(template_ids) out_ids = env['account.tax'].browse(tax_ids) chart_template.process_translations(langs, 'name', in_ids, out_ids) chart_template.process_translations(langs, 'description', in_ids, out_ids) def _notify_accountant_managers(taxes_to_check): accountant_manager_group = env.ref("account.group_account_manager") partner_managers_ids = accountant_manager_group.users.partner_id.ids odoobot_id = env.ref('base.partner_root').id message_body = _( "Please check these taxes. They might be outdated. We did not update them. " "Indeed, they do not exactly match the taxes of the original version of the localization module.<br/>" "You might want to archive or adapt them.<br/><ul>" ) for account_tax in taxes_to_check: message_body += f"<li>{html_escape(account_tax.name)}</li>" message_body += "</ul>" env['mail.thread'].message_notify( subject=_('Your taxes have been updated !'), author_id=odoobot_id, body=message_body, partner_ids=partner_managers_ids, ) def _validate_taxes_country(chart_template, template2tax): """ Checks that existing taxes' country are either compatible with the company's fiscal country, or with the chart_template's country. """ for company_id in template2tax: company = env['res.company'].browse(company_id) for template_id in template2tax[company_id]: tax = env['account.tax'].browse(template2tax[company_id][template_id]) if (not chart_template.country_id or tax.country_id != chart_template.country_id) and tax.country_id != company.account_fiscal_country_id: raise ValidationError(_("Please check the fiscal country of company %s. (Settings > Accounting > Fiscal Country)" "Taxes can only be updated if they are in the company's fiscal country (%s) or the localization's country (%s).", company.name, company.account_fiscal_country_id.name, chart_template.country_id.name)) env = api.Environment(cr, SUPERUSER_ID, {}) chart_template = env.ref(chart_template_xmlid) companies = env['res.company'].search([('chart_template_id', 'child_of', chart_template.id)]) templates = env['account.tax.template'].with_context(active_test=False).search([('chart_template_id', '=', chart_template.id)]) template2tax = _get_template_to_real_xmlid_mapping('account.tax', templates) # adds companies that use the chart_template through fiscal position system companies = companies.union(env['res.company'].browse(template2tax.keys())) outdated_taxes = env['account.tax'] new_tax_template_by_company = defaultdict(env['account.tax.template'].browse) # only contains completely new taxes (not previous taxe had the xmlid) new_template2tax = [] # contains all created taxes _validate_taxes_country(chart_template, template2tax) for company in companies: templates_to_tax_create = [] templates_to_tax_update = [] template2oldtax_company = template2tax.get(company.id) for template in templates: tax = env['account.tax'].browse(template2oldtax_company.get(template.id)) if template2oldtax_company else None if not tax or not _is_tax_and_template_same(template, tax): templates_to_tax_create.append((template, tax)) if tax: outdated_taxes += tax else: # we only want to update fiscal position if there is no previous tax with the mapping new_tax_template_by_company[company.id] += template else: templates_to_tax_update.append((template, tax)) new_template2tax += _create_taxes_from_template(company, templates_to_tax_create) _update_taxes_from_template(templates_to_tax_update) _update_fiscal_positions_from_templates(chart_template, new_tax_template_by_company, templates) if outdated_taxes: _notify_accountant_managers(outdated_taxes) if hasattr(chart_template, 'spoken_languages') and chart_template.spoken_languages: _process_taxes_translations(chart_template, new_template2tax) return new_template2tax # --------------------------------------------------------------- # Account Templates: Account, Tax, Tax Code and chart. + Wizard # --------------------------------------------------------------- class AccountGroupTemplate(models.Model): _name = "account.group.template" _description = 'Template for Account Groups' _order = 'code_prefix_start' parent_id = fields.Many2one('account.group.template', index=True, ondelete='cascade') name = fields.Char(required=True) code_prefix_start = fields.Char() code_prefix_end = fields.Char() chart_template_id = fields.Many2one('account.chart.template', string='Chart Template', required=True) class AccountAccountTemplate(models.Model): _name = "account.account.template" _inherit = ['mail.thread'] _description = 'Templates for Accounts' _order = "code" name = fields.Char(required=True, index=True) currency_id = fields.Many2one('res.currency', string='Account Currency', help="Forces all moves for this account to have this secondary currency.") code = fields.Char(size=64, required=True, index=True) user_type_id = fields.Many2one('account.account.type', string='Type', required=True, help="These types are defined according to your country. The type contains more information "\ "about the account and its specificities.") reconcile = fields.Boolean(string='Allow Invoices & payments Matching', default=False, help="Check this option if you want the user to reconcile entries in this account.") note = fields.Text() tax_ids = fields.Many2many('account.tax.template', 'account_account_template_tax_rel', 'account_id', 'tax_id', string='Default Taxes') nocreate = fields.Boolean(string='Optional Create', default=False, help="If checked, the new chart of accounts will not contain this by default.") chart_template_id = fields.Many2one('account.chart.template', string='Chart Template', help="This optional field allow you to link an account template to a specific chart template that may differ from the one its root parent belongs to. This allow you " "to define chart templates that extend another and complete it with few new accounts (You don't need to define the whole structure that is common to both several times).") tag_ids = fields.Many2many('account.account.tag', 'account_account_template_account_tag', string='Account tag', help="Optional tags you may want to assign for custom reporting") @api.depends('name', 'code') def name_get(self): res = [] for record in self: name = record.name if record.code: name = record.code + ' ' + name res.append((record.id, name)) return res class AccountChartTemplate(models.Model): _name = "account.chart.template" _description = "Account Chart Template" name = fields.Char(required=True) parent_id = fields.Many2one('account.chart.template', string='Parent Chart Template') code_digits = fields.Integer(string='# of Digits', required=True, default=6, help="No. of Digits to use for account code") visible = fields.Boolean(string='Can be Visible?', default=True, help="Set this to False if you don't want this template to be used actively in the wizard that generate Chart of Accounts from " "templates, this is useful when you want to generate accounts of this template only when loading its child template.") currency_id = fields.Many2one('res.currency', string='Currency', required=True) use_anglo_saxon = fields.Boolean(string="Use Anglo-Saxon accounting", default=False) complete_tax_set = fields.Boolean(string='Complete Set of Taxes', default=True, help="This boolean helps you to choose if you want to propose to the user to encode the sale and purchase rates or choose from list " "of taxes. This last choice assumes that the set of tax defined on this template is complete") account_ids = fields.One2many('account.account.template', 'chart_template_id', string='Associated Account Templates') tax_template_ids = fields.One2many('account.tax.template', 'chart_template_id', string='Tax Template List', help='List of all the taxes that have to be installed by the wizard') bank_account_code_prefix = fields.Char(string='Prefix of the bank accounts', required=True) cash_account_code_prefix = fields.Char(string='Prefix of the main cash accounts', required=True) transfer_account_code_prefix = fields.Char(string='Prefix of the main transfer accounts', required=True) income_currency_exchange_account_id = fields.Many2one('account.account.template', string="Gain Exchange Rate Account", domain=[('internal_type', '=', 'other'), ('deprecated', '=', False)]) expense_currency_exchange_account_id = fields.Many2one('account.account.template', string="Loss Exchange Rate Account", domain=[('internal_type', '=', 'other'), ('deprecated', '=', False)]) country_id = fields.Many2one(string="Country", comodel_name='res.country', help="The country this chart of accounts belongs to. None if it's generic.") account_journal_suspense_account_id = fields.Many2one('account.account.template', string='Journal Suspense Account') account_journal_payment_debit_account_id = fields.Many2one('account.account.template', string='Journal Outstanding Receipts Account') account_journal_payment_credit_account_id = fields.Many2one('account.account.template', string='Journal Outstanding Payments Account') default_cash_difference_income_account_id = fields.Many2one('account.account.template', string="Cash Difference Income Account") default_cash_difference_expense_account_id = fields.Many2one('account.account.template', string="Cash Difference Expense Account") default_pos_receivable_account_id = fields.Many2one('account.account.template', string="PoS receivable account") property_account_receivable_id = fields.Many2one('account.account.template', string='Receivable Account') property_account_payable_id = fields.Many2one('account.account.template', string='Payable Account') property_account_expense_categ_id = fields.Many2one('account.account.template', string='Category of Expense Account') property_account_income_categ_id = fields.Many2one('account.account.template', string='Category of Income Account') property_account_expense_id = fields.Many2one('account.account.template', string='Expense Account on Product Template') property_account_income_id = fields.Many2one('account.account.template', string='Income Account on Product Template') property_stock_account_input_categ_id = fields.Many2one('account.account.template', string="Input Account for Stock Valuation") property_stock_account_output_categ_id = fields.Many2one('account.account.template', string="Output Account for Stock Valuation") property_stock_valuation_account_id = fields.Many2one('account.account.template', string="Account Template for Stock Valuation") property_tax_payable_account_id = fields.Many2one('account.account.template', string="Tax current account (payable)") property_tax_receivable_account_id = fields.Many2one('account.account.template', string="Tax current account (receivable)") property_advance_tax_payment_account_id = fields.Many2one('account.account.template', string="Advance tax payment account") property_cash_basis_base_account_id = fields.Many2one( comodel_name='account.account.template', domain=[('deprecated', '=', False)], string="Base Tax Received Account", help="Account that will be set on lines created in cash basis journal entry and used to keep track of the " "tax base amount.") @api.model def _prepare_transfer_account_template(self, prefix=None): ''' Prepare values to create the transfer account that is an intermediary account used when moving money from a liquidity account to another. :return: A dictionary of values to create a new account.account. ''' digits = self.code_digits prefix = prefix or self.transfer_account_code_prefix or '' # Flatten the hierarchy of chart templates. chart_template = self chart_templates = self while chart_template.parent_id: chart_templates += chart_template.parent_id chart_template = chart_template.parent_id new_code = '' for num in range(1, 100): new_code = str(prefix.ljust(digits - 1, '0')) + str(num) rec = self.env['account.account.template'].search( [('code', '=', new_code), ('chart_template_id', 'in', chart_templates.ids)], limit=1) if not rec: break else: raise UserError(_('Cannot generate an unused account code.')) current_assets_type = self.env.ref('account.data_account_type_current_assets', raise_if_not_found=False) return { 'name': _('Liquidity Transfer'), 'code': new_code, 'user_type_id': current_assets_type and current_assets_type.id or False, 'reconcile': True, 'chart_template_id': self.id, } @api.model def _create_liquidity_journal_suspense_account(self, company, code_digits): return self.env['account.account'].create({ 'name': _("Bank Suspense Account"), 'code': self.env['account.account']._search_new_account_code(company, code_digits, company.bank_account_code_prefix or ''), 'user_type_id': self.env.ref('account.data_account_type_current_assets').id, 'company_id': company.id, }) def try_loading(self, company=False, install_demo=True): """ Installs this chart of accounts for the current company if not chart of accounts had been created for it yet. :param company (Model<res.company>): the company we try to load the chart template on. If not provided, it is retrieved from the context. :param install_demo (bool): whether or not we should load demo data right after loading the chart template. """ # do not use `request.env` here, it can cause deadlocks if not company: if request and hasattr(request, 'allowed_company_ids'): company = self.env['res.company'].browse(request.allowed_company_ids[0]) else: company = self.env.company # If we don't have any chart of account on this company, install this chart of account if not company.chart_template_id and not self.existing_accounting(company): for template in self: template.with_context(default_company_id=company.id)._load(15.0, 15.0, company) # Install the demo data when the first localization is instanciated on the company if install_demo and self.env.ref('base.module_account').demo: self.with_context( default_company_id=company.id, allowed_company_ids=[company.id], )._create_demo_data() def _create_demo_data(self): try: with self.env.cr.savepoint(): demo_data = self._get_demo_data() for model, data in demo_data: created = self.env[model]._load_records([{ 'xml_id': "account.%s" % xml_id if '.' not in xml_id else xml_id, 'values': record, 'noupdate': True, } for xml_id, record in data.items()]) self._post_create_demo_data(created) except Exception: # Do not rollback installation of CoA if demo data failed _logger.exception('Error while loading accounting demo data') def _load(self, sale_tax_rate, purchase_tax_rate, company): """ Installs this chart of accounts on the current company, replacing the existing one if it had already one defined. If some accounting entries had already been made, this function fails instead, triggering a UserError. Also, note that this function can only be run by someone with administration rights. """ self.ensure_one() # do not use `request.env` here, it can cause deadlocks # Ensure everything is translated to the company's language, not the user's one. self = self.with_context(lang=company.partner_id.lang).with_company(company) if not self.env.is_admin(): raise AccessError(_("Only administrators can load a chart of accounts")) existing_accounts = self.env['account.account'].search([('company_id', '=', company.id)]) if existing_accounts: # we tolerate switching from accounting package (localization module) as long as there isn't yet any accounting # entries created for the company. if self.existing_accounting(company): raise UserError(_('Could not install new chart of account as there are already accounting entries existing.')) # delete accounting properties prop_values = ['account.account,%s' % (account_id,) for account_id in existing_accounts.ids] existing_journals = self.env['account.journal'].search([('company_id', '=', company.id)]) if existing_journals: prop_values.extend(['account.journal,%s' % (journal_id,) for journal_id in existing_journals.ids]) self.env['ir.property'].sudo().search( [('value_reference', 'in', prop_values)] ).unlink() # delete account, journal, tax, fiscal position and reconciliation model models_to_delete = ['account.reconcile.model', 'account.fiscal.position', 'account.move.line', 'account.move', 'account.journal', 'account.tax', 'account.group'] for model in models_to_delete: res = self.env[model].sudo().search([('company_id', '=', company.id)]) if len(res): res.with_context(force_delete=True).unlink() existing_accounts.unlink() company.write({'currency_id': self.currency_id.id, 'anglo_saxon_accounting': self.use_anglo_saxon, 'bank_account_code_prefix': self.bank_account_code_prefix, 'cash_account_code_prefix': self.cash_account_code_prefix, 'transfer_account_code_prefix': self.transfer_account_code_prefix, 'chart_template_id': self.id }) #set the coa currency to active self.currency_id.write({'active': True}) # When we install the CoA of first company, set the currency to price types and pricelists if company.id == 1: for reference in ['product.list_price', 'product.standard_price', 'product.list0']: try: tmp2 = self.env.ref(reference).write({'currency_id': self.currency_id.id}) except ValueError: pass # If the floats for sale/purchase rates have been filled, create templates from them self._create_tax_templates_from_rates(company.id, sale_tax_rate, purchase_tax_rate) # Set the fiscal country before generating taxes in case the company does not have a country_id set yet if self.country_id: # If this CoA is made for only one country, set it as the fiscal country of the company. company.account_fiscal_country_id = self.country_id elif not company.account_fiscal_country_id: company.account_fiscal_country_id = self.env.ref('base.us') # Install all the templates objects and generate the real objects acc_template_ref, taxes_ref = self._install_template(company, code_digits=self.code_digits) # Set default cash difference account on company if not company.account_journal_suspense_account_id: company.account_journal_suspense_account_id = self._create_liquidity_journal_suspense_account(company, self.code_digits) account_type_current_assets = self.env.ref('account.data_account_type_current_assets') if not company.account_journal_payment_debit_account_id: company.account_journal_payment_debit_account_id = self.env['account.account'].create({ 'name': _("Outstanding Receipts"), 'code': self.env['account.account']._search_new_account_code(company, self.code_digits, company.bank_account_code_prefix or ''), 'reconcile': True, 'user_type_id': account_type_current_assets.id, 'company_id': company.id, }) if not company.account_journal_payment_credit_account_id: company.account_journal_payment_credit_account_id = self.env['account.account'].create({ 'name': _("Outstanding Payments"), 'code': self.env['account.account']._search_new_account_code(company, self.code_digits, company.bank_account_code_prefix or ''), 'reconcile': True, 'user_type_id': account_type_current_assets.id, 'company_id': company.id, }) if not company.default_cash_difference_expense_account_id: company.default_cash_difference_expense_account_id = self.env['account.account'].create({ 'name': _('Cash Difference Loss'), 'code': self.env['account.account']._search_new_account_code(company, self.code_digits, '999'), 'user_type_id': self.env.ref('account.data_account_type_expenses').id, 'tag_ids': [(6, 0, self.env.ref('account.account_tag_investing').ids)], 'company_id': company.id, }) if not company.default_cash_difference_income_account_id: company.default_cash_difference_income_account_id = self.env['account.account'].create({ 'name': _('Cash Difference Gain'), 'code': self.env['account.account']._search_new_account_code(company, self.code_digits, '999'), 'user_type_id': self.env.ref('account.data_account_type_revenue').id, 'tag_ids': [(6, 0, self.env.ref('account.account_tag_investing').ids)], 'company_id': company.id, }) # Set the transfer account on the company company.transfer_account_id = self.env['account.account'].search([ ('code', '=like', self.transfer_account_code_prefix + '%'), ('company_id', '=', company.id)], limit=1) # Create Bank journals self._create_bank_journals(company, acc_template_ref) # Create the current year earning account if it wasn't present in the CoA company.get_unaffected_earnings_account() # set the default taxes on the company company.account_sale_tax_id = self.env['account.tax'].search([('type_tax_use', 'in', ('sale', 'all')), ('company_id', '=', company.id)], limit=1).id company.account_purchase_tax_id = self.env['account.tax'].search([('type_tax_use', 'in', ('purchase', 'all')), ('company_id', '=', company.id)], limit=1).id return {} @api.model def existing_accounting(self, company_id): """ Returns True iff some accounting entries have already been made for the provided company (meaning hence that its chart of accounts cannot be changed anymore). """ model_to_check = ['account.payment', 'account.bank.statement'] for model in model_to_check: if self.env[model].sudo().search([('company_id', '=', company_id.id)], order="id DESC", limit=1): return True if self.env['account.move'].sudo().search([('company_id', '=', company_id.id), ('state', '!=', 'draft')], order="id DESC", limit=1): return True return False def _create_tax_templates_from_rates(self, company_id, sale_tax_rate, purchase_tax_rate): ''' This function checks if this chart template is configured as containing a full set of taxes, and if it's not the case, it creates the templates for account.tax object accordingly to the provided sale/purchase rates. Then it saves the new tax templates as default taxes to use for this chart template. :param company_id: id of the company for which the wizard is running :param sale_tax_rate: the rate to use for created sales tax :param purchase_tax_rate: the rate to use for created purchase tax :return: True ''' self.ensure_one() obj_tax_temp = self.env['account.tax.template'] all_parents = self._get_chart_parent_ids() # create tax templates from purchase_tax_rate and sale_tax_rate fields if not self.complete_tax_set: ref_taxs = obj_tax_temp.search([('type_tax_use', '=', 'sale'), ('chart_template_id', 'in', all_parents)], order="sequence, id desc", limit=1) ref_taxs.write({'amount': sale_tax_rate, 'name': _('Tax %.2f%%') % sale_tax_rate, 'description': '%.2f%%' % sale_tax_rate}) ref_taxs = obj_tax_temp.search([('type_tax_use', '=', 'purchase'), ('chart_template_id', 'in', all_parents)], order="sequence, id desc", limit=1) ref_taxs.write({'amount': purchase_tax_rate, 'name': _('Tax %.2f%%') % purchase_tax_rate, 'description': '%.2f%%' % purchase_tax_rate}) return True def _get_chart_parent_ids(self): """ Returns the IDs of all ancestor charts, including the chart itself. (inverse of child_of operator) :return: the IDS of all ancestor charts, including the chart itself. """ chart_template = self result = [chart_template.id] while chart_template.parent_id: chart_template = chart_template.parent_id result.append(chart_template.id) return result def _create_bank_journals(self, company, acc_template_ref): ''' This function creates bank journals and their account for each line data returned by the function _get_default_bank_journals_data. :param company: the company for which the wizard is running. :param acc_template_ref: the dictionary containing the mapping between the ids of account templates and the ids of the accounts that have been generated from them. ''' self.ensure_one() bank_journals = self.env['account.journal'] # Create the journals that will trigger the account.account creation for acc in self._get_default_bank_journals_data(): bank_journals += self.env['account.journal'].create({ 'name': acc['acc_name'], 'type': acc['account_type'], 'company_id': company.id, 'currency_id': acc.get('currency_id', self.env['res.currency']).id, 'sequence': 10, }) return bank_journals @api.model def _get_default_bank_journals_data(self): """ Returns the data needed to create the default bank journals when installing this chart of accounts, in the form of a list of dictionaries. The allowed keys in these dictionaries are: - acc_name: string (mandatory) - account_type: 'cash' or 'bank' (mandatory) - currency_id (optional, only to be specified if != company.currency_id) """ return [{'acc_name': _('Cash'), 'account_type': 'cash'}, {'acc_name': _('Bank'), 'account_type': 'bank'}] @api.model def _prepare_transfer_account_for_direct_creation(self, name, company): """ Prepare values to create a transfer account directly, based on the method _prepare_transfer_account_template(). This is needed when dealing with installation of payment modules that requires the creation of their own transfer account. :param name: The transfer account name. :param company: The company owning this account. :return: A dictionary of values to create a new account.account. """ vals = self._prepare_transfer_account_template() digits = self.code_digits or 6 prefix = self.transfer_account_code_prefix or '' vals.update({ 'code': self.env['account.account']._search_new_account_code(company, digits, prefix), 'name': name, 'company_id': company.id, }) del(vals['chart_template_id']) return vals @api.model def generate_journals(self, acc_template_ref, company, journals_dict=None): """ This method is used for creating journals. :param acc_template_ref: Account templates reference. :param company_id: company to generate journals for. :returns: True """ JournalObj = self.env['account.journal'] for vals_journal in self._prepare_all_journals(acc_template_ref, company, journals_dict=journals_dict): journal = JournalObj.create(vals_journal) if vals_journal['type'] == 'general' and vals_journal['code'] == _('EXCH'): company.write({'currency_exchange_journal_id': journal.id}) if vals_journal['type'] == 'general' and vals_journal['code'] == _('CABA'): company.write({'tax_cash_basis_journal_id': journal.id}) return True def _prepare_all_journals(self, acc_template_ref, company, journals_dict=None): def _get_default_account(journal_vals, type='debit'): # Get the default accounts default_account = False if journal['type'] == 'sale': default_account = acc_template_ref.get(self.property_account_income_categ_id).id elif journal['type'] == 'purchase': default_account = acc_template_ref.get(self.property_account_expense_categ_id).id return default_account journals = [{'name': _('Customer Invoices'), 'type': 'sale', 'code': _('INV'), 'favorite': True, 'color': 11, 'sequence': 5}, {'name': _('Vendor Bills'), 'type': 'purchase', 'code': _('BILL'), 'favorite': True, 'color': 11, 'sequence': 6}, {'name': _('Miscellaneous Operations'), 'type': 'general', 'code': _('MISC'), 'favorite': True, 'sequence': 7}, {'name': _('Exchange Difference'), 'type': 'general', 'code': _('EXCH'), 'favorite': False, 'sequence': 9}, {'name': _('Cash Basis Taxes'), 'type': 'general', 'code': _('CABA'), 'favorite': False, 'sequence': 10}] if journals_dict != None: journals.extend(journals_dict) self.ensure_one() journal_data = [] for journal in journals: vals = { 'type': journal['type'], 'name': journal['name'], 'code': journal['code'], 'company_id': company.id, 'default_account_id': _get_default_account(journal), 'show_on_dashboard': journal['favorite'], 'color': journal.get('color', False), 'sequence': journal['sequence'] } journal_data.append(vals) return journal_data def generate_properties(self, acc_template_ref, company): """ This method used for creating properties. :param acc_template_ref: Mapping between ids of account templates and real accounts created from them :param company_id: company to generate properties for. :returns: True """ self.ensure_one() PropertyObj = self.env['ir.property'] todo_list = [ ('property_account_receivable_id', 'res.partner'), ('property_account_payable_id', 'res.partner'), ('property_account_expense_categ_id', 'product.category'), ('property_account_income_categ_id', 'product.category'), ('property_account_expense_id', 'product.template'), ('property_account_income_id', 'product.template'), ('property_tax_payable_account_id', 'account.tax.group'), ('property_tax_receivable_account_id', 'account.tax.group'), ('property_advance_tax_payment_account_id', 'account.tax.group'), ] for field, model in todo_list: account = self[field] value = acc_template_ref[account].id if account else False if value: PropertyObj._set_default(field, model, value, company=company) stock_properties = [ 'property_stock_account_input_categ_id', 'property_stock_account_output_categ_id', 'property_stock_valuation_account_id', ] for stock_property in stock_properties: account = getattr(self, stock_property) value = account and acc_template_ref[account].id or False if value: company.write({stock_property: value}) return True def _install_template(self, company, code_digits=None, obj_wizard=None, acc_ref=None, taxes_ref=None): """ Recursively load the template objects and create the real objects from them. :param company: company the wizard is running for :param code_digits: number of digits the accounts code should have in the COA :param obj_wizard: the current wizard for generating the COA from the templates :param acc_ref: Mapping between ids of account templates and real accounts created from them :param taxes_ref: Mapping between ids of tax templates and real taxes created from them :returns: tuple with a dictionary containing * the mapping between the account template ids and the ids of the real accounts that have been generated from them, as first item, * a similar dictionary for mapping the tax templates and taxes, as second item, :rtype: tuple(dict, dict, dict) """ self.ensure_one() if acc_ref is None: acc_ref = {} if taxes_ref is None: taxes_ref = {} if self.parent_id: tmp1, tmp2 = self.parent_id._install_template(company, code_digits=code_digits, acc_ref=acc_ref, taxes_ref=taxes_ref) acc_ref.update(tmp1) taxes_ref.update(tmp2) # Ensure, even if individually, that everything is translated according to the company's language. tmp1, tmp2 = self.with_context(lang=company.partner_id.lang)._load_template(company, code_digits=code_digits, account_ref=acc_ref, taxes_ref=taxes_ref) acc_ref.update(tmp1) taxes_ref.update(tmp2) return acc_ref, taxes_ref def _load_template(self, company, code_digits=None, account_ref=None, taxes_ref=None): """ Generate all the objects from the templates :param company: company the wizard is running for :param code_digits: number of digits the accounts code should have in the COA :param acc_ref: Mapping between ids of account templates and real accounts created from them :param taxes_ref: Mapping between ids of tax templates and real taxes created from them :returns: tuple with a dictionary containing * the mapping between the account template ids and the ids of the real accounts that have been generated from them, as first item, * a similar dictionary for mapping the tax templates and taxes, as second item, :rtype: tuple(dict, dict, dict) """ self.ensure_one() if account_ref is None: account_ref = {} if taxes_ref is None: taxes_ref = {} if not code_digits: code_digits = self.code_digits AccountTaxObj = self.env['account.tax'] # Generate taxes from templates. generated_tax_res = self.with_context(active_test=False).tax_template_ids._generate_tax(company) taxes_ref.update(generated_tax_res['tax_template_to_tax']) # Generating Accounts from templates. account_template_ref = self.generate_account(taxes_ref, account_ref, code_digits, company) account_ref.update(account_template_ref) # Generate account groups, from template self.generate_account_groups(company) # writing account values after creation of accounts for tax, value in generated_tax_res['account_dict']['account.tax'].items(): if value['cash_basis_transition_account_id']: tax.cash_basis_transition_account_id = account_ref.get(value['cash_basis_transition_account_id']) for repartition_line, value in generated_tax_res['account_dict']['account.tax.repartition.line'].items(): if value['account_id']: repartition_line.account_id = account_ref.get(value['account_id']) # Set the company accounts self._load_company_accounts(account_ref, company) # Create Journals - Only done for root chart template if not self.parent_id: self.generate_journals(account_ref, company) # generate properties function self.generate_properties(account_ref, company) # Generate Fiscal Position , Fiscal Position Accounts and Fiscal Position Taxes from templates self.generate_fiscal_position(taxes_ref, account_ref, company) # Generate account operation template templates self.generate_account_reconcile_model(taxes_ref, account_ref, company) return account_ref, taxes_ref def _load_company_accounts(self, account_ref, company): # Set the default accounts on the company accounts = { 'default_cash_difference_income_account_id': self.default_cash_difference_income_account_id, 'default_cash_difference_expense_account_id': self.default_cash_difference_expense_account_id, 'account_journal_suspense_account_id': self.account_journal_suspense_account_id, 'account_journal_payment_debit_account_id': self.account_journal_payment_debit_account_id, 'account_journal_payment_credit_account_id': self.account_journal_payment_credit_account_id, 'account_cash_basis_base_account_id': self.property_cash_basis_base_account_id, 'account_default_pos_receivable_account_id': self.default_pos_receivable_account_id, 'income_currency_exchange_account_id': self.income_currency_exchange_account_id, 'expense_currency_exchange_account_id': self.expense_currency_exchange_account_id, } values = {} # The loop is to avoid writing when we have no values, thus avoiding erasing the account from the parent for key, account in accounts.items(): if account_ref.get(account): values[key] = account_ref.get(account) company.write(values) def create_record_with_xmlid(self, company, template, model, vals): return self._create_records_with_xmlid(model, [(template, vals)], company).id def _create_records_with_xmlid(self, model, template_vals, company): """ Create records for the given model name with the given vals, and create xml ids based on each record's template and company id. """ if not template_vals: return self.env[model] template_model = template_vals[0][0] template_ids = [template.id for template, vals in template_vals] template_xmlids = template_model.browse(template_ids).get_external_id() data_list = [] for template, vals in template_vals: module, name = template_xmlids[template.id].split('.', 1) xml_id = "%s.%s_%s" % (module, company.id, name) data_list.append(dict(xml_id=xml_id, values=vals, noupdate=True)) return self.env[model]._load_records(data_list) @api.model def _load_records(self, data_list, update=False): # When creating a chart template create, for the liquidity transfer account # - an account.account.template: this allow to define account.reconcile.model.template objects refering that liquidity transfer # account although it's not existing in any xml file # - an entry in ir_model_data: this allow to still use the method create_record_with_xmlid() and don't make any difference between # regular accounts created and that liquidity transfer account records = super(AccountChartTemplate, self)._load_records(data_list, update) account_data_list = [] for data, record in zip(data_list, records): # Create the transfer account only for leaf chart template in the hierarchy. if record.parent_id: continue if data.get('xml_id'): account_xml_id = data['xml_id'] + '_liquidity_transfer' if not self.env.ref(account_xml_id, raise_if_not_found=False): account_vals = record._prepare_transfer_account_template() account_data_list.append(dict( xml_id=account_xml_id, values=account_vals, noupdate=data.get('noupdate'), )) self.env['account.account.template']._load_records(account_data_list, update) return records def _get_account_vals(self, company, account_template, code_acc, tax_template_ref): """ This method generates a dictionary of all the values for the account that will be created. """ self.ensure_one() tax_ids = [] for tax in account_template.tax_ids: tax_ids.append(tax_template_ref[tax].id) val = { 'name': account_template.name, 'currency_id': account_template.currency_id and account_template.currency_id.id or False, 'code': code_acc, 'user_type_id': account_template.user_type_id and account_template.user_type_id.id or False, 'reconcile': account_template.reconcile, 'note': account_template.note, 'tax_ids': [(6, 0, tax_ids)], 'company_id': company.id, 'tag_ids': [(6, 0, [t.id for t in account_template.tag_ids])], } return val def generate_account(self, tax_template_ref, acc_template_ref, code_digits, company): """ This method generates accounts from account templates. :param tax_template_ref: Taxes templates reference for write taxes_id in account_account. :param acc_template_ref: dictionary containing the mapping between the account templates and generated accounts (will be populated) :param code_digits: number of digits to use for account code. :param company_id: company to generate accounts for. :returns: return acc_template_ref for reference purpose. :rtype: dict """ self.ensure_one() account_tmpl_obj = self.env['account.account.template'] acc_template = account_tmpl_obj.search([('nocreate', '!=', True), ('chart_template_id', '=', self.id)], order='id') template_vals = [] for account_template in acc_template: code_main = account_template.code and len(account_template.code) or 0 code_acc = account_template.code or '' if code_main > 0 and code_main <= code_digits: code_acc = str(code_acc) + (str('0'*(code_digits-code_main))) vals = self._get_account_vals(company, account_template, code_acc, tax_template_ref) template_vals.append((account_template, vals)) accounts = self._create_records_with_xmlid('account.account', template_vals, company) for template, account in zip(acc_template, accounts): acc_template_ref[template] = account return acc_template_ref def generate_account_groups(self, company): """ This method generates account groups from account groups templates. :param company: company to generate the account groups for """ self.ensure_one() group_templates = self.env['account.group.template'].search([('chart_template_id', '=', self.id)]) template_vals = [] for group_template in group_templates: vals = { 'name': group_template.name, 'code_prefix_start': group_template.code_prefix_start, 'code_prefix_end': group_template.code_prefix_end, 'company_id': company.id, } template_vals.append((group_template, vals)) groups = self._create_records_with_xmlid('account.group', template_vals, company) def _prepare_reconcile_model_vals(self, company, account_reconcile_model, acc_template_ref, tax_template_ref): """ This method generates a dictionary of all the values for the account.reconcile.model that will be created. """ self.ensure_one() account_reconcile_model_lines = self.env['account.reconcile.model.line.template'].search([ ('model_id', '=', account_reconcile_model.id) ]) return { 'name': account_reconcile_model.name, 'sequence': account_reconcile_model.sequence, 'company_id': company.id, 'rule_type': account_reconcile_model.rule_type, 'auto_reconcile': account_reconcile_model.auto_reconcile, 'to_check': account_reconcile_model.to_check, 'match_journal_ids': [(6, None, account_reconcile_model.match_journal_ids.ids)], 'match_nature': account_reconcile_model.match_nature, 'match_amount': account_reconcile_model.match_amount, 'match_amount_min': account_reconcile_model.match_amount_min, 'match_amount_max': account_reconcile_model.match_amount_max, 'match_label': account_reconcile_model.match_label, 'match_label_param': account_reconcile_model.match_label_param, 'match_note': account_reconcile_model.match_note, 'match_note_param': account_reconcile_model.match_note_param, 'match_transaction_type': account_reconcile_model.match_transaction_type, 'match_transaction_type_param': account_reconcile_model.match_transaction_type_param, 'match_same_currency': account_reconcile_model.match_same_currency, 'allow_payment_tolerance': account_reconcile_model.allow_payment_tolerance, 'payment_tolerance_type': account_reconcile_model.payment_tolerance_type, 'payment_tolerance_param': account_reconcile_model.payment_tolerance_param, 'match_partner': account_reconcile_model.match_partner, 'match_partner_ids': [(6, None, account_reconcile_model.match_partner_ids.ids)], 'match_partner_category_ids': [(6, None, account_reconcile_model.match_partner_category_ids.ids)], 'line_ids': [(0, 0, { 'account_id': acc_template_ref[line.account_id].id, 'label': line.label, 'amount_type': line.amount_type, 'force_tax_included': line.force_tax_included, 'amount_string': line.amount_string, 'tax_ids': [[4, tax_template_ref[tax].id, 0] for tax in line.tax_ids], }) for line in account_reconcile_model_lines], } def generate_account_reconcile_model(self, tax_template_ref, acc_template_ref, company): """ This method creates account reconcile models :param tax_template_ref: Taxes templates reference for write taxes_id in account_account. :param acc_template_ref: dictionary with the mapping between the account templates and the real accounts. :param company_id: company to create models for :returns: return new_account_reconcile_model for reference purpose. :rtype: dict """ self.ensure_one() account_reconcile_models = self.env['account.reconcile.model.template'].search([ ('chart_template_id', '=', self.id) ]) for account_reconcile_model in account_reconcile_models: vals = self._prepare_reconcile_model_vals(company, account_reconcile_model, acc_template_ref, tax_template_ref) self.create_record_with_xmlid(company, account_reconcile_model, 'account.reconcile.model', vals) # Create default rules for the reconciliation widget matching invoices automatically. if not self.parent_id: self.env['account.reconcile.model'].sudo().create({ "name": _('Invoices/Bills Perfect Match'), "sequence": '1', "rule_type": 'invoice_matching', "auto_reconcile": True, "match_nature": 'both', "match_same_currency": True, "allow_payment_tolerance": True, "payment_tolerance_type": 'percentage', "payment_tolerance_param": 0, "match_partner": True, "company_id": company.id, }) self.env['account.reconcile.model'].sudo().create({ "name": _('Invoices/Bills Partial Match if Underpaid'), "sequence": '2', "rule_type": 'invoice_matching', "auto_reconcile": False, "match_nature": 'both', "match_same_currency": True, "allow_payment_tolerance": False, "match_partner": True, "company_id": company.id, }) return True def _get_fp_vals(self, company, position): return { 'company_id': company.id, 'sequence': position.sequence, 'name': position.name, 'note': position.note, 'auto_apply': position.auto_apply, 'vat_required': position.vat_required, 'country_id': position.country_id.id, 'country_group_id': position.country_group_id.id, 'state_ids': position.state_ids and [(6,0, position.state_ids.ids)] or [], 'zip_from': position.zip_from, 'zip_to': position.zip_to, } def generate_fiscal_position(self, tax_template_ref, acc_template_ref, company): """ This method generates Fiscal Position, Fiscal Position Accounts and Fiscal Position Taxes from templates. :param taxes_ids: Taxes templates reference for generating account.fiscal.position.tax. :param acc_template_ref: Account templates reference for generating account.fiscal.position.account. :param company_id: the company to generate fiscal position data for :returns: True """ self.ensure_one() positions = self.env['account.fiscal.position.template'].search([('chart_template_id', '=', self.id)]) # first create fiscal positions in batch template_vals = [] for position in positions: fp_vals = self._get_fp_vals(company, position) template_vals.append((position, fp_vals)) fps = self._create_records_with_xmlid('account.fiscal.position', template_vals, company) # then create fiscal position taxes and accounts tax_template_vals = [] account_template_vals = [] for position, fp in zip(positions, fps): for tax in position.tax_ids: tax_template_vals.append((tax, { 'tax_src_id': tax_template_ref[tax.tax_src_id].id, 'tax_dest_id': tax.tax_dest_id and tax_template_ref[tax.tax_dest_id].id or False, 'position_id': fp.id, })) for acc in position.account_ids: account_template_vals.append((acc, { 'account_src_id': acc_template_ref[acc.account_src_id].id, 'account_dest_id': acc_template_ref[acc.account_dest_id].id, 'position_id': fp.id, })) self._create_records_with_xmlid('account.fiscal.position.tax', tax_template_vals, company) self._create_records_with_xmlid('account.fiscal.position.account', account_template_vals, company) return True class AccountTaxTemplate(models.Model): _name = 'account.tax.template' _description = 'Templates for Taxes' _order = 'id' chart_template_id = fields.Many2one('account.chart.template', string='Chart Template', required=True) name = fields.Char(string='Tax Name', required=True) type_tax_use = fields.Selection(TYPE_TAX_USE, string='Tax Type', required=True, default="sale", help="Determines where the tax is selectable. Note : 'None' means a tax can't be used by itself, however it can still be used in a group.") tax_scope = fields.Selection([('service', 'Service'), ('consu', 'Consumable')], help="Restrict the use of taxes to a type of product.") amount_type = fields.Selection(default='percent', string="Tax Computation", required=True, selection=[('group', 'Group of Taxes'), ('fixed', 'Fixed'), ('percent', 'Percentage of Price'), ('division', 'Percentage of Price Tax Included')]) active = fields.Boolean(default=True, help="Set active to false to hide the tax without removing it.") children_tax_ids = fields.Many2many('account.tax.template', 'account_tax_template_filiation_rel', 'parent_tax', 'child_tax', string='Children Taxes') sequence = fields.Integer(required=True, default=1, help="The sequence field is used to define order in which the tax lines are applied.") amount = fields.Float(required=True, digits=(16, 4), default=0) description = fields.Char(string='Display on Invoices') price_include = fields.Boolean(string='Included in Price', default=False, help="Check this if the price you use on the product and invoices includes this tax.") include_base_amount = fields.Boolean(string='Affect Subsequent Taxes', default=False, help="If set, taxes with a higher sequence than this one will be affected by it, provided they accept it.") is_base_affected = fields.Boolean( string="Base Affected by Previous Taxes", default=True, help="If set, taxes with a lower sequence might affect this one, provided they try to do it.") analytic = fields.Boolean(string="Analytic Cost", help="If set, the amount computed by this tax will be assigned to the same analytic account as the invoice line (if any)") invoice_repartition_line_ids = fields.One2many(string="Repartition for Invoices", comodel_name="account.tax.repartition.line.template", inverse_name="invoice_tax_id", copy=True, help="Repartition when the tax is used on an invoice") refund_repartition_line_ids = fields.One2many(string="Repartition for Refund Invoices", comodel_name="account.tax.repartition.line.template", inverse_name="refund_tax_id", copy=True, help="Repartition when the tax is used on a refund") tax_group_id = fields.Many2one('account.tax.group', string="Tax Group") tax_exigibility = fields.Selection( [('on_invoice', 'Based on Invoice'), ('on_payment', 'Based on Payment'), ], string='Tax Due', default='on_invoice', help="Based on Invoice: the tax is due as soon as the invoice is validated.\n" "Based on Payment: the tax is due as soon as the payment of the invoice is received.") cash_basis_transition_account_id = fields.Many2one( comodel_name='account.account.template', string="Cash Basis Transition Account", domain=[('deprecated', '=', False)], help="Account used to transition the tax amount for cash basis taxes. It will contain the tax amount as long as the original invoice has not been reconciled ; at reconciliation, this amount cancelled on this account and put on the regular tax account.") _sql_constraints = [ ('name_company_uniq', 'unique(name, type_tax_use, tax_scope, chart_template_id)', 'Tax names must be unique !'), ] @api.depends('name', 'description') def name_get(self): res = [] for record in self: name = record.description and record.description or record.name res.append((record.id, name)) return res @api.model def _try_instantiating_foreign_taxes(self, country, company): """ This function is called in multivat setup, when a company needs to submit a tax report in a foreign country. It searches for tax templates in the provided countries and instantiates the ones it find in the provided company. Tax accounts are not kept from the templates (this wouldn't make sense, as they don't belong to the same CoA as the one installed on the company). Instead, we search existing tax accounts for approximately equivalent accounts and use their prefix to create new accounts. Doing this gives a roughly correct suggestion that then needs to be reviewed by the user to ensure its consistency. It is intended as a shortcut to avoid hours of encoding, not as an out-of-the-box, always correct solution. """ def create_foreign_tax_account(existing_account, additional_label): new_code = self.env['account.account']._search_new_account_code(existing_account.company_id, len(existing_account.code), existing_account.code[:-2]) return self.env['account.account'].create({ 'name': f"{existing_account.name} - {additional_label}", 'code': new_code, 'user_type_id': existing_account.user_type_id.id, 'company_id': existing_account.company_id.id, }) def get_existing_tax_account(foreign_tax_rep_line, force_tax=None): company = foreign_tax_rep_line.company_id sign_comparator = '<' if foreign_tax_rep_line.factor_percent < 0 else '>' search_domain = [ ('account_id', '!=', False), ('factor_percent', sign_comparator, 0), ('company_id', '=', company.id), '|', '&', ('invoice_tax_id.type_tax_use', '=', tax_rep_line.invoice_tax_id.type_tax_use), ('invoice_tax_id.country_id', '=', company.account_fiscal_country_id.id), '&', ('refund_tax_id.type_tax_use', '=', tax_rep_line.refund_tax_id.type_tax_use), ('refund_tax_id.country_id', '=', company.account_fiscal_country_id.id), ] if force_tax: search_domain += [ '|', ('invoice_tax_id.id', 'in', force_tax.ids), ('refund_tax_id.id', 'in', force_tax.ids), ] return self.env['account.tax.repartition.line'].search(search_domain, limit=1).account_id taxes_in_country = self.env['account.tax'].search([ ('country_id', '=', country.id), ('company_id', '=', company.id) ]) if taxes_in_country: return templates_to_instantiate = self.env['account.tax.template'].with_context(active_test=False).search([('chart_template_id.country_id', '=', country.id)]) default_company_taxes = company.account_sale_tax_id + company.account_purchase_tax_id rep_lines_accounts = templates_to_instantiate._generate_tax(company)['account_dict'] new_accounts_map = {} # Handle tax repartition line accounts tax_rep_lines_accounts_dict = rep_lines_accounts['account.tax.repartition.line'] for tax_rep_line, account_dict in tax_rep_lines_accounts_dict.items(): account_template = account_dict['account_id'] rep_account = new_accounts_map.get(account_template) if not rep_account: existing_account = get_existing_tax_account(tax_rep_line, force_tax=default_company_taxes) if not existing_account: # If the default taxes were not enough to provide the account # we need, search on all other taxes. existing_account = get_existing_tax_account(tax_rep_line) if existing_account: rep_account = create_foreign_tax_account(existing_account, _("Foreign tax account (%s)", country.code)) new_accounts_map[account_template] = rep_account tax_rep_line.account_id = rep_account # Handle cash basis taxes transtion account caba_transition_dict = rep_lines_accounts['account.tax'] for tax, account_dict in caba_transition_dict.items(): transition_account_template = account_dict['cash_basis_transition_account_id'] if transition_account_template: transition_account = new_accounts_map.get(transition_account_template) if not transition_account: rep_lines = tax.invoice_repartition_line_ids + tax.refund_repartition_line_ids tax_accounts = rep_lines.account_id if tax_accounts: transition_account = create_foreign_tax_account(tax_accounts[0], _("Cash basis transition account")) tax.cash_basis_transition_account_id = transition_account # Setup tax closing accounts on foreign tax groups ; we don't want to use the domestic accounts groups = self.env['account.tax.group'].search([('country_id', '=', country.id)]) group_property_fields = [ 'property_tax_payable_account_id', 'property_tax_receivable_account_id', 'property_advance_tax_payment_account_id' ] property_company = self.env['ir.property'].with_company(company) groups_company = groups.with_company(company) for property_field in group_property_fields: default_acc = property_company._get(property_field, 'account.tax.group') if default_acc: groups_company.write({ property_field: create_foreign_tax_account(default_acc, _("Foreign account (%s)", country.code)) }) def _get_tax_vals(self, company, tax_template_to_tax): """ This method generates a dictionary of all the values for the tax that will be created. """ # Compute children tax ids children_ids = [] for child_tax in self.children_tax_ids: if tax_template_to_tax.get(child_tax): children_ids.append(tax_template_to_tax[child_tax].id) self.ensure_one() val = { 'name': self.name, 'type_tax_use': self.type_tax_use, 'tax_scope': self.tax_scope, 'amount_type': self.amount_type, 'active': self.active, 'company_id': company.id, 'sequence': self.sequence, 'amount': self.amount, 'description': self.description, 'price_include': self.price_include, 'include_base_amount': self.include_base_amount, 'is_base_affected': self.is_base_affected, 'analytic': self.analytic, 'children_tax_ids': [(6, 0, children_ids)], 'tax_exigibility': self.tax_exigibility, } # We add repartition lines if there are some, so that if there are none, # default_get is called and creates the default ones properly. if self.invoice_repartition_line_ids: val['invoice_repartition_line_ids'] = self.invoice_repartition_line_ids.get_repartition_line_create_vals(company) if self.refund_repartition_line_ids: val['refund_repartition_line_ids'] = self.refund_repartition_line_ids.get_repartition_line_create_vals(company) if self.tax_group_id: val['tax_group_id'] = self.tax_group_id.id return val def _get_tax_vals_complete(self, company, tax_template_to_tax): """ Returns a dict of values to be used to create the tax corresponding to the template, assuming the account.account objects were already created. It differs from function _get_tax_vals because here, we replace the references to account.template by their corresponding account.account ids ('cash_basis_transition_account_id' and 'account_id' in the invoice and refund repartition lines) """ vals = self._get_tax_vals(company, tax_template_to_tax) if self.cash_basis_transition_account_id.code: cash_basis_account_id = self.env['account.account'].search([ ('code', '=like', self.cash_basis_transition_account_id.code + '%'), ('company_id', '=', company.id) ], limit=1) if cash_basis_account_id: vals.update({"cash_basis_transition_account_id": cash_basis_account_id.id}) vals.update({ "invoice_repartition_line_ids": self.invoice_repartition_line_ids._get_repartition_line_create_vals_complete(company), "refund_repartition_line_ids": self.refund_repartition_line_ids._get_repartition_line_create_vals_complete(company), }) return vals def _generate_tax(self, company, accounts_exist=False): """ This method generate taxes from templates. :param company: the company for which the taxes should be created from templates in self :returns: { 'tax_template_to_tax': mapping between tax template and the newly generated taxes corresponding, 'account_dict': dictionary containing a to-do list with all the accounts to assign on new taxes } """ # default_company_id is needed in context to allow creation of default # repartition lines on taxes ChartTemplate = self.env['account.chart.template'].with_context(default_company_id=company.id) todo_dict = {'account.tax': {}, 'account.tax.repartition.line': {}} tax_template_to_tax = {} templates_todo = list(self) while templates_todo: templates = templates_todo templates_todo = [] # create taxes in batch tax_template_vals = [] for template in templates: if all(child in tax_template_to_tax for child in template.children_tax_ids): if accounts_exist: vals = template._get_tax_vals_complete(company, tax_template_to_tax) else: vals = template._get_tax_vals(company, tax_template_to_tax) if self.chart_template_id.country_id: vals['country_id'] = self.chart_template_id.country_id.id elif company.account_fiscal_country_id: vals['country_id'] = company.account_fiscal_country_id.id else: # Will happen for generic CoAs such as syscohada (they are available for multiple countries, and don't have any country_id) raise UserError(_("Please first define a fiscal country for company %s.", company.name)) tax_template_vals.append((template, vals)) else: # defer the creation of this tax to the next batch templates_todo.append(template) taxes = ChartTemplate._create_records_with_xmlid('account.tax', tax_template_vals, company) # fill in tax_template_to_tax and todo_dict for tax, (template, vals) in zip(taxes, tax_template_vals): tax_template_to_tax[template] = tax # Since the accounts have not been created yet, we have to wait before filling these fields todo_dict['account.tax'][tax] = { 'cash_basis_transition_account_id': template.cash_basis_transition_account_id, } if not accounts_exist: # We also have to delay the assignation of accounts to repartition lines # The below code assigns the account_id to the repartition lines according # to the corresponding repartition line in the template, based on the order. # As we just created the repartition lines, tax.invoice_repartition_line_ids is not well sorted. # But we can force the sort by calling sort() all_tax_rep_lines = tax.invoice_repartition_line_ids.sorted() + tax.refund_repartition_line_ids.sorted() all_template_rep_lines = template.invoice_repartition_line_ids + template.refund_repartition_line_ids for index, template_rep_line in enumerate(all_template_rep_lines): # We assume template and tax repartition lines are in the same order template_account = template_rep_line.account_id if template_account: todo_dict['account.tax.repartition.line'][all_tax_rep_lines[index]] = { 'account_id': template_account, } if any(template.tax_exigibility == 'on_payment' for template in self): # When a CoA is being installed automatically and if it is creating account tax(es) whose field `Use Cash Basis`(tax_exigibility) is set to True by default # (example of such CoA's are l10n_fr and l10n_mx) then in the `Accounting Settings` the option `Cash Basis` should be checked by default. company.tax_exigibility = True return { 'tax_template_to_tax': tax_template_to_tax, 'account_dict': todo_dict } # Tax Repartition Line Template class AccountTaxRepartitionLineTemplate(models.Model): _name = "account.tax.repartition.line.template" _description = "Tax Repartition Line Template" factor_percent = fields.Float(string="%", required=True, help="Factor to apply on the account move lines generated from this distribution line, in percents") repartition_type = fields.Selection(string="Based On", selection=[('base', 'Base'), ('tax', 'of tax')], required=True, default='tax', help="Base on which the factor will be applied.") account_id = fields.Many2one(string="Account", comodel_name='account.account.template', help="Account on which to post the tax amount") invoice_tax_id = fields.Many2one(comodel_name='account.tax.template', help="The tax set to apply this distribution on invoices. Mutually exclusive with refund_tax_id") refund_tax_id = fields.Many2one(comodel_name='account.tax.template', help="The tax set to apply this distribution on refund invoices. Mutually exclusive with invoice_tax_id") tag_ids = fields.Many2many(string="Financial Tags", relation='account_tax_repartition_financial_tags', comodel_name='account.account.tag', copy=True, help="Additional tags that will be assigned by this repartition line for use in financial reports") use_in_tax_closing = fields.Boolean(string="Tax Closing Entry") # These last two fields are helpers used to ease the declaration of account.account.tag objects in XML. # They are directly linked to account.tax.report.line objects, which create corresponding + and - tags # at creation. This way, we avoid declaring + and - separately every time. plus_report_line_ids = fields.Many2many(string="Plus Tax Report Lines", relation='account_tax_repartition_plus_report_line', comodel_name='account.tax.report.line', copy=True, help="Tax report lines whose '+' tag will be assigned to move lines by this repartition line") minus_report_line_ids = fields.Many2many(string="Minus Report Lines", relation='account_tax_repartition_minus_report_line', comodel_name='account.tax.report.line', copy=True, help="Tax report lines whose '-' tag will be assigned to move lines by this repartition line") @api.model def create(self, vals): if vals.get('plus_report_line_ids'): vals['plus_report_line_ids'] = self._convert_tag_syntax_to_orm(vals['plus_report_line_ids']) if vals.get('minus_report_line_ids'): vals['minus_report_line_ids'] = self._convert_tag_syntax_to_orm(vals['minus_report_line_ids']) if vals.get('tag_ids'): vals['tag_ids'] = self._convert_tag_syntax_to_orm(vals['tag_ids']) if vals.get('use_in_tax_closing') is None: if not vals.get('account_id'): vals['use_in_tax_closing'] = False else: internal_group = self.env['account.account.template'].browse(vals.get('account_id')).user_type_id.internal_group vals['use_in_tax_closing'] = not (internal_group == 'income' or internal_group == 'expense') return super(AccountTaxRepartitionLineTemplate, self).create(vals) @api.model def _convert_tag_syntax_to_orm(self, tags_list): """ Repartition lines give the possibility to directly give a list of ids to create for tags instead of a list of ORM commands. This function checks that tags_list uses this syntactic sugar and returns an ORM-compliant version of it if it does. """ if tags_list and all(isinstance(elem, int) for elem in tags_list): return [(6, False, tags_list)] return tags_list @api.constrains('invoice_tax_id', 'refund_tax_id') def validate_tax_template_link(self): for record in self: if record.invoice_tax_id and record.refund_tax_id: raise ValidationError(_("Tax distribution line templates should apply to either invoices or refunds, not both at the same time. invoice_tax_id and refund_tax_id should not be set together.")) @api.constrains('plus_report_line_ids', 'minus_report_line_ids') def validate_tags(self): all_tax_rep_lines = self.mapped('plus_report_line_ids') + self.mapped('minus_report_line_ids') lines_without_tag = all_tax_rep_lines.filtered(lambda x: not x.tag_name) if lines_without_tag: raise ValidationError(_("The following tax report lines are used in some tax distribution template though they don't generate any tag: %s . This probably means you forgot to set a tag_name on these lines.", str(lines_without_tag.mapped('name')))) def get_repartition_line_create_vals(self, company): rslt = [(5, 0, 0)] for record in self: tags_to_add = record._get_tags_to_add() rslt.append((0, 0, { 'factor_percent': record.factor_percent, 'repartition_type': record.repartition_type, 'tag_ids': [(6, 0, tags_to_add.ids)], 'company_id': company.id, 'use_in_tax_closing': record.use_in_tax_closing })) return rslt def _get_repartition_line_create_vals_complete(self, company): """ This function returns a list of values to create the repartition lines of a tax based on one or several account.tax.repartition.line.template. It mimicks the function get_repartition_line_create_vals but adds the missing field account_id (account.account) Returns a list of (0,0, x) ORM commands to create the repartition lines starting with a (5,0,0) command to clear the repartition. """ rslt = self.get_repartition_line_create_vals(company) for idx, template_line in zip(range(1, len(rslt)), self): # ignore first ORM command ( (5, 0, 0) ) account_id = False if template_line.account_id: # take the first account.account which code begins with the correct code account_id = self.env['account.account'].search([ ('code', '=like', template_line.account_id.code + '%'), ('company_id', '=', company.id) ], limit=1).id if not account_id: _logger.warning("The account with code '%s' was not found but is supposed to be linked to a tax", template_line.account_id.code) rslt[idx][2].update({ "account_id": account_id, }) return rslt def _get_tags_to_add(self): self.ensure_one() tags_to_add = self.env["account.account.tag"] tags_to_add += self.plus_report_line_ids.mapped("tag_ids").filtered(lambda x: not x.tax_negate) tags_to_add += self.minus_report_line_ids.mapped("tag_ids").filtered(lambda x: x.tax_negate) tags_to_add += self.tag_ids return tags_to_add # Fiscal Position Templates class AccountFiscalPositionTemplate(models.Model): _name = 'account.fiscal.position.template' _description = 'Template for Fiscal Position' sequence = fields.Integer() name = fields.Char(string='Fiscal Position Template', required=True) chart_template_id = fields.Many2one('account.chart.template', string='Chart Template', required=True) account_ids = fields.One2many('account.fiscal.position.account.template', 'position_id', string='Account Mapping') tax_ids = fields.One2many('account.fiscal.position.tax.template', 'position_id', string='Tax Mapping') note = fields.Text(string='Notes') auto_apply = fields.Boolean(string='Detect Automatically', help="Apply automatically this fiscal position.") vat_required = fields.Boolean(string='VAT required', help="Apply only if partner has a VAT number.") country_id = fields.Many2one('res.country', string='Country', help="Apply only if delivery country matches.") country_group_id = fields.Many2one('res.country.group', string='Country Group', help="Apply only if delivery country matches the group.") state_ids = fields.Many2many('res.country.state', string='Federal States') zip_from = fields.Char(string='Zip Range From') zip_to = fields.Char(string='Zip Range To') class AccountFiscalPositionTaxTemplate(models.Model): _name = 'account.fiscal.position.tax.template' _description = 'Tax Mapping Template of Fiscal Position' _rec_name = 'position_id' position_id = fields.Many2one('account.fiscal.position.template', string='Fiscal Position', required=True, ondelete='cascade') tax_src_id = fields.Many2one('account.tax.template', string='Tax Source', required=True) tax_dest_id = fields.Many2one('account.tax.template', string='Replacement Tax') class AccountFiscalPositionAccountTemplate(models.Model): _name = 'account.fiscal.position.account.template' _description = 'Accounts Mapping Template of Fiscal Position' _rec_name = 'position_id' position_id = fields.Many2one('account.fiscal.position.template', string='Fiscal Mapping', required=True, ondelete='cascade') account_src_id = fields.Many2one('account.account.template', string='Account Source', required=True) account_dest_id = fields.Many2one('account.account.template', string='Account Destination', required=True) class AccountReconcileModelTemplate(models.Model): _name = "account.reconcile.model.template" _description = 'Reconcile Model Template' # Base fields. chart_template_id = fields.Many2one('account.chart.template', string='Chart Template', required=True) name = fields.Char(string='Button Label', required=True) sequence = fields.Integer(required=True, default=10) rule_type = fields.Selection(selection=[ ('writeoff_button', 'Button to generate counterpart entry'), ('writeoff_suggestion', 'Rule to suggest counterpart entry'), ('invoice_matching', 'Rule to match invoices/bills'), ], string='Type', default='writeoff_button', required=True) auto_reconcile = fields.Boolean(string='Auto-validate', help='Validate the statement line automatically (reconciliation based on your rule).') to_check = fields.Boolean(string='To Check', default=False, help='This matching rule is used when the user is not certain of all the information of the counterpart.') matching_order = fields.Selection( selection=[ ('old_first', 'Oldest first'), ('new_first', 'Newest first'), ] ) # ===== Conditions ===== match_text_location_label = fields.Boolean( default=True, help="Search in the Statement's Label to find the Invoice/Payment's reference", ) match_text_location_note = fields.Boolean( default=False, help="Search in the Statement's Note to find the Invoice/Payment's reference", ) match_text_location_reference = fields.Boolean( default=False, help="Search in the Statement's Reference to find the Invoice/Payment's reference", ) match_journal_ids = fields.Many2many('account.journal', string='Journals Availability', domain="[('type', 'in', ('bank', 'cash'))]", help='The reconciliation model will only be available from the selected journals.') match_nature = fields.Selection(selection=[ ('amount_received', 'Amount Received'), ('amount_paid', 'Amount Paid'), ('both', 'Amount Paid/Received') ], string='Amount Type', required=True, default='both', help='''The reconciliation model will only be applied to the selected transaction type: * Amount Received: Only applied when receiving an amount. * Amount Paid: Only applied when paying an amount. * Amount Paid/Received: Applied in both cases.''') match_amount = fields.Selection(selection=[ ('lower', 'Is Lower Than'), ('greater', 'Is Greater Than'), ('between', 'Is Between'), ], string='Amount Condition', help='The reconciliation model will only be applied when the amount being lower than, greater than or between specified amount(s).') match_amount_min = fields.Float(string='Amount Min Parameter') match_amount_max = fields.Float(string='Amount Max Parameter') match_label = fields.Selection(selection=[ ('contains', 'Contains'), ('not_contains', 'Not Contains'), ('match_regex', 'Match Regex'), ], string='Label', help='''The reconciliation model will only be applied when the label: * Contains: The proposition label must contains this string (case insensitive). * Not Contains: Negation of "Contains". * Match Regex: Define your own regular expression.''') match_label_param = fields.Char(string='Label Parameter') match_note = fields.Selection(selection=[ ('contains', 'Contains'), ('not_contains', 'Not Contains'), ('match_regex', 'Match Regex'), ], string='Note', help='''The reconciliation model will only be applied when the note: * Contains: The proposition note must contains this string (case insensitive). * Not Contains: Negation of "Contains". * Match Regex: Define your own regular expression.''') match_note_param = fields.Char(string='Note Parameter') match_transaction_type = fields.Selection(selection=[ ('contains', 'Contains'), ('not_contains', 'Not Contains'), ('match_regex', 'Match Regex'), ], string='Transaction Type', help='''The reconciliation model will only be applied when the transaction type: * Contains: The proposition transaction type must contains this string (case insensitive). * Not Contains: Negation of "Contains". * Match Regex: Define your own regular expression.''') match_transaction_type_param = fields.Char(string='Transaction Type Parameter') match_same_currency = fields.Boolean(string='Same Currency', default=True, help='Restrict to propositions having the same currency as the statement line.') allow_payment_tolerance = fields.Boolean( string="Allow Payment Gap", default=True, help="Difference accepted in case of underpayment.", ) payment_tolerance_param = fields.Float( string="Gap", default=0.0, help="The sum of total residual amount propositions matches the statement line amount under this amount/percentage.", ) payment_tolerance_type = fields.Selection( selection=[('percentage', "in percentage"), ('fixed_amount', "in amount")], required=True, default='percentage', help="The sum of total residual amount propositions and the statement line amount allowed gap type.", ) match_partner = fields.Boolean(string='Partner Is Set', help='The reconciliation model will only be applied when a customer/vendor is set.') match_partner_ids = fields.Many2many('res.partner', string='Restrict Partners to', help='The reconciliation model will only be applied to the selected customers/vendors.') match_partner_category_ids = fields.Many2many('res.partner.category', string='Restrict Partner Categories to', help='The reconciliation model will only be applied to the selected customer/vendor categories.') line_ids = fields.One2many('account.reconcile.model.line.template', 'model_id') decimal_separator = fields.Char(help="Every character that is nor a digit nor this separator will be removed from the matching string") class AccountReconcileModelLineTemplate(models.Model): _name = "account.reconcile.model.line.template" _description = 'Reconcile Model Line Template' model_id = fields.Many2one('account.reconcile.model.template') sequence = fields.Integer(required=True, default=10) account_id = fields.Many2one('account.account.template', string='Account', ondelete='cascade', domain=[('deprecated', '=', False)]) label = fields.Char(string='Journal Item Label') amount_type = fields.Selection([ ('fixed', 'Fixed'), ('percentage', 'Percentage of balance'), ('regex', 'From label'), ], required=True, default='percentage') amount_string = fields.Char(string="Amount") force_tax_included = fields.Boolean(string='Tax Included in Price', help='Force the tax to be managed as a price included tax.') tax_ids = fields.Many2many('account.tax.template', string='Taxes', ondelete='restrict')
56.049914
97,695
69,822
py
PYTHON
15.0
# -*- coding: utf-8 -*- import math from odoo import api, fields, models, _ from odoo.tools import float_is_zero from odoo.tools.misc import formatLang, format_date from odoo.exceptions import UserError, ValidationError class AccountCashboxLine(models.Model): """ Cash Box Details """ _name = 'account.cashbox.line' _description = 'CashBox Line' _rec_name = 'coin_value' _order = 'coin_value' @api.depends('coin_value', 'number') def _sub_total(self): """ Calculates Sub total""" for cashbox_line in self: cashbox_line.subtotal = cashbox_line.coin_value * cashbox_line.number coin_value = fields.Float(string='Coin/Bill Value', required=True, digits=0) number = fields.Integer(string='#Coins/Bills', help='Opening Unit Numbers') subtotal = fields.Float(compute='_sub_total', string='Subtotal', digits=0, readonly=True) cashbox_id = fields.Many2one('account.bank.statement.cashbox', string="Cashbox") currency_id = fields.Many2one('res.currency', related='cashbox_id.currency_id') class AccountBankStmtCashWizard(models.Model): """ Account Bank Statement popup that allows entering cash details. """ _name = 'account.bank.statement.cashbox' _description = 'Bank Statement Cashbox' _rec_name = 'id' cashbox_lines_ids = fields.One2many('account.cashbox.line', 'cashbox_id', string='Cashbox Lines') start_bank_stmt_ids = fields.One2many('account.bank.statement', 'cashbox_start_id') end_bank_stmt_ids = fields.One2many('account.bank.statement', 'cashbox_end_id') total = fields.Float(compute='_compute_total') currency_id = fields.Many2one('res.currency', compute='_compute_currency') @api.depends('start_bank_stmt_ids', 'end_bank_stmt_ids') def _compute_currency(self): for cashbox in self: cashbox.currency_id = False if cashbox.end_bank_stmt_ids: cashbox.currency_id = cashbox.end_bank_stmt_ids[0].currency_id if cashbox.start_bank_stmt_ids: cashbox.currency_id = cashbox.start_bank_stmt_ids[0].currency_id @api.depends('cashbox_lines_ids', 'cashbox_lines_ids.coin_value', 'cashbox_lines_ids.number') def _compute_total(self): for cashbox in self: cashbox.total = sum([line.subtotal for line in cashbox.cashbox_lines_ids]) @api.model def default_get(self, fields): vals = super(AccountBankStmtCashWizard, self).default_get(fields) balance = self.env.context.get('balance') statement_id = self.env.context.get('statement_id') if 'start_bank_stmt_ids' in fields and not vals.get('start_bank_stmt_ids') and statement_id and balance == 'start': vals['start_bank_stmt_ids'] = [(6, 0, [statement_id])] if 'end_bank_stmt_ids' in fields and not vals.get('end_bank_stmt_ids') and statement_id and balance == 'close': vals['end_bank_stmt_ids'] = [(6, 0, [statement_id])] return vals def name_get(self): result = [] for cashbox in self: result.append((cashbox.id, str(cashbox.total))) return result @api.model_create_multi def create(self, vals): cashboxes = super(AccountBankStmtCashWizard, self).create(vals) cashboxes._validate_cashbox() return cashboxes def write(self, vals): res = super(AccountBankStmtCashWizard, self).write(vals) self._validate_cashbox() return res def _validate_cashbox(self): for cashbox in self: if cashbox.start_bank_stmt_ids: cashbox.start_bank_stmt_ids.write({'balance_start': cashbox.total}) if cashbox.end_bank_stmt_ids: cashbox.end_bank_stmt_ids.write({'balance_end_real': cashbox.total}) class AccountBankStmtCloseCheck(models.TransientModel): """ Account Bank Statement wizard that check that closing balance is correct. """ _name = 'account.bank.statement.closebalance' _description = 'Bank Statement Closing Balance' def validate(self): bnk_stmt_id = self.env.context.get('active_id', False) if bnk_stmt_id: self.env['account.bank.statement'].browse(bnk_stmt_id).button_validate() return {'type': 'ir.actions.act_window_close'} class AccountBankStatement(models.Model): _name = "account.bank.statement" _description = "Bank Statement" _order = "date desc, name desc, id desc" _inherit = ['mail.thread', 'sequence.mixin'] _check_company_auto = True _sequence_index = "journal_id" # Note: the reason why we did 2 separate function with the same dependencies (one for balance_start and one for balance_end_real) # is because if we create a bank statement with a default value for one of the field but not the other, the compute method # won't be called and therefore the other field will have a value of 0 and we don't want that. @api.depends('previous_statement_id', 'previous_statement_id.balance_end_real') def _compute_starting_balance(self): # When a bank statement is inserted out-of-order several fields needs to be recomputed. # As the records to recompute are ordered by id, it may occur that the first record # to recompute start a recursive recomputation of field balance_end_real # To avoid this we sort the records by date for statement in self.sorted(key=lambda s: s.date): if statement.previous_statement_id.balance_end_real != statement.balance_start: statement.balance_start = statement.previous_statement_id.balance_end_real else: # Need default value statement.balance_start = statement.balance_start or 0.0 @api.depends('previous_statement_id', 'previous_statement_id.balance_end_real') def _compute_ending_balance(self): latest_statement = self.env['account.bank.statement'].search([('journal_id', '=', self[0].journal_id.id)], limit=1) for statement in self: # recompute balance_end_real in case we are in a bank journal and if we change the # balance_end_real of previous statement as we don't want # holes in case we add a statement in between 2 others statements. # We only do this for the bank journal as we use the balance_end_real in cash # journal for verification and creating cash difference entries so we don't want # to recompute the value in that case if statement.journal_type == 'bank': # If we are on last statement and that statement already has a balance_end_real, don't change the balance_end_real # Otherwise, recompute balance_end_real to prevent holes between statement. if latest_statement.id and statement.id == latest_statement.id and not float_is_zero(statement.balance_end_real, precision_digits=statement.currency_id.decimal_places): statement.balance_end_real = statement.balance_end_real or 0.0 else: total_entry_encoding = sum([line.amount for line in statement.line_ids]) statement.balance_end_real = statement.previous_statement_id.balance_end_real + total_entry_encoding else: # Need default value statement.balance_end_real = statement.balance_end_real or 0.0 @api.depends('line_ids', 'balance_start', 'line_ids.amount', 'balance_end_real') def _end_balance(self): for statement in self: statement.total_entry_encoding = sum([line.amount for line in statement.line_ids]) statement.balance_end = statement.balance_start + statement.total_entry_encoding statement.difference = statement.balance_end_real - statement.balance_end def _is_difference_zero(self): for bank_stmt in self: bank_stmt.is_difference_zero = float_is_zero(bank_stmt.difference, precision_digits=bank_stmt.currency_id.decimal_places) @api.depends('journal_id') def _compute_currency(self): for statement in self: statement.currency_id = statement.journal_id.currency_id or statement.company_id.currency_id @api.depends('move_line_ids') def _get_move_line_count(self): for statement in self: statement.move_line_count = len(statement.move_line_ids) @api.model def _default_journal(self): journal_type = self.env.context.get('journal_type', False) company_id = self.env.company.id if journal_type: return self.env['account.journal'].search([ ('type', '=', journal_type), ('company_id', '=', company_id) ], limit=1) return self.env['account.journal'] @api.depends('balance_start', 'previous_statement_id') def _compute_is_valid_balance_start(self): for bnk in self: bnk.is_valid_balance_start = ( bnk.currency_id.is_zero( bnk.balance_start - bnk.previous_statement_id.balance_end_real ) if bnk.previous_statement_id else True ) @api.depends('date', 'journal_id') def _get_previous_statement(self): for st in self: # Search for the previous statement domain = [('date', '<=', st.date), ('journal_id', '=', st.journal_id.id)] # The reason why we have to perform this test is because we have two use case here: # First one is in case we are creating a new record, in that case that new record does # not have any id yet. However if we are updating an existing record, the domain date <= st.date # will find the record itself, so we have to add a condition in the search to ignore self.id if not isinstance(st.id, models.NewId): domain.extend(['|', '&', ('id', '<', st.id), ('date', '=', st.date), '&', ('id', '!=', st.id), ('date', '!=', st.date)]) previous_statement = self.search(domain, limit=1, order='date desc, id desc') st.previous_statement_id = previous_statement.id name = fields.Char(string='Reference', states={'open': [('readonly', False)]}, copy=False, readonly=True) reference = fields.Char(string='External Reference', states={'open': [('readonly', False)]}, copy=False, readonly=True, help="Used to hold the reference of the external mean that created this statement (name of imported file, reference of online synchronization...)") date = fields.Date(required=True, states={'confirm': [('readonly', True)]}, index=True, copy=False, default=fields.Date.context_today) date_done = fields.Datetime(string="Closed On") balance_start = fields.Monetary(string='Starting Balance', states={'confirm': [('readonly', True)]}, compute='_compute_starting_balance', readonly=False, store=True, tracking=True) balance_end_real = fields.Monetary('Ending Balance', states={'confirm': [('readonly', True)]}, compute='_compute_ending_balance', recursive=True, readonly=False, store=True, tracking=True) state = fields.Selection(string='Status', required=True, readonly=True, copy=False, tracking=True, selection=[ ('open', 'New'), ('posted', 'Processing'), ('confirm', 'Validated'), ], default='open', help="The current state of your bank statement:" "- New: Fully editable with draft Journal Entries." "- Processing: No longer editable with posted Journal entries, ready for the reconciliation." "- Validated: All lines are reconciled. There is nothing left to process.") currency_id = fields.Many2one('res.currency', compute='_compute_currency', string="Currency") journal_id = fields.Many2one('account.journal', string='Journal', required=True, states={'confirm': [('readonly', True)]}, default=_default_journal, check_company=True) journal_type = fields.Selection(related='journal_id.type', help="Technical field used for usability purposes") company_id = fields.Many2one('res.company', related='journal_id.company_id', string='Company', store=True, readonly=True) total_entry_encoding = fields.Monetary('Transactions Subtotal', compute='_end_balance', store=True, help="Total of transaction lines.") balance_end = fields.Monetary('Computed Balance', compute='_end_balance', store=True, help='Balance as calculated based on Opening Balance and transaction lines') difference = fields.Monetary(compute='_end_balance', store=True, help="Difference between the computed ending balance and the specified ending balance.") line_ids = fields.One2many('account.bank.statement.line', 'statement_id', string='Statement lines', states={'confirm': [('readonly', True)]}, copy=True) move_line_ids = fields.One2many('account.move.line', 'statement_id', string='Entry lines', states={'confirm': [('readonly', True)]}) move_line_count = fields.Integer(compute="_get_move_line_count") all_lines_reconciled = fields.Boolean(compute='_compute_all_lines_reconciled', help="Technical field indicating if all statement lines are fully reconciled.") user_id = fields.Many2one('res.users', string='Responsible', required=False, default=lambda self: self.env.user) cashbox_start_id = fields.Many2one('account.bank.statement.cashbox', string="Starting Cashbox") cashbox_end_id = fields.Many2one('account.bank.statement.cashbox', string="Ending Cashbox") is_difference_zero = fields.Boolean(compute='_is_difference_zero', string='Is zero', help="Check if difference is zero.") previous_statement_id = fields.Many2one('account.bank.statement', help='technical field to compute starting balance correctly', compute='_get_previous_statement', store=True) is_valid_balance_start = fields.Boolean(string="Is Valid Balance Start", store=True, compute="_compute_is_valid_balance_start", help="Technical field to display a warning message in case starting balance is different than previous ending balance") country_code = fields.Char(related='company_id.account_fiscal_country_id.code') def write(self, values): res = super(AccountBankStatement, self).write(values) if values.get('date') or values.get('journal'): # If we are changing the date or journal of a bank statement, we have to change its previous_statement_id. This is done # automatically using the compute function, but we also have to change the previous_statement_id of records that were # previously pointing toward us and records that were pointing towards our new previous_statement_id. This is done here # by marking those record as needing to be recomputed. # Note that marking the field is not enough as we also have to recompute all its other fields that are depending on 'previous_statement_id' # hence the need to call modified afterwards. to_recompute = self.search([('previous_statement_id', 'in', self.ids), ('id', 'not in', self.ids), ('journal_id', 'in', self.mapped('journal_id').ids)]) if to_recompute: self.env.add_to_compute(self._fields['previous_statement_id'], to_recompute) to_recompute.modified(['previous_statement_id']) next_statements_to_recompute = self.search([('previous_statement_id', 'in', [st.previous_statement_id.id for st in self]), ('id', 'not in', self.ids), ('journal_id', 'in', self.mapped('journal_id').ids)]) if next_statements_to_recompute: self.env.add_to_compute(self._fields['previous_statement_id'], next_statements_to_recompute) next_statements_to_recompute.modified(['previous_statement_id']) return res @api.model_create_multi def create(self, values): res = super(AccountBankStatement, self).create(values) # Upon bank stmt creation, it is possible that the statement is inserted between two other statements and not at the end # In that case, we have to search for statement that are pointing to the same previous_statement_id as ourselve in order to # change their previous_statement_id to us. This is done by marking the field 'previous_statement_id' to be recomputed for such records. # Note that marking the field is not enough as we also have to recompute all its other fields that are depending on 'previous_statement_id' # hence the need to call modified afterwards. # The reason we are doing this here and not in a compute field is that it is not easy to write dependencies for such field. next_statements_to_recompute = self.search([('previous_statement_id', 'in', [st.previous_statement_id.id for st in res]), ('id', 'not in', res.ids), ('journal_id', 'in', res.journal_id.ids)]) if next_statements_to_recompute: self.env.add_to_compute(self._fields['previous_statement_id'], next_statements_to_recompute) next_statements_to_recompute.modified(['previous_statement_id']) return res @api.depends('line_ids.is_reconciled') def _compute_all_lines_reconciled(self): for statement in self: statement.all_lines_reconciled = all(st_line.is_reconciled for st_line in statement.line_ids) @api.onchange('journal_id') def onchange_journal_id(self): for st_line in self.line_ids: st_line.journal_id = self.journal_id st_line.currency_id = self.journal_id.currency_id or self.company_id.currency_id def _check_balance_end_real_same_as_computed(self): """ Check the balance_end_real (encoded manually by the user) is equals to the balance_end (computed by odoo). """ return self._check_cash_balance_end_real_same_as_computed() and self._check_bank_balance_end_real_same_as_computed() def _check_cash_balance_end_real_same_as_computed(self): """ Check the balance_end_real (encoded manually by the user) is equals to the balance_end (computed by odoo). For a cash statement, if there is a difference, the different is set automatically to a profit/loss account. """ for statement in self.filtered(lambda stmt: stmt.journal_type == 'cash'): if not statement.currency_id.is_zero(statement.difference): st_line_vals = { 'statement_id': statement.id, 'journal_id': statement.journal_id.id, 'amount': statement.difference, 'date': statement.date, } if statement.currency_id.compare_amounts(statement.difference, 0.0) < 0.0: if not statement.journal_id.loss_account_id: raise UserError(_( "Please go on the %s journal and define a Loss Account. " "This account will be used to record cash difference.", statement.journal_id.name )) st_line_vals['payment_ref'] = _("Cash difference observed during the counting (Loss)") st_line_vals['counterpart_account_id'] = statement.journal_id.loss_account_id.id else: # statement.difference > 0.0 if not statement.journal_id.profit_account_id: raise UserError(_( "Please go on the %s journal and define a Profit Account. " "This account will be used to record cash difference.", statement.journal_id.name )) st_line_vals['payment_ref'] = _("Cash difference observed during the counting (Profit)") st_line_vals['counterpart_account_id'] = statement.journal_id.profit_account_id.id self.env['account.bank.statement.line'].create(st_line_vals) return True def _check_bank_balance_end_real_same_as_computed(self): """ Check the balance_end_real (encoded manually by the user) is equals to the balance_end (computed by odoo). """ for statement in self.filtered(lambda stmt: stmt.journal_type == 'bank'): if not statement.currency_id.is_zero(statement.difference): balance_end_real = formatLang(self.env, statement.balance_end_real, currency_obj=statement.currency_id) balance_end = formatLang(self.env, statement.balance_end, currency_obj=statement.currency_id) raise UserError(_( 'The ending balance is incorrect !\nThe expected balance (%(real_balance)s) is different from the computed one (%(computed_balance)s).', real_balance=balance_end_real, computed_balance=balance_end )) return True @api.ondelete(at_uninstall=False) def _unlink_only_if_open(self): for statement in self: if statement.state != 'open': raise UserError(_('In order to delete a bank statement, you must first cancel it to delete related journal items.')) def unlink(self): for statement in self: # Explicitly unlink bank statement lines so it will check that the related journal entries have been deleted first statement.line_ids.unlink() # Some other bank statements might be link to this one, so in that case we have to switch the previous_statement_id # from that statement to the one linked to this statement next_statement = self.search([('previous_statement_id', '=', statement.id), ('journal_id', '=', statement.journal_id.id)]) if next_statement: next_statement.previous_statement_id = statement.previous_statement_id return super(AccountBankStatement, self).unlink() # ------------------------------------------------------------------------- # CONSTRAINT METHODS # ------------------------------------------------------------------------- @api.constrains('journal_id') def _check_journal(self): for statement in self: if any(st_line.journal_id != statement.journal_id for st_line in statement.line_ids): raise ValidationError(_('The journal of a bank statement line must always be the same as the bank statement one.')) def _constrains_date_sequence(self): # Multiple import methods set the name to things that are not sequences: # i.e. Statement from {date1} to {date2} # It makes this constraint not applicable, and it is less needed on bank statements as it # is only an indication and not some thing legal. return # ------------------------------------------------------------------------- # BUSINESS METHODS # ------------------------------------------------------------------------- def open_cashbox_id(self): self.ensure_one() context = dict(self.env.context or {}) if context.get('balance'): context['statement_id'] = self.id if context['balance'] == 'start': cashbox_id = self.cashbox_start_id.id elif context['balance'] == 'close': cashbox_id = self.cashbox_end_id.id else: cashbox_id = False action = { 'name': _('Cash Control'), 'view_mode': 'form', 'res_model': 'account.bank.statement.cashbox', 'view_id': self.env.ref('account.view_account_bnk_stmt_cashbox_footer').id, 'type': 'ir.actions.act_window', 'res_id': cashbox_id, 'context': context, 'target': 'new' } return action def button_post(self): ''' Move the bank statements from 'draft' to 'posted'. ''' if any(statement.state != 'open' for statement in self): raise UserError(_("Only new statements can be posted.")) self._check_cash_balance_end_real_same_as_computed() for statement in self: if not statement.name: statement._set_next_sequence() self.write({'state': 'posted'}) lines_of_moves_to_post = self.line_ids.filtered(lambda line: line.move_id.state != 'posted') if lines_of_moves_to_post: lines_of_moves_to_post.move_id._post(soft=False) def button_validate(self): if any(statement.state != 'posted' or not statement.all_lines_reconciled for statement in self): raise UserError(_('All the account entries lines must be processed in order to validate the statement.')) for statement in self: # Chatter. statement.message_post(body=_('Statement %s confirmed.', statement.name)) # Bank statement report. if statement.journal_id.type == 'bank': content, content_type = self.env.ref('account.action_report_account_statement')._render(statement.id) self.env['ir.attachment'].create({ 'name': statement.name and _("Bank Statement %s.pdf", statement.name) or _("Bank Statement.pdf"), 'type': 'binary', 'raw': content, 'res_model': statement._name, 'res_id': statement.id }) self._check_balance_end_real_same_as_computed() self.write({'state': 'confirm', 'date_done': fields.Datetime.now()}) def button_validate_or_action(self): if self.journal_type == 'cash' and not self.currency_id.is_zero(self.difference): return self.env['ir.actions.act_window']._for_xml_id('account.action_view_account_bnk_stmt_check') return self.button_validate() def button_reopen(self): ''' Move the bank statements back to the 'open' state. ''' if any(statement.state == 'draft' for statement in self): raise UserError(_("Only validated statements can be reset to new.")) self.write({'state': 'open'}) self.line_ids.move_id.button_draft() self.line_ids.button_undo_reconciliation() def button_reprocess(self): """Move the bank statements back to the 'posted' state.""" if any(statement.state != 'confirm' for statement in self): raise UserError(_("Only Validated statements can be reset to new.")) self.write({'state': 'posted', 'date_done': False}) def button_journal_entries(self): return { 'name': _('Journal Entries'), 'view_mode': 'tree', 'res_model': 'account.move.line', 'view_id': self.env.ref('account.view_move_line_tree_grouped_bank_cash').id, 'type': 'ir.actions.act_window', 'domain': [('move_id', 'in', self.line_ids.move_id.ids)], 'context': { 'journal_id': self.journal_id.id, 'group_by': 'move_id', 'expand': True } } def _get_last_sequence_domain(self, relaxed=False): self.ensure_one() where_string = "WHERE journal_id = %(journal_id)s AND name != '/'" param = {'journal_id': self.journal_id.id} if not relaxed: domain = [('journal_id', '=', self.journal_id.id), ('id', '!=', self.id or self._origin.id), ('name', '!=', False)] previous_name = self.search(domain + [('date', '<', self.date)], order='date desc', limit=1).name if not previous_name: previous_name = self.search(domain, order='date desc', limit=1).name sequence_number_reset = self._deduce_sequence_number_reset(previous_name) if sequence_number_reset == 'year': where_string += " AND date_trunc('year', date) = date_trunc('year', %(date)s) " param['date'] = self.date elif sequence_number_reset == 'month': where_string += " AND date_trunc('month', date) = date_trunc('month', %(date)s) " param['date'] = self.date return where_string, param def _get_starting_sequence(self): self.ensure_one() return "%s %s %04d/%02d/00000" % (self.journal_id.code, _('Statement'), self.date.year, self.date.month) class AccountBankStatementLine(models.Model): _name = "account.bank.statement.line" _inherits = {'account.move': 'move_id'} _description = "Bank Statement Line" _order = "statement_id desc, date, sequence, id desc" _check_company_auto = True # FIXME: Fields having the same name in both tables are confusing (partner_id & state). We don't change it because: # - It's a mess to track/fix. # - Some fields here could be simplified when the onchanges will be gone in account.move. # Should be improved in the future. # == Business fields == move_id = fields.Many2one( comodel_name='account.move', auto_join=True, string='Journal Entry', required=True, readonly=True, ondelete='cascade', check_company=True) statement_id = fields.Many2one( comodel_name='account.bank.statement', string='Statement', index=True, required=True, ondelete='cascade', check_company=True) sequence = fields.Integer(index=True, help="Gives the sequence order when displaying a list of bank statement lines.", default=1) account_number = fields.Char(string='Bank Account Number', help="Technical field used to store the bank account number before its creation, upon the line's processing") partner_name = fields.Char( help="This field is used to record the third party name when importing bank statement in electronic format, " "when the partner doesn't exist yet in the database (or cannot be found).") transaction_type = fields.Char(string='Transaction Type') payment_ref = fields.Char(string='Label', required=True) amount = fields.Monetary(currency_field='currency_id') amount_currency = fields.Monetary(currency_field='foreign_currency_id', help="The amount expressed in an optional other currency if it is a multi-currency entry.") foreign_currency_id = fields.Many2one('res.currency', string='Foreign Currency', help="The optional other currency if it is a multi-currency entry.") amount_residual = fields.Float(string="Residual Amount", compute="_compute_is_reconciled", store=True, help="The amount left to be reconciled on this statement line (signed according to its move lines' balance), expressed in its currency. This is a technical field use to speedup the application of reconciliation models.") currency_id = fields.Many2one('res.currency', string='Journal Currency') partner_id = fields.Many2one( comodel_name='res.partner', string='Partner', ondelete='restrict', domain="['|', ('parent_id','=', False), ('is_company','=',True)]", check_company=True) payment_ids = fields.Many2many( comodel_name='account.payment', relation='account_payment_account_bank_statement_line_rel', string='Auto-generated Payments', help="Payments generated during the reconciliation of this bank statement lines.") # == Display purpose fields == is_reconciled = fields.Boolean(string='Is Reconciled', store=True, compute='_compute_is_reconciled', help="Technical field indicating if the statement line is already reconciled.") state = fields.Selection(related='statement_id.state', string='Status', readonly=True) country_code = fields.Char(related='company_id.account_fiscal_country_id.code') # ------------------------------------------------------------------------- # HELPERS # ------------------------------------------------------------------------- def _seek_for_lines(self): ''' Helper used to dispatch the journal items between: - The lines using the liquidity account. - The lines using the transfer account. - The lines being not in one of the two previous categories. :return: (liquidity_lines, suspense_lines, other_lines) ''' liquidity_lines = self.env['account.move.line'] suspense_lines = self.env['account.move.line'] other_lines = self.env['account.move.line'] for line in self.move_id.line_ids: if line.account_id == self.journal_id.default_account_id: liquidity_lines += line elif line.account_id == self.journal_id.suspense_account_id: suspense_lines += line else: other_lines += line return liquidity_lines, suspense_lines, other_lines @api.model def _prepare_liquidity_move_line_vals(self): ''' Prepare values to create a new account.move.line record corresponding to the liquidity line (having the bank/cash account). :return: The values to create a new account.move.line record. ''' self.ensure_one() statement = self.statement_id journal = statement.journal_id company_currency = journal.company_id.currency_id journal_currency = journal.currency_id or company_currency if self.foreign_currency_id and journal_currency: currency_id = journal_currency.id if self.foreign_currency_id == company_currency: amount_currency = self.amount balance = self.amount_currency else: amount_currency = self.amount balance = journal_currency._convert(amount_currency, company_currency, journal.company_id, self.date) elif self.foreign_currency_id and not journal_currency: amount_currency = self.amount_currency balance = self.amount currency_id = self.foreign_currency_id.id elif not self.foreign_currency_id and journal_currency: currency_id = journal_currency.id amount_currency = self.amount balance = journal_currency._convert(amount_currency, journal.company_id.currency_id, journal.company_id, self.date) else: currency_id = company_currency.id amount_currency = self.amount balance = self.amount return { 'name': self.payment_ref, 'move_id': self.move_id.id, 'partner_id': self.partner_id.id, 'currency_id': currency_id, 'account_id': journal.default_account_id.id, 'debit': balance > 0 and balance or 0.0, 'credit': balance < 0 and -balance or 0.0, 'amount_currency': amount_currency, } @api.model def _prepare_counterpart_move_line_vals(self, counterpart_vals, move_line=None): ''' Prepare values to create a new account.move.line move_line. By default, without specified 'counterpart_vals' or 'move_line', the counterpart line is created using the suspense account. Otherwise, this method is also called during the reconciliation to prepare the statement line's journal entry. In that case, 'counterpart_vals' will be used to create a custom account.move.line (from the reconciliation widget) and 'move_line' will be used to create the counterpart of an existing account.move.line to which the newly created journal item will be reconciled. :param counterpart_vals: A python dictionary containing: 'balance': Optional amount to consider during the reconciliation. If a foreign currency is set on the counterpart line in the same foreign currency as the statement line, then this amount is considered as the amount in foreign currency. If not specified, the full balance is took. This value must be provided if move_line is not. 'amount_residual': The residual amount to reconcile expressed in the company's currency. /!\ This value should be equivalent to move_line.amount_residual except we want to avoid browsing the record when the only thing we need in an overview of the reconciliation, for example in the reconciliation widget. 'amount_residual_currency': The residual amount to reconcile expressed in the foreign's currency. Using this key doesn't make sense without passing 'currency_id' in vals. /!\ This value should be equivalent to move_line.amount_residual_currency except we want to avoid browsing the record when the only thing we need in an overview of the reconciliation, for example in the reconciliation widget. **kwargs: Additional values that need to land on the account.move.line to create. :param move_line: An optional account.move.line move_line representing the counterpart line to reconcile. :return: The values to create a new account.move.line move_line. ''' self.ensure_one() statement = self.statement_id journal = statement.journal_id company_currency = journal.company_id.currency_id journal_currency = journal.currency_id or company_currency foreign_currency = self.foreign_currency_id or journal_currency or company_currency statement_line_rate = (self.amount_currency / self.amount) if self.amount else 0.0 balance_to_reconcile = counterpart_vals.pop('balance', None) amount_residual = -counterpart_vals.pop('amount_residual', move_line.amount_residual if move_line else 0.0) \ if balance_to_reconcile is None else balance_to_reconcile amount_residual_currency = -counterpart_vals.pop('amount_residual_currency', move_line.amount_residual_currency if move_line else 0.0)\ if balance_to_reconcile is None else balance_to_reconcile if 'currency_id' in counterpart_vals: currency_id = counterpart_vals['currency_id'] or foreign_currency.id elif move_line: currency_id = move_line.currency_id.id or company_currency.id else: currency_id = foreign_currency.id if currency_id not in (foreign_currency.id, journal_currency.id): currency_id = company_currency.id amount_residual_currency = 0.0 amounts = { company_currency.id: 0.0, journal_currency.id: 0.0, foreign_currency.id: 0.0, } amounts[currency_id] = amount_residual_currency amounts[company_currency.id] = amount_residual if currency_id == journal_currency.id and journal_currency != company_currency: if foreign_currency != company_currency: amounts[company_currency.id] = journal_currency._convert(amounts[currency_id], company_currency, journal.company_id, self.date) if statement_line_rate: amounts[foreign_currency.id] = amounts[currency_id] * statement_line_rate elif currency_id == foreign_currency.id and self.foreign_currency_id: if statement_line_rate: amounts[journal_currency.id] = amounts[foreign_currency.id] / statement_line_rate if foreign_currency != company_currency: amounts[company_currency.id] = journal_currency._convert(amounts[journal_currency.id], company_currency, journal.company_id, self.date) else: amounts[journal_currency.id] = company_currency._convert(amounts[company_currency.id], journal_currency, journal.company_id, self.date) if statement_line_rate: amounts[foreign_currency.id] = amounts[journal_currency.id] * statement_line_rate if foreign_currency == company_currency and journal_currency != company_currency and self.foreign_currency_id: balance = amounts[foreign_currency.id] else: balance = amounts[company_currency.id] if foreign_currency != company_currency and self.foreign_currency_id: amount_currency = amounts[foreign_currency.id] currency_id = foreign_currency.id elif journal_currency != company_currency and not self.foreign_currency_id: amount_currency = amounts[journal_currency.id] currency_id = journal_currency.id else: amount_currency = amounts[company_currency.id] currency_id = company_currency.id return { **counterpart_vals, 'name': counterpart_vals.get('name', move_line.name if move_line else ''), 'move_id': self.move_id.id, 'partner_id': self.partner_id.id or counterpart_vals.get('partner_id', move_line.partner_id.id if move_line else False), 'currency_id': currency_id, 'account_id': counterpart_vals.get('account_id', move_line.account_id.id if move_line else False), 'debit': balance if balance > 0.0 else 0.0, 'credit': -balance if balance < 0.0 else 0.0, 'amount_currency': amount_currency, } @api.model def _prepare_move_line_default_vals(self, counterpart_account_id=None): ''' Prepare the dictionary to create the default account.move.lines for the current account.bank.statement.line record. :return: A list of python dictionary to be passed to the account.move.line's 'create' method. ''' self.ensure_one() if not counterpart_account_id: counterpart_account_id = self.journal_id.suspense_account_id.id if not counterpart_account_id: raise UserError(_( "You can't create a new statement line without a suspense account set on the %s journal." ) % self.journal_id.display_name) liquidity_line_vals = self._prepare_liquidity_move_line_vals() # Ensure the counterpart will have a balance exactly equals to the amount in journal currency. # This avoid some rounding issues when the currency rate between two currencies is not symmetrical. # E.g: # A.convert(amount_a, B) = amount_b # B.convert(amount_b, A) = amount_c != amount_a counterpart_vals = { 'name': self.payment_ref, 'account_id': counterpart_account_id, 'amount_residual': liquidity_line_vals['debit'] - liquidity_line_vals['credit'], } if self.foreign_currency_id and self.foreign_currency_id != self.company_currency_id: # Ensure the counterpart will have exactly the same amount in foreign currency as the amount set in the # statement line to avoid some rounding issues when making a currency conversion. counterpart_vals.update({ 'currency_id': self.foreign_currency_id.id, 'amount_residual_currency': self.amount_currency, }) elif liquidity_line_vals['currency_id']: # Ensure the counterpart will have a balance exactly equals to the amount in journal currency. # This avoid some rounding issues when the currency rate between two currencies is not symmetrical. # E.g: # A.convert(amount_a, B) = amount_b # B.convert(amount_b, A) = amount_c != amount_a counterpart_vals.update({ 'currency_id': liquidity_line_vals['currency_id'], 'amount_residual_currency': liquidity_line_vals['amount_currency'], }) counterpart_line_vals = self._prepare_counterpart_move_line_vals(counterpart_vals) return [liquidity_line_vals, counterpart_line_vals] # ------------------------------------------------------------------------- # COMPUTE METHODS # ------------------------------------------------------------------------- @api.depends('journal_id', 'currency_id', 'amount', 'foreign_currency_id', 'amount_currency', 'move_id.to_check', 'move_id.line_ids.account_id', 'move_id.line_ids.amount_currency', 'move_id.line_ids.amount_residual_currency', 'move_id.line_ids.currency_id', 'move_id.line_ids.matched_debit_ids', 'move_id.line_ids.matched_credit_ids') def _compute_is_reconciled(self): ''' Compute the field indicating if the statement lines are already reconciled with something. This field is used for display purpose (e.g. display the 'cancel' button on the statement lines). Also computes the residual amount of the statement line. ''' for st_line in self: liquidity_lines, suspense_lines, other_lines = st_line._seek_for_lines() # Compute residual amount if st_line.to_check: st_line.amount_residual = -st_line.amount_currency if st_line.foreign_currency_id else -st_line.amount elif suspense_lines.account_id.reconcile: st_line.amount_residual = sum(suspense_lines.mapped('amount_residual_currency')) else: st_line.amount_residual = sum(suspense_lines.mapped('amount_currency')) # Compute is_reconciled if not st_line.id: # New record: The journal items are not yet there. st_line.is_reconciled = False elif suspense_lines: # In case of the statement line comes from an older version, it could have a residual amount of zero. st_line.is_reconciled = suspense_lines.currency_id.is_zero(st_line.amount_residual) elif st_line.currency_id.is_zero(st_line.amount): st_line.is_reconciled = True else: # The journal entry seems reconciled. st_line.is_reconciled = True # ------------------------------------------------------------------------- # CONSTRAINT METHODS # ------------------------------------------------------------------------- @api.constrains('amount', 'amount_currency', 'currency_id', 'foreign_currency_id', 'journal_id') def _check_amounts_currencies(self): ''' Ensure the consistency the specified amounts and the currencies. ''' for st_line in self: if st_line.journal_id != st_line.statement_id.journal_id: raise ValidationError(_('The journal of a statement line must always be the same as the bank statement one.')) if st_line.foreign_currency_id == st_line.currency_id: raise ValidationError(_("The foreign currency must be different than the journal one: %s", st_line.currency_id.name)) if not st_line.foreign_currency_id and st_line.amount_currency: raise ValidationError(_("You can't provide an amount in foreign currency without specifying a foreign currency.")) # ------------------------------------------------------------------------- # LOW-LEVEL METHODS # ------------------------------------------------------------------------- @api.model_create_multi def create(self, vals_list): # OVERRIDE counterpart_account_ids = [] for vals in vals_list: statement = self.env['account.bank.statement'].browse(vals['statement_id']) if statement.state != 'open' and self._context.get('check_move_validity', True): raise UserError(_("You can only create statement line in open bank statements.")) # Force the move_type to avoid inconsistency with residual 'default_move_type' inside the context. vals['move_type'] = 'entry' journal = statement.journal_id # Ensure the journal is the same as the statement one. vals['journal_id'] = journal.id vals['currency_id'] = (journal.currency_id or journal.company_id.currency_id).id if 'date' not in vals: vals['date'] = statement.date # Avoid having the same foreign_currency_id as currency_id. journal_currency = journal.currency_id or journal.company_id.currency_id if vals.get('foreign_currency_id') == journal_currency.id: vals['foreign_currency_id'] = None vals['amount_currency'] = 0.0 # Hack to force different account instead of the suspense account. counterpart_account_ids.append(vals.pop('counterpart_account_id', None)) st_lines = super().create(vals_list) for i, st_line in enumerate(st_lines): counterpart_account_id = counterpart_account_ids[i] to_write = {'statement_line_id': st_line.id, 'narration': st_line.narration} if 'line_ids' not in vals_list[i]: to_write['line_ids'] = [(0, 0, line_vals) for line_vals in st_line._prepare_move_line_default_vals(counterpart_account_id=counterpart_account_id)] st_line.move_id.write(to_write) # Otherwise field narration will be recomputed silently (at next flush) when writing on partner_id self.env.remove_to_compute(st_line.move_id._fields['narration'], st_line.move_id) return st_lines def write(self, vals): # OVERRIDE res = super().write(vals) self._synchronize_to_moves(set(vals.keys())) return res def unlink(self): # OVERRIDE to unlink the inherited account.move (move_id field) as well. moves = self.with_context(force_delete=True).mapped('move_id') res = super().unlink() moves.unlink() return res # ------------------------------------------------------------------------- # SYNCHRONIZATION account.bank.statement.line <-> account.move # ------------------------------------------------------------------------- def _synchronize_from_moves(self, changed_fields): ''' Update the account.bank.statement.line regarding its related account.move. Also, check both models are still consistent. :param changed_fields: A set containing all modified fields on account.move. ''' if self._context.get('skip_account_move_synchronization'): return for st_line in self.with_context(skip_account_move_synchronization=True): move = st_line.move_id move_vals_to_write = {} st_line_vals_to_write = {} if 'state' in changed_fields: if (st_line.state == 'open' and move.state != 'draft') or (st_line.state in ('posted', 'confirm') and move.state != 'posted'): raise UserError(_( "You can't manually change the state of journal entry %s, as it has been created by bank " "statement %s." ) % (st_line.move_id.display_name, st_line.statement_id.display_name)) if 'line_ids' in changed_fields: liquidity_lines, suspense_lines, other_lines = st_line._seek_for_lines() company_currency = st_line.journal_id.company_id.currency_id journal_currency = st_line.journal_id.currency_id if st_line.journal_id.currency_id != company_currency else False if len(liquidity_lines) != 1: raise UserError(_( "The journal entry %s reached an invalid state regarding its related statement line.\n" "To be consistent, the journal entry must always have exactly one journal item involving the " "bank/cash account." ) % st_line.move_id.display_name) st_line_vals_to_write.update({ 'payment_ref': liquidity_lines.name, 'partner_id': liquidity_lines.partner_id.id, }) # Update 'amount' according to the liquidity line. if journal_currency: st_line_vals_to_write.update({ 'amount': liquidity_lines.amount_currency, }) else: st_line_vals_to_write.update({ 'amount': liquidity_lines.balance, }) if len(suspense_lines) == 1: if journal_currency and suspense_lines.currency_id == journal_currency: # The suspense line is expressed in the journal's currency meaning the foreign currency # set on the statement line is no longer needed. st_line_vals_to_write.update({ 'amount_currency': 0.0, 'foreign_currency_id': False, }) elif not journal_currency and suspense_lines.currency_id == company_currency: # Don't set a specific foreign currency on the statement line. st_line_vals_to_write.update({ 'amount_currency': 0.0, 'foreign_currency_id': False, }) else: # Update the statement line regarding the foreign currency of the suspense line. st_line_vals_to_write.update({ 'amount_currency': -suspense_lines.amount_currency, 'foreign_currency_id': suspense_lines.currency_id.id, }) move_vals_to_write.update({ 'partner_id': liquidity_lines.partner_id.id, 'currency_id': (st_line.foreign_currency_id or journal_currency or company_currency).id, }) move.write(move._cleanup_write_orm_values(move, move_vals_to_write)) st_line.write(move._cleanup_write_orm_values(st_line, st_line_vals_to_write)) def _synchronize_to_moves(self, changed_fields): ''' Update the account.move regarding the modified account.bank.statement.line. :param changed_fields: A list containing all modified fields on account.bank.statement.line. ''' if self._context.get('skip_account_move_synchronization'): return if not any(field_name in changed_fields for field_name in ( 'payment_ref', 'amount', 'amount_currency', 'foreign_currency_id', 'currency_id', 'partner_id', )): return for st_line in self.with_context(skip_account_move_synchronization=True): liquidity_lines, suspense_lines, other_lines = st_line._seek_for_lines() company_currency = st_line.journal_id.company_id.currency_id journal_currency = st_line.journal_id.currency_id if st_line.journal_id.currency_id != company_currency else False line_vals_list = st_line._prepare_move_line_default_vals() line_ids_commands = [(1, liquidity_lines.id, line_vals_list[0])] if suspense_lines: line_ids_commands.append((1, suspense_lines.id, line_vals_list[1])) else: line_ids_commands.append((0, 0, line_vals_list[1])) for line in other_lines: line_ids_commands.append((2, line.id)) st_line_vals = { 'currency_id': (st_line.foreign_currency_id or journal_currency or company_currency).id, 'line_ids': line_ids_commands, } if st_line.move_id.partner_id != st_line.partner_id: st_line_vals['partner_id'] = st_line.partner_id.id st_line.move_id.write(st_line_vals) # ------------------------------------------------------------------------- # RECONCILIATION METHODS # ------------------------------------------------------------------------- def _prepare_reconciliation(self, lines_vals_list, allow_partial=False): ''' Helper for the "reconcile" method used to get a full preview of the reconciliation result. This method is quite useful to deal with reconcile models or the reconciliation widget because it ensures the values seen by the user are exactly the values you get after reconciling. :param lines_vals_list: See the 'reconcile' method. :param allow_partial: In case of matching a line having an higher amount, allow creating a partial instead an open balance on the statement line. :return: The diff to be applied on the statement line as a tuple ( lines_to_create: The values to create the account.move.line on the statement line. payments_to_create: The values to create the account.payments. open_balance_vals: A dictionary to create the open-balance line or None if the reconciliation is full. existing_lines: The counterpart lines to which the reconciliation will be done. ) ''' self.ensure_one() journal = self.journal_id company_currency = journal.company_id.currency_id foreign_currency = self.foreign_currency_id or journal.currency_id or company_currency liquidity_lines, suspense_lines, other_lines = self._seek_for_lines() # Ensure the statement line has not yet been already reconciled. # If the move has 'to_check' enabled, it means the statement line has created some lines that # need to be checked later and replaced by the real ones. if not self.move_id.to_check and other_lines: raise UserError(_("The statement line has already been reconciled.")) # A list of dictionary containing: # - line_vals: The values to create the account.move.line on the statement line. # - payment_vals: The optional values to create a bridge account.payment # - counterpart_line: The optional counterpart line to reconcile with 'line'. reconciliation_overview = [] total_balance = liquidity_lines.balance total_amount_currency = -self._prepare_move_line_default_vals()[1]['amount_currency'] sign = 1 if liquidity_lines.balance > 0.0 else -1 # Step 1: Split 'lines_vals_list' into two batches: # - The existing account.move.lines that need to be reconciled with the statement line. # => Will be managed at step 2. # - The account.move.lines to be created from scratch. # => Will be managed directly. # In case of the payment is matched directly with an higher amount, don't create an open # balance but a partial reconciliation. partial_rec_needed = allow_partial to_browse_ids = [] to_process_vals = [] for vals in lines_vals_list: # Don't modify the params directly. vals = dict(vals) if 'id' in vals: # Existing account.move.line. to_browse_ids.append(vals.pop('id')) to_process_vals.append(vals) if any(x in vals for x in ('balance', 'amount_residual', 'amount_residual_currency')): partial_rec_needed = False else: # Newly created account.move.line from scratch. line_vals = self._prepare_counterpart_move_line_vals(vals) total_balance += line_vals['debit'] - line_vals['credit'] total_amount_currency += line_vals['amount_currency'] reconciliation_overview.append({'line_vals': line_vals}) partial_rec_needed = False # Step 2: Browse counterpart lines all in one and process them. existing_lines = self.env['account.move.line'].browse(to_browse_ids) i = 0 for line, counterpart_vals in zip(existing_lines, to_process_vals): line_vals = self._prepare_counterpart_move_line_vals(counterpart_vals, move_line=line) balance = line_vals['debit'] - line_vals['credit'] amount_currency = line_vals['amount_currency'] i += 1 if i == len(existing_lines): # Last line. if partial_rec_needed and sign * (total_amount_currency + amount_currency) < 0.0: # On the last aml, when the total matched amount becomes higher than the residual amount of the # statement line, make sure to not create an open balance later. line_vals = self._prepare_counterpart_move_line_vals( { **counterpart_vals, 'amount_residual': -math.copysign(total_balance, balance), 'amount_residual_currency': -math.copysign(total_amount_currency, amount_currency), 'currency_id': foreign_currency.id, }, move_line=line, ) balance = line_vals['debit'] - line_vals['credit'] amount_currency = line_vals['amount_currency'] elif sign * total_amount_currency < 0.0: # The partial reconciliation is no longer an option since the total matched amount is now higher than # the residual amount of the statement line but this is not the last line to process. Then, since we # don't want to create zero balance lines, do nothing and let the open-balance be created like it # should. partial_rec_needed = False total_balance += balance total_amount_currency += amount_currency reconciliation_overview.append({ 'line_vals': line_vals, 'counterpart_line': line, }) # Step 3: Fix rounding issue due to currency conversions. # Add the remaining balance on the first encountered line starting with the custom ones. if foreign_currency.is_zero(total_amount_currency) and not company_currency.is_zero(total_balance): vals = reconciliation_overview[0]['line_vals'] new_balance = vals['debit'] - vals['credit'] - total_balance vals.update({ 'debit': new_balance if new_balance > 0.0 else 0.0, 'credit': -new_balance if new_balance < 0.0 else 0.0, }) total_balance = 0.0 # Step 4: If the journal entry is not yet balanced, create an open balance. if self.company_currency_id.round(total_balance): counterpart_vals = { 'name': '%s: %s' % (self.payment_ref, _('Open Balance')), 'balance': -total_balance, 'currency_id': self.company_currency_id.id, } partner = self.partner_id or existing_lines.mapped('partner_id')[:1] if partner: if self.amount > 0: open_balance_account = partner.with_company(self.company_id).property_account_receivable_id else: open_balance_account = partner.with_company(self.company_id).property_account_payable_id counterpart_vals['account_id'] = open_balance_account.id counterpart_vals['partner_id'] = partner.id else: if self.amount > 0: open_balance_account = self.company_id.partner_id.with_company(self.company_id).property_account_receivable_id else: open_balance_account = self.company_id.partner_id.with_company(self.company_id).property_account_payable_id counterpart_vals['account_id'] = open_balance_account.id open_balance_vals = self._prepare_counterpart_move_line_vals(counterpart_vals) else: open_balance_vals = None return reconciliation_overview, open_balance_vals def reconcile(self, lines_vals_list, to_check=False, allow_partial=False): ''' Perform a reconciliation on the current account.bank.statement.line with some counterpart account.move.line. If the statement line entry is not fully balanced after the reconciliation, an open balance will be created using the partner. :param lines_vals_list: A list of python dictionary containing: 'id': Optional id of an existing account.move.line. For each line having an 'id', a new line will be created in the current statement line. 'balance': Optional amount to consider during the reconciliation. If a foreign currency is set on the counterpart line in the same foreign currency as the statement line, then this amount is considered as the amount in foreign currency. If not specified, the full balance is taken. This value must be provided if 'id' is not. **kwargs: Custom values to be set on the newly created account.move.line. :param to_check: Mark the current statement line as "to_check" (see field for more details). :param allow_partial: In case of matching a line having an higher amount, allow creating a partial instead of an open balance on the statement line. ''' self.ensure_one() liquidity_lines, suspense_lines, other_lines = self._seek_for_lines() reconciliation_overview, open_balance_vals = self._prepare_reconciliation( lines_vals_list, allow_partial=allow_partial, ) # ==== Manage res.partner.bank ==== if self.account_number and self.partner_id and not self.partner_bank_id: self.partner_bank_id = self._find_or_create_bank_account() # ==== Check open balance ==== if open_balance_vals: if not open_balance_vals.get('partner_id'): raise UserError(_("Unable to create an open balance for a statement line without a partner set.")) if not open_balance_vals.get('account_id'): raise UserError(_("Unable to create an open balance for a statement line because the receivable " "/ payable accounts are missing on the partner.")) # ==== Create & reconcile lines on the bank statement line ==== to_create_commands = [(0, 0, open_balance_vals)] if open_balance_vals else [] to_delete_commands = [(2, line.id) for line in suspense_lines + other_lines] # Cleanup previous lines. self.move_id.with_context(check_move_validity=False, skip_account_move_synchronization=True, force_delete=True).write({ 'line_ids': to_delete_commands + to_create_commands, 'to_check': to_check, }) line_vals_list = [reconciliation_vals['line_vals'] for reconciliation_vals in reconciliation_overview] new_lines = self.env['account.move.line'].create(line_vals_list) new_lines = new_lines.with_context(skip_account_move_synchronization=True) for reconciliation_vals, line in zip(reconciliation_overview, new_lines): if reconciliation_vals.get('counterpart_line'): counterpart_line = reconciliation_vals['counterpart_line'] else: continue (line + counterpart_line).reconcile() # Assign partner if needed (for example, when reconciling a statement # line with no partner, with an invoice; assign the partner of this invoice) if not self.partner_id: rec_overview_partners = set(overview['counterpart_line'].partner_id.id for overview in reconciliation_overview if overview.get('counterpart_line')) if len(rec_overview_partners) == 1 and rec_overview_partners != {False}: self.line_ids.write({'partner_id': rec_overview_partners.pop()}) # Refresh analytic lines. self.move_id.line_ids.analytic_line_ids.unlink() self.move_id.line_ids.create_analytic_lines() # ------------------------------------------------------------------------- # BUSINESS METHODS # ------------------------------------------------------------------------- def _find_or_create_bank_account(self): bank_account = self.env['res.partner.bank'].search( [('company_id', '=', self.company_id.id), ('acc_number', '=', self.account_number)]) if not bank_account: bank_account = self.env['res.partner.bank'].create({ 'acc_number': self.account_number, 'partner_id': self.partner_id.id, 'company_id': self.company_id.id, }) return bank_account def button_undo_reconciliation(self): ''' Undo the reconciliation mades on the statement line and reset their journal items to their original states. ''' self.line_ids.remove_move_reconcile() self.payment_ids.unlink() for st_line in self: st_line.with_context(force_delete=True).write({ 'to_check': False, 'line_ids': [(5, 0)] + [(0, 0, line_vals) for line_vals in st_line._prepare_move_line_default_vals()], })
53.544479
69,822
26,515
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _, Command from odoo.exceptions import UserError, ValidationError from datetime import date class AccountPartialReconcile(models.Model): _name = "account.partial.reconcile" _description = "Partial Reconcile" _rec_name = "id" # ==== Reconciliation fields ==== debit_move_id = fields.Many2one( comodel_name='account.move.line', index=True, required=True) credit_move_id = fields.Many2one( comodel_name='account.move.line', index=True, required=True) full_reconcile_id = fields.Many2one( comodel_name='account.full.reconcile', string="Full Reconcile", copy=False) # ==== Currency fields ==== company_currency_id = fields.Many2one( comodel_name='res.currency', string="Company Currency", related='company_id.currency_id', help="Utility field to express amount currency") debit_currency_id = fields.Many2one( comodel_name='res.currency', store=True, compute='_compute_debit_currency_id', string="Currency of the debit journal item.") credit_currency_id = fields.Many2one( comodel_name='res.currency', store=True, compute='_compute_credit_currency_id', string="Currency of the credit journal item.") # ==== Amount fields ==== amount = fields.Monetary( currency_field='company_currency_id', help="Always positive amount concerned by this matching expressed in the company currency.") debit_amount_currency = fields.Monetary( currency_field='debit_currency_id', help="Always positive amount concerned by this matching expressed in the debit line foreign currency.") credit_amount_currency = fields.Monetary( currency_field='credit_currency_id', help="Always positive amount concerned by this matching expressed in the credit line foreign currency.") # ==== Other fields ==== company_id = fields.Many2one( comodel_name='res.company', string="Company", store=True, readonly=False, related='debit_move_id.company_id') max_date = fields.Date( string="Max Date of Matched Lines", store=True, compute='_compute_max_date', help="Technical field used to determine at which date this reconciliation needs to be shown on the " "aged receivable/payable reports.") # ------------------------------------------------------------------------- # CONSTRAINT METHODS # ------------------------------------------------------------------------- @api.constrains('debit_currency_id', 'credit_currency_id') def _check_required_computed_currencies(self): bad_partials = self.filtered(lambda partial: not partial.debit_currency_id or not partial.credit_currency_id) if bad_partials: raise ValidationError(_("Missing foreign currencies on partials having ids: %s", bad_partials.ids)) # ------------------------------------------------------------------------- # COMPUTE METHODS # ------------------------------------------------------------------------- @api.depends('debit_move_id.date', 'credit_move_id.date') def _compute_max_date(self): for partial in self: partial.max_date = max( partial.debit_move_id.date, partial.credit_move_id.date ) @api.depends('debit_move_id') def _compute_debit_currency_id(self): for partial in self: partial.debit_currency_id = partial.debit_move_id.currency_id \ or partial.debit_move_id.company_currency_id @api.depends('credit_move_id') def _compute_credit_currency_id(self): for partial in self: partial.credit_currency_id = partial.credit_move_id.currency_id \ or partial.credit_move_id.company_currency_id # ------------------------------------------------------------------------- # LOW-LEVEL METHODS # ------------------------------------------------------------------------- def unlink(self): # OVERRIDE to unlink full reconcile linked to the current partials # and reverse the tax cash basis journal entries. # Avoid cyclic unlink calls when removing the partials that could remove some full reconcile # and then, loop again and again. if not self: return True # Retrieve the matching number to unlink. full_to_unlink = self.full_reconcile_id # Retrieve the CABA entries to reverse. moves_to_reverse = self.env['account.move'].search([('tax_cash_basis_rec_id', 'in', self.ids)]) # Unlink partials before doing anything else to avoid 'Record has already been deleted' due to the recursion. res = super().unlink() # Reverse CABA entries. if moves_to_reverse: default_values_list = [{ 'date': move._get_accounting_date(move.date, move._affect_tax_report()), 'ref': _('Reversal of: %s') % move.name, } for move in moves_to_reverse] moves_to_reverse._reverse_moves(default_values_list, cancel=True) # Remove the matching numbers. full_to_unlink.unlink() return res # ------------------------------------------------------------------------- # RECONCILIATION METHODS # ------------------------------------------------------------------------- def _collect_tax_cash_basis_values(self): ''' Collect all information needed to create the tax cash basis journal entries on the current partials. :return: A dictionary mapping each move_id to the result of 'account_move._collect_tax_cash_basis_values'. Also, add the 'partials' keys being a list of dictionary, one for each partial to process: * partial: The account.partial.reconcile record. * percentage: The reconciled percentage represented by the partial. * payment_rate: The applied rate of this partial. ''' tax_cash_basis_values_per_move = {} if not self: return {} for partial in self: for move in {partial.debit_move_id.move_id, partial.credit_move_id.move_id}: # Collect data about cash basis. if move.id not in tax_cash_basis_values_per_move: tax_cash_basis_values_per_move[move.id] = move._collect_tax_cash_basis_values() # Nothing to process on the move. if not tax_cash_basis_values_per_move.get(move.id): continue move_values = tax_cash_basis_values_per_move[move.id] # Check the cash basis configuration only when at least one cash basis tax entry need to be created. journal = partial.company_id.tax_cash_basis_journal_id if not journal: raise UserError(_("There is no tax cash basis journal defined for the '%s' company.\n" "Configure it in Accounting/Configuration/Settings") % partial.company_id.display_name) partial_amount = 0.0 partial_amount_currency = 0.0 rate_amount = 0.0 rate_amount_currency = 0.0 if partial.debit_move_id.move_id == move: partial_amount += partial.amount partial_amount_currency += partial.debit_amount_currency rate_amount -= partial.credit_move_id.balance rate_amount_currency -= partial.credit_move_id.amount_currency source_line = partial.debit_move_id counterpart_line = partial.credit_move_id if partial.credit_move_id.move_id == move: partial_amount += partial.amount partial_amount_currency += partial.credit_amount_currency rate_amount += partial.debit_move_id.balance rate_amount_currency += partial.debit_move_id.amount_currency source_line = partial.credit_move_id counterpart_line = partial.debit_move_id if partial.debit_move_id.move_id.is_invoice(include_receipts=True) and partial.credit_move_id.move_id.is_invoice(include_receipts=True): # Will match when reconciling a refund with an invoice. # In this case, we want to use the rate of each businness document to compute its cash basis entry, # not the rate of what it's reconciled with. rate_amount = source_line.balance rate_amount_currency = source_line.amount_currency payment_date = move.date else: payment_date = counterpart_line.date if move_values['currency'] == move.company_id.currency_id: # Percentage made on company's currency. percentage = partial_amount / move_values['total_balance'] else: # Percentage made on foreign currency. percentage = partial_amount_currency / move_values['total_amount_currency'] if source_line.currency_id != counterpart_line.currency_id: # When the invoice and the payment are not sharing the same foreign currency, the rate is computed # on-the-fly using the payment date. payment_rate = self.env['res.currency']._get_conversion_rate( counterpart_line.company_currency_id, source_line.currency_id, counterpart_line.company_id, payment_date, ) elif rate_amount: payment_rate = rate_amount_currency / rate_amount else: payment_rate = 0.0 partial_vals = { 'partial': partial, 'percentage': percentage, 'payment_rate': payment_rate, } # Add partials. move_values.setdefault('partials', []) move_values['partials'].append(partial_vals) # Clean-up moves having nothing to process. return {k: v for k, v in tax_cash_basis_values_per_move.items() if v} @api.model def _prepare_cash_basis_base_line_vals(self, base_line, balance, amount_currency): ''' Prepare the values to be used to create the cash basis journal items for the tax base line passed as parameter. :param base_line: An account.move.line being the base of some taxes. :param balance: The balance to consider for this line. :param amount_currency: The balance in foreign currency to consider for this line. :return: A python dictionary that could be passed to the create method of account.move.line. ''' account = base_line.company_id.account_cash_basis_base_account_id or base_line.account_id tax_ids = base_line.tax_ids.filtered(lambda x: x.tax_exigibility == 'on_payment') is_refund = base_line.belongs_to_refund() tax_tags = tax_ids.get_tax_tags(is_refund, 'base') product_tags = base_line.tax_tag_ids.filtered(lambda x: x.applicability == 'products') all_tags = tax_tags + product_tags return { 'name': base_line.move_id.name, 'debit': balance if balance > 0.0 else 0.0, 'credit': -balance if balance < 0.0 else 0.0, 'amount_currency': amount_currency, 'currency_id': base_line.currency_id.id, 'partner_id': base_line.partner_id.id, 'account_id': account.id, 'tax_ids': [Command.set(tax_ids.ids)], 'tax_tag_ids': [Command.set(all_tags.ids)], 'tax_tag_invert': base_line.tax_tag_invert, } @api.model def _prepare_cash_basis_counterpart_base_line_vals(self, cb_base_line_vals): ''' Prepare the move line used as a counterpart of the line created by _prepare_cash_basis_base_line_vals. :param cb_base_line_vals: The line returned by _prepare_cash_basis_base_line_vals. :return: A python dictionary that could be passed to the create method of account.move.line. ''' return { 'name': cb_base_line_vals['name'], 'debit': cb_base_line_vals['credit'], 'credit': cb_base_line_vals['debit'], 'account_id': cb_base_line_vals['account_id'], 'amount_currency': -cb_base_line_vals['amount_currency'], 'currency_id': cb_base_line_vals['currency_id'], 'partner_id': cb_base_line_vals['partner_id'], } @api.model def _prepare_cash_basis_tax_line_vals(self, tax_line, balance, amount_currency): ''' Prepare the move line corresponding to a tax in the cash basis entry. :param tax_line: An account.move.line record being a tax line. :param balance: The balance to consider for this line. :param amount_currency: The balance in foreign currency to consider for this line. :return: A python dictionary that could be passed to the create method of account.move.line. ''' tax_ids = tax_line.tax_ids.filtered(lambda x: x.tax_exigibility == 'on_payment') base_tags = tax_ids.get_tax_tags(tax_line.tax_repartition_line_id.refund_tax_id, 'base') product_tags = tax_line.tax_tag_ids.filtered(lambda x: x.applicability == 'products') all_tags = base_tags + tax_line.tax_repartition_line_id.tag_ids + product_tags return { 'name': tax_line.name, 'debit': balance if balance > 0.0 else 0.0, 'credit': -balance if balance < 0.0 else 0.0, 'tax_base_amount': tax_line.tax_base_amount, 'tax_repartition_line_id': tax_line.tax_repartition_line_id.id, 'tax_ids': [Command.set(tax_ids.ids)], 'tax_tag_ids': [Command.set(all_tags.ids)], 'account_id': tax_line.tax_repartition_line_id.account_id.id or tax_line.company_id.account_cash_basis_base_account_id.id or tax_line.account_id.id, 'amount_currency': amount_currency, 'currency_id': tax_line.currency_id.id, 'partner_id': tax_line.partner_id.id, # No need to set tax_tag_invert as on the base line; it will be computed from the repartition line } @api.model def _prepare_cash_basis_counterpart_tax_line_vals(self, tax_line, cb_tax_line_vals): ''' Prepare the move line used as a counterpart of the line created by _prepare_cash_basis_tax_line_vals. :param tax_line: An account.move.line record being a tax line. :param cb_tax_line_vals: The result of _prepare_cash_basis_counterpart_tax_line_vals. :return: A python dictionary that could be passed to the create method of account.move.line. ''' return { 'name': cb_tax_line_vals['name'], 'debit': cb_tax_line_vals['credit'], 'credit': cb_tax_line_vals['debit'], 'account_id': tax_line.account_id.id, 'amount_currency': -cb_tax_line_vals['amount_currency'], 'currency_id': cb_tax_line_vals['currency_id'], 'partner_id': cb_tax_line_vals['partner_id'], } @api.model def _get_cash_basis_base_line_grouping_key_from_vals(self, base_line_vals): ''' Get the grouping key of a cash basis base line that hasn't yet been created. :param base_line_vals: The values to create a new account.move.line record. :return: The grouping key as a tuple. ''' tax_ids = base_line_vals['tax_ids'][0][2] # Decode [(6, 0, [...])] command base_taxes = self.env['account.tax'].browse(tax_ids) return ( base_line_vals['currency_id'], base_line_vals['partner_id'], base_line_vals['account_id'], tuple(base_taxes.filtered(lambda x: x.tax_exigibility == 'on_payment').ids), ) @api.model def _get_cash_basis_base_line_grouping_key_from_record(self, base_line, account=None): ''' Get the grouping key of a journal item being a base line. :param base_line: An account.move.line record. :param account: Optional account to shadow the current base_line one. :return: The grouping key as a tuple. ''' return ( base_line.currency_id.id, base_line.partner_id.id, (account or base_line.account_id).id, tuple(base_line.tax_ids.filtered(lambda x: x.tax_exigibility == 'on_payment').ids), ) @api.model def _get_cash_basis_tax_line_grouping_key_from_vals(self, tax_line_vals): ''' Get the grouping key of a cash basis tax line that hasn't yet been created. :param tax_line_vals: The values to create a new account.move.line record. :return: The grouping key as a tuple. ''' tax_ids = tax_line_vals['tax_ids'][0][2] # Decode [(6, 0, [...])] command base_taxes = self.env['account.tax'].browse(tax_ids) return ( tax_line_vals['currency_id'], tax_line_vals['partner_id'], tax_line_vals['account_id'], tuple(base_taxes.filtered(lambda x: x.tax_exigibility == 'on_payment').ids), tax_line_vals['tax_repartition_line_id'], ) @api.model def _get_cash_basis_tax_line_grouping_key_from_record(self, tax_line, account=None): ''' Get the grouping key of a journal item being a tax line. :param tax_line: An account.move.line record. :param account: Optional account to shadow the current tax_line one. :return: The grouping key as a tuple. ''' return ( tax_line.currency_id.id, tax_line.partner_id.id, (account or tax_line.account_id).id, tuple(tax_line.tax_ids.filtered(lambda x: x.tax_exigibility == 'on_payment').ids), tax_line.tax_repartition_line_id.id, ) def _create_tax_cash_basis_moves(self): ''' Create the tax cash basis journal entries. :return: The newly created journal entries. ''' tax_cash_basis_values_per_move = self._collect_tax_cash_basis_values() today = fields.Date.context_today(self) moves_to_create = [] to_reconcile_after = [] for move_values in tax_cash_basis_values_per_move.values(): move = move_values['move'] pending_cash_basis_lines = [] for partial_values in move_values['partials']: partial = partial_values['partial'] # Init the journal entry. lock_date = move.company_id._get_user_fiscal_lock_date() move_date = partial.max_date if partial.max_date > (lock_date or date.min) else today move_vals = { 'move_type': 'entry', 'date': move_date, 'ref': move.name, 'journal_id': partial.company_id.tax_cash_basis_journal_id.id, 'line_ids': [], 'tax_cash_basis_rec_id': partial.id, 'tax_cash_basis_origin_move_id': move.id, 'fiscal_position_id': move.fiscal_position_id.id, } # Tracking of lines grouped all together. # Used to reduce the number of generated lines and to avoid rounding issues. partial_lines_to_create = {} for caba_treatment, line in move_values['to_process_lines']: # ========================================================================== # Compute the balance of the current line on the cash basis entry. # This balance is a percentage representing the part of the journal entry # that is actually paid by the current partial. # ========================================================================== # Percentage expressed in the foreign currency. amount_currency = line.currency_id.round(line.amount_currency * partial_values['percentage']) balance = partial_values['payment_rate'] and amount_currency / partial_values['payment_rate'] or 0.0 # ========================================================================== # Prepare the mirror cash basis journal item of the current line. # Group them all together as much as possible to reduce the number of # generated journal items. # Also track the computed balance in order to avoid rounding issues when # the journal entry will be fully paid. At that case, we expect the exact # amount of each line has been covered by the cash basis journal entries # and well reported in the Tax Report. # ========================================================================== if caba_treatment == 'tax': # Tax line. cb_line_vals = self._prepare_cash_basis_tax_line_vals(line, balance, amount_currency) grouping_key = self._get_cash_basis_tax_line_grouping_key_from_vals(cb_line_vals) elif caba_treatment == 'base': # Base line. cb_line_vals = self._prepare_cash_basis_base_line_vals(line, balance, amount_currency) grouping_key = self._get_cash_basis_base_line_grouping_key_from_vals(cb_line_vals) if grouping_key in partial_lines_to_create: aggregated_vals = partial_lines_to_create[grouping_key]['vals'] debit = aggregated_vals['debit'] + cb_line_vals['debit'] credit = aggregated_vals['credit'] + cb_line_vals['credit'] balance = debit - credit aggregated_vals.update({ 'debit': balance if balance > 0 else 0, 'credit': -balance if balance < 0 else 0, 'amount_currency': aggregated_vals['amount_currency'] + cb_line_vals['amount_currency'], }) if caba_treatment == 'tax': aggregated_vals.update({ 'tax_base_amount': aggregated_vals['tax_base_amount'] + cb_line_vals['tax_base_amount'], }) partial_lines_to_create[grouping_key]['tax_line'] += line else: partial_lines_to_create[grouping_key] = { 'vals': cb_line_vals, } if caba_treatment == 'tax': partial_lines_to_create[grouping_key].update({ 'tax_line': line, }) # ========================================================================== # Create the counterpart journal items. # ========================================================================== # To be able to retrieve the correct matching between the tax lines to reconcile # later, the lines will be created using a specific sequence. sequence = 0 for grouping_key, aggregated_vals in partial_lines_to_create.items(): line_vals = aggregated_vals['vals'] line_vals['sequence'] = sequence pending_cash_basis_lines.append((grouping_key, line_vals['amount_currency'])) if 'tax_repartition_line_id' in line_vals: # Tax line. tax_line = aggregated_vals['tax_line'] counterpart_line_vals = self._prepare_cash_basis_counterpart_tax_line_vals(tax_line, line_vals) counterpart_line_vals['sequence'] = sequence + 1 if tax_line.account_id.reconcile: move_index = len(moves_to_create) to_reconcile_after.append((tax_line, move_index, counterpart_line_vals['sequence'])) else: # Base line. counterpart_line_vals = self._prepare_cash_basis_counterpart_base_line_vals(line_vals) counterpart_line_vals['sequence'] = sequence + 1 sequence += 2 move_vals['line_ids'] += [(0, 0, counterpart_line_vals), (0, 0, line_vals)] moves_to_create.append(move_vals) moves = self.env['account.move'].create(moves_to_create) moves._post(soft=False) # Reconcile the tax lines being on a reconcile tax basis transfer account. for lines, move_index, sequence in to_reconcile_after: # In expenses, all move lines are created manually without any grouping on tax lines. # In that case, 'lines' could be already reconciled. lines = lines.filtered(lambda x: not x.reconciled) if not lines: continue counterpart_line = moves[move_index].line_ids.filtered(lambda line: line.sequence == sequence) # When dealing with tiny amounts, the line could have a zero amount and then, be already reconciled. if counterpart_line.reconciled: continue (lines + counterpart_line).reconcile() return moves
48.740809
26,515
2,921
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api, _ from odoo.tools import float_round from odoo.exceptions import ValidationError class AccountCashRounding(models.Model): """ In some countries, we need to be able to make appear on an invoice a rounding line, appearing there only because the smallest coinage has been removed from the circulation. For example, in Switzerland invoices have to be rounded to 0.05 CHF because coins of 0.01 CHF and 0.02 CHF aren't used anymore. see https://en.wikipedia.org/wiki/Cash_rounding for more details. """ _name = 'account.cash.rounding' _description = 'Account Cash Rounding' name = fields.Char(string='Name', translate=True, required=True) rounding = fields.Float(string='Rounding Precision', required=True, default=0.01, help='Represent the non-zero value smallest coinage (for example, 0.05).') strategy = fields.Selection([('biggest_tax', 'Modify tax amount'), ('add_invoice_line', 'Add a rounding line')], string='Rounding Strategy', default='add_invoice_line', required=True, help='Specify which way will be used to round the invoice amount to the rounding precision') profit_account_id = fields.Many2one('account.account', string='Profit Account', company_dependent=True, domain="[('deprecated', '=', False), ('company_id', '=', current_company_id)]") loss_account_id = fields.Many2one('account.account', string='Loss Account', company_dependent=True, domain="[('deprecated', '=', False), ('company_id', '=', current_company_id)]") rounding_method = fields.Selection(string='Rounding Method', required=True, selection=[('UP', 'UP'), ('DOWN', 'DOWN'), ('HALF-UP', 'HALF-UP')], default='HALF-UP', help='The tie-breaking rule used for float rounding operations') company_id = fields.Many2one('res.company', related='profit_account_id.company_id') @api.constrains('rounding') def validate_rounding(self): for record in self: if record.rounding <= 0: raise ValidationError(_("Please set a strictly positive rounding value.")) def round(self, amount): """Compute the rounding on the amount passed as parameter. :param amount: the amount to round :return: the rounded amount depending the rounding value and the rounding method """ return float_round(amount, precision_rounding=self.rounding, rounding_method=self.rounding_method) def compute_difference(self, currency, amount): """Compute the difference between the base_amount and the amount after rounding. For example, base_amount=23.91, after rounding=24.00, the result will be 0.09. :param currency: The currency. :param amount: The amount :return: round(difference) """ difference = self.round(amount) - amount return currency.round(difference)
54.092593
2,921
6,405
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import UserError class AccountAnalyticAccount(models.Model): _inherit = 'account.analytic.account' invoice_count = fields.Integer("Invoice Count", compute='_compute_invoice_count') vendor_bill_count = fields.Integer("Vendor Bill Count", compute='_compute_vendor_bill_count') @api.constrains('company_id') def _check_company_consistency(self): analytic_accounts = self.filtered('company_id') if not analytic_accounts: return self.flush(['company_id']) self._cr.execute(''' SELECT line.id FROM account_move_line line JOIN account_analytic_account account ON account.id = line.analytic_account_id WHERE line.analytic_account_id IN %s AND line.company_id != account.company_id ''', [tuple(analytic_accounts.ids)]) if self._cr.fetchone(): raise UserError(_("You can't set a different company on your analytic account since there are some journal items linked to it.")) @api.depends('line_ids') def _compute_invoice_count(self): sale_types = self.env['account.move'].get_sale_types() domain = [ ('parent_state', '=', 'posted'), ('move_id.move_type', 'in', sale_types), ('analytic_account_id', 'in', self.ids) ] groups = self.env['account.move.line'].read_group(domain, ['move_id:count_distinct'], ['analytic_account_id']) moves_count_mapping = dict((g['analytic_account_id'][0], g['move_id']) for g in groups) for account in self: account.invoice_count = moves_count_mapping.get(account.id, 0) @api.depends('line_ids') def _compute_vendor_bill_count(self): purchase_types = self.env['account.move'].get_purchase_types() domain = [ ('parent_state', '=', 'posted'), ('move_id.move_type', 'in', purchase_types), ('analytic_account_id', 'in', self.ids) ] groups = self.env['account.move.line'].read_group(domain, ['move_id:count_distinct'], ['analytic_account_id']) moves_count_mapping = dict((g['analytic_account_id'][0], g['move_id']) for g in groups) for account in self: account.vendor_bill_count = moves_count_mapping.get(account.id, 0) def action_view_invoice(self): self.ensure_one() result = { "type": "ir.actions.act_window", "res_model": "account.move", "domain": [('id', 'in', self.line_ids.move_id.move_id.ids), ('move_type', 'in', self.env['account.move'].get_sale_types())], "context": {"create": False, 'default_move_type': 'out_invoice'}, "name": _("Customer Invoices"), 'view_mode': 'tree,form', } return result def action_view_vendor_bill(self): self.ensure_one() result = { "type": "ir.actions.act_window", "res_model": "account.move", "domain": [('id', 'in', self.line_ids.move_id.move_id.ids), ('move_type', 'in', self.env['account.move'].get_purchase_types())], "context": {"create": False, 'default_move_type': 'in_invoice'}, "name": _("Vendor Bills"), 'view_mode': 'tree,form', } return result class AccountAnalyticTag(models.Model): _inherit = 'account.analytic.tag' @api.constrains('company_id') def _check_company_consistency(self): analytic_tags = self.filtered('company_id') if not analytic_tags: return self.flush(['company_id']) self._cr.execute(''' SELECT line.id FROM account_analytic_tag_account_move_line_rel tag_rel JOIN account_analytic_tag tag ON tag.id = tag_rel.account_analytic_tag_id JOIN account_move_line line ON line.id = tag_rel.account_move_line_id WHERE tag_rel.account_analytic_tag_id IN %s AND line.company_id != tag.company_id ''', [tuple(analytic_tags.ids)]) if self._cr.fetchone(): raise UserError(_("You can't set a different company on your analytic tags since there are some journal items linked to it.")) class AccountAnalyticLine(models.Model): _inherit = 'account.analytic.line' _description = 'Analytic Line' product_id = fields.Many2one('product.product', string='Product', check_company=True) general_account_id = fields.Many2one('account.account', string='Financial Account', ondelete='restrict', readonly=True, related='move_id.account_id', store=True, domain="[('deprecated', '=', False), ('company_id', '=', company_id)]", compute_sudo=True) move_id = fields.Many2one('account.move.line', string='Journal Item', ondelete='cascade', index=True, check_company=True) code = fields.Char(size=8) ref = fields.Char(string='Ref.') category = fields.Selection(selection_add=[('invoice', 'Customer Invoice'), ('vendor_bill', 'Vendor Bill')]) @api.onchange('product_id', 'product_uom_id', 'unit_amount', 'currency_id') def on_change_unit_amount(self): if not self.product_id: return {} result = 0.0 prod_accounts = self.product_id.product_tmpl_id.with_company(self.company_id)._get_product_accounts() unit = self.product_uom_id account = prod_accounts['expense'] if not unit or self.product_id.uom_po_id.category_id.id != unit.category_id.id: unit = self.product_id.uom_po_id # Compute based on pricetype amount_unit = self.product_id.price_compute('standard_price', uom=unit)[self.product_id.id] amount = amount_unit * self.unit_amount or 0.0 result = (self.currency_id.round(amount) if self.currency_id else round(amount, 2)) * -1 self.amount = result self.general_account_id = account self.product_uom_id = unit @api.model def view_header_get(self, view_id, view_type): if self.env.context.get('account_id'): return _( "Entries: %(account)s", account=self.env['account.analytic.account'].browse(self.env.context['account_id']).name ) return super().view_header_get(view_id, view_type)
43.869863
6,405
5,724
py
PYTHON
15.0
# -*- coding: utf-8 -*- import time from odoo import api, models, _ from odoo.exceptions import UserError class ReportJournal(models.AbstractModel): _name = 'report.account.report_journal' _description = 'Account Journal Report' def lines(self, target_move, journal_ids, sort_selection, data): if isinstance(journal_ids, int): journal_ids = [journal_ids] move_state = ['draft', 'posted'] if target_move == 'posted': move_state = ['posted'] query_get_clause = self._get_query_get_clause(data) params = [tuple(move_state), tuple(journal_ids)] + query_get_clause[2] query = 'SELECT "account_move_line".id FROM ' + query_get_clause[0] + ', account_move am, account_account acc WHERE "account_move_line".account_id = acc.id AND "account_move_line".move_id=am.id AND am.state IN %s AND "account_move_line".journal_id IN %s AND ' + query_get_clause[1] + ' ORDER BY ' if sort_selection == 'date': query += '"account_move_line".date' else: query += 'am.name' query += ', "account_move_line".move_id, acc.code' self.env.cr.execute(query, tuple(params)) ids = (x[0] for x in self.env.cr.fetchall()) return self.env['account.move.line'].browse(ids) def _sum_debit(self, data, journal_id): move_state = ['draft', 'posted'] if data['form'].get('target_move', 'all') == 'posted': move_state = ['posted'] query_get_clause = self._get_query_get_clause(data) params = [tuple(move_state), tuple(journal_id.ids)] + query_get_clause[2] self.env.cr.execute('SELECT SUM(debit) FROM ' + query_get_clause[0] + ', account_move am ' 'WHERE "account_move_line".move_id=am.id AND am.state IN %s AND "account_move_line".journal_id IN %s AND ' + query_get_clause[1] + ' ', tuple(params)) return self.env.cr.fetchone()[0] or 0.0 def _sum_credit(self, data, journal_id): move_state = ['draft', 'posted'] if data['form'].get('target_move', 'all') == 'posted': move_state = ['posted'] query_get_clause = self._get_query_get_clause(data) params = [tuple(move_state), tuple(journal_id.ids)] + query_get_clause[2] self.env.cr.execute('SELECT SUM(credit) FROM ' + query_get_clause[0] + ', account_move am ' 'WHERE "account_move_line".move_id=am.id AND am.state IN %s AND "account_move_line".journal_id IN %s AND ' + query_get_clause[1] + ' ', tuple(params)) return self.env.cr.fetchone()[0] or 0.0 def _get_taxes(self, data, journal_id): move_state = ['draft', 'posted'] if data['form'].get('target_move', 'all') == 'posted': move_state = ['posted'] query_get_clause = self._get_query_get_clause(data) params = [tuple(move_state), tuple(journal_id.ids)] + query_get_clause[2] query = """ SELECT rel.account_tax_id, SUM("account_move_line".balance) AS base_amount FROM account_move_line_account_tax_rel rel, """ + query_get_clause[0] + """ LEFT JOIN account_move am ON "account_move_line".move_id = am.id WHERE "account_move_line".id = rel.account_move_line_id AND am.state IN %s AND "account_move_line".journal_id IN %s AND """ + query_get_clause[1] + """ GROUP BY rel.account_tax_id""" self.env.cr.execute(query, tuple(params)) ids = [] base_amounts = {} for row in self.env.cr.fetchall(): ids.append(row[0]) base_amounts[row[0]] = row[1] res = {} for tax in self.env['account.tax'].browse(ids): self.env.cr.execute('SELECT sum(debit - credit) FROM ' + query_get_clause[0] + ', account_move am ' 'WHERE "account_move_line".move_id=am.id AND am.state IN %s AND "account_move_line".journal_id IN %s AND ' + query_get_clause[1] + ' AND tax_line_id = %s', tuple(params + [tax.id])) res[tax] = { 'base_amount': base_amounts[tax.id], 'tax_amount': self.env.cr.fetchone()[0] or 0.0, } if journal_id.type == 'sale': #sales operation are credits res[tax]['base_amount'] = res[tax]['base_amount'] * -1 res[tax]['tax_amount'] = res[tax]['tax_amount'] * -1 return res def _get_query_get_clause(self, data): return self.env['account.move.line'].with_context(data['form'].get('used_context', {}))._query_get() @api.model def _get_report_values(self, docids, data=None): if not data.get('form'): raise UserError(_("Form content is missing, this report cannot be printed.")) target_move = data['form'].get('target_move', 'all') sort_selection = data['form'].get('sort_selection', 'date') res = {} for journal in data['form']['journal_ids']: res[journal] = self.with_context(data['form'].get('used_context', {})).lines(target_move, journal, sort_selection, data) return { 'doc_ids': data['form']['journal_ids'], 'doc_model': self.env['account.journal'], 'data': data, 'docs': self.env['account.journal'].browse(data['form']['journal_ids']), 'time': time, 'lines': res, 'sum_credit': self._sum_credit, 'sum_debit': self._sum_debit, 'get_taxes': self._get_taxes, 'company_id': self.env['res.company'].browse( data['form']['company_id'][0]), }
47.305785
5,724
7,989
py
PYTHON
15.0
# -*- coding: utf-8 -*- from odoo import models, fields, api from odoo.addons.account.models.account_move import PAYMENT_STATE_SELECTION from functools import lru_cache class AccountInvoiceReport(models.Model): _name = "account.invoice.report" _description = "Invoices Statistics" _auto = False _rec_name = 'invoice_date' _order = 'invoice_date desc' # ==== Invoice fields ==== move_id = fields.Many2one('account.move', readonly=True) journal_id = fields.Many2one('account.journal', string='Journal', readonly=True) company_id = fields.Many2one('res.company', string='Company', readonly=True) company_currency_id = fields.Many2one('res.currency', string='Company Currency', readonly=True) partner_id = fields.Many2one('res.partner', string='Partner', readonly=True) commercial_partner_id = fields.Many2one('res.partner', string='Partner Company', help="Commercial Entity") country_id = fields.Many2one('res.country', string="Country") invoice_user_id = fields.Many2one('res.users', string='Salesperson', readonly=True) move_type = fields.Selection([ ('out_invoice', 'Customer Invoice'), ('in_invoice', 'Vendor Bill'), ('out_refund', 'Customer Credit Note'), ('in_refund', 'Vendor Credit Note'), ], readonly=True) state = fields.Selection([ ('draft', 'Draft'), ('posted', 'Open'), ('cancel', 'Cancelled') ], string='Invoice Status', readonly=True) payment_state = fields.Selection(selection=PAYMENT_STATE_SELECTION, string='Payment Status', readonly=True) fiscal_position_id = fields.Many2one('account.fiscal.position', string='Fiscal Position', readonly=True) invoice_date = fields.Date(readonly=True, string="Invoice Date") # ==== Invoice line fields ==== quantity = fields.Float(string='Product Quantity', readonly=True) product_id = fields.Many2one('product.product', string='Product', readonly=True) product_uom_id = fields.Many2one('uom.uom', string='Unit of Measure', readonly=True) product_categ_id = fields.Many2one('product.category', string='Product Category', readonly=True) invoice_date_due = fields.Date(string='Due Date', readonly=True) account_id = fields.Many2one('account.account', string='Revenue/Expense Account', readonly=True, domain=[('deprecated', '=', False)]) analytic_account_id = fields.Many2one('account.analytic.account', string='Analytic Account', groups="analytic.group_analytic_accounting") price_subtotal = fields.Float(string='Untaxed Total', readonly=True) price_average = fields.Float(string='Average Price', readonly=True, group_operator="avg") _depends = { 'account.move': [ 'name', 'state', 'move_type', 'partner_id', 'invoice_user_id', 'fiscal_position_id', 'invoice_date', 'invoice_date_due', 'invoice_payment_term_id', 'partner_bank_id', ], 'account.move.line': [ 'quantity', 'price_subtotal', 'amount_residual', 'balance', 'amount_currency', 'move_id', 'product_id', 'product_uom_id', 'account_id', 'analytic_account_id', 'journal_id', 'company_id', 'currency_id', 'partner_id', ], 'product.product': ['product_tmpl_id'], 'product.template': ['categ_id'], 'uom.uom': ['category_id', 'factor', 'name', 'uom_type'], 'res.currency.rate': ['currency_id', 'name'], 'res.partner': ['country_id'], } @property def _table_query(self): return '%s %s %s' % (self._select(), self._from(), self._where()) @api.model def _select(self): return ''' SELECT line.id, line.move_id, line.product_id, line.account_id, line.analytic_account_id, line.journal_id, line.company_id, line.company_currency_id, line.partner_id AS commercial_partner_id, move.state, move.move_type, move.partner_id, move.invoice_user_id, move.fiscal_position_id, move.payment_state, move.invoice_date, move.invoice_date_due, uom_template.id AS product_uom_id, template.categ_id AS product_categ_id, line.quantity / NULLIF(COALESCE(uom_line.factor, 1) / COALESCE(uom_template.factor, 1), 0.0) * (CASE WHEN move.move_type IN ('in_invoice','out_refund','in_receipt') THEN -1 ELSE 1 END) AS quantity, -line.balance * currency_table.rate AS price_subtotal, -COALESCE( -- Average line price (line.balance / NULLIF(line.quantity, 0.0)) * (CASE WHEN move.move_type IN ('in_invoice','out_refund','in_receipt') THEN -1 ELSE 1 END) -- convert to template uom * (NULLIF(COALESCE(uom_line.factor, 1), 0.0) / NULLIF(COALESCE(uom_template.factor, 1), 0.0)), 0.0) * currency_table.rate AS price_average, COALESCE(partner.country_id, commercial_partner.country_id) AS country_id ''' @api.model def _from(self): return ''' FROM account_move_line line LEFT JOIN res_partner partner ON partner.id = line.partner_id LEFT JOIN product_product product ON product.id = line.product_id LEFT JOIN account_account account ON account.id = line.account_id LEFT JOIN account_account_type user_type ON user_type.id = account.user_type_id LEFT JOIN product_template template ON template.id = product.product_tmpl_id LEFT JOIN uom_uom uom_line ON uom_line.id = line.product_uom_id LEFT JOIN uom_uom uom_template ON uom_template.id = template.uom_id INNER JOIN account_move move ON move.id = line.move_id LEFT JOIN res_partner commercial_partner ON commercial_partner.id = move.commercial_partner_id JOIN {currency_table} ON currency_table.company_id = line.company_id '''.format( currency_table=self.env['res.currency']._get_query_currency_table({'multi_company': True, 'date': {'date_to': fields.Date.today()}}), ) @api.model def _where(self): return ''' WHERE move.move_type IN ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt') AND line.account_id IS NOT NULL AND NOT line.exclude_from_invoice_tab ''' class ReportInvoiceWithoutPayment(models.AbstractModel): _name = 'report.account.report_invoice' _description = 'Account report without payment lines' @api.model def _get_report_values(self, docids, data=None): docs = self.env['account.move'].browse(docids) qr_code_urls = {} for invoice in docs: if invoice.display_qr_code: new_code_url = invoice.generate_qr_code() if new_code_url: qr_code_urls[invoice.id] = new_code_url return { 'doc_ids': docids, 'doc_model': 'account.move', 'docs': docs, 'qr_code_urls': qr_code_urls, } class ReportInvoiceWithPayment(models.AbstractModel): _name = 'report.account.report_invoice_with_payments' _description = 'Account report with payment lines' _inherit = 'report.account.report_invoice' @api.model def _get_report_values(self, docids, data=None): rslt = super()._get_report_values(docids, data) rslt['report_type'] = data.get('report_type') if data else '' return rslt
48.418182
7,989
738
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ReportAccountHashIntegrity(models.AbstractModel): _name = 'report.account.report_hash_integrity' _description = 'Get hash integrity result as PDF.' @api.model def _get_report_values(self, docids, data=None): if data: data.update(self.env.company._check_hash_integrity()) else: data = self.env.company._check_hash_integrity() return { 'doc_ids' : docids, 'doc_model' : self.env['res.company'], 'data' : data, 'docs' : self.env['res.company'].browse(self.env.company.id), }
33.545455
738
1,217
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http, _ from odoo.http import request def sitemap_terms(env, rule, qs): if qs and qs.lower() not in '/terms': return use_invoice_terms = env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms') if use_invoice_terms and env.company.terms_type == 'html': yield {'loc': '/terms'} class TermsController(http.Controller): @http.route('/terms', type='http', auth='public', website=True, sitemap=sitemap_terms) def terms_conditions(self, **kwargs): use_invoice_terms = request.env['ir.config_parameter'].sudo().get_param('account.use_invoice_terms') if not (use_invoice_terms and request.env.company.terms_type == 'html'): return request.render('http_routing.http_error', { 'status_code': _('Oops'), 'status_message': _("""The requested page is invalid, or doesn't exist anymore.""")}) values = { 'use_invoice_terms': use_invoice_terms, 'company': request.env.company } return request.render("account.account_terms_conditions_page", values)
40.566667
1,217
6,108
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import http, _ from odoo.addons.portal.controllers.portal import CustomerPortal, pager as portal_pager from odoo.exceptions import AccessError, MissingError from collections import OrderedDict from odoo.http import request class PortalAccount(CustomerPortal): def _prepare_home_portal_values(self, counters): values = super()._prepare_home_portal_values(counters) if 'invoice_count' in counters: invoice_count = request.env['account.move'].search_count(self._get_invoices_domain()) \ if request.env['account.move'].check_access_rights('read', raise_exception=False) else 0 values['invoice_count'] = invoice_count return values # ------------------------------------------------------------ # My Invoices # ------------------------------------------------------------ def _invoice_get_page_view_values(self, invoice, access_token, **kwargs): values = { 'page_name': 'invoice', 'invoice': invoice, } return self._get_page_view_values(invoice, access_token, values, 'my_invoices_history', False, **kwargs) def _get_invoices_domain(self): return [('state', 'not in', ('cancel', 'draft')), ('move_type', 'in', ('out_invoice', 'out_refund', 'in_invoice', 'in_refund', 'out_receipt', 'in_receipt'))] @http.route(['/my/invoices', '/my/invoices/page/<int:page>'], type='http', auth="user", website=True) def portal_my_invoices(self, page=1, date_begin=None, date_end=None, sortby=None, filterby=None, **kw): values = self._prepare_portal_layout_values() AccountInvoice = request.env['account.move'] domain = self._get_invoices_domain() searchbar_sortings = { 'date': {'label': _('Date'), 'order': 'invoice_date desc'}, 'duedate': {'label': _('Due Date'), 'order': 'invoice_date_due desc'}, 'name': {'label': _('Reference'), 'order': 'name desc'}, 'state': {'label': _('Status'), 'order': 'state'}, } # default sort by order if not sortby: sortby = 'date' order = searchbar_sortings[sortby]['order'] searchbar_filters = { 'all': {'label': _('All'), 'domain': []}, 'invoices': {'label': _('Invoices'), 'domain': [('move_type', 'in', ('out_invoice', 'out_refund'))]}, 'bills': {'label': _('Bills'), 'domain': [('move_type', 'in', ('in_invoice', 'in_refund'))]}, } # default filter by value if not filterby: filterby = 'all' domain += searchbar_filters[filterby]['domain'] if date_begin and date_end: domain += [('create_date', '>', date_begin), ('create_date', '<=', date_end)] # count for pager invoice_count = AccountInvoice.search_count(domain) # pager pager = portal_pager( url="/my/invoices", url_args={'date_begin': date_begin, 'date_end': date_end, 'sortby': sortby}, total=invoice_count, page=page, step=self._items_per_page ) # content according to pager and archive selected invoices = AccountInvoice.search(domain, order=order, limit=self._items_per_page, offset=pager['offset']) request.session['my_invoices_history'] = invoices.ids[:100] values.update({ 'date': date_begin, 'invoices': invoices, 'page_name': 'invoice', 'pager': pager, 'default_url': '/my/invoices', 'searchbar_sortings': searchbar_sortings, 'sortby': sortby, 'searchbar_filters': OrderedDict(sorted(searchbar_filters.items())), 'filterby':filterby, }) return request.render("account.portal_my_invoices", values) @http.route(['/my/invoices/<int:invoice_id>'], type='http', auth="public", website=True) def portal_my_invoice_detail(self, invoice_id, access_token=None, report_type=None, download=False, **kw): try: invoice_sudo = self._document_check_access('account.move', invoice_id, access_token) except (AccessError, MissingError): return request.redirect('/my') if report_type in ('html', 'pdf', 'text'): return self._show_report(model=invoice_sudo, report_type=report_type, report_ref='account.account_invoices', download=download) values = self._invoice_get_page_view_values(invoice_sudo, access_token, **kw) return request.render("account.portal_invoice_page", values) # ------------------------------------------------------------ # My Home # ------------------------------------------------------------ def details_form_validate(self, data): error, error_message = super(PortalAccount, self).details_form_validate(data) # prevent VAT/name change if invoices exist partner = request.env['res.users'].browse(request.uid).partner_id if not partner.can_edit_vat(): if 'vat' in data and (data['vat'] or False) != (partner.vat or False): error['vat'] = 'error' error_message.append(_('Changing VAT number is not allowed once invoices have been issued for your account. Please contact us directly for this operation.')) if 'name' in data and (data['name'] or False) != (partner.name or False): error['name'] = 'error' error_message.append(_('Changing your name is not allowed once invoices have been issued for your account. Please contact us directly for this operation.')) if 'company_name' in data and (data['company_name'] or False) != (partner.company_name or False): error['company_name'] = 'error' error_message.append(_('Changing your company name is not allowed once invoices have been issued for your account. Please contact us directly for this operation.')) return error, error_message
49.258065
6,108
1,597
py
PYTHON
15.0
from odoo import http from odoo.http import request class OnboardingController(http.Controller): @http.route('/account/account_invoice_onboarding', auth='user', type='json') def account_invoice_onboarding(self): """ Returns the `banner` for the account invoice onboarding panel. It can be empty if the user has closed it or if he doesn't have the permission to see it. """ company = request.env.company if not request.env.is_admin() or \ company.account_invoice_onboarding_state == 'closed': return {} return { 'html': request.env.ref('account.account_invoice_onboarding_panel')._render({ 'company': company, 'state': company.get_and_update_account_invoice_onboarding_state() }) } @http.route('/account/account_dashboard_onboarding', auth='user', type='json') def account_dashboard_onboarding(self): """ Returns the `banner` for the account dashboard onboarding panel. It can be empty if the user has closed it or if he doesn't have the permission to see it. """ company = request.env.company if not request.env.is_admin() or \ company.account_dashboard_onboarding_state == 'closed': return {} return { 'html': request.env.ref('account.account_dashboard_onboarding_panel')._render({ 'company': company, 'state': company.get_and_update_account_dashboard_onboarding_state() }) }
38.95122
1,597
1,640
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name' : 'Fleet', 'version' : '0.1', 'sequence': 185, 'category': 'Human Resources/Fleet', 'website' : 'https://www.odoo.com/app/fleet', 'summary' : 'Manage your fleet and track car costs', 'description' : """ Vehicle, leasing, insurances, cost ================================== With this module, Odoo helps you managing all your vehicles, the contracts associated to those vehicle as well as services, costs and many other features necessary to the management of your fleet of vehicle(s) Main Features ------------- * Add vehicles to your fleet * Manage contracts for vehicles * Reminder when a contract reach its expiration date * Add services, odometer values for all vehicles * Show all costs associated to a vehicle or to a type of service * Analysis graph for costs """, 'depends': [ 'base', 'mail', ], 'data': [ 'security/fleet_security.xml', 'security/ir.model.access.csv', 'views/fleet_vehicle_model_views.xml', 'views/fleet_vehicle_views.xml', 'views/fleet_vehicle_cost_views.xml', 'views/fleet_board_view.xml', 'views/mail_activity_views.xml', 'views/res_config_settings_views.xml', 'data/fleet_cars_data.xml', 'data/fleet_data.xml', 'data/mail_data.xml', ], 'demo': ['data/fleet_demo.xml'], 'installable': True, 'application': True, 'assets': { 'web.assets_backend': [ 'fleet/static/src/**/*', ], }, 'license': 'LGPL-3', }
29.818182
1,640
863
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, new_test_user class TestFleet(common.TransactionCase): def test_manager_create_vehicle(self): manager = new_test_user(self.env, "test fleet manager", groups="fleet.fleet_group_manager,base.group_partner_manager") user = new_test_user(self.env, "test base user", groups="base.group_user") brand = self.env["fleet.vehicle.model.brand"].create({ "name": "Audi", }) model = self.env["fleet.vehicle.model"].create({ "brand_id": brand.id, "name": "A3", }) self.env["fleet.vehicle"].with_user(manager).create({ "model_id": model.id, "driver_id": user.partner_id.id, "plan_to_change_car": False })
39.227273
863
1,679
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests import common, new_test_user from odoo import fields class TestFleet(common.TransactionCase): def test_search_renewal(self): """ Should find the car with overdue contract or renewal due soon """ user = new_test_user(self.env, "test base user", groups="base.group_user") brand = self.env["fleet.vehicle.model.brand"].create({ "name": "Audi", }) model = self.env["fleet.vehicle.model"].create({ "brand_id": brand.id, "name": "A3", }) car_1 = self.env["fleet.vehicle"].create({ "model_id": model.id, "driver_id": user.partner_id.id, "plan_to_change_car": False }) car_2 = self.env["fleet.vehicle"].create({ "model_id": model.id, "driver_id": user.partner_id.id, "plan_to_change_car": False }) Log = self.env['fleet.vehicle.log.contract'] log = Log.create({ 'vehicle_id': car_2.id, 'expiration_date': fields.Date.add(fields.Date.today(), days=10) }) res = self.env["fleet.vehicle"].search([('contract_renewal_due_soon', '=', True), ('id', '=', car_2.id)]) self.assertEqual(res, car_2) log = Log.create({ 'vehicle_id': car_1.id, 'expiration_date': fields.Date.add(fields.Date.today(), days=-10) }) res = self.env["fleet.vehicle"].search([('contract_renewal_overdue', '=', True), ('id', '=', car_1.id)]) self.assertEqual(res, car_1)
37.311111
1,679
517
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class FleetServiceType(models.Model): _name = 'fleet.service.type' _description = 'Fleet Service Type' name = fields.Char(required=True, translate=True) category = fields.Selection([ ('contract', 'Contract'), ('service', 'Service') ], 'Category', required=True, help='Choose whether the service refer to contracts, vehicle services or both')
34.466667
517
3,432
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ from odoo.exceptions import UserError class FleetVehicleLogServices(models.Model): _name = 'fleet.vehicle.log.services' _inherit = ['mail.thread', 'mail.activity.mixin'] _rec_name = 'service_type_id' _description = 'Services for vehicles' active = fields.Boolean(default=True) vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle', required=True, help='Vehicle concerned by this log') amount = fields.Monetary('Cost') description = fields.Char('Description') odometer_id = fields.Many2one('fleet.vehicle.odometer', 'Odometer', help='Odometer measure of the vehicle at the moment of this log') odometer = fields.Float( compute="_get_odometer", inverse='_set_odometer', string='Odometer Value', help='Odometer measure of the vehicle at the moment of this log') odometer_unit = fields.Selection(related='vehicle_id.odometer_unit', string="Unit", readonly=True) date = fields.Date(help='Date when the cost has been executed', default=fields.Date.context_today) company_id = fields.Many2one('res.company', 'Company', default=lambda self: self.env.company) currency_id = fields.Many2one('res.currency', related='company_id.currency_id') purchaser_id = fields.Many2one('res.partner', string="Driver", compute='_compute_purchaser_id', readonly=False, store=True) inv_ref = fields.Char('Vendor Reference') vendor_id = fields.Many2one('res.partner', 'Vendor') notes = fields.Text() service_type_id = fields.Many2one( 'fleet.service.type', 'Service Type', required=True, default=lambda self: self.env.ref('fleet.type_service_service_8', raise_if_not_found=False), ) state = fields.Selection([ ('new', 'New'), ('running', 'Running'), ('done', 'Done'), ('cancelled', 'Cancelled'), ], default='new', string='Stage', group_expand='_expand_states') def _get_odometer(self): self.odometer = 0 for record in self: if record.odometer_id: record.odometer = record.odometer_id.value def _set_odometer(self): for record in self: if not record.odometer: raise UserError(_('Emptying the odometer value of a vehicle is not allowed.')) odometer = self.env['fleet.vehicle.odometer'].create({ 'value': record.odometer, 'date': record.date or fields.Date.context_today(record), 'vehicle_id': record.vehicle_id.id }) self.odometer_id = odometer @api.model_create_multi def create(self, vals_list): for data in vals_list: if 'odometer' in data and not data['odometer']: # if received value for odometer is 0, then remove it from the # data as it would result to the creation of a # odometer log with 0, which is to be avoided del data['odometer'] return super(FleetVehicleLogServices, self).create(vals_list) @api.depends('vehicle_id') def _compute_purchaser_id(self): for service in self: service.purchaser_id = service.vehicle_id.driver_id def _expand_states(self, states, domain, order): return [key for key, dummy in type(self).state.selection]
46.378378
3,432
493
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import fields, models class FleetVehicleState(models.Model): _name = 'fleet.vehicle.state' _order = 'sequence asc' _description = 'Vehicle Status' name = fields.Char(required=True, translate=True) sequence = fields.Integer(help="Used to order the note stages") _sql_constraints = [('fleet_state_name_unique', 'unique(name)', 'State name already exists')]
32.866667
493
3,080
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import _, api, fields, models FUEL_TYPES = [ ('diesel', 'Diesel'), ('gasoline', 'Gasoline'), ('hybrid', 'Hybrid Diesel'), ('full_hybrid_gasoline', 'Hybrid Gasoline'), ('plug_in_hybrid_diesel', 'Plug-in Hybrid Diesel'), ('plug_in_hybrid_gasoline', 'Plug-in Hybrid Gasoline'), ('cng', 'CNG'), ('lpg', 'LPG'), ('hydrogen', 'Hydrogen'), ('electric', 'Electric'), ] class FleetVehicleModel(models.Model): _name = 'fleet.vehicle.model' _description = 'Model of a vehicle' _order = 'name asc' name = fields.Char('Model name', required=True) brand_id = fields.Many2one('fleet.vehicle.model.brand', 'Manufacturer', required=True, help='Manufacturer of the vehicle') category_id = fields.Many2one('fleet.vehicle.model.category', 'Category') vendors = fields.Many2many('res.partner', 'fleet_vehicle_model_vendors', 'model_id', 'partner_id', string='Vendors') image_128 = fields.Image(related='brand_id.image_128', readonly=True) active = fields.Boolean(default=True) vehicle_type = fields.Selection([('car', 'Car'), ('bike', 'Bike')], default='car', required=True) transmission = fields.Selection([('manual', 'Manual'), ('automatic', 'Automatic')], 'Transmission', help='Transmission Used by the vehicle') vehicle_count = fields.Integer(compute='_compute_vehicle_count') model_year = fields.Integer() color = fields.Char() seats = fields.Integer(string='Seats Number') doors = fields.Integer(string='Doors Number') trailer_hook = fields.Boolean(default=False, string='Trailer Hitch') default_co2 = fields.Float('CO2 Emissions') co2_standard = fields.Char() default_fuel_type = fields.Selection(FUEL_TYPES, 'Fuel Type', default='diesel') power = fields.Integer('Power') horsepower = fields.Integer() horsepower_tax = fields.Float('Horsepower Taxation') electric_assistance = fields.Boolean(default=False) @api.depends('name', 'brand_id') def name_get(self): res = [] for record in self: name = record.name if record.brand_id.name: name = record.brand_id.name + '/' + name res.append((record.id, name)) return res def _compute_vehicle_count(self): group = self.env['fleet.vehicle'].read_group( [('model_id', 'in', self.ids)], ['id', 'model_id'], groupby='model_id', lazy=False, ) count_by_model = {entry['model_id'][0]: entry['__count'] for entry in group} for model in self: model.vehicle_count = count_by_model.get(model.id, 0) def action_model_vehicle(self): self.ensure_one() view = { 'type': 'ir.actions.act_window', 'view_mode': 'kanban,tree,form', 'res_model': 'fleet.vehicle', 'name': _('Vehicles'), 'context': {'search_default_model_id': self.id, 'default_model_id': self.id} } return view
41.066667
3,080
1,145
py
PYTHON
15.0
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class FleetVehicleModelBrand(models.Model): _name = 'fleet.vehicle.model.brand' _description = 'Brand of the vehicle' _order = 'name asc' name = fields.Char('Make', required=True) image_128 = fields.Image("Logo", max_width=128, max_height=128) model_count = fields.Integer(compute="_compute_model_count", string="", store=True) model_ids = fields.One2many('fleet.vehicle.model', 'brand_id') @api.depends('model_ids') def _compute_model_count(self): Model = self.env['fleet.vehicle.model'] for record in self: record.model_count = Model.search_count([('brand_id', '=', record.id)]) def action_brand_model(self): self.ensure_one() view = { 'type': 'ir.actions.act_window', 'view_mode': 'tree,form', 'res_model': 'fleet.vehicle.model', 'name': 'Models', 'context': {'search_default_brand_id': self.id, 'default_brand_id': self.id} } return view
34.69697
1,145