From bad40665ec0e92f20574dc659ab583de2f0c3e04 Mon Sep 17 00:00:00 2001 From: Daniel Reis Date: Sat, 6 Apr 2024 15:18:31 +0100 Subject: [PATCH 1/2] [FIX] account_invoice_margin: wrong default margin calculation When installing the module, the Invoice total margin initial calculation was including all AML lines, including taxes. This resulted in a margin of more than 100%. --- account_invoice_margin/hooks.py | 1 + 1 file changed, 1 insertion(+) diff --git a/account_invoice_margin/hooks.py b/account_invoice_margin/hooks.py index 4c50a742..edebcaae 100644 --- a/account_invoice_margin/hooks.py +++ b/account_invoice_margin/hooks.py @@ -43,6 +43,7 @@ def pre_init_hook(cr): FROM account_move_line INNER JOIN account_move ON account_move.id = account_move_line.move_id + WHERE account_move_line.exclude_from_invoice_tab = false GROUP BY account_move_line.move_id ) UPDATE account_move From e91d51f0e791119c307034ae8708249a244b254d Mon Sep 17 00:00:00 2001 From: Daniel Reis Date: Sat, 6 Apr 2024 22:07:54 +0100 Subject: [PATCH 2/2] [IMP] account_invoice_margin: init Invoice margins from SOs if possible --- account_invoice_margin/hooks.py | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/account_invoice_margin/hooks.py b/account_invoice_margin/hooks.py index edebcaae..735533c1 100644 --- a/account_invoice_margin/hooks.py +++ b/account_invoice_margin/hooks.py @@ -33,6 +33,39 @@ def pre_init_hook(cr): AND price_subtotal > 0.0; """ ) + if column_exists(cr, "sale_order_line", "purchase_price"): + # Copy margins from Sale Orders, if possible + _logger.info("Copy margins from Sale Orders to Invoices...") + cr.execute( + """ + WITH margins AS ( + SELECT aml.id + , SUM(sol.purchase_price * sol.product_uom_qty) + / SUM(sol.product_uom_qty) as purchase_price_unit + FROM account_move_line aml + INNER JOIN account_move am + ON aml.move_id = am.id + INNER JOIN sale_order_line_invoice_rel rel + ON rel.invoice_line_id = aml.id + INNER JOIN sale_order_line sol + ON rel.order_line_id = sol.id + WHERE am.move_type NOT ILIKE 'in_%' + AND aml.price_subtotal <> 0 + AND sol.product_uom_qty <> 0 + AND sol.purchase_price <> 0 + GROUP BY aml.id + HAVING SUM(sol.purchase_price) <> 0 + ) + UPDATE account_move_line + SET purchase_price = m.purchase_price_unit * quantity + , margin = price_subtotal - (m.purchase_price_unit * quantity) + , margin_signed = price_subtotal - (m.purchase_price_unit * quantity) + , margin_percent = (price_subtotal - (m.purchase_price_unit * quantity)) + / price_subtotal + FROM margins m + WHERE m.id = account_move_line.id ; + """ + ) cr.execute( """ WITH aml AS(