| 1 | from collections import defaultdict |
| 2 | |
| 3 | from odoo import api, models, _ |
| 4 | from odoo.exceptions import UserError |
| 5 | |
| 6 | |
| 7 | class AccountAccount(models.Model): |
| 8 | _name = 'account.account' |
| 9 | _inherit = 'account.account' |
| 10 | |
| 11 | @api.ondelete(at_uninstall=False) |
| 12 | def _unlink_bank_cash_accounts(self): |
| 13 | nb_account_to_delete_per_company = defaultdict(self.env['account.account'].browse) |
| 14 | for account in self: |
| 15 | for company in account.company_ids: |
| 16 | if company.country_code == 'DK': |
| 17 | nb_account_to_delete_per_company[company] |= account |
| 18 | |
| 19 | if not nb_account_to_delete_per_company: |
| 20 | return |
| 21 | |
| 22 | grouped_counts = self.read_group( |
| 23 | domain=[('company_ids.account_fiscal_country_id.code', '=', 'DK'), ('account_type', '=', 'asset_cash')], |
| 24 | fields=['company_ids', 'id:count'], |
| 25 | groupby=['company_ids'], |
| 26 | ) |
| 27 | nb_account_per_company = {self.env['res.company'].browse(entry['company_ids'][0]): entry['company_ids_count'] for entry in grouped_counts} |
| 28 | |
| 29 | for company_id, count in nb_account_per_company.items(): |
| 30 | nb_to_delete = sum(1 for account in nb_account_to_delete_per_company.get(company_id) if account.account_type == 'asset_cash') |
| 31 | if count - nb_to_delete < 1: |
| 32 | raise UserError(_("You must keep at least one bank and cash account for %(company)s!", company=company_id.name)) |