From a9a0826f540d9af36d861fb27f3d6afcb53918b7 Mon Sep 17 00:00:00 2001 From: Ricardoalso Date: Mon, 6 Jan 2025 15:53:02 +0100 Subject: [PATCH] account_invoice_refund_link: translate post_init_hook into SQL --- account_invoice_refund_link/hooks.py | 72 +++++++++++++++++----------- 1 file changed, 45 insertions(+), 27 deletions(-) diff --git a/account_invoice_refund_link/hooks.py b/account_invoice_refund_link/hooks.py index 1d5c7837bba..062ebf04133 100644 --- a/account_invoice_refund_link/hooks.py +++ b/account_invoice_refund_link/hooks.py @@ -5,34 +5,52 @@ from odoo import SUPERUSER_ID, api -def match_origin_lines(refund): - """Try to match lines by product or by description.""" - invoice = refund.reversed_entry_id - invoice_lines = invoice.invoice_line_ids - for refund_line in refund.invoice_line_ids: - for invoice_line in invoice_lines: - match = ( - refund_line.product_id - and refund_line.product_id == invoice_line.product_id - or refund_line.name == invoice_line.name - ) - if match: - invoice_lines -= invoice_line - refund_line.origin_line_id = invoice_line.id - break - if not invoice_lines: - break - def post_init_hook(cr, registry): with api.Environment.manage(): env = api.Environment(cr, SUPERUSER_ID, {}) - # Linking all refund invoices to its original invoices - refunds = env["account.move"].search( - [ - ("move_type", "in", ("out_refund", "in_refund")), - ("reversed_entry_id", "!=", False), - ] - ) - for refund in refunds: - match_origin_lines(refund) + SQL = """ +WITH refund_lines AS ( + SELECT + aml.id AS refund_line_id, + aml.move_id AS refund_id, + aml.product_id, + aml.name, + am.reversed_entry_id AS invoice_id + FROM + account_move_line aml + JOIN + account_move am ON aml.move_id = am.id + WHERE + am.move_type IN ('out_refund', 'in_refund') + AND am.reversed_entry_id IS NOT NULL +), +matched_lines AS ( + SELECT + rl.refund_line_id, + il.id AS invoice_line_id, + ROW_NUMBER() OVER ( + PARTITION BY rl.refund_line_id + ORDER BY + CASE + WHEN rl.product_id = il.product_id THEN 1 + WHEN rl.name = il.name THEN 2 + ELSE 3 + END + ) AS match_priority + FROM + refund_lines rl + JOIN + account_move_line il ON rl.invoice_id = il.move_id + WHERE + (rl.product_id IS NOT NULL AND rl.product_id = il.product_id) + OR rl.name = il.name +) +UPDATE account_move_line aml +SET origin_line_id = ml.invoice_line_id +FROM matched_lines ml +WHERE + aml.id = ml.refund_line_id + AND ml.match_priority = 1; +""" + env.cr.execute(SQL)