# API Contract Base URL: `http://127.0.0.1:8000` Interactive docs: `http://127.0.0.1:8000/docs` --- ## Inventory Management | Endpoint | Method | Description | | :--- | :--- | :--- | | `/api/items` | GET | Paginated, filtered, sortable item list | | `/api/items` | POST | Create new item | | `/api/items/count` | GET | Count items matching filters (use before paginating) | | `/api/items/search` | GET | Autocomplete search across SKU, name, description, supplier | | `/api/items/{item_id}` | GET | Single item with BOM cost enrichment | | `/api/items/{item_id}` | PUT | Update item fields | | `/api/items/by-sku/{sku}` | GET | Fetch item by SKU string (useful for P-items) | ### `GET /api/items` | Param | Type | Default | Description | | :--- | :--- | :--- | :--- | | `skip` | int | `0` | Pagination offset | | `limit` | int | `10` | Page size | | `view` | string | — | `all`, `components`, `in_stock`, `boms` | | `search` | string | — | Text search | | `category` | string | — | Filter by Article Group | | `sort_by` | string | `name` | `name`, `sku`, `stock_quantity`, `average_price` | | `sort_order` | string | `asc` | `asc` or `desc` | | `clean_view` | bool | `true` | Hide zero-cost and unused items | Response: `List[ItemSchema]` ### `GET /api/items/count` | Param | Type | Description | | :--- | :--- | :--- | | `view` | string | Same filters as `/api/items` | | `search` | string | | | `category` | string | | | `clean_view` | bool | | Response: `{"count": int}` ### `GET /api/items/search` | Param | Type | Default | Description | | :--- | :--- | :--- | :--- | | `q` | string | required | Min 1 char | | `view` | string | — | `all`, `components`, `in_stock`, `boms` | | `item_type` | string | — | `RAW` or `BOM` | | `category` | string | — | | | `in_stock` | bool | — | | | `limit` | int | `10` | Max 50 | Response: `[{id, sku, name, type, category, stock_quantity}]` --- ## Stock Movements | Endpoint | Method | Description | | :--- | :--- | :--- | | `/api/items/{item_id}/movement` | POST | Record stock in/out with cost tracking | Body (`StockMovement`): ```json { "quantity_change": float, "unit_price": float | null, "supplier": "string | null", "author": "string" } ``` Response: `ItemSchema` --- ## Audit Logs | Endpoint | Method | Description | | :--- | :--- | :--- | | `/api/items/{item_id}/history` | GET | Event log for a specific item | | `/api/events` | GET | Global activity stream | ### `GET /api/items/{item_id}/history` | Param | Default | | | :--- | :--- | :--- | | `skip` | `0` | | | `limit` | `10` | | ### `GET /api/events` | Param | Default | | | :--- | :--- | :--- | | `skip` | `0` | | | `limit` | `50` | | | `action` | — | Filter by action type | Response: `List[EventLogSchema]` --- ## Customers | Endpoint | Method | Description | | :--- | :--- | :--- | | `/api/customers/search` | GET | Search customers; merges by name when multiple IDs share a name | | Param | Default | | | :--- | :--- | :--- | | `q` | required | Min 1 char | | `limit` | `15` | | Response: `[{id, name, code_count}]` `code_count > 1` means multiple Visma customer IDs were merged under this name. --- ## Exchange Rates | Endpoint | Method | Description | | :--- | :--- | :--- | | `/api/exchange-rates` | GET | Returns live SEK-based rates; cached in DB once per calendar day | ### `GET /api/exchange-rates` No query parameters. Response: ```json { "rates": { "SEK": 1.0, "EUR": float, "USD": float }, "updated_at": "ISO 8601 datetime string", "source": "cache" | "live" | "fallback" } ``` **Behavior:** - On first call of the day, fetches live rates from `open.er-api.com/v6/latest/SEK` and persists to `ExchangeRateCache` (id=1, single-row upsert). - On subsequent calls the same calendar day, returns the cached row. - If the external API is unreachable, falls back silently to hardcoded rates (`EUR: 0.088, USD: 0.095`) and labels `source` as `"fallback"`. - Timeout on outbound HTTP: 5 seconds. --- ## Dashboard | Endpoint | Method | Description | | :--- | :--- | :--- | | `/api/dashboard/filters` | GET | Available filter dimensions | | `/api/dashboard/analytics` | GET | Full KPI snapshot (inventory, revenue, service/freight) | ### `GET /api/dashboard/filters` Response: ```json { "categories": ["string"], "projects": ["string"], "profit_centres": ["string"], "customers": [{"id": "string", "name": "string"}] } ``` ### `GET /api/dashboard/analytics` | Param | Description | | :--- | :--- | | `period` | `this_month`, `last_month`, `qtd`, `ytd`, `all` | | `start_date` | ISO `YYYY-MM-DD`. Enforced minimum: `2024-01-01` | | `end_date` | ISO `YYYY-MM-DD` | | `sku` | Filter by product SKU | | `category` | Filter by Article Group | | `project` | Filter by Visma project code | | `profit_centre` | Filter by profit centre | | `customer_id` | Filter by customer ID (aggregates all linked sub-IDs sharing the same name) | **Date logic**: `period` takes precedence over `start_date`/`end_date`. Default (no params) = YTD. `MIN_DATE = 2024-01-01` is always enforced regardless of input. Response shape: ```json { "inventory": { "kpis": { "stock_value_sek": float, "zero_cost_articles": int, "negative_disposable": int, "dead_stock_value_sek": float, "dead_component_count": int, "dead_component_value_sek": float, "dead_bom_count": int, "dead_bom_value_sek": float }, "charts": {"composition": [...], "viability": [...]}, "lists": {"capital_lockup": [...], "expensive_boms": [...]} }, "revenue": { "kpis": { "total_revenue_sek": float, "total_margin_visma": float, "total_margin_kalkyl": float, "total_margin_fifo": float, "total_margin_avg": float, "margin_pct": float, "product_invoice_count": int, "avg_order_value": float, "unique_customers": int }, "charts": {"trend": [...], "by_category": [...]}, "rankings": { "top_revenue": [...], "bottom_revenue": [...], "top_margin": [...], "bottom_margin": [...] }, "customers": [...] }, "service_freight": { "kpis": { "freight_revenue_sek": float, "service_revenue_sek": float, "combined_revenue_sek": float, "freight_gap_reconciled": float }, "charts": {"split": [...], "service_cats": [...], "freight_geog": [...]}, "pivots": {"service": {...}} } } ``` --- ## Data Import (background jobs) | Endpoint | Method | Description | | :--- | :--- | :--- | | `/api/import/visma` | POST | Multi-file import: Articles, BOM, Customers | | `/api/import/invoices` | POST | Multi-file import: Invoice Headers, Lines | | `/api/import/csv` | POST | Generic CSV import | | `/api/import/gl` | POST | Chart of accounts + GL voucher rows | | `/api/import/procurement` | POST | MVP 2: suppliers, currency rates, purchase prices, purchase orders, supplier invoices, delivery notes (9 optional files) | | `/api/import/sales-documents` | POST | MVP 2: sales orders + offers (headers and lines) | | `/api/import/stock-movements` | POST | MVP 2: manual deliveries in/out, stock counts | | `/api/import/payments` | POST | MVP 2: customer payments (AR), supplier payments (AP) | | `/api/import/agreements` | POST | MVP 2: agreements (avtal) + projects | | `/api/import/visma-extras` | POST | GL extras: booking years, voucher series, periodiseringar (accrual schedules) | All import endpoints return `{"job_id": ...}` immediately; poll `GET /api/import/jobs/{job_id}`. The MVP 2 endpoints (`backend/routers/import_mvp2.py`) accept the CSVs produced by `visma_unified_extractor.py --mvp2`; form field names are listed in `etl/sync_to_hf.py:BUNDLES`. Each register is a full wipe+insert in one transaction, skipped when its files are byte-identical to a previous run (`processed_files`). Derived at import: SEK amounts (latest Visma rate per currency), `sales_orders.is_internal` (internal production customer), far-future placeholder dates → NULL. Files are rejected if their SHA-256 hash matches a previously imported file (`ProcessedFile` deduplication). ### Required CSV Headers | File | Required Columns | | :--- | :--- | | Articles | `SKU`, `Name`, `Stock_Qty`, `Standard_Price`, `Last_Purchase_Price`, `Min_Order_Qty` | | BOM | `Parent_SKU`, `Child_SKU`, `Qty_Used` | | Customers | `Customer_ID`, `Name`, `Country`, `Currency_Code` | | Invoice Headers | `Invoice_Number`, `Invoice_Date`, `Customer_ID`, `Total_Excl_VAT_FX`, `Currency_Code` | | Invoice Lines | `Invoice_Number`, `SKU`, `Qty_Delivered`, `Revenue_SEK_Final` | ### Job Status Payload `GET /api/import/jobs/{job_id}` (admin only) returns the live state of a background import. Progress used to arrive as Server-Sent Events; polling replaced it because the deployed Space proxies `/api/*` through Next.js, which buffers streamed responses. | Key | Description | | :--- | :--- | | `job_id` | Echo of the id returned by the import endpoint | | `status` | `running` \| `complete` \| `error` | | `steps` | `{step_id: {status, label, current?, total?}}` — per-step progress, drives the modal | | `warnings` | Non-fatal messages collected during the run | | `result` | Import counters (e.g. `articles_added`, `invoices_created`, `lines_imported`); `null` until complete | | `error` | Failure message, `null` otherwise | | `created_at` / `updated_at` | Unix timestamps | Jobs are evicted one hour after they finish (`job_store._TTL_SECONDS`), after which this endpoint returns 404. --- ## Exports All export endpoints return `text/csv` with semicolon (`;`) delimiter and a `Content-Disposition: attachment` header. | Endpoint | Method | Description | | :--- | :--- | :--- | | `/api/export/analytics/bom-costs` | GET | BOM cost export — list or tree mode | | `/api/export/analytics/revenue` | GET | Revenue rankings CSV | | `/api/export/analytics/invoice-lines` | GET | Row-level invoice lines CSV (`scope=products\|service\|freight`) | | `/api/export/analytics/invoices` | GET | One row per invoice — totals, VAT, margin, balance, reconciliation (`period`, `customer_id`, `search`) | | `/api/accounting/summary` | GET | GL breakdown per account for a window (`period` or `start_date`/`end_date`, `account_filter=pure_accruals\|revenue\|all`), income-statement sign; `schedules` block = revenue-side periodiseringar sliced to the window + `posted_sek` reconciliation (1.3.76) | | `/api/export/analytics/accruals` | GET | GL voucher rows behind Accruals · GL Ledger (`account_filter=pure_accruals\|revenue\|all`) | | `/api/export/analytics/freight-costs` | GET | Carrier-cost ledger rows (GL 57xx) with invoiced/cost/net summary — window only | | `/api/export/analytics/inventory` | GET | Capital lock-up CSV | | `/api/export/analytics/customers` | GET | Customer revenue CSV | | `/api/export/analytics/bom-comparison` | GET | BOM vs FIFO cost comparison CSV | | `/api/export/analytics/bom-detail` | GET | Detailed BOM component list CSV | | `/api/export/analytics/suppliers` | GET | Supplier matrix CSV | | `/api/export/analytics/distributors` | GET | Top distributors CSV | | `/api/export/analytics/demand` | GET | Demand volume CSV | | `/api/export/analytics/accessories` | GET | Accessory catalog CSV | | `/api/export/analytics/production/{item_id}` | GET | Production Analytics export — xlsx workbook or flat CSV | ### `GET /api/export/analytics/bom-costs` Unified BOM cost export. Operates in two modes depending on whether `item_id` is supplied. | Param | Type | Default | Description | | :--- | :--- | :--- | :--- | | `item_id` | int | — | If provided: tree-mode export for a single item | | `view` | string | — | Inventory tab filter: `boms`, `components`, `in_stock` | | `search` | string | — | Text search (SKU/name) — same as Inventory page | | `category` | string | — | Category filter | | `clean_view` | bool | `true` | Mirrors the Inventory Clean View toggle | **List mode** (no `item_id`): mirrors the current Inventory & BOMs page filters. Each item emits rows according to the anti-duplication rule (see [Business Logic](business_logic.md)). **Tree mode** (`item_id` provided): expands the full BOM tree for one item. If the item has no direct BOM components, the router attempts to resolve its P-prefix parent (e.g. `P{SKU}`) and expands that instead. The root item is emitted as `cost_source="parent_header"` with `Line_Cost=0`; leaf nodes emit their own costs. **CSV columns:** | Column | Description | | :--- | :--- | | `Level` | Depth in BOM tree (0 = root) | | `Parent_SKU` | SKU of the immediate parent node | | `SKU` | This item's SKU | | `Name` | Item name | | `Type` | `RAW` or `BOM` | | `Category` | Article Group | | `Qty` | Quantity at this level (from parent BOM relationship) | | `Estimated_Total_Cost` | Item's own Kalkylpris (unit cost, unscaled) | | `Line_Cost` | `Estimated_Total_Cost * Qty` for leaf rows; `0` for `parent_header` rows | | `Cost_Source` | `own` (leaf / self-costed item) or `parent_header` (expanded parent placeholder) | | `Path` | Full ancestry path: `"GrandparentSKU > ParentSKU > SKU"` | Filenames: `bom_costs_{date}.csv` (list mode) or `bom_costs_tree_{SKU}_{date}.csv` (tree mode). --- ## Production Analytics Read-only multi-level buildable-units analysis (engine: `backend/production_analytics.py`). Results are cached per `(item, data version)` where the data version is `MAX(event_logs.id)` — stock movements, item/BOM updates and imports all write EventLog rows, so any relevant change invalidates the cache. ### `GET /api/analysis/production/{item_id}` | Param | Type | Default | Description | | :--- | :--- | :--- | :--- | | `n` | int | Buildable B | Unlock-simulator target batch size | | `buy_units` | int | — | Purchase suggestion: max total pieces to buy | | `buy_budget` | float | — | Purchase suggestion: max SEK to spend | Returns `{item, kpis, rows, flags, unlock, generated_at, data_version}` (+ `purchase_suggestion` when `buy_units` and/or `buy_budget` is given): - **`kpis`** — `buildable_a` (complete units from stock as-is; min over the root's direct non-labor lines of `floor(stock / qty_per_root)`, sub-assembly lines by finished stock), `buildable_b` (MRP netting: demand netted top-down per SKU, aggregated **across branches** before comparing to stock), `binding_constraint` (SKU capping Mode A), `capital_tied_up` (Σ unit cost × stock over distinct non-labor SKUs in the tree, negative stock as 0), `labor_minutes_per_unit`, `flag_count`. - **`rows`** — fully exploded tree, one row per component per path: `level, path[], sku, name(_en/_pt), unit, line_type (purchased|bom|labor), qty_per_parent, qty_per_root (cumulative), unit_cost, cost_per_root, stock, min_quantity, below_min, units_a, units_b, is_constraint_a, row_flags`. Cycle guard + max depth 10; fractional quantities preserved (floor only at the units-supported step). - **`flags`** — data-quality warnings: `cost_mismatch` (parent-line unit cost vs sub-BOM COGS, Δ > 2%), `root_cost_divergence` (snapshot vs live COGS), `below_min`, `negative_stock`, `zero_cost`, `cycle`, `max_depth`, `missing_component`. - **`unlock`** — shortage list after netting at `n`: per purchased SKU `need / have / short / est_purchase_cost`, plus `total_unlock_cost` and `value_released` (`n ×` last sold price, fallback list price). - **`purchase_suggestion`** — inverse simulator: the max buildable N with purchases capped at `buy_units` pieces and/or `buy_budget` SEK (caps combine with AND; shortage totals are monotone in N, found by binary search from Buildable B). `to_buy` lines carry `buy_qty` (netted shortage rounded UP to whole pieces), `unit_cost`, `cost`, `supplier`, `lead_time_days` and `min_order_qty` — ready to paste into a purchase order. Also `additional_units` (vs stock-only), `total_buy_units`, `total_cost`, `value_released`. Labor/time articles are identified by `Item.category == 'T'` (Visma Article Group "Labour/Time") — excluded from stock constraints and capital, summed as minutes per root unit. ### `GET /api/export/analytics/production/{item_id}` | Param | Type | Default | Description | | :--- | :--- | :--- | :--- | | `format` | `xlsx` \| `csv` | `xlsx` | Workbook or flat CSV | | `n` | int | Buildable B | Batch size used by the Shortages sheet | | `locale` | `sv` \| `us` | `sv` | CSV only — delimiter/decimal convention | `xlsx`: four sheets — **Summary** (KPIs, binding constraint, top-5 bottlenecks, labor minutes, flag count), **Exploded BOM** (flat, every nested BOM fully expanded), **Shortages**, **Flags** — with real numeric cells (Excel renders decimals per viewer locale). `csv`: the flat exploded sheet only. Filename: `production_analysis_{SKU}_{date}.{ext}`. --- ## Purchasing (Procurement) Reads the MVP 2 registers imported from Visma (purchase orders, supplier invoices, delivery notes, purchase prices, suppliers). Aggregates are "as of today"; amounts are SEK unless the field name ends in `_fx`. All endpoints require authentication. ### `GET /api/procurement/summary` KPI block: open POs (count, total and remaining SEK, overdue), open payables (total/overdue SEK + counts), 90-day on-time delivery rate, active suppliers. ### `GET /api/procurement/open-orders` Open POs (not delivered, not voided), most urgent first. Per row: dates, currency, `total_sek`, pro-rata `remaining_sek`, `received_pct`, `status` (`late | due_soon | on_track | no_date`) and `days_late`. ### `GET /api/procurement/ap-aging` Open supplier invoices (balance != 0) bucketed by days overdue (`not_due`, `d1_30`, `d31_60`, `d61_90`, `d90_plus`), plus the invoices themselves (top 200, most overdue first; credit notes carry negative balances). ### `GET /api/procurement/supplier-otd?window_days=365&grace_days=0` Per-supplier on-time delivery. A receipt is a delivery-note row traced to its PO row (`connection_type` 'B'); promised = the PO row's date2, falling back to the PO header delivery date; actual = arrival date, falling back to note date. ### `GET /api/procurement/purchase-orders/{po_number}` One PO in full: header, every row, receipts against it (delivery notes connected 'B') and the supplier invoices whose rows point back at it (from_type 'I'). 404 when unknown. ### `GET /api/procurement/supplier-invoices/{supplier_invoice_id}` The whole voucher (article + K/S/M rows), the POs its rows came from and the payments registered against it. 404 when unknown. ### `GET /api/procurement/price-variance?window_days=180` Latest effective price paid per supplier+SKU (invoice row amount / quantity, so discounts count) vs the purchase price list (base price preferred, else the lowest quantity break). Prices stay in the supplier's currency; deviations within 0.05% are dropped. ### `GET /api/procurement/items/{sku}/purchases?limit=300` One article's purchase history — the Purchase History section of the Inventory item drawer. Article rows only (`row_type` ''); an article nobody ever bought answers 200 with empty lists, not 404. - `purchases` — supplier-invoice rows: what was paid, newest first. `unit_price_fx`/`unit_price_sek` are amount / quantity, so discounts count. - `open_orders` — PO rows with quantity still undelivered (voided and closed POs excluded), `open_value_sek` pro-rata by the undelivered share. - `receipts` — delivery-note rows, with the PO they were booked against (`connection_type` 'B') when there is one. - `suppliers` — per-supplier rollup of `purchases` plus that supplier's list price for the article. - `price_list` — the agreed purchase prices (every quantity break). - `summary` — totals, first/last purchase, last and average unit price, `price_trend_pct` (last vs previous SEK unit price) and open exposure. `purchases` is capped at `limit` rows, newest first. The cap is on the LIST ONLY — `summary` and `suppliers` are computed over every row, so totals and shares stay exact. Compare `len(purchases)` with `summary.purchase_count` to tell whether rows were left out. ## Sales Insights Same conventions as Purchasing: MVP 2 registers plus the legacy invoice headers, aggregates as of today, SEK unless the field ends in `_fx`, auth required. ### `GET /api/sales/items/{sku}/sales?limit=300` One article's sales history — the mirror of `/api/procurement/items/{sku}/purchases` and the second half of the Inventory item drawer. Answers 200 with empty lists for an article never sold. - `sales` — legacy invoice rows (`row_source` 'adk'), newest first, with cost and margin AS POSTED (see `routers/invoice_lines.py`: `margin_sek` is ADK field 21 and `unit_cost_sek` is never read). Credit notes carry negative quantity and revenue and net out when summed. Rows are kept whatever their account, so `account_number` and `row_type` travel with each row. - `backlog` — open sales-order rows (order not delivered, not voided) with quantity still to ship. Package and structure rows are skipped, matching `/backlog`. Internal Produktion rows carry no prices: `open_value_sek` is 0 and `is_internal` is set. - `offers` — rows on open offers (not voided, `order_number` 0). - `customers` — rollup grouped by customer NAME, not by Visma id: one commercial customer routinely spans several ids, and `account_count` says how many. Same reasoning as `helpers.related_customer_ids`. - `summary` — totals, margin %, first/last sale, last unit price, `price_trend_pct` (last vs previous invoice) and backlog/offer exposure, with the internal backlog counted separately. `sales` is capped like `purchases` above — a heavily sold article has thousands of invoice rows (SKU 106: 2 163 rows, 1 MB of JSON uncapped), and the aggregates still cover all of them. ### `GET /api/sales/backlog` Open sales orders (not delivered, not voided) split external vs internal (Produktion). External carries value (head totals); internal is tracked by count. Per order: dates, status (`late | due_soon | reserved | to_invoice | on_track | no_date`), `reserved_pct` (row Q1 filled in Visma) and `delivered_pct` (same %, only with head delivery evidence — delivery note printed / delivered; otherwise null) from plain article rows (package/structure rows ignored). Rule in `backend/order_delivery.py`. KPIs include `reserved_count`/`reserved_value_sek` next to `to_invoice_*`. ### `GET /api/sales/offers?window_days=365` Open offers (not voided, no linked order) with expiry flags, plus the window's conversion funnel (issued vs converted to orders). ### `GET /api/sales/receivables?window_days=365` Two blocks. `open_ar`: legacy invoice headers with a balance, bucketed by days overdue (credit notes enter negative). `payment_behaviour`: customer payments netted per invoice and joined to the invoice dates — DSO weighted by paid SEK, average delay vs due date, on-time share, and the same per customer. ### `GET /api/sales/orders/{order_number}` One sales order in full: header, every row (package/structure flagged), the offer it came from and the invoice it became. 404 when unknown. ### `GET /api/sales/offers/{offer_number}` One offer in full: header, rows, and the sales order it converted into. 404 when unknown. ### `GET /api/sales/recurring` Active agreements (not completed): per-cycle value in the agreement currency, annualised SEK (cycle x 12 / interval months), next invoice date and agreements ending within 90 days. ## Common Responses | Status | Meaning | | :--- | :--- | | `200` | Success | | `404` | Item/resource not found (`{"detail": "Item not found"}`) | | `400` | Duplicate file hash or missing required CSV headers | | `500` | Database or processing error (`{"detail": "..."}`) |