diff --git a/openupgrade_scripts/scripts/l10n_it/18.0.0.9/pre-migration.py b/openupgrade_scripts/scripts/l10n_it/18.0.0.9/pre-migration.py new file mode 100644 index 000000000000..2c3d211c1fce --- /dev/null +++ b/openupgrade_scripts/scripts/l10n_it/18.0.0.9/pre-migration.py @@ -0,0 +1,73 @@ +from openupgradelib import openupgrade + +# List of XML IDs of tax reports defined in l10n_it +# These include the generic VAT report and the annual reports +ITALIAN_REPORT_XML_IDS = [ + "l10n_it.tax_report_vat", + "l10n_it.tax_annual_report_vat_va", + "l10n_it.tax_annual_report_vat_ve", + "l10n_it.tax_annual_report_vat_vf", + "l10n_it.tax_annual_report_vat_vh", + "l10n_it.tax_annual_report_vat_vj", + "l10n_it.tax_annual_report_vat_vl", +] + + +@openupgrade.migrate() +def migrate(env, version): + """ + Remove existing reports and related records to avoid duplications. + """ + if not version: + return + + # Try standard cleanup first, this usually isn't enough + openupgrade.delete_records_safely_by_xml_id( + env, ITALIAN_REPORT_XML_IDS, delete_childs=True + ) + + for xml_id in ITALIAN_REPORT_XML_IDS: + report = env.ref(xml_id, raise_if_not_found=False) + if not report or report._name != "account.report": + continue + + # Explicitly search for linked records + # 1. Report lines + lines = env["account.report.line"].search([("report_id", "=", report.id)]) + + # 2. Expressions linked to lines + expressions = env["account.report.expression"].search( + [("report_line_id", "in", lines.ids)] + ) + + # 3. Report columns + columns = env["account.report.column"].search([("report_id", "=", report.id)]) + + # Delete related records + for record_set in [expressions, lines, columns]: + if record_set: + try: + openupgrade.safe_unlink(record_set, do_raise=True) + except Exception as e: + openupgrade.logger.error( + "Failed to delete %s for report %s: %s", + record_set._name, + xml_id, + repr(e), + ) + + # Delete the report itself + try: + openupgrade.safe_unlink(report, do_raise=True) + except Exception as e: + openupgrade.logger.error("Failed to delete report %s: %s", xml_id, repr(e)) + # Switch to noupdate to avoid future errors if unlink failed + module, name = xml_id.split(".") + imd = env["ir.model.data"].search( + [ + ("module", "=", module), + ("name", "=", name), + ] + ) + if imd and not imd.noupdate: + imd.noupdate = True