# 04 — Costing Layer (Technical Digest)

> Source: `files/manufacturing_spec/markdown/04_costing.md`. Lossless digest: every entity, field, rule, enum and formula. Inherits all cross-cutting rules from `00` (frozen snapshots, status state machines, "every actual event posts a GL entry", config-over-code, multi-level recursion, resource abstraction).

The costing layer is the "money" layer: it translates all production operations into financial figures and reveals problems. It has **four components**. The most valuable output is **Variance Analysis**.

---

## 4.1 Component: Costing Method

**Purpose:** Strategic decision on how inventory & production are valued. "Set once; hard to change." Configurable **per item** (field `Item.costing_method`).

### Enum
```
costing_method ∈ { Standard, Actual, Average, FIFO }
```

| Method | Philosophy | Suits |
|---|---|---|
| Standard | Pre-set standard cost; difference between actual and standard = variance | Stable mass production |
| Actual | Real cost computed per order | Job shops |
| Average | Moving average cost | Volatile prices |
| FIFO | Oldest batch issued first | Products with shelf life |

### Formulas
```
Average (moving):  new_avg = (existing_qty × old_cost + new_qty × new_cost) / total_qty
FIFO:              issue at oldest batch prices, in order
```

### Standard cost build-up entity
```
Standard_Cost: {
  std_material_cost,
  std_labor_cost,
  std_overhead_cost,
  std_total_cost,        # = sum of the three above
  last_updated,
  update_frequency
}
```

### Generic-design rule — MIXED METHODS (mandatory)
The system MUST support **mixed methods across items**, not one global method:
- Standard for finished products → enables variances + stable inventory valuation.
- Average for volatile raw materials.
- Per-item `costing_method` field is the branch point.

### Melamine test case
- Powder (volatile price) → `Average`.
- Dishes (finished good) → `Standard`.

---

## 4.2 Component: Cost Elements

**Purpose:** Total product cost decomposes into three elements, each with its own source and calculation.

```
Total Cost = Direct Material + Direct Labor + Manufacturing Overhead
```

### Element 1 — Direct Material
```
Direct Material = Σ( BOM_qty × material_price )
source: BOM (quantities) + Material Master (price per the item's costing_method)
GL POST: Debit WIP / Credit Raw Materials
```

### Element 2 — Direct Labor (generalized by `labor_calc` enum)
```
labor_calc ∈ { Hourly, PieceRate }
Hourly:     labor_cost = labor_hours × labor_rate
PieceRate:  labor_cost = quantity × piece_rate
GL POST: Debit WIP / Credit Labor Applied
```
**Critical classification rule:** Only labor whose **pay varies with output** is Direct Labor. Fixed-salary workers (even if standing on the production line) → Overhead.
> Test: "Does this person's pay change with production volume?" Yes → Direct Labor. No → Overhead.

### Element 3 — Manufacturing Overhead (MOH)
```
overhead_rate = total_annual_overhead / total_annual_cost_driver
cost_driver ∈ { LaborHours, MachineHours, DirectMaterialCost, UnitsProduced }
GL POST (at confirmation): Debit WIP / Credit MOH Applied
month-end reconciliation: applied OH vs actual OH → over-applied / under-applied → P&L
```
**Overhead types:**
- Variable OH — electricity, consumables.
- Fixed OH — rent, depreciation, salaries.
- Semi-variable OH — maintenance.

### Generic-design rules
- **Negligible consumables → overhead pool**, NOT BOM lines (e.g. sprayed glaze, tape). (Mirrors `00` rule: tiny-quantity materials treated as overhead consumable, not a BOM line.)
- **Usage-based depreciation for tools** — depreciate by cycles/usage, not by calendar. Only running/mounted tools wear. Depreciation is allocated **per piece per its specific tool**, so expensive/large items carry proportionally more depreciation cost.

### Melamine cost model (illustrative decomposition)
```
piece cost = material (powder + decor if printed)   [direct, varies per unit]
           + press labor (piece_rate)               [direct, varies per unit]
           + everything else (overhead rate)        [fixed pool]
           + that shape's mold depreciation         [usage-based, per tool]
Only material & press-labor vary per piece; all else is overhead.
```

---

## 4.3 Component: Cost Center

**Purpose:** Accounting unit that accumulates costs for a part of the plant. Enables statements like "pressing cost = X, assembly cost = Y."

### Entity
```
Cost_Center: {
  cc_id,
  type ∈ { Production, Service, Auxiliary },
  parent_cc,           # hierarchical / nestable
  manager_id,
  budget_amount,
  actual_amount,
  status
}
```

### Allocation methods (service cost centers → production cost centers)
```
Direct:      service → production only (ignores service-to-service)
Step-Down:   service → other services + production, sequentially (one-directional cascade)
Reciprocal:  all services allocate mutually + to production (handles two-way dependencies)
```

### Generic-design rule
Service costs allocate **by cause**, not evenly. Maintenance of presses → allocate mainly to the pressing center, not split equally (assembly should not bear press maintenance).

### Melamine test case
```
Maintenance 8000, Direct method:
  CC-PRESS    90% → 7200
  CC-FINISH   10% → 800
  CC-ASSEMBLY  0% → 0   (no presses)
```

---

## 4.4 Component: Variance Analysis (THE key output)

