Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(docs): real screenshots in the guides, plus the seed data they need (#1384)

Anshul sharma9a8aeadd3767
diff --git a/.ai/plans/2026-08-12-docs-screenshots.md b/.ai/plans/2026-08-12-docs-screenshots.md
new file mode 100644
index 0000000000..2d9bc2c63f
--- /dev/null
+++ b/.ai/plans/2026-08-12-docs-screenshots.md
@@ -0,0 +1,378 @@
+# Docs screenshots — what's missing and how to capture it
+
+Date: 2026-08-12 · Branch: `feat/docs-screenshots`
+
+## Summary
+
+The docs site (`docs/`, Fumadocs) has **38 screenshot slots** and **zero real screenshots**.
+Every slot is a `<Screenshot label=… caption=… ratio=… />` placeholder that renders a dashed
+grey box with the label text inside (`docs/components/editorial/mdx.tsx:57`). There is no
+`src` prop, and `docs/public/` contains no screenshot directory.
+
+So this work is two things:
+
+1. **Code change (small, do first):** teach `<Screenshot>` to accept `src` and render a real
+ `<img>` inside the existing `Zoomable` frame, falling back to today's dashed placeholder
+ when `src` is absent. That keeps un-captured slots working while we fill them in batches.
+2. **Capture + place 38 images** under `docs/public/screens/` and add `src=` to each slot.
+
+Proposed convention: `docs/public/screens/<guide-or-page-slug>-<short-slug>.png`, e.g.
+`docs/public/screens/plan-projections.png`. Capture at a fixed viewport (suggest 1600×900 for
+`ratio="wide"`, 1200×1600 for `ratio="tall"`), 2× DPR, light theme only (the site is light-only).
+
+## Feasibility at a glance
+
+- **28 of 38** are plain authenticated ERP pages or in-page modals — straightforward.
+- **5** live in the MES app on a different port (3001) — same login, just a second browser target.
+- **2** are public tokenized share pages (`/share/quote/:externalLinkId`,
+ `/share/supplier-quote/:externalLinkId`) — capturable, but the link must be copied out of the
+ ERP record first, and should be shot in a clean window so no ERP chrome is in frame.
+- **3** need heavy prerequisite data (traceability graph, job production events, RFQ compare)
+ — they render an empty state unless a full flow has actually been run.
+- **1** is access-gated (`/x/settings/backups`, internal-email only) but **open on local dev**,
+ so capture it locally.
+
+Two capture-order dependencies worth planning around: production events (#28) needs time logged
+in MES first, and the change-notice diff (#38) needs the notice walked Draft → Implementation
+with real draft edits.
+
+## The 38 screenshots
+
+Legend: **App** = erp (port 3000) / mes (port 3001) / share (public page).
+`:id` params are DB UUIDs, not the human-readable IDs shown in the UI.
+
+### Guide: quote-to-cash
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 1 | `guides/quote-to-cash.mdx:33` — Quote builder | erp | `/x/quote/:quoteId/:lineId/details` | Quote in Draft with ≥2 lines and multiple `quotePrice` rows (quantity breaks). The line page shows the explorer + the break grid together. |
+| 2 | `guides/quote-to-cash.mdx:47` — Digital quote, customer view | share | `/share/quote/:externalLinkId` | Quote status **Sent**, `companySettings.digitalQuoteEnabled`. Copy the link from the quote header's Share button. PO-upload field needs `digitalQuoteIncludesPurchaseOrders`. |
+| 3 | `guides/quote-to-cash.mdx:69` — Sales order | erp | `/x/sales-order/:orderId/details` | Order created via the quote header's **Convert to Order**; opens at "To Ship and Invoice". |
+
+### Guide: order
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 4 | `guides/order.mdx:20` — Sales order dashboard | erp | `/x/sales/orders` (list) or `/x/sales-order/:orderId/details` | No "delivery schedule" entity exists — it's per-line `promisedDate`. Use 3 lines of 30 with staggered dates. |
+| 5 | `guides/order.mdx:34` — Jobs card + Convert Line to Job dialog | erp | `/x/sales-order/:orderId/:lineId/details`, click **Make to Order** | In-page modal, no URL. Line `methodType = "Make to Order"`. Prefilled qty = remaining, so create 0–2 jobs first to show the 90 → 60 story. |
+| 6 | `guides/order.mdx:46` — Job overview with copied method | erp | `/x/job/:jobId/details` | Job must have a populated `jobMakeMethod`, else BoM/BoP cards are empty. |
+
+### Guide: order-to-cash
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 7 | `guides/order-to-cash.mdx:43` — Post shipment | erp | `/x/shipment/:shipmentId/details`, click **Post** | Modal, no URL. Shipment is created only by the sales order header's **Ship** button (`/x/shipment/new` is POST-only). Order must be To Ship / To Ship and Invoice. |
+| 8 | `guides/order-to-cash.mdx:51` — Sales invoice | erp | `/x/sales-invoice/:invoiceId/details` | Created from a **posted** shipment. Don't re-hit `/x/sales-invoice/new?...` — it creates a new invoice every load. |
+
+### Guide: ship
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 9 | `guides/ship.mdx:16` — Quality issue | erp | `/x/issue/:id/details` | Issue created at `/x/issue/new` with an item + workflow, then a **job-operation association** added. |
+| 10 | `guides/ship.mdx:42` — Procedure version history | erp | `/x/procedure/:id`, open the `V{n}` version dropdown | Needs ≥2 versions (ideally one Active, one Archived). Alternative non-interactive shot: the Versions popover on `/x/production/procedures`. |
+| 11 | `guides/ship.mdx:52` — Traceability graph | erp | `/x/traceability/graph?trackedEntityId=<id>` | **Heavy prereq:** a serialized entity with real build activity. Without a tracked param the route redirects to `/x/traceability`; without activity it renders an empty state. |
+| 12 | `guides/ship.mdx:60` — Shipment & invoice (partial) | erp | `/x/shipment/:shipmentId/details` then `/x/sales-invoice/:invoiceId/details` | **Two pages, one slot** — either pick the stronger one or composite. Ship 30 of 90; the order stays To Ship and Invoice. |
+
+### Guide: build
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 13 | `guides/build.mdx:45` — BoM Subassembly / Kit toggle | erp | `/x/part/:itemId/make/:makeMethodId`, expand a material row | The toggle renders **only** when the material's `methodType = "Make to Order"`, and only on a **Draft** method. |
+| 14 | `guides/build.mdx:57` — Job method explorer | erp | `/x/job/:jobId/details` | Multi-level method (Make-to-Order children with their own materials + ops). Don't shoot from the `operations`/`events` tabs — they auto-collapse the explorer. |
+
+### Guide: floor
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 15 | `guides/floor.mdx:22` — MES schedule board | **mes** | `/x/operations` | Released jobs with operations at work centers **in the user's active location**. |
+| 16 | `guides/floor.mdx:39` — Job routing with an outside operation | erp | `/x/job/:jobId/details` (Bill of Process card) | Needs one `Process` op and one `Outside Processing` op with a supplier process attached. |
+| 17 | `guides/floor.mdx:45` — Shop-floor work instructions | **mes** | `/x/operation/:operationId` → **Instructions** tab | Tab is React state, not deep-linkable — must be clicked. Operation needs an attached procedure with steps + images. |
+| 18 | `guides/floor.mdx:66` — MES operation screen | **mes** | `/x/operation/:operationId` | Operation type must be `Process` (Assembly/Inspection redirect elsewhere). Job Released with materials on the op. |
+| 19 | `guides/floor.mdx:87` — Shop-floor scan | **mes** | `/x/assembly/:operationId` → click a tracked material → Issue Material modal | Operation type `Assembly`; parent serial-tracked; a batch/serial-tracked material with available lots. **No physical scanner needed** — the modal has a searchable dropdown. |
+
+### Guide: plan
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 20 | `guides/plan.mdx:18` — Production → Projections | erp | `/x/production/projections` | Needs a location with defaults set; enter quantities for a few weeks. |
+| 21 | `guides/plan.mdx:35` — Part: Planning tab | erp | `/x/part/:itemId/planning` | Set a reordering policy, reorder point, lot size; the chart needs some on-hand/demand history. |
+| 22 | `guides/plan.mdx:49` — Planning table | erp | `/x/production/planning` (and/or `/x/purchasing/planning`) | Caption says "jobs **and** POs" but these are two separate pages — pick one, or split the slot. Needs open demand + parts with a reordering policy. |
+| 23 | `guides/plan.mdx:59` — Receiving a purchase order | erp | `/x/receipt/:receiptId/details`, expand a line | Receipt created from a released PO via **Receive**; PO line must be for a **Batch**-tracked part so the lot field shows inline. Requires the `create` edge function running locally. |
+
+### Guide: job-finish-close / job-costing
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 24 | `guides/job-finish-close.mdx:25` — Job completion | erp | any job page → header **Complete** button → modal | Job not already Completed/Cancelled. Posting is irreversible — use a throwaway job. |
+| 25 | `guides/job-costing.mdx:35` — Job production events | erp | `/x/job/:jobId/events` | **Dependency:** needs logged `productionEvent` rows — run Setup/Labor/Machine in MES first (#18), or add events manually at `/x/job/:jobId/events/new`. Work centers need rates for the cost columns to read well. |
+
+### Guide: rfq-to-po
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 26 | `guides/rfq-to-po.mdx:27` — RFQ supplier comparison | erp | `/x/purchasing-rfq/:rfqId` → **Compare Quotes** drawer | **Heavy prereq:** RFQ finalized (Requested) with ≥2 suppliers and >1 *Active* supplier quote actually submitted, else the button doesn't render. |
+| 27 | `guides/rfq-to-po.mdx:39` — Supplier quote portal | share | `/share/supplier-quote/:externalLinkId` | Public tokenized page; copy the link from the supplier quote header. Shoot in a clean window. |
+| 28 | `guides/rfq-to-po.mdx:51` — Purchase order | erp | `/x/purchase-order/:orderId/details` | Finalized PO, nothing received or invoiced. Watch out: a high-value PO shows "Needs Approval" instead. |
+
+### Guide: receive-and-bill
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 29 | `guides/receive-and-bill.mdx:35` — Post receipt | erp | `/x/receipt/:receiptId/details`, click **Post** | Modal, no URL. Draft receipt from a finalized PO with received quantities. |
+| 30 | `guides/receive-and-bill.mdx:55` — Purchase invoice | erp | `/x/purchase-invoice/:invoiceId/details` | Draft invoice created from the receipt/PO **Invoice** button, lines carrying `purchaseOrderLineId`. |
+
+### Guide: fixed assets
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 31 | `guides/fixed-assets-acquire.mdx:31` — Fixed asset register | erp | `/x/fixed-asset/:fixedAssetId/register` (directly linkable drawer) | Asset must be **Draft** — the route redirects otherwise. The accounting *list* pages are behind a beta gate; the detail routes are not. |
+| 32 | `guides/fixed-assets-acquire.mdx:45` — Depreciation run | erp | `/x/depreciation-run/:depreciationRunId` | ≥1 Active asset with a depreciation method + start date, open accounting period, run still Draft. |
+| 33 | `guides/fixed-assets-sell.mdx:25` — Sell fixed asset | erp | `/x/fixed-asset/:fixedAssetId/sell` (modal, linkable) | Asset must be Active or Fully Depreciated; needs a customer to pick. |
+
+### Guide: change-order
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 34 | `guides/change-order.mdx:40` — New change notice form | erp | `/x/change-notice/new` | Change-notice types must exist (seeded). Capture before any affected item is added. |
+| 35 | `guides/change-order.mdx:60` — Affected item + change-type selector | erp | `/x/items/change-notice/:id/:affectedId/details` | Affected item must be a **Part** with a live make method so the draft BoM/BoP renders. |
+| 36 | `guides/change-order.mdx:108` — Release diff review (`ratio="tall"`) | erp | `/x/items/change-notice/:id/details` → header **Release** | **Heaviest prereq:** notice must be walked to status **Implementation** one step at a time, with real draft edits (a removed BoM line, a changed attribute), else the diff is empty. Modal state is not routable. |
+
+### Reference / platform pages
+
+| # | Slot | App | Where to capture | Prereqs / notes |
+|---|---|---|---|---|
+| 37 | `docs/platform/backups.mdx:33` — Settings → Backups | erp | `/x/settings/backups` | **Gated:** internal email or `IS_LOCAL_DEV`. Capture locally. Also open the `i` contents popover for the live per-area counts. |
+| 38 | `docs/reference/import-export.mdx:24` — Parts list Download CSV | erp | `/x/items/parts` | The dashed download button only renders when the table has ≥1 row. Hover it if we want the "Download CSV" tooltip in frame. |
+
+## Open questions for the next session
+
+1. **`<Screenshot src>` shape** — plain `<img>` vs Next `<Image>`. Next `<Image>` gives us
+ width/height and lazy loading, but needs intrinsic dimensions; plain `<img>` inside the
+ existing aspect-ratio box is the smaller change. Recommend plain `<img>` first.
+2. **Slot #12 and #22 each describe two pages.** Either capture the stronger single view or
+ split the slot into two `<Screenshot>`s. Needs a call.
+3. **Data seeding.** Several slots (11, 25, 26, 36) need a flow actually run end to end. Worth
+ deciding whether we seed a demo company once and shoot everything against it.
+4. **Redaction.** Whatever company we shoot against will have its name, users, and part numbers
+ in frame permanently. Recommend a purpose-built demo company matching the guides' robot story.
+
+---
+
+# Data audit — 2026-08-12
+
+Checked against the local dev Postgres for this worktree
+(`postgresql://postgres:postgres@localhost:64728/postgres`), company
+**Nebula aerospace** (`JdWKt22cuZfGGCmEH6jP7u`), the company owned by
+`[email protected]`. The other company in the DB (`Carbon Development`,
+`d9u72rtbc0gg2fdet3sg`, owned by `[email protected]`) holds an identical copy of the
+same seed — same gaps.
+
+Verdict: **the seed fills every list screen, but ~24 of the 38 screenshots would still
+come out empty or wrong.** The single biggest hole is that jobs were seeded without any
+operations or materials.
+
+## Empty / missing (blocks a screenshot)
+
+| Gap | Evidence | Blocks |
+|---|---|---|
+| **Jobs have no operations and no materials** | `jobOperation` = 0 and `jobMaterial` = 0 for all 8 jobs, though `jobMakeMethod` = 8 | 6, 14, 15, 16, 17, 18, 19, 24, 25 |
+| No procedures at all | `procedure` = 0, `procedureStep` = 0 | 10, 17 |
+| No purchasing RFQs or supplier quotes | `purchasingRfq` = 0, `supplierQuote` = 0 | 26, 27, 28 |
+| No demand projections | `demandProjection` = 0 | 20 |
+| No production events | `productionEvent` = 0 | 25 |
+| No tracked activity (no genealogy) | `trackedActivity` = 0; the 8 `trackedEntity` rows are all `sourceDocument = 'Item'` | 11 |
+| No depreciation runs | `depreciationRun` = 0 | 32 |
+| No quantity-break pricing | `quoteLinePrice` = 0 | 1 |
+| Digital quote unreachable | every `quote.externalLinkId` is null, and `companySettings.digitalQuoteEnabled = false` | 2 |
+| No issue↔job-operation link | `nonConformanceJobOperation` = 0 | 9 |
+| Nothing is batch- or serial-tracked | all 33 items are `itemTrackingType = 'Inventory'` | 19, 23, 11 |
+| No outside-processing operations | all 27 `methodOperation` rows are `operationType = 'Process'` (2 `supplierProcess` rows exist but are unused) | 16 |
+| No Make-to-Order child materials | all 40 `methodMaterial` rows are `Pull from Inventory`, so no subassembly exists | 13, 14 |
+| No order at "To Ship and Invoice" | statuses present: Draft, Confirmed, In Progress, To Ship, Completed, Closed, Cancelled | 3, 7 |
+| No PO at "To Receive and Invoice" | present: Draft, To Receive, To Invoice | 28 |
+| Thin sales orders | 8 of 9 orders have exactly 1 line; only the `To Ship` order has 2 lines and `promisedDate` set | 4, 5 |
+| Only one fixed asset, already Active | `fixedAsset` = 1 (`FA000001`, Active) — the Register drawer needs a **Draft** asset | 31 |
+
+## Already fine
+
+Parts list (22 parts) for 38 · Backups page for 37 (open on local dev) · Draft shipment
+from a sales order for 7 · Draft receipt from a PO for 29 · Draft sales invoice for 8 ·
+Draft purchase invoice for 30 · `itemPlanning` reordering policies on all 66 rows for 21 ·
+the Active fixed asset for 33 · 3 change notices (one at **Implementation**) with one
+affected item each for 34/35 — though 36 still needs real draft edits on that affected item
+to produce a non-empty diff.
+
+## How to fill the gaps
+
+The dev seed is already well structured — `packages/database/src/seed-dev/tiers/01…12`,
+run by `pnpm run db:seed:dev -- --email [email protected]`. Extending those tiers is the
+right fix: repeatable, reviewable, and it goes through the same code paths the app uses, so
+nothing about navigation breaks. Hand-written one-off `INSERT`s would drift and risk
+half-built records.
+
+Caveat to confirm before running: `seed-dev.ts` **wipes the company's business data and
+rebuilds it** unless `--skip-wipe` is passed. Reference/config data is preserved.
+
+---
+
+# Data fixes applied — 2026-08-12
+
+All gaps were closed by extending the dev seed (`packages/database/src/seed-dev/`), not by
+hand-written inserts, so the fix is repeatable: `pnpm run db:seed:dev -- --email [email protected]`.
+
+## The root cause behind nine of the empty screenshots
+
+`tiers/06-production.ts` guarded its only `jobOperation` insert on
+`ctx.refs.processes["Mechanical Assembly"]` and `ctx.refs.workCenters["Fabrication Bay"]` —
+neither name exists (the real ones are "Clean Room Assembly", "CNC Mill", …). The guard was
+`if (jmm1 && procAssembly && wcFab)`, so it silently did nothing and **every job shipped with
+zero operations and zero materials**.
+
+Fixed properly rather than by renaming the two refs: a new
+`helpers/job-method.ts` copies an item's active make method onto a job the way the `get-method`
+edge function's `itemToJob` path does — recursively, so subassemblies get their own
+`jobMakeMethod`, materials keep the operation they are consumed at, and rates come from the work
+center. The seed runs as one SQL transaction and cannot invoke an edge function, which is why
+this had to be reimplemented rather than called. It is deliberately narrower than the edge
+function: no configuration rules, no supersession redirect, no step/tool/parameter copy.
+
+Result: 81 job operations and 113 job materials across the 8 jobs, 11 levels deep on SAT-1000.
+
+## Everything else
+
+| Gap | Fix | Tier |
+|---|---|---|
+| No subassemblies (all BOM lines "Pull from Inventory") | `addBomLine` now derives `methodType` from the component's new `isMake` flag and sets `materialMakeMethodId` to the component's active method | `helpers/items.ts` |
+| No outside-processing step | Hard-anodize operation on BUS-STR-001 backed by a new AstroMill `supplierProcess` | 01, 02 |
+| Nothing batch- or serial-tracked | SAT-1000 + RW-010 Serial; BAT-LIION-48V + MAT-AL7075-PLT Batch | 02 |
+| Assembly view unreachable in MES | SAT-1000's integration operation is now `operationType: Assembly` | 02 |
+| No procedures | Two procedures with steps; "Structural Frame Assembly" has V1 Archived + V2 Active, attached to real operations | 01, 02 |
+| Scan picker empty | Available lots/serials for the tracked buy parts | 03 |
+| No production events | Setup/Labor/Machine events + a production quantity on the in-progress job | 06 |
+| Traceability graph empty | `SAT1000-SN-0001` with a Produce activity and six Consume activities carrying real inputs | 06 |
+| Issue had no association | `nonConformanceJobOperation` + `nonConformanceItem` on NCR000001 | 07 |
+| MES board empty even with jobs | The employee sat at Headquarters while every job and work center is at the plant — `employeeJob.locationId` now points at the plant (`userDefaults` is a view over it) | 01 |
+| No quantity-break pricing, digital quote unreachable, no "To Ship and Invoice" order, single-line orders | 8 `quoteLinePrice` rows, `digitalQuoteEnabled`, a real `externalLink`, and a 3-line staggered-delivery order | 04 |
+| No RFQ, no supplier quotes, no portal link, no PO at "To Receive and Invoice" | One RFQ to 3 suppliers, 3 Active supplier quotes with comparable break pricing and portal links, and PO000004 converted from the winner | 05 |
+| One Active fixed asset, no depreciation run | 4 assets (Draft / Active ×2 / Fully Depreciated) + a Draft run with lines | 09 |
+| Projections blank | 48-week period horizon + 24 weekly projections for three make parts | 12 |
+| Receipt line did not ask for a lot | `requiresBatchTracking` on the battery receipt line | 05 |
+
+## Verified after re-seed
+
+`jobOperation` 81 · `jobMaterial` 113 · `jobMakeMethod` 56 · Assembly ops 2 · Outside Processing
+ops 3 · procedures 2 Active + 1 Archived with 11 steps · operations carrying a procedure 5 ·
+`trackedActivity` 1 Produce + 6 Consume · `productionEvent` 6 · `demandProjection` 24 ·
+`depreciationRun` 1 with 2 lines · fixed assets Draft/Active×2/Fully Depreciated ·
+`quoteLinePrice` 8 · digital quote enabled with a live `externalLinkId` · a sales order at
+"To Ship and Invoice" · a PO at "To Receive and Invoice" · 3 supplier quotes with portal links ·
+`nonConformanceJobOperation` 1 · Make-to-Order BOM lines 10 · tracked items 2 Serial + 2 Batch.
+
+## Change notices + one wipe bug
+
+`changeOrderAffectedItem` rows had `draftMakeMethodId` / `baseMakeMethodId` NULL, so the
+affected-item page had nothing to edit and the Release diff was empty. All three notices now
+clone the item's method into a CO-owned Draft. CN-000002 (the one at `Implementation`, the
+status the Release button needs) diverges from its base on purpose — MAT-KAPTON dropped, the
+battery quantity 1→2, HARNESS-001 added, an operation renamed and re-timed, and a description
+set that the base does not have — so the diff shows a removal, an addition, a modification and
+an attribute change. `changeSummary` is dead code (nothing reads it) and was left null.
+
+Adding supplier quotes exposed a latent bug in `wipe.ts`: `supplierQuoteLine.itemId` has the same
+check constraint `salesOrderLine.itemId` does, so `nullNullableReferences` could not null it and
+the **second** seed run failed during the wipe. `supplierQuote` and `purchasingRfq` joined the
+list of headers deleted before that pass. The seed has since been run twice in a row cleanly.
+
+## Caveat
+
+Everything above is verified at the database level (row counts, statuses, foreign keys), not by
+loading each of the 38 pages in a browser. The page-by-page check happens naturally during the
+capture pass — anything still empty will be obvious the moment we open it.
+
+---
+
+# Capture spec — 2026-08-12
+
+The shot list, resolved to exact URLs against this worktree's data. Written so a capture run is
+mechanical: open URL, do the action, save to the filename.
+
+## Settings (identical for every shot)
+
+- **ERP** `https://erp.docs-screenshots.dev` · **MES** `https://mes.docs-screenshots.dev` ·
+ share pages are public routes on the ERP host.
+- Sign in as `[email protected]`, company **Nebula aerospace**, location **Manufacturing Plant**
+ (the MES board and the location-scoped ERP pages read the signed-in user's default location).
+- Viewport **1600×1000** at **2× device pixel ratio** for `ratio="wide"`, **1200×1500** for
+ `ratio="tall"` (only slot 36). Viewport clip, **not** full-page — a 4000px-tall page scaled into
+ a 16:9 figure is unreadable.
+- Light theme only; the docs site is light-only and a dark screenshot would fight the paper.
+- No browser chrome, no OS window frame, no cursor. Page content only.
+- PNG. Collapse the left sidebar only if it crowds the subject; otherwise leave the app's normal
+ chrome in frame so readers recognise where they are.
+- Wait for skeletons/spinners to clear before capturing. Several of these pages stream.
+
+## Naming and location
+
+`docs/public/screens/<guide-slug>-<subject>.png`, referenced from MDX as
+`src="/screens/<file>.png"` (paths under `docs/public/` are served from the site root).
+
+## Shot list
+
+`ratio="wide"` unless noted. Action blank = the URL alone is the shot.
+
+| # | File (`docs/public/screens/…`) | App | URL | Action |
+|---|---|---|---|---|
+| 1 | `quote-builder.png` | erp | `/x/quote/quote_YRQzVHySHTzr76KwtRAp4u/KaBjBdxm6xTw3ivoapvG9s/details` | Q000002, has the quantity breaks. No Draft quote carries breaks; Sent is fine. |
+| 2 | `quote-digital-customer.png` | share | `/share/quote/5eed0000-0000-4000-8000-000000000001` | Clean window, signed out. |
+| 3 | `quote-sales-order.png` | erp | `/x/sales-order/so_UpXcS5TNoTCg4PBdR3peqf/details` | SO000009, the only "To Ship and Invoice" order. Frame the header + status band. |
+| 4 | `order-dashboard.png` | erp | `/x/sales-order/so_UpXcS5TNoTCg4PBdR3peqf/details` | Same record as 3, framed on the three staggered `promisedDate` lines instead. |
+| 5 | `order-convert-line-to-job.png` | erp | `/x/sales-order/so_UpXcS5TNoTCg4PBdR3peqf/PF1EB543BGPgJuuQa65BaR/details` | SAW-001, 30 ea, Make to Order. Click **Make to Order** on the Jobs card. |
+| 6 | `order-job-overview.png` | erp | `/x/job/job_8N4xDHh7PkZDHC7zUXWxGT/details` | J000001. |
+| 7 | `otc-post-shipment.png` | erp | `/x/shipment/sh_4sYD2sAk34hWensuB3PxLo/details` | Open the **Post** modal. Do not confirm. |
+| 8 | `otc-sales-invoice.png` | erp | `/x/sales-invoice/si_BFQ5UXqePsHKen5dbPLVQr/details` | AR000001 Draft. |
+| 9 | `ship-quality-issue.png` | erp | `/x/issue/nc_Wfzn2Lyqsbb6wnQyPxvYSJ/details` | NCR000001 — the one carrying the job-operation link. |
+| 10 | `ship-procedure-versions.png` | erp | `/x/procedure/pro_YDRL1aV6LKJKaoPhzFUwr5` | Open the `V2` version dropdown (V1 is Archived). |
+| 11 | `ship-traceability-graph.png` | erp | `/x/traceability/graph?trackedEntityId=rSMCuSuyt7ZfaIUaM14vJ` | SAT1000-SN-0001. Without the param the route redirects. |
+| 12a | `ship-partial-shipment.png` | erp | `/x/shipment/sh_4sYD2sAk34hWensuB3PxLo/details` | Slot split in two — shipment half. |
+| 12b | `ship-partial-invoice.png` | erp | `/x/sales-invoice/si_BFQ5UXqePsHKen5dbPLVQr/details` | Slot split in two — invoice half. |
+| 13 | `build-subassembly-kit-toggle.png` | erp | `/x/part/item_PsbBdE9LPj13J9rpWegmgH/make/make_LnujjSJLt2XWLMU6outVaJ` | SAT-1000 **v2.00 Draft** — the toggle renders only on a Draft method, on a Make-to-Order line. Expand one. |
+| 14 | `build-job-method-explorer.png` | erp | `/x/job/job_8N4xDHh7PkZDHC7zUXWxGT/details` | Expand the explorer. Stay on `details`; other tabs auto-collapse it. |
+| 15 | `floor-mes-schedule.png` | **mes** | `/x/operations` | |
+| 16 | `floor-outside-operation.png` | erp | `/x/job/job_8N4xDHh7PkZDHC7zUXWxGT/details` | Frame the Bill of Process card — `jo_7riMHK66MAftECyk2nhvcc` is the anodize step at AstroMill. |
+| 17 | `floor-work-instructions.png` | **mes** | `/x/operation/jo_B8bp9wUytWkE2uW34Rqyyh` | Click the **Instructions** tab (React state, not deep-linkable). Procedure attached. |
+| 18 | `floor-mes-operation.png` | **mes** | `/x/operation/jo_7Z4q5gGdKERVgV7VgEYi5J` | "Machine structural panels" at CNC Mill — `Process`, Ready, on J000001. |
+| 19 | `floor-shopfloor-scan.png` | **mes** | `/x/assembly/jo_KazG6bdws4tWUFmWtAZtjT` | Click a tracked material → **Issue Material** modal. Dropdown, no scanner needed. |
+| 20 | `plan-projections.png` | erp | `/x/production/projections` | |
+| 21 | `plan-part-planning.png` | erp | `/x/part/item_ACg9bW6vQnYRh99VWRwaAj/planning` | Battery — batch-tracked, has a reorder policy. |
+| 22a | `plan-production-planning.png` | erp | `/x/production/planning` | Slot split in two — suggested jobs. |
+| 22b | `plan-purchasing-planning.png` | erp | `/x/purchasing/planning` | Slot split in two — suggested POs. |
+| 23 | `plan-receive-po.png` | erp | `/x/receipt/rec_S7rNbTW4zTAQL4V9nwX2qs/details` | Expand the battery line so the batch/lot field shows. |
+| 24 | `job-completion.png` | erp | `/x/job/job_JSiDJmAGFsRq7UAR2EKUYH/details` | J000002 Ready → header **Complete** → modal. **Mutating** — see ordering below. |
+| 25 | `job-production-events.png` | erp | `/x/job/job_8N4xDHh7PkZDHC7zUXWxGT/events` | 6 seeded events across two operations. |
+| 26 | `rfq-supplier-comparison.png` | erp | `/x/purchasing-rfq/d9u8j2tbc0ghholet58g` | PRFQ000001 Requested → **Compare Quotes** drawer (3 Active quotes). |
+| 27 | `rfq-supplier-portal.png` | share | `/share/supplier-quote/5c0e1a3d-7b41-4c92-9f18-2ad6e0b71c01` | Clean window, signed out. |
+| 28 | `rfq-purchase-order.png` | erp | `/x/purchase-order/po_TaZiGpDdrPvrCfJzRMvLYU/details` | PO000004, "To Receive and Invoice". |
+| 29 | `receive-post-receipt.png` | erp | `/x/receipt/rec_S7rNbTW4zTAQL4V9nwX2qs/details` | Open the **Post** modal. **Mutating if confirmed** — do not confirm. |
+| 30 | `receive-purchase-invoice.png` | erp | `/x/purchase-invoice/pi_RiMaXHS9ibtut6RdV29kUS/details` | AP000001 Draft. |
+| 31 | `fa-register.png` | erp | `/x/fixed-asset/d9u8j2tbc0ghholet5d0/register` | FA000003, the Draft asset — the route redirects for any other status. |
+| 32 | `fa-depreciation-run.png` | erp | `/x/depreciation-run/d9u8j2tbc0ghholet5e0` | Draft run, 2 lines. |
+| 33 | `fa-sell.png` | erp | `/x/fixed-asset/d9u8j2tbc0ghholet5c0/sell` | FA000001 Active. |
+| 34 | `co-new-notice.png` | erp | `/x/change-notice/new` | Empty form, before any affected item. |
+| 35 | `co-affected-item.png` | erp | `/x/items/change-notice/co_Xc8BasAdAcZwgCtGXqL6YV/coai_GddTJkkreziJcnQa4NbAFU/details` | CN-000002's affected item, draft method populated. |
+| 36 | `co-release-diff.png` (`ratio="tall"`) | erp | `/x/items/change-notice/co_Xc8BasAdAcZwgCtGXqL6YV/details` | CN-000002 at **Implementation** → header **Release** → diff modal. **Mutating if confirmed** — do not confirm. |
+| 37 | `platform-backups.png` | erp | `/x/settings/backups` | Open the `i` contents popover. Gated to internal email / local dev — fine here. |
+| 38 | `reference-parts-csv.png` | erp | `/x/items/parts` | Hover the download button so the "Download CSV" tooltip is in frame. |
+
+## Ordering
+
+Shots 1–23 and 25–28, 30–35, 37–38 are read-only. **24 is the only one that changes data** if the
+modal is confirmed — leave it last, and never confirm 7, 29 or 36 either. If a retake needs clean
+state, re-run `pnpm run db:seed:dev -- --email [email protected]` (it wipes and rebuilds the
+company's business data, so any manual edits made during capture are lost) and re-resolve the ids
+in this table, since they are regenerated on every seed.
+
+## MDX edits that come with this
+
+Slots 12 and 22 each become two `<Screenshot>` elements — `guides/ship.mdx:60` and
+`guides/plan.mdx:49`. Their captions need splitting too, one sentence per image. Everything else is
+a one-line change: add `src="/screens/<file>.png"` to the existing element.
diff --git a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
index b51bcc1ea5..62e7381888 100644
--- a/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
+++ b/apps/mes/app/components/JobOperation/components/IssueMaterialModal.tsx
@@ -342,7 +342,9 @@ export function IssueMaterialModal({
const [selectedSerialNumbers, setSelectedSerialNumbers] = useState<
Array<{ index: number; id: string }>
>(
- Array(Math.max(1, initialQuantity))
+ // A batch material's quantity can be fractional (4.5 plate x 3 units), and
+ // Array() throws "Invalid array length" on a non-integer.
+ Array(Math.max(1, Math.ceil(initialQuantity)))
.fill("")
.map((_, index) => ({ index, id: "" }))
);
diff --git a/docs/components/editorial/illustrations.tsx b/docs/components/editorial/illustrations.tsx
index 891cea956d..a8532264a3 100644
--- a/docs/components/editorial/illustrations.tsx
+++ b/docs/components/editorial/illustrations.tsx
@@ -284,20 +284,20 @@ function KitVsSubassembly() {
<text x={24} y={26} fontSize="11.5" fontWeight={600} fill={INK_60} fontFamily="var(--font-mono)">
SUBASSEMBLY
</text>
- <Box x={110} y={42} w={150} h={46} label="Arm" sub="make to order" />
+ <Box x={110} y={42} w={150} h={46} label="Frame" sub="make to order" />
<Arrow x1={185} y1={88} x2={185} y2={118} />
- <Box x={100} y={118} w={170} h={48} label="Arm job" sub="own routing" accent />
+ <Box x={100} y={118} w={170} h={48} label="Frame job" sub="own routing" accent />
<g stroke={LINE} strokeWidth={1.4} fill="none">
<path d="M 185 166 L 185 184 M 145 184 L 265 184 M 145 184 L 145 198 M 265 184 L 265 198" />
</g>
- <Box x={90} y={198} w={110} h={38} label="Part" />
- <Box x={210} y={198} w={110} h={38} label="Motor" />
+ <Box x={90} y={198} w={110} h={38} label="Panel" />
+ <Box x={210} y={198} w={110} h={38} label="Bracket" />
{/* Kit — components issued straight into the parent */}
<text x={400} y={26} fontSize="11.5" fontWeight={600} fill={INK_60} fontFamily="var(--font-mono)">
KIT
</text>
- <Box x={465} y={42} w={150} h={46} label="Arm" sub="make to order" />
+ <Box x={465} y={42} w={150} h={46} label="Frame" sub="make to order" />
<Arrow x1={540} y1={88} x2={540} y2={116} />
<rect x={442} y={116} width={196} height={106} rx={12} fill="#EAF8FF" stroke={BRAND} strokeWidth={1.4} strokeDasharray="5 4" />
<text x={540} y={137} textAnchor="middle" fontSize="10.5" fontWeight={600} fill={BRAND_INK} fontFamily="var(--font-mono)">
@@ -305,11 +305,11 @@ function KitVsSubassembly() {
</text>
<rect x={462} y={148} width={156} height={28} rx={7} fill="#FBFBF8" stroke={LINE} strokeWidth={1.3} />
<text x={540} y={166} textAnchor="middle" fontSize="12.5" fontWeight={500} fill={INK}>
- Part
+ Panel
</text>
<rect x={462} y={184} width={156} height={28} rx={7} fill="#FBFBF8" stroke={LINE} strokeWidth={1.3} />
<text x={540} y={202} textAnchor="middle" fontSize="12.5" fontWeight={500} fill={INK}>
- Motor
+ Bracket
</text>
</svg>
);
diff --git a/docs/components/editorial/mdx.tsx b/docs/components/editorial/mdx.tsx
index d1210a7d12..9b28eb2ad4 100644
--- a/docs/components/editorial/mdx.tsx
+++ b/docs/components/editorial/mdx.tsx
@@ -54,11 +54,17 @@ export function Figure({ illustration, caption }: { illustration: IllustrationKe
);
}
+/** A captured screenshot once `src` is set (a path under `docs/public/`, e.g.
+ * "/screens/sales-order.png"); until then, the dashed placeholder box, so a slot can be
+ * authored before the image exists. `label` is the alt text either way. A real image keeps
+ * its own aspect — `ratio` only sizes the placeholder. */
export function Screenshot({
+ src,
label,
caption,
ratio = "wide",
}: {
+ src?: string;
label: string;
caption?: string;
ratio?: "wide" | "tall" | "square";
@@ -68,17 +74,27 @@ export function Screenshot({
return (
<figure className="my-10">
<Zoomable>
- <div
- className={`relative w-full ${aspect} rounded-xl border border-dashed border-ed-warm-500 bg-ed-header overflow-hidden`}
- >
- <div className="absolute inset-0 flex flex-col items-center justify-center gap-2.5 px-6 text-center">
- <ImageGlyph />
- <span className="font-mono text-ed-10 tracking-[0.08em] uppercase text-ed-ink/70">
- Carbon screenshot
- </span>
- <span className="text-ed-14 font-medium text-ed-ink/78 max-w-90">{label}</span>
+ {src ? (
+ // Plain <img>: the file is a static asset of known path but unknown intrinsic size,
+ // and next/image needs either a static import or explicit width/height.
+ <img
+ src={src}
+ alt={label}
+ className="block w-full h-auto rounded-xl border border-ed-hairline bg-ed-header"
+ />
+ ) : (
+ <div
+ className={`relative w-full ${aspect} rounded-xl border border-dashed border-ed-warm-500 bg-ed-header overflow-hidden`}
+ >
+ <div className="absolute inset-0 flex flex-col items-center justify-center gap-2.5 px-6 text-center">
+ <ImageGlyph />
+ <span className="font-mono text-ed-10 tracking-[0.08em] uppercase text-ed-ink/70">
+ Carbon screenshot
+ </span>
+ <span className="text-ed-14 font-medium text-ed-ink/78 max-w-90">{label}</span>
+ </div>
</div>
- </div>
+ )}
</Zoomable>
{caption && (
<figcaption className="mt-3 text-center text-ed-12 text-ink-faint">{caption}</figcaption>
diff --git a/docs/content/docs/index.mdx b/docs/content/docs/index.mdx
index a479e0b2d3..56f33e02ee 100644
--- a/docs/content/docs/index.mdx
+++ b/docs/content/docs/index.mdx
@@ -7,7 +7,7 @@ Carbon is a manufacturing system: **ERP** for the office (orders, purchasing, pl
**MES** for the floor (<Term id="job">jobs</Term>, <Term id="operation">operations</Term>, tracking). One platform over one data model.
These are the **technical docs**: exact behavior, fields, and operations. If you're new, start with the
-narrated [**Guide**](/guides/order), which walks one order from the sales desk to a shipped, traceable robot.
+narrated [**Guide**](/guides/order), which walks one order from the sales desk to a shipped, traceable satellite.
Come here when you already know the noun you need and want the precise detail behind it.
## How the docs are organized
diff --git a/docs/content/docs/platform/backups.mdx b/docs/content/docs/platform/backups.mdx
index ba57509e50..adb0651375 100644
--- a/docs/content/docs/platform/backups.mdx
+++ b/docs/content/docs/platform/backups.mdx
@@ -30,7 +30,7 @@ When you export, **Include** offers two options:
On **Settings → Backups**, the "Create a backup" card snapshots the company's data. Give it an optional label, choose **Data only** or **Data + files**, and select **Create backup**. It runs in the background and the finished file appears in the list below, where you can download or delete it.
-<Screenshot label="Settings → Backups, the Create a backup card with the Data only / Data + files choice and the i contents button" caption="Export snapshots the company's data; the contents popover shows a live count per area." ratio="wide" />
+<Screenshot src="/screens/platform-backups.png" label="Settings → Backups, the Create a backup card with the Data only / Data + files choice and the i contents button" caption="Export snapshots the company's data; the contents popover shows a live count per area." ratio="wide" />
## Restore in place
diff --git a/docs/content/docs/reference/import-export.mdx b/docs/content/docs/reference/import-export.mdx
index c698e23e8b..3782a1a474 100644
--- a/docs/content/docs/reference/import-export.mdx
+++ b/docs/content/docs/reference/import-export.mdx
@@ -7,7 +7,7 @@ Carbon moves data both ways through CSV. Every data table can **export** its cur
## Exporting a table to CSV
-Open any data table (a parts list, a sales order dashboard, an inventory grid) and look for the dashed **Download CSV** button in the header. There is no setting to turn it on: every table built on Carbon's shared data grid gets the button automatically.
+Open any data table (a parts list, a sales order dashboard, an inventory grid) and look for the small download icon in the table header — hover it and its **Download CSV** tooltip appears. There is no setting to turn it on: every table built on Carbon's shared data grid gets the button automatically.
The download reflects **what you are currently looking at**, not a full server dump:
@@ -21,7 +21,7 @@ For id-bearing columns like item, supplier, employee, and customer, the export s
Export builds the file entirely in your browser and downloads it as `data.csv` with no server round-trip. Rename it after downloading if you're exporting several tables.
</Callout>
-<Screenshot label="Parts list with the dashed Download CSV button in the table header" caption="Every Carbon data table exports its current view. Filter and arrange columns first, since the export mirrors exactly what's on screen." />
+<Screenshot src="/screens/reference-parts-csv.png" label="Parts list with the Download CSV icon in the table header" caption="Every Carbon data table exports its current view. Filter and arrange columns first, since the export mirrors exactly what's on screen." />
## What you can import
diff --git a/docs/content/docs/reference/methods.mdx b/docs/content/docs/reference/methods.mdx
index 2ede26c13d..d51501bbf3 100644
--- a/docs/content/docs/reference/methods.mdx
+++ b/docs/content/docs/reference/methods.mdx
@@ -59,7 +59,7 @@ is frozen so jobs already running against it don't shift mid-build.
<Cards>
<Card title="Inside the build" href="/guides/build">
- See method types, kits, and Get Method in the story of a robot build.
+ See method types, kits, and Get Method in the story of a satellite build.
</Card>
<Card title="Reordering policy" href="/docs/reference/reordering">
How the replenishment system pairs with a part's reordering policy.
diff --git a/docs/content/docs/reference/planning.mdx b/docs/content/docs/reference/planning.mdx
index 5db2499c71..e54871d0d6 100644
--- a/docs/content/docs/reference/planning.mdx
+++ b/docs/content/docs/reference/planning.mdx
@@ -5,7 +5,7 @@ description: How demand turns into suggested jobs and purchase orders — and wh
Planning answers one question: *what should we make or buy, and how much?* Carbon's <Term>MRP</Term> looks at everything you owe and everything you have coming, and turns the gap into suggested orders that you choose to act on.
-Without planning you'd reorder by hand. MRP nets demand against supply across the whole <Term id="bom">bill of materials</Term>, so a shortfall on a top-level robot surfaces as the right quantity of every component, offset for its <Term>lead time</Term> — before you're caught short.
+Without planning you'd reorder by hand. MRP nets demand against supply across the whole <Term id="bom">bill of materials</Term>, so a shortfall on a top-level satellite surfaces as the right quantity of every component, offset for its <Term>lead time</Term> — before you're caught short.
## Two stages
diff --git a/docs/content/guides/build.mdx b/docs/content/guides/build.mdx
index 7501edd759..0f8193af37 100644
--- a/docs/content/guides/build.mdx
+++ b/docs/content/guides/build.mdx
@@ -1,17 +1,17 @@
---
title: Inside the build
-description: How each robot part is made or bought.
+description: How each satellite part is made or bought.
label: "(II)"
index: 1
---
-Open the job you just released and look at what it actually takes to build a robot. This is where the product structure you set up in PLM meets the reality of the floor.
+Open the job you just released and look at what it actually takes to build a satellite bus. This is where the product structure you set up in PLM meets the reality of the floor.
> PLM specifies the parts. The method adds the clarity: how each part is obtained, and whether it's built, bought, or pulled from the shelf.
## The bill of materials
-A robot's <Term id="bom">bill of materials</Term> (BoM) is a tree. The robot is built from an arm and a leg; each of those is built from a machined part and a motor. Carbon shows the whole structure at a glance, with every node carrying an icon for how it's obtained.
+A satellite bus's <Term id="bom">bill of materials</Term> (BoM) is a tree. SAT-1000 is built from subassemblies — the BUS-STR-001 structural frame, the EPS-001 electrical power subsystem, ADCS-001, COMMS-001 and the rest — and each of those is built from parts of its own: the power subsystem from solar array wings and a battery pack, the frame from aluminium plate and fasteners. Carbon shows the whole structure at a glance, with every node carrying an icon for how it's obtained.
<Figure illustration="bom-tree" caption="The robot BoM: made parts in blue, bought parts in amber, every leaf pulled from stock." />
@@ -21,8 +21,8 @@ Every item in that tree carries a <Term>method type</Term>, and it's the single
<Figure illustration="method-types" caption="One field, three values: Make to Order becomes a job, Purchase to Order a PO, Pull from Inventory a stock pull." />
-- <Term>Make to Order</Term>: you manufacture it. The arm part and leg part are machined in-house, so each becomes its own <Term>job</Term> with its own operations.
-- <Term>Purchase to Order</Term>: you purchase it. The motors come from a supplier, so they flow through [purchasing](/guides/rfq-to-po) as a <Term>purchase order</Term>, never touching the floor.
+- <Term>Make to Order</Term>: you manufacture it. The structural frame and the solar array wings are built in-house, so each becomes its own <Term>job</Term> with its own operations.
+- <Term>Purchase to Order</Term>: you purchase it. The battery packs come from a supplier, so they flow through [purchasing](/guides/rfq-to-po) as a <Term>purchase order</Term>, never touching the floor.
- <Term>Pull from Inventory</Term>: you pull it from stock when the parent is built, whether you originally made it or bought it.
You don't tag this on each BoM line by hand. The method type lives on [the item itself](/docs/reference/items), and every BoM that uses that item mirrors it. Switch a part's method type once, and it cascades everywhere the part appears.
@@ -33,20 +33,20 @@ Method type answers "how does this part get into its parent?": Make to Order, Pu
## Kits & subassemblies
-Because the arm and leg are Make to Order parts, they aren't just line items — they're built things. But Carbon gives a made item in a BoM two flavors, and the choice changes how the floor handles it:
+Because the structural frame and the power subsystem are Make to Order parts, they aren't just line items — they're built things. But Carbon gives a made item in a BoM two flavors, and the choice changes how the floor handles it:
-<Figure illustration="kit-vs-subassembly" caption="Same arm, two treatments: a Subassembly builds as its own job; a Kit is issued straight into the parent." />
+<Figure illustration="kit-vs-subassembly" caption="Same frame, two treatments: a Subassembly builds as its own job; a Kit is issued straight into the parent." />
-- <Term>Subassembly</Term>: built as its own job, with its own <Term>routing</Term> and its own completion. You can release the left arm independently of the final robot, and Carbon keeps the hierarchy in sync.
+- <Term>Subassembly</Term>: built as its own job, with its own <Term>routing</Term> and its own completion. You can release the structural frame independently of the final satellite, and Carbon keeps the hierarchy in sync.
- <Term>Kit</Term>: not built separately at all. Its components are issued together straight into the parent job, as a set. There's no kit job and no kit operation — just the parts, grouped.
Reach for a subassembly when the thing is genuinely manufactured and worth tracking on its own. Reach for a kit when a cluster of parts always goes in together and a separate build would just be ceremony.
-<Screenshot label="BoM — Subassembly / Kit toggle" caption="Switching the arm between a tracked Subassembly and an issued-together Kit." ratio="wide" />
+<Screenshot src="/screens/build-subassembly-kit-toggle.png" label="BoM — Subassembly / Kit toggle" caption="Switching the BUS-STR-001 structural frame on the SAT-1000 BoM between a tracked Subassembly and an issued-together Kit." ratio="wide" />
## Methods on the job
-Back on the job, you're looking at that working copy of the method from the last chapter, and you can drill the whole way down. The robot's method lists the arm and leg; open the arm and you're in the arm's method, its machined part set to Make to Order and its motor set to Purchase to Order. The tree is as deep as the product.
+Back on the job, you're looking at that working copy of the method from the last chapter, and you can drill the whole way down. The bus's method lists the structural frame, the power subsystem, and their siblings; open the power subsystem and you're in its method, its solar array wings set to Make to Order and its battery pack set to Purchase to Order. The tree is as deep as the product.
Methods are versioned, which is what keeps a busy shop sane. A method is Draft, Active, or Archived, and only a Draft can be edited. An Active method is frozen, the jobs running against it won't shift under anyone's feet, so you revise by publishing a new version, not by editing a live one.
@@ -54,4 +54,4 @@ Methods are versioned, which is what keeps a busy shop sane. A method is Draft,
Draft is the workbench; Active is the published, locked recipe; Archived is history. Changes flow forward into the next version and the next job — never backward into a build that's already moving.
</Callout>
-<Screenshot label="Job method explorer" caption="The robot job's method expanded: arm and leg subassemblies, each with its own materials and operations." ratio="wide" />
+<Screenshot src="/screens/build-job-method-explorer.png" label="Job method explorer" caption="Job J000001's method expanded: the SAT-1000's subassemblies — structural frame, power subsystem, ADCS and the rest — each with its own materials and operations." ratio="wide" />
diff --git a/docs/content/guides/change-order.mdx b/docs/content/guides/change-order.mdx
index b1d7219707..17e54fa2b0 100644
--- a/docs/content/guides/change-order.mdx
+++ b/docs/content/guides/change-order.mdx
@@ -8,7 +8,7 @@ flowName: Engineering change
flowIndex: 4
---
-The robot's arm bracket needs a thicker wall and one fewer fastener. In a lot of systems that means editing
+The satellite bus's antenna pointing bracket needs a thicker wall and one fewer fastener. In a lot of systems that means editing
the live part and hoping nothing in flight notices. Carbon makes you do it deliberately: you open a
<Term id="change-order">change notice</Term>, edit a hidden draft of the part's method, review exactly what changed, and release
when it's ready. Until that moment, every job, plan, and cost calculation still sees the old bracket.
@@ -37,7 +37,7 @@ change notice linked, so nobody revises a design that's already mid-change. The
blocks: a second change notice on the same part is allowed, and Carbon keeps their draft versions from
colliding, so a deliberate parallel change is fine.
-<Screenshot label="New change notice form" caption="Name, category, reason, owner, and priority. The header before any affected item is added." ratio="wide" />
+<Screenshot src="/screens/co-new-notice.png" label="New change notice form" caption="Name, category, reason, owner, and priority. The header before any affected item is added." ratio="wide" />
<Callout tone="blue" badge="TOP-DOWN, NOT BOTTOM-UP" title="You pick the parts first, then edit them in place.">
Carbon doesn't ask you to describe a change as a list of add-this, delete-that rows. You select the affected
@@ -57,7 +57,7 @@ change notice, because it decides both what you can touch and what release will
later, but not for free: switching discards the draft and mints a fresh one from the live method, so any
edits you'd made are reset. Decide the type first, then edit.
-<Screenshot label="Affected item with change-type selector" caption="The bracket's draft method open for editing, with its change type set on the item card." ratio="wide" />
+<Screenshot src="/screens/co-affected-item.png" label="Affected item with change-type selector" caption="An affected item's draft method open for editing on CN-000001, with the 'Change type' select on the item card." ratio="wide" />
- <Term id="change-order-change-type">Version</Term> revises how the *same* part is made. You edit its BoM and
BoP; release publishes a new method version and archives the old one. No new part, nothing superseded.
@@ -105,7 +105,7 @@ At **"Implementation"** the **"Release"** action opens. It doesn't just apply th
affected item's change as a read-only diff first. Materials added and removed, operations and their steps
changed, attributes that moved — laid out line by line against the method you snapshotted from.
-<Screenshot label="Release change notice — diff review" caption="The dropped fastener line and the thicker-wall attribute, shown as a diff before you confirm." ratio="tall" />
+<Screenshot src="/screens/co-release-diff.png" label="Release change notice — diff review" caption="The dropped fastener line and the thicker-wall attribute, shown as a diff before you confirm." ratio="tall" />
<Callout tone="neutral" badge="EXACT BY CONSTRUCTION" title="The diff is real because the draft is real.">
There's no shadow copy of your edits to drift out of sync. You edited an actual draft method, so the diff is
diff --git a/docs/content/guides/fixed-assets-acquire.mdx b/docs/content/guides/fixed-assets-acquire.mdx
index d24c71488d..06b5b926fc 100644
--- a/docs/content/guides/fixed-assets-acquire.mdx
+++ b/docs/content/guides/fixed-assets-acquire.mdx
@@ -28,7 +28,7 @@ An asset comes onto the books one of two ways, and both start at **"Draft"**.
The purchase-receipt path posts the acquisition entry and the Draft → Active flip inside the same gate as every other ledger posting. With accounting off, the PO line is received but the asset itself is left untouched. Register it manually instead.
</Callout>
-<Screenshot label="Fixed asset — register" caption="Bringing an asset to Active with its acquisition cost and depreciation start date." ratio="wide" />
+<Screenshot src="/screens/fa-register.png" label="Fixed asset — register" caption="Bringing an asset to Active with its acquisition cost and depreciation start date." ratio="wide" />
## Depreciate it
@@ -42,7 +42,7 @@ The book charge follows the asset's method (**<Term>straight line</Term>**, **<T
Each run's amounts are calculated when you create it and held as a draft, so you can check the period's charges before they hit the ledger. When an asset's <Term>net book value</Term> reaches its <Term>residual value</Term>, posting flips it to **"Fully Depreciated"** and it stops accruing.
</Callout>
-<Screenshot label="Depreciation run" caption="A monthly run: every active asset's charge, computed and held as a draft for review before posting." ratio="wide" />
+<Screenshot src="/screens/fa-depreciation-run.png" label="Depreciation run" caption="A monthly run: every active asset's charge, computed and held as a draft for review before posting." ratio="wide" />
## Two books at once
diff --git a/docs/content/guides/fixed-assets-sell.mdx b/docs/content/guides/fixed-assets-sell.mdx
index 89abcc1baf..634f02f7cd 100644
--- a/docs/content/guides/fixed-assets-sell.mdx
+++ b/docs/content/guides/fixed-assets-sell.mdx
@@ -22,7 +22,7 @@ Selling a piece of equipment is a sales act, so it lives with the sales team. Th
The Sell action doesn't invent a separate sale mechanism. It creates a normal sales order, lined up at net book value, that ships and invoices like any other. The fixed-asset line just remembers which asset was sold.
</Callout>
-<Screenshot label="Sell fixed asset" caption="The Sell action drafts a sales order for the asset at its net book value." ratio="wide" />
+<Screenshot src="/screens/fa-sell.png" label="Sell fixed asset" caption="The Sell action drafts a sales order for the asset at its net book value." ratio="wide" />
## Dispose it
diff --git a/docs/content/guides/floor.mdx b/docs/content/guides/floor.mdx
index 45a85c619a..2dbe683b44 100644
--- a/docs/content/guides/floor.mdx
+++ b/docs/content/guides/floor.mdx
@@ -5,7 +5,7 @@ label: "(IV)"
index: 3
---
-Time to build. You release the first <Term id="job">production job</Term>, the first 30 robots, to the shop floor, along with the <Term>subassembly</Term> jobs for the parts that feed it. This is the handoff most shops fumble; in Carbon it's a single, traceable step.
+Time to build. You release the first <Term id="job">production job</Term> to the shop floor, along with the <Term>subassembly</Term> jobs for the parts that feed it. This is the handoff most shops fumble; in Carbon it's a single, traceable step.
<Figure illustration="shopfloor-loop" caption="On the floor, every operation reports back: material consumed, labor logged, parts scanned." />
@@ -19,36 +19,36 @@ The released work lands on the MES "Schedule" board, a Kanban with one column pe
The MES board is a live read of the schedule, so operators can filter and focus but they don't drag work to reschedule it. Rebalancing the plan, moving an operation to a different work center or shifting a job's dates so Carbon reschedules it, happens on the [ERP scheduling boards](/guides/plan), where a planner owns the sequence. What lands here is the result.
</Callout>
-<Screenshot label="MES schedule board" caption="The first 30-robot job and its subassemblies queued across work-center columns." ratio="wide" />
+<Screenshot src="/screens/floor-mes-schedule.png" label="MES schedule board" caption="Released operations queued across the work-center columns: Clean Room Bay A, CNC Mill, PCB Lab, Potting Station, and QC Bench." ratio="wide" />
## Operations & work centers
-Open a job and its <Term>routing</Term> is an ordered list of operations. Each operation names a process (Mill, Deburr, Anodize, Assemble) and the work center that runs it, with separate setup, labor, and machine time so estimates and costs are honest about where the hours go.
+Open a job and its <Term>routing</Term> is an ordered list of operations. Each operation names a process (Mill, Weld, Anodize, Assemble) and the work center that runs it, with separate setup, labor, and machine time so estimates and costs are honest about where the hours go.
Most operations run on your floor. But some don't, and Carbon plans for that explicitly:
- Inside operation: runs at one of your work centers, by your people.
-- <Term>Outside operation</Term>: performed by a supplier. Anodizing the arm part, say: the step leaves your floor, goes out, and comes back to finish its routing.
+- <Term>Outside operation</Term>: performed by a supplier. Hard-anodizing the structural panels, say: the step leaves your floor, goes out, and comes back to finish its routing.
<Figure illustration="outside-processing" caption="An outside step leaves the floor for a supplier and raises its own PO — then rejoins the routing." />
<Callout tone="blue" badge="OUTSIDE PROCESSING" title="A supplier-run step raises its own purchase order.">
-Tie a process to a supplier and mark the operation Outside. Releasing the job raises an Outside Processing PO for that step, priced at the supplier's rate, and its lead time takes its place in the routing, so the schedule knows the arm is away being anodized.
+Tie a process to a supplier and mark the operation Outside. Releasing the job raises an Outside Processing PO for that step, priced at the supplier's rate, and its lead time takes its place in the routing, so the schedule knows the frame is away being anodized.
</Callout>
-<Screenshot label="Job routing with an outside operation" caption="The arm's routing: in-house milling, then an outside anodize step at a supplier." ratio="wide" />
+<Screenshot src="/screens/floor-outside-operation.png" label="Job routing with an outside operation" caption="The structural frame's routing on J000001: machining and welding in-house, then a hard-anodize step outside at AstroMill Machining." ratio="wide" />
## Work instructions
-On the shop-floor view, an operator doesn't see a spreadsheet — they see rich work instructions: ordered steps, with images, for the exact operation in front of them. It reads like a great minimal manual, and it's always the current revision.
+On the shop-floor view, an operator doesn't see a spreadsheet — they see rich work instructions: an ordered checklist of steps, each with its description and the measurement tolerance it has to meet, for the exact operation in front of them. It reads like a great minimal manual, and it's always the current revision.
-<Screenshot label="Shop-floor work instructions" caption="A step-by-step work instruction for assembling the arm, with reference images." ratio="wide" />
+<Screenshot src="/screens/floor-work-instructions.png" label="Shop-floor work instructions" caption="The step checklist for J000001's final assembly and torque operation, with the torque and squareness tolerances each step must hit." ratio="wide" />
## At the station
When the operator opens their operation on the MES, the controls feel physical, closer to a machine panel than a form. A big Play button reads "Start"; press it and it becomes "Pause". Everything they do here flows straight back to the job:
-- Clock time with the "Setup", "Labor", and "Machine" toggles, each of which starts and stops a <Term id="production-event">production event</Term>, so the operation's estimated hours meet the actual ones.
+- Clock time against the operation's work type: the button beside the Play control reads "Labor", and starting and stopping it opens and closes a <Term id="production-event">production event</Term>, so the operation's estimated hours meet the actual ones. An operation that also carries setup or machine time offers those work types in the same control.
- "Issue Material" to <Term id="material-issue">issue</Term> the operation's components onto the job as they're consumed.
- "Log Completed" for good units, "Log Scrap" with a <Term>scrap</Term> reason, or "Log <Term>Rework</Term>" as pieces come off the operation. "Complete All" reports the whole remaining quantity in one tap.
- "Finish" to close the operation. It ends every active production event in one move and flips the operation to "Done".
@@ -63,13 +63,13 @@ Logged hours multiply by the work center's labor and machine rates; issued mater
"Finish" closes one operation for good. "End Operations", from the sidebar, is the end-of-shift move: it stops every production event you have running without completing or finishing any of them, so the clock stops but the work stays open for the next person to pick up. If time cards are turned on, clocking out does the same to your labor clock.
</Callout>
-<Screenshot label="MES operation screen" caption="An operator running the arm's mill operation: time toggles, quantities, and material." ratio="wide" />
+<Screenshot src="/screens/floor-mes-operation.png" label="MES operation screen" caption="An operator on J000001's 'Machine structural panels' operation at the CNC Mill: the Labor work type, quantities, and the material list." ratio="wide" />
## Backflush & issue
Material leaves inventory two ways in Carbon, and the BoM decides which one applies to each component, so stock stays accurate without busywork:
-- Issued: tracked material, like the serialized or batch-tracked motors, is issued to the operation (or picked to the line) so every unit is accounted for by its lot.
+- Issued: tracked material, like the serialized frames or the batch-tracked battery packs, is issued to the operation (or picked to the line) so every unit is accounted for by its lot.
- <Term id="backflush">Backflushed</Term>: non-tracked material is pulled from stock automatically the moment the operation or job reports complete. No transactions, no keystrokes.
<Callout tone="green" badge="BACKFLUSH" title="The everyday consumables update themselves as the floor builds.">
@@ -81,7 +81,7 @@ Flag a material to backflush and you never reconcile it by hand. The moment an o
For parts that demand a paper trail, operators scan as they build. Under the hood, every physical thing (a serial, a batch, a lot) is a <Term>tracked entity</Term>. Scanning a child into the unit you're building records a [tracked activity](/docs/reference/traceability): the child is marked consumed, the unit is marked produced, and the link between them is permanent.
<Callout tone="blue" badge="SERIAL vs BATCH" title="Two tracking modes, one genealogy.">
-<Term id="serial">Serialize</Term> what you track one-by-one: the finished robot, its arm, its leg. <Term id="batch">Batch-track</Term> what moves in lots: motors, fasteners, raw stock. Scan a serial into a batch and Carbon records the link, so the robot's record knows exactly which motor lot it carries.
+<Term id="serial">Serialize</Term> what you track one-by-one: the finished satellite, its structural frame, its solar array wings. <Term id="batch">Batch-track</Term> what moves in lots: battery packs, fasteners, aluminium plate. Scan a serial into a batch and Carbon records the link, so the satellite's record knows exactly which battery lot it carries.
</Callout>
-<Screenshot label="Shop-floor scan" caption="An operator scanning a motor lot into robot serial #0001 at the assembly station." ratio="wide" />
+<Screenshot src="/screens/floor-shopfloor-scan.png" label="Shop-floor material issue" caption="An operator issuing one tracked Structural Frame Assembly into the job at the station." ratio="wide" />
diff --git a/docs/content/guides/job-costing.mdx b/docs/content/guides/job-costing.mdx
index 351c49272e..aab942731b 100644
--- a/docs/content/guides/job-costing.mdx
+++ b/docs/content/guides/job-costing.mdx
@@ -8,7 +8,7 @@ flowName: Manufacturing accounting
flowIndex: 3
---
-The [make-to-order tour](/guides/order) built robots. This flow follows the money those jobs spend. As a job is worked, Carbon accumulates its cost (materials consumed, plus labor, machine, and overhead time) into <Term id="wip">work-in-process</Term>, then releases that cost into finished-goods inventory when the job completes. Every figure here is grounded in real ledger postings, so it's worth being precise about what posts, when, and to which account.
+The [make-to-order tour](/guides/order) built satellites. This flow follows the money those jobs spend. As a job is worked, Carbon accumulates its cost (materials consumed, plus labor, machine, and overhead time) into <Term id="wip">work-in-process</Term>, then releases that cost into finished-goods inventory when the job completes. Every figure here is grounded in real ledger postings, so it's worth being precise about what posts, when, and to which account.
## Accounting is a switch
@@ -32,7 +32,7 @@ As the job runs, cost flows **into** its work-in-process. Two streams feed it.
WIP is the sum of consumed material and the priced production events. Each event posts labor and machine at the work center's rates, and when the work center has an overhead rate, that too is absorbed into WIP alongside the time, gated on the overhead-absorption account being configured. WIP is real material plus real time, not a standard estimate.
</Callout>
-<Screenshot label="Job — production events" caption="Production events on a job; each posts labor, machine, and overhead to WIP at the work center's rates as it's logged." ratio="wide" />
+<Screenshot src="/screens/job-production-events.png" label="Job — production events" caption="Production events on J000001 — setup, labor, and machine time logged against each work center — priced into WIP at that work center's rates." ratio="wide" />
## Issued or backflushed
diff --git a/docs/content/guides/job-finish-close.mdx b/docs/content/guides/job-finish-close.mdx
index 4b86019c17..811cd45acc 100644
--- a/docs/content/guides/job-finish-close.mdx
+++ b/docs/content/guides/job-finish-close.mdx
@@ -14,7 +14,7 @@ A <Term>job</Term> has been collecting cost in <Term id="wip">work-in-process</T
## Finish into inventory
-When the last operation is done, Carbon completes the job. It <Term id="backflush">backflushes</Term> any material still owed, catches up any labor that hasn't posted yet, and then **receives the finished goods into inventory**: a debit to inventory, a credit to work-in-process, tagged *Job Receipt*. The job moves to **"Completed"**.
+When the last operation is done, you complete the job. The **"Complete Job"** dialog confirms the move — it shows the **"Quantity Completed"**, derived from the serials and batches completed in MES rather than typed in, and warns that the job will no longer be available on the shop floor. Carbon then <Term id="backflush">backflushes</Term> any untracked material still owed — serial- and batch-tracked material has to be scanned in on the floor, so it is never backflushed — catches up any labor that hasn't posted yet, and **receives the finished goods into inventory**: a debit to inventory, a credit to work-in-process, tagged *Job Receipt*. The job moves to **"Completed"**.
The receipt is valued at the job's **actual accumulated WIP cost** — whatever really went in. Carbon does not receive finished goods at standard and book a variance; the finished unit's cost is simply the sum of what the job spent.
@@ -22,7 +22,7 @@ The receipt is valued at the job's **actual accumulated WIP cost** — whatever
Completion moves the whole WIP balance into inventory one-for-one, equal debit and credit, so there's no variance at finish time. The item's costing method only decides how that cost is carried forward onto the part, not the value it's received at.
</Callout>
-<Screenshot label="Job completion" caption="Completing the job: finished goods received into inventory at the job's accumulated cost." ratio="wide" />
+<Screenshot src="/screens/job-completion.png" label="Job completion" caption="The Complete Job dialog: the quantity completed comes from the serials and batches finished in MES and can't be edited here." ratio="wide" />
## Make-to-order still goes through stock
diff --git a/docs/content/guides/order-to-cash.mdx b/docs/content/guides/order-to-cash.mdx
index 234c35a766..39b33c686a 100644
--- a/docs/content/guides/order-to-cash.mdx
+++ b/docs/content/guides/order-to-cash.mdx
@@ -40,7 +40,7 @@ Creating it changes nothing on hand: **<Term id="posting">posting</Term>** is th
A posted shipment decrements stock and advances the order, and if accounting is enabled it writes the <Term id="cogs">COGS</Term> journal entries. What it does **not** do is create the invoice. Fulfillment and billing are deliberately separate steps.
</Callout>
-<Screenshot label="Post shipment" caption="Posting the shipment: inventory moves, the line's sent quantity rises, the order advances." ratio="wide" />
+<Screenshot src="/screens/otc-post-shipment.png" label="Post shipment" caption="The Post Shipment confirmation. Posting is the move that drops inventory, raises the line's sent quantity, and advances the order." ratio="wide" />
## Raise the invoice
@@ -48,7 +48,7 @@ A sales invoice has two possible sources. You can bill straight from the **sales
The invoice opens at **"Draft"**, fully editable. The moment it leaves "Draft" it locks, a guard against changing numbers that have already entered the books.
-<Screenshot label="Sales invoice" caption="A draft invoice drawn from the posted shipment, quantities matched to what shipped." ratio="wide" />
+<Screenshot src="/screens/otc-sales-invoice.png" label="Sales invoice" caption="AR000001 in Draft, its SAT-1000 line and Net 30 terms carried across from the order, still fully editable until it's posted." ratio="wide" />
## Post and get paid
diff --git a/docs/content/guides/order.mdx b/docs/content/guides/order.mdx
index b3781747ba..0e1978cc96 100644
--- a/docs/content/guides/order.mdx
+++ b/docs/content/guides/order.mdx
@@ -1,11 +1,11 @@
---
title: Start with the order
-description: A 90-unit robot order becomes real work.
+description: A 90-unit solar array wing order becomes real work.
label: "(I)"
index: 0
---
-Meet the shop we'll follow through this guide: an <Term>OEM</Term> that builds humanoid robots. One customer just placed an order for 90 units. By the end, you'll have followed that order all the way from the sales desk to 90 finished robots on the shipping dock — and seen most of Carbon along the way.
+Meet the shop we'll follow through this guide: Nebula Aerospace, an <Term>OEM</Term> that builds satellites. One customer, NovaSat Networks, just placed an order for 90 solar array wings. By the end, you'll have followed that order all the way from the sales desk to 90 finished wings on the shipping dock — and seen most of Carbon along the way.
Carbon spans the office and the floor: ERP for orders, purchasing, and planning; MES for the people actually building. The thread that ties them together is a single order, so that's where we start.
@@ -13,11 +13,11 @@ Carbon spans the office and the floor: ERP for orders, purchasing, and planning;
## The sales order
-Open the <Term>sales order</Term> dashboard. There's already an order on the books: 90 robots. But the customer doesn't want all 90 at once. They want 30 this week, 30 next week, and 30 the week after. That delivery schedule is going to shape everything downstream.
+Open the <Term>sales order</Term> dashboard. There's already an order on the books: SO000009, 90 SAW-001 Solar Array Wings at $35,000 each. But the customer doesn't want all 90 at once, so the order carries three lines of 30 — one this week, one next week, one the week after. That delivery schedule is going to shape everything downstream.
-Shipping part of an order doesn't close it. While any unit still has to ship, the order's status reads **"To Ship and Invoice"**. Once every unit has shipped but you haven't billed yet, it moves to **"To Invoice"**. The order closes only when everything has both shipped and been invoiced. That's what lets one order be fulfilled in batches without losing track of what's left.
+Shipping part of an order doesn't close it. The badge on the header reads **"In Progress"**, the display status Carbon shows while the order's make-to-order lines still have production to finish; the stored status underneath is **"To Ship and Invoice"** while any unit has yet to ship. Once every unit has shipped but you haven't billed yet, it moves to **"To Invoice"**. The order closes only when everything has both shipped and been invoiced. That's what lets one order be fulfilled in batches without losing track of what's left.
-<Screenshot label="Sales order dashboard" caption="The 90-unit robot order, with its three-week delivery schedule." ratio="wide" />
+<Screenshot src="/screens/order-dashboard.png" label="Sales order dashboard" caption="SO000009 for NovaSat Networks: three lines of 30 Solar Array Wings, an 'In Progress' badge, and a 'Jobs Required' banner waiting on you to create the jobs." ratio="wide" />
<Callout tone="neutral" badge="UPSTREAM" title="The order often starts as a quote.">
Carbon has a full <Term>Quote</Term> module with quantity-break pricing, so the 90-unit price could have been negotiated in <Term>quote to cash</Term> first. We'll pick the story up at the confirmed sales order, where the build truly begins.
@@ -25,13 +25,13 @@ Carbon has a full <Term>Quote</Term> module with quantity-break pricing, so the
## Batch it into jobs
-You don't build 90 robots as one monolithic job. To match the three-week delivery schedule, you split the order into three <Term id="job">jobs</Term> of 30, one per delivery, each scheduled, released, and shipped on its own timeline.
+You don't build 90 wings as one monolithic job. To match the three-week delivery schedule, the order's three lines of 30 become three <Term id="job">jobs</Term> of 30, one per delivery, each scheduled, released, and shipped on its own timeline.
-You create those jobs from the sales order itself. On the line's **Jobs** card, click **"Make to Order"**; in the **"Convert Line to Job"** dialog, set the **Quantity** to 30 and create the first job. Repeat for the second and third. Carbon counts down the units still waiting on a job (90 → 60 → 30), so you always know how much of the order is left to batch. To build all 90 at once instead, you'd leave the **Quantity** at the full 90 and create a single job.
+You create those jobs from the sales order itself. The **"Jobs Required"** banner at the top of the order is the prompt; its **"Create Jobs"** button covers the whole order at once. To do it line by line, use the line's **Jobs** card: click **"Make to Order"** and the **"Convert Line to Job"** dialog opens with the **Quantity** already prefilled at the line's 30. Create the first job, then repeat for the second and third lines. Carbon counts down the units still waiting on a job (90 → 60 → 30), so you always know how much of the order is left to batch. To build only part of a line, lower the prefilled **Quantity** and convert the remainder later.
<Figure illustration="order-split" caption="One 90-unit order, batched into three 30-unit jobs across three weeks." />
-<Screenshot label="Sales order line: Jobs card and the Convert Line to Job dialog" caption="Where you batch: the line's Jobs card. 'Make to Order' opens 'Convert Line to Job'. Set Quantity to 30 and create each batch, repeating until the order is fully covered." ratio="wide" />
+<Screenshot src="/screens/order-convert-line-to-job.png" label="Sales order line: Jobs card and the Convert Line to Job dialog" caption="Where you batch: the line's Jobs card. 'Make to Order' opens 'Convert Line to Job' with the Quantity prefilled at the line's 30. Create each batch, repeating until the order is fully covered." ratio="wide" />
<Callout tone="blue" badge="WHY BATCH" title="Batching matches your build to the delivery promise.">
Three jobs of 30 let you release week one now, keep weeks two and three in planning, and ship each batch the moment it's done — instead of waiting on all 90.
@@ -41,9 +41,9 @@ Three jobs of 30 let you release week one now, keep weeks two and three in plann
From the sales order, create the job. Carbon carries the part, quantity, and due date across automatically. The job inherits exactly what was sold. That way, the shop floor always has the up-to-date specifications and requirements for the job.
-Carbon carries one more thing across, and it's the most important: the robot's <Term id="method">manufacturing method</Term>, its full recipe of materials and operations. The job doesn't point at the part's master recipe, though. It gets its own copy.
+Carbon carries one more thing across, and it's the most important: the part's <Term id="method">manufacturing method</Term>, its full recipe of materials and operations. The job doesn't point at the part's master recipe, though. It gets its own copy.
-<Screenshot label="Job overview with its copied method" caption="The first 30-unit job, carrying its own copy of the robot's method: part, quantity, and due date all inherited from the sales order line." ratio="wide" />
+<Screenshot src="/screens/order-job-overview.png" label="Job overview with its copied method" caption="A job created this way — here J000001 for the SAT-1000 satellite bus — carries its own copy of the part's method, with part, quantity, and due date inherited from the sales order line." ratio="wide" />
## Get the method
diff --git a/docs/content/guides/plan.mdx b/docs/content/guides/plan.mdx
index 8d3bf23ca2..fbf6065ce1 100644
--- a/docs/content/guides/plan.mdx
+++ b/docs/content/guides/plan.mdx
@@ -5,17 +5,17 @@ label: "(III)"
index: 2
---
-Creating that first <Term>job</Term> created demand. Carbon now knows it needs arm parts, motors, and machine time. But your <Term id="sales-order">sales orders</Term> only show part of the picture. The pipeline says more robots are coming, even though no order exists yet.
+Creating that first <Term>job</Term> created demand. Carbon now knows it needs structural frames, battery packs, and machine time. But your <Term id="sales-order">sales orders</Term> only show part of the picture. The pipeline says more satellite buses are coming, even though no order exists yet.
Planning on confirmed orders alone means you're always reacting. Carbon lets you plan on what you expect, too — and lets each part decide for itself how aggressively to replenish.
## Demand forecasting
-Under Production, open Projections and enter what you expect to need in the coming weeks. Here, the pipeline points to 50 robots in week four and 70 in week five, real demand with no order behind it yet. <Term id="demand-forecast">Forecasting</Term> puts it into the plan anyway.
+Under Production, open Projections and enter what you expect to need in the coming weeks. Here, the pipeline points to two SAT-1000 satellite buses a week for the next fortnight, climbing to four a week by week six, and to the subsystems that ride with them: ADCS-001 and EPS-001. That's real demand with no order behind it yet. <Term id="demand-forecast">Forecasting</Term> puts it into the plan anyway.
<Figure illustration="demand-forecast" caption="Confirmed orders (weeks 1–3) plus forecasted demand (weeks 4–5), the full picture Carbon plans against." />
-<Screenshot label="Production → Projections" caption="Entering projected weekly quantities for the robot from the sales pipeline." ratio="wide" />
+<Screenshot src="/screens/plan-projections.png" label="Production → Projections" caption="Entering projected weekly quantities from the sales pipeline: the SAT-1000 bus at 2, 2, 3, 3, 4, 4 over the first six weeks, with ADCS-001 and EPS-001 alongside it." ratio="wide" />
## Reordering policy
@@ -29,10 +29,10 @@ Not every part should wait for demand to pull it. A fast-moving fastener wants a
<Figure illustration="reorder-policy" caption="Reorder point in action: on-hand falls to the trigger, and an order tops it back up." />
<Callout tone="blue" badge="BUY OR MAKE" title="The policy decides how much; the replenishment system decides what kind of order.">
-A part set to Buy turns a replenishment into a <Term id="purchase-order">purchase order</Term>; set to Make, it turns into a job. Lot size and minimum / maximum order quantities round the raw number into something you can actually order or build.
+A part set to Buy turns a replenishment into a <Term id="purchase-order">purchase order</Term>; set to Make, it turns into a job. The reorder quantity and the minimum / maximum order quantities round the raw number into something you can actually order or build.
</Callout>
-<Screenshot label="Part: Planning tab" caption="A part's reordering policy, reorder point, and lot size that drive every suggestion." ratio="wide" />
+<Screenshot src="/screens/plan-part-planning.png" label="Part: Planning tab" caption="A part's Reordering Policy, Reorder Point, and Reorder Quantity that drive every suggestion." ratio="wide" />
## Into jobs & POs
@@ -40,20 +40,22 @@ Now Carbon turns the whole picture (orders, forecast, and each part's policy) in
<Figure illustration="planning-engine" caption="Demand in, plan out: production planning suggests jobs, purchasing planning suggests POs." />
-Purchasing planning applies <Term id="conversion-factor">conversion factors</Term> as it goes, so a robot's worth of demand becomes the right quantity in the units you actually buy. Nothing is committed until you confirm a suggestion. That's the moment a proposed line becomes a real job or a real PO.
+Purchasing planning applies <Term id="conversion-factor">conversion factors</Term> as it goes, so a satellite's worth of demand becomes the right quantity in the units you actually buy. Nothing is committed until you confirm a suggestion. That's the moment a proposed line becomes a real job or a real PO.
<Callout tone="neutral" badge="BY LOCATION" title="Demand and planning can differ by location.">
Run different plans for different sites, and let each part replenish the way that site needs: full demand-driven planning in one, simple min/max for high-runners in another.
</Callout>
-<Screenshot label="Planning table" caption="Suggested jobs and purchase orders, ready to confirm." ratio="wide" />
+<Screenshot src="/screens/plan-production-planning.png" label="Production planning" caption="Suggested jobs for the parts you make, with the weekly shortfall that triggered each one." ratio="wide" />
+
+<Screenshot src="/screens/plan-purchasing-planning.png" label="Purchasing planning" caption="The same view for the parts you buy: suggested purchase orders, ready to confirm." ratio="wide" />
## Receiving
When a purchase order arrives, you receive it. A <Term>receipt</Term> starts as a Draft against the PO, auto-fills its lines from what was ordered, and validates the quantities; <Term id="posting">posting</Term> it turns the goods into on-hand stock on a shelf.
-For a <Term id="batch">batch-tracked</Term> part like the motors, Carbon captures the lot right on the receipt line, and a conversion factor converts what you bought into what you stock, so a box of ten motors becomes ten units on the shelf. Months later, you can answer exactly which lot of motors went into which robots.
+For a <Term id="batch">batch-tracked</Term> part like the BAT-LIION-48V battery packs, Carbon captures the batch number right on the receipt line, and a conversion factor converts what you bought into what you stock, so a case of ten packs becomes ten units on the shelf. Months later, you can answer exactly which lot of packs went into which satellites.
<Figure illustration="conversion-factor" caption="A conversion factor reconciles units: one purchased box of ten lands as ten stocked Each." />
-<Screenshot label="Receiving a purchase order" caption="Receiving a batch-tracked motor shipment against its PO, lot captured on the line." ratio="wide" />
+<Screenshot src="/screens/plan-receive-po.png" label="Receiving a purchase order" caption="Receiving a batch-tracked battery-pack shipment against PO000001, batch LOT-BAT-2609 captured on the line." ratio="wide" />
diff --git a/docs/content/guides/quote-to-cash.mdx b/docs/content/guides/quote-to-cash.mdx
index cc56cecd17..a627a8d3b3 100644
--- a/docs/content/guides/quote-to-cash.mdx
+++ b/docs/content/guides/quote-to-cash.mdx
@@ -26,11 +26,11 @@ A sales order does not require a quote, and a quote does not require an RFQ. Eac
## Build the quote
-Open a new quote and add a line per item the customer asked about. Pricing lives on the line and supports quantity breaks, so the unit price for 10 can differ from the price for 100. The negotiated number you land on is what carries forward later.
+Open a new quote and add a line per item the customer asked about. Pricing lives on the line and supports quantity breaks, so the unit price for one can differ from the price for twenty-five. The negotiated number you land on is what carries forward later.
A fresh quote sits at **"Draft"**. Each line moves through its own state as you work it up: **"Draft"**, **"In Progress"**, then **"Complete"** once you've settled its pricing. The line states let you quote a multi-item inquiry piecemeal instead of all at once, marking lines complete one by one rather than all at once.
-<Screenshot label="Quote builder" caption="A multi-line quote with quantity-break pricing, each line worked up independently." ratio="wide" />
+<Screenshot src="/screens/quote-builder.png" label="Quote builder" caption="A multi-line quote with quantity-break pricing, each line worked up independently." ratio="wide" />
When the numbers are ready, finalizing the quote moves it to **"Sent"** and marks its lines **"Complete"**. That status is also the gate for the next step.
@@ -38,13 +38,13 @@ When the numbers are ready, finalizing the quote moves it to **"Sent"** and mark
Carbon can hand the customer the quote directly. With digital quotes enabled, a **"Sent"** quote exposes a private share link: an unguessable id, no login required. Internal notes are stripped before anything reaches the customer.
-From that link the customer does one of two things. They **accept**, optionally attaching their PO as a PDF, and the quote converts straight into a sales order. Or they **reject**, and the quote moves to **"Lost"**. Either way the outcome lands back in Carbon without a single email thread.
+From that link the customer does one of two things. They **accept** — the page ends with an **"Accept Quote"** button — and the quote converts straight into a sales order; the option to attach their PO as a PDF appears once they've accepted. Or they **reject**, via the **"Reject Quote"** link underneath, and the quote moves to **"Lost"**. Either way the outcome lands back in Carbon without a single email thread.
<Callout tone="blue" badge="DIGITAL QUOTE" title="Acceptance is a first-class action, not an inbox.">
The customer-facing share link turns an accept into a real conversion and a reject into a recorded outcome. A companion customer portal then shows them live order and job status as the work proceeds.
</Callout>
-<Screenshot label="Digital quote: customer view" caption="What the customer sees: line pricing, accept with an optional PO upload, or reject." ratio="wide" />
+<Screenshot src="/screens/quote-digital-customer.png" label="Digital quote: customer view" caption="What the customer sees: line pricing, an 'Accept Quote' button, and a 'Reject Quote' link beneath it." ratio="wide" />
## When a quote doesn't land
@@ -66,4 +66,4 @@ That status is the handoff. Everything from here (production, shipment, invoice)
There is no path from a quote straight to a production job. A [make-to-order](/guides/order) line on the *sales order* is what spawns a job, so the sequence is always quote → order → job. The order is the source of truth the floor builds against.
</Callout>
-<Screenshot label="Sales order" caption="The converted order at 'To Ship and Invoice', priced from the accepted quote." ratio="wide" />
+<Screenshot src="/screens/quote-sales-order.png" label="Sales order" caption="The converted order, priced from the accepted quote. Its badge reads 'In Progress' while the make-to-order lines still have jobs to finish." ratio="wide" />
diff --git a/docs/content/guides/receive-and-bill.mdx b/docs/content/guides/receive-and-bill.mdx
index 5e0421e056..9223933239 100644
--- a/docs/content/guides/receive-and-bill.mdx
+++ b/docs/content/guides/receive-and-bill.mdx
@@ -32,7 +32,7 @@ Posting a receipt always updates inventory. The accounting entries are written o
Receive an item flagged for inspection and its <Term id="tracked-entity">tracked units</Term> come in **"On Hold"**, with an inbound inspection opened at **"Pending"** — received, but quarantined until quality clears them for use.
</Callout>
-<Screenshot label="Post receipt" caption="Posting the receipt: stock enters the item ledger, the line's received quantity rises, the order advances." ratio="wide" />
+<Screenshot src="/screens/receive-post-receipt.png" label="Post receipt" caption="Posting the receipt: stock enters the item ledger, the line's received quantity rises, the order advances." ratio="wide" />
## Buy by the box, stock by the each
@@ -52,7 +52,7 @@ There is, deliberately, no direct link from an invoice to a receipt. A receipt i
Order, receipt, and bill are reconciled through the quantities on their shared purchase order line. Posting the invoice clears the GR/IR accrual the receipt booked, at the receipt's cost, and books any difference between order price and bill to a purchase price-variance account.
</Callout>
-<Screenshot label="Purchase invoice" caption="A draft supplier invoice drawn from the order, lines matched on the purchase order line." ratio="wide" />
+<Screenshot src="/screens/receive-purchase-invoice.png" label="Purchase invoice" caption="A draft supplier invoice drawn from the order, lines matched on the purchase order line." ratio="wide" />
## Match and post
diff --git a/docs/content/guides/rfq-to-po.mdx b/docs/content/guides/rfq-to-po.mdx
index 69a089d05b..50836beb8a 100644
--- a/docs/content/guides/rfq-to-po.mdx
+++ b/docs/content/guides/rfq-to-po.mdx
@@ -8,7 +8,7 @@ flowName: RFQ to bill
flowIndex: 2
---
-Every robot the shop builds is mostly parts it buys. RFQ to bill is the procurement side of the house, the mirror image of quote to cash, run from the buyer's chair. You ask suppliers for a price, you place an order, the goods arrive, and a supplier bill lands that you reconcile against what you actually ordered and received.
+Every satellite the shop builds is mostly parts it buys. RFQ to bill is the procurement side of the house, the mirror image of quote to cash, run from the buyer's chair. You ask suppliers for a price, you place an order, the goods arrive, and a supplier bill lands that you reconcile against what you actually ordered and received.
We'll follow one purchased part from a blank request all the way to a posted supplier invoice.
@@ -24,7 +24,7 @@ When you finalize it, Carbon does the fan-out for you. It creates one **supplier
You can start at the purchase order and skip the shopping-around entirely. When you do use them, the RFQ, the supplier quotes, and the eventual PO are tied together by junction records, not a rigid chain, so one request can spread across many suppliers and many orders.
</Callout>
-<Screenshot label="Purchasing RFQ — supplier comparison" caption="One request, the same lines, fanned out to several suppliers to compare." ratio="wide" />
+<Screenshot src="/screens/rfq-supplier-comparison.png" label="Purchasing RFQ — supplier comparison" caption="One request, the same lines, fanned out to several suppliers to compare." ratio="wide" />
## Suppliers quote back
@@ -36,7 +36,7 @@ It's the same digital-quote machinery as the sales side, pointed the other way:
The share link lives on each supplier quote, so every supplier responds in their own document. You see the bids side by side and pick the one to turn into an order.
</Callout>
-<Screenshot label="Supplier quote portal" caption="The supplier's view: enter unit price, quantity breaks, and lead time, then submit." ratio="wide" />
+<Screenshot src="/screens/rfq-supplier-portal.png" label="Supplier quote portal" caption="The supplier's view: enter unit price, quantity breaks, and lead time, then submit." ratio="wide" />
## Into a purchase order
@@ -48,7 +48,7 @@ A purchase order's status is never typed in by hand. Carbon computes it from the
Each line tracks whether it's fully received and fully invoiced. The order rolls those up: "To Receive and Invoice" → "To Receive" or "To Invoice" → "Completed", so the header always reflects what's actually outstanding, never a stale label.
</Callout>
-<Screenshot label="Purchase order" caption="The order converted from the chosen supplier quote, sitting at 'To Receive and Invoice'." ratio="wide" />
+<Screenshot src="/screens/rfq-purchase-order.png" label="Purchase order" caption="The order converted from the chosen supplier quote, sitting at 'To Receive and Invoice'." ratio="wide" />
## Send work out, too
diff --git a/docs/content/guides/ship.mdx b/docs/content/guides/ship.mdx
index bafcbe2007..b8bfba49b2 100644
--- a/docs/content/guides/ship.mdx
+++ b/docs/content/guides/ship.mdx
@@ -5,15 +5,15 @@ label: "(V)"
index: 4
---
-Building the robot is most of the work, but it isn't the whole job. You still have to prove it was built right, and close the loop with the customer and your books.
+Building the satellite is most of the work, but it isn't the whole job. You still have to prove it was built right, and close the loop with the customer and your books.
## Raise an issue
-Say an operator flags a defect on an arm. You open an Issue, Carbon's name for a <Term id="nonconformance">non-conformance</Term>. It moves through a clear lifecycle, from Registered to In Progress to Closed, and it links to the part itself, so the arm now carries that open issue everywhere it appears in the system.
+Say an operator flags a short in the EPS wiring harness. You open an Issue, Carbon's name for a <Term id="nonconformance">non-conformance</Term>. It moves through a clear lifecycle, from Registered to In Progress to Closed, and it links to the part and the job operation it was found on, so the bus now carries that open issue everywhere it appears in the system.
<Figure illustration="eight-d" caption="An issue moves through its workflow (contain, correct, verify) until the fix is proven." />
-<Screenshot label="Quality issue" caption="An issue opened against the arm assembly operation." ratio="wide" />
+<Screenshot src="/screens/ship-quality-issue.png" label="Quality issue" caption="NCR000001, 'EPS wiring harness short detected', opened against J000001's clean room assembly operation." ratio="wide" />
## Workflows & actions
@@ -28,37 +28,37 @@ An issue doesn't just sit there — it runs a workflow you define. A classic <Te
- Communication: keep the customer in the loop.
<Callout tone="amber" badge="DISPOSITION" title="Held material doesn't move until someone signs off.">
-A review step gates what happens to the non-conforming arms: use as is, <Term>rework</Term>, <Term>scrap</Term>, or return to the supplier. Nothing is dispositioned on a hunch; the decision is recorded against the issue alongside its actions.
+A review step gates what happens to the non-conforming assemblies: use as is, <Term>rework</Term>, <Term>scrap</Term>, or return to the supplier. Nothing is dispositioned on a hunch; the decision is recorded against the issue alongside its actions.
</Callout>
## Versioned procedures
-Those work instructions the operator followed didn't appear from nowhere. They're generated from versioned procedures, the same Draft / Active / Archived discipline you saw on <Term id="method">methods</Term>. When a corrective action changes how the arm is assembled, you publish a new revision; every future job picks it up, and every job already running keeps the revision it started on.
+Those work instructions the operator followed didn't appear from nowhere. They're generated from versioned procedures, the same Draft / Active / Archived discipline you saw on <Term id="method">methods</Term>. When a corrective action changes how the structural frame is assembled, you publish a new revision; every future job picks it up, and every job already running keeps the revision it started on.
<Callout tone="green" badge="REVISIONS" title="Change the procedure once; the floor follows everywhere.">
-New jobs pick up the latest published version; in-flight jobs never shift mid-build. And every robot's record pins the exact procedure revision it was actually built to.
+New jobs pick up the latest published version; in-flight jobs never shift mid-build. And every satellite's record pins the exact procedure revision it was actually built to.
</Callout>
-<Screenshot label="Procedure version history" caption="A new revision of the arm-assembly procedure, published from the issue's corrective action." ratio="wide" />
+<Screenshot src="/screens/ship-procedure-versions.png" label="Procedure version history" caption="V2 of the Structural Frame Assembly procedure, active, with V1 archived behind it." ratio="wide" />
## Traceability
-Because everything was captured at build time, the <Term>genealogy</Term> of a finished robot is complete. Carbon stores it as a graph of <Term id="tracked-entity">tracked entities</Term> and the activities that link them, so from one serial you can walk backward to every ancestor (which arm, which motor lot, which raw material) or forward to every place a lot was used.
+Because everything was captured at build time, the <Term>genealogy</Term> of a finished satellite is complete. Carbon stores it as a graph of <Term id="tracked-entity">tracked entities</Term> and the activities that link them, so from one serial you can walk backward to every ancestor (which frame, which battery lot, which plate of aluminium) or forward to every place a lot was used.
<Figure illustration="traceability-graph" caption="The genealogy of one finished robot, from serial number down to material lots." />
-One click, or one scan of the robot's QR label, answers the question every auditor and every recall asks: what exactly went into this unit, and where else did that lot go?
+One click, or one scan of the satellite's QR label, answers the question every auditor and every recall asks: what exactly went into this unit, and where else did that lot go?
-<Screenshot label="Traceability graph" caption="The full as-built genealogy for robot serial #0001." ratio="wide" />
+<Screenshot src="/screens/ship-traceability-graph.png" label="Traceability graph" caption="The full as-built genealogy for SAT-1000 serial SAT1000-SN-0001, down to the aluminium plate and reaction wheels it consumed." ratio="wide" />
## Ship & invoice
-Week one's 30 robots are done. You create a [shipment](/guides/order-to-cash) against the <Term id="sales-order">sales order</Term>. It drafts its lines from what's outstanding, you pick and post it, then <Term id="invoice">invoice</Term> that same 30. Because the order still has units to ship, it stays at "To Ship and Invoice" and simply carries the remaining 60 forward; the line's completed count rolls up as each batch ships.
+The first finished units are ready. You create a [shipment](/guides/order-to-cash) against the <Term id="sales-order">sales order</Term>. It drafts its lines from what's outstanding, and you ship only what's actually built: on SHP000001 the line reads 2 shipped against 3 ordered, so 1 stays outstanding. Post it, then <Term id="invoice">invoice</Term> that same 2. Because the order still has a unit to ship, it stays at "To Ship and Invoice" and simply carries the remainder forward; the line's shipped count rolls up as each batch goes.
Carbon ties the invoice straight into your accounting system, so the build that started at the [sales desk](/guides/quote-to-cash) closes on the books — partial quantity and all.
-<Screenshot label="Shipment & invoice" caption="Shipping the first 30 units and invoicing the partial quantity." ratio="wide" />
+<Screenshot src="/screens/ship-partial-shipment.png" label="Partial shipment" caption="Shipping part of the order — SHP000001 sends 2 of the 3 ordered, leaving 1 outstanding, so the order stays open." ratio="wide" />
<Divider />
-That's the whole loop: a 90-unit promise became three jobs, a tree of made and bought parts, a forecast-aware plan, traceable work on the floor, a quality save, and a shipped, invoiced, fully-traceable robot. Every entity you saw (methods, kits, policies, operations, issues) has its own page in the Reference when you're ready for the detail.
+That's the whole loop: a 90-unit promise became three jobs, a tree of made and bought parts, a forecast-aware plan, traceable work on the floor, a quality save, and a shipped, invoiced, fully-traceable satellite. Every entity you saw (methods, kits, policies, operations, issues) has its own page in the Reference when you're ready for the detail.
diff --git a/docs/public/screens/build-job-method-explorer.png b/docs/public/screens/build-job-method-explorer.png
new file mode 100644
index 0000000000..ebdf38337e
Binary files /dev/null and b/docs/public/screens/build-job-method-explorer.png differ
diff --git a/docs/public/screens/build-subassembly-kit-toggle.png b/docs/public/screens/build-subassembly-kit-toggle.png
new file mode 100644
index 0000000000..e55252a27f
Binary files /dev/null and b/docs/public/screens/build-subassembly-kit-toggle.png differ
diff --git a/docs/public/screens/co-affected-item.png b/docs/public/screens/co-affected-item.png
new file mode 100644
index 0000000000..27cab5ea74
Binary files /dev/null and b/docs/public/screens/co-affected-item.png differ
diff --git a/docs/public/screens/co-new-notice.png b/docs/public/screens/co-new-notice.png
new file mode 100644
index 0000000000..1c84a1dc84
Binary files /dev/null and b/docs/public/screens/co-new-notice.png differ
diff --git a/docs/public/screens/co-release-diff.png b/docs/public/screens/co-release-diff.png
new file mode 100644
index 0000000000..fa647dbac5
Binary files /dev/null and b/docs/public/screens/co-release-diff.png differ
diff --git a/docs/public/screens/fa-depreciation-run.png b/docs/public/screens/fa-depreciation-run.png
new file mode 100644
index 0000000000..4c9a568939
Binary files /dev/null and b/docs/public/screens/fa-depreciation-run.png differ
diff --git a/docs/public/screens/fa-register.png b/docs/public/screens/fa-register.png
new file mode 100644
index 0000000000..b2ce9cf933
Binary files /dev/null and b/docs/public/screens/fa-register.png differ
diff --git a/docs/public/screens/fa-sell.png b/docs/public/screens/fa-sell.png
new file mode 100644
index 0000000000..bcf8e2d5ab
Binary files /dev/null and b/docs/public/screens/fa-sell.png differ
diff --git a/docs/public/screens/floor-mes-operation.png b/docs/public/screens/floor-mes-operation.png
new file mode 100644
index 0000000000..2f577cb06d
Binary files /dev/null and b/docs/public/screens/floor-mes-operation.png differ
diff --git a/docs/public/screens/floor-mes-schedule.png b/docs/public/screens/floor-mes-schedule.png
new file mode 100644
index 0000000000..9df89b1a20
Binary files /dev/null and b/docs/public/screens/floor-mes-schedule.png differ
diff --git a/docs/public/screens/floor-outside-operation.png b/docs/public/screens/floor-outside-operation.png
new file mode 100644
index 0000000000..5b105f7791
Binary files /dev/null and b/docs/public/screens/floor-outside-operation.png differ
diff --git a/docs/public/screens/floor-shopfloor-scan.png b/docs/public/screens/floor-shopfloor-scan.png
new file mode 100644
index 0000000000..9227a9ab3b
Binary files /dev/null and b/docs/public/screens/floor-shopfloor-scan.png differ
diff --git a/docs/public/screens/floor-work-instructions.png b/docs/public/screens/floor-work-instructions.png
new file mode 100644
index 0000000000..74fe199691
Binary files /dev/null and b/docs/public/screens/floor-work-instructions.png differ
diff --git a/docs/public/screens/job-completion.png b/docs/public/screens/job-completion.png
new file mode 100644
index 0000000000..b1953f1dbe
Binary files /dev/null and b/docs/public/screens/job-completion.png differ
diff --git a/docs/public/screens/job-production-events.png b/docs/public/screens/job-production-events.png
new file mode 100644
index 0000000000..8523e952f9
Binary files /dev/null and b/docs/public/screens/job-production-events.png differ
diff --git a/docs/public/screens/order-convert-line-to-job.png b/docs/public/screens/order-convert-line-to-job.png
new file mode 100644
index 0000000000..14e2c346fd
Binary files /dev/null and b/docs/public/screens/order-convert-line-to-job.png differ
diff --git a/docs/public/screens/order-dashboard.png b/docs/public/screens/order-dashboard.png
new file mode 100644
index 0000000000..63647f6335
Binary files /dev/null and b/docs/public/screens/order-dashboard.png differ
diff --git a/docs/public/screens/order-job-overview.png b/docs/public/screens/order-job-overview.png
new file mode 100644
index 0000000000..e822173a16
Binary files /dev/null and b/docs/public/screens/order-job-overview.png differ
diff --git a/docs/public/screens/otc-post-shipment.png b/docs/public/screens/otc-post-shipment.png
new file mode 100644
index 0000000000..1fcf2b4158
Binary files /dev/null and b/docs/public/screens/otc-post-shipment.png differ
diff --git a/docs/public/screens/otc-sales-invoice.png b/docs/public/screens/otc-sales-invoice.png
new file mode 100644
index 0000000000..ef48598c4f
Binary files /dev/null and b/docs/public/screens/otc-sales-invoice.png differ
diff --git a/docs/public/screens/plan-part-planning.png b/docs/public/screens/plan-part-planning.png
new file mode 100644
index 0000000000..d1cee77732
Binary files /dev/null and b/docs/public/screens/plan-part-planning.png differ
diff --git a/docs/public/screens/plan-production-planning.png b/docs/public/screens/plan-production-planning.png
new file mode 100644
index 0000000000..80314fe7cd
Binary files /dev/null and b/docs/public/screens/plan-production-planning.png differ
diff --git a/docs/public/screens/plan-projections.png b/docs/public/screens/plan-projections.png
new file mode 100644
index 0000000000..27050b8d3d
Binary files /dev/null and b/docs/public/screens/plan-projections.png differ
diff --git a/docs/public/screens/plan-purchasing-planning.png b/docs/public/screens/plan-purchasing-planning.png
new file mode 100644
index 0000000000..757b76b864
Binary files /dev/null and b/docs/public/screens/plan-purchasing-planning.png differ
diff --git a/docs/public/screens/plan-receive-po.png b/docs/public/screens/plan-receive-po.png
new file mode 100644
index 0000000000..24b645d2b3
Binary files /dev/null and b/docs/public/screens/plan-receive-po.png differ
diff --git a/docs/public/screens/platform-backups.png b/docs/public/screens/platform-backups.png
new file mode 100644
index 0000000000..b1fb0242ef
Binary files /dev/null and b/docs/public/screens/platform-backups.png differ
diff --git a/docs/public/screens/quote-builder.png b/docs/public/screens/quote-builder.png
new file mode 100644
index 0000000000..c703056e15
Binary files /dev/null and b/docs/public/screens/quote-builder.png differ
diff --git a/docs/public/screens/quote-digital-customer.png b/docs/public/screens/quote-digital-customer.png
new file mode 100644
index 0000000000..f765d23c08
Binary files /dev/null and b/docs/public/screens/quote-digital-customer.png differ
diff --git a/docs/public/screens/quote-sales-order.png b/docs/public/screens/quote-sales-order.png
new file mode 100644
index 0000000000..63647f6335
Binary files /dev/null and b/docs/public/screens/quote-sales-order.png differ
diff --git a/docs/public/screens/receive-post-receipt.png b/docs/public/screens/receive-post-receipt.png
new file mode 100644
index 0000000000..22f4e9415d
Binary files /dev/null and b/docs/public/screens/receive-post-receipt.png differ
diff --git a/docs/public/screens/receive-purchase-invoice.png b/docs/public/screens/receive-purchase-invoice.png
new file mode 100644
index 0000000000..25a1251ee3
Binary files /dev/null and b/docs/public/screens/receive-purchase-invoice.png differ
diff --git a/docs/public/screens/reference-parts-csv.png b/docs/public/screens/reference-parts-csv.png
new file mode 100644
index 0000000000..4fdaa3de3b
Binary files /dev/null and b/docs/public/screens/reference-parts-csv.png differ
diff --git a/docs/public/screens/rfq-purchase-order.png b/docs/public/screens/rfq-purchase-order.png
new file mode 100644
index 0000000000..faafe86b2b
Binary files /dev/null and b/docs/public/screens/rfq-purchase-order.png differ
diff --git a/docs/public/screens/rfq-supplier-comparison.png b/docs/public/screens/rfq-supplier-comparison.png
new file mode 100644
index 0000000000..7ea47932fc
Binary files /dev/null and b/docs/public/screens/rfq-supplier-comparison.png differ
diff --git a/docs/public/screens/rfq-supplier-portal.png b/docs/public/screens/rfq-supplier-portal.png
new file mode 100644
index 0000000000..448eb6e6cd
Binary files /dev/null and b/docs/public/screens/rfq-supplier-portal.png differ
diff --git a/docs/public/screens/ship-partial-shipment.png b/docs/public/screens/ship-partial-shipment.png
new file mode 100644
index 0000000000..378e085b8a
Binary files /dev/null and b/docs/public/screens/ship-partial-shipment.png differ
diff --git a/docs/public/screens/ship-procedure-versions.png b/docs/public/screens/ship-procedure-versions.png
new file mode 100644
index 0000000000..9e37a00345
Binary files /dev/null and b/docs/public/screens/ship-procedure-versions.png differ
diff --git a/docs/public/screens/ship-quality-issue.png b/docs/public/screens/ship-quality-issue.png
new file mode 100644
index 0000000000..d97a045802
Binary files /dev/null and b/docs/public/screens/ship-quality-issue.png differ
diff --git a/docs/public/screens/ship-traceability-graph.png b/docs/public/screens/ship-traceability-graph.png
new file mode 100644
index 0000000000..b9d86ec028
Binary files /dev/null and b/docs/public/screens/ship-traceability-graph.png differ
diff --git a/packages/database/src/seed-dev/helpers/items.ts b/packages/database/src/seed-dev/helpers/items.ts
index 806d11e880..fec1ad2c12 100644
--- a/packages/database/src/seed-dev/helpers/items.ts
+++ b/packages/database/src/seed-dev/helpers/items.ts
@@ -52,6 +52,7 @@ export async function createItem(ctx: Ctx, spec: ItemSpec): Promise<ItemRef> {
name: spec.name,
type: spec.type,
makeMethodId: mm?.id ?? null,
+ isMake,
unitCost: spec.standardCost ?? 0,
unitOfMeasureCode: uom
};
@@ -133,6 +134,7 @@ export async function createItem(ctx: Ctx, spec: ItemSpec): Promise<ItemRef> {
name: spec.name,
type: spec.type,
makeMethodId,
+ isMake,
unitCost: spec.standardCost ?? 0,
unitOfMeasureCode: uom
};
@@ -155,23 +157,48 @@ function extensionTableFor(type: ItemType): string {
}
}
+/**
+ * A Make component is a subassembly: `methodType` must say so, and
+ * `materialMakeMethodId` must point at the component's own active method, or the
+ * BOM renders as one flat level and the Subassembly/Kit control never appears.
+ */
export async function addBomLine(
ctx: Ctx,
makeMethodId: string,
componentItem: ItemRef,
quantity: number,
- order: number
-): Promise<void> {
- await insertId(ctx, "methodMaterial", {
+ order: number,
+ opts: { methodType?: MethodType; kit?: boolean } = {}
+): Promise<string> {
+ const methodType =
+ opts.methodType ??
+ (componentItem.isMake ? "Make to Order" : "Pull from Inventory");
+ const isSubassembly = methodType === "Make to Order";
+
+ return insertId(ctx, "methodMaterial", {
makeMethodId,
itemId: componentItem.id,
itemType: componentItem.type,
unitOfMeasureCode: componentItem.unitOfMeasureCode,
+ methodType,
+ materialMakeMethodId: isSubassembly ? componentItem.makeMethodId : null,
+ kit: opts.kit ?? false,
quantity,
order
});
}
+export type MethodType =
+ | "Make to Order"
+ | "Pull from Inventory"
+ | "Purchase to Order";
+
+export type OperationType =
+ | "Process"
+ | "Assembly"
+ | "Inspection"
+ | "Outside Processing";
+
export async function addBopOperation(
ctx: Ctx,
makeMethodId: string,
@@ -179,7 +206,19 @@ export async function addBopOperation(
workCenterId: string | undefined,
description: string,
order: number,
- opts: { laborTime?: number; laborUnit?: string; setupTime?: number } = {}
+ opts: {
+ laborTime?: number;
+ laborUnit?: string;
+ setupTime?: number;
+ machineTime?: number;
+ operationType?: OperationType;
+ // Required by the UI for an Outside Processing step — without it the job
+ // cannot be released and no supplier name renders on the operation.
+ operationSupplierProcessId?: string;
+ operationLeadTime?: number;
+ operationUnitCost?: number;
+ procedureId?: string;
+ } = {}
): Promise<string> {
return insertId(ctx, "methodOperation", {
makeMethodId,
@@ -189,6 +228,12 @@ export async function addBopOperation(
order,
laborTime: opts.laborTime ?? 0.5,
laborUnit: opts.laborUnit ?? "Hours/Piece",
- setupTime: opts.setupTime ?? 0
+ setupTime: opts.setupTime ?? 0,
+ machineTime: opts.machineTime ?? 0,
+ operationType: opts.operationType ?? "Process",
+ operationSupplierProcessId: opts.operationSupplierProcessId ?? null,
+ operationLeadTime: opts.operationLeadTime ?? 0,
+ operationUnitCost: opts.operationUnitCost ?? 0,
+ procedureId: opts.procedureId ?? null
});
}
diff --git a/packages/database/src/seed-dev/helpers/job-method.ts b/packages/database/src/seed-dev/helpers/job-method.ts
new file mode 100644
index 0000000000..b0c3c84ce4
--- /dev/null
+++ b/packages/database/src/seed-dev/helpers/job-method.ts
@@ -0,0 +1,326 @@
+import { insertId, maybeOne, rows } from "../sql.ts";
+import type { Ctx } from "../types.ts";
+
+/**
+ * Copies an item's active make method onto a job, the way the `get-method` edge
+ * function's `itemToJob` path does at runtime.
+ *
+ * The seed runs as one SQL transaction and cannot invoke an edge function, so
+ * without this every seeded job has a bare `jobMakeMethod` (the insert
+ * interceptor creates that much) and nothing else — no operations, no
+ * materials, no subassembly tree. That is what left the job pages, the MES
+ * schedule board and the method explorer empty.
+ *
+ * Deliberately narrower than the edge function: no configuration rules, no
+ * supersession redirect, no tool or parameter copy. Those need runtime inputs
+ * the seed has no opinion about. Procedure steps ARE copied — without them the
+ * operator's Instructions tab is blank.
+ */
+
+type MethodOperationRow = {
+ id: string;
+ order: number;
+ processId: string;
+ workCenterId: string | null;
+ description: string;
+ setupTime: string;
+ setupUnit: string;
+ laborTime: string;
+ laborUnit: string;
+ machineTime: string;
+ machineUnit: string;
+ operationOrder: string;
+ operationType: string;
+ operationSupplierProcessId: string | null;
+ operationLeadTime: string | null;
+ operationUnitCost: string | null;
+ procedureId: string | null;
+};
+
+type MethodMaterialRow = {
+ id: string;
+ itemId: string;
+ itemType: string;
+ methodType: string;
+ materialMakeMethodId: string | null;
+ quantity: string;
+ order: number;
+ methodOperationId: string | null;
+ unitOfMeasureCode: string;
+ kit: boolean;
+ description: string | null;
+ itemTrackingType: string;
+ unitCost: string | null;
+};
+
+type Rates = {
+ laborRate: number;
+ machineRate: number;
+ overheadRate: number;
+};
+
+export type JobOperationStatus =
+ | "Todo"
+ | "Ready"
+ | "Waiting"
+ | "In Progress"
+ | "Paused"
+ | "Done"
+ | "Canceled";
+
+export type CopyMethodResult = {
+ operations: number;
+ materials: number;
+ levels: number;
+};
+
+/**
+ * @param operationStatus status for every copied operation. The caller decides:
+ * a Draft job's operations are Todo, a released job's are Ready.
+ */
+export async function copyMethodToJob(
+ ctx: Ctx,
+ jobId: string,
+ quantity: number,
+ operationStatus: JobOperationStatus = "Todo"
+): Promise<CopyMethodResult> {
+ const { client, companyId } = ctx;
+
+ const root = await maybeOne<{ id: string; itemId: string }>(
+ client,
+ `SELECT id, "itemId" FROM "jobMakeMethod"
+ WHERE "jobId" = $1 AND "parentMaterialId" IS NULL AND "companyId" = $2
+ LIMIT 1`,
+ [jobId, companyId]
+ );
+ if (!root) {
+ throw new Error(`Seed: job ${jobId} has no root jobMakeMethod`);
+ }
+
+ const makeMethod = await activeMakeMethod(ctx, root.itemId);
+ if (!makeMethod) return { operations: 0, materials: 0, levels: 0 };
+
+ const result: CopyMethodResult = { operations: 0, materials: 0, levels: 0 };
+ await copyLevel(
+ ctx,
+ jobId,
+ makeMethod,
+ root.id,
+ quantity,
+ operationStatus,
+ result,
+ new Set([makeMethod])
+ );
+ return result;
+}
+
+async function activeMakeMethod(
+ ctx: Ctx,
+ itemId: string
+): Promise<string | null> {
+ const row = await maybeOne<{ id: string }>(
+ ctx.client,
+ `SELECT id FROM "makeMethod"
+ WHERE "itemId" = $1 AND "companyId" = $2 AND status = 'Active'
+ ORDER BY version DESC
+ LIMIT 1`,
+ [itemId, ctx.companyId]
+ );
+ return row?.id ?? null;
+}
+
+async function ratesFor(ctx: Ctx, workCenterId: string | null): Promise<Rates> {
+ if (!workCenterId) return { laborRate: 0, machineRate: 0, overheadRate: 0 };
+ const row = await maybeOne<{
+ laborRate: string;
+ machineRate: string;
+ overheadRate: string;
+ }>(
+ ctx.client,
+ `SELECT "laborRate", "machineRate", "overheadRate" FROM "workCenter" WHERE id = $1`,
+ [workCenterId]
+ );
+ return {
+ laborRate: Number(row?.laborRate ?? 0),
+ machineRate: Number(row?.machineRate ?? 0),
+ overheadRate: Number(row?.overheadRate ?? 0)
+ };
+}
+
+// The operator's Instructions tab reads jobOperationStep, not the procedure —
+// the steps are snapshotted onto the operation so a later procedure revision
+// cannot rewrite what the floor was told to do.
+async function copyProcedureSteps(
+ ctx: Ctx,
+ procedureId: string,
+ jobOperationId: string
+): Promise<void> {
+ await ctx.client.query(
+ `INSERT INTO "jobOperationStep"
+ ("name", "required", "sortOrder", "type", "unitOfMeasureCode",
+ "minValue", "maxValue", "listValues", "fileTypes", "description",
+ "operationId", "companyId", "createdBy")
+ SELECT ps."name", ps."required", ps."sortOrder", ps."type", ps."unitOfMeasureCode",
+ ps."minValue", ps."maxValue", ps."listValues", ps."fileTypes", ps."description",
+ $2, $3, $4
+ FROM "procedureStep" ps
+ WHERE ps."procedureId" = $1
+ ORDER BY ps."sortOrder"`,
+ [procedureId, jobOperationId, ctx.companyId, ctx.userId]
+ );
+}
+
+async function adoptChildMakeMethod(
+ ctx: Ctx,
+ jobId: string,
+ jobMaterialId: string,
+ quantityPerParent: number
+): Promise<string | null> {
+ const row = await maybeOne<{ id: string }>(
+ ctx.client,
+ `UPDATE "jobMakeMethod" SET "quantityPerParent" = $4
+ WHERE "jobId" = $1 AND "parentMaterialId" = $2 AND "companyId" = $3
+ RETURNING id`,
+ [jobId, jobMaterialId, ctx.companyId, quantityPerParent]
+ );
+ return row?.id ?? null;
+}
+
+// `visited` guards against a BOM that references itself through a chain — the
+// DB only blocks the one-node case, and an infinite recursion here would hang
+// the seed inside an open transaction.
+async function copyLevel(
+ ctx: Ctx,
+ jobId: string,
+ makeMethodId: string,
+ jobMakeMethodId: string,
+ extendedQuantity: number,
+ operationStatus: JobOperationStatus,
+ result: CopyMethodResult,
+ visited: Set<string>
+): Promise<void> {
+ const { client, companyId } = ctx;
+ result.levels += 1;
+
+ const operations = await rows<MethodOperationRow>(
+ client,
+ `SELECT id, "order", "processId", "workCenterId", description,
+ "setupTime", "setupUnit"::text, "laborTime", "laborUnit"::text,
+ "machineTime", "machineUnit"::text, "operationOrder"::text,
+ "operationType"::text, "operationSupplierProcessId",
+ "operationLeadTime", "operationUnitCost", "procedureId"
+ FROM "methodOperation"
+ WHERE "makeMethodId" = $1 AND "companyId" = $2
+ ORDER BY "order"`,
+ [makeMethodId, companyId]
+ );
+
+ // methodOperation.id -> jobOperation.id, so a material can keep the operation
+ // it is consumed at.
+ const operationMap = new Map<string, string>();
+ for (const op of operations) {
+ const rates = await ratesFor(ctx, op.workCenterId);
+ const jobOperationId = await insertId(ctx, "jobOperation", {
+ jobId,
+ jobMakeMethodId,
+ order: op.order,
+ operationOrder: op.operationOrder,
+ processId: op.processId,
+ workCenterId: op.workCenterId,
+ description: op.description,
+ setupTime: op.setupTime,
+ setupUnit: op.setupUnit,
+ laborTime: op.laborTime,
+ laborUnit: op.laborUnit,
+ machineTime: op.machineTime,
+ machineUnit: op.machineUnit,
+ operationType: op.operationType,
+ operationSupplierProcessId: op.operationSupplierProcessId,
+ operationLeadTime: op.operationLeadTime ?? 0,
+ operationUnitCost: op.operationUnitCost ?? 0,
+ procedureId: op.procedureId,
+ laborRate: rates.laborRate,
+ machineRate: rates.machineRate,
+ overheadRate: rates.overheadRate,
+ operationQuantity: extendedQuantity,
+ targetQuantity: extendedQuantity,
+ status: operationStatus
+ });
+ operationMap.set(op.id, jobOperationId);
+ if (op.procedureId)
+ await copyProcedureSteps(ctx, op.procedureId, jobOperationId);
+ result.operations += 1;
+ }
+
+ const materials = await rows<MethodMaterialRow>(
+ client,
+ `SELECT mm.id, mm."itemId", mm."itemType", mm."methodType"::text,
+ mm."materialMakeMethodId", mm.quantity, mm."order",
+ mm."methodOperationId", mm."unitOfMeasureCode", mm.kit,
+ i.name AS description, i."itemTrackingType"::text, ic."standardCost" AS "unitCost"
+ FROM "methodMaterial" mm
+ JOIN item i ON i.id = mm."itemId"
+ LEFT JOIN "itemCost" ic ON ic."itemId" = mm."itemId"
+ WHERE mm."makeMethodId" = $1 AND mm."companyId" = $2
+ ORDER BY mm."order"`,
+ [makeMethodId, companyId]
+ );
+
+ for (const material of materials) {
+ const perParent = Number(material.quantity);
+ const childExtended = perParent * extendedQuantity;
+ const isSubassembly = material.methodType === "Make to Order";
+
+ const jobMaterialId = await insertId(ctx, "jobMaterial", {
+ jobId,
+ jobMakeMethodId,
+ jobOperationId: material.methodOperationId
+ ? (operationMap.get(material.methodOperationId) ?? null)
+ : null,
+ itemId: material.itemId,
+ itemType: material.itemType,
+ methodType: material.methodType,
+ kit: material.kit,
+ order: material.order,
+ description: material.description ?? material.itemId,
+ quantity: perParent,
+ estimatedQuantity: childExtended,
+ unitOfMeasureCode: material.unitOfMeasureCode,
+ unitCost: material.unitCost ?? 0,
+ requiresSerialTracking: material.itemTrackingType === "Serial",
+ requiresBatchTracking: material.itemTrackingType === "Batch"
+ });
+ result.materials += 1;
+
+ if (!isSubassembly) continue;
+
+ const childMakeMethodId =
+ material.materialMakeMethodId ??
+ (await activeMakeMethod(ctx, material.itemId));
+ if (!childMakeMethodId || visited.has(childMakeMethodId)) continue;
+
+ // The `sync_insert_job_material_make_method` interceptor already created this
+ // row (and its Reserved trackedEntity) the moment the Make-to-Order material
+ // was inserted. Inserting a second one gives the method explorer two identical
+ // branches per subassembly. Adopt the interceptor's row and fill in what it
+ // does not know.
+ const childJobMakeMethodId = await adoptChildMakeMethod(
+ ctx,
+ jobId,
+ jobMaterialId,
+ perParent
+ );
+ if (!childJobMakeMethodId) continue;
+
+ await copyLevel(
+ ctx,
+ jobId,
+ childMakeMethodId,
+ childJobMakeMethodId,
+ childExtended,
+ operationStatus,
+ result,
+ new Set([...visited, childMakeMethodId])
+ );
+ }
+}
diff --git a/packages/database/src/seed-dev/tiers/01-foundation.ts b/packages/database/src/seed-dev/tiers/01-foundation.ts
index 85cbf148de..0b5e2a3311 100644
--- a/packages/database/src/seed-dev/tiers/01-foundation.ts
+++ b/packages/database/src/seed-dev/tiers/01-foundation.ts
@@ -1,6 +1,27 @@
-import { insertId, insertRow, one, rows } from "../sql.ts";
+import { insertId, insertRow, one, RICH, rows } from "../sql.ts";
import type { Ctx } from "../types.ts";
+type ProcedureStepSpec = {
+ name: string;
+ type: "Task" | "Checkbox" | "Measurement" | "Value" | "List" | "Person";
+ instruction: string;
+ required?: boolean;
+ unitOfMeasureCode?: string;
+ minValue?: number;
+ maxValue?: number;
+};
+
+type ProcedureSpec = {
+ name: string;
+ process: string;
+ description: string;
+ versions: Array<{
+ version: number;
+ status: "Draft" | "Active" | "Archived";
+ steps: ProcedureStepSpec[];
+ }>;
+};
+
// ---------------------------------------------------------------------------
// Satellites / spacecraft theme — Orbital Systems Inc.
// ---------------------------------------------------------------------------
@@ -231,7 +252,168 @@ const SUPPLIER_CONTACTS = [
// Supplier processes for the contract manufacturer
const SUPPLIER_PROCESSES = [
{ supplier: "AstroMill Machining", process: "Machining" },
- { supplier: "AstroMill Machining", process: "Welding" }
+ { supplier: "AstroMill Machining", process: "Welding" },
+ // Backs the outside-processing (anodize) step on the structural frame.
+ { supplier: "AstroMill Machining", process: "Outside Processing" }
+];
+
+const STRUCTURAL_STEPS_V2: ProcedureStepSpec[] = [
+ {
+ name: "Verify panel kit against the pick list",
+ type: "Checkbox",
+ instruction:
+ "Confirm all six machined panels and both bracket sets are present and match the drawing revision on the traveler."
+ },
+ {
+ name: "Torque corner fasteners",
+ type: "Measurement",
+ instruction:
+ "Torque the M6 corner fasteners in a star pattern. Record the final torque wrench reading.",
+ unitOfMeasureCode: "EA",
+ minValue: 8,
+ maxValue: 10
+ },
+ {
+ name: "Measure diagonal squareness",
+ type: "Measurement",
+ instruction:
+ "Measure both diagonals across the frame. The difference must stay inside 0.5 mm.",
+ unitOfMeasureCode: "EA",
+ minValue: 0,
+ maxValue: 0.5
+ },
+ {
+ name: "Record assembler",
+ type: "Person",
+ instruction: "Sign off as the assembler responsible for this frame."
+ },
+ {
+ name: "Bag and label for clean room transfer",
+ type: "Task",
+ instruction:
+ "Bag the frame in ESD-safe film, apply the job label, and stage it on the clean room transfer cart.",
+ required: false
+ }
+];
+
+const PROCEDURES: ProcedureSpec[] = [
+ {
+ name: "Structural Frame Assembly",
+ process: "Clean Room Assembly",
+ description:
+ "Assembly and torque procedure for the ESPA-class structural frame.",
+ versions: [
+ {
+ version: 1,
+ status: "Archived",
+ steps: [
+ {
+ name: "Verify panel kit against the pick list",
+ type: "Checkbox",
+ instruction: "Confirm all machined panels are present."
+ },
+ {
+ name: "Torque corner fasteners",
+ type: "Measurement",
+ instruction:
+ "Torque the M6 corner fasteners in a star pattern to 9 Nm.",
+ unitOfMeasureCode: "EA",
+ minValue: 8.5,
+ maxValue: 9.5
+ }
+ ]
+ },
+ { version: 2, status: "Active", steps: STRUCTURAL_STEPS_V2 }
+ ]
+ },
+ {
+ name: "Satellite Systems Integration",
+ process: "Clean Room Assembly",
+ description:
+ "Clean room integration of the bus subsystems into the SAT-1000 airframe.",
+ versions: [
+ {
+ version: 1,
+ status: "Active",
+ steps: [
+ {
+ name: "Stage subsystems in the clean room",
+ type: "Checkbox",
+ instruction:
+ "Move the structural frame, power subsystem, avionics stack, comms payload and propulsion module into Bay A and confirm each serial against the traveler."
+ },
+ {
+ name: "Mate avionics stack to the frame",
+ type: "Task",
+ instruction:
+ "Seat the avionics stack on its rails, engage the captive fasteners and confirm the ground strap is bonded."
+ },
+ {
+ name: "Route and dress the harness",
+ type: "Checkbox",
+ instruction:
+ "Route HARNESS-001 through the frame raceways, tie at every bracket and confirm no connector is under strain."
+ },
+ {
+ name: "Measure stowed mass",
+ type: "Measurement",
+ instruction:
+ "Weigh the integrated bus with the wings stowed and record the mass in pounds.",
+ unitOfMeasureCode: "LB",
+ minValue: 305,
+ maxValue: 335
+ },
+ {
+ name: "Record integration lead",
+ type: "Person",
+ instruction:
+ "Sign off as the integration lead responsible for this bus."
+ }
+ ]
+ }
+ ]
+ },
+ {
+ name: "TVAC Qualification Test",
+ process: "Thermal Vacuum Test",
+ description:
+ "Thermal vacuum qualification cycle for an integrated satellite bus.",
+ versions: [
+ {
+ version: 1,
+ status: "Active",
+ steps: [
+ {
+ name: "Install harness and thermocouples",
+ type: "Task",
+ instruction:
+ "Route the test harness through the chamber feedthrough and bond thermocouples to the four survey points."
+ },
+ {
+ name: "Pump down to test pressure",
+ type: "Measurement",
+ instruction:
+ "Pump the chamber down and record the pressure once it stabilises.",
+ unitOfMeasureCode: "EA",
+ minValue: 0,
+ maxValue: 0.00001
+ },
+ {
+ name: "Run eight thermal cycles",
+ type: "Checkbox",
+ instruction:
+ "Cycle between -20 C and +60 C, dwelling one hour at each extreme. Tick once all eight cycles complete."
+ },
+ {
+ name: "Functional check at hot soak",
+ type: "Checkbox",
+ instruction:
+ "Command the bus through the functional script during the final hot dwell and confirm all telemetry is nominal."
+ }
+ ]
+ }
+ ]
+ }
];
const SHIPPING_METHODS = [
@@ -329,6 +511,15 @@ export async function runTier1(ctx: Ctx): Promise<void> {
ctx.refs.locations.Plant = plantId;
ctx.refs.locations.HQ = locationId;
+ // Every job and work center lives at the plant, and both the MES board and
+ // the ERP's location-scoped pages read the signed-in user's default location.
+ // Leave that at HQ and the shop floor renders empty.
+ await ctx.client.query(
+ `UPDATE "employeeJob" SET "locationId" = $2 WHERE "companyId" = $1`,
+ [ctx.companyId, plantId]
+ );
+ // (`userDefaults` is a view over employeeJob — the UPDATE above is what moves it.)
+
// ── Warehouses ────────────────────────────────────────────────────────────
ctx.log("warehouses");
ctx.refs.warehouses.Main = await insertId(ctx, "warehouse", {
@@ -611,11 +802,12 @@ export async function runTier1(ctx: Ctx): Promise<void> {
const supplierId = ctx.refs.suppliers[sp.supplier];
const processId = ctx.refs.processes[sp.process];
if (supplierId && processId) {
- await insertId(ctx, "supplierProcess", {
+ const spId = await insertId(ctx, "supplierProcess", {
supplierId,
processId,
leadTime: 5
});
+ ctx.refs.misc[`sp:${sp.supplier}:${sp.process}`] = spId;
}
}
@@ -678,6 +870,40 @@ export async function runTier1(ctx: Ctx): Promise<void> {
companyId
});
+ // ── Procedures (shop-floor work instructions) ─────────────────────────────
+ // Two versions of the same name: the version menu groups on `name`, so V1
+ // Archived + V2 Active is what gives a procedure a readable history.
+ ctx.log("procedures");
+ for (const spec of PROCEDURES) {
+ const processId = ctx.refs.processes[spec.process];
+ if (!processId) continue;
+ for (const version of spec.versions) {
+ const procedureId = await insertId(ctx, "procedure", {
+ name: spec.name,
+ processId,
+ version: version.version,
+ status: version.status,
+ content: RICH(spec.description)
+ });
+ if (version.status === "Active") {
+ ctx.refs.misc[`procedure:${spec.name}`] = procedureId;
+ }
+ for (const [index, step] of version.steps.entries()) {
+ await insertId(ctx, "procedureStep", {
+ procedureId,
+ name: step.name,
+ type: step.type,
+ sortOrder: index + 1,
+ required: step.required ?? true,
+ unitOfMeasureCode: step.unitOfMeasureCode ?? null,
+ minValue: step.minValue ?? null,
+ maxValue: step.maxValue ?? null,
+ description: RICH(step.instruction)
+ });
+ }
+ }
+ }
+
// ── Cost centers ───────────────────────────────────────────────────────────
ctx.log("cost centers");
for (const name of [
diff --git a/packages/database/src/seed-dev/tiers/02-items.ts b/packages/database/src/seed-dev/tiers/02-items.ts
index 2d9efd5798..3c0be38503 100644
--- a/packages/database/src/seed-dev/tiers/02-items.ts
+++ b/packages/database/src/seed-dev/tiers/02-items.ts
@@ -26,6 +26,9 @@ const BUY_PARTS: ItemSpec[] = [
name: "Li-Ion Battery Pack 48V 100Wh",
type: "Part",
replenishment: "Buy",
+ // Batch-tracked: receiving captures a lot, and the lot is what gets scanned
+ // into an assembly on the floor.
+ trackingType: "Batch",
standardCost: 2400,
unitSalePrice: 3600,
leadTime: 60
@@ -43,6 +46,7 @@ const BUY_PARTS: ItemSpec[] = [
name: "Reaction Wheel 0.010 Nm",
type: "Part",
replenishment: "Buy",
+ trackingType: "Serial",
standardCost: 14500,
unitSalePrice: 21750,
leadTime: 90
@@ -128,6 +132,7 @@ const MATERIALS: ItemSpec[] = [
readableId: "MAT-AL7075-PLT",
name: "Aluminum 7075-T651 Plate",
type: "Material",
+ trackingType: "Batch",
standardCost: 12,
unitOfMeasureCode: "LB",
leadTime: 10
@@ -224,6 +229,8 @@ const MAKE_PARTS: ItemSpec[] = [
name: "ESPA-Class Smallsat Bus (Complete)",
type: "Part",
replenishment: "Make",
+ // Serial-tracked: each satellite gets its own genealogy in traceability.
+ trackingType: "Serial",
standardCost: 0,
unitSalePrice: 1800000
},
@@ -364,6 +371,10 @@ export async function runTier2(ctx: Ctx): Promise<void> {
return ref;
}
+ // Fractional per-unit quantities are kept to halves, quarters and eighths.
+ // Extended quantity is float multiplication, so 0.05 x 3 renders as
+ // 0.15000000000000002 on the shop floor — these values multiply out clean.
+
// -- Structural Frame (BUS-STR-001) --
{
const mm = needMM(i, "BUS-STR-001");
@@ -371,7 +382,7 @@ export async function runTier2(ctx: Ctx): Promise<void> {
await addBomLine(ctx, mm, need("FST-M4-TI"), 48, 2);
await addBomLine(ctx, mm, need("FST-M6-A286"), 24, 3);
await addBomLine(ctx, mm, need("BRG-6201"), 4, 4);
- await addBomLine(ctx, mm, need("CN-GREASE-001"), 0.05, 5);
+ await addBomLine(ctx, mm, need("CN-GREASE-001"), 0.25, 5);
await addBopOperation(
ctx,
mm,
@@ -390,14 +401,36 @@ export async function runTier2(ctx: Ctx): Promise<void> {
2,
{ laborTime: 2 }
);
+ // Sent out to AstroMill for hard anodize between welding and assembly.
+ await addBopOperation(
+ ctx,
+ mm,
+ pr["Outside Processing"]!,
+ undefined,
+ "Hard anodize (Type III) at supplier",
+ 3,
+ {
+ operationType: "Outside Processing",
+ operationSupplierProcessId:
+ ctx.refs.misc["sp:AstroMill Machining:Outside Processing"],
+ operationLeadTime: 7,
+ operationUnitCost: 240,
+ laborTime: 0,
+ laborUnit: "Total Hours"
+ }
+ );
await addBopOperation(
ctx,
mm,
pr["Clean Room Assembly"]!,
wc["Clean Room Bay A"],
"Final assembly & torque",
- 3,
- { laborTime: 3 }
+ 4,
+ {
+ laborTime: 3,
+ // Gives the MES operation screen an Instructions tab with real steps.
+ procedureId: ctx.refs.misc["procedure:Structural Frame Assembly"]
+ }
);
}
@@ -405,7 +438,7 @@ export async function runTier2(ctx: Ctx): Promise<void> {
{
const mm = needMM(i, "SAW-001");
await addBomLine(ctx, mm, need("MAT-GAAS-CELL"), 64, 1);
- await addBomLine(ctx, mm, need("MAT-CF-LAM"), 0.8, 2);
+ await addBomLine(ctx, mm, need("MAT-CF-LAM"), 0.75, 2);
await addBomLine(ctx, mm, need("MAT-KAPTON"), 2.5, 3);
await addBopOperation(
ctx,
@@ -440,8 +473,8 @@ export async function runTier2(ctx: Ctx): Promise<void> {
{
const mm = needMM(i, "PCB-EPS-R1");
await addBomLine(ctx, mm, need("PCB-BARE-REV3"), 1, 1);
- await addBomLine(ctx, mm, need("MAT-SYLGARD"), 0.05, 2);
- await addBomLine(ctx, mm, need("MAT-CONFCOAT"), 0.1, 3);
+ await addBomLine(ctx, mm, need("MAT-SYLGARD"), 0.25, 2);
+ await addBomLine(ctx, mm, need("MAT-CONFCOAT"), 0.125, 3);
await addBopOperation(
ctx,
mm,
@@ -475,7 +508,7 @@ export async function runTier2(ctx: Ctx): Promise<void> {
{
const mm = needMM(i, "PCB-ADCS-R1");
await addBomLine(ctx, mm, need("PCB-BARE-REV3"), 1, 1);
- await addBomLine(ctx, mm, need("MAT-CONFCOAT"), 0.08, 2);
+ await addBomLine(ctx, mm, need("MAT-CONFCOAT"), 0.125, 2);
await addBopOperation(
ctx,
mm,
@@ -563,8 +596,8 @@ export async function runTier2(ctx: Ctx): Promise<void> {
// -- Patch Antenna (ANT-PATCH-01) --
{
const mm = needMM(i, "ANT-PATCH-01");
- await addBomLine(ctx, mm, need("MAT-CF-LAM"), 0.1, 1);
- await addBomLine(ctx, mm, need("MAT-KAPTON"), 0.3, 2);
+ await addBomLine(ctx, mm, need("MAT-CF-LAM"), 0.125, 1);
+ await addBomLine(ctx, mm, need("MAT-KAPTON"), 0.25, 2);
await addBopOperation(
ctx,
mm,
@@ -680,7 +713,14 @@ export async function runTier2(ctx: Ctx): Promise<void> {
wc["Clean Room Bay A"],
"Systems integration",
1,
- { laborTime: 16 }
+ // Assembly (not Process) so the MES routes this operation to the assembly
+ // view, where tracked components are scanned into the serial being built.
+ {
+ laborTime: 16,
+ operationType: "Assembly",
+ // Gives the MES assembly view its step checklist.
+ procedureId: ctx.refs.misc["procedure:Satellite Systems Integration"]
+ }
);
await addBopOperation(
ctx,
@@ -689,7 +729,11 @@ export async function runTier2(ctx: Ctx): Promise<void> {
wc["TVAC Chamber 1"],
"TVAC qualification test",
2,
- { laborTime: 72, laborUnit: "Total Hours" }
+ {
+ laborTime: 72,
+ laborUnit: "Total Hours",
+ procedureId: ctx.refs.misc["procedure:TVAC Qualification Test"]
+ }
);
await addBopOperation(
ctx,
diff --git a/packages/database/src/seed-dev/tiers/03-inventory.ts b/packages/database/src/seed-dev/tiers/03-inventory.ts
index 6ec5f9efbb..265adfbbe0 100644
--- a/packages/database/src/seed-dev/tiers/03-inventory.ts
+++ b/packages/database/src/seed-dev/tiers/03-inventory.ts
@@ -30,6 +30,36 @@ const OPENING_STOCK: Array<{
{ item: "CN-GREASE-001", qty: 2, cost: 95, shelf: "A1-L3" }
];
+// Lots/serials that back the tracked slice of the opening stock above.
+const ON_HAND_TRACKED: Array<{
+ item: string;
+ entities: Array<{ readableId: string; quantity: number }>;
+}> = [
+ {
+ item: "BAT-LIION-48V",
+ entities: [
+ { readableId: "LOT-BAT-2607", quantity: 2 },
+ { readableId: "LOT-BAT-2608", quantity: 1 }
+ ]
+ },
+ {
+ item: "RW-010",
+ entities: [
+ { readableId: "RW010-SN-0051", quantity: 1 },
+ { readableId: "RW010-SN-0052", quantity: 1 },
+ { readableId: "RW010-SN-0053", quantity: 1 },
+ { readableId: "RW010-SN-0054", quantity: 1 }
+ ]
+ },
+ {
+ item: "MAT-AL7075-PLT",
+ entities: [
+ { readableId: "LOT-AL7075-2608", quantity: 40 },
+ { readableId: "LOT-AL7075-2609", quantity: 20 }
+ ]
+ }
+];
+
export async function runTier3(ctx: Ctx): Promise<void> {
const { companyId, userId, locationId } = ctx;
const plantId = ctx.refs.locations.Plant ?? locationId;
@@ -54,6 +84,29 @@ export async function runTier3(ctx: Ctx): Promise<void> {
});
}
+ // ── Lots and serials on hand ──────────────────────────────────────────────
+ // A batch- or serial-tracked part is only issuable if a tracked entity for it
+ // is Available — without these the shop floor's scan-material picker is empty
+ // even though the item shows stock.
+ ctx.log("available lots and serials");
+ for (const stock of ON_HAND_TRACKED) {
+ const itemRef = ctx.refs.items[stock.item];
+ if (!itemRef) continue;
+ for (const entity of stock.entities) {
+ await insertId(ctx, "trackedEntity", {
+ quantity: entity.quantity,
+ status: "Available",
+ sourceDocument: "Item",
+ sourceDocumentId: itemRef.id,
+ sourceDocumentReadableId: itemRef.readableId,
+ readableId: entity.readableId,
+ itemId: itemRef.id,
+ attributes: JSON.stringify({}),
+ updatedBy: userId
+ });
+ }
+ }
+
// ── Kanbans (auto-replenishment cards) for high-usage buy parts ───────────
ctx.log("kanban cards");
const kanbanItems: Array<{ item: string; qty: number; supplier: string }> = [
diff --git a/packages/database/src/seed-dev/tiers/04-sales.ts b/packages/database/src/seed-dev/tiers/04-sales.ts
index 762886ad48..bf23c2b0a0 100644
--- a/packages/database/src/seed-dev/tiers/04-sales.ts
+++ b/packages/database/src/seed-dev/tiers/04-sales.ts
@@ -5,6 +5,75 @@ import type { Ctx } from "../types.ts";
// test for the whole seed. Every detail page (opportunity, rfq, quote,
// salesOrder, shipment, salesInvoice) must open without a 500 or redirect.
+// Only these four columns are stored on quoteLinePrice — every net* and
+// converted* column is GENERATED ALWAYS from them.
+type PriceBreak = {
+ quantity: number;
+ unitPrice: number;
+ leadTime: number;
+ discountPercent?: number;
+ shippingCost?: number;
+};
+
+// The public page filters price rows against the line's own quantity array, so
+// a break that isn't in quoteLine.quantity is invisible. Keep the two in step.
+const SAT_PRICE_BREAKS: readonly PriceBreak[] = [
+ { quantity: 1, unitPrice: 1950000, leadTime: 240 },
+ { quantity: 5, unitPrice: 1840000, leadTime: 270, discountPercent: 0.03 },
+ { quantity: 10, unitPrice: 1725000, leadTime: 300, discountPercent: 0.06 },
+ { quantity: 25, unitPrice: 1580000, leadTime: 360, discountPercent: 0.1 }
+];
+const SAT_BREAK_QUANTITIES = SAT_PRICE_BREAKS.map((b) => b.quantity);
+
+const EPS_PRICE_BREAKS: readonly PriceBreak[] = [
+ { quantity: 2, unitPrice: 128000, leadTime: 120 },
+ {
+ quantity: 10,
+ unitPrice: 118000,
+ leadTime: 150,
+ discountPercent: 0.05,
+ shippingCost: 2400
+ }
+];
+const EPS_BREAK_QUANTITIES = EPS_PRICE_BREAKS.map((b) => b.quantity);
+
+// The Sent quote is the one the docs screenshot at /share/quote/:externalLinkId,
+// so the link id is fixed rather than generated — the URL has to survive a
+// re-seed. expiresAt / expirationDate must stay ahead of "today" or the public
+// page renders its Expired state instead of the quote.
+const NOVASAT_QUOTE_LINK_ID = "5eed0000-0000-4000-8000-000000000001";
+const NOVASAT_QUOTE_EXPIRATION = "2027-06-30";
+
+// Three deliveries of the same make part, three weeks apart. Gives the docs a
+// real delivery schedule, and three Make to Order lines with no job attached is
+// what puts the "Jobs Required" / Create Jobs card on the order.
+const STAGGERED_DELIVERIES = [
+ { key: "1", promisedDate: "2026-09-04", sortOrder: 1 },
+ { key: "2", promisedDate: "2026-09-25", sortOrder: 2 },
+ { key: "3", promisedDate: "2026-10-16", sortOrder: 3 }
+] as const;
+
+async function insertPriceBreaks(
+ ctx: Ctx,
+ quoteId: string,
+ quoteLineId: string,
+ breaks: readonly PriceBreak[]
+): Promise<void> {
+ for (const brk of breaks) {
+ await insertRow(ctx, "quoteLinePrice", {
+ quoteId,
+ quoteLineId,
+ quantity: brk.quantity,
+ unitPrice: brk.unitPrice,
+ leadTime: brk.leadTime,
+ discountPercent: brk.discountPercent ?? 0,
+ shippingCost: brk.shippingCost ?? 0,
+ exchangeRate: 1,
+ priceSource: "system"
+ });
+ }
+}
+
export async function runTier4(ctx: Ctx): Promise<void> {
const { companyId, userId, locationId } = ctx;
const plantId = ctx.refs.locations.Plant ?? locationId;
@@ -33,6 +102,26 @@ export async function runTier4(ctx: Ctx): Promise<void> {
const commsItem = ctx.refs.items["COMMS-001"]!;
const propItem = ctx.refs.items["PROP-001"]!;
const harnessItem = ctx.refs.items["HARNESS-001"]!;
+ const sawItem = ctx.refs.items["SAW-001"]!;
+
+ // companySettings has no companyId column, so the wipe preserves it — the row
+ // already exists and only needs the digital-quote flags flipped on. Without
+ // digitalQuoteEnabled the public quote page renders no Accept/Reject buttons,
+ // and without digitalQuoteIncludesPurchaseOrders the PO-upload field is gone.
+ ctx.log("company settings — digital quotes enabled");
+ await insertRow(
+ ctx,
+ "companySettings",
+ {
+ id: companyId,
+ digitalQuoteEnabled: true,
+ digitalQuoteIncludesPurchaseOrders: true
+ },
+ {
+ onConflict:
+ '("id") DO UPDATE SET "digitalQuoteEnabled" = true, "digitalQuoteIncludesPurchaseOrders" = true'
+ }
+ );
// ── Opportunity 1: ORBSEC — complete chain (rfq → quote → SO → shipment → invoice) ──
ctx.log("opportunity 1 — full chain (ORBSEC)");
@@ -87,7 +176,7 @@ export async function runTier4(ctx: Ctx): Promise<void> {
shippingMethodId,
companyId
});
- await insertId(ctx, "quoteLine", {
+ const quote1Line = await insertId(ctx, "quoteLine", {
quoteId: quote1,
itemId: satItem.id,
itemType: "Part",
@@ -98,7 +187,11 @@ export async function runTier4(ctx: Ctx): Promise<void> {
status: "Complete",
sortOrder: 1
});
+ await insertPriceBreaks(ctx, quote1, quote1Line, [
+ { quantity: 3, unitPrice: 1800000, leadTime: 260 }
+ ]);
ctx.refs.documents["quote:orbsec"] = quote1;
+ ctx.refs.documents["quoteline:orbsec:sat"] = quote1Line;
const so1Id = await nextSequence(ctx, "salesOrder");
const so1 = await insertId(ctx, "salesOrder", {
@@ -217,7 +310,7 @@ export async function runTier4(ctx: Ctx): Promise<void> {
locationId: plantId,
currencyCode: "USD",
opportunityId: opp2Id,
- expirationDate: "2025-12-31"
+ expirationDate: NOVASAT_QUOTE_EXPIRATION
});
await insertRow(ctx, "quotePayment", {
id: quote2,
@@ -230,29 +323,50 @@ export async function runTier4(ctx: Ctx): Promise<void> {
shippingMethodId,
companyId
});
- await insertId(ctx, "quoteLine", {
+ const quote2SatLine = await insertId(ctx, "quoteLine", {
quoteId: quote2,
itemId: satItem.id,
itemType: "Part",
description: satItem.name,
methodType: "Make to Order",
unitOfMeasureCode: "EA",
- quantity: [2],
+ quantity: SAT_BREAK_QUANTITIES,
status: "Complete",
sortOrder: 1
});
- await insertId(ctx, "quoteLine", {
+ await insertPriceBreaks(ctx, quote2, quote2SatLine, SAT_PRICE_BREAKS);
+ const quote2EpsLine = await insertId(ctx, "quoteLine", {
quoteId: quote2,
itemId: epsItem.id,
itemType: "Part",
description: epsItem.name,
methodType: "Make to Order",
unitOfMeasureCode: "EA",
- quantity: [2],
- status: "In Progress",
+ quantity: EPS_BREAK_QUANTITIES,
+ status: "Complete",
sortOrder: 2
});
+ await insertPriceBreaks(ctx, quote2, quote2EpsLine, EPS_PRICE_BREAKS);
+
+ // The external link is what /share/quote/:id resolves against. It has to be
+ // created after the quote (it stores the quote's id) and pointed back at it,
+ // which is the same two-step upsertExternalLink does when a quote is created.
+ const quote2Link = await insertId(ctx, "externalLink", {
+ id: NOVASAT_QUOTE_LINK_ID,
+ documentType: "Quote",
+ documentId: quote2,
+ customerId: customers.novasat,
+ expiresAt: NOVASAT_QUOTE_EXPIRATION
+ });
+ await ctx.client.query(
+ `UPDATE "quote" SET "externalLinkId" = $1 WHERE id = $2 AND "companyId" = $3`,
+ [quote2Link, quote2, companyId]
+ );
+
ctx.refs.documents["quote:novasat"] = quote2;
+ ctx.refs.documents["quoteline:novasat:sat"] = quote2SatLine;
+ ctx.refs.documents["quoteline:novasat:eps"] = quote2EpsLine;
+ ctx.refs.documents["quotelink:novasat"] = quote2Link;
ctx.refs.documents["opp:novasat"] = opp2Id;
// ── Opportunity 3: Apex — RFQ only (no quote yet) ─────────────────────────
@@ -311,7 +425,7 @@ export async function runTier4(ctx: Ctx): Promise<void> {
shippingMethodId,
companyId
});
- await insertId(ctx, "quoteLine", {
+ const quote4Line = await insertId(ctx, "quoteLine", {
quoteId: quote4,
itemId: satItem.id,
itemType: "Part",
@@ -322,7 +436,11 @@ export async function runTier4(ctx: Ctx): Promise<void> {
status: "Complete",
sortOrder: 1
});
+ await insertPriceBreaks(ctx, quote4, quote4Line, [
+ { quantity: 1, unitPrice: 1800000, leadTime: 240 }
+ ]);
ctx.refs.documents["quote:polar"] = quote4;
+ ctx.refs.documents["quoteline:polar:sat"] = quote4Line;
const so4Id = await nextSequence(ctx, "salesOrder");
const so4 = await insertId(ctx, "salesOrder", {
@@ -470,4 +588,59 @@ export async function runTier4(ctx: Ctx): Promise<void> {
ctx.refs.documents[`soline:${spec.key}`] = lineId;
ctx.refs.documents[`opp:${spec.key}`] = oppId;
}
+
+ // ── Released order — "To Ship and Invoice" ────────────────────────────────
+ // The status is written by the app (releaseSalesOrder), not derived by a
+ // trigger, but it must still agree with what getSalesOrderStatus would
+ // compute: nothing sent and nothing invoiced on any line.
+ ctx.log("sales order — To Ship and Invoice (NovaSat, staggered deliveries)");
+ const opp5Id = await insertId(ctx, "opportunity", {
+ customerId: customers.novasat
+ });
+ const so5Id = await nextSequence(ctx, "salesOrder");
+ const so5 = await insertId(ctx, "salesOrder", {
+ salesOrderId: so5Id,
+ status: "To Ship and Invoice",
+ customerId: customers.novasat,
+ customerLocationId: cLocs.novasat ?? null,
+ locationId: plantId,
+ currencyCode: "USD",
+ opportunityId: opp5Id,
+ orderDate: "2026-08-03"
+ });
+ await insertRow(ctx, "salesOrderPayment", {
+ id: so5,
+ paymentTermId,
+ companyId
+ });
+ await insertRow(ctx, "salesOrderShipment", {
+ id: so5,
+ locationId: plantId,
+ shippingMethodId,
+ customerId: customers.novasat,
+ customerLocationId: cLocs.novasat ?? null,
+ companyId
+ });
+
+ for (const delivery of STAGGERED_DELIVERIES) {
+ ctx.log(` delivery ${delivery.key} — promised ${delivery.promisedDate}`);
+ const lineId = await insertId(ctx, "salesOrderLine", {
+ salesOrderId: so5,
+ salesOrderLineType: "Part",
+ itemId: sawItem.id,
+ description: sawItem.name,
+ saleQuantity: 30,
+ unitPrice: 35000,
+ unitOfMeasureCode: "EA",
+ locationId: plantId,
+ methodType: "Make to Order",
+ status: "Ordered",
+ promisedDate: delivery.promisedDate,
+ sortOrder: delivery.sortOrder
+ });
+ ctx.refs.documents[`soline:toshipinvoice:${delivery.key}`] = lineId;
+ }
+
+ ctx.refs.documents["so:toshipinvoice"] = so5;
+ ctx.refs.documents["opp:toshipinvoice"] = opp5Id;
}
diff --git a/packages/database/src/seed-dev/tiers/05-purchasing.ts b/packages/database/src/seed-dev/tiers/05-purchasing.ts
index 67ca01619c..a81d4123a6 100644
--- a/packages/database/src/seed-dev/tiers/05-purchasing.ts
+++ b/packages/database/src/seed-dev/tiers/05-purchasing.ts
@@ -1,6 +1,119 @@
-import { insertId, insertRow, nextSequence } from "../sql.ts";
+import { insertId, insertRow, need, nextSequence, RICH } from "../sql.ts";
import type { Ctx } from "../types.ts";
+// Every RFQ line and every supplier quote prices the same quantity breaks, so
+// the Compare Quotes drawer can total all three quotes at any tier it offers.
+const RFQ_QUANTITY_BREAKS = [10, 25, 50];
+
+const RFQ_LINES = [
+ { item: "PCB-BARE-REV3", description: "Bare EPS board, rev 3 — ENIG finish" },
+ { item: "BAT-LIION-48V", description: "48V Li-ion pack — flight qualified" }
+];
+
+type RfqQuoteSpec = {
+ key: string;
+ supplier: string;
+ supplierReference: string;
+ // Hard-coded so /share/supplier-quote/<id> is the same URL on every re-run.
+ externalLinkId: string;
+ shippingCost: number;
+ lines: {
+ item: string;
+ supplierPartId: string;
+ // [supplier unit price, lead time in days] per RFQ_QUANTITY_BREAKS entry
+ breaks: [number, number][];
+ }[];
+};
+
+// Cheapest (CelestialElex) vs fastest (Deep Space RF) vs slowest and dearest
+// (PropTech) — the comparison has a winner without being a one-horse race.
+const RFQ_QUOTES: RfqQuoteSpec[] = [
+ {
+ key: "celex",
+ supplier: "CelestialElex",
+ supplierReference: "CEX-Q-4471",
+ externalLinkId: "5c0e1a3d-7b41-4c92-9f18-2ad6e0b71c01",
+ shippingCost: 250,
+ lines: [
+ {
+ item: "PCB-BARE-REV3",
+ supplierPartId: "CEX-PCB-EPS3",
+ breaks: [
+ [94, 21],
+ [88, 21],
+ [82, 28]
+ ]
+ },
+ {
+ item: "BAT-LIION-48V",
+ supplierPartId: "CEX-BAT-48V",
+ breaks: [
+ [2180, 30],
+ [2080, 30],
+ [1990, 35]
+ ]
+ }
+ ]
+ },
+ {
+ key: "dsrf",
+ supplier: "Deep Space RF",
+ supplierReference: "DSRF-2026-0188",
+ externalLinkId: "5c0e1a3d-7b41-4c92-9f18-2ad6e0b71c02",
+ shippingCost: 180,
+ lines: [
+ {
+ item: "PCB-BARE-REV3",
+ supplierPartId: "DSRF-PCB-3",
+ breaks: [
+ [99, 14],
+ [93, 14],
+ [89, 18]
+ ]
+ },
+ {
+ item: "BAT-LIION-48V",
+ supplierPartId: "DSRF-BAT48",
+ breaks: [
+ [2260, 21],
+ [2170, 21],
+ [2090, 24]
+ ]
+ }
+ ]
+ },
+ {
+ key: "proptech",
+ supplier: "PropTech Solutions",
+ supplierReference: "PTS-RFQ-9931",
+ externalLinkId: "5c0e1a3d-7b41-4c92-9f18-2ad6e0b71c03",
+ shippingCost: 400,
+ lines: [
+ {
+ item: "PCB-BARE-REV3",
+ supplierPartId: "PTS-EPS-PCB",
+ breaks: [
+ [112, 35],
+ [104, 35],
+ [96, 42]
+ ]
+ },
+ {
+ item: "BAT-LIION-48V",
+ supplierPartId: "PTS-48V-PACK",
+ breaks: [
+ [2290, 45],
+ [2210, 45],
+ [2140, 45]
+ ]
+ }
+ ]
+ }
+];
+
+const RFQ_WINNING_QUOTE = "celex";
+const RFQ_ORDER_QUANTITY = 25;
+
export async function runTier5(ctx: Ctx): Promise<void> {
const { companyId, locationId } = ctx;
const plantId = ctx.refs.locations.Plant ?? locationId;
@@ -84,7 +197,10 @@ export async function runTier5(ctx: Ctx): Promise<void> {
receivedQuantity: 0,
locationId: plantId,
unitOfMeasure: "EA",
- unitPrice: 2200
+ unitPrice: 2200,
+ // The battery is a Batch item, so the receipt line has to ask for a lot —
+ // that inline lot field is the whole point of the receiving screenshot.
+ requiresBatchTracking: true
});
ctx.refs.documents["receipt:rocket"] = rec1;
@@ -194,4 +310,198 @@ export async function runTier5(ctx: Ctx): Promise<void> {
locationId: plantId
});
ctx.refs.documents["po:celex"] = po3;
+
+ // ── RFQ: 2 lines, finalized (Requested), fanned out to 3 suppliers ────────
+ ctx.log("purchasing RFQ — Requested (3 suppliers)");
+ const rfqReadableId = await nextSequence(ctx, "purchasingRfq");
+ const rfq = await insertId(ctx, "purchasingRfq", {
+ rfqId: rfqReadableId,
+ status: "Requested",
+ employeeId: ctx.userId,
+ locationId: plantId,
+ rfqDate: "2026-07-20",
+ expirationDate: "2026-09-30",
+ notes: RICH("Dual-source the EPS board and the 48V pack for the Q4 build."),
+ internalNotes: RICH(
+ "Award on landed cost at 25 pcs unless lead time slips."
+ )
+ });
+ ctx.refs.documents["prfq:avionics"] = rfq;
+
+ let rfqLineOrder = 1;
+ for (const spec of RFQ_LINES) {
+ const item = need(ctx.refs.items, spec.item);
+ await insertId(ctx, "purchasingRfqLine", {
+ purchasingRfqId: rfq,
+ itemId: item.id,
+ description: spec.description,
+ quantity: RFQ_QUANTITY_BREAKS,
+ purchaseUnitOfMeasureCode: "EA",
+ inventoryUnitOfMeasureCode: "EA",
+ conversionFactor: 1,
+ order: rfqLineOrder++
+ });
+ }
+
+ // ── One Active supplier quote per RFQ supplier, linked back to the RFQ ────
+ let winningInteractionId = "";
+ for (const spec of RFQ_QUOTES) {
+ ctx.log(`supplier quote — ${spec.supplier} (Active)`);
+ const supplierId = need(ctx.refs.suppliers, spec.supplier);
+
+ await insertId(ctx, "purchasingRfqSupplier", {
+ purchasingRfqId: rfq,
+ supplierId
+ });
+
+ const interactionId = await insertId(ctx, "supplierInteraction", {
+ supplierId
+ });
+ const quoteReadableId = await nextSequence(ctx, "supplierQuote");
+ const quoteId = await insertId(ctx, "supplierQuote", {
+ supplierQuoteId: quoteReadableId,
+ supplierQuoteType: "Purchase",
+ status: "Active",
+ supplierId,
+ supplierContactId: need(ctx.refs.contacts, `sc:${spec.supplier}`),
+ supplierLocationId: need(ctx.refs.misc, `sloc:${spec.supplier}`),
+ supplierReference: spec.supplierReference,
+ supplierInteractionId: interactionId,
+ quotedDate: "2026-07-28",
+ expirationDate: "2026-12-31",
+ currencyCode: "USD",
+ exchangeRate: 1,
+ externalNotes: RICH(`Quote against ${rfqReadableId}. Prices FOB origin.`)
+ });
+
+ // Same two steps as supplier-quote finalize: create the external link, then
+ // point the quote at it — that id is what /share/supplier-quote/:id reads.
+ await insertRow(ctx, "externalLink", {
+ id: spec.externalLinkId,
+ documentType: "SupplierQuote",
+ documentId: quoteId,
+ supplierId,
+ expiresAt: "2026-12-31T23:59:59Z"
+ });
+ await ctx.client.query(
+ `UPDATE "supplierQuote" SET "externalLinkId" = $1 WHERE id = $2`,
+ [spec.externalLinkId, quoteId]
+ );
+ ctx.refs.misc[`sqlink:${spec.key}`] = spec.externalLinkId;
+
+ let quoteLineSort = 1;
+ for (const line of spec.lines) {
+ const item = need(ctx.refs.items, line.item);
+ const quoteLineId = await insertId(ctx, "supplierQuoteLine", {
+ supplierQuoteId: quoteId,
+ supplierQuoteLineType: "Part",
+ itemId: item.id,
+ description: item.name,
+ supplierPartId: line.supplierPartId,
+ quantity: RFQ_QUANTITY_BREAKS,
+ purchaseUnitOfMeasureCode: "EA",
+ inventoryUnitOfMeasureCode: "EA",
+ conversionFactor: 1,
+ sortOrder: quoteLineSort++
+ });
+
+ // A short break list would silently drop a tier from the comparison.
+ if (line.breaks.length !== RFQ_QUANTITY_BREAKS.length) {
+ throw new Error(
+ `Seed: ${spec.key}/${line.item} must price every quantity break`
+ );
+ }
+
+ for (const [index, [unitPrice, leadTime]] of line.breaks.entries()) {
+ await insertRow(ctx, "supplierQuoteLinePrice", {
+ supplierQuoteId: quoteId,
+ supplierQuoteLineId: quoteLineId,
+ quantity: RFQ_QUANTITY_BREAKS[index],
+ supplierUnitPrice: unitPrice,
+ leadTime,
+ exchangeRate: 1,
+ supplierShippingCost: spec.shippingCost,
+ supplierTaxAmount: 0
+ });
+ }
+ }
+
+ await insertRow(ctx, "purchasingRfqToSupplierQuote", {
+ purchasingRfqId: rfq,
+ supplierQuoteId: quoteId
+ });
+ ctx.refs.documents[`sq:${spec.key}`] = quoteId;
+
+ if (spec.key === RFQ_WINNING_QUOTE) winningInteractionId = interactionId;
+ }
+
+ // ── PO 4: converted from the winning quote — To Receive and Invoice ───────
+ // The convert edge function reuses the quote's supplier interaction, and a PO
+ // with nothing received and nothing invoiced is exactly the state post-receipt
+ // and post-purchase-invoice call "To Receive and Invoice".
+ const winner = RFQ_QUOTES.find((q) => q.key === RFQ_WINNING_QUOTE);
+ if (!winner) {
+ throw new Error(`Seed: unknown winning quote "${RFQ_WINNING_QUOTE}"`);
+ }
+ const orderBreak = RFQ_QUANTITY_BREAKS.indexOf(RFQ_ORDER_QUANTITY);
+ if (orderBreak === -1) {
+ throw new Error(`Seed: no quantity break for ${RFQ_ORDER_QUANTITY}`);
+ }
+
+ ctx.log("purchase order 4 — To Receive and Invoice (from winning quote)");
+ const po4Id = await nextSequence(ctx, "purchaseOrder");
+ const po4 = await insertId(ctx, "purchaseOrder", {
+ purchaseOrderId: po4Id,
+ purchaseOrderType: "Purchase",
+ status: "To Receive and Invoice",
+ supplierId: need(ctx.refs.suppliers, winner.supplier),
+ supplierContactId: need(ctx.refs.contacts, `sc:${winner.supplier}`),
+ supplierReference: winner.supplierReference,
+ supplierInteractionId: winningInteractionId,
+ currencyCode: "USD",
+ exchangeRate: 1,
+ orderDate: "2026-08-05"
+ });
+ await insertRow(ctx, "purchaseOrderDelivery", {
+ id: po4,
+ locationId: plantId,
+ shippingMethodId,
+ companyId
+ });
+ await insertRow(ctx, "purchaseOrderPayment", {
+ id: po4,
+ paymentTermId,
+ companyId
+ });
+
+ let po4LineSort = 1;
+ for (const line of winner.lines) {
+ const item = need(ctx.refs.items, line.item);
+ const orderPrice = line.breaks[orderBreak];
+ if (!orderPrice) {
+ throw new Error(
+ `Seed: ${line.item} has no price at ${RFQ_ORDER_QUANTITY}`
+ );
+ }
+ await insertId(ctx, "purchaseOrderLine", {
+ purchaseOrderId: po4,
+ purchaseOrderLineType: "Part",
+ itemId: item.id,
+ description: item.name,
+ purchaseQuantity: RFQ_ORDER_QUANTITY,
+ supplierUnitPrice: orderPrice[0],
+ supplierShippingCost: winner.shippingCost,
+ exchangeRate: 1,
+ inventoryUnitOfMeasureCode: "EA",
+ purchaseUnitOfMeasureCode: "EA",
+ locationId: plantId,
+ sortOrder: po4LineSort++
+ });
+ }
+
+ await insertRow(ctx, "purchasingRfqToPurchaseOrder", {
+ purchasingRfqId: rfq,
+ purchaseOrderId: po4
+ });
+ ctx.refs.documents[`po:sq-${RFQ_WINNING_QUOTE}`] = po4;
}
diff --git a/packages/database/src/seed-dev/tiers/06-production.ts b/packages/database/src/seed-dev/tiers/06-production.ts
index 73379f6aa0..b3db3e6b1a 100644
--- a/packages/database/src/seed-dev/tiers/06-production.ts
+++ b/packages/database/src/seed-dev/tiers/06-production.ts
@@ -1,4 +1,8 @@
-import { insertId, maybeOne, need, nextSequence } from "../sql.ts";
+import {
+ copyMethodToJob,
+ type JobOperationStatus
+} from "../helpers/job-method.ts";
+import { insertId, insertRow, need, nextSequence, rows } from "../sql.ts";
import type { Ctx } from "../types.ts";
// Every non-deprecated jobStatus, each one hanging off a real salesOrderLine, so
@@ -114,15 +118,29 @@ const JOBS: JobSpec[] = [
}
];
+// A job's operations open in the state its own status implies — a Draft job's
+// work has not been handed to the floor, a released one's has.
+function operationStatusFor(jobStatus: string): JobOperationStatus {
+ switch (jobStatus) {
+ case "Draft":
+ case "Planned":
+ return "Todo";
+ case "Completed":
+ case "Closed":
+ return "Done";
+ case "Cancelled":
+ return "Canceled";
+ case "Paused":
+ return "Paused";
+ default:
+ return "Ready";
+ }
+}
+
export async function runTier6(ctx: Ctx): Promise<void> {
- const { client, locationId } = ctx;
+ const { locationId } = ctx;
const plantId = ctx.refs.locations.Plant ?? locationId;
- const procAssembly = ctx.refs.processes["Mechanical Assembly"];
- const procTest = ctx.refs.processes["System Test"];
- const wcFab = ctx.refs.workCenters["Fabrication Bay"];
- const wcClean = ctx.refs.workCenters["Clean Room"];
-
for (const spec of JOBS) {
ctx.log(`job ${spec.item} — ${spec.status}`);
const item = need(ctx.refs.items, spec.item);
@@ -145,37 +163,238 @@ export async function runTier6(ctx: Ctx): Promise<void> {
completedDate: spec.completedDate ?? null
});
ctx.refs.documents[`job:${spec.key}`] = id;
+
+ // The interceptor gives the job a bare root jobMakeMethod; this is what
+ // fills it in, and it is the whole reason the job pages, the method
+ // explorer and the MES board have anything to show.
+ const copied = await copyMethodToJob(
+ ctx,
+ id,
+ spec.quantity,
+ operationStatusFor(spec.status)
+ );
+ ctx.log(
+ ` method: ${copied.operations} operations, ${copied.materials} materials, ${copied.levels} levels`
+ );
+
+ // The interceptor's reserved entity for the unit being built has no
+ // readableId, so the MES assembly view labels the first serial with a raw
+ // id. Name it after the job.
+ await ctx.client.query(
+ `UPDATE "trackedEntity" te SET "readableId" = $3
+ FROM "jobMakeMethod" jmm
+ WHERE jmm.id = te.attributes->>'Job Make Method'
+ AND jmm."jobId" = $1 AND jmm."parentMaterialId" IS NULL
+ AND te."companyId" = $2 AND te."readableId" IS NULL`,
+ [id, ctx.companyId, `${jobId}-01`]
+ );
+ }
+
+ await seedProductionEvents(ctx);
+ await seedGenealogy(ctx);
+}
+
+/**
+ * Logged time on the in-progress job. Without these the job's Events tab and
+ * every WIP cost the docs describe are empty, because cost is posted per
+ * production event at the work center's rates.
+ */
+async function seedProductionEvents(ctx: Ctx): Promise<void> {
+ const jobId = need(ctx.refs.documents, "job:in-progress");
+
+ const operations = await rows<{
+ id: string;
+ workCenterId: string | null;
+ order: number;
+ }>(
+ ctx.client,
+ `SELECT jo.id, jo."workCenterId", jo."order"
+ FROM "jobOperation" jo
+ JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"
+ WHERE jo."jobId" = $1 AND jmm."parentMaterialId" IS NULL
+ AND jo."companyId" = $2
+ ORDER BY jo."order"
+ LIMIT 2`,
+ [jobId, ctx.companyId]
+ );
+ if (operations.length === 0) return;
+
+ // Literal start/end pairs — the seed must produce identical rows on every run,
+ // and this repo does not use JS Date for time arithmetic.
+ const shifts: Array<Array<{ type: string; start: string; end: string }>> = [
+ [
+ {
+ type: "Setup",
+ start: "2026-08-04T13:00:00Z",
+ end: "2026-08-04T13:45:00Z"
+ },
+ {
+ type: "Labor",
+ start: "2026-08-04T13:45:00Z",
+ end: "2026-08-04T17:45:00Z"
+ },
+ {
+ type: "Machine",
+ start: "2026-08-04T13:45:00Z",
+ end: "2026-08-04T17:45:00Z"
+ }
+ ],
+ [
+ {
+ type: "Setup",
+ start: "2026-08-05T13:00:00Z",
+ end: "2026-08-05T13:20:00Z"
+ },
+ {
+ type: "Labor",
+ start: "2026-08-05T13:20:00Z",
+ end: "2026-08-05T16:20:00Z"
+ },
+ {
+ type: "Machine",
+ start: "2026-08-05T13:20:00Z",
+ end: "2026-08-05T16:20:00Z"
+ }
+ ]
+ ];
+
+ ctx.log("production events");
+ for (const [index, operation] of operations.entries()) {
+ const events = shifts[index] ?? shifts[0]!;
+
+ for (const event of events) {
+ await insertRow(ctx, "productionEvent", {
+ jobOperationId: operation.id,
+ type: event.type,
+ startTime: event.start,
+ // `duration` is a generated column — Postgres derives it from the range.
+ endTime: event.end,
+ employeeId: ctx.userId,
+ workCenterId: operation.workCenterId,
+ postedToGL: false
+ });
+ }
+
+ await insertId(ctx, "productionQuantity", {
+ jobOperationId: operation.id,
+ type: "Production",
+ quantity: 1
+ });
}
+}
+
+// Tracked components consumed into the first satellite. Item, lot/serial id,
+// and how many of that lot went in.
+const GENEALOGY_INPUTS: Array<{
+ item: string;
+ readableId: string;
+ quantity: number;
+}> = [
+ { item: "MAT-AL7075-PLT", readableId: "LOT-AL7075-2607", quantity: 4.5 },
+ { item: "BAT-LIION-48V", readableId: "LOT-BAT-2606", quantity: 1 },
+ { item: "RW-010", readableId: "RW010-SN-0041", quantity: 1 },
+ { item: "RW-010", readableId: "RW010-SN-0042", quantity: 1 },
+ { item: "RW-010", readableId: "RW010-SN-0043", quantity: 1 },
+ { item: "RW-010", readableId: "RW010-SN-0044", quantity: 1 }
+];
- // Operations on the in-progress job, adopting its auto-created jobMakeMethod.
- const inProgressJob = need(ctx.refs.documents, "job:in-progress");
- const jmm1 = await maybeOne<{ id: string }>(
- client,
- `SELECT id FROM "jobMakeMethod" WHERE "jobId" = $1 AND "parentMaterialId" IS NULL LIMIT 1`,
- [inProgressJob]
+/**
+ * As-built genealogy for the first satellite off the in-progress job.
+ *
+ * The traceability graph is drawn from activities, not from entities: each
+ * consumed component is the INPUT of a Consume activity whose OUTPUT is the
+ * parent being built. Seeding entities alone leaves the graph empty, which is
+ * what it was.
+ */
+async function seedGenealogy(ctx: Ctx): Promise<void> {
+ const jobId = need(ctx.refs.documents, "job:in-progress");
+ const satellite = ctx.refs.items["SAT-1000"];
+ if (!satellite) return;
+
+ const assemblyOperation = await rows<{ id: string }>(
+ ctx.client,
+ `SELECT jo.id
+ FROM "jobOperation" jo
+ JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"
+ WHERE jo."jobId" = $1 AND jmm."parentMaterialId" IS NULL
+ AND jo."companyId" = $2
+ ORDER BY jo."order"
+ LIMIT 1`,
+ [jobId, ctx.companyId]
);
- if (jmm1 && procAssembly && wcFab) {
- await insertId(ctx, "jobOperation", {
- jobId: inProgressJob,
- jobMakeMethodId: jmm1.id,
- order: 1,
- processId: procAssembly,
- workCenterId: wcFab,
- description: "Structural Integration",
- setupTime: 2,
- laborTime: 16,
- status: "In Progress"
+ const operationId = assemblyOperation[0]?.id;
+ if (!operationId) return;
+
+ ctx.log("as-built genealogy");
+
+ const serialId = await insertId(ctx, "trackedEntity", {
+ quantity: 1,
+ status: "Available",
+ sourceDocument: "Job",
+ sourceDocumentId: jobId,
+ sourceDocumentReadableId: "SAT-1000",
+ readableId: "SAT1000-SN-0001",
+ itemId: satellite.id,
+ attributes: JSON.stringify({ Job: jobId }),
+ updatedBy: ctx.userId
+ });
+ ctx.refs.documents["trackedEntity:sat-0001"] = serialId;
+
+ // The unit exists because the operation produced it.
+ const produceId = await insertId(ctx, "trackedActivity", {
+ type: "Produce",
+ sourceDocument: "Job Operation",
+ sourceDocumentId: operationId,
+ sourceDocumentReadableId: "SAT-1000",
+ attributes: JSON.stringify({
+ "Job Operation": operationId,
+ Employee: ctx.userId,
+ Quantity: 1
+ }),
+ updatedBy: ctx.userId
+ });
+ await insertRow(ctx, "trackedActivityOutput", {
+ trackedActivityId: produceId,
+ trackedEntityId: serialId,
+ quantity: 1,
+ updatedBy: ctx.userId
+ });
+
+ for (const input of GENEALOGY_INPUTS) {
+ const item = ctx.refs.items[input.item];
+ if (!item) continue;
+
+ const childId = await insertId(ctx, "trackedEntity", {
+ quantity: input.quantity,
+ status: "Consumed",
+ sourceDocument: "Item",
+ sourceDocumentId: item.id,
+ sourceDocumentReadableId: item.readableId,
+ readableId: input.readableId,
+ itemId: item.id,
+ attributes: JSON.stringify({ Job: jobId }),
+ updatedBy: ctx.userId
+ });
+
+ const consumeId = await insertId(ctx, "trackedActivity", {
+ type: "Consume",
+ sourceDocument: "Job Material",
+ sourceDocumentId: jobId,
+ sourceDocumentReadableId: item.readableId,
+ attributes: JSON.stringify({ Job: jobId, Employee: ctx.userId }),
+ updatedBy: ctx.userId
+ });
+ await insertRow(ctx, "trackedActivityInput", {
+ trackedActivityId: consumeId,
+ trackedEntityId: childId,
+ quantity: input.quantity,
+ updatedBy: ctx.userId
});
- await insertId(ctx, "jobOperation", {
- jobId: inProgressJob,
- jobMakeMethodId: jmm1.id,
- order: 2,
- processId: procTest,
- workCenterId: wcClean ?? wcFab,
- description: "Functional Test",
- setupTime: 1,
- laborTime: 8,
- status: "Todo"
+ await insertRow(ctx, "trackedActivityOutput", {
+ trackedActivityId: consumeId,
+ trackedEntityId: serialId,
+ quantity: 1,
+ updatedBy: ctx.userId
});
}
}
diff --git a/packages/database/src/seed-dev/tiers/07-quality.ts b/packages/database/src/seed-dev/tiers/07-quality.ts
index d7fc1d4e11..721359c0d9 100644
--- a/packages/database/src/seed-dev/tiers/07-quality.ts
+++ b/packages/database/src/seed-dev/tiers/07-quality.ts
@@ -1,4 +1,4 @@
-import { insertId, nextSequence, one } from "../sql.ts";
+import { insertId, insertRow, maybeOne, nextSequence, one } from "../sql.ts";
import type { Ctx } from "../types.ts";
export async function runTier7(ctx: Ctx): Promise<void> {
@@ -45,4 +45,41 @@ export async function runTier7(ctx: Ctx): Promise<void> {
companyId
});
ctx.refs.documents["ncr:fastener"] = ncr2;
+
+ // ── Associations ──────────────────────────────────────────────────────────
+ // An issue raised on the floor is raised against the operation that produced
+ // it. Without this link the issue page's Associations card is empty.
+ const jobId = ctx.refs.documents["job:in-progress"];
+ if (!jobId) return;
+
+ const operation = await maybeOne<{ id: string; jobReadableId: string }>(
+ client,
+ `SELECT jo.id, j."jobId" AS "jobReadableId"
+ FROM "jobOperation" jo
+ JOIN job j ON j.id = jo."jobId"
+ JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"
+ WHERE jo."jobId" = $1 AND jmm."parentMaterialId" IS NULL
+ AND jo."companyId" = $2
+ ORDER BY jo."order"
+ LIMIT 1`,
+ [jobId, companyId]
+ );
+ if (!operation) return;
+
+ ctx.log("NCR 1 — job operation association");
+ await insertRow(ctx, "nonConformanceJobOperation", {
+ nonConformanceId: ncr1,
+ jobOperationId: operation.id,
+ jobId,
+ jobReadableId: operation.jobReadableId
+ });
+
+ const satellite = ctx.refs.items["SAT-1000"];
+ if (satellite) {
+ await insertRow(ctx, "nonConformanceItem", {
+ nonConformanceId: ncr1,
+ itemId: satellite.id,
+ quantity: 1
+ });
+ }
}
diff --git a/packages/database/src/seed-dev/tiers/08-change-orders.ts b/packages/database/src/seed-dev/tiers/08-change-orders.ts
index 4d0562586f..80ed851cc7 100644
--- a/packages/database/src/seed-dev/tiers/08-change-orders.ts
+++ b/packages/database/src/seed-dev/tiers/08-change-orders.ts
@@ -1,10 +1,116 @@
-import { insertId, nextSequence } from "../sql.ts";
-import type { Ctx } from "../types.ts";
+import { addBomLine, createItem } from "../helpers/items.ts";
+import type { Row } from "../sql.ts";
+import {
+ insertId,
+ insertRow,
+ need,
+ nextSequence,
+ one,
+ quote,
+ rows,
+ sharedColumns
+} from "../sql.ts";
+import type { Ctx, ItemRef } from "../types.ts";
+
+// Columns never copied verbatim when a change notice clones a method's BoM/BoP:
+// the row's own identity, its parent method (the clone's whole point), tenancy +
+// audit (re-stamped by insertRow) and methodMaterial's generated
+// productionQuantity. Everything else comes from sharedColumns, so a migration
+// that adds a column can't silently drop it from the clone.
+const CLONE_EXCLUDE = [
+ "id",
+ "makeMethodId",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ "updatedAt",
+ "updatedBy",
+ "productionQuantity"
+];
+
+// The item's current (highest-version) make method — what a change notice clones
+// its draft from, and what the release diff reads as the base.
+async function baseMakeMethod(
+ ctx: Ctx,
+ item: ItemRef
+): Promise<{ id: string; version: string }> {
+ return one<{ id: string; version: string }>(
+ ctx.client,
+ `SELECT id, version FROM "makeMethod"
+ WHERE "itemId" = $1 AND "companyId" = $2
+ ORDER BY version DESC
+ LIMIT 1`,
+ [item.id, ctx.companyId]
+ );
+}
+
+/**
+ * Copy one method's BoM/BoP onto another (what `copyMakeMethod` does in the app).
+ * Operations are cloned first so each material's methodOperationId can be remapped
+ * onto the cloned operation. Operation children (steps / parameters / tools) are
+ * not copied — no tier writes any.
+ */
+async function cloneMethodRows(
+ ctx: Ctx,
+ sourceMakeMethodId: string,
+ targetMakeMethodId: string
+): Promise<void> {
+ const operationColumns = await sharedColumns(
+ ctx.client,
+ "methodOperation",
+ "methodOperation",
+ CLONE_EXCLUDE
+ );
+ const sourceOperations = await rows<Row>(
+ ctx.client,
+ `SELECT "id", ${operationColumns.map(quote).join(", ")}
+ FROM "methodOperation"
+ WHERE "makeMethodId" = $1 AND "companyId" = $2
+ ORDER BY "order"`,
+ [sourceMakeMethodId, ctx.companyId]
+ );
+
+ const operationIds = new Map<string, string>();
+ for (const { id, ...operation } of sourceOperations) {
+ const cloned = await insertId(ctx, "methodOperation", {
+ ...operation,
+ makeMethodId: targetMakeMethodId
+ });
+ operationIds.set(id as string, cloned);
+ }
+
+ const materialColumns = await sharedColumns(
+ ctx.client,
+ "methodMaterial",
+ "methodMaterial",
+ CLONE_EXCLUDE
+ );
+ const sourceMaterials = await rows<Row>(
+ ctx.client,
+ `SELECT ${materialColumns.map(quote).join(", ")}
+ FROM "methodMaterial"
+ WHERE "makeMethodId" = $1 AND "companyId" = $2
+ ORDER BY "order"`,
+ [sourceMakeMethodId, ctx.companyId]
+ );
+
+ for (const material of sourceMaterials) {
+ const operationId = material.methodOperationId;
+ await insertRow(ctx, "methodMaterial", {
+ ...material,
+ makeMethodId: targetMakeMethodId,
+ methodOperationId:
+ typeof operationId === "string"
+ ? (operationIds.get(operationId) ?? null)
+ : null
+ });
+ }
+}
export async function runTier8(ctx: Ctx): Promise<void> {
- const satItem = ctx.refs.items["SAT-1000"]!;
- const epsItem = ctx.refs.items["EPS-001"]!;
- const busItem = ctx.refs.items["BUS-STR-001"]!;
+ const satItem = need(ctx.refs.items, "SAT-1000");
+ const epsItem = need(ctx.refs.items, "EPS-001");
+ const busItem = need(ctx.refs.items, "BUS-STR-001");
// ── CO 1: Draft — version bump on SAT-1000 ───────────────────────────────
ctx.log("change order 1 — Draft");
@@ -16,10 +122,26 @@ export async function runTier8(ctx: Ctx): Promise<void> {
status: "Draft",
openDate: "2025-09-01"
});
+
+ // A Version stays on the same item: the notice owns a new Draft method version
+ // cloned from the active one, and the affected item points at both ends.
+ const satBase = await baseMakeMethod(ctx, satItem);
+ const satDraftVersion = Number(satBase.version) + 1;
+ const satDraft = await insertId(ctx, "makeMethod", {
+ itemId: satItem.id,
+ version: satDraftVersion,
+ status: "Draft",
+ changeOrderId: co1
+ });
+ await cloneMethodRows(ctx, satBase.id, satDraft);
+ ctx.log(` SAT-1000 draft method v${satDraftVersion}`);
+
await insertId(ctx, "changeOrderAffectedItem", {
changeOrderId: co1,
itemId: satItem.id,
changeType: "Version",
+ draftMakeMethodId: satDraft,
+ baseMakeMethodId: satBase.id,
sortOrder: 1
});
ctx.refs.documents["co:draft"] = co1;
@@ -34,28 +156,97 @@ export async function runTier8(ctx: Ctx): Promise<void> {
status: "Implementation",
openDate: "2025-10-10"
});
+
+ // A Revision mints a new revision of the item (EPS-001.A) and edits ITS method.
+ // The revision stays hidden — inactive, notice-owned — until release.
+ const epsBase = await baseMakeMethod(ctx, epsItem);
+ const epsRevision = await createItem(ctx, {
+ readableId: epsItem.readableId,
+ revision: "A",
+ name: epsItem.name,
+ type: "Part",
+ replenishment: "Make",
+ standardCost: 0,
+ unitSalePrice: 120000,
+ description:
+ "Rev A — potted connector backshells and a revised harness remove the short-circuit path"
+ });
+ const epsDraft = epsRevision.makeMethodId;
+ if (!epsDraft) {
+ throw new Error("Seed: EPS-001.A has no make method to use as the draft");
+ }
+ await ctx.client.query(
+ `UPDATE item SET active = false, "changeOrderId" = $2, "updatedBy" = $3
+ WHERE id = $1`,
+ [epsRevision.id, co2, ctx.userId]
+ );
+ await ctx.client.query(
+ `UPDATE "makeMethod" SET status = 'Draft', "changeOrderId" = $2, "updatedBy" = $3
+ WHERE id = $1`,
+ [epsDraft, co2, ctx.userId]
+ );
+ await cloneMethodRows(ctx, epsBase.id, epsDraft);
+ ctx.log(" EPS-001.A draft method");
+
+ // The engineering edits themselves — without them the draft mirrors its base
+ // and the release diff has nothing to show.
+ await ctx.client.query(
+ `DELETE FROM "methodMaterial" WHERE "makeMethodId" = $1 AND "itemId" = $2`,
+ [epsDraft, need(ctx.refs.items, "MAT-KAPTON").id]
+ );
+ await ctx.client.query(
+ `UPDATE "methodMaterial" SET quantity = 2, "updatedBy" = $3
+ WHERE "makeMethodId" = $1 AND "itemId" = $2`,
+ [epsDraft, need(ctx.refs.items, "BAT-LIION-48V").id, ctx.userId]
+ );
+ await addBomLine(ctx, epsDraft, need(ctx.refs.items, "HARNESS-001"), 1, 5);
+ await ctx.client.query(
+ `UPDATE "methodOperation"
+ SET description = $2, "laborTime" = 3, "updatedBy" = $3
+ WHERE "makeMethodId" = $1 AND "order" = 2`,
+ [epsDraft, "EPS functional & hipot test", ctx.userId]
+ );
+ ctx.log(" EPS-001.A draft edits (−1 line, +1 line, 2 modified)");
+
await insertId(ctx, "changeOrderAffectedItem", {
changeOrderId: co2,
itemId: epsItem.id,
changeType: "Revision",
+ draftMakeMethodId: epsDraft,
+ baseMakeMethodId: epsBase.id,
+ newItemId: epsRevision.id,
+ supersessionMode: "Consume First",
+ discontinuationDate: "2026-09-30",
+ successorEffectivityDate: "2026-10-01",
sortOrder: 1
});
ctx.refs.documents["co:impl"] = co2;
- // ── CO 3: Done — new part added for bus structure ─────────────────────────
+ // ── CO 3: Done — bus structure introduced under change control ────────────
ctx.log("change order 3 — Done");
const co3Id = await nextSequence(ctx, "changeOrder");
const co3 = await insertId(ctx, "changeOrder", {
changeOrderId: co3Id,
- name: "Add thermal doubler to bus primary structure",
+ name: "Introduce bus primary structure under change control",
type: "Engineering",
status: "Done",
openDate: "2025-08-01"
});
+
+ // Released: a New Part has no predecessor (baseMakeMethodId null, newItemId is
+ // the item itself), its draft is now the item's live method with the notice
+ // link cleared, and item.changeOrderId is the permanent back-link release writes.
+ const busBase = await baseMakeMethod(ctx, busItem);
+ await ctx.client.query(
+ `UPDATE item SET "changeOrderId" = $2, "updatedBy" = $3 WHERE id = $1`,
+ [busItem.id, co3, ctx.userId]
+ );
await insertId(ctx, "changeOrderAffectedItem", {
changeOrderId: co3,
itemId: busItem.id,
changeType: "New Part",
+ draftMakeMethodId: busBase.id,
+ newItemId: busItem.id,
sortOrder: 1
});
ctx.refs.documents["co:done"] = co3;
diff --git a/packages/database/src/seed-dev/tiers/09-accounting.ts b/packages/database/src/seed-dev/tiers/09-accounting.ts
index 189fd27b06..ad483673f3 100644
--- a/packages/database/src/seed-dev/tiers/09-accounting.ts
+++ b/packages/database/src/seed-dev/tiers/09-accounting.ts
@@ -1,6 +1,110 @@
-import { insertId, maybeOne, nextSequence } from "../sql.ts";
+import { insertId, insertRow, maybeOne, nextSequence, rows } from "../sql.ts";
import type { Ctx } from "../types.ts";
+// Every fixed asset status the UI branches on, so the docs screenshots aren't
+// dead ends: Draft is the ONLY status /x/fixed-asset/:id/register accepts
+// (the loader redirects away otherwise), and the Sell modal requires Active or
+// Fully Depreciated.
+type FixedAssetSpec = {
+ key: string;
+ className: string;
+ location: "Plant" | "HQ";
+ name: string;
+ description: string;
+ serialNumber: string;
+ status: "Draft" | "Active" | "Fully Depreciated";
+ depreciationMethod: "Straight Line" | "Declining Balance";
+ usefulLifeMonths: number;
+ // Whole percent — the app reads residual as cost * (percent / 100).
+ residualValuePercent: number;
+ acquisitionCost: number;
+ acquisitionDate: string | null;
+ depreciationStartDate: string | null;
+ accumulatedDepreciation: number;
+ // The straight-line charge buildDepreciationLines() computes for
+ // DEPRECIATION_PERIOD_END with no prior posted run:
+ // (cost - residual) / usefulLifeMonths * months since depreciationStartDate.
+ // Omit to leave the asset out of the seeded run.
+ depreciationCharge?: number;
+};
+
+// One month behind the current period, so "New Depreciation Run" still has a
+// period left to create (getNextPeriodEnd rolls this forward to 2026-08-31).
+const DEPRECIATION_PERIOD_END = "2026-07-31";
+
+const FIXED_ASSETS: FixedAssetSpec[] = [
+ {
+ key: "hvac",
+ className: "Buildings",
+ location: "Plant",
+ name: "Clean Room HVAC System",
+ description: "ISO Class 7 clean room air handling and filtration plant",
+ serialNumber: "HVAC-CR7-88421",
+ status: "Active",
+ depreciationMethod: "Straight Line",
+ usefulLifeMonths: 120,
+ residualValuePercent: 5,
+ acquisitionCost: 85000,
+ acquisitionDate: "2024-01-15",
+ depreciationStartDate: "2024-02-15",
+ accumulatedDepreciation: 0,
+ // 80,750 / 120 = 672.92 per month x 30 months (2024-02-15 → 2026-07-31)
+ depreciationCharge: 20187.5
+ },
+ {
+ key: "cmm",
+ className: "Machinery & Equipment",
+ location: "Plant",
+ name: "Coordinate Measuring Machine",
+ description: "Bridge-type CMM used for first article inspection",
+ serialNumber: "CMM-BR12-00317",
+ status: "Active",
+ depreciationMethod: "Straight Line",
+ usefulLifeMonths: 120,
+ residualValuePercent: 5,
+ acquisitionCost: 240000,
+ acquisitionDate: "2025-03-10",
+ depreciationStartDate: "2025-04-15",
+ accumulatedDepreciation: 0,
+ // 228,000 / 120 = 1,900 per month x 16 months (2025-04-15 → 2026-07-31)
+ depreciationCharge: 30400
+ },
+ {
+ key: "cnc",
+ className: "Machinery & Equipment",
+ location: "Plant",
+ name: "5-Axis CNC Machining Center",
+ description: "Awaiting registration — acquisition cost booked on register",
+ serialNumber: "CNC-5X-72094",
+ status: "Draft",
+ depreciationMethod: "Straight Line",
+ usefulLifeMonths: 120,
+ residualValuePercent: 5,
+ // A Draft asset has not been capitalized yet: the register drawer is what
+ // supplies cost, acquisition date and depreciation start date.
+ acquisitionCost: 0,
+ acquisitionDate: null,
+ depreciationStartDate: null,
+ accumulatedDepreciation: 0
+ },
+ {
+ key: "van",
+ className: "Vehicles",
+ location: "HQ",
+ name: "Delivery Van",
+ description: "Cargo van for local supplier pickups",
+ serialNumber: "VIN-1FTBW2CM7KKA10293",
+ status: "Fully Depreciated",
+ depreciationMethod: "Straight Line",
+ usefulLifeMonths: 60,
+ residualValuePercent: 0,
+ acquisitionCost: 48000,
+ acquisitionDate: "2019-06-14",
+ depreciationStartDate: "2019-07-15",
+ accumulatedDepreciation: 48000
+ }
+];
+
export async function runTier9(ctx: Ctx): Promise<void> {
const { client, companyId } = ctx;
@@ -56,26 +160,69 @@ export async function runTier9(ctx: Ctx): Promise<void> {
}
}
- // ── Fixed asset: clean room HVAC ─────────────────────────────────────────
- ctx.log("fixed asset — clean room HVAC");
- const faClass = await maybeOne<{ id: string }>(
+ // ── Fixed assets ─────────────────────────────────────────────────────────
+ // fixedAssetClass is in PRESERVED_TABLES — bootstrap seeds the three classes,
+ // so look them up by name rather than inserting.
+ const faClasses = await rows<{ id: string; name: string }>(
client,
- `SELECT id FROM "fixedAssetClass" WHERE "companyId" = $1 LIMIT 1`,
+ `SELECT id, name FROM "fixedAssetClass" WHERE "companyId" = $1`,
[companyId]
);
- if (faClass) {
- const faId = await nextSequence(ctx, "fixedAsset");
+ const faClassByName = new Map(faClasses.map((c) => [c.name, c.id]));
+ const fallbackClassId = faClasses[0]?.id;
+
+ const runLines: { fixedAssetId: string; amount: number }[] = [];
+
+ for (const spec of FIXED_ASSETS) {
+ const fixedAssetClassId =
+ faClassByName.get(spec.className) ?? fallbackClassId;
+ if (!fixedAssetClassId) {
+ ctx.log(`fixed asset ${spec.name} — no fixedAssetClass, skipping`);
+ continue;
+ }
+ ctx.log(`fixed asset ${spec.name} — ${spec.status}`);
+ const fixedAssetId = await nextSequence(ctx, "fixedAsset");
const fa = await insertId(ctx, "fixedAsset", {
- fixedAssetId: faId,
- fixedAssetClassId: faClass.id,
- name: "Clean Room HVAC System",
- status: "Active",
- depreciationMethod: "Straight Line",
- usefulLifeMonths: 120,
- residualValuePercent: 0.05,
- acquisitionCost: 85000,
- acquisitionDate: "2024-01-15"
+ fixedAssetId,
+ fixedAssetClassId,
+ locationId: ctx.refs.locations[spec.location] ?? ctx.locationId,
+ name: spec.name,
+ description: spec.description,
+ serialNumber: spec.serialNumber,
+ status: spec.status,
+ depreciationMethod: spec.depreciationMethod,
+ usefulLifeMonths: spec.usefulLifeMonths,
+ residualValuePercent: spec.residualValuePercent,
+ acquisitionCost: spec.acquisitionCost,
+ acquisitionDate: spec.acquisitionDate,
+ depreciationStartDate: spec.depreciationStartDate,
+ accumulatedDepreciation: spec.accumulatedDepreciation
});
- ctx.refs.documents["fixedAsset:hvac"] = fa;
+ ctx.refs.documents[`fixedAsset:${spec.key}`] = fa;
+ if (spec.depreciationCharge) {
+ runLines.push({ fixedAssetId: fa, amount: spec.depreciationCharge });
+ }
+ }
+
+ // ── Depreciation run: unposted, one line per Active asset ────────────────
+ // Mirrors what accounting+/depreciation-runs.new.tsx builds. taxAmount stays
+ // NULL because companySettings.assetTaxDepreciationEnabled is off, which is
+ // also what buildDepreciationLines() produces in that case.
+ if (runLines.length > 0) {
+ ctx.log("depreciation run — Draft");
+ const depreciationRunId = await nextSequence(ctx, "depreciationRun");
+ const run = await insertId(ctx, "depreciationRun", {
+ depreciationRunId,
+ periodEnd: DEPRECIATION_PERIOD_END,
+ status: "Draft"
+ });
+ for (const line of runLines) {
+ await insertRow(ctx, "depreciationRunLine", {
+ depreciationRunId: run,
+ fixedAssetId: line.fixedAssetId,
+ amount: line.amount
+ });
+ }
+ ctx.refs.documents["depreciationRun:draft"] = run;
}
}
diff --git a/packages/database/src/seed-dev/tiers/12-planning.ts b/packages/database/src/seed-dev/tiers/12-planning.ts
index 2dc72170a9..b6fdc7eff5 100644
--- a/packages/database/src/seed-dev/tiers/12-planning.ts
+++ b/packages/database/src/seed-dev/tiers/12-planning.ts
@@ -1,4 +1,10 @@
-import { insertId, insertRow, nextSequence } from "../sql.ts";
+import {
+ insertId,
+ insertMaybe,
+ insertRow,
+ nextSequence,
+ rows
+} from "../sql.ts";
import type { Ctx } from "../types.ts";
// "Fixed Reorder Quantity" with reorderPoint > 0 is the only policy that makes
@@ -23,6 +29,22 @@ const MAKE_ITEM_IDS = [
"COMMS-001"
];
+// Mirrors WEEKS_TO_PROJECT in apps/erp/app/routes/x+/production+/projections.tsx.
+// The whole horizon is seeded (not just the weeks that carry demand) so
+// getOrCreatePeriods finds every period already present and returns them in the
+// order they were inserted — otherwise the loader appends the ones it creates
+// and the Week N column headers stop being consecutive.
+const WEEKS_TO_PROJECT = 12 * 4;
+
+// get_production_projections INNER JOINs demandProjection, so /x/production/
+// projections shows only items that have a forecast. These three are Make,
+// Inventory-tracked, active and already have an itemPlanning row at the Plant.
+const DEMAND_PROJECTIONS: { readableId: string; quantities: number[] }[] = [
+ { readableId: "SAT-1000", quantities: [2, 2, 3, 3, 4, 4, 5, 5] },
+ { readableId: "EPS-001", quantities: [6, 6, 8, 8, 10, 10, 12, 12] },
+ { readableId: "ADCS-001", quantities: [3, 4, 4, 5, 6, 6, 8, 8] }
+];
+
export async function runTier12(ctx: Ctx): Promise<void> {
const { client, companyId, userId, refs } = ctx;
const plantId = refs.locations.Plant ?? ctx.locationId;
@@ -136,4 +158,74 @@ export async function runTier12(ctx: Ctx): Promise<void> {
sortOrder: 2
});
ctx.refs.documents["so:planning-seed"] = so;
+
+ // ── 4. demandProjection → /x/production/projections ─────────────────────────
+ // getOrCreatePeriods(today, WEEKS_TO_PROJECT) keys periods on startDate +
+ // periodType = 'Week' with a Sunday start (startOfWeek(..., "en-US")), so the
+ // ranges are derived the same way here. `period` has no companyId, so the wipe
+ // leaves it alone — look up first, insert only what is missing, chronologically.
+ ctx.log("period — weekly planning horizon");
+ const weekRanges = await rows<{ startDate: string; endDate: string }>(
+ client,
+ `SELECT to_char(d::date, 'YYYY-MM-DD') AS "startDate",
+ to_char(d::date + 6, 'YYYY-MM-DD') AS "endDate"
+ FROM generate_series(
+ CURRENT_DATE - EXTRACT(DOW FROM CURRENT_DATE)::int,
+ CURRENT_DATE - EXTRACT(DOW FROM CURRENT_DATE)::int + ($1::int - 1) * 7,
+ INTERVAL '7 days'
+ ) AS d`,
+ [WEEKS_TO_PROJECT]
+ );
+
+ const existingPeriods = await rows<{ id: string; startDate: string }>(
+ client,
+ `SELECT id, to_char("startDate", 'YYYY-MM-DD') AS "startDate"
+ FROM period
+ WHERE "periodType" = 'Week'
+ AND "startDate" = ANY($1::date[])`,
+ [weekRanges.map((r) => r.startDate)]
+ );
+ const periodIdByStart = new Map(
+ existingPeriods.map((p) => [p.startDate, p.id])
+ );
+
+ const periodIds: string[] = [];
+ for (const range of weekRanges) {
+ let periodId = periodIdByStart.get(range.startDate);
+ if (!periodId) {
+ periodId = await insertId(ctx, "period", {
+ startDate: range.startDate,
+ endDate: range.endDate,
+ periodType: "Week"
+ });
+ }
+ periodIds.push(periodId);
+ }
+
+ ctx.log("demandProjection — weekly forecast for make parts");
+ for (const spec of DEMAND_PROJECTIONS) {
+ const item = refs.items[spec.readableId];
+ if (!item) {
+ ctx.log(` skip ${spec.readableId} — not in refs`);
+ continue;
+ }
+ for (let week = 0; week < spec.quantities.length; week++) {
+ const periodId = periodIds[week];
+ if (!periodId) break;
+ // updatedBy is NOT NULL with no default, and insertRow only auto-fills
+ // companyId / createdBy.
+ await insertMaybe(ctx, "demandProjection", {
+ itemId: item.id,
+ locationId: plantId,
+ periodId,
+ forecastQuantity: spec.quantities[week],
+ updatedBy: userId
+ });
+ }
+ }
+
+ for (let week = 0; week < 8; week++) {
+ const periodId = periodIds[week];
+ if (periodId) ctx.refs.misc[`period:week${week + 1}`] = periodId;
+ }
}
diff --git a/packages/database/src/seed-dev/types.ts b/packages/database/src/seed-dev/types.ts
index c88c2aa5ef..90ac2a7704 100644
--- a/packages/database/src/seed-dev/types.ts
+++ b/packages/database/src/seed-dev/types.ts
@@ -29,6 +29,8 @@ export type ItemRef = {
name: string;
type: ItemType;
makeMethodId: string | null;
+ // Drives the BOM line's methodType — a Make component is a subassembly.
+ isMake: boolean;
unitCost: number;
unitOfMeasureCode: string;
};
diff --git a/packages/database/src/seed-dev/wipe.ts b/packages/database/src/seed-dev/wipe.ts
index 4ef0cda166..15d3120271 100644
--- a/packages/database/src/seed-dev/wipe.ts
+++ b/packages/database/src/seed-dev/wipe.ts
@@ -202,7 +202,9 @@ export async function wipeCompanyBusinessData(ctx: Ctx): Promise<void> {
"salesOrder",
"purchaseOrder",
"quote",
- "salesRfq"
+ "salesRfq",
+ "supplierQuote",
+ "purchasingRfq"
]) {
if (deleteSet.has(t)) {
await client.query(`DELETE FROM ${quote(t)} WHERE "companyId" = $1`, [