From 2e7396b485919f5068d42b2cd63bbd7d33b7317f Mon Sep 17 00:00:00 2001 From: ernestotejeda Date: Wed, 8 Jan 2020 15:52:03 -0500 Subject: [PATCH] [IMP] account_chart_update: black, isort --- account_chart_update/__manifest__.py | 5 +- .../models/ir_model_fields.py | 10 +- .../tests/test_account_chart_update.py | 412 ++++---- .../wizard/wizard_chart_update.py | 893 ++++++++++-------- 4 files changed, 712 insertions(+), 608 deletions(-) diff --git a/account_chart_update/__manifest__.py b/account_chart_update/__manifest__.py index 36bc4ab2..8dbc72ff 100644 --- a/account_chart_update/__manifest__.py +++ b/account_chart_update/__manifest__.py @@ -8,10 +8,7 @@ "name": "Detect changes and update the Account Chart from a template", "summary": "Wizard to update a company's account chart from a template", "version": "12.0.1.0.0", - "author": "Tecnativa, " - "BCIM, " - "Okia, " - "Odoo Community Association (OCA)", + "author": "Tecnativa, " "BCIM, " "Okia, " "Odoo Community Association (OCA)", "website": "http://github.com/OCA/account-financial-tools", "depends": ["account"], "category": "Accounting", diff --git a/account_chart_update/models/ir_model_fields.py b/account_chart_update/models/ir_model_fields.py index f444de17..db6817e1 100644 --- a/account_chart_update/models/ir_model_fields.py +++ b/account_chart_update/models/ir_model_fields.py @@ -5,15 +5,15 @@ from odoo import models class IrModelFields(models.Model): - _inherit = 'ir.model.fields' + _inherit = "ir.model.fields" def name_get(self): """Return special label when showing fields in chart update wizard.""" - if self.env.context.get('account_chart_update'): + if self.env.context.get("account_chart_update"): res = [] for record in self: - res.append((record.id, "%s (%s)" % ( - record.field_description, record.name, - ))) + res.append( + (record.id, "{} ({})".format(record.field_description, record.name)) + ) return res return super(IrModelFields, self).name_get() diff --git a/account_chart_update/tests/test_account_chart_update.py b/account_chart_update/tests/test_account_chart_update.py index 733fe156..e9625b73 100644 --- a/account_chart_update/tests/test_account_chart_update.py +++ b/account_chart_update/tests/test_account_chart_update.py @@ -10,130 +10,139 @@ class TestAccountChartUpdate(common.HttpCase): post_install = True def _create_xml_id(self, record): - return self.env['ir.model.data'].create({ - 'module': 'account_chart_update', - 'name': "%s-%s" % (record._table, record.id), - 'model': record._name, - 'res_id': record.id, - }) + return self.env["ir.model.data"].create( + { + "module": "account_chart_update", + "name": "{}-{}".format(record._table, record.id), + "model": record._name, + "res_id": record.id, + } + ) def _create_account_tmpl(self, name, code, user_type, chart_template): - record = self.env['account.account.template'].create({ - 'name': name, - 'code': code, - 'user_type_id': user_type.id, - 'chart_template_id': chart_template and chart_template.id, - }) + record = self.env["account.account.template"].create( + { + "name": name, + "code": code, + "user_type_id": user_type.id, + "chart_template_id": chart_template and chart_template.id, + } + ) self._create_xml_id(record) return record def _create_tax_tmpl(self, name, chart_template): - record = self.env['account.tax.template'].create({ - 'name': name, - 'amount': 0, - 'chart_template_id': chart_template.id, - 'tax_group_id': self.env.ref('account.tax_group_taxes').id, - }) + record = self.env["account.tax.template"].create( + { + "name": name, + "amount": 0, + "chart_template_id": chart_template.id, + "tax_group_id": self.env.ref("account.tax_group_taxes").id, + } + ) self._create_xml_id(record) return record def _create_fp_tmpl(self, name, chart_template): - record = self.env['account.fiscal.position.template'].create({ - 'name': name, - 'chart_template_id': chart_template.id, - }) + record = self.env["account.fiscal.position.template"].create( + {"name": name, "chart_template_id": chart_template.id} + ) self._create_xml_id(record) return record def _get_model_data(self, record): - return self.env['ir.model.data'].search([ - ('model', '=', record._name), - ('res_id', '=', record.id), - ]) + return self.env["ir.model.data"].search( + [("model", "=", record._name), ("res_id", "=", record.id)] + ) def setUp(self): super(TestAccountChartUpdate, self).setUp() # Make sure user is in English - self.env.user.lang = 'en_US' - self.account_type = self.env['account.account.type'].create({ - 'name': 'Test account_chart_update account type', - }) - self.account_template = self._create_account_tmpl( - 'Test', '100000', self.account_type, False, + self.env.user.lang = "en_US" + self.account_type = self.env["account.account.type"].create( + {"name": "Test account_chart_update account type"} + ) + self.account_template = self._create_account_tmpl( + "Test", "100000", self.account_type, False + ) + self.chart_template = self.env["account.chart.template"].create( + { + "name": "Test account_chart_update chart", + "currency_id": self.env.ref("base.EUR").id, + "code_digits": 6, + "transfer_account_id": self.account_template.id, + "cash_account_code_prefix": "570", + "bank_account_code_prefix": "572", + "transfer_account_code_prefix": "100000", + } ) - self.chart_template = self.env['account.chart.template'].create({ - 'name': 'Test account_chart_update chart', - 'currency_id': self.env.ref('base.EUR').id, - 'code_digits': 6, - 'transfer_account_id': self.account_template.id, - 'cash_account_code_prefix': '570', - 'bank_account_code_prefix': '572', - 'transfer_account_code_prefix': '100000', - }) self.account_template.chart_template_id = self.chart_template.id self.account_template_pl = self._create_account_tmpl( - 'Undistributed Profits/Losses', '999999', + "Undistributed Profits/Losses", + "999999", self.env.ref("account.data_unaffected_earnings"), self.chart_template, ) - self.tax_template = self._create_tax_tmpl( - 'Test tax', self.chart_template, + self.tax_template = self._create_tax_tmpl("Test tax", self.chart_template) + self.fp_template = self._create_fp_tmpl("Test fp", self.chart_template) + self.fp_template_tax = self.env["account.fiscal.position.tax.template"].create( + {"tax_src_id": self.tax_template.id, "position_id": self.fp_template.id} ) - self.fp_template = self._create_fp_tmpl('Test fp', self.chart_template) - self.fp_template_tax = self.env[ - 'account.fiscal.position.tax.template' - ].create({ - 'tax_src_id': self.tax_template.id, - 'position_id': self.fp_template.id, - }) self._create_xml_id(self.fp_template_tax) self.fp_template_account = self.env[ - 'account.fiscal.position.account.template' - ].create({ - 'account_src_id': self.account_template.id, - 'account_dest_id': self.account_template.id, - 'position_id': self.fp_template.id, - }) + "account.fiscal.position.account.template" + ].create( + { + "account_src_id": self.account_template.id, + "account_dest_id": self.account_template.id, + "position_id": self.fp_template.id, + } + ) self._create_xml_id(self.fp_template_account) - self.tax_group = self.env['account.tax.group'].create({ - 'name': 'Test tax group', - }) - self.account_tag_1 = self.env['account.account.tag'].create({ - 'name': 'Test account tag 1', - }) - self.account_tag_2 = self.env['account.account.tag'].create({ - 'name': 'Test account tag 2', - }) - self.company = self.env['res.company'].create({ - 'name': 'Test account_chart_update company', - 'currency_id': self.chart_template.currency_id.id, - }) - company_user = self.env.user.copy({'company_id': self.company.id}) + self.tax_group = self.env["account.tax.group"].create( + {"name": "Test tax group"} + ) + self.account_tag_1 = self.env["account.account.tag"].create( + {"name": "Test account tag 1"} + ) + self.account_tag_2 = self.env["account.account.tag"].create( + {"name": "Test account tag 2"} + ) + self.company = self.env["res.company"].create( + { + "name": "Test account_chart_update company", + "currency_id": self.chart_template.currency_id.id, + } + ) + company_user = self.env.user.copy({"company_id": self.company.id}) chart_by_company_user = self.chart_template.sudo(company_user) chart_by_company_user.try_loading_for_current_company() - self.tax = self.env['account.tax'].search([ - ('name', '=', self.tax_template.name), - ('company_id', '=', self.company.id), - ]) - self.account = self.env['account.account'].search([ - ('code', '=', self.account_template.code), - ('company_id', '=', self.company.id), - ]) - self.fp = self.env['account.fiscal.position'].search([ - ('name', '=', self.fp_template.name), - ('company_id', '=', self.company.id), - ]) + self.tax = self.env["account.tax"].search( + [ + ("name", "=", self.tax_template.name), + ("company_id", "=", self.company.id), + ] + ) + self.account = self.env["account.account"].search( + [ + ("code", "=", self.account_template.code), + ("company_id", "=", self.company.id), + ] + ) + self.fp = self.env["account.fiscal.position"].search( + [("name", "=", self.fp_template.name), ("company_id", "=", self.company.id)] + ) # Prepare wizard values - self.wizard_obj = self.env['wizard.update.charts.accounts'] + self.wizard_obj = self.env["wizard.update.charts.accounts"] self.wizard_vals = { - 'company_id': self.company.id, - 'chart_template_id': self.chart_template.id, - 'code_digits': 6, - 'lang': 'en_US' + "company_id": self.company.id, + "chart_template_id": self.chart_template.id, + "code_digits": 6, + "lang": "en_US", } - @mute_logger('odoo.sql_db') + @mute_logger("odoo.sql_db") def test_chart_update(self): wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() @@ -141,50 +150,45 @@ class TestAccountChartUpdate(common.HttpCase): field = wizard.fp_field_ids[:1] name = field.with_context(account_chart_update=True).name_get()[0] self.assertEqual(name[0], field.id) - self.assertEqual( - name[1], "%s (%s)" % (field.field_description, field.name), - ) + self.assertEqual(name[1], "{} ({})".format(field.field_description, field.name)) name = field.name_get()[0] self.assertEqual(name[0], field.id) - self.assertEqual( - name[1], "%s (%s)" % (field.field_description, field.model), - ) + self.assertEqual(name[1], "{} ({})".format(field.field_description, field.model)) # Test no changes - self.assertEqual(wizard.state, 'ready') + self.assertEqual(wizard.state, "ready") self.assertFalse(wizard.tax_ids) self.assertFalse(wizard.account_ids) self.assertFalse(wizard.fiscal_position_ids) wizard.unlink() # Add templates - new_tax_tmpl = self._create_tax_tmpl( - 'Test tax 2', self.chart_template, - ) + new_tax_tmpl = self._create_tax_tmpl("Test tax 2", self.chart_template) new_account_tmpl = self._create_account_tmpl( - 'Test account 2', '333333', self.account_type, self.chart_template, + "Test account 2", "333333", self.account_type, self.chart_template + ) + new_fp = self._create_fp_tmpl("Test fp 2", self.chart_template) + fp_template_tax = self.env["account.fiscal.position.tax.template"].create( + {"tax_src_id": self.tax_template.id, "position_id": new_fp.id} ) - new_fp = self._create_fp_tmpl('Test fp 2', self.chart_template) - fp_template_tax = self.env[ - 'account.fiscal.position.tax.template' - ].create({ - 'tax_src_id': self.tax_template.id, - 'position_id': new_fp.id, - }) self._create_xml_id(fp_template_tax) fp_template_account = self.env[ - 'account.fiscal.position.account.template' - ].create({ - 'account_src_id': self.account_template.id, - 'account_dest_id': self.account_template.id, - 'position_id': new_fp.id, - }) + "account.fiscal.position.account.template" + ].create( + { + "account_src_id": self.account_template.id, + "account_dest_id": self.account_template.id, + "position_id": new_fp.id, + } + ) self._create_xml_id(fp_template_account) # Check that no action is performed if the option is not selected wizard_vals = self.wizard_vals.copy() - wizard_vals.update({ - 'update_tax': False, - 'update_account': False, - 'update_fiscal_position': False, - }) + wizard_vals.update( + { + "update_tax": False, + "update_account": False, + "update_fiscal_position": False, + } + ) wizard = self.wizard_obj.create(wizard_vals) wizard.action_find_records() self.assertFalse(wizard.tax_ids) @@ -196,33 +200,30 @@ class TestAccountChartUpdate(common.HttpCase): wizard.action_find_records() self.assertTrue(wizard.tax_ids) self.assertEqual(wizard.tax_ids.tax_id, new_tax_tmpl) - self.assertEqual(wizard.tax_ids.type, 'new') + self.assertEqual(wizard.tax_ids.type, "new") self.assertTrue(wizard.account_ids) self.assertEqual(wizard.account_ids.account_id, new_account_tmpl) - self.assertEqual(wizard.tax_ids.type, 'new') + self.assertEqual(wizard.tax_ids.type, "new") self.assertTrue(wizard.fiscal_position_ids) self.assertEqual(wizard.fiscal_position_ids.fiscal_position_id, new_fp) - self.assertEqual(wizard.fiscal_position_ids.type, 'new') + self.assertEqual(wizard.fiscal_position_ids.type, "new") wizard.action_update_records() - self.assertEqual(wizard.state, 'done') + self.assertEqual(wizard.state, "done") self.assertEqual(wizard.new_taxes, 1) self.assertEqual(wizard.new_accounts, 1) self.assertEqual(wizard.new_fps, 1) self.assertTrue(wizard.log) - new_tax = self.env['account.tax'].search([ - ('name', '=', new_tax_tmpl.name), - ('company_id', '=', self.company.id), - ]) + new_tax = self.env["account.tax"].search( + [("name", "=", new_tax_tmpl.name), ("company_id", "=", self.company.id)] + ) self.assertTrue(new_tax) - new_account = self.env['account.account'].search([ - ('code', '=', new_account_tmpl.code), - ('company_id', '=', self.company.id), - ]) + new_account = self.env["account.account"].search( + [("code", "=", new_account_tmpl.code), ("company_id", "=", self.company.id)] + ) self.assertTrue(new_account) - fp = self.env['account.fiscal.position'].search([ - ('name', '=', new_fp.name), - ('company_id', '=', self.company.id), - ]) + fp = self.env["account.fiscal.position"].search( + [("name", "=", new_fp.name), ("company_id", "=", self.company.id)] + ) self.assertTrue(fp) self.assertTrue(fp.tax_ids) self.assertTrue(fp.account_ids) @@ -233,7 +234,7 @@ class TestAccountChartUpdate(common.HttpCase): self.tax_template.refund_account_id = new_account_tmpl.id self.account_template.name = "Other name" self.account_template.tag_ids = [ - (6, 0, [self.account_tag_1.id, self.account_tag_2.id]), + (6, 0, [self.account_tag_1.id, self.account_tag_2.id]) ] self.fp_template.note = "Test note" self.fp_template.account_ids.account_dest_id = new_account_tmpl.id @@ -242,16 +243,16 @@ class TestAccountChartUpdate(common.HttpCase): wizard.action_find_records() self.assertTrue(wizard.tax_ids) self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) - self.assertEqual(wizard.tax_ids.type, 'updated') + self.assertEqual(wizard.tax_ids.type, "updated") self.assertTrue(wizard.account_ids) self.assertEqual(wizard.account_ids.account_id, self.account_template) - self.assertEqual(wizard.account_ids.type, 'updated') + self.assertEqual(wizard.account_ids.type, "updated") self.assertTrue(wizard.fiscal_position_ids) - self.assertTrue(wizard.fiscal_position_ids.type, 'updated') + self.assertTrue(wizard.fiscal_position_ids.type, "updated") self.assertEqual( - wizard.fiscal_position_ids.fiscal_position_id, self.fp_template, + wizard.fiscal_position_ids.fiscal_position_id, self.fp_template ) - self.assertEqual(wizard.fiscal_position_ids.type, 'updated') + self.assertEqual(wizard.fiscal_position_ids.type, "updated") wizard.action_update_records() self.assertEqual(wizard.updated_taxes, 1) self.assertEqual(wizard.updated_accounts, 1) @@ -272,18 +273,15 @@ class TestAccountChartUpdate(common.HttpCase): self.fp_template.note = "Test note 2" wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() - wizard.tax_field_ids -= self.env['ir.model.fields'].search([ - ('model', '=', 'account.tax.template'), - ('name', '=', 'description'), - ]) - wizard.account_field_ids -= self.env['ir.model.fields'].search([ - ('model', '=', 'account.account.template'), - ('name', '=', 'name'), - ]) - wizard.fp_field_ids -= self.env['ir.model.fields'].search([ - ('model', '=', 'account.fiscal.position.template'), - ('name', '=', 'note'), - ]) + wizard.tax_field_ids -= self.env["ir.model.fields"].search( + [("model", "=", "account.tax.template"), ("name", "=", "description")] + ) + wizard.account_field_ids -= self.env["ir.model.fields"].search( + [("model", "=", "account.account.template"), ("name", "=", "name")] + ) + wizard.fp_field_ids -= self.env["ir.model.fields"].search( + [("model", "=", "account.fiscal.position.template"), ("name", "=", "note")] + ) wizard.action_find_records() self.assertFalse(wizard.tax_ids) self.assertFalse(wizard.account_ids) @@ -298,35 +296,45 @@ class TestAccountChartUpdate(common.HttpCase): wizard.action_find_records() self.assertTrue(wizard.tax_ids) self.assertEqual(wizard.tax_ids.update_tax_id, new_tax) - self.assertEqual(wizard.tax_ids.type, 'deleted') + self.assertEqual(wizard.tax_ids.type, "deleted") wizard.action_update_records() self.assertEqual(wizard.deleted_taxes, 1) self.assertFalse(new_tax.active) wizard.unlink() # Errors on account update - self.account_template.currency_id = self.ref('base.USD') - self.env['account.move'].create({ - 'name': 'Test move', - 'journal_id': self.env['account.journal'].search([ - ('company_id', '=', self.company.id), - ], limit=1).id, - 'date': fields.Date.today(), - 'line_ids': [ - (0, 0, { - 'account_id': self.account.id, - 'name': 'Test move line', - 'debit': 10, - 'credit': 0, - 'currency_id': self.ref('base.EUR'), - }), - (0, 0, { - 'account_id': self.account.id, - 'name': 'Test move line2', - 'debit': 0, - 'credit': 10, - }), - ] - }) + self.account_template.currency_id = self.ref("base.USD") + self.env["account.move"].create( + { + "name": "Test move", + "journal_id": self.env["account.journal"] + .search([("company_id", "=", self.company.id)], limit=1) + .id, + "date": fields.Date.today(), + "line_ids": [ + ( + 0, + 0, + { + "account_id": self.account.id, + "name": "Test move line", + "debit": 10, + "credit": 0, + "currency_id": self.ref("base.EUR"), + }, + ), + ( + 0, + 0, + { + "account_id": self.account.id, + "name": "Test move line2", + "debit": 0, + "credit": 10, + }, + ), + ], + } + ) self.tax_template.description = "Other description" wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() @@ -343,12 +351,12 @@ class TestAccountChartUpdate(common.HttpCase): # Errors on account_creation self.account_template.currency_id = False new_account_tmpl_2 = self._create_account_tmpl( - 'Test account 3', '444444', self.account_type, self.chart_template, + "Test account 3", "444444", self.account_type, self.chart_template ) wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() - self.assertEqual(wizard.account_ids.type, 'new') - new_account_tmpl_2.code = '333333' # Trick the code for forcing error + self.assertEqual(wizard.account_ids.type, "new") + new_account_tmpl_2.code = "333333" # Trick the code for forcing error with self.assertRaises(Exception): wizard.action_update_records() wizard.continue_on_errors = True @@ -366,12 +374,13 @@ class TestAccountChartUpdate(common.HttpCase): wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) - self.assertEqual(wizard.tax_ids.type, 'updated') + self.assertEqual(wizard.tax_ids.type, "updated") self.assertEqual(wizard.account_ids.account_id, self.account_template) - self.assertEqual(wizard.account_ids.type, 'updated') - self.assertTrue(wizard.fiscal_position_ids.type, 'updated') - self.assertEqual(wizard.fiscal_position_ids.fiscal_position_id, - self.fp_template) + self.assertEqual(wizard.account_ids.type, "updated") + self.assertTrue(wizard.fiscal_position_ids.type, "updated") + self.assertEqual( + wizard.fiscal_position_ids.fiscal_position_id, self.fp_template + ) wizard.action_update_records() self.assertEqual(wizard.updated_taxes, 1) self.assertEqual(wizard.updated_accounts, 1) @@ -392,12 +401,13 @@ class TestAccountChartUpdate(common.HttpCase): wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) - self.assertEqual(wizard.tax_ids.type, 'updated') + self.assertEqual(wizard.tax_ids.type, "updated") self.assertEqual(wizard.account_ids.account_id, self.account_template) - self.assertEqual(wizard.account_ids.type, 'updated') - self.assertTrue(wizard.fiscal_position_ids.type, 'updated') - self.assertEqual(wizard.fiscal_position_ids.fiscal_position_id, - self.fp_template) + self.assertEqual(wizard.account_ids.type, "updated") + self.assertTrue(wizard.fiscal_position_ids.type, "updated") + self.assertEqual( + wizard.fiscal_position_ids.fiscal_position_id, self.fp_template + ) wizard.action_update_records() self.assertEqual(wizard.updated_taxes, 1) self.assertEqual(wizard.updated_accounts, 1) @@ -412,7 +422,7 @@ class TestAccountChartUpdate(common.HttpCase): wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.account_ids.account_id, self.account_template) - self.assertEqual(wizard.account_ids.type, 'updated') + self.assertEqual(wizard.account_ids.type, "updated") wizard.action_update_records() self.assertEqual(wizard.updated_accounts, 1) self.assertEqual(self.account.code, self.account_template.code) @@ -426,12 +436,13 @@ class TestAccountChartUpdate(common.HttpCase): wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) - self.assertEqual(wizard.tax_ids.type, 'updated') + self.assertEqual(wizard.tax_ids.type, "updated") self.assertEqual(wizard.account_ids.account_id, self.account_template) - self.assertEqual(wizard.account_ids.type, 'updated') - self.assertTrue(wizard.fiscal_position_ids.type, 'updated') - self.assertEqual(wizard.fiscal_position_ids.fiscal_position_id, - self.fp_template) + self.assertEqual(wizard.account_ids.type, "updated") + self.assertTrue(wizard.fiscal_position_ids.type, "updated") + self.assertEqual( + wizard.fiscal_position_ids.fiscal_position_id, self.fp_template + ) # There is no XML-ID self.assertFalse(list(self.tax.get_xml_id().values())[0]) self.assertFalse(list(self.account.get_xml_id().values())[0]) @@ -457,12 +468,13 @@ class TestAccountChartUpdate(common.HttpCase): wizard = self.wizard_obj.create(self.wizard_vals) wizard.action_find_records() self.assertEqual(wizard.tax_ids.tax_id, self.tax_template) - self.assertEqual(wizard.tax_ids.type, 'updated') + self.assertEqual(wizard.tax_ids.type, "updated") self.assertEqual(wizard.account_ids.account_id, self.account_template) - self.assertEqual(wizard.account_ids.type, 'updated') - self.assertTrue(wizard.fiscal_position_ids.type, 'updated') - self.assertEqual(wizard.fiscal_position_ids.fiscal_position_id, - self.fp_template) + self.assertEqual(wizard.account_ids.type, "updated") + self.assertTrue(wizard.fiscal_position_ids.type, "updated") + self.assertEqual( + wizard.fiscal_position_ids.fiscal_position_id, self.fp_template + ) # There is no XML-ID self.assertFalse(list(self.tax.get_xml_id().values())[0]) self.assertFalse(list(self.account.get_xml_id().values())[0]) diff --git a/account_chart_update/wizard/wizard_chart_update.py b/account_chart_update/wizard/wizard_chart_update.py index 3b69ec12..6823de60 100644 --- a/account_chart_update/wizard/wizard_chart_update.py +++ b/account_chart_update/wizard/wizard_chart_update.py @@ -8,96 +8,124 @@ # Copyright 2018 Tecnativa - Pedro M. Baeza # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). -from odoo import _, api, exceptions, fields, models, tools -from odoo.tools import config +import logging from contextlib import closing from io import StringIO -import logging + +from odoo import _, api, exceptions, fields, models, tools +from odoo.tools import config _logger = logging.getLogger(__name__) EXCEPTION_TEXT = "Traceback (most recent call last)" class WizardUpdateChartsAccounts(models.TransientModel): - _name = 'wizard.update.charts.accounts' - _description = 'Wizard Update Charts Accounts' + _name = "wizard.update.charts.accounts" + _description = "Wizard Update Charts Accounts" state = fields.Selection( - selection=[('init', 'Configuration'), - ('ready', 'Select records to update'), - ('done', 'Wizard completed')], - string='Status', readonly=True, default='init') + selection=[ + ("init", "Configuration"), + ("ready", "Select records to update"), + ("done", "Wizard completed"), + ], + string="Status", + readonly=True, + default="init", + ) company_id = fields.Many2one( - comodel_name='res.company', string='Company', required=True, - ondelete='set null', default=lambda self: self.env.user.company_id.id) + comodel_name="res.company", + string="Company", + required=True, + ondelete="set null", + default=lambda self: self.env.user.company_id.id, + ) chart_template_id = fields.Many2one( - comodel_name='account.chart.template', string='Chart Template', - ondelete='cascade', required=True) + comodel_name="account.chart.template", + string="Chart Template", + ondelete="cascade", + required=True, + ) chart_template_ids = fields.Many2many( "account.chart.template", string="Chart Templates", compute="_compute_chart_template_ids", - help="Includes all chart templates.") - code_digits = fields.Integer( - related="chart_template_id.code_digits") + help="Includes all chart templates.", + ) + code_digits = fields.Integer(related="chart_template_id.code_digits") lang = fields.Selection( - lambda self: self._get_lang_selection_options(), 'Language', size=5, + lambda self: self._get_lang_selection_options(), + "Language", + size=5, required=True, help="For records searched by name (taxes, fiscal " - "positions), the template name will be matched against the " - "record name on this language.", - default=lambda self: self.env.context.get('lang', self.env.user.lang)) - update_tax = fields.Boolean( - string='Update taxes', default=True, - help="Existing taxes are updated. Taxes are searched by name.") - update_account = fields.Boolean( - string='Update accounts', default=True, - help="Existing accounts are updated. Accounts are searched by code.") - update_fiscal_position = fields.Boolean( - string='Update fiscal positions', default=True, - help="Existing fiscal positions are updated. Fiscal positions are " - "searched by name.") - continue_on_errors = fields.Boolean( - string="Continue on errors", default=False, - help="If set, the wizard will continue to the next step even if " - "there are minor errors.") - recreate_xml_ids = fields.Boolean( - string="Recreate missing XML-IDs", + "positions), the template name will be matched against the " + "record name on this language.", + default=lambda self: self.env.context.get("lang", self.env.user.lang), ) + update_tax = fields.Boolean( + string="Update taxes", + default=True, + help="Existing taxes are updated. Taxes are searched by name.", + ) + update_account = fields.Boolean( + string="Update accounts", + default=True, + help="Existing accounts are updated. Accounts are searched by code.", + ) + update_fiscal_position = fields.Boolean( + string="Update fiscal positions", + default=True, + help="Existing fiscal positions are updated. Fiscal positions are " + "searched by name.", + ) + continue_on_errors = fields.Boolean( + string="Continue on errors", + default=False, + help="If set, the wizard will continue to the next step even if " + "there are minor errors.", + ) + recreate_xml_ids = fields.Boolean(string="Recreate missing XML-IDs") tax_ids = fields.One2many( - comodel_name='wizard.update.charts.accounts.tax', ondelete='cascade', - inverse_name='update_chart_wizard_id', string='Taxes') + comodel_name="wizard.update.charts.accounts.tax", + ondelete="cascade", + inverse_name="update_chart_wizard_id", + string="Taxes", + ) account_ids = fields.One2many( - comodel_name='wizard.update.charts.accounts.account', - inverse_name='update_chart_wizard_id', string='Accounts', - ondelete='cascade') + comodel_name="wizard.update.charts.accounts.account", + inverse_name="update_chart_wizard_id", + string="Accounts", + ondelete="cascade", + ) fiscal_position_ids = fields.One2many( - comodel_name='wizard.update.charts.accounts.fiscal.position', - inverse_name='update_chart_wizard_id', string='Fiscal positions', - ondelete='cascade') - new_taxes = fields.Integer( - string='New taxes', compute="_compute_new_taxes_count") + comodel_name="wizard.update.charts.accounts.fiscal.position", + inverse_name="update_chart_wizard_id", + string="Fiscal positions", + ondelete="cascade", + ) + new_taxes = fields.Integer(string="New taxes", compute="_compute_new_taxes_count") new_accounts = fields.Integer( - string='New accounts', - compute="_compute_new_accounts_count") + string="New accounts", compute="_compute_new_accounts_count" + ) rejected_new_account_number = fields.Integer() new_fps = fields.Integer( - string='New fiscal positions', - compute="_compute_new_fps_count") + string="New fiscal positions", compute="_compute_new_fps_count" + ) updated_taxes = fields.Integer( - string='Updated taxes', - compute="_compute_updated_taxes_count") + string="Updated taxes", compute="_compute_updated_taxes_count" + ) rejected_updated_account_number = fields.Integer() updated_accounts = fields.Integer( - string='Updated accounts', - compute="_compute_updated_accounts_count") + string="Updated accounts", compute="_compute_updated_accounts_count" + ) updated_fps = fields.Integer( - string='Updated fiscal positions', - compute="_compute_updated_fps_count") + string="Updated fiscal positions", compute="_compute_updated_fps_count" + ) deleted_taxes = fields.Integer( - string='Deactivated taxes', - compute="_compute_deleted_taxes_count") - log = fields.Text(string='Messages and Errors', readonly=True) + string="Deactivated taxes", compute="_compute_deleted_taxes_count" + ) + log = fields.Text(string="Messages and Errors", readonly=True) tax_field_ids = fields.Many2many( comodel_name="ir.model.fields", relation="wizard_update_charts_tax_fields_rel", @@ -140,64 +168,69 @@ class WizardUpdateChartsAccounts(models.TransientModel): def _domain_per_name(self, name): return [ - ('model', '=', name), - ('name', 'not in', tuple(self.fields_to_ignore(name))), + ("model", "=", name), + ("name", "not in", tuple(self.fields_to_ignore(name))), ] def _domain_tax_field_ids(self): - return self._domain_per_name('account.tax.template') + return self._domain_per_name("account.tax.template") def _domain_account_field_ids(self): - return self._domain_per_name('account.account.template') + return self._domain_per_name("account.account.template") def _domain_fp_field_ids(self): - return self._domain_per_name('account.fiscal.position.template') + return self._domain_per_name("account.fiscal.position.template") def _default_tax_field_ids(self): - return [(4, x.id) for x in self.env['ir.model.fields'].search( - self._domain_tax_field_ids() - )] + return [ + (4, x.id) + for x in self.env["ir.model.fields"].search(self._domain_tax_field_ids()) + ] def _default_account_field_ids(self): - return [(4, x.id) for x in self.env['ir.model.fields'].search( - self._domain_account_field_ids() - )] + return [ + (4, x.id) + for x in self.env["ir.model.fields"].search( + self._domain_account_field_ids() + ) + ] def _default_fp_field_ids(self): - return [(4, x.id) for x in self.env['ir.model.fields'].search( - self._domain_fp_field_ids() - )] + return [ + (4, x.id) + for x in self.env["ir.model.fields"].search(self._domain_fp_field_ids()) + ] def _get_matching_ids(self, model_name, ordered_opts): vals = [] for seq, opt in enumerate(ordered_opts, 1): - vals.append((0, False, {'sequence': seq, 'matching_value': opt})) + vals.append((0, False, {"sequence": seq, "matching_value": opt})) all_options = self.env[model_name]._get_matching_selection() all_options = map(lambda x: x[0], all_options) all_options = list(set(all_options) - set(ordered_opts)) for seq, opt in enumerate(all_options, len(ordered_opts) + 1): - vals.append((0, False, {'sequence': seq, 'matching_value': opt})) + vals.append((0, False, {"sequence": seq, "matching_value": opt})) return vals def _default_fp_matching_ids(self): - ordered_opts = ['xml_id', 'name'] - return self._get_matching_ids('wizard.fp.matching', ordered_opts) + ordered_opts = ["xml_id", "name"] + return self._get_matching_ids("wizard.fp.matching", ordered_opts) def _default_tax_matching_ids(self): - ordered_opts = ['xml_id', 'description', 'name'] - return self._get_matching_ids('wizard.tax.matching', ordered_opts) + ordered_opts = ["xml_id", "description", "name"] + return self._get_matching_ids("wizard.tax.matching", ordered_opts) def _default_account_matching_ids(self): - ordered_opts = ['xml_id', 'code', 'name'] - return self._get_matching_ids('wizard.account.matching', ordered_opts) + ordered_opts = ["xml_id", "code", "name"] + return self._get_matching_ids("wizard.account.matching", ordered_opts) @api.model def _get_lang_selection_options(self): """Gets the available languages for the selection.""" - langs = self.env['res.lang'].search([]) + langs = self.env["res.lang"].search([]) return [(lang.code, lang.name) for lang in langs] @api.multi @@ -207,47 +240,47 @@ class WizardUpdateChartsAccounts(models.TransientModel): self.chart_template_ids = all_parents @api.multi - @api.depends('tax_ids') + @api.depends("tax_ids") def _compute_new_taxes_count(self): - self.new_taxes = len(self.tax_ids.filtered(lambda x: x.type == 'new')) + self.new_taxes = len(self.tax_ids.filtered(lambda x: x.type == "new")) @api.multi - @api.depends('account_ids') + @api.depends("account_ids") def _compute_new_accounts_count(self): - self.new_accounts = len( - self.account_ids.filtered(lambda x: x.type == 'new') - ) - self.rejected_new_account_number + self.new_accounts = ( + len(self.account_ids.filtered(lambda x: x.type == "new")) + - self.rejected_new_account_number + ) @api.multi - @api.depends('fiscal_position_ids') + @api.depends("fiscal_position_ids") def _compute_new_fps_count(self): - self.new_fps = len( - self.fiscal_position_ids.filtered(lambda x: x.type == 'new')) + self.new_fps = len(self.fiscal_position_ids.filtered(lambda x: x.type == "new")) @api.multi - @api.depends('tax_ids') + @api.depends("tax_ids") def _compute_updated_taxes_count(self): - self.updated_taxes = len( - self.tax_ids.filtered(lambda x: x.type == 'updated')) + self.updated_taxes = len(self.tax_ids.filtered(lambda x: x.type == "updated")) @api.multi - @api.depends('account_ids') + @api.depends("account_ids") def _compute_updated_accounts_count(self): - self.updated_accounts = len( - self.account_ids.filtered(lambda x: x.type == 'updated') - ) - self.rejected_updated_account_number + self.updated_accounts = ( + len(self.account_ids.filtered(lambda x: x.type == "updated")) + - self.rejected_updated_account_number + ) @api.multi - @api.depends('fiscal_position_ids') + @api.depends("fiscal_position_ids") def _compute_updated_fps_count(self): self.updated_fps = len( - self.fiscal_position_ids.filtered(lambda x: x.type == 'updated')) + self.fiscal_position_ids.filtered(lambda x: x.type == "updated") + ) @api.multi - @api.depends('tax_ids') + @api.depends("tax_ids") def _compute_deleted_taxes_count(self): - self.deleted_taxes = len( - self.tax_ids.filtered(lambda x: x.type == 'deleted')) + self.deleted_taxes = len(self.tax_ids.filtered(lambda x: x.type == "deleted")) @api.multi @api.onchange("company_id") @@ -257,30 +290,31 @@ class WizardUpdateChartsAccounts(models.TransientModel): @api.multi def _reopen(self): return { - 'type': 'ir.actions.act_window', - 'view_mode': 'form', - 'view_type': 'form', - 'res_id': self.id, - 'res_model': self._name, - 'target': 'new', + "type": "ir.actions.act_window", + "view_mode": "form", + "view_type": "form", + "res_id": self.id, + "res_model": self._name, + "target": "new", # save original model in context, # because selecting the list of available # templates requires a model in context - 'context': { - 'default_model': self._name, - }, + "context": {"default_model": self._name}, } @api.multi def action_init(self): """Initial action that sets the initial state.""" - self.write({ - 'state': 'init', - 'tax_ids': [(2, r.id, False) for r in self.tax_ids], - 'account_ids': [(2, r.id, False) for r in self.account_ids], - 'fiscal_position_ids': [(2, r.id, False) for r in - self.fiscal_position_ids], - }) + self.write( + { + "state": "init", + "tax_ids": [(2, r.id, False) for r in self.tax_ids], + "account_ids": [(2, r.id, False) for r in self.account_ids], + "fiscal_position_ids": [ + (2, r.id, False) for r in self.fiscal_position_ids + ], + } + ) return self._reopen() @api.multi @@ -295,7 +329,7 @@ class WizardUpdateChartsAccounts(models.TransientModel): if self.update_fiscal_position: self._find_fiscal_positions() # Write the results, and go to the next step. - self.state = 'ready' + self.state = "ready" return self._reopen() @api.multi @@ -313,8 +347,10 @@ class WizardUpdateChartsAccounts(models.TransientModel): perform_rest = True if self.update_account: self._update_accounts() - if (EXCEPTION_TEXT in log_output.getvalue() and - not self.continue_on_errors): # Abort early + if ( + EXCEPTION_TEXT in log_output.getvalue() + and not self.continue_on_errors + ): # Abort early perform_rest = False # Clear this cache for avoiding incorrect account hits (as it was # queried before account creation) @@ -329,15 +365,14 @@ class WizardUpdateChartsAccounts(models.TransientModel): self.log = log_output.getvalue() # Check if errors where detected and wether we should stop. if EXCEPTION_TEXT in self.log and not self.continue_on_errors: - raise exceptions.Warning( - _("One or more errors detected!\n\n%s") % self.log) + raise exceptions.Warning(_("One or more errors detected!\n\n%s") % self.log) # Store the data and go to the next step. - self.state = 'done' + self.state = "done" return self._reopen() def _get_real_xml_name(self, template): [external_id] = template.get_external_id().values() - (name, module) = external_id.split('.') + (name, module) = external_id.split(".") return "%s.%d_%s" % (name, self.company_id.id, module) @api.multi @@ -346,26 +381,30 @@ class WizardUpdateChartsAccounts(models.TransientModel): """Find a tax that matches the template.""" # search inactive taxes too, to avoid re-creating # taxes that have been deactivated before - tax_model = self.env['account.tax'].with_context(active_test=False) + tax_model = self.env["account.tax"].with_context(active_test=False) for template in templates: - for matching in self.tax_matching_ids.sorted('sequence'): - if matching.matching_value == 'xml_id': - real = self.env.ref(self._get_real_xml_name(template), - raise_if_not_found=False) + for matching in self.tax_matching_ids.sorted("sequence"): + if matching.matching_value == "xml_id": + real = self.env.ref( + self._get_real_xml_name(template), raise_if_not_found=False + ) if not real: continue - criteria = ('id', '=', real.id) + criteria = ("id", "=", real.id) else: field_name = matching.matching_value if not template[field_name]: continue - criteria = (field_name, '=', template[field_name]) + criteria = (field_name, "=", template[field_name]) - result = tax_model.search([ - criteria, - ("company_id", "=", self.company_id.id), - ("type_tax_use", "=", template.type_tax_use), - ], limit=1) + result = tax_model.search( + [ + criteria, + ("company_id", "=", self.company_id.id), + ("type_tax_use", "=", template.type_tax_use), + ], + limit=1, + ) if result: return result.id @@ -375,16 +414,16 @@ class WizardUpdateChartsAccounts(models.TransientModel): @tools.ormcache("code") def padded_code(self, code): """Return a right-zero-padded code with the chosen digits.""" - return code.ljust(self.code_digits, '0') + return code.ljust(self.code_digits, "0") @api.multi @tools.ormcache("templates") def find_account_by_templates(self, templates): """Find an account that matches the template.""" - account_model = self.env['account.account'] - for matching in self.account_matching_ids.sorted('sequence'): - if matching.matching_value == 'xml_id': - real = self.env['account.account'] + account_model = self.env["account.account"] + for matching in self.account_matching_ids.sorted("sequence"): + if matching.matching_value == "xml_id": + real = self.env["account.account"] for template in templates: try: real |= self.env.ref(self._get_real_xml_name(template)) @@ -393,21 +432,22 @@ class WizardUpdateChartsAccounts(models.TransientModel): if not real: continue - criteria = ('id', 'in', real.ids) - elif matching.matching_value == 'code': + criteria = ("id", "in", real.ids) + elif matching.matching_value == "code": codes = templates.mapped("code") if not codes: continue - criteria = ('code', 'in', list(map(self.padded_code, codes))) + criteria = ("code", "in", list(map(self.padded_code, codes))) else: field_name = matching.matching_value field_values = templates.mapped(field_name) if not field_values: continue - criteria = (field_name, 'in', field_values) + criteria = (field_name, "in", field_values) result = account_model.search( - [criteria, ('company_id', '=', self.company_id.id)]) + [criteria, ("company_id", "=", self.company_id.id)] + ) if result: return result.id @@ -417,10 +457,10 @@ class WizardUpdateChartsAccounts(models.TransientModel): @tools.ormcache("templates") def find_fp_by_templates(self, templates): """Find a real fiscal position from a template.""" - fp_model = self.env['account.fiscal.position'] - for matching in self.fp_matching_ids.sorted('sequence'): - if matching.matching_value == 'xml_id': - real = self.env['account.fiscal.position'] + fp_model = self.env["account.fiscal.position"] + for matching in self.fp_matching_ids.sorted("sequence"): + if matching.matching_value == "xml_id": + real = self.env["account.fiscal.position"] for template in templates: try: real |= self.env.ref(self._get_real_xml_name(template)) @@ -429,17 +469,17 @@ class WizardUpdateChartsAccounts(models.TransientModel): if not real: continue - criteria = ('id', 'in', real.ids) + criteria = ("id", "in", real.ids) else: field_name = matching.matching_value field_values = templates.mapped(field_name) if not field_values: continue - criteria = (field_name, 'in', field_values) + criteria = (field_name, "in", field_values) - result = fp_model.search([ - criteria, ('company_id', '=', self.company_id.id) - ], limit=1) + result = fp_model.search( + [criteria, ("company_id", "=", self.company_id.id)], limit=1 + ) if result: return result.id @@ -453,18 +493,26 @@ class WizardUpdateChartsAccounts(models.TransientModel): pos_id = self.find_fp_by_templates(tpl.position_id) src_id = self.find_account_by_templates(tpl.account_src_id) dest_id = self.find_account_by_templates(tpl.account_dest_id) - existing = self.env["account.fiscal.position.account"].search([ - ("position_id", "=", pos_id), - ("account_src_id", "=", src_id), - ("account_dest_id", "=", dest_id), - ]) + existing = self.env["account.fiscal.position.account"].search( + [ + ("position_id", "=", pos_id), + ("account_src_id", "=", src_id), + ("account_dest_id", "=", dest_id), + ] + ) if not existing: # create a new mapping - result.append((0, 0, { - 'position_id': pos_id, - 'account_src_id': src_id, - 'account_dest_id': dest_id, - })) + result.append( + ( + 0, + 0, + { + "position_id": pos_id, + "account_src_id": src_id, + "account_dest_id": dest_id, + }, + ) + ) else: current_fp_accounts -= existing # Mark to be removed the lines not found @@ -480,18 +528,26 @@ class WizardUpdateChartsAccounts(models.TransientModel): pos_id = self.find_fp_by_templates(tpl.position_id) src_id = self.find_tax_by_templates(tpl.tax_src_id) dest_id = self.find_tax_by_templates(tpl.tax_dest_id) - existing = self.env["account.fiscal.position.tax"].search([ - ("position_id", "=", pos_id), - ("tax_src_id", "=", src_id), - ("tax_dest_id", "=", dest_id), - ]) + existing = self.env["account.fiscal.position.tax"].search( + [ + ("position_id", "=", pos_id), + ("tax_src_id", "=", src_id), + ("tax_dest_id", "=", dest_id), + ] + ) if not existing: # create a new mapping - result.append((0, 0, { - 'position_id': pos_id, - 'tax_src_id': src_id, - 'tax_dest_id': dest_id, - })) + result.append( + ( + 0, + 0, + { + "position_id": pos_id, + "tax_src_id": src_id, + "tax_dest_id": dest_id, + }, + ) + ) else: current_fp_taxes -= existing # Mark to be removed the lines not found @@ -509,19 +565,15 @@ class WizardUpdateChartsAccounts(models.TransientModel): :return set: Fields to ignore in diff. """ specials_mapping = { - "account.tax.template": { - "chart_template_id", - "children_tax_ids", - }, - "account.account.template": { - "chart_template_id", - }, - "account.fiscal.position.template": { - "chart_template_id", - }, + "account.tax.template": {"chart_template_id", "children_tax_ids"}, + "account.account.template": {"chart_template_id"}, + "account.fiscal.position.template": {"chart_template_id"}, } - specials = ({"display_name", "__last_update", "company_id"} | - specials_mapping.get(name, set())) + specials = { + "display_name", + "__last_update", + "company_id", + } | specials_mapping.get(name, set()) return set(models.MAGIC_COLUMNS) | specials @api.model @@ -539,12 +591,12 @@ class WizardUpdateChartsAccounts(models.TransientModel): result = dict() ignore = self.fields_to_ignore(template._name) to_include = [] - if template._name == 'account.tax.template': - to_include = self.tax_field_ids.mapped('name') - elif template._name == 'account.account.template': - to_include = self.account_field_ids.mapped('name') - elif template._name == 'account.fiscal.position.template': - to_include = self.fp_field_ids.mapped('name') + if template._name == "account.tax.template": + to_include = self.tax_field_ids.mapped("name") + elif template._name == "account.account.template": + to_include = self.account_field_ids.mapped("name") + elif template._name == "account.fiscal.position.template": + to_include = self.fp_field_ids.mapped("name") for key, field in template._fields.items(): if key in ignore or key not in to_include: continue @@ -559,10 +611,9 @@ class WizardUpdateChartsAccounts(models.TransientModel): if t: find = getattr( self, - "find_%s%s_by_templates" % ( - "fp_" if ".fiscal.position" in relation - else "", - t)) + "find_%s%s_by_templates" + % ("fp_" if ".fiscal.position" in relation else "", t), + ) if ".fiscal.position" in relation: # Special case: if something is returned, then # there's any difference, so it will get non equal @@ -579,9 +630,8 @@ class WizardUpdateChartsAccounts(models.TransientModel): result[key] = expected else: template_value = template[key] - if template._name == "account.account.template" \ - and key == 'code': - template_value = self.padded_code(template['code']) + if template._name == "account.account.template" and key == "code": + template_value = self.padded_code(template["code"]) if template_value != real[key]: result[key] = template_value # Avoid to cache recordset references @@ -609,11 +659,12 @@ class WizardUpdateChartsAccounts(models.TransientModel): result = list() different_fields = sorted( template._fields[f].get_description(self.env)["string"] - for f in self.diff_fields(template, real).keys()) + for f in self.diff_fields(template, real).keys() + ) if different_fields: result.append( - _("Differences in these fields: %s.") % - ", ".join(different_fields)) + _("Differences in these fields: %s.") % ", ".join(different_fields) + ) # Special for taxes if template._name == "account.tax.template": if not real.active: @@ -621,11 +672,13 @@ class WizardUpdateChartsAccounts(models.TransientModel): return "\n".join(result) def missing_xml_id(self, real_obj): - return not self.env['ir.model.data'].search([ - ('res_id', '=', real_obj.id), - ('model', '=', real_obj._name), - ('module', '!=', '__export__'), - ]) + return not self.env["ir.model.data"].search( + [ + ("res_id", "=", real_obj.id), + ("model", "=", real_obj._name), + ("module", "!=", "__export__"), + ] + ) @api.multi def _find_taxes(self): @@ -633,22 +686,25 @@ class WizardUpdateChartsAccounts(models.TransientModel): found_taxes_ids = [] self.tax_ids.unlink() # Search for changes between template and real tax - for template in self.chart_template_ids.\ - with_context(active_test=False).mapped("tax_template_ids"): + for template in self.chart_template_ids.with_context(active_test=False).mapped( + "tax_template_ids" + ): # Check if the template matches a real tax tax_id = self.find_tax_by_templates(template) if not tax_id: # Tax to be created - self.tax_ids.create({ - 'tax_id': template.id, - 'update_chart_wizard_id': self.id, - 'type': 'new', - 'notes': _('Name or description not found.'), - }) + self.tax_ids.create( + { + "tax_id": template.id, + "update_chart_wizard_id": self.id, + "type": "new", + "notes": _("Name or description not found."), + } + ) else: found_taxes_ids.append(tax_id) # Check the tax for changes - tax = self.env['account.tax'].browse(tax_id) + tax = self.env["account.tax"].browse(tax_id) notes = self.diff_notes(template, tax) if self.recreate_xml_ids and self.missing_xml_id(tax): @@ -656,26 +712,33 @@ class WizardUpdateChartsAccounts(models.TransientModel): if notes: # Tax to be updated - self.tax_ids.create({ - 'tax_id': template.id, - 'update_chart_wizard_id': self.id, - 'type': 'updated', - 'update_tax_id': tax_id, - 'notes': notes, - }) + self.tax_ids.create( + { + "tax_id": template.id, + "update_chart_wizard_id": self.id, + "type": "updated", + "update_tax_id": tax_id, + "notes": notes, + } + ) # search for taxes not in the template and propose them for # deactivation - taxes_to_deactivate = self.env['account.tax'].search( - [('company_id', '=', self.company_id.id), - ("id", "not in", found_taxes_ids), - ("active", "=", True)]) + taxes_to_deactivate = self.env["account.tax"].search( + [ + ("company_id", "=", self.company_id.id), + ("id", "not in", found_taxes_ids), + ("active", "=", True), + ] + ) for tax in taxes_to_deactivate: - self.tax_ids.create({ - 'update_chart_wizard_id': self.id, - 'type': 'deleted', - 'update_tax_id': tax.id, - 'notes': _("To deactivate: not in the template"), - }) + self.tax_ids.create( + { + "update_chart_wizard_id": self.id, + "type": "deleted", + "update_tax_id": tax.id, + "notes": _("To deactivate: not in the template"), + } + ) @api.multi def _find_accounts(self): @@ -686,15 +749,17 @@ class WizardUpdateChartsAccounts(models.TransientModel): account_id = self.find_account_by_templates(template) if not account_id: # Account to be created - self.account_ids.create({ - 'account_id': template.id, - 'update_chart_wizard_id': self.id, - 'type': 'new', - 'notes': _('No account found with this code.'), - }) + self.account_ids.create( + { + "account_id": template.id, + "update_chart_wizard_id": self.id, + "type": "new", + "notes": _("No account found with this code."), + } + ) else: # Check the account for changes - account = self.env['account.account'].browse(account_id) + account = self.env["account.account"].browse(account_id) notes = self.diff_notes(template, account) if self.recreate_xml_ids and self.missing_xml_id(account): @@ -702,37 +767,42 @@ class WizardUpdateChartsAccounts(models.TransientModel): if notes: # Account to be updated - self.account_ids.create({ - 'account_id': template.id, - 'update_chart_wizard_id': self.id, - 'type': 'updated', - 'update_account_id': account_id, - 'notes': notes, - }) + self.account_ids.create( + { + "account_id": template.id, + "update_chart_wizard_id": self.id, + "type": "updated", + "update_account_id": account_id, + "notes": notes, + } + ) @api.multi def _find_fiscal_positions(self): """Load fiscal position templates to create/update.""" - wiz_fp = self.env['wizard.update.charts.accounts.fiscal.position'] + wiz_fp = self.env["wizard.update.charts.accounts.fiscal.position"] self.fiscal_position_ids.unlink() # Search for new / updated fiscal positions - templates = self.env['account.fiscal.position.template'].search( - [('chart_template_id', 'in', self.chart_template_ids.ids)]) + templates = self.env["account.fiscal.position.template"].search( + [("chart_template_id", "in", self.chart_template_ids.ids)] + ) for template in templates: # Search for a real fiscal position that matches the template fp_id = self.find_fp_by_templates(template) if not fp_id: # Fiscal position to be created - wiz_fp.create({ - 'fiscal_position_id': template.id, - 'update_chart_wizard_id': self.id, - 'type': 'new', - 'notes': _('No fiscal position found with this name.') - }) + wiz_fp.create( + { + "fiscal_position_id": template.id, + "update_chart_wizard_id": self.id, + "type": "new", + "notes": _("No fiscal position found with this name."), + } + ) else: # Check the fiscal position for changes - fp = self.env['account.fiscal.position'].browse(fp_id) + fp = self.env["account.fiscal.position"].browse(fp_id) notes = self.diff_notes(template, fp) if self.recreate_xml_ids and self.missing_xml_id(fp): @@ -740,34 +810,36 @@ class WizardUpdateChartsAccounts(models.TransientModel): if notes: # Fiscal position template to be updated - wiz_fp.create({ - 'fiscal_position_id': template.id, - 'update_chart_wizard_id': self.id, - 'type': 'updated', - 'update_fiscal_position_id': fp_id, - 'notes': notes, - }) + wiz_fp.create( + { + "fiscal_position_id": template.id, + "update_chart_wizard_id": self.id, + "type": "updated", + "update_fiscal_position_id": fp_id, + "notes": notes, + } + ) def recreate_xml_id(self, template, real_obj): - ir_model_data = self.env['ir.model.data'] - template_xmlid = ir_model_data.search([ - ('model', '=', template._name), - ('res_id', '=', template.id), - ]) + ir_model_data = self.env["ir.model.data"] + template_xmlid = ir_model_data.search( + [("model", "=", template._name), ("res_id", "=", template.id)] + ) new_xml_id = "%d_%s" % (self.company_id.id, template_xmlid.name) - real_xmlid = ir_model_data.search([ - ('model', '=', real_obj._name), - ('res_id', '=', real_obj.id), - ], limit=1) + real_xmlid = ir_model_data.search( + [("model", "=", real_obj._name), ("res_id", "=", real_obj.id)], limit=1 + ) if real_xmlid: real_xmlid.unlink() - template_xmlid.copy({ - 'model': real_obj._name, - 'res_id': real_obj.id, - 'name': new_xml_id, - 'noupdate': True, - }) + template_xmlid.copy( + { + "model": real_obj._name, + "res_id": real_obj.id, + "name": new_xml_id, + "noupdate": True, + } + ) @api.multi def _update_taxes(self): @@ -775,61 +847,61 @@ class WizardUpdateChartsAccounts(models.TransientModel): for wiz_tax in self.tax_ids: template, tax = wiz_tax.tax_id, wiz_tax.update_tax_id # Deactivate tax - if wiz_tax.type == 'deleted': + if wiz_tax.type == "deleted": tax.active = False _logger.info(_("Deactivated tax %s."), "'%s'" % tax.name) continue # Create tax - if wiz_tax.type == 'new': + if wiz_tax.type == "new": template._generate_tax(self.company_id) _logger.info(_("Created tax %s."), "'%s'" % template.name) # Update tax else: for key, value in self.diff_fields(template, tax).items(): # We defer update because account might not be created yet - if key in {'account_id', 'refund_account_id'}: + if key in {"account_id", "refund_account_id"}: continue tax[key] = value _logger.info(_("Updated tax %s."), "'%s'" % template.name) if self.recreate_xml_ids and self.missing_xml_id(tax): self.recreate_xml_id(template, tax) - _logger.info(_("Updated tax %s. (Recreated XML-IDs)"), - "'%s'" % template.name) + _logger.info( + _("Updated tax %s. (Recreated XML-IDs)"), "'%s'" % template.name + ) @api.multi def _update_accounts(self): """Process accounts to create/update.""" for wiz_account in self.account_ids: - account, template = (wiz_account.update_account_id, - wiz_account.account_id) - if wiz_account.type == 'new': + account, template = (wiz_account.update_account_id, wiz_account.account_id) + if wiz_account.type == "new": # Create the account tax_template_ref = { - tax.id: self.find_tax_by_templates(tax) for tax in - template.tax_ids + tax.id: self.find_tax_by_templates(tax) for tax in template.tax_ids } vals = self.chart_template_id._get_account_vals( - self.company_id, template, + self.company_id, + template, self.padded_code(template.code), tax_template_ref, ) try: with self.env.cr.savepoint(): self.chart_template_id.create_record_with_xmlid( - self.company_id, template, 'account.account', vals, + self.company_id, template, "account.account", vals ) _logger.info( _("Created account %s."), - "'%s - %s'" % (vals['code'], vals['name']), + "'{} - {}'".format(vals["code"], vals["name"]), ) except Exception: self.rejected_new_account_number += 1 - if config['test_enable']: + if config["test_enable"]: _logger.info(EXCEPTION_TEXT) else: # pragma: no cover _logger.exception( "ERROR: " + _("Exception creating account %s."), - "'%s - %s'" % (template.code, template.name), + "'{} - {}'".format(template.code, template.name), ) if not self.continue_on_errors: break @@ -837,29 +909,29 @@ class WizardUpdateChartsAccounts(models.TransientModel): # Update the account try: with self.env.cr.savepoint(): - for key, value in (iter(self.diff_fields( - template, account).items())): + for key, value in iter( + self.diff_fields(template, account).items() + ): account[key] = value _logger.info( _("Updated account %s."), - "'%s - %s'" % (account.code, account.name), + "'{} - {}'".format(account.code, account.name), ) - if self.recreate_xml_ids \ - and self.missing_xml_id(account): + if self.recreate_xml_ids and self.missing_xml_id(account): self.recreate_xml_id(template, account) _logger.info( _("Updated account %s. (Recreated XML-ID)"), - "'%s - %s'" % (account.code, account.name), + "'{} - {}'".format(account.code, account.name), ) except Exception: self.rejected_updated_account_number += 1 - if config['test_enable']: + if config["test_enable"]: _logger.info(EXCEPTION_TEXT) else: # pragma: no cover _logger.exception( "ERROR: " + _("Exception writing account %s."), - "'%s - %s'" % (account.code, account.name), + "'{} - {}'".format(account.code, account.name), ) if not self.continue_on_errors: break @@ -877,7 +949,7 @@ class WizardUpdateChartsAccounts(models.TransientModel): tax = wiz_tax.update_tax_id done = False for key, value in self.diff_fields(template, tax).items(): - if key in {'account_id', 'refund_account_id'}: + if key in {"account_id", "refund_account_id"}: tax[key] = value done = True if done: @@ -888,50 +960,53 @@ class WizardUpdateChartsAccounts(models.TransientModel): tax_mapping = [] for fp_tax in fp_template.tax_ids: # Create the fp tax mapping - tax_mapping.append({ - 'tax_src_id': self.find_tax_by_templates(fp_tax.tax_src_id), - 'tax_dest_id': self.find_tax_by_templates(fp_tax.tax_dest_id), - }) + tax_mapping.append( + { + "tax_src_id": self.find_tax_by_templates(fp_tax.tax_src_id), + "tax_dest_id": self.find_tax_by_templates(fp_tax.tax_dest_id), + } + ) # Account mappings account_mapping = [] for fp_account in fp_template.account_ids: # Create the fp account mapping - account_mapping.append({ - 'account_src_id': ( - self.find_account_by_templates(fp_account.account_src_id) - ), - 'account_dest_id': ( - self.find_account_by_templates(fp_account.account_dest_id) - ), - }) + account_mapping.append( + { + "account_src_id": ( + self.find_account_by_templates(fp_account.account_src_id) + ), + "account_dest_id": ( + self.find_account_by_templates(fp_account.account_dest_id) + ), + } + ) return { - 'company_id': self.company_id.id, - 'name': fp_template.name, - 'tax_ids': [(0, 0, x) for x in tax_mapping], - 'account_ids': [(0, 0, x) for x in account_mapping], + "company_id": self.company_id.id, + "name": fp_template.name, + "tax_ids": [(0, 0, x) for x in tax_mapping], + "account_ids": [(0, 0, x) for x in account_mapping], } @api.multi def _update_fiscal_positions(self): """Process fiscal position templates to create/update.""" for wiz_fp in self.fiscal_position_ids: - fp, template = (wiz_fp.update_fiscal_position_id, - wiz_fp.fiscal_position_id) - if wiz_fp.type == 'new': + fp, template = (wiz_fp.update_fiscal_position_id, wiz_fp.fiscal_position_id) + if wiz_fp.type == "new": # Create a new fiscal position self.chart_template_id.create_record_with_xmlid( - self.company_id, template, 'account.fiscal.position', + self.company_id, + template, + "account.fiscal.position", self._prepare_fp_vals(template), ) - _logger.info( - _("Created fiscal position %s."), - "'%s'" % template.name, - ) + _logger.info(_("Created fiscal position %s."), "'%s'" % template.name) else: for key, value in self.diff_fields(template, fp).items(): fp[key] = value - _logger.info(_("Updated fiscal position %s."), - "'%s'" % template.name) + _logger.info( + _("Updated fiscal position %s."), "'%s'" % template.name + ) if self.recreate_xml_ids and self.missing_xml_id(fp): self.recreate_xml_id(template, fp) @@ -942,104 +1017,125 @@ class WizardUpdateChartsAccounts(models.TransientModel): class WizardUpdateChartsAccountsTax(models.TransientModel): - _name = 'wizard.update.charts.accounts.tax' - _description = ("Tax that needs to be updated (new or updated in the " - "template).") + _name = "wizard.update.charts.accounts.tax" + _description = "Tax that needs to be updated (new or updated in the " "template)." tax_id = fields.Many2one( - comodel_name='account.tax.template', string='Tax template', - ondelete='set null') + comodel_name="account.tax.template", string="Tax template", ondelete="set null" + ) update_chart_wizard_id = fields.Many2one( - comodel_name='wizard.update.charts.accounts', - string='Update chart wizard', required=True, ondelete='cascade') + comodel_name="wizard.update.charts.accounts", + string="Update chart wizard", + required=True, + ondelete="cascade", + ) type = fields.Selection( - selection=[('new', 'New template'), - ('updated', 'Updated template'), - ('deleted', 'Tax to deactivate')], - string='Type', - readonly=True) - type_tax_use = fields.Selection( - related="tax_id.type_tax_use", - readonly=True) + selection=[ + ("new", "New template"), + ("updated", "Updated template"), + ("deleted", "Tax to deactivate"), + ], + string="Type", + readonly=True, + ) + type_tax_use = fields.Selection(related="tax_id.type_tax_use", readonly=True) update_tax_id = fields.Many2one( - comodel_name='account.tax', string='Tax to update', required=False, - ondelete='set null') - notes = fields.Text('Notes', readonly=True) + comodel_name="account.tax", + string="Tax to update", + required=False, + ondelete="set null", + ) + notes = fields.Text("Notes", readonly=True) class WizardUpdateChartsAccountsAccount(models.TransientModel): - _name = 'wizard.update.charts.accounts.account' - _description = ("Account that needs to be updated (new or updated in the " - "template).") + _name = "wizard.update.charts.accounts.account" + _description = ( + "Account that needs to be updated (new or updated in the " "template)." + ) account_id = fields.Many2one( - comodel_name='account.account.template', string='Account template', - required=True, ondelete='set null') + comodel_name="account.account.template", + string="Account template", + required=True, + ondelete="set null", + ) update_chart_wizard_id = fields.Many2one( - comodel_name='wizard.update.charts.accounts', - string='Update chart wizard', required=True, ondelete='cascade' + comodel_name="wizard.update.charts.accounts", + string="Update chart wizard", + required=True, + ondelete="cascade", ) type = fields.Selection( - selection=[('new', 'New template'), - ('updated', 'Updated template')], - string='Type', - readonly=True) + selection=[("new", "New template"), ("updated", "Updated template")], + string="Type", + readonly=True, + ) update_account_id = fields.Many2one( - comodel_name='account.account', string='Account to update', - required=False, ondelete='set null') - notes = fields.Text('Notes', readonly=True) + comodel_name="account.account", + string="Account to update", + required=False, + ondelete="set null", + ) + notes = fields.Text("Notes", readonly=True) class WizardUpdateChartsAccountsFiscalPosition(models.TransientModel): - _name = 'wizard.update.charts.accounts.fiscal.position' - _description = ("Fiscal position that needs to be updated (new or updated " - "in the template).") + _name = "wizard.update.charts.accounts.fiscal.position" + _description = ( + "Fiscal position that needs to be updated (new or updated " "in the template)." + ) fiscal_position_id = fields.Many2one( - comodel_name='account.fiscal.position.template', - string='Fiscal position template', required=True, ondelete='set null') + comodel_name="account.fiscal.position.template", + string="Fiscal position template", + required=True, + ondelete="set null", + ) update_chart_wizard_id = fields.Many2one( - comodel_name='wizard.update.charts.accounts', - string='Update chart wizard', required=True, ondelete='cascade') + comodel_name="wizard.update.charts.accounts", + string="Update chart wizard", + required=True, + ondelete="cascade", + ) type = fields.Selection( - selection=[('new', 'New template'), - ('updated', 'Updated template')], - string='Type', readonly=True, required=True, + selection=[("new", "New template"), ("updated", "Updated template")], + string="Type", + readonly=True, + required=True, ) update_fiscal_position_id = fields.Many2one( - comodel_name='account.fiscal.position', required=False, - string='Fiscal position to update', ondelete='set null') - notes = fields.Text('Notes', readonly=True) + comodel_name="account.fiscal.position", + required=False, + string="Fiscal position to update", + ondelete="set null", + ) + notes = fields.Text("Notes", readonly=True) class WizardMatching(models.TransientModel): - _name = 'wizard.matching' - _description = 'Wizard Matching' - _order = 'sequence' + _name = "wizard.matching" + _description = "Wizard Matching" + _order = "sequence" update_chart_wizard_id = fields.Many2one( - comodel_name='wizard.update.charts.accounts', - string='Update chart wizard', + comodel_name="wizard.update.charts.accounts", + string="Update chart wizard", required=True, - ondelete='cascade', - ) - sequence = fields.Integer( - required=True, - default=1, - ) - matching_value = fields.Selection( - selection="_get_matching_selection", + ondelete="cascade", ) + sequence = fields.Integer(required=True, default=1) + matching_value = fields.Selection(selection="_get_matching_selection") def _get_matching_selection(self): - return [('xml_id', 'XML-ID')] + return [("xml_id", "XML-ID")] def _selection_from_files(self, model_name, field_opts): result = [] for opt in field_opts: model = self.env[model_name] desc = model._fields[opt].get_description(self.env)["string"] - result.append((opt, "%s (%s)" % (desc, opt))) + result.append((opt, "{} ({})".format(desc, opt))) return result @@ -1049,8 +1145,9 @@ class WizardTaxMatching(models.TransientModel): def _get_matching_selection(self): vals = super(WizardTaxMatching, self)._get_matching_selection() - vals += self._selection_from_files('account.tax.template', - ['description', 'name']) + vals += self._selection_from_files( + "account.tax.template", ["description", "name"] + ) return vals @@ -1060,17 +1157,15 @@ class WizardAccountMatching(models.TransientModel): def _get_matching_selection(self): vals = super(WizardAccountMatching, self)._get_matching_selection() - vals += self._selection_from_files('account.account.template', - ['code', 'name']) + vals += self._selection_from_files("account.account.template", ["code", "name"]) return vals class WizardFpMatching(models.TransientModel): - _name = 'wizard.fp.matching' + _name = "wizard.fp.matching" _inherit = "wizard.matching" def _get_matching_selection(self): vals = super(WizardFpMatching, self)._get_matching_selection() - vals += self._selection_from_files('account.fiscal.position.template', - ['name']) + vals += self._selection_from_files("account.fiscal.position.template", ["name"]) return vals