Spaces:
Running

File size: 4,081 Bytes
d1fa6aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
"""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