Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[IMP] account_invoice_margin: init Invoice margins from SOs if possible #202

Merged
merged 2 commits into from
Aug 23, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions account_invoice_margin/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -43,6 +76,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
Expand Down
Loading