"""Shared SQL expressions for line margins — as invoiced vs adjusted. Two margins are reported wherever margin is shown (rule since 1.3.108): * invoiced — `invoice_lines.margin_sek` (ADK field 21, the Visma margin). * adjusted — revenue − `unit_cost_adj_sek` × qty where cost_adjustment.py corrected the line (freight/leasing/non-article/rebate → cost 0, stale kalkylpris → source cost), else the invoiced margin. Same rule as cost_adjustment.adjusted_line_values(). Margin exists only on real ADK rows outside freight: synthetic reconciliation rows carry none, and article 106's stale kalkylpris would poison freight. """ from sqlalchemy import and_, case, func, or_ import models from helpers import FREIGHT_ACCTS L = models.InvoiceLine HAS_MARGIN = and_(L.row_source == "adk", or_(L.account_number.is_(None), L.account_number.notin_(FREIGHT_ACCTS))) IS_COST_ADJ = and_(L.cost_adj_reason.isnot(None), L.unit_cost_adj_sek.isnot(None)) MARGIN_EXPR = case((HAS_MARGIN, L.margin_sek), else_=None) MARGIN_ADJ_EXPR = case( (and_(HAS_MARGIN, IS_COST_ADJ), func.coalesce(L.revenue_sek, 0.0) - L.unit_cost_adj_sek * func.coalesce(L.qty, 0.0)), (HAS_MARGIN, L.margin_sek), else_=None, ) MARGIN_SUM = func.coalesce(func.sum(func.coalesce(MARGIN_EXPR, 0.0)), 0.0) MARGIN_ADJ_SUM = func.coalesce(func.sum(func.coalesce(MARGIN_ADJ_EXPR, 0.0)), 0.0) def line_margin_adj(line) -> float: """Python twin of MARGIN_ADJ_EXPR for code that aggregates ORM rows: the invoiced margin, or revenue − corrected unit cost × qty where a correction applies. Callers choose which lines carry margin, as they do for margin_sek.""" if line.cost_adj_reason and line.unit_cost_adj_sek is not None: return (line.revenue_sek or 0.0) - float(line.unit_cost_adj_sek) * (line.qty or 0.0) return line.margin_sek or 0.0 # ── FIFO basis: today's item-master cost ───────────────────────────────────── # The Revenue page's historical "FIFO" margin: revenue − qty × the article's # current unit cost from helpers.get_bom_costs (last purchase price, rolled up # through the BOM). Not the cost at the time of sale — it shows what the sale # would earn at today's cost. A line whose SKU has no item row has no FIFO # cost; aggregates then fall back to its invoice margin, so totals stay whole. def item_fifo_costs(db) -> dict: """{sku: FIFO unit cost} for every item.""" from helpers import get_bom_costs items = db.query(models.Item).all() item_map = {i.sku: i for i in items} memo: dict = {} return {i.sku: get_bom_costs(i, item_map, memo)[1] for i in items} def fifo_margin(costs: dict, sku, revenue, qty, invoice_margin) -> float: """FIFO margin of a line or of one SKU's summed lines.""" if sku and sku in costs: return (revenue or 0.0) - costs[sku] * (qty or 0.0) return invoice_margin or 0.0 def line_margin_fifo(line, costs: dict): """Per-line FIFO margin, or None when the line has no margin or no item.""" if line.sku and line.sku in costs: return (line.revenue_sek or 0.0) - costs[line.sku] * (line.qty or 0.0) return None def fifo_delta_by_invoice(db, costs: dict, invoice_filter) -> dict: """{invoice_number: FIFO margin − invoice margin} over the margin-bearing lines whose SKU has an item cost. Invoice-level FIFO is the header margin plus this delta — the way the adjusted header margin is built.""" rows = ( db.query(L.invoice_number, L.sku, func.coalesce(func.sum(L.revenue_sek), 0.0), func.coalesce(func.sum(L.qty), 0.0), func.coalesce(func.sum(L.margin_sek), 0.0)) .filter(HAS_MARGIN, L.sku.isnot(None), invoice_filter) .group_by(L.invoice_number, L.sku) .all() ) out: dict = {} for inv, sku, rev, qty, mar in rows: if sku in costs: out[inv] = out.get(inv, 0.0) + (rev - costs[sku] * qty) - mar return out