Skip to content

Commit

Permalink
account_invoice_refund_link: translate post_init_hook into SQL
Browse files Browse the repository at this point in the history
  • Loading branch information
Ricardoalso committed Jan 6, 2025
1 parent d29f7ab commit a9a0826
Showing 1 changed file with 45 additions and 27 deletions.
72 changes: 45 additions & 27 deletions account_invoice_refund_link/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

0 comments on commit a9a0826

Please sign in to comment.