From 6a8fcab936319ddfc93c70b548b5661eafcd69fb Mon Sep 17 00:00:00 2001 From: Suherdy Yacob Date: Tue, 28 Apr 2026 17:58:22 +0700 Subject: [PATCH] feat: implement post-init and uninstall hooks to automatically sync and manage shared bank/cash accounts across company branches --- __init__.py | 43 +++++++++++++++++++++++++++++++++++++++++++ __manifest__.py | 2 ++ 2 files changed, 45 insertions(+) diff --git a/__init__.py b/__init__.py index 0650744..b3c9695 100644 --- a/__init__.py +++ b/__init__.py @@ -1 +1,44 @@ from . import models +from odoo import api, SUPERUSER_ID + +def _auto_share_accounts_post_init(env): + """ + Automatically link accounts from the Parent Company (ID 2 - OT) to any Branch Company + that does not have its own Chart of Accounts. + """ + # Link Parent Company (ID 2) accounts to other companies if they don't have their own COA + env.cr.execute(""" + INSERT INTO account_account_res_company_rel (account_id, company_id) + SELECT a.id, c.id + FROM account_account a + CROSS JOIN res_company c + WHERE a.company_id = 2 + AND c.id != 2 + AND NOT EXISTS ( + SELECT 1 FROM account_account_res_company_rel r + WHERE r.account_id = a.id AND r.company_id = c.id + ) + AND NOT EXISTS ( + SELECT 1 FROM account_account a2 + WHERE a2.company_id = c.id + ) + ON CONFLICT DO NOTHING + """) + + # Set a dummy chart template for branches to satisfy Odoo 19 POS validation + env.cr.execute(""" + UPDATE res_company + SET chart_template = 'id' + WHERE id != 2 AND chart_template IS NULL + """) + +def _cleanup_shared_accounts_uninstall(env): + """ + Remove the shared account relations upon uninstallation to prevent + UserErrors when Odoo's standard company consistency checks are restored. + """ + env.cr.execute(""" + DELETE FROM account_account_res_company_rel + WHERE company_id != 2 + AND account_id IN (SELECT id FROM account_account WHERE company_id = 2) + """) diff --git a/__manifest__.py b/__manifest__.py index 4b177e1..0a85ca3 100644 --- a/__manifest__.py +++ b/__manifest__.py @@ -15,4 +15,6 @@ This module removes the standard restriction that prevents Chart of Accounts (CO 'installable': True, 'application': False, 'license': 'LGPL-3', + 'post_init_hook': '_auto_share_accounts_post_init', + 'uninstall_hook': '_cleanup_shared_accounts_uninstall', }