**Purpose:** Reveals production problems. `Variance = actual − standard`. The total variance is useless alone; the value is in **decomposition** — each variance type points to a specific problem and a specific owner.

### The seven variances (formulas + owner)
```
1. Material Price Variance    MPV  = (actual_price − std_price) × actual_qty        → Purchasing
2. Material Usage Variance    MUV  = (actual_qty − std_qty)   × std_price           → Production (waste)
3. Labor Rate Variance        LRV  = (actual_rate − std_rate) × actual_hours        → (n/a if piece-rate)
4. Labor Efficiency Variance  LEV  = (actual_hours − std_hours) × std_rate          → Production
5. Variable OH Spending Var.  VOSV = actual_var_OH − (actual_hours × std_VOH_rate)  → Management
6. Variable OH Efficiency Var.VOEV = (actual_hours − std_hours) × std_VOH_rate
7. Fixed OH Volume Variance   FOVV = (actual_production − budgeted) × std_fixed_OH_per_unit
```

### Generic-design rules
- Under **PieceRate**, traditional LRV/LEV do NOT apply (a slow worker only costs himself); the deviation shifts to machine / overhead variances instead.
- **FOVV is critical when fixed costs are large**: lower output spreads fixed cost over fewer units → higher unit cost. This drives the "run at full capacity" management insight.

### Variance tolerance bands
```
< 2%    → Normal — no investigation
2–5%    → Monitor
> 5%    → Investigation Required
```

### Analysis logic (pseudo-code)
```
monthly, for each closed order:
    compute the 7 variances
    for each variance > tolerance:
        classify (material / labor / overhead)
        route to owner
    generate Pareto report (biggest causes first)
```

### Owner mapping (routing output)
```
Material Price   ↑  → Purchasing
Material Usage   ↑  → Production (waste)
Labor Efficiency ↑  → Production
Overhead         ↑  → Management
Volume Variance     → Sales / Management (output dropped)
```

### Joint-products costing (recap from Execution layer)
```
total_sale_value = Σ( grade.qty × grade.price )
grade.cost       = total_cost × (grade.qty × grade.price) / total_sale_value
```
Cost follows **value**, not an equal split. Grade A (priciest) absorbs the most cost per unit.

---

## WIP accounting & period-end settlement (woven through all components)

Per `00` rule "every actual event posts an accounting entry," costing is woven into execution, not a separate batch:
- **Material issue** → Debit WIP / Credit Raw Materials.
- **Labor confirmation** → Debit WIP / Credit Labor Applied.
- **Overhead application at confirmation** → Debit WIP / Credit MOH Applied (using `overhead_rate`).
- **Goods receipt of finished good** → (implied) Credit WIP / Debit Finished Goods at standard or actual cost.
- **Month-end:** applied OH vs actual OH → over-/under-applied variance posted to P&L; the 7 variances computed per closed order and routed to owners.

---

## Enums / config points introduced or used by this file
```
costing_method ∈ { Standard, Actual, Average, FIFO }          (per item)
labor_calc     ∈ { Hourly, PieceRate }                        (drives Direct Labor calc + LRV/LEV applicability)
cost_driver    ∈ { LaborHours, MachineHours, DirectMaterialCost, UnitsProduced }   (overhead_rate denominator)
cc_type        ∈ { Production, Service, Auxiliary }            (Cost_Center.type)
allocation     ∈ { Direct, Step-Down, Reciprocal }            (service → production allocation)
overhead_type  ∈ { Variable, Fixed, Semi-variable }
tolerance band ∈ { <2% Normal, 2–5% Monitor, >5% Investigate }
```

---

## What this layer EXPECTS FROM THE ERP (integration contract)

1. **GL posting engine** for every event: WIP, Raw Materials, Labor Applied, MOH Applied, Finished Goods, over/under-applied OH, variance accounts. (Moon ERP: `Modules\Accounting\Actions\CreateJournalEntry`.)
2. **Inventory valuation engine** that can value the SAME inventory by different methods per item: Standard, Actual, Average (moving), FIFO. (Moon ERP: `InventoryCostLayer` already supports Average/FIFO layers; Standard/Actual + per-item method selection must be confirmed/added.)
3. **Cost center master** with type, hierarchy (`parent_cc`), manager, budget vs actual, status. (Moon ERP: `Modules\Accounting\Models\CostCenter` exists — must confirm it carries `type`, `parent`, budget/actual, and that JE lines can be tagged with a cost center.)
4. **Material Master price** per costing method (raw-material price the BOM cost calc reads).
5. **BOM quantities** (from Master Data / Production module BOM) for Direct Material.
6. **Routing + confirmation actuals**: actual hours, actual qty, labor rate / piece rate (from Execution / SFC).
7. **Standard cost record** per item: `std_material_cost`, `std_labor_cost`, `std_overhead_cost`, `std_total_cost`, `last_updated`, `update_frequency`.
8. **Fiscal calendar / period close** to drive month-end OH reconciliation and per-order variance run. (Moon ERP: `FiscalYear` / `FiscalPeriod`, events `PeriodClosed` / `FiscalYearClosed`.)
9. **Tool/Mold registry** with per-cycle usage counters to drive usage-based depreciation per piece per tool.
10. **Joint-product grade data** (grade.qty, grade.price) from Execution to allocate cost by value.
11. **Budget data** per cost center and budgeted production volume (for FOVV and cost-center variance).
