Spaces:
Running
Running
File size: 23,648 Bytes
77db408 4152937 77db408 4152937 77db408 4152937 77db408 4152937 77db408 3f51f8d 77db408 4152937 77db408 4152937 77db408 4152937 77db408 8d4eeb8 77db408 | 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 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 | # 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": "..."}`) |
|