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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
(feat): demo data now fills every ERP and MES screen (#1723)
Anshul sharma382e8d64d967
diff --git a/.ai/plans/2026-09-22-demo-data-completeness.md b/.ai/plans/2026-09-22-demo-data-completeness.mdnew file mode 100644index 0000000000..91e39f7144--- /dev/null+++ b/.ai/plans/2026-09-22-demo-data-completeness.md@@ -0,0 +1,299 @@+# Demo Data Completeness — implementation plan++**Spec / source:** `.ai/specs/2026-09-22-demo-data-completeness.md`+**Branch:** `feat/demo-data-completeness`+**Research:** `.ai/research/2026-09-22-demo-data-current-coverage.md` (what exists), `.ai/research/2026-09-22-app-feature-surface.md` (what must be covered), `.ai/research/2026-09-22-demo-data-validation-gate.md` (validation holes)++**Plan-time corrections to the spec** (verified against `packages/database/src/types.ts` on this branch):+- Inspection engine tables are `inspection`, `inspectionSample`, `inspectionMeasurement`, `inspectionSamplingPlan` (not "inboundInspection"/"itemSamplingPlan").+- Change-order tasks table is `changeOrderActionTask`.+- These tables DO NOT exist and are dropped from scope: `crew`, `equipment`, `customerPortal`, `receiptLineTracking`, `batchNumber`, `serialNumber`, `nonConformanceInvestigationTask`. Tracked-entity rows ARE the lot/serial registry.+- All other target tables verified present (pickingList, stockTransfer, warehouseTransfer, salesReturnOrder, purchaseReturnOrder, qualityDocument, gauge(+CalibrationRecord), riskRegister, maintenanceSchedule/Dispatch, training(+Question/Assignment), timeCardEntry, holiday, employeeAbility/Shift, payment, invoiceSettlement, memo, exchangeRate, accountingPeriod, periodCloseTask, fixedAssetDisposal, workflowRun/StepRun, jobOperationBatch/Note, itemSupersession, material* taxonomy, rework, note, tag, project, dimensionValue, *StatusHistory, jobFavorite, itemShelfLife, suggestion, quoteMakeMethod, customerItemPriceOverride, pricingRule, configurationParameter, customerPartToItem, nonConformance{ActionTask,ApprovalTask,Reviewer,Supplier,Customer,SalesOrderLine,PurchaseOrderLine,TrackedEntity,Inspection}).++## Ground rules for every task (read once, apply always)++1. Working dir `/Users/aashu/work/carbon/carbon`. Never `npm`; always `pnpm`. **Never commit** — the user commits.+2. Engine idiom: tiers use `insertRow`/`insertId`/`insertMaybe` from `datasets/sql.ts` (auto-fills `companyId`, `createdBy`; validates columns against live `information_schema` at runtime and throws on unknown table/column). Cross-refs resolve via `need(ctx.refs.X, key)`. Dates ONLY via `DayOffset` + `resolveDate`/`resolveTimestamp` (`datasets/dates.ts`); never JS `Date`, never `CURRENT_DATE`.+3. Before inserting into any table for the first time, read its Insert type in `packages/database/src/types.ts` (search ` <table>: {` then the `Insert:` block) — do not guess columns. Nullable FKs may be omitted; NOT NULL columns must be supplied.+4. Sync interceptors run during seeding — before adding an insert, check whether an interceptor already creates the row (pattern: tier 2's itemCost UPDATE, tier 6's jobMakeMethod adopt). If a unique violation appears, adopt-and-UPDATE instead of insert.+5. The verification loop after every cluster:+ ```bash+ pnpm --filter @carbon/database typecheck # tsgo --noEmit+ pnpm --silent db:check:datasets # must print ✓ for all four (~3s)+ ```+ Fix until green before the next cluster. A `Seed:`-prefixed error names the bad ref; a raw PG error names the constraint.+6. All four data packs move together per cluster: new Dataset fields are REQUIRED (compile enforces parity). `data/satellite/` is authored first as the canonical pattern; robotics/precision/motor mirror it with industry-appropriate content (same shape/volume, different story).+7. Story voice: each industry keeps its narrative (satellite manufacturer, robotics OEM, machine shop, motor assembler). Names/quantities/prices must be plausible for that industry; date offsets relative and internally ordered (order < ship < invoice, etc.).+8. Ledger invariant: any hand-authored `itemLedger` consumption/shipment must be covered by opening stock or seeded receipts for that (item, shelf); journals must balance per entry.+9. If an assumption in a task turns out false (missing column, interceptor conflict that can't be adopted, table shape incompatible), re-decide via the ship-it resolution ladder, record the change in the spec's Autonomous Decisions section, and continue. Improvising silently is forbidden; so is silently dropping coverage.++## Progress++- [x] Task 1: Loud refs — silent skips become throws (kept `.Plant ?? locationId` fallbacks: tier 01 sets `refs.locations.Plant` unconditionally, so they are dead-safe; shelf-parent guard already existed)+- [x] Task 2: Pure dataset validator + pre-DB wiring + vitest (drill passed: broken ref + DB down → exit 1 with named violation; genealogy-input check corrected to uniqueness — tier 06 creates those entities itself)+- [x] Task 3: Cluster C1 — foundation & parties depth (supplier status is the `supplierStatus` enum column; tag has no color column so TagSpec is `{name, table}`; holiday.year is GENERATED — never inserted; EUR ships in bootstrap's full ISO currency set so no tier currency insert; EUR-supplier-per-dataset made a validator convention)+- [x] Task 4: Cluster C2 — items depth (verified: typecheck ✓, 18 vitest ✓, db:check ✓×4; one Consume First supersession pair per dataset, customer parts, price overrides, pricing rules, config params, material classification, revision ladders, Timestamp/File/Inspection procedure steps, method op tools+parameters)+- [x] Task 5: Cluster C3 — inventory states (verified: typecheck ✓, 20 vitest ✓, db:check ✓×4; counts Draft+Posted w/ variance ledger, On Hold/Rejected lots, shelf life + expiring lot, Make/Transfer kanbans, stock+warehouse transfers ×3 statuses w/ ledger pairs)+- [x] Task 6: Cluster C4 — sales matrix, RMA, fulfillment lifecycle (verified: typecheck ✓, 22 vitest ✓, db:check ✓×4; full RFQ/quote/SO status matrix incl. No Quote + reasons, posted/partial/voided shipments w/ Sale ledger, invoice lifecycle keyed for C9 settlement, RMAs ×3 statuses, status history, favorites; validator now pins required-status sets)+- [x] Task 7: Cluster C5 — purchasing matrix, returns, OSP, FX (verified: typecheck ✓, 24 vitest ✓, db:check ✓×4; full PO matrix + OSP + EUR PO, posted/partial/voided receipts w/ Purchase ledger + minted batch lots, invoice lifecycle keyed for C9, purchase returns ×3, standalone supplier quotes Draft/Expired/Declined, PO status history)+- [x] Task 8: Cluster C6 — production depth + picking (verified: typecheck ✓, 26 vitest ✓, db:check ✓×4; deadline types, op-status overrides unlocking In Progress/Waiting, Scrap/Rework quantities, op notes, open MES event, picking lists In Progress/Completed w/ ledger; quote-method fill deferred per Decision 9)+- [x] Task 9: Cluster C7 — quality depth (verified: typecheck ✓, 29 vitest ✓, db:check ✓×4; NCRs Registered/In Progress/Closed × all priorities × both sources w/ required-action tasks, MRB approval + Engineering/Quality reviewers, supplier/PO-line/customer/SO-line/lot/inspection links; file-less inspection plan → Partial receipt lot w/ per-feature sampling plans, derived samples + measurements, history; quality docs Draft/Active/Archived; gauges Pending/In/Out-of-Calibration; 5 risks all statuses/sources)+- [x] Task 10: Cluster C8 — change-order lifecycle (verified with Task 9; Start/Engineering Complete/Cancelled notices, item-free, typed + prioritized, NCR-linked, action tasks covering all 4 task statuses)+- [x] Task 11: Cluster C9 — accounting depth (verified: typecheck ✓, 34 vitest ✓, db:check ✓×4; 5 journals incl. Reversed pair + dimension tags, 12 periods Closed/Locked/Open + close tasks, 6 payments + settlements (views probe-verified Paid/Partially Paid/credited), 2 memos, 2 projects, EUR override (global exchangeRate deliberately untouched), Disposed + Units of Production assets; see spec Decision 13)+- [x] Task 12: Cluster C10 — ops slice (maintenance/HR/training) + workflow runs (verified: typecheck ✓, 38 vitest ✓, db:check ✓×4; 5 schedules, 5 dispatches ×5 statuses w/ Maintenance Consumption spare-part issue, 3 trainings (5 question types, Completed+Pending), 6 timecards, 2 suggestions, 2 person notes, 3 runs Succeeded/Failed/Skipped; see spec Decision 14)+- [x] Task 13: Row-count floors in verify.ts (verified: 213 measured floors in datasets/coverage.ts — min across datasets, volume ×0.8; dimension* scoped by companyGroup, favorites via parent, period skipped; one UNION ALL before ROLLBACK; drill pickingList 2→3 + jobFavorite 1→2 → ✗ naming both, exit 1, reverted; see spec Decision 15)+- [x] Task 14: Full verification — seed, audit matrix, re-apply, baselines (verified: audit 264 present / 103 absent all classified, 3 §B gaps fixed ×4 datasets — lifecycle RFQs, Scrapped lot, Production/Prototype revisions; re-apply was broken by posted invoices/settlements/payments + leaked org groups → wipe fixed; sat→rob→sat both 229/231 tables = clean apply; 4 baselines + structural (no methodMaterial/methodOperation decrease, journals balance); drills: DB-down ✗ exit 1, hook "Commit blocked" exit 1; typecheck ✓, 43 vitest ✓, db:check ✓×4, jobs typecheck ✓, biome 0 errors)+- [x] Task 15: Docs — rule file + datasets AGENTS.md + spec appendix (verified: db:check ✓×4 in 3.6s, 43 vitest ✓, typecheck ✓; also packages/database/AGENTS.md, workflow-run-history rule `completedAt` fix, demo-data.mdx + regenerated agent KB; spec Status → Implemented with evidence-ticked acceptance criteria)++## Dependencies++Task 1 → Task 2 → Tasks 3–12 strictly in order (each cluster leaves the tree green; later clusters reference earlier refs). Task 13 after 12. Task 14 after 13. Task 15 after 14. Within each cluster task, the three mirror-industry authoring subtasks are parallel.++---++## Task 1: Loud refs — silent skips become throws++**Depends on:** none+**Files:**+- Modify: `packages/database/src/datasets/tiers/12-planning.ts` — lines ~40-44, ~60-64, ~178-182: replace `if (!item) { ctx.log(...); continue; }` with `need(ctx.refs.items, readableId)`-style resolution; line ~84 `?? null` for the demand order's `cloc:` key → `need`.+- Modify: `packages/database/src/datasets/tiers/09-accounting.ts` — line ~75-78 missing fixedAssetClass → throw with a named error; line ~22-23 "no GL accounts" → throw; line ~84 `ctx.refs.locations[spec.location] ?? ctx.locationId` → `need(ctx.refs.locations, spec.location)`.+- Modify: `packages/database/src/datasets/tiers/04-sales.ts` — lines ~61 and ~320 `ctx.refs.misc[`cloc:${spec.customer}`] ?? null` → `need`.+- Modify: `packages/database/src/datasets/tiers/01-foundation.ts` — line ~131 unguarded shelf parent → `need(ctx.refs.shelves, shelf.parent)` when `shelf.parent` is set; line ~175 unguarded work-center ref → `need`.+- Leave alone: `refs.locations.Plant ?? locationId` in 03/04/12 ONLY if some dataset legitimately lacks a Plant — check all four `foundation.ts`; all four define a plant, so convert to `need(ctx.refs.locations, "Plant")` via a shared helper `plantLocation(ctx)` if the key name varies per dataset, use the dataset's own plant name. If a dataset names its plant differently, resolve by the foundation's `plant.name`.+- Modify: `packages/database/src/check-datasets.ts` — pass a `log` callback through to `verifyDataset` that buffers tier logs and prints them ONLY on failure (so remaining legitimate `ctx.log` diagnostics are visible when something breaks).++**Steps:**+1. Read `packages/database/src/datasets/sql.ts` `need()` (~line 180) for the exact error shape.+2. Make each replacement above. Where the value feeds a nullable column that the spec may legitimately omit (optional field on the spec type), keep optionality — the throw is only for keys that are PRESENT but unresolvable.+3. Run the loop.++**Verify:**+```bash+pnpm --filter @carbon/database typecheck && pnpm --silent db:check:datasets+# Expected: ✓ satellite ✓ robotics ✓ precision ✓ motor (current data is valid, so throws change nothing)+```++**Out of scope:** any data file changes; `06-production.ts` `if (!industryId) return` (a null industryId is a legitimate dataset state).++## Task 2: Pure dataset validator + pre-DB wiring + vitest++**Depends on:** Task 1+**Files:**+- Create: `packages/database/src/datasets/validate.ts`+- Create: `packages/database/src/datasets/validate.test.ts`+- Modify: `packages/database/src/check-datasets.ts` — run the validator for all selected datasets BEFORE `pool.connect()`; on failure print each `✗ <dataset>: <message>` and `process.exitCode = 1` and return (never reach `skip()`).++**Steps:**+1. `export function validateDataset(dataset: Dataset): string[]` returning human-readable violations (empty = valid). Build ref indexes from the dataset itself (item readableIds across all six buckets + change-order-minted revisions; customer names; supplier names; process names; work-center names; shelf names; warehouse names; job keys; opportunity/SO keys). Checks, each with a precise message naming the slice + key:+ - every slice non-empty (arrays length > 0 where the rule doc requires it);+ - every cross-ref string resolves (BOM components, BOP processes/work centers/supplier processes, opening-stock shelves, sales/planning item+customer refs, purchasing supplier refs, job item/SO/customer refs, NCR item/job refs, change-order item refs, kanban/supersession/shelf-life refs, ops-slice refs — extend this list as later tasks add fields);+ - `rfqQuotes[].lines[].prices.length === rfqQuantityBreaks.length`;+ - every `JournalEntrySpec` balances (Σdebit = Σcredit) at 2dp;+ - `promisedDateOffset` values within 0–336 days (48-week horizon);+ - assembly `componentNodeIds` ⊆ node ids of the bundled `assets/<industryId>/models/<name>.graph.json` (resolve via the same glob as `assets.ts`; skip when `industryId` null);+ - net on-hand per (item) never negative: Σ(openingStock + posted receipt quantities) − Σ(posted shipment/pick/consumption quantities authored in data) ≥ 0 — implement against the fields that exist at the time, extend in later tasks;+ - supersession pairs reference two distinct existing items.+2. `validate.test.ts`: `for (const key of datasetKeys) expect(validateDataset(getDataset(key))).toEqual([])`, plus 2–3 negative cases on a hand-built minimal invalid dataset fragment (bad item ref, unbalanced journal) asserting the message text.+3. Wire into `check-datasets.ts` before any DB work, with block message: `The demo datasets are internally inconsistent. Fix them in packages/database/src/datasets/data/ before committing.`+4. Loop.++**Verify:**+```bash+pnpm --filter @carbon/database typecheck && pnpm --filter @carbon/database test && pnpm --silent db:check:datasets+# Expected: vitest green incl. validate.test.ts; ✓ all four datasets+# Then: temporarily break one BOM ref in data/motor/items.ts, run `pnpm --silent db:check:datasets` with the DB STOPPED-equivalent (unset SUPABASE_DB_URL) — expect exit 1 + named violation; revert the break.+```++**Out of scope:** row-count floors (Task 13); DB-layer skip behavior (stays).++## Tasks 3–12: cluster mechanics (applies to every cluster below)++Each cluster task = five subtasks:+1. **Types:** extend `datasets/types.ts` with the cluster's new REQUIRED fields/specs (JSDoc every ref field with what it resolves against, matching existing style).+2. **Engine:** extend the named tier(s). New refs bucket entries go in `ctx.refs` (extend `SeedRefs` if a new bucket is needed).+3. **Satellite data:** author `data/satellite/<slice>.ts` additions (canonical pattern).+4. **Mirror ×3 (parallel subagents):** robotics, precision, motor — same shape/volume, industry-appropriate story. Subagent prompt must include: the cluster's types diff, the satellite file as exemplar, ground rules 2/3/7/8, and the verify loop.+5. **Validator:** extend `validate.ts` + its test for the new ref fields; run the full loop (`typecheck`, `test`, `db:check:datasets`).++## Task 3: Cluster C1 — foundation & parties depth++**Depends on:** Task 2+**Files:** `datasets/types.ts`, `tiers/01-foundation.ts`, `data/*/foundation.ts`, `validate.ts`+**New capabilities (FoundationData):**+- `CustomerSpec`/`SupplierSpec` gain optional `currencyCode` (default "USD"; tier passes through — currency rows for USD/EUR exist from bootstrap, verify `currency` table contents in tier via lookup and throw if code unknown) and optional `paymentTerm` (name matched against bootstrap `paymentTerm` rows via ILIKE-free exact fetch of all terms into `ctx.refs.misc`).+- `SupplierSpec.status` optional `"Active" | "Inactive" | "Pending" | "Rejected"` → `supplier.supplierStatusId`? — READ the `supplier` Insert type first: status is via `supplierStatusType` enum column or a status table; implement per actual schema (escape hatch rule 9 if neither).+- `holidays: { name: string; dateOffset: DayOffset }[]` → `holiday` (companyId-scoped; read Insert type for year/date columns).+- `employeeLinks` (fixed behavior, no per-dataset data): tier links `ctx.userId` to the first 2 abilities (`employeeAbility`) and first shift (`employeeShift`).+- `materialTaxonomy`: seed `materialType`/`materialForm`/`materialSubstance`/`materialGrade`/`materialFinish`/`materialDimension` rows (READ Insert types; some are companyId-scoped with defaults from migrations — only seed what bootstrap doesn't, check for existing rows first with `insertMaybe`), and `MaterialItemSpec` in C2 will reference them.+- `tags: { name: string; color?: string }[]` → `tag` table (read Insert type for `table`/scope column).+**Data volume per dataset:** ≥2 holidays, ≥4 tags, 1 supplier per non-Active status (3 new suppliers), 1 EUR-currency supplier (reuse one of them or add), taxonomy rows apt for the industry (≥1 per taxonomy table).+**Verify:** the standard loop.+**Out of scope:** exchangeRate rows (C9); material item classification (C2).++## Task 4: Cluster C2 — items depth++**Depends on:** Task 3+**Files:** `datasets/types.ts`, `tiers/02-items.ts`, `datasets/helpers/items.ts`, `data/*/items.ts`, `validate.ts`+**New capabilities (ItemsData):**+- `supersessions: { predecessor: string; successor: string; mode: SupersessionMode; conversionFactor?: number; successorEffectivityOffset?: DayOffset; discontinuationOffset?: DayOffset }[]` → `itemSupersession` (PK itemId alone). One per dataset: a phased-out buy part with stock → its successor (Consume First).+- `customerParts: { item: string; customer: string; customerPartId: string; customerRevision?: string }[]` → `customerPartToItem`.+- `priceOverrides` → `customerItemPriceOverride` (+`customerItemPriceOverrideBreak` if the table pair exists — read types; else single-row).+- `pricingRules` → `pricingRule` (one Discount percentage rule for a customer).+- `configurable`: ONE make item per dataset gets `configurationParameterGroup` + 2–3 `configurationParameter` rows (one numeric, one list, one boolean) — display-only depth; NO configurationRule (rules engine risk).+- `MaterialSpec` items gain taxonomy refs (`materialFormId` etc. per Insert type of `material` extension table) resolving against C1 rows.+- `revisionLadder`: ONE part per dataset seeded with revisions across `itemRevisionStatus` values: existing active revision stays Production-equivalent; add a prior Obsolete revision and a Design/Prototype next revision via `createItem` with distinct `revision` strings — READ how `item.active`/`revisionStatus`? column is named in `item` Insert type first (revision status may be `status` on item or separate; implement per schema, escape hatch otherwise).+- Procedure step types: extend `ProcedureStepSpec.type` union with the remaining app-supported types (`File`, `Inspection`, `Task` already?) — compare against DB enum `procedureStepType` and add all values that need no file payload; add ≥1 new-typed step to one procedure per dataset.+- Method op depth: `BopOperationSpec` gains optional `tools: { description: string; quantity: number }[]` and `parameters: { key: string; value: string }[]` → `methodOperationTool`/`methodOperationParameter` (read Insert types; `methodOperationTool` may require a `tool` item id — if so, reference a seeded Tool item).+**Verify:** standard loop.+**Out of scope:** quote methods (C6); BOM restructuring of existing items (keep structural sums stable where possible — additions only).++## Task 5: Cluster C3 — inventory states++**Depends on:** Task 4+**Files:** `datasets/types.ts`, `tiers/03-inventory.ts`, `data/*/inventory.ts`, `validate.ts`+**New capabilities (InventoryData):**+- `inventoryCounts` becomes an array (replaces single `inventoryCount`): keep one Draft; add one **Posted** count with authorable lines `{ item: string; shelf: string; countedQuantity: number }`; for the posted count the tier writes the count + lines + one `itemLedger` `"Positive Adjmt."`/`"Negative Adjmt."` row per non-zero variance (documentType `"Inventory Count"` — confirm enum value in `itemLedgerDocumentType`).+- `trackedStates`: extend `OnHandTrackedSpec` with optional `status` (`Available | On Hold | Rejected | Scrapped`) and optional `expiryOffset: DayOffset`; expiry writes `trackedEntity` attribute or `itemShelfLife`? — READ `itemShelfLife` + `trackedEntity` Insert types; seed `itemShelfLife` on one batch-tracked item (mode `Fixed Duration`) AND stamp expiry on its lots per the traceability model (check `.claude/rules/traceability-model.md` for where expiry lives). Scrapped lot pairs with a `"Scrap"` `itemLedger` row (quantity out) + `productionQuantity`? NO — a standalone scrapped lot only needs the entity status + ledger `Negative Adjmt.` with `Scrap` documentType if the enum allows; keep consistent with validator on-hand math.+- `kanbans`: add `replenishmentSystem` authorable (`Buy | Make | Transfer`); Make kanban references a make item + work-cell-free fields per Insert type; Transfer kanban needs source shelf/location fields per Insert type.+- `stockTransfers`: `{ key; status: "Draft" | "Released" | "Completed"; fromShelf; toShelf; lines: { item; quantity }[] }` → `stockTransfer`+`stockTransferLine`; Completed also writes paired `"Transfer"` itemLedger rows (out/in).+- `warehouseTransfers`: `{ key; status: "Draft" | "To Ship" | "Completed"; fromLocation; toLocation; lines }` → `warehouseTransfer`+`warehouseTransferLine`; Completed writes ledger pairs.+**Data volume:** 2 counts, ≥2 non-Available tracked entities + 1 expiring lot, 3 kanbans (one per system), 3 stock transfers (one per status), 3 warehouse transfers.+**Verify:** standard loop.+**Out of scope:** pickingList (C6 — needs jobs).++## Task 6: Cluster C4 — sales matrix, RMA, fulfillment lifecycle++**Depends on:** Task 5+**Files:** `datasets/types.ts`, `tiers/04-sales.ts`, `data/*/sales.ts`, `validate.ts`+**New capabilities (SalesData):**+- Opportunities extended so the status matrix lands (spec §B): add specs producing quote statuses Draft/Partial/Lost(+`noQuoteReason` + line status `No Quote`)/Cancelled/Expired; RFQ Draft/Closed; SO Needs Approval/To Invoice/Invoiced. Reuse existing spec fields where possible (statuses are already free strings validated by enum at insert).+- `quoteLine` fields: allow authorable line `status` variety (Not Started/In Progress) — already authorable; use it.+- Shipments: `ShipmentSpec` gains `postedOffset?: DayOffset` + per-line `shippedQuantity` already exists; tier change: when status `"Posted"`, set `postingDate`, write per-line `itemLedger` rows (`entryType: "Sale"`, documentType `"Sales Shipment"`, negative quantity, from the line's item default shelf) and set line `shippedQuantity`; support a partial posted shipment (shipped < ordered) and a `"Voided"` one (no ledger).+- Sales invoices: multiple specs with statuses Draft/Submitted/Overdue/Paid/Partially Paid/Voided/Credit Note Issued (payment + settlement rows come in C9 referencing these by key — add `key` to `SalesInvoiceSpec` and register in `ctx.refs.misc` as `sinv:<key>`).+- `salesReturnOrders`: `{ key; status: "Draft" | "To Receive" | "Completed"; customer; returnReason; lines: { item; quantity; salesOrderKey? }[] }` → `salesReturnOrder`+`salesReturnOrderLine` (+credit line table if NOT NULL-required; read types). Completed return writes a `"Positive Adjmt."`-family ledger row per line (documentType from `itemLedgerDocumentType` — use the sales-return value present in the enum).+- `statusHistory`: tier writes 2–3 `salesOrderStatusHistory` rows for one order (Draft→Confirmed→In Progress with staggered `createdAt` timestamps via `resolveTimestamp`).+- `favorites`: tier stars 1 job/quote/SO for `ctx.userId` (`jobFavorite`, `quoteFavorite`, `salesOrderFavorite`).+**Verify:** standard loop + spot query in the run log:+```bash+psql postgresql://postgres:postgres@localhost:57312/postgres -c 'SELECT DISTINCT status FROM "quote"' # via a check-datasets debug run is NOT possible (rollback); rely on Task 14 audit instead+pnpm --filter @carbon/database typecheck && pnpm --filter @carbon/database test && pnpm --silent db:check:datasets+# Expected: green ×4+```+**Out of scope:** payments/settlements (C9); RMA credit memos (C9).++## Task 7: Cluster C5 — purchasing matrix, returns, OSP, FX++**Depends on:** Task 6+**Files:** `datasets/types.ts`, `tiers/05-purchasing.ts`, `data/*/purchasing.ts`, `validate.ts`+**New capabilities (PurchasingData):**+- Direct PO specs cover remaining statuses: Planned, Closed, Rejected, Needs Approval, To Review, Completed; one PO `purchaseOrderType: "Outside Processing"` referencing the OSP supplier process from foundation.+- One PO in EUR against the EUR supplier (`currencyCode`, `exchangeRate` on the PO per Insert type), left unpaid.+- Receipts: `ReceiptSpec.status` gains `"Posted"` + `postedOffset`; posted receipt writes per-line `itemLedger` (`entryType: "Purchase"`, documentType `"Purchase Receipt"`, positive, `receivedQuantity` set); one partial posted receipt (received < ordered); one Voided.+- For the batch-tracked receipt line: also create a `trackedEntity` (Purchased source) linked per the traceability idiom used in tier 03 — read how `itemTracking`/`trackedEntity.sourceDocument` values are used for receipts (`itemTrackingSourceDocument` "Receipt").+- Purchase invoices: statuses Open/Overdue/Paid/Partially Paid/Voided/Debit Note Issued (+`key` registered as `pinv:<key>` for C9).+- `purchaseReturnOrders`: Draft / To Ship / Completed (+ ledger out rows on Completed).+- Supplier quote `status` becomes authorable (`Draft | Active | Expired | Declined`) — replace the hardcode; add one of each beyond the RFQ trio (keep RFQ trio Active).+- `purchaseOrderStatusHistory` rows for one PO.+**Verify:** standard loop.+**Out of scope:** payments/memos (C9); supplier approval workflow tables (EE-adjacent `approvalRequest` — excluded per spec).++## Task 8: Cluster C6 — production depth + picking++**Depends on:** Task 7+**Files:** `datasets/types.ts`, `tiers/06-production.ts`, `datasets/helpers/job-method.ts`, `data/*/production.ts`, `validate.ts`+**New capabilities (ProductionData):**+- `JobSpec.deadlineType` authorable (all four values across the 8 jobs); `JobSpec.operationOverrides?: { order: number; status: JobOperationStatus }[]` applied after `copyMethodToJob` → unlocks `In Progress` and `Waiting` ops on the in-progress job.+- `quantities`: authorable `productionQuantity` specs per job `{ type: "Production" | "Scrap" | "Rework"; quantity; scrapReason? }` (scrapReason resolved from bootstrap `scrapReason` rows loaded into refs). Add Scrap(2, with reason) + Rework(1) to the in-progress job.+- One `rework` row if the `rework` table's Insert type is satisfiable from job/operation refs (read type; else drop with a spec note — escape hatch).+- `jobOperationNote`: 1–2 notes on in-progress job ops. `jobOperationBatch`: ONE Active batch on the in-progress job's first op if Insert type is satisfiable from (operation, quantities); else escape hatch.+- Open MES event: extend the shifts/events spec so ONE production event for `ctx.userId` has `endTime: null` (Setup, started ~1h ago via `resolveTimestamp`).+- `pickingLists`: `{ key; status: "In Progress" | "Completed"; jobKey; lines: { item; quantityRequired; quantityPicked; status: "Pending" | "Picked" | "Short"; fromShelf }[] }` → `pickingList` + `pickingListLine` (read Insert types; link to job + location). Completed list's Picked lines write paired `"Transfer"` ledger rows shelf→lineside (work-center floor unit from foundation refs). In-Progress list has Pending + one Short line, no ledger.+- Quote methods attempt: mirror `copyMethodToJob` as `copyMethodToQuote` filling `quoteMakeMethod`/`quoteMaterial`/`quoteOperation` for the SENT quote's lines (adopt interceptor-created `quoteMakeMethod` rows like tier 6 adopts jobMakeMethod). Time-box: if the interceptor/row graph fights back after 2 honest attempts, drop, record in spec (Decision 9 fallback), and continue.+**Verify:** standard loop.+**Out of scope:** scheduling engine rows (`capacityReservation`), jobOperationDependency.++## Task 9: Cluster C7 — quality depth++**Depends on:** Task 8+**Files:** `datasets/types.ts`, `tiers/07-quality.ts`, `data/*/quality.ts`, `validate.ts`+**New capabilities (QualityData):**+- NCR: authorable `type` (name resolved against bootstrap `nonConformanceType` rows), add a **Closed** NCR (with `closeDateOffset` per Insert type); priorities across all four; one `source: "External"` NCR with `nonConformanceSupplier` + `nonConformancePurchaseOrderLine` associations; add `nonConformanceCustomer`, `nonConformanceSalesOrderLine`, `nonConformanceTrackedEntity` on others; task depth: 1–2 `nonConformanceActionTask` (Containment/Corrective, varied `nonConformanceTaskStatus`), 1 `nonConformanceApprovalTask` (MRB), 1 `nonConformanceReviewer`; required-action link via bootstrap `nonConformanceRequiredAction` rows if the task tables reference them (read types).+- `inspections`: ONE inspection story on the posted receipt (C5): `inspection` (status `Passed` or `Partial`), 2 `inspectionSample` rows (one Passed one Failed), 2–3 `inspectionMeasurement` rows; plus ONE `inspectionSamplingPlan` (AQL, ANSI_Z1_4, level II) on the received item. Read all four Insert types first; source doc "Receipt".+- `qualityDocuments`: 3 (`Draft`/`Active`/`Archived`) with a couple of `qualityDocumentStep` rows on the Active one (if step table Insert is satisfiable).+- `gauges`: 3 gauges (2 Active incl. one Master role, 1 Inactive), types from bootstrap `gaugeType`; `gaugeCalibrationRecord` rows producing all three `gaugeCalibrationStatus` values (calibration status may live on gauge — read types and place accordingly).+- `risks`: ≥4 `riskRegister` rows: statuses Open/In Review/Mitigating/Closed(or Accepted), one `type: "Opportunity"`, sources spread (Customer/Supplier/Item/Job) with the matching FK columns per Insert type.+**Verify:** standard loop.+**Out of scope:** `inspectionDocument`/ballooning (file-adjacent), issue workflows (`nonConformanceWorkflow` — verify shape; include ONLY if a plain row links NCR→existing issue workflow config without file payloads, else skip with spec note).++## Task 10: Cluster C8 — change-order lifecycle++**Depends on:** Task 9+**Files:** `datasets/types.ts`, `tiers/08-change-orders.ts`, `data/*/change-orders.ts`, `validate.ts`+**Steps:** add three more change orders per dataset with statuses `Start`, `Engineering Complete`, `Cancelled` (types Engineering/Manufacturing/Documentation spread); attach 1–2 `changeOrderActionTask` rows with varied `changeOrderTaskStatus` (read Insert type; required-action from bootstrap `changeOrderRequiredAction`); keep existing three orders untouched.+**Verify:** standard loop.+**Out of scope:** additional Version/Revision method clones (method churn risks structural sums).++## Task 11: Cluster C9 — accounting depth++**Depends on:** Task 10+**Files:** `datasets/types.ts`, `tiers/09-accounting.ts`, `data/*/accounting.ts`, `validate.ts`+**New capabilities (AccountingData):**+- `journalEntries`: extend `accountClass` union to all five classes; add 2 Posted entries (balanced, business-flavored: payroll accrual, depreciation) and 1 Reversed pair (original + reversal linked per `journalEntry`/`journal` reversal columns — read types).+- `periods`: tier ensures `accountingPeriod` rows for the trailing 12 months (derive from anchor via `previousMonthEnd`-style helpers; check uniqueness/insertMaybe — table may be companyId-scoped with fiscal linkage; read types); mark the oldest seeded period `periodCloseStatus` Closed and one Locked; write 2–3 `periodCloseTask` rows (statuses Open/Done/Skipped) for the current period referencing bootstrap `periodCloseTaskDefinition`.+- `exchangeRates`: EUR rate today + 3 history points (`exchangeRate` + `exchangeRateHistory` if present — read types).+- `payments`: `{ key; type: "Receipt" | "Disbursement"; amount; dateOffset; customer?/supplier?; applies: { invoiceKey; amount }[] }` → `payment` + `invoiceSettlement` rows against C4/C6 invoice keys (`sinv:`/`pinv:` refs). Fully settle the Paid invoices; partially settle the Partially Paid ones. Respect base-vs-document amounts (all settled invoices are USD by design — the EUR PO/invoice stays unpaid; see `.claude/rules/numeric-precision.md` accounting boundaries).+- `memos`: 1 Posted credit memo (customer, tied to the Credit Note Issued sales invoice) + 1 Posted debit memo (supplier).+- `projects`: 2 rows; link one to a job if `job.projectId` exists (read type).+- `dimensionValues`: 2 `dimensionValue` rows on a bootstrap Custom dimension + `journalLineDimension` on one posted journal line (read types; skip journalLineDimension if it demands sync-ledger coupling — escape hatch).+- Fixed assets: add one **Disposed** asset + `fixedAssetDisposal` (Sale) — extend `FixedAssetSpec.status` union; add one Units of Production asset + 2 `fixedAssetUsageLog` rows if table Insert is satisfiable.+- Fix the journal-skip trap: the existing "skip if journalEntryId exists" guard stays (wipe preserves journals) but log now surfaces via Task 1's failure-only log path.+**Verify:** standard loop.+**Out of scope:** costLedger (valuation report feeds from item ledger/costs; confirmed out), card transactions, intercompany, sync tie-out.++## Task 12: Cluster C10 — ops slice (maintenance/HR/training) + workflow runs++**Depends on:** Task 11+**Files:** `datasets/types.ts` (new `ops: OpsData` slice on Dataset), `tiers/10-ops.ts` (real implementation), `tiers/11-workflows.ts`, `data/*/ops.ts` (new file), `data/*/index.ts` (register slice), `data/*/workflows.ts`, `validate.ts`+**New capabilities:**+- `OpsData.maintenanceSchedules`: ≥3 per dataset (work-center-linked, frequencies spread) → `maintenanceSchedule` (+`maintenanceScheduleItem` if NOT NULL-required).+- `OpsData.maintenanceDispatches`: 5 — one per status (Open/Assigned/In Progress/Completed/Cancelled), severity/priority/source/OEE-impact spread, failure modes from bootstrap `maintenanceFailureMode`, work-center refs; the Completed one consumes a consumable via the dispatch-item table (read `maintenanceDispatch*` child Insert types; issue = itemLedger `Negative Adjmt.` documentType consistent with app behavior — check MES `dispatch.$dispatchId.add-and-issue` service for the documentType used and mirror it).+- `OpsData.trainings`: 2 courses (Active + Draft) with ≥5 `trainingQuestion` rows covering all five `trainingQuestionType` values on the Active one; `trainingAssignment` rows for `ctx.userId` (one Completed w/ completion row if table exists, one Pending).+- `OpsData.timecards`: ≥5 `timeCardEntry` rows for `ctx.userId` over the past week (read Insert type for start/end/work-center columns).+- `OpsData.suggestions`: 2 `suggestion` rows. `OpsData.notes`: 2 `note` rows (one on a job, one on a customer — read `note` Insert type for the polymorphic id columns).+- Workflow runs (tier 11): for the published workflow, seed 3 terminal `workflowRun` rows (Succeeded / Failed / Skipped, `isTest: false`, `completedAt` set, `sourceEventId` `"seed:<n>"`) + `workflowStepRun` rows (trigger step + one action step each, per the run-history rule's shapes — read `.claude/rules/workflow-run-history.md` and both Insert types; `versionId` = the published version).+**Verify:** standard loop.+**Out of scope:** peopleAbsence/peopleAssignment (thin UI value), lessonCompletion/challengeAttempt (academy).++## Task 13: Row-count floors in verify.ts++**Depends on:** Task 12+**Files:**+- Create: `packages/database/src/datasets/coverage.ts` — `export const COVERAGE_FLOORS: Record<string, number>` listing every seeded table and its minimum row count (derive actuals from Task 14's first seed run; floor = actual for singletons, actual−20% rounded down for volume tables).+- Modify: `packages/database/src/datasets/verify.ts` — after `applyDatasetTiers`, before ROLLBACK: one query per floors entry (`SELECT count(*) FROM "<table>" WHERE "companyId" = $1` — skip the WHERE for the global `period` table), collect all failures into the returned error as `table <t>: expected ≥ N, got M`.+**Verify:**+```bash+pnpm --filter @carbon/database typecheck && pnpm --silent db:check:datasets+# Expected: ✓ ×4. Then temporarily set one floor above actual → expect ✗ naming the table; revert.+```+**Out of scope:** structural sums (stay in the manual baseline procedure).++## Task 14: Full verification — seed, audit matrix, re-apply, baselines++**Depends on:** Task 13+**Steps:**+1. `pnpm db:seed:dev -- --email [email protected] --dataset satellite` (bootstraps a scratch user+company; does NOT touch the user's own company).+2. Audit script (one-off, `.ai/scratch/` or scratchpad): psql against `postgresql://postgres:postgres@localhost:57312/postgres` printing `SELECT DISTINCT status FROM <table> WHERE "companyId" = <scratch>` for every status-bearing table in the spec §B matrix; save output to `.ai/runs/2026-09-22-demo-data-status-audit.txt`; verify every ✱ value appears; fix data and re-run until complete.+3. Re-apply check: `pnpm db:seed:dev -- --email [email protected] --dataset robotics` over the same company (exercises `wipeFirst`); must complete green; spot-check `assertSingle` didn't fire and counts match robotics.+4. Capture new baselines: the seed's `Seeded row counts` block → `.ai/runs/2026-09-22-seed-baseline-<key>.txt` for all four (satellite also structural sums per the rule doc's procedure).+5. Full gates: `pnpm --filter @carbon/database typecheck && pnpm --filter @carbon/database test && pnpm run lint` (lint scoped if the repo command is slow: `pnpm exec biome check packages/database/src/datasets`).+6. Deliberate-failure drill (acceptance #1/#2): break a ref, confirm `git commit` (dry: run `.husky/pre-commit` directly with the file staged) blocks with the named violation; revert.+**Verify:** audit file complete; all commands green; working tree has only intended changes (`git status`).++## Task 15: Docs — rule file + AGENTS.md + spec appendix++**Depends on:** Task 14+**Files:**+- Modify: `.claude/rules/onboarding-company-templates.md` — new slices, the pure validator, floors, new baseline paths, updated "Adding an industry" (12 slices incl. ops), corrected drift-check description (now blocks on internal inconsistency even with DB down).+- Modify: `packages/database/src/datasets/AGENTS.md` — same, local detail.+- Modify: `.ai/specs/2026-09-22-demo-data-completeness.md` — final Autonomous Decisions additions (anything re-decided via escape hatches), acceptance checklist ticked with evidence pointers.+**Verify:** `pnpm --silent db:check:datasets` one last time; `git status` shows only the intended files.diff --git a/.ai/plans/2026-09-23-demo-data-review-fixes.md b/.ai/plans/2026-09-23-demo-data-review-fixes.mdnew file mode 100644index 0000000000..eebe8aa05c--- /dev/null+++ b/.ai/plans/2026-09-23-demo-data-review-fixes.md@@ -0,0 +1,24 @@+# Demo data — thermo-nuclear review fixes++**Source:** `.ai/runs/2026-09-23-thermo-nuclear-review.md` (item numbers #1–#24 + Minor), detail files `.ai/runs/2026-09-23-tnr-{A,B,C,D}-*.md`.+**Branch:** `feat/demo-data-completeness` · user chose: fix everything, in the suggested order.++## Ground rules++1. Repo `/Users/aashu/work/carbon/carbon`. pnpm only. Never commit/stash/reset/checkout; never `.claude/worktrees`; never rebuild the DB. DB writes only in rolled-back transactions or `pnpm db:seed:dev -- --email [email protected] …`.+2. Behaviour-preserving unless the item is a bug fix. **Golden oracle:** `…/scratchpad/golden/compare.sh` re-applies all 4 datasets (rolled back) and diffs per-table row counts against `baseline.json`. Pure refactors must print `DIFFS: 0`. A fix may change counts only in the tables it names — list every delta in the step report; then refresh the baseline with `cp current.json baseline.json` (the orchestrator does this after review).+3. Gate after every step: `pnpm --filter @carbon/database typecheck` (exit 0) · `pnpm --filter @carbon/database test` (all pass) · `pnpm --silent db:check:datasets` (✓×4) · `pnpm exec turbo run typecheck --filter=@carbon/jobs` · `pnpm exec biome check packages/database/src packages/jobs/src` (0 errors) · golden compare.+4. Engine rules unchanged: `need()`, DayOffset dates, tenancy predicates, no literal PKs, no global-table writes, no auth-claim spoofing. Comments sparse (why only).+5. Autonomous mode: resolve gaps with the ship-it ladder; record decisions in `.ai/specs/2026-09-23-demo-data-screen-coverage.md` Autonomous Decisions (continue numbering).++## Progress+- [x] R1: Single method copier (#8) → fixes #12 change-order tools/params, #13 quote assembly link (set in tier 02)+- [x] R2: Split `types.ts` → `types/<slice>.ts` + `types/engine.ts` + `context.ts` (#2) — D83/D84+- [x] R3: Split `validate.ts` → `validate/` modules (#1) + table-driven `validate.test.ts` (#3) — D85–D87+- [x] R4: SSOT small: enum-derived REQUIRED table (#4), shared GL sign/balance (#6), inspection-verdict core in `functions/shared` (#7), one lookup helper (#9), RULE_FIELDS + EVENT_SOURCES drift tests (#10, #11), return-credit/tier 09 memo dedupe (#21) — D88–D93+- [ ] R5: SSOT large: pure posting builders extracted from edge functions and imported (#5)+- [ ] R6: Wipe policy map (#15) + complete VOID pass (#14) + ledger-driven valuation (#16)+- [ ] R7: Types & refs: discriminated unions + generated enums (#17), typed refs (#18), job-specific production fields onto job specs (#20), sales/purchasing header dedupe (#19)+- [ ] R8: Data packs: derived defaults (#22), job → salesOrderLine only (#23), comment dedupe (#24)+- [ ] R9: Minor list (planningError, `.cts` entry, activeJobStatuses, repoRoot, fallbacks, companyId predicates, rowCount checks, coverage typing, footer, header, exports)+- [ ] R10: Full verification (gate + real re-apply + screen matrix ×4 + pre-commit drill) + docs sync + review re-rundiff --git a/.ai/plans/2026-09-23-demo-data-screen-coverage.md b/.ai/plans/2026-09-23-demo-data-screen-coverage.mdnew file mode 100644index 0000000000..893e41927b--- /dev/null+++ b/.ai/plans/2026-09-23-demo-data-screen-coverage.md@@ -0,0 +1,212 @@+# Demo Data Screen Coverage — implementation plan++**Spec / source:** `.ai/specs/2026-09-23-demo-data-screen-coverage.md`+**Branch:** `feat/demo-data-completeness` (checkout `/Users/aashu/work/carbon/carbon`)+**Research (per-screen sources, filters, exact tables to seed):**+- `.ai/research/2026-09-23-screen-audit-erp-commercial.md` (sales, purchasing, invoicing, accounting)+- `.ai/research/2026-09-23-screen-audit-erp-operations.md` (production, items, inventory)+- `.ai/research/2026-09-23-screen-audit-mes-quality-resources.md` (MES, quality, resources, workflows)+- `.ai/research/2026-09-23-screen-audit-erp-settings-people.md` (settings, users, people)+- `.ai/research/2026-09-23-planning-engine-seeding.md` (MRP + scheduler)++## Ground rules for every task (read once, apply always)++1. Working dir `/Users/aashu/work/carbon/carbon`. Always `pnpm`, never `npm`. **Never commit, stash, reset or checkout** — the user commits. Never use `.claude/worktrees`. Never rebuild the database. Never write to the DB outside (a) rolled-back transactions and (b) `pnpm db:seed:dev -- --email [email protected] …` (the scratch company `dapnjkh860gjckkl52t0`). Company `dap2gkh860gg2ccl14sg` belongs to the user — SELECT only.+2. Engine idiom (unchanged from the 2026-09-22 plan): tiers use `insertRow`/`insertId`/`insertMaybe` from `datasets/sql.ts`; refs via `need(map, key, label)` — never `map[key]!` or a silent `continue`; dates ONLY via `DayOffset` + `resolveDate`/`resolveTimestamp` (`datasets/dates.ts`) — no JS `Date`, no `CURRENT_DATE`; every query carries a `companyId` (or `companyGroupId`) predicate; never a literal primary key; never write global tables (`user`, `exchangeRate`, `period` except tier 12's locked insert).+3. Before inserting into a table for the first time, read its `Insert` type in `packages/database/src/types.ts` and its CHECK constraints (`psql … -c "select pg_get_constraintdef(oid) from pg_constraint where conrelid='\"<table>\"'::regclass and contype='c'"`). Check for sync interceptors that already create the row (adopt-and-UPDATE on unique violation, as tier 02 does for `itemCost`).+4. All four data packs move together: new `Dataset` fields are REQUIRED (compile-enforced parity). Author `data/satellite/` first, then robotics / precision / motor with industry-appropriate content of the same shape and volume. Keep each industry's story voice.+5. Every new shape gets, in the same task: a `validate.ts` rule (refs resolve; required variety via a `REQUIRED_*` set where it is a status/family/type) + a negative case in `validate.test.ts`.+6. Verification loop after every task (all must be green before the next task):+ ```bash+ pnpm --filter @carbon/database typecheck # Expected: no output, exit 0+ pnpm --filter @carbon/database test # Expected: all tests passed+ pnpm --silent db:check:datasets # Expected: ✓ satellite ✓ robotics ✓ precision ✓ motor+ ```+7. Floors: after a task adds rows to a table, add/raise its entry in `datasets/coverage.ts` `COVERAGE_FLOORS` (floor = min count across the 4 datasets, ×0.8 for volume tables). Engine outputs (`demandActual`, `demandForecast`, `demandForecastSource`, `supplyActual`, `supplyForecast`, `capacityReservation`, `jobOperationDependency`) stay OUT of the floors.+8. If an assumption in a task turns out false (missing column, CHECK shape differs, interceptor conflict, screen filter different from the research), re-decide via the ship-it resolution ladder, record it in the spec's Autonomous Decisions section, and continue. Improvising silently or silently dropping coverage is forbidden.+9. Comments: only where a future dev needs the why; one line by default. No task/cluster tags in code comments.++## Progress+- [x] Task 1: Wipe — model-only slides + refusal preflight+- [x] Task 2: Post-commit planning step (MRP + scheduler) for both callers+- [x] Task 3: Production floor (B1)+- [x] Task 4: Planning inputs, people & time (B2 + B6 time cards)+- [x] Task 5: Sales & purchasing surfaces (B3)+- [x] Task 6: Invoicing & accounting (B4)+- [x] Task 7: Quality, maintenance, resources (B5)+- [x] Task 8: Settings & people remainder (B6)+- [x] Task 9: Screen matrix — script, real seeds ×4, fix loop+- [x] Task 10: Full verification + evidence+- [x] Task 11: Docs++## Dependencies+Task 1 and Task 2 are independent of each other and of the data tasks. Tasks 3–8 run **sequentially** (all touch `types.ts`, `validate.ts`, `coverage.ts`). Task 4 needs Task 3 (assignments reference the new jobs). Task 9 needs 1–8. Task 10 needs 9. Task 11 needs 10.++---++## Task 1: Wipe — model-only slides + refusal preflight++**Depends on:** none+**Files:**+- Modify: `packages/database/src/datasets/wipe.ts`+- Precedent: `TRANSIENT_MRP_TABLES` handling in the same file (delete before `nullNullableReferences`).++**Steps:**+1. Add `const MODEL_SLIDE_TABLES = ["assemblyInstructionStepSlide", "methodOperationStepSlide", "jobOperationStepSlide", "quoteOperationStepSlide"]` with a one-line why (their `imagePath OR modelUploadId` CHECK cannot survive the FK-nulling pass). Delete each (if in `deleteSet`) right after the `TRANSIENT_MRP_TABLES` loop.+2. Add `async function assertWipeable(ctx)` called first in `wipeCompanyBusinessData`, before any write. It runs one query per case, scoped by `companyId`:+ - `SELECT count(*) FROM customer WHERE "companyId"=$1 AND "intercompanyCompanyId" IS NOT NULL` (+ same for `supplier`) → throw `Seed: this company trades with other companies in its group (N intercompany customer/supplier record(s)). Demo data can only be applied to a company without intercompany partners.`+ - `SELECT count(*) FROM "cardTransaction" WHERE "companyId"=$1 AND status <> 'Draft'` → throw `Seed: this company has N posted or voided card transaction(s), which cannot be deleted. Demo data can only be applied to a company without posted card transactions.`+3. Keep the accounting-period change already in the working tree (PRESERVED `accountingPeriod`, tier 09 period adoption).++**Verify:** a scratchpad probe (not committed) that, per case, inside `BEGIN … ROLLBACK` on company `dap2gkh860gg2ccl14sg` (user `eeb03435-d6ca-4665-8c0d-bde873fe3b7e`), creates the state and calls `applyDatasetTiers(…, wipeFirst: true)`:+- IC customer: `UPDATE customer SET "intercompanyCompanyId"='dapnjkh860gjckkl52t0' WHERE id=(first customer)` → expected error starts `Seed: this company trades with other companies`+- Posted card: insert Draft `cardTransaction` (cardAccountId = a Liability account of the company group) then UPDATE to Posted with postingDate/postedAt/postedBy → expected `Seed: this company has 1 posted or voided card transaction`+- Model-only slide: insert `modelUpload(modelPath)` + `assemblyInstructionStepSlide(stepId=a seeded step, modelUploadId)` → expected `APPLY OK`+- Baseline → `APPLY OK`+Place the probe at `packages/database/src/zz-probe.ts` (tsx must resolve `./client.ts`; run `pnpm exec tsx src/zz-probe.ts` from `packages/database`) and DELETE it afterwards. Save output to `.ai/runs/2026-09-23-wipe-probes.txt`. Then the standard loop.+**Out of scope:** changing the triggers themselves.++## Task 2: Post-commit planning step (MRP + scheduler) for both callers++**Depends on:** none+**Files:**+- Create: `packages/jobs/src/demo-planning.ts` — `planDemoCompany`+- Create: `packages/jobs/src/scripts/plan-company.ts` — CLI (precedent: `packages/jobs/src/scripts/check-backups.ts`)+- Modify: `packages/jobs/package.json` — script `"plan:company": "tsx --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/scripts/plan-company.ts"`+- Modify: `packages/jobs/src/inngest/functions/tasks/company-template.ts` — new step after `apply-template`+- Modify: `packages/database/src/seed-dev.ts` (+ `datasets/cli.ts` if args live there) — spawn the script; `--skip-plan`+- Precedents: `packages/jobs/src/inngest/functions/scheduled/mrp.ts:86` (runMrp call), `apps/erp/app/routes/api+/schedule.ts` (runLocationSchedule call)++**Steps:**+1. `planDemoCompany({ companyId, userId }): Promise<{ mrp: "ok" | string; schedule: { locationId: string; result: "ok" | string }[] }>`:+ - `const client = getCarbonServiceRole(); const db = getJobDatabaseClient();`+ - `await runMrp(client, db, { type: "company", id: companyId, companyId, userId })` in try/catch → record message.+ - Locations to schedule: `SELECT DISTINCT "locationId" FROM job WHERE "companyId"=$1 AND status IN ('Ready','In Progress','Paused') AND "locationId" IS NOT NULL` (Kysely). For each: `await runLocationSchedule({ db, client, locationId, companyId, userId })` in try/catch.+ - Never throws; returns the per-step outcome.+2. Template job: after the `apply-template` step returns successfully, `await step.run("plan-template", () => planDemoCompany({ companyId, userId }))`; log failures; write `planningError` into the marker's metadata only if a sub-step failed (read how the marker metadata is updated in the same file and reuse that helper). A planning failure must not change the marker status from its post-apply value.+3. CLI `plan-company.ts`: `parseArgs` `--company`, `--user` (required) → `planDemoCompany` → print one line per step (`MRP ✓` / `MRP ✗ <msg>`, `Schedule <locationId> ✓/✗`); exit 0 even on failure (planning is best-effort), exit 1 only on bad args.+4. `seed-dev.ts`: after the seed commits, unless `--skip-plan`, `spawnSync("pnpm", ["--silent", "--filter", "@carbon/jobs", "plan:company", "--", "--company", companyId, "--user", userId], { stdio: "inherit", cwd: <repo root> })`; on non-zero status print `⚠ Planning step failed — run it later with: pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id>`. Document `--skip-plan` in the CLI usage text.+**Verify:**+```bash+pnpm exec turbo run typecheck --filter=@carbon/jobs # Expected: Tasks: N successful+pnpm --filter @carbon/database typecheck # Expected: exit 0+pnpm db:seed:dev -- --email [email protected] --dataset robotics # Expected: exit 0, "MRP ✓", "Schedule … ✓"+psql postgresql://postgres:postgres@localhost:57312/postgres -At -c "select (select count(*) from \"demandActual\" where \"companyId\"='dapnjkh860gjckkl52t0'),(select count(*) from \"capacityReservation\" where \"companyId\"='dapnjkh860gjckkl52t0')"+# Expected: both > 0+```+If `runMrp`/`runLocationSchedule` need env not present locally (service key/URL), re-decide per ground rule 8.+**Out of scope:** changing engine code; the `carbon/mrp` event (nothing consumes it).++## Task 3: Production floor (B1)++**Depends on:** none (sequential with 4–8)+**Files:** `datasets/types.ts`, `tiers/06-production.ts`, `data/*/production.ts`, `data/*/items.ts` (if short-routing items are needed), `validate.ts`, `validate.test.ts`, `coverage.ts`+**Screens to fill (research: operations §Production, MES §5):** Priorities (week + Unscheduled), MES operations board (all plant work centers), MES Assigned, work-center displays, production KPIs (completion time, estimates vs actuals), job Steps tab, batches, MES inspection op, MES assembly 3D, procedures lifecycle, make-method status, pickMethod.+**Capabilities:**+- Re-date existing open jobs (Ready/In Progress/Paused/Planned) to due −3…+21; keep document chronology valid (validator).+- ≥ 10 new released jobs per dataset (mix Ready / In Progress), short routings, every plant work center gets ≥ 2 open ops; 1 Ready job with `dueDate` NULL; 2 make-to-stock jobs (no sales order).+- `JobSpec.priority` (distinct 1…n) and `assignee: "self"` → `ctx.userId`; op-level `assignee` on ~6 open ops.+- 3 Completed jobs finished −25…−3 with `releasedDate` and Setup/Labor/Machine `productionEvent`s whose durations roughly match estimates; open `productionEvent` (`endTime` NULL, start today) on 3–4 more work centers with those ops `In Progress`.+- `jobOperationStepRecord` for done ops with steps; `jobOperationParameter`, `jobOperationTool` on ≥ 3 ops (read tables first).+- One item's Final Inspection method op: `operationType='Inspection'` + `inspectionDocumentId` (the seeded inspection document); copied to its jobs by `copyMethodToJob` (extend the helper if it drops those columns).+- Link the seeded assembly instruction to the assembly op (`methodOperation.assemblyInstructionId` + job copy).+- One process `batchable=true`; an Active `jobOperationBatch` with ≥ 2 member ops from different jobs.+- Procedures: versions so the set shows Draft, Active and Archived; make methods of seeded items `Active`; assembly instruction in its published/active status (read the enum).+- `pickMethod` default shelf per stocked item at the plant.+- Validator: `REQUIRED_PROCEDURE_STATUSES = {Draft, Active, Archived}`; ≥ 18 jobs; every plant work center has ≥ 1 open op; ≥ 1 open job due within 0…+7; ≥ 1 released job without due date.+**Verify:** loop (ground rule 6) + floors updated.+**Out of scope:** capacityReservation / op dates (the scheduler writes them — Task 2).++## Task 4: Planning inputs, people & time (B2 + B6 time cards)++**Depends on:** Task 3+**Files:** `types.ts`, `tiers/01-foundation.ts`, `tiers/10-ops.ts`, `tiers/12-planning.ts`, `data/*/foundation.ts`, `data/*/ops.ts`, `data/*/planning.ts`, validator, floors+**Capabilities:**+- Shifts created at the plant location (today `ctx.locationId` = HQ, `01-foundation.ts:43-47`) + `workCenterShift` for every plant work center; `employeeShift` points at a plant shift.+- Upsert the applying user's `employeeJob` (today an UPDATE that no-ops when the row is missing, `01-foundation.ts:117-122`): `locationId` = plant, `title`, `departmentId`, `shiftId`, `startDate`, `managerId` NULL. Do NOT modify the `user` row.+- `peopleAssignment` for the applying user across the current week (not only today — today's row pre-filters the MES board to one work center; research MES §4; pick days −2…+4 excluding today OR today on the work center with the most ops, and record which), + 1 `peopleAbsence` next week.+- `companySettings.timeCardEnabled = true`; one open `timeCardEntry` (clockIn today 07:00 company TZ, clockOut NULL) unless it conflicts with an existing open entry rule (read constraints).+- Planning setup at HQ too (one reorder policy + projection) so the location picker on HQ is not empty.+**Verify:** loop.++## Task 5: Sales & purchasing surfaces (B3)++**Depends on:** Task 4+**Files:** `types.ts`, `tiers/02-items.ts`, `tiers/04-sales.ts`, `tiers/05-purchasing.ts`, `data/*/items.ts`, `data/*/sales.ts`, `data/*/purchasing.ts`, validator, floors; new helper if needed `helpers/quote-method.ts` (precedent: `helpers/job-method.ts` `copyMethodToJob`)+**Capabilities:**+- `enforcementRule` families `sales` (item-targeted; CHECK: targetType 'item', appliesToAll false, surfaces ⊂ quoteLine/salesOrderLine/salesInvoiceLine, severity warn|error), `storage`, and a work-center rule; assignments via `enforcementRuleItemAssignment` / `enforcementRuleWorkCenterAssignment`. Read the condition JSON shape from `packages/ee/src/rules/` models before authoring. `REQUIRED_ENFORCEMENT_RULE_FAMILIES` covers every family the UI lists.+- Customer portals: `externalLink` documentType `Customer` for 2 customers (documentId = customerId), id minted by default (never literal).+- `approvalRule` (purchaseOrder ≥ 5000, ≥ 25000; supplier) with `approverGroupIds` = the company's Admin employee-type group (resolve by query, never a literal); Pending `approvalRequest` for the Needs-Approval PO and the Pending supplier (read `packages/ee/src/approvals/` for the request shape).+- Quote methods: copy each Make-to-Order quote line's item method into `quoteMakeMethod`/`quoteMaterial`/`quoteOperation` (adopt interceptor-created `quoteMakeMethod` like tier 06 adopts `jobMakeMethod`).+- Configurator: one configurable item `requiresConfiguration=true`, one `configurationRule`, one quote line with a configuration.+- `assignee` = applying user on ≥ 2 open quotes, SOs, POs, RFQs; `status` on every supplier; `createdAt` of quotes/RFQs/supplier quotes spread over past offsets (a new optional `createdOffset`); 2 more `pricingRule`s; customer/supplier bank-account rows only if the table is company-scoped tenant data (check).+- Return orders: memos linked via `salesReturnOrderId`/`purchaseReturnOrderId` + their credit lines; `nonConformanceSalesReturnOrderLine` / `nonConformancePurchaseReturnOrderLine`.+**Verify:** loop.++## Task 6: Invoicing & accounting (B4)++**Depends on:** Task 5+**Files:** `types.ts`, `tiers/04-sales.ts`, `tiers/05-purchasing.ts`, `tiers/09-accounting.ts`, `data/*/accounting.ts`, `data/*/sales.ts`, `data/*/purchasing.ts`, validator, floors; `.claude/rules/onboarding-company-templates.md` (payments convention changes)+**Capabilities:**+- `postingDate` = `dateIssued` on every non-Draft sales/purchase invoice.+- Posted journals shaped like the posting paths — read `packages/database/supabase/functions/post-sales-invoice`, `post-purchase-invoice`, `post-payment` (or their current names) for account defaults and line `documentType`/`documentId`: `sourceType` `Sales Invoice` (AR debit / Revenue credit), `Purchase Invoice` (Inventory or Expense / AP), `Payment` (Cash vs AR/AP; set `payment.journalId`); one `Opening Balance`. `accountingPeriodId` set from the adopted period for the posting date. Every journal balances (validator already checks authored journals — extend to the generated ones by deriving them in data, or generate them in the tier from the invoice specs and assert balance in the tier).+- Invoice dates spread so receivables aging hits Current, 1–30, 31–60, 61–90.+- Draft Receipt + Draft Disbursement payments.+- `costLedger` rows paired with posted receipt/shipment `itemLedger` rows (shape from `post-receipt`/`post-shipment`); `itemCost.unitCost` non-zero for stocked items.+- `companyAccountsReceivableBillingAddress` / `companyAccountsPayableBillingAddress` (id = companyId).+**Verify:** loop + `psql` spot check in a real seed is Task 9's job.++## Task 7: Quality, maintenance, resources (B5)++**Depends on:** Task 6+**Files:** `types.ts`, `tiers/07-quality.ts`, `tiers/10-ops.ts`, `tiers/01-foundation.ts` (partners, HQ work center), `data/*/quality.ts`, `data/*/ops.ts`, `data/*/foundation.ts`, `helpers/inspection.ts` if inspection math changes, validator, floors+**Capabilities:**+- `nonConformanceWorkflow` ×3 linked from ≥ 2 NCRs; `nonConformanceItem` on every NCR; NCR `assignee`; `nonConformanceSupplier` on a supplier NCR dated in the current month; `nonConformanceActionProcess` linking an open task to a process in use; `procedureParameter` on ≥ 2 procedures.+- `QualityData.inspection` → `inspections: InspectionSpec[]` with ≥ 3 entries: Passed receipt lot, Pending lot, Job Operation lot (keep `helpers/inspection.ts` sample math shared with the validator).+- Maintenance: `maintenanceDispatchItem.unitCost`; Reactive dispatch on a production-event day; 2 Completed dispatches at −55…−35; a Scheduled dispatch due today; an In Progress dispatch with the work center Down; `workCenterReplacementPart`; one HQ work center with 1 dispatch + 1 schedule.+- `partner` rows (read the table first).+**Verify:** loop.++## Task 8: Settings & people remainder (B6)++**Depends on:** Task 7+**Files:** `types.ts`, `tiers/01-foundation.ts` or `tiers/10-ops.ts`, `data/*/foundation.ts` / `data/*/ops.ts`, validator, floors+**Capabilities:**+- `userAttributeCategory` → `userAttribute` (Date, List, User data types) → `userAttributeValue` for the applying user.+- `itemSerialSequence` for every serial-tracked item; 3 `customField` rows (part Text, customer User, job Yes/No — resolve `dataTypeId` by name from the lookup table); `printJob` history (completed, failed, queued) against a printer route. ~~one `webhook` `active=false`~~ — dropped (spec D66).+**Verify:** loop.++## Task 9: Screen matrix — script, real seeds ×4, fix loop++**Depends on:** Tasks 1–8+**Files:**+- Create (scratchpad, not committed): `…/scratchpad/screen-matrix.ts` (or `.sql`)+- Create: `.ai/runs/2026-09-23-screen-matrix-{satellite,robotics,precision,motor}.txt`+**Steps:**+1. From the five research files, list every screen classified EMPTY/FILTERED-EMPTY that is in scope, plus the previously-OK core lists as regression guards. For each, write ONE count query reproducing the loader's source and filters for the applying user (RPCs called inside `BEGIN … ROLLBACK`).+2. For each dataset: `pnpm db:seed:dev -- --email [email protected] --dataset <key>` (includes Task 2's planning), then run the matrix for company `dapnjkh860gjckkl52t0`; write `<screen> | query | count | PASS/FAIL` to the evidence file.+3. Any FAIL → fix in the owning tier/data (ground rules apply), re-run the loop, re-seed, re-run the matrix. Repeat until 0 FAIL for all four datasets.+**Verify:** each evidence file ends with `FAIL: 0`.++## Task 10: Full verification + evidence++**Depends on:** Task 9+**Steps / Verify:**+```bash+pnpm --filter @carbon/database typecheck # exit 0+pnpm --filter @carbon/database test # all pass+pnpm --silent db:check:datasets # ✓ ×4+pnpm exec turbo run typecheck --filter=@carbon/jobs # all successful+pnpm exec biome check packages/database/src packages/jobs/src # 0 errors+```+- Real re-apply over an existing seeded company: seed robotics then satellite onto `[email protected]`; both exit 0; no robotics items remain.+- Re-run Task 1 probes (now also against the final code).+- Pre-commit drill: break one new ref in `data/satellite/*.ts`, stage only that file, `sh .husky/pre-commit` → `Commit blocked`; restore the file byte-identical (checksum before/after); unstage.+- Refresh `.ai/runs/2026-09-23-seed-baseline-*.txt` (row counts) and the status audit if statuses changed.+Record everything in `.ai/runs/2026-09-23-screen-coverage-verification.txt`.++## Task 11: Docs++**Depends on:** Task 10+**Files:** `.claude/rules/onboarding-company-templates.md` (planning step, wipe refusals, slides, payments now journaled, shifts at plant, volume), `packages/database/src/datasets/AGENTS.md`, `packages/database/AGENTS.md` (dev CLI `--skip-plan`), `packages/jobs/AGENTS.md` if it lists scripts/functions, `docs/content/docs/platform/demo-data.mdx` (user-facing: what the demo includes, that planning runs after apply, the two refusal messages) then regenerate the agent KB exactly as the previous pass did (find the generator in `.claude/rules/agent-knowledge-base.md`), spec status → Implemented + changelog.+**Verify:** `grep -n "plan:company\|planDemoCompany" .claude/rules/onboarding-company-templates.md packages/database/AGENTS.md` shows both; KB manifest regenerated without diff noise outside demo-data.diff --git a/.ai/plans/2026-09-24-demo-data-orphan-recovery.md b/.ai/plans/2026-09-24-demo-data-orphan-recovery.mdnew file mode 100644index 0000000000..4666f578f2--- /dev/null+++ b/.ai/plans/2026-09-24-demo-data-orphan-recovery.md@@ -0,0 +1,177 @@+# Demo data orphan fix + scope-violation recovery — implementation plan++**Spec / source:** `.ai/specs/2026-09-24-demo-data-orphan-recovery.md`+**Branch:** feat/demo-data-completeness++## Progress+- [x] Task 1: `buildDanglingPredicate` + `deleteDanglingRows` in scope.ts (+ tests)+- [x] Task 2: Call it from `wipeAndLoad` on own restores+- [x] Task 3: Template job records scope-violation failures+- [x] Task 4: `CompanyTemplateRun` carries reason/violations+- [x] Task 5: Extract `PurgeCorruptedRowsModal`; backups.tsx uses it+- [x] Task 6: `purgeAndApply` action + demo-data page wiring+- [x] Task 7: `TemplateReviewRow` scope-violation failure UI+- [x] Task 8: Verify (tests, typecheck, lingui) — manual browser check pending (user)++## Dependencies+Task 2 needs 1. Tasks 1–3 independent of 4–5. Task 6 needs 4, 5. Task 7 needs 4, 6. Task 8 last.++---++## Task 1: Dangling-row helpers in scope.ts++**Depends on:** none+**Files:**+- Modify: `packages/jobs/src/backups/scope.ts`, adding two exports after `purgeScopeViolations`+- Modify: `packages/jobs/src/backups/scope.test.ts` to add a `describe("buildDanglingPredicate")`+- Precedent: `buildExclusionPredicate` / `violationTerm` in the same file++**Steps:**+1. `export function buildDanglingPredicate(table: TableInfo, byName: Map<string, TableInfo>): RawBuilder<unknown> | null`.+ For each `fk` of `table.foreignKeys` where `fk.refColumn === "id"`, `!RETAINED_REF_TABLES.has(fk.refTable)`,+ `byName.has(fk.refTable)`, and the column exists and is NOT nullable, emit+ `("<col>" NOT IN (SELECT "id" FROM "<refTable>"))`. OR the terms together; return null if there are none.+ Doc comment: the row points at a row that no longer exists ANYWHERE. This is what `ON DELETE CASCADE` would have removed if the wipe hadn't run with `session_replication_role='replica'`. It is not "outside company scope"; those rows go through the user-confirmed purge.+2. `export async function deleteDanglingRows(trx, tables: TableInfo[], byName, companyId, companyGroupId): Promise<Array<{ table: string; rows: number }>>`.+ Walk `[...tables].reverse()`, skip null predicates, and run+ `DELETE FROM <t> WHERE <buildScopeFilter(t, …)> AND (<predicate>)`. Push only non-zero `numAffectedRows`.+3. Tests (compile-only `db` already in the file): a table `employeeAbility` with+ `abilityId → ability` (NOT NULL), `employeeId → user`, and `lastTrainingDate` nullable FK-less. Expect the+ predicate to contain `"abilityId" NOT IN (SELECT "id" FROM "ability")` and not contain `"user"`; a table with only a nullable FK returns null.++**Verify:**+```bash+cd packages/jobs && pnpm exec vitest run src/backups/scope.test.ts+# Expected: all tests pass, including the new buildDanglingPredicate cases+```+**Out of scope:** changing `violationTerm`, `purgeScopeViolations`, or the export guard.++## Task 2: Own-restore cleans dangling identity rows++**Depends on:** 1+**Files:**+- Modify: `packages/jobs/src/inngest/functions/tasks/company-restore.ts` (`wipeAndLoad`)++**Steps:**+1. Import `deleteDanglingRows` from `../../../backups/scope` (match the existing import path of `ExportScopeViolationError` in this file).+2. Inside the transaction, after the load loop, when `!remap`: build+ `kept = catalog.tables.filter(t => isUserScopedIdentityTable(t) && t.scopeColumn === "companyId")`,+ call `deleteDanglingRows(trx, kept, byName, companyId, targetGroupId)`, and if it returns anything, `logger.warn` / `console.warn` it+ (use whatever logger the file already uses at module level; if none, return it in the result instead and log it at the call site. Do not add a new logger dependency).+3. Update the comment above `selectWipeableTables` usage to mention the cleanup.++**Verify:**+```bash+cd packages/jobs && pnpm exec vitest run src/inngest/functions/tasks src/backups && pnpm run typecheck+# Expected: tests pass; tsc exits 0+```+**Out of scope:** changing `selectWipeableTables` semantics or remap behaviour.++## Task 3: Template job records scope violations++**Depends on:** none+**Files:**+- Modify: `packages/jobs/src/inngest/functions/tasks/company-template.ts`+- Precedent: `company-restore.ts` catch at ~L575-605 and `RestoreMeta` fields++**Steps:**+1. `TemplateMeta`: add `reason?: "scope-violations" | null; violations?: ScopeViolation[] | null; violationRowsByTable?: Array<{table:string;rows:number}> | null;` (import `ScopeViolation`, `ExportScopeViolationError` from wherever company-restore imports them).+2. In the apply's `running` patch, add `reason: null, violations: null, violationRowsByTable: null`.+3. In the apply's `catch (err)`, spread `...(err instanceof ExportScopeViolationError ? { reason: "scope-violations", violations: err.violations, violationRowsByTable: err.rowsByTable } : {})` into the failed patch. After writing, `if (err instanceof ExportScopeViolationError) throw new NonRetriableError(message, { cause: err });`, then `throw err`.++**Verify:**+```bash+cd packages/jobs && pnpm run typecheck+# Expected: exits 0+```+**Out of scope:** the revert and finalize functions.++## Task 4: `CompanyTemplateRun` exposes the failure reason++**Depends on:** none+**Files:**+- Modify: `apps/erp/app/modules/settings/backups.service.ts`: `CompanyTemplateRun` + `getCompanyTemplateRun`+- Modify: `apps/erp/app/routes/x+/settings+/demo-data.tsx`: `optimisticRun` literal gets the new fields+- Precedent: `CompanyExportRun` / `getCompanyExportRun` in the same file++**Steps:**+1. Add `reason: "scope-violations" | null; violations: ScopeViolationSummary[]; violationRowsByTable: RowsByTable[];` to the type, the meta cast, and the projection (defaults `null`, `[]`, `[]`).+2. `optimisticRun` in demo-data.tsx: `reason: null, violations: [], violationRowsByTable: []`.++**Verify:** covered by Task 8's typecheck.++## Task 5: Shared purge confirmation modal++**Depends on:** none+**Files:**+- Create: `apps/erp/app/modules/settings/ui/Backups/PurgeCorruptedRowsModal.tsx`+- Modify: `apps/erp/app/modules/settings/ui/Backups/index.ts`, adding an export+- Modify: `apps/erp/app/routes/x+/settings+/backups.tsx`, replacing the inline modal (~L737-800)+- Copy from (precedent): the inline `{purgeRun && (<Modal …>)}` block in backups.tsx++**Steps:**+1. Component props: `rowsByTable: RowsByTable[]; description: ReactNode; confirmLabel: ReactNode; onConfirm: () => void; onCancel: () => void`. Render exactly the current Modal markup: title `Plural` on `totalScopeRows(rowsByTable)`, `description` paragraph, the per-table list (keep its comment), Cancel + destructive confirm.+2. backups.tsx: render `<PurgeCorruptedRowsModal rowsByTable={purgeRun.violationRowsByTable} description={<Trans>…existing text…</Trans>} confirmLabel={<Trans>Delete and restore</Trans>} onCancel={() => setPurgeRun(null)} onConfirm={…existing submit body…} />`. Remove `purgeRowCount` and any imports that become unused.++**Verify:** covered by Task 8 (typecheck + lint); visual check in Task 8.+**Out of scope:** changing the Backups copy or behaviour.++## Task 6: `purgeAndApply` action + page wiring++**Depends on:** 4, 5+**Files:**+- Modify: `apps/erp/app/routes/x+/settings+/demo-data.tsx`+- Precedent: `case "purgeAndRestore"` in `apps/erp/app/routes/x+/settings+/backups.tsx`++**Steps:**+1. Import `purgeCorruptedRows` from `~/modules/settings/backups.server`.+2. New `case "purgeAndApply"`:+ - `const current = await getCompanyTemplateRun(client, companyId)`; refuse (`{ success: false, message: "This demo data change can't be retried this way" }`) unless `current.data?.templateRunId === templateRunId && status === "failed" && reason === "scope-violations" && datasetKey && datasetKeys().includes(datasetKey)`.+ - `try { ({ deleted } = await purgeCorruptedRows(companyId)) } catch (err) → { success: false, message: err.message ?? "Failed to remove corrupted data — nothing was deleted" }`.+ - `rows = sum(deleted)`; `try { const startedRunId = await startCompanyTemplate({ companyId, userId, datasetKey }); return { success: true, message: \`Removed ${rows} row(s) — applying demo data\`, templateRunId: startedRunId } } catch → { success: false, message: \`Removed ${rows} row(s), but the demo data didn't start — apply it again. (…)\` }` (same pluralisation as restore).+3. Page component:+ - `const hasLiveRun = run !== null && !resolvedRunIds.includes(run.templateRunId);` and use it in place of `hasRun` in the pendingApplyKey-clearing effect and `optimisticRun` (so an optimistic apply can replace a resolved failed run).+ - Pass to `TemplateReviewRow` a new prop `onPurgeAndApply={() => { setResolvedRunIds(p => [...p, pending.templateRunId]); setPendingApplyKey(pending.datasetKey); }}` and `onPurgeFailed={(id) => { setResolvedRunIds(p => p.filter(x => x !== id)); setPendingApplyKey(null); }}`.++**Verify:** covered by Task 8.+**Out of scope:** the existing apply/keep/revert/dismiss cases.++## Task 7: TemplateReviewRow scope-violation UI++**Depends on:** 4, 5, 6+**Files:**+- Modify: `apps/erp/app/modules/settings/ui/DemoData/TemplateReviewRow.tsx`+- Copy from (precedent): `apps/erp/app/modules/settings/ui/Backups/RestoreReviewRow.tsx` (failed branch)++**Steps:**+1. Props: add `onPurgeAndApply: () => void` and `onPurgeFailed: (templateRunId: string) => void`.+2. Failed branch: when `run.reason === "scope-violations"`, render (instead of `Failed — {error}`) a `text-xs text-destructive` span with+ `<Plural value={totalScopeRows(run.violationRowsByTable)} one="# row links to data outside this company, so a safety copy of your current data can't be made." other="# rows link …" />` plus+ `<ExcludedRowsInfo excludedRows={run.violations} title={<Trans>Why this failed</Trans>} description={<Trans>Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply.</Trans>} technical={run.error} />`.+3. Buttons: when failed + scope-violations, before Dismiss add `<Button variant="destructive" onClick={() => setConfirmPurge(true)}><Trans>Remove corrupted data and apply</Trans></Button>`.+4. `confirmPurge` state renders `PurgeCorruptedRowsModal` with description `<Trans>These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied.</Trans>`, confirmLabel `<Trans>Delete and apply</Trans>`. On confirm: `fetcher.submit({ intent: "purgeAndApply", templateRunId: run.templateRunId, datasetKey: run.datasetKey ?? "" }, { method: "post", action: path.to.demoData })`, `onPurgeAndApply()`, close.+5. A second fetcher `purgeFetcher` for this submit; `useEffect`: when `purgeFetcher.state === "idle" && purgeFetcher.data?.success === false`, call `onPurgeFailed(run.templateRunId)` and `toast.error(purgeFetcher.data.message)` (`toast` from `@carbon/react`, as backups.tsx does).+ NOTE: the row unmounts once hidden, so the effect lives in the ROUTE if the row is hidden optimistically. Put the purge fetcher + effect in the route component instead, pass `onPurgeAndApply(run)` up, and keep only the button + modal in the row.++**Verify:** covered by Task 8.++## Task 8: Verify++**Depends on:** all+**Steps / Verify:**+```bash+cd packages/jobs && pnpm exec vitest run src/backups src/inngest/functions/tasks && pnpm run typecheck+# Expected: all pass, tsc exits 0+cd apps/erp && pnpm run typecheck+# Expected: exits 0+cd /Users/aashu/work/carbon/carbon && pnpm exec biome check apps/erp/app/routes/x+/settings+/demo-data.tsx apps/erp/app/routes/x+/settings+/backups.tsx apps/erp/app/modules/settings packages/jobs/src/backups packages/jobs/src/inngest/functions/tasks/company-template.ts packages/jobs/src/inngest/functions/tasks/company-restore.ts+# Expected: no errors+```+Manual (user, running stack): on company `dap2gkh860gg2ccl14sg`, apply Aerospace & Satellite. You should see the 4-row message, the info popover, and the button; confirm, and the rows are deleted and the apply reaches `ready`. Then Revert and Apply again: the second apply succeeds.+Do NOT commit (user rule).++## Execution notes (2026-09-24)+- Task 2: added a module-level `getLogger("jobs", "company-restore")` (same pattern as company-export.ts; `@carbon/logger` already a dependency).+- Task 7: the purge fetcher + result effect live in the route (`demo-data.tsx`); the row only owns the button + modal, as the plan's NOTE required. Added a stale-response guard so a retry can't settle on the previous result.+- Task 5: kept the Plural variable name `purgeRowCount` so the existing translated msgid is unchanged.+- Verified: jobs vitest 103/103, jobs tsc, erp tsgo, biome clean, lingui extract adds only the 5 new msgids. Not verified: running app (manual check below).diff --git a/.ai/research/2026-09-22-app-feature-surface.md b/.ai/research/2026-09-22-app-feature-surface.mdnew file mode 100644index 0000000000..87d0eec28b--- /dev/null+++ b/.ai/research/2026-09-22-app-feature-surface.md@@ -0,0 +1,141 @@+# Carbon application feature surface — complete map (research, 2026-09-22)++Source: Explore agent over apps/erp + apps/mes on main. Purpose: the "what should demo data cover" side of the gap analysis. Enum values from `packages/database/src/types.ts` (Enums block, ~84773–85400); module registry `apps/erp/app/hooks/useModules.tsx`.++## 1. Sales (`modules/sales`, routes x+/sales+, sales-rfq+, quote+, sales-order+, sales-return-order+, customer+)+- Sales RFQ — `salesRfqStatus`: Draft, Ready for Quote, Closed, Quoted+- Quote — `quoteStatus`: Draft, Sent, Ordered, Partial, Lost, Cancelled, Expired; `quoteLineStatus`: Not Started, In Progress, Complete, No Quote+- Sales Order — `salesOrderStatus`: Draft, Needs Approval, Confirmed, In Progress, Completed, Invoiced, Cancelled, Closed, To Ship and Invoice, To Ship, To Invoice; line status: Ordered, In Progress, Completed; line types: Comment, Part, Material, Tool, Service, Consumable, Fixture, Fixed Asset+- Sales Return Order (RMA) — `salesReturnOrderStatus`: Draft, To Receive, Completed, Cancelled+- Customer tabs: details, contacts, locations, payments, shipping, tax, accounting, bank accounts, documents, risks; customerStatus/customerType are user-defined tables+- Customer Portals (x+/sales+/customer-portals.*), Price Lists / Pricing Rules (`pricingRuleType` Discount/Markup; amountType Percentage/Fixed), Sales Rules, No Quote Reasons, Return Reasons+- `sourcingType`: Specified, Drop Ship, Ship from Inventory; `fulfillmentType`: Inventory, Job+- Dashboard KPIs: quoteCount, rfqCount, salesFunnel, salesOrderCount, salesOrderRevenue++## 2. Purchasing (x+/purchasing+, purchasing-rfq+, supplier-quote+, purchase-order+, purchase-return-order+, supplier+)+- Purchasing RFQ — Draft, Requested, Closed+- Supplier Quote — Active, Expired, Draft, Declined, Cancelled+- Purchase Order — Draft, To Review, Rejected, To Receive, To Receive and Invoice, To Invoice, Completed, Closed, Planned, Needs Approval; `purchaseOrderType`: Purchase, Return, Outside Processing; line types incl. G/L Account, Fixed Asset+- Purchase Return Order — Draft, To Ship, Completed, Cancelled+- Supplier — `supplierStatusType`: Active, Inactive, Pending, Rejected; tabs incl. approval, processes, default-attachments, risks; supplier approval `approvalStatus`: Pending, Approved, Rejected, Cancelled over purchaseOrder/qualityDocument/supplier+- `supplierPartPriceSourceType`: Quote, Purchase Order, Manual Entry; supplier ledger doc types: Payment, Invoice, Credit Memo, Finance Charge Memo, Reminder, Refund+- Material Planning (x+/purchasing+/planning.tsx); KPIs: supplierQuoteCount, purchaseOrderCount, purchaseInvoiceCount, amounts++## 3. Production (x+/production+, job+, scheduling+, priority+, assembly+, procedure+, inspection-document+)+- Job — Draft, Ready, In Progress, Paused, Completed, Cancelled, Overdue, Due Today, Planned, Closed; `deadlineType`: No Deadline, ASAP, Soft Deadline, Hard Deadline+- Job Operation — Canceled, Done, In Progress, Paused, Ready, Todo, Waiting; `operationType`: Process, Assembly, Inspection, Outside Processing+- Operation Batch — `jobOperationBatchStatus`: Planned, Active, Completing, Completed; `batchType`: Sequential, Simultaneous+- Production Event — Setup, Labor, Machine; Production Quantity — Rework, Scrap, Production+- Make Method — Draft, Active, Archived; `methodType`: Purchase to Order, Pull from Inventory, Make to Order; op order After Previous/With Previous+- Assembly Instruction — Draft, Published, Archived; steps Todo/Review/Done+- Procedure — Draft, Active, Archived; step types: Value, Measurement, Checkbox, Timestamp, Person, List, File, Task, Inspection+- Inspection documents (usage: Receipt); Demand Forecasts (`demandForecastSourceType`: Job Material, Sales Order, Demand Projection); Scrap Reasons+- Scheduling: x+/scheduling+/forecast, x+/priority+ (dates, operations, people, batching); `capacityResourceKind`: WorkCenter, OperatorPool, Employee+- Job DAG, BoM explorer, Estimates vs Actuals; KPIs: utilization, estimatesVsActuals, completionTime+- `factor` rate enum: Hours/Piece … Total Minutes (11 values)++## 4. Inventory (x+/inventory+, receipt+, shipment+, stock-transfer+, warehouse-transfer+, picking-list+, inventory-count+, traceability+)+- Receipt — Draft, Pending, Posted, Voided; sources: Sales Order, Sales Invoice, Sales Return Order, Purchase Order, Purchase Invoice, Purchase Return Order, Inbound Transfer, Outbound Transfer, Manufacturing Consumption, Manufacturing Output+- Shipment — Draft, Pending, Posted, Voided; carriers UPS/FedEx/USPS/DHL/Other+- Stock Transfer — Draft, Released, In Progress, Completed+- Warehouse Transfer — Draft, To Ship and Receive, To Ship, To Receive, Completed, Cancelled+- Picking List — Draft, In Progress, Completed, Cancelled, Partial; lines Pending, Picked, Short, Cancelled; pick sort Default/FEFO/FIFO/LIFO+- Inventory Count — Draft, Pending, Posted+- Tracked Entity — Available, Reserved, On Hold, Consumed, Rejected, Scrapped; `trackingSource` Purchased/Manufactured+- Kanban — replenishment Buy/Make/Transfer; output label/qrcode/url+- Item Ledger — types incl. Assembly Consumption/Output; 28 doc types incl. Batch Split/Merge, Scrap, Non-Conformance, Inbound Inspection+- Shelf life modes; Supersession — Consume First, Prefer New, Stock Only, No Stock+- Storage Units/Types/Rules; Traceability graph; Quantities & valuation report++## 5. Items (x+/items+, part+, material+, tool+, consumable+, service+, change-notice+)+- `itemType`: Part, Material, Tool, Service, Consumable, Fixture+- Revision — Design, Prototype, Production, Obsolete; Tracking — Inventory, Non-Inventory, Serial, Batch+- Replenishment — Buy, Make, Buy and Make; reordering — Manual, Demand-Based, Fixed Reorder Quantity, Maximum Quantity+- Costing — Standard, Average, LIFO, FIFO+- Change Notice — `changeOrderStatus`: Draft, Start, Engineering Complete, Implementation, Done, Cancelled; tasks Pending/In Progress/Completed/Skipped; change types Version/Revision/Replacement Part/New Part; CN types Engineering/Manufacturing/Documentation (stage machine items.models.ts:1046-1140)+- Configuration params (text/numeric/boolean/list/date/material); serviceType Internal/External+- Item tabs: details, costing, inventory, planning, purchasing (supplier parts), quality, sales (customer parts), make method, parameters, rules+- Material properties: Dimensions, Finishes, Grades, Shapes, Substances, Types; Item Groups; UoM++## 6. Quality (x+/quality+, issue+, issue-workflow+, quality-document+, inspection+)+- Issue/NCR — Registered, In Progress, Closed; priority Low/Medium/High/Critical; source Internal/External; approval MRB; tasks Pending/In Progress/Completed/Skipped; action types Containment, Corrective, Preventive, Verification, Communication+- NCR associations: items, customers, suppliers, jobOperations, purchaseOrderLines, salesOrderLines, shipmentLines, receiptLines, salesReturnOrderLines, purchaseReturnOrderLines, trackedEntities, inspections+- Disposition (12 values incl. Quarantine, Rework, Use As Is, Return to Supplier/Customer)+- Inspection — Pending, In Progress, Passed, Failed, Partial; samples Pending/Passed/Failed; source Receipt / Job Operation+- Sampling — All/First/Percentage/AQL; ANSI_Z1_4 / ISO_2859_1; levels I–III, S1–S4; severity Normal/Tightened/Reduced+- Gauges — Active/Inactive, role Master/Standard; calibration Pending, In-Calibration, Out-of-Calibration+- Quality Document — Draft, Active, Archived+- Risk Register — Open, In Review, Mitigating, Closed, Accepted; type Risk/Opportunity; sources Customer, General, Item, Job, Quote Line, Supplier, Work Center+- Issue Workflows; configure: Action Types, Gauge Types, Issue Types+- KPIs: weeklyTracking, statusDistribution, paretoByType, ncrsByType, sourceAnalysis, supplierQuality, weeksOpen++## 7. Resources (x+/resources+, maintenance+, training+)+- Maintenance Dispatch — Open, Assigned, In Progress, Completed, Cancelled; priority L/M/H/Critical; severity Preventive, Operator Performed, Support Required, OEM Required; source Scheduled, Reactive, Non-Conformance; frequency Daily…Annual; failure modes Maintenance/Quality/Operations/Other; OEE impact Down/Planned/Impact/No Impact+- Work Centers (+ rules), Processes (activate/deactivate), Locations, Abilities (curve/shadow/recertify)+- Training — Draft, Active, Archived; Mandatory/Optional; Once/Quarterly/Annual; question types MultipleChoice, TrueFalse, MultipleAnswers, MatchingPairs, Numerical; assignments Completed, Pending, Overdue, Not Required+- Contractors, Partners, Suggestions+- Maintenance KPIs: mttr, mtbf, sparePartCost, worstPerformingMachines, sparePartConsumption++## 8. People (x+/people+, person+)+Employees, Person detail (details, job, abilities, attributes, notes, timecard), Timecards (periodType Week/Day/Month), Attributes + categories, Departments, Holidays, Shifts.++## 9. Invoicing (x+/invoicing+, sales-invoice+, purchase-invoice+, payments+, credits+)+- Sales Invoice — Draft, Pending, Submitted, Return, Credit Note Issued, Paid, Partially Paid, Overdue, Voided+- Purchase Invoice — Draft, Pending, Open, Return, Debit Note Issued, Paid, Partially Paid, Overdue, Voided+- Payment — Draft, Posted, Voided; type Receipt/Disbursement+- Credit/Debit Memo — Draft, Posted, Voided; direction Credit/Debit+- Card Transaction — Draft, Posted, Voided; Charge, Credit, Payment, Cashback, Repayment+- Payables/Receivables workbenches; invoicing dashboard++## 10. Accounting (x+/accounting+, journal-entry+, fixed-asset+, depreciation-run+, reports+)+- Journal Entry — Draft, Posted, Reversed; 26 source types; 24 line doc types+- Accounting Period — Inactive/Active; period close Open/Locked/Closed; close tasks Open/Done/Skipped (Auto/Action/Manual)+- Fixed Asset — Draft, Active, Fully Depreciated, Disposed; depreciation Straight Line/Declining Balance/Units of Production (+MACRS tax, conventions, property classes); disposal Sale/Scrapping+- CoA (`accountType` 22 values, classes, income/balance), cost ledger types, intercompany (Unmatched/Matched/Eliminated), dimensions (16 entity types), payment terms (Net/EOM/Day of Month), tax exemptions, incoterms+- Cost Centers, Default Accounts, Exchange Rates, Fiscal Years, Projects, Asset Classes, Sync Tie-Out+- Reports: Balance Sheet, Income Statement, Trial Balance, AP Aging, AR Aging, Executive P&L, Inventory Valuation (+reconcile), Purchases, saved views++## 11. Documents (x+/documents+)+All/My/Recent/Pinned/Trash; `documentType` 11 values; `documentSourceType` 23 values; comment threads (`documentthreadtype`): nonConformance, quote, salesOrder, job, purchaseOrder, invoice, receipt, shipment; AI extraction (purchaseInvoice/salesRfq).++## 12. Workflows (x+/workflows+, x+/workflow+)+List, canvas builder, publish/versions, test-run, runs + run detail.++## 13. Users (x+/users+)+Employees, Operators (PIN), Groups, Employee Types, permissions (17 modules), customer/supplier accounts (routes exist, nav commented); roles customer/employee/supplier; system types Admin, Console Operator.++## 14. Settings (x+/settings+, x+/templates+)+Billing, Company(-ies), Document Templates, Logos, Printing (+jobs); per-module settings; API Keys, Approval Rules, Audit Logs, Backups, Custom Fields, Demo Data, Integrations, ITAR, Security, Sequences, Serial Numbers, SSO, Tags, Webhooks.+- Enforcement rules family storage/sales; 13 surfaces+- Sync ops status enum; integrations: QuickBooks, Xero, Rillet, Ramp, Stripe, Slack, Jira, Linear, Onshape, Radan, Paperless Parts++## 15. Onboarding / Get Started+onboarding+ (company, industry, plan, theme, user); x+/get-started+ implementation hub (15 screens); implementationStatus/Tier/StateKind enums.++## 16. Account+Profile, Notifications, Security (MFA/passkeys), Theme.++## MES (apps/mes)+Nav: Schedule, Assigned, Active, Recent, Jobs, Maintenance, Picking (+ Displays, console pin).+Surfaces: operations queue; operation work screen (start/end/finish/pause); job detail; procedure steps (complete-all, inspection); timecard/end-shift; material issue/unconsume/adjustment; scrap & rework (+trigger-rework); batches; assembly work instructions; inspection lot (sample, measurement, disposition, complete-passed); quality-issue.new (NCR from floor); maintenance dispatches (+add-and-issue); picking (+tracked lines, suggested allocation); tracked entity convert; record production; label printing (PDF+ZPL); shop-floor TV displays (Scoreboard/QueueTable/ActiveWorkPanel per work center, work + maintenance); console PIN mode; suggestions; kanban board; 3D viewer (`modelProcessingStatus` Idle/Queued/Processing/Success/Failed).++## Cross-cutting a demo should exercise+- Dashboards & charts on every module landing (api+/*.kpi.$key.ts)+- Global search, document search, traceability search+- PDFs/previews/printing, document templates preview+- Notifications (topbar; SalesRuleViolation, ChangeNotice* events)+- Audit log (settings + api, packages/database/src/audit.ts)+- Approvals (approval rules; PO/qualityDocument/supplier)+- MRP & planning (api+/mrp.ts, production/purchasing planning, demand forecasts, scheduling forecast, priorities)+- Traceability lot/serial (graph, containment, expiry, unscrap, lineage.server)+- Fixed assets (register, purchase, sell, dispose, depreciation runs, asset classes; FA lines on receipts/shipments)+- Risk register (quality + customer/supplier/job tabs)+- Workflows (canvas, publish, runs)+- Portals/shares: share+/quote.$id (accept/reject), supplier-quote, purchasing-rfq, customer portal, scar.$id (supplier corrective action), training.$id, download.$token+- AI agent + KB; API keys/webhooks (not demo-data relevant)+- Imports, custom fields, saved views, tags, notes+- Multi-company/location, exchange rates, i18n++## End-to-end chains worth demoing+- Sales RFQ → Quote → SO → Job(s) → MES ops → Shipment → Sales Invoice → Payment+- Purchasing RFQ → Supplier Quote → PO → Receipt → Inbound Inspection → Purchase Invoice → Paymentdiff --git a/.ai/research/2026-09-22-demo-data-current-coverage.md b/.ai/research/2026-09-22-demo-data-current-coverage.mdnew file mode 100644index 0000000000..9ae9e1a936--- /dev/null+++ b/.ai/research/2026-09-22-demo-data-current-coverage.md@@ -0,0 +1,76 @@+# Demo-data datasets — current coverage inventory (research, 2026-09-22)++Source: Explore agent over `packages/database/src/datasets/` (types + 12 tiers + 4 data packs) on main.++## Architecture recap+`Dataset` (`types.ts:786-802`) = 11 pure-data slices + key/label/industryId. Engine = `tiers/01…12`, one transaction via `applyDataset` (`index.ts:80-92`) with `app.sync_in_progress` set — async event dispatch suppressed but **sync DB interceptors still run** (that's where itemCost, itemPlanning, jobMakeMethod, reserved trackedEntity, posting groups come from). Keys: satellite | robotics | precision | motor.++## Tables written per tier (complete)+- **01 foundation**: department, shift (HQ loc), process (+UPDATE requiresAbility), ability, itemPostingGroup, location (Plant), employeeJob UPDATE (moves employees to Plant), warehouse, storageType, storageUnit (shelves + per-WC floor units), workCenter, workCenterProcess, customerType, supplierType, shippingMethod (carrier from name prefix), shippingTerm, customer (currency hardcoded USD), customerPayment/customerShipping UPDATE (Net-30 via ILIKE), contact, address, customerLocation ("Billing"), customerContact, supplier (+contractor agency), supplierPayment/supplierShipping UPDATE, supplierLocation, supplierContact, supplierProcess (leadTime hardcoded 5), contractor (40h hardcoded), contractorAbility, printerRoute, procedure, procedureStep, costCenter, noQuoteReason.+- **02 items** (helpers/items.ts): item (createItem), itemCost (assert+UPDATE), itemUnitSalePrice UPDATE, itemReplenishment UPDATE (leadTime), part/material/tool/consumable/service/fixture (approved:true), methodMaterial (addBomLine), methodOperation (addBopOperation), supplierPart (MOQ 1), supplierPartPrice (single break, Manual Entry). makeMethod left **Draft** deliberately (helpers/items.ts:110-112). Interceptors create itemCost/itemReplenishment/itemUnitSalePrice/itemPlanning/makeMethod.+- **03 inventory**: itemLedger (Positive Adjmt. "Opening balance" — the ONLY ledger writes), trackedEntity (Available), kanban (Buy + autoRelease only), inventoryCount (Draft), inventoryCountLine (first 6 opening-stock rows only).+- **04 sales**: companySettings upsert (digitalQuote on), opportunity, salesRfq(+lines, uom "EA"), quote (+quotePayment/quoteShipment), quoteLine (always Part + Make to Order), quoteLinePrice, externalLink (Quote) + quote UPDATE, salesOrder(+payment/shipment), salesOrderLine (Part, Make to Order), shipment (Draft only — posting needs edge fn, :234), shipmentLine, salesInvoice (+salesInvoiceShipment required by view INNER JOIN), salesInvoiceLine. Order: opportunities → statusOrders → releasedOrders (readable-id sequence).+- **05 purchasing**: supplierInteraction, purchaseOrder (direct + winningQuote), purchaseOrderDelivery/Payment, purchaseOrderLine, receipt (Draft, 0 received), receiptLine (requiresBatchTracking), purchaseInvoice(+delivery, lines, Draft), purchasingRfq(+lines, suppliers), supplierQuote (status hardcoded **Active**, :183) + externalLink, supplierQuoteLine(+prices per break), purchasingRfqToSupplierQuote / ToPurchaseOrder. Quote date offsets hardcoded (−16/+140).+- **06 production**: modelUpload (Success, bundled glb), assemblyInstruction (**Draft** hardcoded), assemblyInstructionStep, item UPDATE (modelUploadId), job (deadlineType always Hard Deadline, scrapQuantity 0), jobOperation/jobOperationStep/jobMaterial/jobMakeMethod-adopt (helpers/job-method.ts — "no configuration rules, no supersession redirect, no tool or parameter copy"), trackedEntity rename, productionEvent (first 2 root ops of eventsJobKey only, postedToGL:false), productionQuantity (Production, qty 1), genealogy trackedEntity/trackedActivity/Input/Output. `operationStatusFor` (:63-78): Draft/Planned→Todo, Completed/Closed→Done, Cancelled→Canceled, Paused→Paused, else→Ready — **In Progress / Waiting op statuses unreachable**.+- **07 quality**: nonConformance (type = FIRST nonConformanceType found — not authorable), nonConformanceJobOperation, nonConformanceItem. Nothing else.+- **08 change-orders**: changeOrder, makeMethod (Version clone via cloneMethodRows), methodOperation/methodMaterial clones, item (Revision path new revision, New Part path), item/makeMethod UPDATEs, methodMaterial DELETE/UPDATE/insert (bomEdits), methodOperation UPDATE (description/laborTime only), changeOrderAffectedItem (supersessionMode lands HERE — no live itemSupersession row). Operation children (steps/params/tools) not copied (:52-53).+- **09 accounting**: journal + journalLine (skipped entirely on re-seed — journal is in wipe PRESERVED_TABLES; account by class Asset/Revenue via companyGroupId), fixedAsset (class by name, fallback first), depreciationRun (Draft, previousMonthEnd), depreciationRunLine. taxAmount deliberately NULL.+- **10 ops**: **EMPTY placeholder** (:5-7) — intended future scope per comment: maintenance, table views, custom fields, approvals. No `ops` slice exists in Dataset.+- **11 workflows**: workflow, workflowVersion (always v1), workflow UPDATE publishedVersionId (published only), workflowTriggerEvent, eventSystemSubscription (delete+insert). **No workflowRun/workflowStepRun** — Runs page empty.+- **12 planning**: itemPlanning UPDATEs (Buy 5/10, Make 3/5, policy forced Fixed Reorder Quantity; silent skip on missing ref), opportunity+salesOrder(+payment/shipment/lines — methodType authorable here), period (48 weekly, global table, advisory lock 4820260813), demandProjection (insertMaybe).++## Slice expressiveness limits (engine ceilings)+- customer/supplier currency hardcoded USD; one Net-30 payment term for all; supplierProcess.leadTime=5; contractor 40h; shifts at HQ not Plant.+- Procedure step types authorable: Task/Checkbox/Measurement/Value/List/Person (of 9 in app — no File/Inspection).+- Shipment/receipt/invoice/count: **Draft only reachable** (posting = edge functions; seed is one SQL transaction — architectural boundary, tiers/04-sales.ts:234, 03-inventory.ts:66).+- supplierQuote status + NCR type not authorable (hardcoded/first-row).+- inventoryCount lines not authorable (first 6 opening-stock rows).+- Quality slice = NCR header + 2 association types only. No CAPA/tasks/inspections.+- Fixed asset status union Draft|Active|Fully Depreciated (no Disposed); journal lines only Asset|Revenue classes; journal Draft|Posted.+- planning: exactly one demandOrder; kanban always Buy.++## Robotics actual states used (representative; 4 datasets near-identical by volume contract)+- Row counts (baseline): location 2, process 9, workCenter 7, customer 4, supplier 8, item 34, makeMethod 27, methodMaterial 51, itemLedger 19, opportunity 11, salesRfq 2, quote 3, salesOrder 10, shipment 1, salesInvoice 1, supplierInteraction 6, purchasingRfq 1, supplierQuote 3, purchaseOrder 4, receipt 1, purchaseInvoice 1, job 8, jobOperation 81, nonConformance 2, changeOrder 3, fixedAsset 4, workflow 7.+- salesRfq: Quoted, Ready for Quote (no Draft/Closed). Quotes: Ordered×2, Sent×1 (**no Draft/Expired/Lost/Partial/Cancelled**); all quote lines Complete. SO: In Progress, Confirmed×2, Draft, Completed, Closed, Cancelled, To Ship and Invoice, To Ship (**no Needs Approval/Invoiced/To Invoice**). 1 shipment Draft 0-shipped; 1 sales invoice Draft.+- PO: To Receive, To Invoice, Draft, To Receive and Invoice (**no Planned/Closed/Rejected/Needs Approval/Completed/To Review**); 1 receipt Draft 0-received; 1 purchase invoice Draft; supplier quotes all Active.+- Jobs: all 8 seedable statuses ✓ (Draft, Ready, In Progress, Paused, Planned, Completed, Closed, Cancelled). Op statuses: Todo/Ready/Paused/Done/Canceled (no In Progress/Waiting). Events: 6 rows on 2 ops of one job; quantities: 2×Production. **No scrap/rework, no batches.**+- Genealogy: 1 serial + 6 consumed inputs; tracked entities all Available (or Consumed via genealogy).+- Inventory: 19 opening rows, 3 kanbans, 1 Draft count. **No transfers, no picking, no posted count.**+- Quality: 2 NCRs (In Progress, Registered). No Closed; no inspections; no gauges; no risks; no quality documents.+- Change orders: Draft/Version, Implementation/Revision (Consume First supersession on affected item), Done/New Part ✓ (no Start/Engineering Complete/Cancelled).+- Accounting: FA Active×2/Draft/Fully Depreciated; 1 Draft depreciation run; 1 Draft journal. **No posted anything, no periods, no dimensions, no exchange rates, no payments/memos.**+- Workflows: 1 published + 6 drafts; zero runs.+- Planning: 11 items policied, 3 demand projections, 1 To Ship order.++## Never-touched tables (by module)+- **Returns/RMA**: salesReturnOrder(+line/credit/tracked), purchaseReturnOrder(+…), returnReason.+- **Inspection/quality execution**: inboundInspection(+Feature/History/Measurement/Sample), inspectionDocument, inspectionFeature, itemInspectionDocumentAssignment, itemSamplingPlan, balloon, qualityDocument(+Step).+- **NCR depth**: nonConformanceActionTask/ActionProcess/ApprovalTask/InvestigationTask/InvestigationType/Reviewer/Workflow/Customer/Supplier/TrackedEntity/ItemTrackedEntity/ReceiptLine/ShipmentLine/SalesOrderLine/PurchaseOrderLine/SalesReturnOrderLine/PurchaseReturnOrderLine/InboundInspection.+- **Picking/fulfillment**: pickingList(+line/lineTrackedEntity), pickMethod, fulfillment, deliveryTracking.+- **Quote methods**: quoteMakeMethod (bare interceptor row only), quoteMaterial(+Step), quoteOperation(+Attribute/Parameter/Tool/ToolStep/StepSlide/WorkInstruction) — quote lines have no costed method.+- **Job op depth**: jobOperationTool/ToolStep/Parameter/Attribute/AttributeRecord/Dependency/Note/Batch/StepSlide, jobMaterialStep, jobMaterialTracking, jobProductionTracking.+- **Method depth**: methodOperationTool/ToolStep/Parameter/Attribute/StepSlide/WorkInstruction, methodMaterialStep, buyMethod, procedureParameter.+- **Accounting**: accountingPeriod(+Balance), periodCloseTask, costLedger, supplierLedger, journalLineDimension, dimension(+Value), memo, accountingSyncOperation/TieOut, intercompany*, cardTransaction(+Line), exchangeRate(+History/Override), documentTransaction, purchaseOrderTransaction, salesOrderTransaction. (postingGroup* interceptor-created only.)+- **Traceability**: batchNumber, batchProperty, serialNumber, itemSerialSequence, itemTracking, itemShelfLife, itemInventory, itemStockQuantities.+- **Item config/rules/supersession**: configurationParameter(+Group), configurationRule, itemRule(+Assignment), **itemSupersession**, changeOrderSupersession, customerPartToItem, customerItemPriceOverride(+Break), pricingRule.+- **Material taxonomy**: materialType/Form/Grade/Finish/Substance/Dimension — seeded materials are unclassified.+- **People/HR**: employeeAbility, employeeShift, crew(+Ability), peopleAssignment, peopleAbsence, holiday, timeCardEntry, training(+Assignment/Completion/Question), lessonCompletion. (Shifts/abilities/contractors exist but NO employee linked to any.)+- **Equipment**: equipment(+Type), workCell(+Type), workCenterShift, workCenterReplacementPart, capacityReservation.+- **Maintenance**: maintenanceSchedule(+Item), maintenanceDispatch(+5 children). maintenanceFailureMode bootstrap-only.+- **Gauges**: gauge, gaugeCalibrationRecord (gaugeType bootstrap-preserved).+- **Risk**: riskRegister.+- **Docs/collab**: document*, note, task, project, tag, suggestion, feedback, notification*, reportView/Pin, every *Favorite (job/quote/salesOrder/purchaseOrder/salesRfq/purchasingRfq/supplierQuote).+- **Status history**: salesOrderStatusHistory, purchaseOrderStatusHistory, purchaseInvoiceStatusHistory.+- **Rules/approvals/enterprise**: approvalRule, approvalRequest, enforcementRule(+assignments/ack), itarCertification, sso*, passkeyCredential, userAttribute*, partner.+- **Integrations/infra** (mostly developer-owned, wipe-preserved): webhook(+Table), apiKey, oauth*, integration, companyIntegration, externalIntegrationMapping, slackDocumentThread, printJob, agent*, implementation*.+- **Workflow observability**: workflowRun, workflowStepRun.+- **Assembly depth**: assemblyComponentMapping, assemblyInstructionStepMaterial/Requirement/Slide/Tool, assemblyPlanJob, assemblyStandardNote, assemblyUnit.+- **Forecast**: demandForecast(+Source), demandActual, supplyForecast, supplyActual (last four wiped as transient by wipe.ts:66-71 — MRP recomputes).+- **FA depth**: fixedAssetDisposal, fixedAssetUsageLog, receiptFixedAssetLine, shipmentFixedAssetLine.++## Structural observations+1. Tier 10 is a no-op placeholder; no `ops` slice exists.+2. **No posted document anywhere** — architectural (edge functions can't run inside the seed transaction). Largest coverage boundary.+3. **No partial states** (partial receipt/shipment/payment/issue) — everything 0-or-all.+4. journal/journalLine PRESERVED by dataset wipe → tier 9 skips on every re-seed.+5. Volume contract: all four industries must roughly match (rule doc "Adding an industry"); baselines in .ai/runs/2026-08-13-*-baseline.txt; structural sums file for satellite (methodMaterial|51|258.375; methodOperation|33|263.75|0|0; salesOrderLine|13|112; quoteLinePrice|8).diff --git a/.ai/research/2026-09-22-demo-data-validation-gate.md b/.ai/research/2026-09-22-demo-data-validation-gate.mdnew file mode 100644index 0000000000..0c181c3d3a--- /dev/null+++ b/.ai/research/2026-09-22-demo-data-validation-gate.md@@ -0,0 +1,61 @@+# Demo-data validation gate — current state and gaps (research, 2026-09-22)++Source: Explore agent over `.husky/pre-commit`, `packages/database/src/check-datasets.ts`, `packages/database/src/datasets/verify.ts`, `sql.ts`, tiers.++## 1. The pre-commit trigger and failure behavior++`.husky/pre-commit:46-58`:++```sh+if [ -z "$CARBON_SKIP_DATASET_CHECK" ] && git diff --cached --name-only | grep -q '^packages/database/'; then+ echo "Checking demo datasets against the schema..."+ if ! pnpm --silent db:check:datasets; then+ echo ""+ echo "Commit blocked by the demo-dataset check. The reason is printed above."+ echo "Skip it with: CARBON_SKIP_DATASET_CHECK=1 git commit ..."+ exit 1+ fi+fi+```++- **Trigger:** any staged path under `^packages/database/` (whole package, not just datasets). Changes outside `packages/database/` that break seeding do NOT trigger it.+- **Blocks:** yes — real failure sets `process.exitCode = 1` (`check-datasets.ts:127`), hook exits 1 with a clear message. Script prints per-dataset `✗ <key> (Ns) — <error>` (`check-datasets.ts:120`) plus "N migrations behind" hint or "fix them in packages/database/src/datasets/…" (`check-datasets.ts:112-124`).+- **Bypasses:** `CARBON_SKIP_DATASET_CHECK=1`, `git commit --no-verify`, and husky missing (`.husky/pre-commit:5-8` exits 0 on fresh clone before pnpm install).+- Scripts: root `package.json:47` → `pnpm --filter @carbon/database db:check:datasets --` → `tsx src/check-datasets.ts`. Backup check hook block (`.husky/pre-commit:60-71`) triggers narrower: only `^packages/database/supabase/migrations/`.++## 2. What verify.ts validates++Apply-only, always-rollback (`verify.ts:64-107`): BEGIN → `SET LOCAL app.sync_in_progress` → `seedCompanyReferenceData` → `applyDatasetTiers` → ROLLBACK in `finally`. Failures returned per dataset, not thrown, so one broken dataset doesn't mask others.++Proves: every INSERT accepted by live schema. `buildInsert` reads `information_schema` and throws named errors for unknown table/column (`sql.ts:34-79`). FK/NOT NULL/CHECK/enum/unique violations surface as raw Postgres errors (`verify.ts:96-100`). `assertSingle` catches specific duplicate rows.++Does NOT check: row counts (a tier inserting 0 rows passes), referential completeness beyond Postgres FKs, wipeFirst/re-apply, business invariants.++## 3. Gap surface++| Failure mode | Caught? | Where |+|---|---|---|+| Dropped/renamed column | Yes, if DB current | `sql.ts:75-77` |+| FK / NOT NULL / CHECK / unique violation | Yes, raw PG error | `verify.ts:96-100` |+| Wrong ref key in most tiers | Yes — `need()` throws (`sql.ts:180-186`) | 01:17 uses, 05:14, 04:11, 06:8, 03:7, 02:5, 07:2, 08:2, 12:1 |+| Wrong ref key in 12-planning / 09-accounting | **No** — logs + continue | `12-planning.ts:40,60,178`; `09-accounting.ts:22,75` (and 09/10/11 have **zero** `need()` calls) |+| Wrong `cloc:`/location/shelf-parent key | **No** — `?? null` / unguarded fallback | `04-sales.ts:61,320`; `09-accounting.ts:84`; `01-foundation.ts:131,175`; `12-planning.ts:84` |+| Bad `componentNodeIds` vs graph.json | **No** — graph never read by check | `types.ts` AssemblyStepSpec |+| Wrong quantities/prices/dates/totals; shipment > order qty; invoice subtotal ≠ lines | **No** — no invariant checks | — |+| Row-count regression (silent 0-row tier) | **No** | `verify.ts` |+| promisedDateOffset outside 48-week horizon | **No** — `if (!periodId) break;` | `12-planning.ts:186-187` |+| Migration written but not applied | **No** — reads live schema | `sql.ts:29-32` |+| DB down / no users | **No** — warn + exit 0 (`skip()`) | `check-datasets.ts:42-45,100-111` |+| Ref keys at typecheck | **No** — all bare `string`; `SeedRefs` is `Record<string,string>` | `types.ts` |++Also: `ctx.log` skip messages are invisible in the pre-commit run — `check-datasets.ts` never passes a `log` callback to `verifyDataset`. No tests exist under `src/datasets/`. Typecheck is not run by the hook (lint-staged runs biome only, `package.json:27-34`).++Silent-skip / silent-null sites (full list):+- `12-planning.ts:40-44,60-64,178-182` — missing item ref → skip itemPlanning / demand projection+- `09-accounting.ts:22-23` — no GL accounts → skip journal block; `:75-78` missing fixedAssetClass → skip asset; `:84` wrong location → falls back to HQ+- `04-sales.ts:61,320` — `cloc:` key `?? null` (SO with null customer location)+- `01-foundation.ts:131` — bad shelf parent → root shelf; `:175` unguarded workCenter ref+- `06-production.ts:17` (`!industryId` → whole assembly skipped), `:35` (optional-chained item), `:237` (`!operationId` → genealogy skipped)+- `03-inventory.ts:7`, `04-sales.ts:29`, `12-planning.ts:30` — `refs.locations.Plant ?? locationId`++Typed unions that DO exist: `DatasetKey`, `ChangeType`, `ProcedureStepSpec.type`, `FixedAssetSpec` fields, `JournalLineSpec.accountClass`, `JournalEntrySpec.status`, `BomLineEditSpec`, `PurchaseOrderSpec` discriminants, `ItemType`. Dataset shape itself is a compile error if malformed.diff --git a/.ai/runs/2026-09-23-demo-data-status-audit.txt b/.ai/runs/2026-09-23-demo-data-status-audit.txtnew file mode 100644index 0000000000..a7ed37b298--- /dev/null+++ b/.ai/runs/2026-09-23-demo-data-status-audit.txt@@ -0,0 +1,883 @@+DEMO DATA STATUS-MATRIX AUDIT — final (satellite)+Spec: .ai/specs/2026-09-22-demo-data-completeness.md §B; plan Task 14 step 2. Enum labels read from pg_enum for each column's type+(generated types.ts Enums mirror pg_enum); workflowRun/workflowStepRun statuses from their CHECK constraints.++GAPS FOUND ON THE FIRST AUDIT AND FIXED (all four datasets, validator-pinned):+ purchasingRfq.status Draft, Closed -> purchasing.lifecycleRfqs (Draft + Closed/cancelled RFQ); REQUIRED_PURCHASING_RFQ_STATUSES+ trackedEntity.status Scrapped -> scrapped lot w/ scrap posting (tier 03 scrapLot); REQUIRED_TRACKED_ENTITY_STATUSES+ item.revisionStatus Prototype, Production -> ladder active rev promoted to Production, next rung Prototype; validator requires a Prototype rung++Totals: 264 present, 103 absent — all absent classified (a) intentional; (b) open gaps: 0++column value state classification+--------------------------------------------------------------------------------------------------------------------------------------------+salesRfq.status Draft present+salesRfq.status Ready for Quote present+salesRfq.status Closed present+salesRfq.status Quoted present+quote.status Draft present+quote.status Sent present+quote.status Ordered present+quote.status Partial present+quote.status Lost present+quote.status Cancelled present+quote.status Expired present+quoteLine.status Not Started present+quoteLine.status In Progress present+quoteLine.status Complete present+quoteLine.status No Quote present+salesOrder.status Draft present+salesOrder.status Needs Approval present+salesOrder.status Confirmed present+salesOrder.status In Progress present+salesOrder.status Completed present+salesOrder.status Invoiced present+salesOrder.status Cancelled present+salesOrder.status Closed present+salesOrder.status To Ship and Invoice present+salesOrder.status To Ship present+salesOrder.status To Invoice present+salesOrderLine.status Ordered present+salesOrderLine.status In Progress present+salesOrderLine.status Completed present+shipment.status Draft present+shipment.status Pending absent (a) transient — spec Autonomous Decision 8 (C4): 'Pending' shipment excluded+shipment.status Posted present+shipment.status Voided present+shipment.sourceDocument Sales Order present+shipment.sourceDocument Sales Invoice absent (a) document-type column, outside §B; transfers are seeded as ledger pairs per spec §A tier-03 row, not shipment/receipt docs+shipment.sourceDocument Sales Return Order absent (a) document-type column, outside §B; transfers are seeded as ledger pairs per spec §A tier-03 row, not shipment/receipt docs+shipment.sourceDocument Purchase Order absent (a) document-type column, outside §B; transfers are seeded as ledger pairs per spec §A tier-03 row, not shipment/receipt docs+shipment.sourceDocument Purchase Invoice absent (a) document-type column, outside §B; transfers are seeded as ledger pairs per spec §A tier-03 row, not shipment/receipt docs+shipment.sourceDocument Purchase Return Order present+shipment.sourceDocument Inbound Transfer absent (a) document-type column, outside §B; transfers are seeded as ledger pairs per spec §A tier-03 row, not shipment/receipt docs+shipment.sourceDocument Outbound Transfer absent (a) document-type column, outside §B; transfers are seeded as ledger pairs per spec §A tier-03 row, not shipment/receipt docs+salesInvoice.status Draft present+salesInvoice.status Pending absent (a) transient — Decision 8 (C4)+salesInvoice.status Submitted present+salesInvoice.status Return absent (a) outside §B (salesInvoice row lists Draft..Credit Note Issued); flow-only, mirrors C5's purchase 'Return' exclusion (Decision 9)+salesInvoice.status Credit Note Issued present+salesInvoice.status Paid present+salesInvoice.status Partially Paid present+salesInvoice.status Overdue present+salesInvoice.status Voided present+salesReturnOrder.status Draft present+salesReturnOrder.status To Receive present+salesReturnOrder.status Completed present+salesReturnOrder.status Cancelled absent (a) Decision 8 (C4): 'Cancelled' RMA out of scope+purchasingRfq.status Draft present+purchasingRfq.status Requested present+purchasingRfq.status Closed present+supplierQuote.status Active present+supplierQuote.status Expired present+supplierQuote.status Draft present+supplierQuote.status Declined present+supplierQuote.status Cancelled absent (a) Decision 9 (C5): 'Cancelled' quote flow-only (set by the RFQ cancel action)+supplierQuote.supplierQuoteType Purchase present+supplierQuote.supplierQuoteType Return absent (a) outside §B (supplierQuote row pins statuses only)+supplierQuote.supplierQuoteType Outside Processing absent (a) outside §B (supplierQuote row pins statuses only)+purchaseOrder.status Draft present+purchaseOrder.status To Review present+purchaseOrder.status Rejected present+purchaseOrder.status To Receive present+purchaseOrder.status To Receive and Invoice present+purchaseOrder.status To Invoice present+purchaseOrder.status Completed present+purchaseOrder.status Closed present+purchaseOrder.status Planned present+purchaseOrder.status Needs Approval present+purchaseOrder.purchaseOrderType Purchase present+purchaseOrder.purchaseOrderType Return absent (a) §B: 'types Purchase + Outside Processing' — Return type not in scope+purchaseOrder.purchaseOrderType Outside Processing present+receipt.status Draft present+receipt.status Pending absent (a) Decision 9 (C5): 'Pending' receipt transient+receipt.status Posted present+receipt.status Voided present+receipt.sourceDocument Sales Order absent (a) document-type column, outside §B (see shipment.sourceDocument)+receipt.sourceDocument Sales Invoice absent (a) document-type column, outside §B (see shipment.sourceDocument)+receipt.sourceDocument Sales Return Order present+receipt.sourceDocument Purchase Order present+receipt.sourceDocument Purchase Invoice absent (a) document-type column, outside §B (see shipment.sourceDocument)+receipt.sourceDocument Purchase Return Order absent (a) document-type column, outside §B (see shipment.sourceDocument)+receipt.sourceDocument Inbound Transfer absent (a) document-type column, outside §B (see shipment.sourceDocument)+receipt.sourceDocument Outbound Transfer absent (a) document-type column, outside §B (see shipment.sourceDocument)+receipt.sourceDocument Manufacturing Consumption absent (a) document-type column, outside §B (see shipment.sourceDocument)+receipt.sourceDocument Manufacturing Output absent (a) document-type column, outside §B (see shipment.sourceDocument)+purchaseInvoice.status Draft present+purchaseInvoice.status Pending absent (a) Decision 9 (C5)+purchaseInvoice.status Open present+purchaseInvoice.status Return absent (a) Decision 9 (C5): 'Return' invoice flow-only+purchaseInvoice.status Debit Note Issued present+purchaseInvoice.status Paid present+purchaseInvoice.status Partially Paid present+purchaseInvoice.status Overdue present+purchaseInvoice.status Voided present+purchaseReturnOrder.status Draft present+purchaseReturnOrder.status To Ship present+purchaseReturnOrder.status Completed present+purchaseReturnOrder.status Cancelled absent (a) Decision 9 (C5): 'Cancelled' return excluded+job.status Draft present+job.status Ready present+job.status In Progress present+job.status Paused present+job.status Completed present+job.status Cancelled present+job.status Overdue absent (a) deprecated stored status — UI derives it from dueDate (types.ts JobDeadlineType comment; §B 'all 8 seedable')+job.status Due Today absent (a) same as Overdue+job.status Planned present+job.status Closed present+job.deadlineType No Deadline present+job.deadlineType ASAP present+job.deadlineType Soft Deadline present+job.deadlineType Hard Deadline present+jobOperation.status Canceled present+jobOperation.status Done present+jobOperation.status In Progress present+jobOperation.status Paused present+jobOperation.status Ready present+jobOperation.status Todo present+jobOperation.status Waiting present+jobOperationBatch.status Planned absent (a) §B: 'one Active jobOperationBatch'+jobOperationBatch.status Active present+jobOperationBatch.status Completing absent (a) §B: 'one Active jobOperationBatch'+jobOperationBatch.status Completed absent (a) §B: 'one Active jobOperationBatch'+productionQuantity.type Rework present+productionQuantity.type Scrap present+productionQuantity.type Production present+productionEvent.type Setup present+productionEvent.type Labor present+productionEvent.type Machine present+pickingList.status Draft absent (a) §B: 'pickingList: In Progress + Completed'+pickingList.status In Progress present+pickingList.status Completed present+pickingList.status Cancelled absent (a) §B: 'pickingList: In Progress + Completed'+pickingList.status Partial absent (a) §B: 'pickingList: In Progress + Completed'+pickingListLine.status Pending present+pickingListLine.status Picked present+pickingListLine.status Short present+pickingListLine.status Cancelled absent (a) §B: 'lines Pending/Picked/Short'+stockTransfer.status Draft present+stockTransfer.status Released present+stockTransfer.status In Progress absent (a) spec §A tier-03 row: stockTransfer (Draft/Released/Completed)+stockTransfer.status Completed present+warehouseTransfer.status Draft present+warehouseTransfer.status To Ship and Receive absent (a) spec §A tier-03 row: warehouseTransfer (Draft/To Ship/Completed)+warehouseTransfer.status To Ship present+warehouseTransfer.status To Receive absent (a) spec §A tier-03 row: warehouseTransfer (Draft/To Ship/Completed)+warehouseTransfer.status Completed present+warehouseTransfer.status Cancelled absent (a) spec §A tier-03 row: warehouseTransfer (Draft/To Ship/Completed)+inventoryCount.status Draft present+inventoryCount.status Pending absent (a) §B: 'inventoryCount: Draft + Posted'+inventoryCount.status Posted present+trackedEntity.status Available present+trackedEntity.status Reserved present+trackedEntity.status On Hold present+trackedEntity.status Consumed present+trackedEntity.status Rejected present+trackedEntity.status Scrapped present+nonConformance.status Registered present+nonConformance.status In Progress present+nonConformance.status Closed present+nonConformance.priority Low present+nonConformance.priority Medium present+nonConformance.priority High present+nonConformance.priority Critical present+nonConformance.source Internal present+nonConformance.source External present+nonConformanceActionTask.status Pending present+nonConformanceActionTask.status In Progress present+nonConformanceActionTask.status Completed present+nonConformanceActionTask.status Skipped absent (a) optional — validate.ts REQUIRED_NCR_* comment: nothing in the issue flow requires skipping a task+inspection.status Pending absent (a) Decision 11 (C7): lot seeded Partial; Failed validator-forbidden (would need a post-nonconformance write-off); §B asks Passed+Failed SAMPLES (present)+inspection.status In Progress absent (a) Decision 11 (C7): lot seeded Partial; Failed validator-forbidden (would need a post-nonconformance write-off); §B asks Passed+Failed SAMPLES (present)+inspection.status Passed absent (a) Decision 11 (C7): lot seeded Partial; Failed validator-forbidden (would need a post-nonconformance write-off); §B asks Passed+Failed SAMPLES (present)+inspection.status Failed absent (a) Decision 11 (C7): lot seeded Partial; Failed validator-forbidden (would need a post-nonconformance write-off); §B asks Passed+Failed SAMPLES (present)+inspection.status Partial present+inspectionSample.status Pending absent (a) §B: 'Passed + Failed samples'+inspectionSample.status Passed present+inspectionSample.status Failed present+qualityDocument.status Draft present+qualityDocument.status Active present+qualityDocument.status Archived present+gauge.gaugeCalibrationStatus Pending present+gauge.gaugeCalibrationStatus In-Calibration present+gauge.gaugeCalibrationStatus Out-of-Calibration present+gauge.gaugeStatus Active present+gauge.gaugeStatus Inactive present+gauge.gaugeRole Master present+gauge.gaugeRole Standard present+gaugeCalibrationRecord.inspectionStatus Pass present+gaugeCalibrationRecord.inspectionStatus Fail present+riskRegister.status Open present+riskRegister.status In Review present+riskRegister.status Mitigating present+riskRegister.status Closed present+riskRegister.status Accepted present+riskRegister.source Customer present+riskRegister.source General present+riskRegister.source Item present+riskRegister.source Job present+riskRegister.source Quote Line absent (a) Decision 11 (C7): sources Customer/Supplier/Item/Job/General; §B '≥4 rows'+riskRegister.source Supplier present+riskRegister.source Work Center absent (a) Decision 11 (C7): sources Customer/Supplier/Item/Job/General; §B '≥4 rows'+riskRegister.type Risk present+riskRegister.type Opportunity present+changeOrder.status Draft present+changeOrder.status Start present+changeOrder.status Engineering Complete present+changeOrder.status Implementation present+changeOrder.status Done present+changeOrder.status Cancelled present+changeOrder.priority Low present+changeOrder.priority Medium present+changeOrder.priority High present+changeOrder.priority Critical absent (a) outside §B (changeOrder row pins the 6 statuses)+changeOrder.type Engineering present+changeOrder.type Manufacturing present+changeOrder.type Documentation present+changeOrderActionTask.status Pending present+changeOrderActionTask.status In Progress present+changeOrderActionTask.status Completed present+changeOrderActionTask.status Skipped present+fixedAsset.status Draft present+fixedAsset.status Active present+fixedAsset.status Fully Depreciated present+fixedAsset.status Disposed present+fixedAsset.depreciationMethod Straight Line present+fixedAsset.depreciationMethod Declining Balance absent (a) outside §B (fixedAsset row pins statuses; UoP added by Decision 13)+fixedAsset.depreciationMethod Units of Production present+journal.status Draft present+journal.status Posted present+journal.status Reversed present+journal.sourceType Manual present+journal.sourceType Purchase Receipt absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Purchase Invoice absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Purchase Return absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Sales Invoice absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Sales Shipment absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Sales Return absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Transfer Receipt absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Inventory Adjustment absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Production Order absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Job Consumption absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Job Receipt absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Production Event absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Job Close absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Asset Depreciation absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Asset Disposal absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Payment absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Credit Memo absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Debit Memo absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Non-Conformance absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Inbound Inspection absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Opening Balance absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Sales Return Receipt absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Sales Return Shipment absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Purchase Return Shipment absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+journal.sourceType Card Transaction absent (a) posting-engine source types; journals are hand-authored Manual entries (Decision 13); <null> = the legacy JE-SEED-001+accountingPeriod.status Inactive present+accountingPeriod.status Active present+accountingPeriod.closeStatus Open present+accountingPeriod.closeStatus Locked present+accountingPeriod.closeStatus Closed present+payment.paymentType Receipt present+payment.paymentType Disbursement present+payment.status Draft absent (a) §B: 'payment ×2 types' (both present); Draft/Voided outside §B+payment.status Posted present+payment.status Voided absent (a) §B: 'payment ×2 types' (both present); Draft/Voided outside §B+memo.direction Credit present+memo.direction Debit present+memo.status Draft absent (a) §B: 'memo ×2 directions' (both present); Draft/Voided outside §B+memo.status Posted present+memo.status Voided absent (a) §B: 'memo ×2 directions' (both present); Draft/Voided outside §B+maintenanceDispatch.status Open present+maintenanceDispatch.status Assigned present+maintenanceDispatch.status In Progress present+maintenanceDispatch.status Completed present+maintenanceDispatch.status Cancelled present+maintenanceDispatch.priority Low present+maintenanceDispatch.priority Medium present+maintenanceDispatch.priority High present+maintenanceDispatch.priority Critical present+maintenanceDispatch.severity Preventive present+maintenanceDispatch.severity Operator Performed present+maintenanceDispatch.severity Support Required present+maintenanceDispatch.severity OEM Required present+maintenanceDispatch.source Scheduled present+maintenanceDispatch.source Reactive present+maintenanceDispatch.source Non-Conformance present+maintenanceDispatch.oeeImpact Down present+maintenanceDispatch.oeeImpact Planned present+maintenanceDispatch.oeeImpact Impact present+maintenanceDispatch.oeeImpact No Impact present+maintenanceSchedule.frequency Daily present+maintenanceSchedule.frequency Weekly present+maintenanceSchedule.frequency Monthly present+maintenanceSchedule.frequency Quarterly present+maintenanceSchedule.frequency Annual present+training.status Draft present+training.status Active present+training.status Archived absent (a) §B: 'training ≥2 courses'; Decision 14 pins Active + Draft+training.frequency Once present+training.frequency Quarterly absent (a) outside §B+training.frequency Annual present+training.type Mandatory present+training.type Optional present+trainingQuestion.type MultipleChoice present+trainingQuestion.type TrueFalse present+trainingQuestion.type MultipleAnswers present+trainingQuestion.type MatchingPairs present+trainingQuestion.type Numerical present+workflowRun.status Queued absent (a) engine-only transient/in-flight states; §B '≥3 terminal runs' (Decision 10)+workflowRun.status Running absent (a) engine-only transient/in-flight states; §B '≥3 terminal runs' (Decision 10)+workflowRun.status Succeeded present+workflowRun.status Failed present+workflowRun.status Blocked absent (a) engine-only transient/in-flight states; §B '≥3 terminal runs' (Decision 10)+workflowRun.status Skipped present+workflowStepRun.status Running absent (a) engine-only (Running) / condition-branch (Skipped) states; Decision 14 shapes+workflowStepRun.status Succeeded present+workflowStepRun.status Failed present+workflowStepRun.status Skipped absent (a) engine-only (Running) / condition-branch (Skipped) states; Decision 14 shapes+supplier.supplierStatus Active present+supplier.supplierStatus Inactive present+supplier.supplierStatus Pending present+supplier.supplierStatus Rejected present+itemSupersession.supersessionMode Consume First present+itemSupersession.supersessionMode Prefer New absent (a) §B: 'itemSupersession 1 live pair' (Consume First, Task 4)+itemSupersession.supersessionMode Stock Only absent (a) §B: 'itemSupersession 1 live pair' (Consume First, Task 4)+itemSupersession.supersessionMode No Stock absent (a) §B: 'itemSupersession 1 live pair' (Consume First, Task 4)+kanban.replenishmentSystem Buy present+kanban.replenishmentSystem Make present+kanban.replenishmentSystem Transfer present+item.type Part present+item.type Material present+item.type Tool present+item.type Service present+item.type Consumable present+item.type Fixture absent (a) outside §B (pre-existing catalog)+item.replenishmentSystem Buy present+item.replenishmentSystem Make present+item.replenishmentSystem Buy and Make absent (a) outside §B+item.itemTrackingType Inventory present+item.itemTrackingType Non-Inventory absent (a) outside §B+item.itemTrackingType Serial present+item.itemTrackingType Batch present+item.revisionStatus Design present+item.revisionStatus Prototype present+item.revisionStatus Production present+item.revisionStatus Obsolete present+salesReturnOrderLine.disposition Conditional Acceptance absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Deviation Accepted absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Hold absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition No Action Required absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Pending present+salesReturnOrderLine.disposition Quarantine absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Repair absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Return to Supplier absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Rework absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Scrap absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Use As Is absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'+salesReturnOrderLine.disposition Return to Customer absent (a) outside §B; Completed+Pending is a real app state — sales.service.ts setSalesReturnOrderLineDisposition: post-receipt auto-completes the RMA and 'disposition is a post-receipt decision'++============================================================================================================================================+RAW AUDIT OUTPUT (per-value row counts in brackets) + LIST-SCREEN COUNTS+============================================================================================================================================+Company: dapnjkh860gjckkl52t0 ([email protected]) generated 2026-09-23T07:19Z++################ STATUS MATRIX ################+== salesRfq.status (salesRfqStatus) [Closed=1 Draft=1 Quoted=1 Ready for Quote=1 ]+ present Draft+ present Ready for Quote+ present Closed+ present Quoted+== quote.status (quoteStatus) [Cancelled=1 Draft=1 Expired=1 Lost=1 Ordered=2 Partial=1 Sent=1 ]+ present Draft+ present Sent+ present Ordered+ present Partial+ present Lost+ present Cancelled+ present Expired+== quoteLine.status (quoteLineStatus) [Complete=7 In Progress=1 No Quote=1 Not Started=1 ]+ present Not Started+ present In Progress+ present Complete+ present No Quote+== salesOrder.status (salesOrderStatus) [Cancelled=1 Closed=3 Completed=1 Confirmed=2 Draft=1 In Progress=2 Invoiced=3 Needs Approval=1 To Invoice=2 To Ship=2 To Ship and Invoice=2 ]+ present Draft+ present Needs Approval+ present Confirmed+ present In Progress+ present Completed+ present Invoiced+ present Cancelled+ present Closed+ present To Ship and Invoice+ present To Ship+ present To Invoice+== salesOrderLine.status (salesOrderLineStatus) [Completed=9 In Progress=3 Ordered=11 ]+ present Ordered+ present In Progress+ present Completed+== shipment.status (shipmentStatus) [Draft=1 Posted=3 Voided=1 ]+ present Draft+ ABSENT Pending+ present Posted+ present Voided+== shipment.sourceDocument (shipmentSourceDocument) [Purchase Return Order=1 Sales Order=4 ]+ present Sales Order+ ABSENT Sales Invoice+ ABSENT Sales Return Order+ ABSENT Purchase Order+ ABSENT Purchase Invoice+ present Purchase Return Order+ ABSENT Inbound Transfer+ ABSENT Outbound Transfer+== salesInvoice.status (salesInvoiceStatus) [Credit Note Issued=1 Draft=1 Overdue=1 Paid=1 Partially Paid=1 Submitted=1 Voided=1 ]+ present Draft+ ABSENT Pending+ present Submitted+ ABSENT Return+ present Credit Note Issued+ present Paid+ present Partially Paid+ present Overdue+ present Voided+== salesInvoices.status (text) [Credit Note Issued=1 Draft=1 Overdue=1 Paid=1 Partially Paid=1 Submitted=1 Voided=1 ]+== salesReturnOrder.status (salesReturnOrderStatus) [Completed=1 Draft=1 To Receive=1 ]+ present Draft+ present To Receive+ present Completed+ ABSENT Cancelled+== purchasingRfq.status (purchasingRfqStatus) [Closed=1 Draft=1 Requested=1 ]+ present Draft+ present Requested+ present Closed+== supplierQuote.status (supplierQuoteStatus) [Active=3 Declined=1 Draft=1 Expired=1 ]+ present Active+ present Expired+ present Draft+ present Declined+ ABSENT Cancelled+== supplierQuote.supplierQuoteType (purchaseOrderType) [Purchase=6 ]+ present Purchase+ ABSENT Return+ ABSENT Outside Processing+== purchaseOrder.status (purchaseOrderStatus) [Closed=2 Completed=4 Draft=1 Needs Approval=1 Planned=1 Rejected=1 To Invoice=2 To Receive=3 To Receive and Invoice=1 To Review=1 ]+ present Draft+ present To Review+ present Rejected+ present To Receive+ present To Receive and Invoice+ present To Invoice+ present Completed+ present Closed+ present Planned+ present Needs Approval+== purchaseOrder.purchaseOrderType (purchaseOrderType) [Outside Processing=1 Purchase=16 ]+ present Purchase+ ABSENT Return+ present Outside Processing+== receipt.status (receiptStatus) [Draft=1 Posted=3 Voided=1 ]+ present Draft+ ABSENT Pending+ present Posted+ present Voided+== receipt.sourceDocument (receiptSourceDocument) [Purchase Order=4 Sales Return Order=1 ]+ ABSENT Sales Order+ ABSENT Sales Invoice+ present Sales Return Order+ present Purchase Order+ ABSENT Purchase Invoice+ ABSENT Purchase Return Order+ ABSENT Inbound Transfer+ ABSENT Outbound Transfer+ ABSENT Manufacturing Consumption+ ABSENT Manufacturing Output+== purchaseInvoice.status (purchaseInvoiceStatus) [Debit Note Issued=1 Draft=1 Open=1 Overdue=1 Paid=1 Partially Paid=1 Voided=1 ]+ present Draft+ ABSENT Pending+ present Open+ ABSENT Return+ present Debit Note Issued+ present Paid+ present Partially Paid+ present Overdue+ present Voided+== purchaseInvoices.status (text) [Debit Note Issued=1 Draft=1 Open=1 Overdue=1 Paid=1 Partially Paid=1 Voided=1 ]+== purchaseReturnOrder.status (purchaseReturnOrderStatus) [Completed=1 Draft=1 To Ship=1 ]+ present Draft+ present To Ship+ present Completed+ ABSENT Cancelled+== job.status (jobStatus) [Cancelled=1 Closed=1 Completed=1 Draft=1 In Progress=1 Paused=1 Planned=1 Ready=1 ]+ present Draft+ present Ready+ present In Progress+ present Paused+ present Completed+ present Cancelled+ ABSENT Overdue+ ABSENT Due Today+ present Planned+ present Closed+== job.deadlineType (deadlineType) [ASAP=1 Hard Deadline=5 No Deadline=1 Soft Deadline=1 ]+ present No Deadline+ present ASAP+ present Soft Deadline+ present Hard Deadline+== jobOperation.status (jobOperationStatus) [Canceled=2 Done=7 In Progress=1 Paused=5 Ready=53 Todo=12 Waiting=1 ]+ present Canceled+ present Done+ present In Progress+ present Paused+ present Ready+ present Todo+ present Waiting+== jobOperationBatch.status (jobOperationBatchStatus) [Active=1 ]+ ABSENT Planned+ present Active+ ABSENT Completing+ ABSENT Completed+== productionQuantity.type (productionQuantityType) [Production=1 Rework=1 Scrap=1 ]+ present Rework+ present Scrap+ present Production+== productionEvent.type (productionEventType) [Labor=2 Machine=2 Setup=3 ]+ present Setup+ present Labor+ present Machine+== pickingList.status (pickingListStatus) [Completed=1 In Progress=1 ]+ ABSENT Draft+ present In Progress+ present Completed+ ABSENT Cancelled+ ABSENT Partial+== pickingListLine.status (pickingListLineStatus) [Pending=1 Picked=2 Short=1 ]+ present Pending+ present Picked+ present Short+ ABSENT Cancelled+== stockTransfer.status (stockTransferStatus) [Completed=1 Draft=1 Released=1 ]+ present Draft+ present Released+ ABSENT In Progress+ present Completed+== warehouseTransfer.status (warehouseTransferStatus) [Completed=1 Draft=1 To Ship=1 ]+ present Draft+ ABSENT To Ship and Receive+ present To Ship+ ABSENT To Receive+ present Completed+ ABSENT Cancelled+== inventoryCount.status (inventoryCountStatus) [Draft=1 Posted=1 ]+ present Draft+ ABSENT Pending+ present Posted+== trackedEntity.status (trackedEntityStatus) [Available=10 Consumed=6 On Hold=1 Rejected=1 Reserved=32 Scrapped=1 ]+ present Available+ present Reserved+ present On Hold+ present Consumed+ present Rejected+ present Scrapped+== nonConformance.status (nonConformanceStatus) [Closed=1 In Progress=2 Registered=2 ]+ present Registered+ present In Progress+ present Closed+== nonConformance.priority (nonConformancePriority) [Critical=1 High=1 Low=1 Medium=2 ]+ present Low+ present Medium+ present High+ present Critical+== nonConformance.source (nonConformanceSource) [External=2 Internal=3 ]+ present Internal+ present External+== nonConformanceActionTask.status (nonConformanceTaskStatus) [Completed=4 In Progress=1 Pending=2 ]+ present Pending+ present In Progress+ present Completed+ ABSENT Skipped+== inspection.status (inspectionStatusType) [Partial=1 ]+ ABSENT Pending+ ABSENT In Progress+ ABSENT Passed+ ABSENT Failed+ present Partial+== inspectionSample.status (inspectionSampleStatusType) [Failed=1 Passed=1 ]+ ABSENT Pending+ present Passed+ present Failed+== qualityDocument.status (qualityDocumentStatus) [Active=1 Archived=1 Draft=1 ]+ present Draft+ present Active+ present Archived+== gauge.gaugeCalibrationStatus (gaugeCalibrationStatus) [In-Calibration=1 Out-of-Calibration=1 Pending=1 ]+ present Pending+ present In-Calibration+ present Out-of-Calibration+== gauge.gaugeStatus (gaugeStatus) [Active=2 Inactive=1 ]+ present Active+ present Inactive+== gauge.gaugeRole (gaugeRole) [Master=1 Standard=2 ]+ present Master+ present Standard+== gaugeCalibrationRecord.inspectionStatus (inspectionStatus) [Fail=1 Pass=3 ]+ present Pass+ present Fail+== riskRegister.status (riskStatus) [Accepted=1 Closed=1 In Review=1 Mitigating=1 Open=1 ]+ present Open+ present In Review+ present Mitigating+ present Closed+ present Accepted+== riskRegister.source (riskSource) [Customer=1 General=1 Item=1 Job=1 Supplier=1 ]+ present Customer+ present General+ present Item+ present Job+ ABSENT Quote Line+ present Supplier+ ABSENT Work Center+== riskRegister.type (riskRegisterType) [Opportunity=1 Risk=4 ]+ present Risk+ present Opportunity+== changeOrder.status (changeOrderStatus) [Cancelled=1 Done=1 Draft=1 Engineering Complete=1 Implementation=1 Start=1 ]+ present Draft+ present Start+ present Engineering Complete+ present Implementation+ present Done+ present Cancelled+== changeOrder.priority (nonConformancePriority) [High=1 Low=1 Medium=1 <null>=3 ]+ present Low+ present Medium+ present High+ ABSENT Critical+== changeOrder.type (changeOrderTypeEnum) [Documentation=1 Engineering=4 Manufacturing=1 ]+ present Engineering+ present Manufacturing+ present Documentation+== changeOrderActionTask.status (changeOrderTaskStatus) [Completed=2 In Progress=2 Pending=1 Skipped=1 ]+ present Pending+ present In Progress+ present Completed+ present Skipped+== fixedAsset.status (fixedAssetStatus) [Active=3 Disposed=1 Draft=1 Fully Depreciated=1 ]+ present Draft+ present Active+ present Fully Depreciated+ present Disposed+== fixedAsset.depreciationMethod (depreciationMethod) [Straight Line=5 Units of Production=1 ]+ present Straight Line+ ABSENT Declining Balance+ present Units of Production+== journal.status (journalEntryStatus) [Draft=1 Posted=3 Reversed=1 ]+ present Draft+ present Posted+ present Reversed+== journal.sourceType (journalEntrySourceType) [Manual=4 <null>=1 ]+ present Manual+ ABSENT Purchase Receipt+ ABSENT Purchase Invoice+ ABSENT Purchase Return+ ABSENT Sales Invoice+ ABSENT Sales Shipment+ ABSENT Sales Return+ ABSENT Transfer Receipt+ ABSENT Inventory Adjustment+ ABSENT Production Order+ ABSENT Job Consumption+ ABSENT Job Receipt+ ABSENT Production Event+ ABSENT Job Close+ ABSENT Asset Depreciation+ ABSENT Asset Disposal+ ABSENT Payment+ ABSENT Credit Memo+ ABSENT Debit Memo+ ABSENT Non-Conformance+ ABSENT Inbound Inspection+ ABSENT Opening Balance+ ABSENT Sales Return Receipt+ ABSENT Sales Return Shipment+ ABSENT Purchase Return Shipment+ ABSENT Card Transaction+== accountingPeriod.status (accountingPeriodStatus) [Active=1 Inactive=11 ]+ present Inactive+ present Active+== accountingPeriod.closeStatus (periodCloseStatus) [Closed=2 Locked=1 Open=9 ]+ present Open+ present Locked+ present Closed+== payment.paymentType (paymentType) [Disbursement=3 Receipt=3 ]+ present Receipt+ present Disbursement+== payment.status (paymentStatus) [Posted=6 ]+ ABSENT Draft+ present Posted+ ABSENT Voided+== memo.direction (memoDirection) [Credit=1 Debit=1 ]+ present Credit+ present Debit+== memo.status (memoStatus) [Posted=2 ]+ ABSENT Draft+ present Posted+ ABSENT Voided+== maintenanceDispatch.status (maintenanceDispatchStatus) [Assigned=1 Cancelled=1 Completed=1 In Progress=1 Open=1 ]+ present Open+ present Assigned+ present In Progress+ present Completed+ present Cancelled+== maintenanceDispatch.priority (maintenanceDispatchPriority) [Critical=1 High=1 Low=1 Medium=2 ]+ present Low+ present Medium+ present High+ present Critical+== maintenanceDispatch.severity (maintenanceSeverity) [OEM Required=1 Operator Performed=1 Preventive=2 Support Required=1 ]+ present Preventive+ present Operator Performed+ present Support Required+ present OEM Required+== maintenanceDispatch.source (maintenanceSource) [Non-Conformance=1 Reactive=2 Scheduled=2 ]+ present Scheduled+ present Reactive+ present Non-Conformance+== maintenanceDispatch.oeeImpact (oeeImpact) [Down=1 Impact=1 No Impact=1 Planned=2 ]+ present Down+ present Planned+ present Impact+ present No Impact+== maintenanceSchedule.frequency (maintenanceFrequency) [Annual=1 Daily=1 Monthly=1 Quarterly=1 Weekly=1 ]+ present Daily+ present Weekly+ present Monthly+ present Quarterly+ present Annual+== training.status (trainingStatus) [Active=2 Draft=1 ]+ present Draft+ present Active+ ABSENT Archived+== training.frequency (trainingFrequency) [Annual=1 Once=2 ]+ present Once+ ABSENT Quarterly+ present Annual+== training.type (trainingType) [Mandatory=2 Optional=1 ]+ present Mandatory+ present Optional+== trainingQuestion.type (trainingQuestionType) [MatchingPairs=1 MultipleAnswers=1 MultipleChoice=2 Numerical=2 TrueFalse=2 ]+ present MultipleChoice+ present TrueFalse+ present MultipleAnswers+ present MatchingPairs+ present Numerical+== workflowRun.status (text CHECK) [Failed=1 Skipped=1 Succeeded=1 ]+ ABSENT Queued+ ABSENT Running+ present Succeeded+ present Failed+ ABSENT Blocked+ present Skipped+== workflowStepRun.status (text CHECK) [Failed=1 Succeeded=3 ]+ ABSENT Running+ present Succeeded+ present Failed+ ABSENT Skipped+== supplier.supplierStatus (supplierStatusType) [Active=1 Inactive=1 <null>=7 Pending=1 Rejected=1 ]+ present Active+ present Inactive+ present Pending+ present Rejected+== itemSupersession.supersessionMode (supersessionMode) [Consume First=1 ]+ present Consume First+ ABSENT Prefer New+ ABSENT Stock Only+ ABSENT No Stock+== kanban.replenishmentSystem (kanbanReplenishmentSystem) [Buy=3 Make=1 Transfer=1 ]+ present Buy+ present Make+ present Transfer+== item.type (itemType) [Consumable=2 Material=6 Part=26 Service=1 Tool=2 ]+ present Part+ present Material+ present Tool+ present Service+ present Consumable+ ABSENT Fixture+== item.replenishmentSystem (itemReplenishmentSystem) [Buy=23 Make=14 ]+ present Buy+ present Make+ ABSENT Buy and Make+== item.itemTrackingType (itemTrackingType) [Batch=2 Inventory=33 Serial=2 ]+ present Inventory+ ABSENT Non-Inventory+ present Serial+ present Batch+== item.revisionStatus (itemRevisionStatus) [Design=34 Obsolete=1 Production=1 Prototype=1 ]+ present Design+ present Prototype+ present Production+ present Obsolete+== salesReturnOrderLine.disposition (disposition) [Pending=3 ]+ ABSENT Conditional Acceptance+ ABSENT Deviation Accepted+ ABSENT Hold+ ABSENT No Action Required+ present Pending+ ABSENT Quarantine+ ABSENT Repair+ ABSENT Return to Supplier+ ABSENT Rework+ ABSENT Scrap+ ABSENT Use As Is+ ABSENT Return to Customer++ABSENT enum values (before classification): 103++################ LIST-SCREEN COUNTS (views where the app lists from a view) ################+ OK Parts (parts) 23+ OK Materials (materials) 6+ OK Tools (tools) 2+ OK Consumables (consumables) 2+ OK Services (services) 1+ OK Customers (customers) 4+ OK Suppliers (suppliers) 11+ OK Sales RFQs ("salesRfqs") 4+ OK Quotes (quotes) 8+ OK Sales orders ("salesOrders") 20+ OK Sales invoices ("salesInvoices") 7+ OK Shipments (shipment) 5+ OK Sales returns ("salesReturnOrders") 3+ OK Purchasing RFQs ("purchasingRfqs") 3+ OK Supplier quotes ("supplierQuotes") 6+ OK Purchase orders ("purchaseOrders") 17+ OK Purchase invoices ("purchaseInvoices") 7+ OK Receipts (view) (receipts) 5+ OK Receipts (table, list svc) (receipt) 5+ OK Purchase returns ("purchaseReturnOrders") 3+ OK Jobs (jobs) 8+ OK Picking lists ("pickingLists") 2+ OK Stock transfers ("stockTransfer") 3+ OK Warehouse transfers ("warehouseTransfer") 3+ OK Inventory counts ("inventoryCount") 2+ OK Kanbans (kanbans) 5+ OK Tracked entities ("trackedEntity") 51+ OK Issues (NCR) (issues) 5+ OK Inspections (inspection) 1+ OK Quality documents ("qualityDocuments") 2+ OK Gauges (gauges) 3+ OK Gauge calibrations ("gaugeCalibrationRecords") 4+ OK Risks ("riskRegisters") 5+ OK Change orders ("changeOrders") 6+ OK Maintenance dispatches ("maintenanceDispatch") 5+ OK Maintenance schedules ("maintenanceSchedule") 5+ OK Trainings (trainings) 3+ OK Timecards ("timeCardEntry") 6+ OK Fixed assets ("fixedAsset") 6+ OK Journal entries ("journalEntries") 5+ OK Payments (payment) 6+ OK Memos (memo) 2+ OK Accounting periods ("accountingPeriod") 12+ OK Workflow runs ("workflowRun") 3+ OK Workflows (workflow) 7diff --git a/.ai/runs/2026-09-23-demo-data-verification-drills.txt b/.ai/runs/2026-09-23-demo-data-verification-drills.txtnew file mode 100644index 0000000000..98d82068c9--- /dev/null+++ b/.ai/runs/2026-09-23-demo-data-verification-drills.txt@@ -0,0 +1,49 @@+# Negative-path drills — 2026-09-23, branch feat/demo-data-completeness (plan Tasks 13-14, spec acceptance #1/#2)++## Task 13 — row-count floor drill (coverage.ts floors temporarily raised above actual, then restored; file sha identical after)+$ (pickingList floor 2->3, jobFavorite floor 1->2) pnpm --silent db:check:datasets --dataset satellite+Checking 1 dataset(s) against the schema...+ ✗ satellite (1.0s) — 2 table(s) below their row-count floor (datasets/coverage.ts):+ jobFavorite: expected ≥ 2, got 1+ pickingList: expected ≥ 3, got 2++The demo datasets no longer match the schema, or a table fell below its row-count floor (datasets/coverage.ts). Fix them in packages/database/src/datasets/ — onboarding's demo templates and pnpm db:seed:dev both run this code.+Re-run on its own with: pnpm db:check:datasets+Commit anyway with: CARBON_SKIP_DATASET_CHECK=1 git commit ...+exit=1++## Task 14 step 6a — broken item ref, DB unreachable+$ SUPABASE_DB_URL=postgresql://postgres:postgres@localhost:1/postgres pnpm --silent db:check:datasets+ ✗ satellite — 1 consistency violation(s):+ purchasing.lifecycleRfqs "prfq:star-tracker": unknown item "ST-050-BOGUS"++The demo datasets are internally inconsistent. Fix them in packages/database/src/datasets/data/ before committing.+Re-run on its own with: pnpm db:check:datasets+Commit anyway with: CARBON_SKIP_DATASET_CHECK=1 git commit ...+exit=1++## Task 14 step 6b — broken file staged alone, hook run directly (output tail)++strip-po-headers: 26 file(s) normalized+Checking demo datasets against the schema...+ ✗ satellite — 1 consistency violation(s):+ purchasing.lifecycleRfqs "prfq:star-tracker": unknown item "ST-050-BOGUS"++The demo datasets are internally inconsistent. Fix them in packages/database/src/datasets/data/ before committing.+Re-run on its own with: pnpm db:check:datasets+Commit anyway with: CARBON_SKIP_DATASET_CHECK=1 git commit ...++Commit blocked by the demo-dataset check. The reason is printed above.+Skip it with: CARBON_SKIP_DATASET_CHECK=1 git commit ...+husky - pre-commit hook exited with code 1 (error)+exit=1++--- restore: git restore --staged packages/database/src/datasets/data/satellite/purchasing.ts && cp <pre-drill backup> packages/database/src/datasets/data/satellite/purchasing.ts+staged files now: []+file sha before: 38f65d7b5b6be7168975ad54e67fc14f2267f324 packages/database/src/datasets/data/satellite/purchasing.ts+file sha after: 38f65d7b5b6be7168975ad54e67fc14f2267f324 packages/database/src/datasets/data/satellite/purchasing.ts+git diff sha before: 96bf1505e7d5450756ae008a6cfec0c9543786b4 -+git diff sha after: 96bf1505e7d5450756ae008a6cfec0c9543786b4 -+grep BOGUS: 0+status vs pre-drill: identical+hook side effects: lingui:clean rewrote locale .po files with identical content (git status unchanged); no stash left behinddiff --git a/.ai/runs/2026-09-23-seed-baseline-motor.txt b/.ai/runs/2026-09-23-seed-baseline-motor.txtnew file mode 100644index 0000000000..7d9a9bbeb7--- /dev/null+++ b/.ai/runs/2026-09-23-seed-baseline-motor.txt@@ -0,0 +1,30 @@+# pnpm db:seed:dev -- --email [email protected] --dataset motor (2026-09-23, branch feat/demo-data-completeness, re-apply onto scratch company dapnjkh860gjckkl52t0, exit 0)+Seeded row counts+-----------------+ location 2+ process 14+ workCenter 8+ customer 4+ supplier 12+ item 37+ makeMethod 30+ methodMaterial 54+ itemLedger 38+ opportunity 28+ salesRfq 4+ quote 8+ salesOrder 20+ shipment 5+ salesInvoice 7+ supplierInteraction 22+ purchasingRfq 3+ supplierQuote 6+ purchaseOrder 17+ receipt 5+ purchaseInvoice 7+ job 8+ jobOperation 54+ nonConformance 5+ changeOrder 6+ fixedAsset 6+ workflow 7diff --git a/.ai/runs/2026-09-23-seed-baseline-precision.txt b/.ai/runs/2026-09-23-seed-baseline-precision.txtnew file mode 100644index 0000000000..af49adea5d--- /dev/null+++ b/.ai/runs/2026-09-23-seed-baseline-precision.txt@@ -0,0 +1,30 @@+# pnpm db:seed:dev -- --email [email protected] --dataset precision (2026-09-23, branch feat/demo-data-completeness, re-apply onto scratch company dapnjkh860gjckkl52t0, exit 0)+Seeded row counts+-----------------+ location 2+ process 11+ workCenter 7+ customer 4+ supplier 12+ item 37+ makeMethod 30+ methodMaterial 54+ itemLedger 38+ opportunity 28+ salesRfq 4+ quote 8+ salesOrder 20+ shipment 5+ salesInvoice 7+ supplierInteraction 22+ purchasingRfq 3+ supplierQuote 6+ purchaseOrder 17+ receipt 5+ purchaseInvoice 7+ job 8+ jobOperation 80+ nonConformance 5+ changeOrder 6+ fixedAsset 6+ workflow 7diff --git a/.ai/runs/2026-09-23-seed-baseline-robotics.txt b/.ai/runs/2026-09-23-seed-baseline-robotics.txtnew file mode 100644index 0000000000..3728b2fc66--- /dev/null+++ b/.ai/runs/2026-09-23-seed-baseline-robotics.txt@@ -0,0 +1,30 @@+# pnpm db:seed:dev -- --email [email protected] --dataset robotics (2026-09-23, branch feat/demo-data-completeness, re-apply onto scratch company dapnjkh860gjckkl52t0, exit 0)+Seeded row counts+-----------------+ location 2+ process 14+ workCenter 7+ customer 4+ supplier 12+ item 37+ makeMethod 30+ methodMaterial 51+ itemLedger 38+ opportunity 28+ salesRfq 4+ quote 8+ salesOrder 20+ shipment 5+ salesInvoice 7+ supplierInteraction 22+ purchasingRfq 3+ supplierQuote 6+ purchaseOrder 17+ receipt 5+ purchaseInvoice 7+ job 8+ jobOperation 81+ nonConformance 5+ changeOrder 6+ fixedAsset 6+ workflow 7diff --git a/.ai/runs/2026-09-23-seed-baseline-satellite-structural.txt b/.ai/runs/2026-09-23-seed-baseline-satellite-structural.txtnew file mode 100644index 0000000000..9e998e57ed--- /dev/null+++ b/.ai/runs/2026-09-23-seed-baseline-satellite-structural.txt@@ -0,0 +1,36 @@+# Structural sums — satellite, scratch company dapnjkh860gjckkl52t0 ([email protected]), 2026-09-23, branch feat/demo-data-completeness+# Queries (all WHERE "companyId" = <company>):+# methodMaterial: count(*), sum(quantity)+# methodOperation: count(*), sum("laborTime"), sum("setupTime"), sum("machineTime") (old file's column order — its values 263.75|0|0 match laborTime)+# salesOrderLine: count(*), sum("saleQuantity"); quoteLinePrice: count(*)+# itemLedger: count(*), sum(quantity), then per (entryType, documentType)+# journalLine: count(*), sum(amount), then per account.class (journalLine.accountId -> account.id)+# journal balance: amount is signed by the account's natural balance (lib/utils.ts debit/credit),+# so per journal debit-minus-credit = sum(CASE class IN (Asset, Expense) THEN amount ELSE -amount) must be 0+methodMaterial|51|258.375+methodOperation|33|263.75|0.00|0.00+salesOrderLine|23|752.00000+quoteLinePrice|13+itemLedger|38|1138+ itemLedger|Positive Adjmt.|Sales Return Receipt|1|1+ itemLedger|Positive Adjmt.|Purchase Receipt|3|14+ itemLedger|Positive Adjmt.|Inventory Receipt|19|1173+ itemLedger|Positive Adjmt.|Inventory Count|1|2+ itemLedger|Negative Adjmt.|Sales Shipment|2|-4+ itemLedger|Negative Adjmt.|Purchase Return Shipment|1|-40+ itemLedger|Negative Adjmt.|Inventory Count|1|-2+ itemLedger|Negative Adjmt.|Scrap|1|-4+ itemLedger|Transfer|Transfer Shipment|1|-25+ itemLedger|Transfer|Transfer Receipt|1|25+ itemLedger|Transfer|Direct Transfer|6|0+ itemLedger|Consumption|Maintenance Consumption|1|-2+journalLine|10|3697000+ journalLine|Asset|2|1798750+ journalLine|Liability|3|48500+ journalLine|Revenue|1|1800000+ journalLine|Expense|4|49750+ journal|JE-SEED-001|Draft|2|0+ journal|JE-SEED-002|Posted|2|0+ journal|JE-SEED-003|Posted|2|0+ journal|JE-SEED-004|Reversed|2|0+ journal|JE-SEED-005|Posted|2|0diff --git a/.ai/runs/2026-09-23-seed-baseline-satellite.txt b/.ai/runs/2026-09-23-seed-baseline-satellite.txtnew file mode 100644index 0000000000..2b57815172--- /dev/null+++ b/.ai/runs/2026-09-23-seed-baseline-satellite.txt@@ -0,0 +1,30 @@+# pnpm db:seed:dev -- --email [email protected] --dataset satellite (2026-09-23, branch feat/demo-data-completeness, re-apply onto scratch company dapnjkh860gjckkl52t0, exit 0)+Seeded row counts+-----------------+ location 2+ process 12+ workCenter 7+ customer 4+ supplier 11+ item 37+ makeMethod 30+ methodMaterial 51+ itemLedger 38+ opportunity 28+ salesRfq 4+ quote 8+ salesOrder 20+ shipment 5+ salesInvoice 7+ supplierInteraction 22+ purchasingRfq 3+ supplierQuote 6+ purchaseOrder 17+ receipt 5+ purchaseInvoice 7+ job 8+ jobOperation 81+ nonConformance 5+ changeOrder 6+ fixedAsset 6+ workflow 7diff --git a/.ai/specs/2026-09-22-demo-data-completeness.md b/.ai/specs/2026-09-22-demo-data-completeness.mdnew file mode 100644index 0000000000..a57034b5e3--- /dev/null+++ b/.ai/specs/2026-09-22-demo-data-completeness.md@@ -0,0 +1,232 @@+# Demo Data Completeness — every feature, every state++**Status:** Implemented (autonomous mode — user-delegated; uncommitted on the branch, awaiting the user's commit) · **Date:** 2026-09-22 · **Branch:** `feat/demo-data-completeness`+**Research:** `.ai/research/2026-09-22-demo-data-current-coverage.md`, `.ai/research/2026-09-22-app-feature-surface.md`, `.ai/research/2026-09-22-demo-data-validation-gate.md`++## Reading of the request (autonomous mode)++**What:** Expand the demo-data datasets (`packages/database/src/datasets/`) so a company seeded from any of the four industry templates exercises every major feature and reachable state of the ERP + MES apps — every list screen has rows, every detail screen opens, every status enum value a user can encounter appears somewhere. **Why:** demo data is the primary way prospects, staff and developers experience Carbon; today it covers ~40% of the app (no returns, no inspections, no maintenance, no picking, no posted documents, no payments, no HR, …). **Where:** the dataset engine (tiers), the dataset type, all four industry data packs, and the pre-commit validation. **Who:** anyone applying a demo template (Settings → Demo Data, onboarding, `pnpm db:seed:dev`). **Explicit user constraints:** leave out *files* (no document/file uploads); everything else in; be maximally thorough; no regressions; keep FK integrity; validation must block commits on invalid demo data with a clear message.++## Goals++1. Every user-reachable status enum value of every major document type appears in every dataset (matrix in Design §B).+2. Every module's list screens are non-empty and detail screens open: Sales (incl. RMA), Purchasing (incl. returns), Production (incl. batches, scrap/rework), Inventory (incl. picking, transfers, counts, tracked-entity states, supersession), Items (incl. taxonomy, revisions), Quality (incl. inspections, gauges, quality docs, risks, NCR depth), Resources (incl. maintenance, training, HR links), People (timecards, holidays), Invoicing (payments, memos, settlement states), Accounting (posted journals, periods, exchange rates, projects, FA lifecycle incl. disposal), Workflows (incl. run history), MES (queue, active work, picking, maintenance, batches, inspection).+3. Posted/partial document states exist with **hand-authored, internally consistent downstream effects** (item ledger, journals, settlements) — same pattern tier 3 already uses for opening stock.+4. All four industries stay in rough volume parity (the existing coverage contract), enforced structurally by required (non-optional) slice fields.+5. Validation: a commit with invalid demo data is blocked with a clear, actionable message — including when the local DB is down (new pure-TS layer).++## Non-goals++- **Files/uploads** (user-excluded): `document*`, storage objects, slide/file attachments. Notes and tags are data, not files — they are IN scope (light).+- Integrations config (`integration`, `companyIntegration`, `webhook`, `apiKey`, `oauth*`), SSO/passkeys/ITAR, notifications, agent threads, implementation hub, saved table views, `printJob`.+- Multi-company / intercompany / consolidation.+- EE-entitlement-authored data: approval rules, enforcement rules, demand/supply forecasts (`demandForecast*` are also wiped as transient; existing `demandProjection` seeding stays).+- Card transactions (Ramp-integration-coupled).+- New CAD models/thumbnails (existing bundled assets stay as-is).+- Derived/deprecated job statuses (`Overdue`, `Due Today`) — deliberate existing exclusion.+- CI enforcement (pre-commit remains the gate; CI was previously declined on cost).++## Design++### A. Engine extensions (tiers + types)++The Dataset stays pure data; every new capability is a tier feature + a slice field. New/changed per tier:++| Tier | Extension |+|---|---|+| 01 foundation | Party currency (`currencyCode` per customer/supplier), per-party payment terms, supplier statuses (Active/Inactive/Pending/Rejected), holidays, equipment (if table is UI-live; verify at plan), employee links for the applying user (`employeeAbility`, `employeeShift`), crews (1), material taxonomy rows (`materialType/Form/Grade/Substance/Finish/Dimension`) + classification on material items, tags |+| 02 items | `itemSupersession` (one live Consume First pair per industry), `customerPartToItem`, `customerItemPriceOverride`(+breaks), `pricingRule`, configuration parameters (+group, one rule) on one configurable item, `methodOperationTool/Parameter` (light), procedure step types extended to the full set the builder supports, item revision statuses (Design/Prototype/Production/Obsolete) via extra revisions of one item |+| 03 inventory | Posted inventory count (+adjustment ledger rows) alongside the Draft one; authorable count lines; tracked-entity states (Reserved via job stays; add On Hold, Rejected, Scrapped); `itemShelfLife` + expiring lots; kanban Make + Transfer cards; `pickingList` (In Progress w/ Pending lines; Completed w/ Picked lines + transfer ledger rows); `stockTransfer` (Draft/Released/Completed); `warehouseTransfer` (Draft/To Ship/Completed + ledger for completed) |+| 04 sales | Full quote/RFQ/SO status matrix; No Quote line + `noQuoteReason`; posted + partial + voided shipments (with Sale ledger rows); sales invoice lifecycle (Submitted/Overdue/Paid/Partially Paid/Voided/Credit Note Issued); `salesReturnOrder` (Draft/To Receive/Completed + credit lines); `salesOrderStatusHistory`; favorites for the applying user; customer portal row if table exists (verify at plan) |+| 05 purchasing | Full PO status matrix incl. Planned/Closed/Rejected/Needs Approval/To Review; Outside Processing PO; posted + partial receipts (+`receiptLineTracking` for batch items, Purchase ledger rows); purchase invoice lifecycle (Open/Overdue/Paid/Partially Paid/Voided/Debit Note Issued); `purchaseReturnOrder` (Draft/To Ship/Completed); supplier-quote status authorable (Draft/Active/Expired/Declined); `purchaseOrderStatusHistory` |+| 06 production | Per-operation status overrides (unlock In Progress/Waiting); scrap + rework `productionQuantity` rows (+ scrapReason); one `jobOperationBatch` (Active); `jobOperationNote`; authorable `deadlineType`; one open production event for the applying user (MES “Active”); quote-line methods (`quoteMakeMethod` fill via copyMethodToQuote analog) — verify feasibility at plan, else record as engine ceiling |+| 07 quality | NCR full depth: authorable type, Closed status, all priorities/sources, tasks (investigation/action/approval/review), associations (supplier, customer, PO line, SO line, tracked entity); `inboundInspection` on the posted receipt (Passed + Failed samples w/ measurements); `itemSamplingPlan` (AQL); `qualityDocument` (Draft/Active/Archived); gauges + calibration records (all calibration statuses); `riskRegister` (all statuses, Risk+Opportunity, varied sources) |+| 08 change orders | Add Start / Engineering Complete / Cancelled statuses; task rows (`changeOrderTaskStatus` variety) if table supports (verify at plan) |+| 09 accounting | Posted + Reversed journals across all five account classes; `accountingPeriod` rows (trailing 12 months; one prior period Locked/Closed + `periodCloseTask` states); `exchangeRate` (+history) for EUR; one EUR-currency supplier PO/invoice (document currency, unpaid); `payment`s (Receipt + Disbursement) + `invoiceSettlement` for Paid/Partially Paid invoices; `memo` (posted credit + debit); projects (2, one linked to a job); `dimensionValue` + `journalLineDimension` (light); FA: add Disposed (+`fixedAssetDisposal`), Units of Production asset + usage log; keep Draft depreciation run, add a Posted one only if postable without the edge path (verify at plan) |+| 10 ops (NEW slice `ops`) | Maintenance: schedules (+items) per work center, dispatches in all 5 statuses × varied severity/source/priority, failure modes, one spare-part issue; training courses (+questions of all 5 types, assignment states for the applying user); timecard entries (past week, applying user); suggestions (2); notes on a job/customer |+| 11 workflows | Seed `workflowRun` + `workflowStepRun` history for the published workflow (Succeeded / Failed / Skipped runs, terminal, `isTest=false`) |+| 12 planning | Silent skips → throws (`need()`); no data change beyond what sales-matrix needs |++Ledger-consistency invariant (new, load-bearing): **on-hand per (item, shelf) derived from all seeded `itemLedger` rows must remain ≥ 0 at every point and end equal to what pickable/genealogy flows assume.** The authoring convention: opening balances stay the baseline; posted receipts add; posted shipments/picks subtract only from items with sufficient opening stock. The pure validator (D) checks the end-state non-negativity per item/shelf from the dataset alone.++### B. Coverage matrix (per dataset — all four industries)++Every enum value marked ✱ is newly reachable. Counts are minimums per dataset.++- salesRfq: Draft✱, Ready for Quote, Quoted, Closed✱ (4)+- quote: Draft✱, Sent, Ordered, Partial✱, Lost✱, Cancelled✱, Expired✱ (7); line statuses all 4 (No Quote✱, In Progress✱, Not Started✱)+- salesOrder: all 11 (Needs Approval✱, Invoiced✱, To Invoice✱ added)+- salesReturnOrder✱: Draft, To Receive, Completed (3)+- shipment: Draft, Posted✱ (one full, one partial✱), Voided✱+- salesInvoice: Draft, Submitted✱, Overdue✱, Paid✱, Partially Paid✱, Voided✱, Credit Note Issued✱+- purchasingRfq: Draft✱, Requested, Closed✱+- supplierQuote: Draft✱, Active, Expired✱, Declined✱+- purchaseOrder: all 10 statuses; types Purchase + Outside Processing✱+- receipt: Draft, Posted✱ (full + partial✱), Voided✱+- purchaseInvoice: Draft, Open✱, Overdue✱, Paid✱, Partially Paid✱, Voided✱, Debit Note Issued✱+- purchaseReturnOrder✱: Draft, To Ship, Completed+- job: all 8 seedable (existing) + deadlineType variety✱; jobOperation: all 7 (In Progress✱, Waiting✱); productionQuantity: Production, Scrap✱, Rework✱; one Active jobOperationBatch✱+- tracked entities: Available, Consumed, Reserved, On Hold✱, Rejected✱, Scrapped✱; expiring lot✱+- pickingList✱: In Progress + Completed; lines Pending/Picked/Short+- stockTransfer✱ / warehouseTransfer✱: 3 states each+- inventoryCount: Draft + Posted✱+- NCR: Registered, In Progress, Closed✱; priorities all 4; sources both; with task/association depth✱+- inboundInspection✱: Passed + Failed samples; qualityDocument✱ ×3 statuses; gauge✱ + calibrations (3 statuses); riskRegister✱ ≥4 rows+- changeOrder: all 6 statuses (Start✱, Engineering Complete✱, Cancelled✱ added)+- fixedAsset: Draft, Active, Fully Depreciated, Disposed✱+- journal: Draft, Posted✱, Reversed✱; accountingPeriod✱ + one closed period✱+- payment✱ ×2 types; memo✱ ×2 directions; exchangeRate✱ EUR+- maintenanceDispatch✱: all 5 statuses; maintenanceSchedule✱ ≥3+- training✱ ≥2 courses; timeCardEntry✱ ≥5; holiday✱ ≥2; employeeAbility/Shift✱ for applying user+- workflowRun✱ ≥3 terminal runs+- itemSupersession✱ 1 live pair; material taxonomy✱ classified materials; item revisions across 4 revision statuses✱++### C. Data integrity strategy++1. **Refs are loud.** Every cross-reference resolved via `need()`; the silent-skip/null-coalesce sites in tiers 01/03/04/06/09/12 (list in validation research) become throws. Genuine authored-optional fields keep `?? null` only where the column is nullable *and* the spec omitted the key on purpose (typed as optional).+2. **Posted docs carry their ledger.** Hand-authored `itemLedger`/`journal`/`invoiceSettlement` rows accompany every posted/paid state, balanced (`assertBalanced`-style check in the validator for journals; non-negative on-hand check for ledgers). GL account resolution stays class-based (extended to all 5 classes).+3. **Sequences respected.** All new readable-id documents go through the existing sequence machinery; insertion order rules (opportunities → statusOrders → releasedOrders) preserved and extended.+4. **Interceptors respected.** New inserts follow the adopt-don't-duplicate pattern (`jobMakeMethod`, `itemCost`) wherever a sync interceptor creates the row.+5. **Wipe compatibility.** All new tables are companyId-scoped → `wipeCompanyBusinessData` discovers them automatically; verify none belong in `PRESERVED_TABLES` (only `period` (global) and bootstrap-owned config do). Re-apply (second template onto same company) must stay clean — covered by acceptance test.+6. **Timezone/dates:** all offsets via `DayOffset` + `resolveDate`; `previousMonthEnd` for period ends; no JS `Date`.++### D. Validation (the commit gate)++1. **New `datasets/validate.ts` — pure, no DB.** Validates each dataset: every string ref resolves within the dataset (items, customers, suppliers, processes, work centers, shelves, warehouses, job keys, SO keys, price-break arity vs `rfqQuantityBreaks`); journal lines balance; end-state on-hand non-negative per item; `promisedDateOffset` within the 48-week horizon; `componentNodeIds` ⊆ bundled `graph.json`; every slice non-empty; supersession pairs reference distinct existing items. Runs (a) first inside `check-datasets.ts` — **before** the DB connection, so a broken dataset blocks the commit even with the DB down; (b) as a vitest suite (`datasets.test.ts`) so `pnpm test` covers it.+2. **`verify.ts` gains row-count floors.** After tiers, assert per-table minimum counts from a small manifest (e.g. `job ≥ 8`, `pickingList ≥ 2`, `nonConformance ≥ 3`…). Catches silent 0-row tiers. Still always rolls back.+3. **Hook semantics unchanged** (trigger path, skip env var, DB-down warning for the DB layer, clear block message). The pure layer never skips.+4. Baselines re-captured (`.ai/runs/`), structural sums extended (add itemLedger sum, journal balance), rule doc + datasets AGENTS.md updated.++## Design Decisions++| # | Decision | Choice | Rationale |+|---|---|---|---|+| 1 | Posted/partial documents | Hand-authored downstream rows in-transaction | Edge functions can't run inside the seed transaction (architectural); tier 3 already sets the precedent; the alternative (post-commit edge calls) breaks all-or-nothing apply and verify rollback |+| 2 | New capability placement | Extend existing slices + one new `ops` slice for tier 10 | Tier 10 was reserved for exactly this (its own comment); keeps tier ordering contract intact |+| 3 | Industry parity | All four datasets get full new data | Volume is the coverage contract; onboarding shows all four; required (non-optional) type fields enforce parity at compile time |+| 4 | Silent skips | Become `need()` throws | A demo dataset is first-party data; a typo should fail the gate, not degrade. Data fixed in same change, so no behavior break |+| 5 | Pure validator placement | `check-datasets.ts` pre-DB + vitest | Closes the "DB down → warn+pass" hole without changing the deliberate DB-layer skip |+| 6 | EE-gated features (approvals, enforcement, forecasts) | Excluded | Seeding data behind an entitlement gate is invisible in community/self-hosted demos; forecasts additionally wiped as transient |+| 7 | Files/documents module | Excluded | Explicit user instruction |+| 8 | Card transactions, intercompany | Excluded | Integration-coupled / multi-company out of scope |+| 9 | Quote-line methods (`quoteMakeMethod` fill) | Attempt; fall back to documented ceiling if job-helper reuse isn't clean | Quote costing screens are a major demo surface, but the helper was built for jobs; plan verifies feasibility first |+| 10 | Workflow run history | Seed terminal runs directly | Rows are read-only history for the UI; engine never re-reads terminal runs |+| 11 | Open MES production event | One open Setup event for the applying user | Makes MES “Active”/timecard live; bounded risk (one row, user can end it) |+| 12 | CI check | Not added | Previously declined on cost; pre-commit + vitest suffice |++## Acceptance criteria++- [x] 1. `pnpm db:check:datasets` passes for all four datasets on a migrated local DB (< ~15s total), and **fails with a named, actionable error** when a ref key is deliberately broken (tested once, then reverted). — *Evidence:* ✓×4 in 3.6s wall (Task 15 re-run, 2026-09-23); broken ref `ST-050-BOGUS` → `✗ satellite … unknown item` exit 1, and floor drill → `pickingList: expected ≥ 3, got 2` exit 1, both in `.ai/runs/2026-09-23-demo-data-verification-drills.txt`.+- [x] 2. Pure validator: `pnpm --filter @carbon/database test` includes dataset validation; breaking a ref fails the test AND blocks `git commit` even with the DB stopped. — *Evidence:* `validate.test.ts` runs `validateDataset` on every key plus negative cases (unknown BOM item, unbalanced journal, …) — 43/43 pass; drills 6a (DB unreachable → exit 1) and 6b (hook run with the broken file staged → "Commit blocked by the demo-dataset check") in the drills file. The broken-ref drill was run through `check-datasets`, not vitest; vitest's ref coverage is the negative cases.+- [x] 3. `pnpm db:seed:dev -- --dataset satellite` (and robotics) completes; the printed row counts match new baselines. — *Evidence:* all four seeded exit 0; row counts captured as `.ai/runs/2026-09-23-seed-baseline-{satellite,robotics,precision,motor}.txt` + `-satellite-structural.txt` (untracked until the user commits).+- [x] 4. Re-apply is clean: applying a second dataset over a seeded company leaves exactly one demo story. — *Evidence:* every baseline header records "re-apply onto scratch company dapnjkh860gjckkl52t0, exit 0"; plan Task 14 records "sat→rob→sat both 229/231 tables = clean apply". Required the `wipe.ts` fixes in Autonomous Decision 15.+- [x] 5. Status-matrix audit lists DISTINCT statuses per document table and matches §B for every ✱ value. — *Evidence:* `.ai/runs/2026-09-23-demo-data-status-audit.txt` — 264 present, 103 absent all classified, 0 open gaps (3 gaps found and fixed, Decision 15).+- [x] 6. Every seeded journal balances; no (item, shelf) on-hand goes negative (validator-enforced). — *Evidence:* `validate.ts` journal-balance and net on-hand checks run on every commit; structural baseline shows JE-SEED-001…005 each with debit − credit = 0.+- [x] 7. `pnpm exec turbo run typecheck --filter=@carbon/database` green; Biome green. — *Evidence:* `pnpm --filter @carbon/database typecheck` exit 0 (Task 15 re-run); Biome 0 errors at Task 14.+- [x] 8. `.claude/rules/onboarding-company-templates.md` + `packages/database/src/datasets/AGENTS.md` updated (new slices, validator, baselines). — *Evidence:* Task 15; also `packages/database/AGENTS.md`, `.claude/rules/workflow-run-history.md`, `docs/content/docs/platform/demo-data.mdx` (+ regenerated agent KB).++## Autonomous Decisions (high-stakes first)++1. **Seeding posted documents with hand-authored ledger/settlement effects** (Decision 1) — bypasses the posting engines; mitigated by balance/non-negativity validation and per-table acceptance checks. *(Rung: codebase precedent — tier 3/tier 6 already write ledger + genealogy rows directly.)*+2. **Scope exclusions** (Decisions 6–8, non-goals list) — narrows "every feature" to features that are demoable in a community, single-company, no-files context. *(Rung: product judgement + user's own "leave out files".)*+3. **Making silent skips throw** (Decision 4) — a behavior change in the shared seed path; safe only because all four data packs are fixed in the same change. *(Rung: user's stated intent — validation must catch invalid data.)*+4. **New required slice/fields → compile-breaking Dataset shape** (Decision 3) — any out-of-tree dataset would break; none exist. *(Rung: codebase precedent — DatasetKey is already a closed union.)*+5. **Pure validator wired before the DB layer in the pre-commit path** (Decision 5) — commits can now be blocked with no DB running, which is precisely the user's requirement. *(Rung: user's stated intent.)*+6. Branch/workflow: work directly on `feat/demo-data-completeness` in this checkout; **no commits without explicit user permission** (standing user rule overrides ship-it's commit steps).+7. Smaller calls: open MES event (D11), workflow run history (D10), quote-methods attempt (D9), notes/tags in scope but light, crews/equipment pending plan-time table verification.+8. **Cluster C4 (Task 6) resolutions:**+ - The no-quote reason column is `salesRfq.noQuoteReasonId` (not quote/quoteLine — `updateSalesRFQStatus` writes it), so it is wired as `SalesRfqSpec.noQuoteReason` on the Closed RFQ that pairs with each dataset's Lost quote; tier 01 now registers `nqr:<name>` refs.+ - `SalesInvoiceSpec.key` is OPTIONAL (`sinv:<key>` in ctx.refs.misc) so the pre-existing Draft invoices stay byte-identical; all six new lifecycle invoices carry keys (C9 settles "paid"/"partial").+ - `SalesReturnSpec.salesOrder` sits at the HEADER (schema: `salesReturnOrder.salesOrderId`; the line-level column is `salesOrderLineId`, which the seed leaves null). `returnReason` is a header field applied to every line's `returnReasonId` (per-line in schema).+ - A Completed RMA mirrors post-receipt's "Sales Return Order" branch fully: a Posted `receipt` (sourceDocument "Sales Return Order") + `receiptLine` rows + one "Positive Adjmt." / "Sales Return Receipt" itemLedger row per line into the line's `toShelf`. `salesReturnOrderCreditLine` is NOT seeded — its `memoId` is NOT NULL, so credit rows cannot precede C9's memos.+ - Posted shipments write `entryType: "Negative Adjmt."` (not "Sale") with documentType "Sales Shipment" — that is what post-shipment actually inserts.+ - Validator: quote lines with status "No Quote" are the one case allowed zero price breaks; REQUIRED_* status-coverage constants exported from validate.ts pin the C4 matrix per dataset ("Pending" shipment/invoice and "Cancelled" RMA are transient/out-of-scope and excluded); net-on-hand check moved below the sales slice so posted shipments/completed returns participate.+ - Conventions (no per-dataset data): status history = Draft→Confirmed→In Progress on the first order with status "In Progress"; quoteFavorite = the Sent quote; salesOrderFavorite = first released order; jobFavorite (tier 06) = the `eventsJobKey` job.++9. **Cluster C5 (Task 7) resolutions:**+ - Posted receipts write `entryType: "Positive Adjmt."` with documentType "Purchase Receipt" — the plan text said entryType "Purchase", but post-receipt's Purchase Order branch actually inserts "Positive Adjmt." (itemLedgerType "Purchase" is the COST ledger's type). Code wins.+ - The batch receipt lot mirrors `update_receipt_line_batch_tracking` + the posting flip: `trackedEntity` with sourceDocument "Item" (NOT "Receipt" — that enum value belongs to inspections/activities), sourceDocumentId = the item, readableId = the lot number, attributes `{"Receipt Line", "Receipt", "Supplier"}`, status "Available" (no Receipt-usage inspection plan is seeded), ledger row stamped with `trackedEntityId`. No `trackedActivity` rows — the minimal coherent shape; tier 06's genealogy owns activities.+ - A Completed purchase return mirrors post-shipment's "Purchase Return Order" branch: a Posted `shipment` (sourceDocument "Purchase Return Order", supplierId set) + `shipmentLine` rows + one "Negative Adjmt." / "Purchase Return Shipment" itemLedger row per line out of the line's fromShelf. `PurchaseReturnSpec.lines[].unitPrice` was added beyond the plan's minimum shape (mirrors SalesReturnLineSpec; a $0 debit basis reads as fake data). No child delivery/payment tables exist for purchaseReturnOrder.+ - OSP POs mirror the `create` edge function's outside-processing branch: an ordinary direct PO with `purchaseOrderType: "Outside Processing"` whose line is the PROCESSED MAKE PART (the jobMakeMethod item) priced at the operation's `operationUnitCost`; `jobId`/`jobOperationId` stay null (jobs are seeded in tier 06, after purchasing). Validator requires the supplier to hold a foundation supplierProcess.+ - FX discipline is validator-pinned: exactly one direct PO carries `currencyCode: "EUR"` (rate 1.08, `exchangeRateUpdatedAt` stamped at the order date the way `insertPurchaseOrder` does), on the C1 EUR supplier, childless, status "To Invoice"/"Draft"; every other PO stays base-currency.+ - Standalone supplier quotes get no `externalLink` — finalize mints that, and none of the Draft/Expired/Declined quotes were finalized. Suppliers must be Active with a supplierContact (the quote row needs contact + supplier-location refs).+ - Purchasing documents may only name Active suppliers (validator-enforced) — the C1 status-showcase suppliers exist for the supplier list, not order flow.+ - Conventions (no per-dataset data): purchaseOrderStatusHistory = Draft→To Review→To Receive on the first direct PO whose receipt posted; timeline rules order ≤ receipt ≤ invoice enforced in the validator; completed purchase returns are dated after the posted inventory count so its snapshot stays the opening balance.+ - Lot-id registry extended: posted receipt lotNumbers join onHandTracked + genealogy inputs + the genealogy assembly serial in one collision check; REQUIRED_PURCHASE_* status sets exported ("Pending" receipt/invoice, "Return" invoice, "Cancelled" return/quote are transient or flow-only and excluded).++10. **Cluster C6 (Task 8) resolutions:**+ - Spec fields address job operations by **1-based position among the job's ROOT operations sorted by `"order"`** (`operationOverrides`, `quantities`, `operationNotes`, `openEvent`, `batch`, `rework`) — robust to methods numbered 10/20/30, and the same key tier 06's existing root-op queries use.+ - `jobOperationNote.note` is **plain TEXT, not TipTap** — the MES operation Chat writes/reads bare strings (`Chat.tsx` renders `{m.note}` in a `<p>`), so the seed authors plain sentences and does NOT use `RICH()`. The plan's "likely TipTap" guess was wrong; code wins.+ - `jobOperationBatch` links members via `jobOperation.jobOperationBatchId` (no child table). Seeded the way the `batch-operations` edge function creates one: readableId from the `jobOperationBatch` sequence (BAT…), processId/workCenterId from the member operation, status "Active", `mergeOutput: false`, then UPDATE the operation. One batch per dataset on the events job's first root op, per the plan.+ - `rework` is fully satisfiable (jobId, quantity, reason, requestedById, target/triggeredAt operation ids) — seeded OPEN (`completedAt` null) with target upstream of the triggering op, mirroring trigger-rework's back-path semantics; validator enforces target ≤ triggeredAt.+ - The picking-list status trigger (`update_picking_list_status`, migration 20260601143527) fires **only on UPDATE of pickingListLine** — seeded INSERTs never recompute the header, so the tier inserts the final header status directly (probe-verified: Completed and In Progress both stick).+ - Picked moves mirror the post-picking edge function byte-for-byte: paired itemLedger rows `entryType "Transfer"`, `documentType "Direct Transfer"`, documentId = pickingList row id, out of the line's `storageUnitId` into `toStorageUnitId`. The lineside destination is the floor storage unit (`isWorkCenterDefault`) of the work center on the job's **first root operation with a work center** (no `toWorkCenter` spec field).+ - `pickingListLine.jobMaterialId` is NOT NULL — lines resolve the job's jobMaterial row by (jobId, itemId), which is why the validator requires each picked item to be a component of the job item's method TREE (recursive walk of `items.methods`).+ - A "No Deadline" job carries **no dueDate** (`dueDateOffset` now optional; validator: required for every other deadlineType, forbidden for "No Deadline"). Deadline spread by status: Draft=No Deadline, Ready=ASAP, Planned=Soft Deadline, rest Hard.+ - `JobSpec.quantities` REPLACES the tier's legacy per-op Production-1 rows for that job (other jobs keep today's behavior); Scrap rows must name a bootstrap scrapReason (Defective/Damaged/Quality — validated against seed.data.ts, resolved by name at runtime and cached in `ctx.refs.misc`, never module scope, which would leak across the drift check's four companies).+ - The open MES event is a Setup `productionEvent` with `endTime: null` for ctx.userId at `resolveTimestamp(anchor, 0, "08:00:00")`, on the op overridden to "In Progress" (validator-pinned to the openEvent order).+ - Net-on-hand ≥ 0 assertion moved BELOW the production slice — completed picking lists now consume from their fromShelf bins.+ - **Quote methods (Decision 9): NOT implemented in C6** per the task directive — feasibility analysis recorded in the run report instead. Short version: feasible; tier 04 quote lines are already `methodType: "Make to Order"` so interceptor-minted root `quoteMakeMethod` rows exist to adopt, and `sync_insert_quote_material_make_method` mints child rows exactly like the job-side interceptor copyMethodToJob already adopts.++11. **Cluster C7 (Task 9) resolutions:**+ - **NCR tasks mirror the `create` edge function's "nonConformanceTasks" case**, not free-standing rows: `nonConformance.requiredActionIds` lists the bootstrap `nonConformanceRequiredAction` ids in order and each becomes a `nonConformanceActionTask` (`actionTypeId`, 1-based `sortOrder`); `approvalRequirements = ["MRB"]` yields one `nonConformanceApprovalTask` plus the **two** reviewer rows the function seeds ("Engineering" + "Quality") — the plan said "1 reviewer", code wins. Validator: a Registered NCR holds only Pending tasks; a Closed NCR none open. "In Progress" tasks/approvals/reviewers are assigned to the applying user (someone owns active work).+ - NCR `type` resolves by name against the company's bootstrap `nonConformanceType` rows (shared cached helper `helpers/bootstrap-lookup.ts`, also used for gauge/CO lookups); omitted = the legacy first-row query, so the pre-C7 NCRs are unchanged. New fields: `description` (+ TipTap `content`, as the edge function derives it), `dueDateOffset`, `closeDateOffset` (required iff Closed).+ - Associations write the exact shapes `insertIssue` / the association modal write: `nonConformanceSupplier` (its `sync_create_nc_external_link` interceptor mints the externalLink — verified), `nonConformancePurchaseOrderLine` (+ PO id/readable id), `nonConformanceCustomer`, `nonConformanceSalesOrderLine` (+ SO id/readable id), `nonConformanceTrackedEntity`, `nonConformanceInspection`. Validator pins the PO's supplier = the NCR's supplier and the SO line's customer = the NCR's customer. New refs: tier 03/05 register `te:<readableId>` (ctx.refs.misc) for every seeded lot; tier 05 registers `poline:<poRef>:<item>` and `rline:<receiptRef>:<item>` (ctx.refs.documents).+ - **Inspection graph is fully seedable without files.** `inspectionSamplingPlan` is NOT an item-level AQL plan (the plan text was stale — `itemSamplingPlan` was dropped 2026-07-26): it is per (inspection lot, inspectionFeature), and features hang off an `inspectionDocument`, whose `storagePath` is nullable — the app's own "new inspection plan" form creates one with no file. So each dataset seeds, mirroring post-receipt: a file-less `inspectionDocument` (AQL default rule, ANSI_Z1_4 / II / Normal) with 2 Measurement `inspectionFeature`s, the Receipt-usage `itemInspectionDocumentAssignment`, the lot `inspection` (plan snapshot resolved by the real `resolveSamplingPlan`), one `inspectionSamplingPlan` per feature, n samples + measurements, and the disposition's `inspectionHistory` row. No balloons (file-bound). Escape hatch not needed.+ - Inspected line must be untracked (Inventory) with a resolved sample size ≤ 5, and the dataset authors EXACTLY n samples; lot status **Partial** (the brief allowed Partial/Failed). **Failed is validator-forbidden**: a rejected untracked lot posts a `post-nonconformance` write-off (itemLedger + GL) the seed does not author. Sample/measurement statuses are derived with the engine's rules (`helpers/inspection.ts` duplicates `valuateMeasurement` — `@carbon/database/quality` imports kysely at runtime) and the validator pins authored sample status = derived. Standard is the company default ANSI_Z1_4.+ - **Gauge calibration status lives on `gauge`** (`gaugeCalibrationStatus` + `lastCalibrationStatus`, last/next dates); `gaugeCalibrationRecord` carries Pass/Fail (`inspectionStatus`). The tier replays records the way `upsertGaugeCalibrationRecord` does (no records ⇒ Pending; latest Pass ⇒ In-Calibration; latest Fail ⇒ Out-of-Calibration; next = last + interval months via CalendarDate). A gauge ending Out-of-Calibration also gets `lastCalibrationStatus` Out-of-Calibration — the state the nightly cleanup leaves after notifying — so a fresh demo company fires no stale alert. Story: Active Master (2 Pass), Active Standard never calibrated (Pending), Inactive Standard retired after a Fail (the `gauges` view also shows Inactive as Out-of-Calibration).+ - `riskRegister` links follow each entity's `RiskRegisterCard`: `sourceId` = customer/supplier/item/job/work-center id; Item risks also set `itemId`, Job risks set `itemId` = the job's item; General has neither. Five risks per dataset cover all five statuses and sources Customer/Supplier/Item/Job/General, with the General one an Opportunity.+ - Quality documents: an Archived v1 + Active v2 of the same name (the archive-on-activate interceptor fires on UPDATE only, so inserting both is stable) + a Draft v0 of another document; the Active one has Checkbox/List/Measurement steps (Measurement steps require a bootstrap UoM — schema CHECK). No File steps.+ - `nonConformanceWorkflow` skipped (out of scope per plan; no need for a workflow link to demo NCR depth).+12. **Cluster C8 (Task 10) resolutions:**+ - The three new notices (Start / Engineering Complete / Cancelled) carry **no affected items**: every change type (Version/Revision/New Part/Replacement Part) spins or re-points a method draft in the app, and the status route has no affected-item gate, so a lifecycle-only notice is a legal, realistic state and keeps structural sums untouched. `ChangeOrderSpec.affectedItems` stays required (authored `[]`).+ - New optional fields: `changeOrderType` (bootstrap name → `changeOrderTypeId`), `priority`, `dueDateOffset`, `reasonForChange` (TipTap), `nonConformance` (NCR ref → `changeOrder.nonConformanceId`; the Engineering Complete notice links the external supplier NCR), `actionTasks`. Tasks mirror `setChangeNoticeActionTasks`: `actionTypeId` + the template's `name`, 1-based `sortOrder`; `changeOrder.requiredActionIds` is not written (the app derives the selection from the tasks).+ - Validator pins all six changeOrder statuses AND all four `changeOrderTaskStatus` values per dataset.+13. **Cluster C9 (Task 11) resolutions:**+ - **Payments mirror post-payment with accounting disabled**: Posted `payment` (USD, rate 1, `bankAccount` = `accountDefault.bankCashAccount`, `journalId` NULL) + `invoiceSettlement` rows with `appliedAmount` (base) = `sourceAmount` (principal), rates 1, fx 0, `sourcePaymentId` NULL. No payment/memo journals: posting journals needs the invoices' own AR/AP control lines (post-payment reads them), and the C4/C5 invoices were seeded without GL — a lone payment journal would unbalance the subledger tie-out. There is no payment-line/allocation table; settlements ARE the allocation.+ - **Invoice views derive status/balance from settlements** (`salesInvoices`/`purchaseInvoices`, migration 20260916143022): Σ `COALESCE(sourceAmount, appliedAmount)` over Posted payments/memos vs the LINE total. Base status "Paid" forces balance 0; "Partially Paid" / Credit/Debit Note Issued show total − settled. Probe-verified per dataset. The validator pins it: Paid and Credit/Debit Note Issued fully settled, Partially Paid strictly between with a pre-today payment, every other status unsettled (else the view would re-derive it).+ - **Memos have no invoice column**: the tie is `memo.reference` = the invoice readable id plus a credit application carried by a zero-cash Posted payment (`invoiceSettlement.memoId` + `appliedViaPaymentId`, the `applyCreditsToInvoices` shape; `payment_totalAmount_check` allows 0). Without it the AR/AP aging (excludes only Draft/Pending/Voided) would double-count the invoice and the unapplied memo. Each memo credits its invoice in full; `reasonAccount` = what post-memo stamps with no return order (salesDiscountAccount / supplierPaymentDiscountAccount). So each dataset has 6 payments: paid + partial per side, plus one credit application per side.+ - **Exchange rates → `exchangeRateOverride`, not `exchangeRate`**: `exchangeRate` is the platform-GLOBAL market-rate store (no companyId, service-role writes, every tenant reads it); a tenant template writing it would leak fake rates to all companies. No `exchangeRateHistory` table exists. Seeded one company-scoped EUR override at 1.0852 — same direction as the C5 EUR PO's 1.08 snapshot (EUR per USD, the document convention); validator requires ±5% of the PO rate. The "3 history points" are dropped (no company-scoped history exists). Note for review: 1.08 EUR/USD is the inverse of the real-world ~0.92 — a C5 data choice this cluster follows for consistency.+ - **Periods**: 12 trailing monthly `accountingPeriod` rows (anchor month back 11), `(fiscalYear, periodNumber)` computed from `fiscalYearSettings.startMonth` exactly like `resolveAccountingPeriod`, upserted on that unique key. Months −11/−10 Closed (sequential close), −9 Locked, rest Open, anchor month Active; lock/close stamps set. Periods are seeded BEFORE journals so `journal_check_period_open` vets every seeded posting date. Proven bounds (checked over 8 years of anchors): offsets ≥ −273 never land in a Closed month (existing Draft JE at −256 is safe), ≥ −242 always land in an Open one — validator enforces −273 for Draft journals and −242 for posted journals/payments/memos/disposals.+ - **Journals keep `accountingPeriodId` NULL**: journal/journalLine survive the dataset wipe but accountingPeriod does not, and the wipe's FK-nulling pass would UPDATE a Posted journal — which `journal_posted_immutable` rejects. The period trigger resolves a NULL period from postingDate.+ - **Journal lines name an account by bootstrap CoA number** (`account: "6060"`) or, for the legacy line form, by class (first account of the class by number — the original revenue entry is byte-identical). New per dataset: payroll accrual (6060 / 2150), license amortization (6310 / contra 1420 credit, negative), and a Reversed pair mirroring `reverseJournalEntry` (original inserted Posted then flipped Posted→Reversed with `reversedById`, the one UPDATE the immutability trigger allows; reversal Posted with `reversalOfId` and negated lines, sourceType Manual). The amortization targets an intangible, not a registered fixed asset, so it cannot contradict the Draft depreciation run.+ - **Projects link via `purchaseInvoiceLine.projectId`** — `job` has no projectId column (only `purchaseInvoiceLine` and `cardTransactionLine` carry project coding). One project per dataset codes the paid purchase invoice's first line.+ - **Dimensions**: bootstrap seeds no Custom dimension, so each dataset creates one (Mission Phase / Product Line / Work Cell / Motor Family) with 2 values; dimension/dimensionValue are companyGroup-scoped (never wiped) so the tier looks up before inserting. The payroll accrual's expense line carries TWO `journalLineDimension` tags: the bootstrap entity-backed **Project** dimension (valueId = project id, as post-card-transaction writes it) and the custom value. Tags re-attach on re-apply (journalLineDimension IS wiped while journals are not), found by a unique `journalLineReference`.+ - **Close checklist**: 3 `periodCloseTask` rows on the Locked period (Done / Skipped+reason / Open), snapshotted from the bootstrap definitions like `getPeriodCloseChecklist`; the other definitions materialize lazily on first view (unique key makes that idempotent).+ - **Fixed assets**: one Disposed (Sale) asset per dataset with `fixedAssetDisposal` (NBV = cost − accumulated, gainLoss = proceeds − NBV, journalId NULL) — two gains, two losses across datasets; one Units of Production asset with 2 monthly `fixedAssetUsageLog` rows. Its run line is exactly what `buildDepreciationLines` computes from the log whose `periodEnd` equals the run's (monthsBack 1); the older month's usage is its opening accumulated depreciation. Validator recomputes the UoP charge. Existing assets insert the identical column set (new columns are undefined → dropped).++14. **Cluster C10 (Task 12) resolutions:**+ - **Notes hang on the person, not a job/customer.** The `note` table is read by exactly one screen: `getNotes(client, documentId)` (`apps/erp/app/modules/shared/shared.service.ts`) called from `x+/person+/$personId.notes.tsx`. A note keyed to a job or customer id would be written and never shown, so both seeded notes use `documentId = ctx.userId` and render on the demo user's Notes tab. *(Rung: codebase precedent — overrides the plan's "one job, one customer".)*+ - **Spare-part issue mirrors `issue` → `maintenanceDispatchInventory`** (`supabase/functions/issue/index.ts`): a `maintenanceDispatchItem` plus an itemLedger row `entryType "Consumption"`, `documentType "Maintenance Consumption"`, `documentId` = dispatch, `documentLineId` = the item line, negative quantity. The plan guessed `Negative Adjmt.`; the code wins. Untracked consumables only (tracked items need per-entity consumption). Each Completed dispatch issues its dataset's grease/fluid (satellite CN-GREASE-001 ×2 @ A1-L3, robotics CN-GREASE-EP ×2 @ A1-L2, precision CN-COOLANT-55 ×1 @ B3-L1, motor CN-BRG-GREASE ×2 @ A2-L2), and the validator counts that draw in the same per-(item, shelf) on-hand balance as every other cluster.+ - **A Skipped run has no step rows and no `startedAt`.** A run-level Skip only happens at the engine's `load` step (unpublished / not entitled) via `finishRun` (`packages/jobs/src/workflows/engine/log.ts`), which sets `status`, `statusReason`, `completedAt`, `durationMs` — `claimRun` never ran, so no `startedAt` and no trigger step. Succeeded/Failed runs carry the trigger step (sequence 0, Succeeded) plus the `action_assign` step. The Failed step's error is the update action's real message (`actions/update.ts`: "The assignee you chose is not in this company."); the Skipped reason is the engine's `UNPUBLISHED` constant. Note for Task 15: `.claude/rules/workflow-run-history.md` says Skipped runs never set `completedAt` — false for load-time skips.+ - **Runs fire on their sales order's order date** (`salesOrder.created`): each dataset's three runs target the To Ship (−14), To Invoice (−28) and To Ship and Invoice (−21) released orders. Validator requires `at.offset` ≥ the order's `orderDateOffset` and < 0.+ - **Volume**: 5 schedules (one per frequency), 5 dispatches (one per status, together covering every severity/priority/source/OEE impact; the Non-Conformance one links an existing NCR — satellite `ncr:txrx-tvac`, robotics `ncr:drive-fault`, precision `ncr:bore`, motor `ncr:fan-noise`), 3 trainings (Active "Once" with all five question types + a Completed assignment, Active "Annual" with a Pending assignment, Draft), 6 timecards over days −5…−1 (lunch split on −1), 2 suggestions, 2 notes. A completion is only authored on a "Once" training: a recurring one counts only when its period is the current one, which a day offset cannot guarantee.+ - **Validator (`validateOps`)** pins: ≥3 schedules over ≥3 frequencies; the full dispatch status/severity/source/OEE sets; Scheduled ⇔ schedule on the same work center; Non-Conformance ⇔ a known NCR; bootstrap failure modes; actualStart/actualEnd/spare parts/actualFailureMode only in the statuses that stamp them; chronology; Active + Draft trainings, one Active training covering all five `trainingQuestionType`s, ≥1 Completed + ≥1 Pending assignment; ≥5 timecards inside −7…−1 with no overlaps; ≥2 suggestions (ERP `/x/` paths) and notes; runs Succeeded/Failed/Skipped present, workflow published, step nodeIds ⊆ the definition's non-trigger node ids, Skipped ⇔ no steps ⇔ statusReason.++15. **Tasks 13–14 (floors + full verification) resolutions:**+ - **Row-count floors** (`datasets/coverage.ts`, checked in `verify.ts` before the ROLLBACK, one UNION ALL query, every shortfall listed as `table: expected ≥ N, got M`). The table list was MEASURED, not grepped: rolled-back runs counted every companyId table after bootstrap and again after the tiers for all four datasets — 210 tables grow in every dataset (208 companyId tables — direct inserts plus interceptor rows such as itemCost / jobMakeMethod / quoteMakeMethod / jobOperationStep — and the 2 group-scoped dimension tables), plus the three user-scoped favorites = 213 floors. Floor = the smallest count any dataset produced; volume tables (smallest ≥ 20) get floor(min × 0.8). Counts are absolute, so bootstrap rows are included for group / location / eventSystemSubscription / dimension. **Scoping:** `dimension`/`dimensionValue` are counted by the scratch company's `companyGroupId` rather than excluded — the drift check mints a fresh group per run, so the count is exact, and the custom dimension is a C9 deliverable worth guarding; `jobFavorite`/`quoteFavorite`/`salesOrderFavorite` (no companyId) are counted through their parent document; the global `period` table is skipped. The check-datasets failure advice now names the floors. *(Rung: plan Task 13 + codebase precedent — `assertWipeClean`'s UNION ALL.)*+ - **Three §B gaps found by the status audit and fixed in all four datasets:** (1) `purchasingRfq` Draft + Closed — new `purchasing.lifecycleRfqs`; Closed mirrors the app's cancel action (`purchasing-rfq+/$rfqId.cancel.tsx`: Closed, assignee cleared) taken before quotes were requested, so there are no supplier quotes to cancel. (2) `trackedEntity` Scrapped — Task 5 had dropped it with only a validator comment ("would need a paired scrap ledger row from a job"), which ground rule 9 forbids; it now mirrors post-inventory-adjustment's full-entity Scrap (entity Scrapped and keeps its quantity, a "Scrap" trackedActivity + input, a "Negative Adjmt." / "Scrap" itemLedger row carrying `scrapReasonId`), with the shelf's opening stock raised by the lot so available stock is unchanged; no GL, like every other seeded inventory posting. (3) `itemRevisionStatus` Prototype + Production — Task 4 assumed the ladder item's active revision was "Production-equivalent", but the column defaults to Design; tier 02 now promotes it to Production (the released revision — an app-level BOM/BOP lock in `items.server.ts`, no DB trigger, and no change order edits the ladder items) and every ladder's next rung is Prototype. Validator pins all three (`REQUIRED_PURCHASING_RFQ_STATUSES`, `REQUIRED_TRACKED_ENTITY_STATUSES`, a Prototype-rung rule) with five new vitest cases. Every other absent enum value is classified, with a citation, in `.ai/runs/2026-09-23-demo-data-status-audit.txt` — notably a Completed RMA whose lines keep disposition Pending is a real app state (`setSalesReturnOrderLineDisposition`: post-receipt auto-completes the RMA and disposition is a post-receipt decision).+ - **Re-apply was broken by this branch's lifecycle data** (found by the Task 14 re-apply step): the wipe could not clear a company holding the demo's posted documents. Fixed in `wipe.ts`, all inside the one apply transaction: (a) the `prevent_posted_{sales,purchase}_invoice_deletion` sync interceptors refuse deleting any non-Draft invoice and run even under `app.sync_in_progress`, so the wipe first returns the company's invoices to Draft — a re-seed clear, not an app-level delete of a posted document; (b) `invoiceSettlement` holds ON DELETE RESTRICT FKs to its target invoice/memo, so it is deleted before the invoice headers; (c) `payment` and `memo` carry a customer-XOR-supplier CHECK that the FK-nulling pass would break, so they are deleted with the settlements. `session_replication_role = 'replica'` (the restore wipe's approach) was rejected: it needs superuser, and this wipe also runs in the hosted `company-template` job. *(Rung: spec §C5 — re-apply must stay clean; acceptance #4.)*+ - **Pre-existing leak fixed on the same path:** the customer/supplier interceptors mint one `group` per partner (org groups, id = the partner id) and per customer/supplier type, and nothing deletes them; `group` is preserved, so every re-apply left ~25 orphan groups named after the previous story's partners in the group pickers. The wipe now deletes org/type groups whose owner is gone, keeping bootstrap's "All Customers"/"All Suppliers" roots by their `getGroupId` id; employee-type groups are untouched.+ - **Documented, deliberately unchanged:** `journal`/`journalLine` survive the wipe (posted immutability), and tier 09 adopts `JE-SEED-00x` by `journalEntryId`, so after a cross-dataset re-apply the FIRST dataset's journal text remains (verified: robotics over satellite kept the five satellite entries); `dimension`/`dimensionValue` are companyGroup-scoped and a company wipe must never delete them (sibling companies share them), so each distinct dataset applied adds its own name-keyed custom dimension — bounded at one per dataset.+ - **Baseline method notes:** the 2026-08-13 structural file's methodOperation columns are (laborTime, setupTime, machineTime) — its 263.75 | 0 | 0 matches laborTime exactly; the journal balance metric is natural-balance signed (`lib/utils.ts` debit/credit: asset/expense debit = +, liability/equity/revenue credit = +), so a raw Σ`amount` is non-zero by design and the per-journal debit-minus-credit is what must be 0.++## Open Questions (audit trail — all resolved autonomously)++- [x] How can posted/paid states exist without edge functions? — **Autonomous:** hand-authored downstream rows (Decision 1).+- [x] One flagship dataset or all four? — **Autonomous:** all four (Decision 3).+- [x] Where do maintenance/HR/training live? — **Autonomous:** new `ops` slice, tier 10 (Decision 2).+- [x] Should validation fail when the DB is down? — **Autonomous:** the new pure layer always runs; the DB layer keeps its deliberate skip (Decision 5).+- [x] EE-gated demo data? — **Autonomous:** excluded (Decision 6).+- [x] Row-count regression guard? — **Autonomous:** verify.ts floors manifest + baselines (§D2).+- [x] Quote costing methods? — **Autonomous:** attempt with fallback (Decision 9).+- [x] What does "leave out files" exclude exactly? — **Autonomous:** the Documents module + any storage uploads; notes/tags stay (they are rows, not files).++## Changelog++- 2026-09-22: Spec written (autonomous mode, per user instruction); proceeds directly to plan.+- 2026-09-23: Tasks 13–14 — row-count floors, status audit (3 gaps fixed), re-apply repaired, baselines re-captured (Autonomous Decision 15).+- 2026-09-23: Task 15 — docs synced (onboarding rule: 12 slices, two-layer drift check, wipe pre-steps, new "Posted documents" section, new baselines; datasets + database AGENTS.md; workflow-run-history `completedAt` claim corrected; user docs + agent KB). Status → Implemented. The tier 07 NCR job-operation `continue` flagged during docs review was converted to a named `Seed:` throw (orchestrator), consistent with Decision 4.++### §13a Correction after C9 review (orchestrator)+- **EUR rate direction fixed.** C5 seeded the EUR PO at `exchangeRate: 1.08` and C9 pinned the override at 1.0852 to match. Both columns are "units of the foreign currency per 1 unit of base" (`exchangeRateOverride` migration comment; `toBaseAmount(documentAmount, foreignPerBaseRate)` divides), so 1.08 meant 1 USD = 1.08 EUR — inverted. Changed to PO 0.92 / override 0.9215 in all four datasets, and the validator now fails any EUR rate outside (0.5, 1) with an "is it inverted?" message. *(Rung: codebase precedent — the precision rule and the migration define the direction.)*diff --git a/.ai/specs/2026-09-23-demo-data-screen-coverage.md b/.ai/specs/2026-09-23-demo-data-screen-coverage.mdnew file mode 100644index 0000000000..de35e7ce7c--- /dev/null+++ b/.ai/specs/2026-09-23-demo-data-screen-coverage.md@@ -0,0 +1,233 @@+# Demo Data Screen Coverage — every screen renders, every engine has run++**Status:** Implemented (autonomous, uncommitted — awaiting the user's commit) · **Date:** 2026-09-23 · **Branch:** `feat/demo-data-completeness`+**Follows:** `.ai/specs/2026-09-22-demo-data-completeness.md` (status-matrix pass, committed as `bfdfc1de02` + `3f682e8aca`).+**Research:** `.ai/research/2026-09-23-screen-audit-erp-commercial.md`, `.ai/research/2026-09-23-screen-audit-erp-operations.md`, `.ai/research/2026-09-23-screen-audit-mes-quality-resources.md`, `.ai/research/2026-09-23-screen-audit-erp-settings-people.md`, `.ai/research/2026-09-23-planning-engine-seeding.md`++## Reading of the request (autonomous mode)++**What:** after applying any of the four demo datasets, every ERP and MES screen a user can open shows meaningful, editable data — not just "every status appears somewhere". **Why:** the user opened the app and found whole screens empty (customer portals, sales rules, MES schedule, Production › Forecast / Priorities, resource and material planning) and only 8 jobs; the previous pass verified status coverage, never screens. **Where:** the dataset engine + data packs, the dataset wipe, a post-commit planning step (MRP + scheduler) for the two callers that commit (template job, dev CLI), and the commit gate. **Who:** anyone applying a demo template (onboarding, Settings › Demo Data, `pnpm db:seed:dev`). Constraints carried over: files excluded, FK integrity, no regressions, invalid demo data blocks the commit, autonomous mode, never commit without asking, never rebuild the DB.++## Goals++1. Every screen classified EMPTY or FILTERED-EMPTY in the five research audits renders rows after a real apply of each dataset, except the documented exclusions (Non-goals).+2. Planning screens are populated by the **real engines**: MRP (`runMrp`) and the scheduler (`runLocationSchedule`) run once, post-commit, after every template apply and every dev-CLI seed.+3. The shop floor looks alive: ≥ 18 jobs per dataset with open work due within −3…+21 days of today, spread over every work center, with priorities, assignees, running production events and recent completions.+4. Three pre-existing apply failures on used companies are fixed (intercompany partners, posted card transactions, model-only step slides); the accounting-period fix stays.+5. Every new shape is pinned by `validateDataset`, `REQUIRED_*` sets and `COVERAGE_FLOORS`, so a regression blocks the commit.++## Non-goals++- **Files** (user-excluded): documents, logos, backups, attachments, inspection-plan drawings/balloons, step-slide images.+- **New global `user` rows** (synthetic employees / console operators / portal accounts) — see Autonomous Decision H3.+- **Audit log** — needs a per-company DDL table (`create_audit_log_table`) the wipe cannot manage.+- **API keys** — a fake hash would be a non-working credential in a security screen.+- Integrations, SSO, billing, subsidiaries/ITAR (env- or credential-gated); home "recents" (browser localStorage).+- Real intercompany / card-transaction data (integration-coupled) — the wipe now refuses such companies instead.+- Changing app code to make empty-by-design defaults nicer (e.g. maintenance lists defaulting to the first location) — seed around it.++## Design++### A. Wipe (applies to all callers)++| Case | Behaviour |+|---|---|+| `accountingPeriod` (done, uncommitted) | preserved; tier 09 adopts a month's existing period by `(fiscalYear, periodNumber)`, else by `startDate` |+| model-only step slides | `assemblyInstructionStepSlide`, `methodOperationStepSlide`, `jobOperationStepSlide`, `quoteOperationStepSlide` deleted before the FK-nulling pass (their content CHECK cannot survive it), like `TRANSIENT_MRP_TABLES` |+| intercompany customers/suppliers (`intercompanyCompanyId` set) | refuse up front, before any write: "This company trades with other companies in its group … demo data can only be applied to a company without intercompany partners." |+| Posted/Voided `cardTransaction` | refuse up front: "This company has posted card transactions, which cannot be deleted …" |++Refusals are thrown as a named `Seed:` error from a `preflight` inside `wipeCompanyBusinessData`, so the template job's marker gets `failed` + the message and nothing is written.++### B. Seed data + tier extensions (all four datasets)++Grouped by screen. "Tier" = engine shape to add; everything else is data in `data/<key>/`.++**B1 Production floor (tier 06, production.ts)**+- Open jobs re-dated to due −3…+21 (existing open jobs moved; validator chronology kept).+- ≥ 10 additional released jobs (Ready/In Progress) of short-routing items per dataset, touching every work center; 1 released job with no due date (Priorities › Unscheduled); 2 make-to-stock jobs (`salesOrderId` NULL).+- Distinct `job.priority`; `job.assignee` / `jobOperation.assignee` = applying user on ~6 open items.+- 3 jobs Completed within the last 3–25 days with Setup/Labor/Machine `productionEvent`s (completion-time + estimates-vs-actuals KPIs); open events (`endTime` NULL) today on 3–4 work centers.+- `jobOperationStepRecord` for done ops; `jobOperationParameter` / `jobOperationTool` on a few ops; one Final Inspection op `operationType='Inspection'` + `inspectionDocumentId`; ROB-style assembly op linked to the seeded assembly instruction (`methodOperation`/`jobOperation.assemblyInstructionId`).+- One batchable process; an Active `jobOperationBatch` with ≥ 2 members from different jobs.+- Procedures: one Active, one Archived, rest Draft (versions); make methods of seeded items Active; assembly instruction published state.+- `pickMethod` default shelf per stocked item at the plant.++**B2 Planning (tier 12 + post-commit step)**+- Engines run post-commit (Section C) → `demandActual/Forecast/supplyActual/Forecast`, `capacityReservation`, op start/due dates, dependencies.+- `peopleAssignment` for the current week and a `peopleAbsence`; shifts created at the **plant** (not HQ) + `workCenterShift` links; the applying user's `employeeJob` upserted (it is a silent no-op today when missing) with location = plant, title, department, shift, start date.++**B3 Sales & purchasing (tiers 02, 04, 05)**+- `enforcementRule` family `sales` (item-targeted, warn + error) with item assignments; family `storage` and a work-center rule with assignments.+- Customer portals: `externalLink` documentType `Customer` for 2 customers.+- `approvalRule` (PO tiers + supplier) and Pending `approvalRequest`s for the Needs-Approval PO and the Pending supplier.+- Quote methods: each Make-to-Order quote line gets its item's method copied (`quoteMakeMethod`/`quoteMaterial`/`quoteOperation`) — reverses 2026-09-22 Decision 9.+- Configurator: one configurable item `requiresConfiguration=true`, a `configurationRule`, one configured quote line.+- `assignee` on a few open quotes/SOs/POs/RFQs; supplier `status` on every supplier; `createdAt` spread over past offsets for quotes/RFQs/supplier quotes; 2 more pricing rules; customer/supplier bank accounts if the table is tenant data.+- Return orders: memos linked (`salesReturnOrderId`/`purchaseReturnOrderId`) with credit lines; `nonConformance{Sales,Purchase}ReturnOrderLine`.++**B4 Invoicing & accounting (tiers 04, 05, 09)**+- `postingDate` = `dateIssued` on every non-Draft invoice (fills Receivables/Payables/aging).+- Posted journals shaped like the posting paths: `Sales Invoice` (AR/Revenue), `Purchase Invoice` (Inventory|Expense/AP), `Payment` (Cash vs AR/AP, `payment.journalId` set), plus one `Opening Balance`, with `accountingPeriodId` set (periods now survive the wipe). Aging spread over Current / 1–30 / 31–60 / 61–90.+- Draft Receipt + Draft Disbursement payments (apply UI).+- `costLedger` rows paired with posted receipt/shipment ledger rows; `itemCost.unitCost` non-zero.+- AR/AP billing-address rows.++**B5 Quality, maintenance, resources (tiers 07, 10)**+- `nonConformanceWorkflow` ×3 linked from NCRs; `nonConformanceItem` on every NCR; NCR `assignee`; `nonConformanceSupplier` on a supplier NCR; `nonConformanceActionProcess`; `procedureParameter`.+- `QualityData.inspection` becomes a list: Passed receipt lot, Pending lot, Job Operation lot.+- Maintenance: `maintenanceDispatchItem.unitCost`; a Reactive dispatch on a production-event day; 2 back-dated Completed dispatches; a Scheduled dispatch due today; an In Progress + Down dispatch; `workCenterReplacementPart`; one HQ work center with a dispatch + schedule.+- `partner` rows.++**B6 Settings & people (tiers 01, 10)**+- `companySettings.timeCardEnabled = true` + one open time-card entry today.+- `userAttributeCategory` → `userAttribute` → `userAttributeValue` for the applying user.+- `itemSerialSequence` per serial-tracked item; 3 `customField`s; `printJob` history. ~~one `active=false` webhook~~ — dropped (D66).++### C. Post-commit planning step++`planDemoCompany({ companyId, userId })` in `@carbon/jobs` (which already depends on `@carbon/planning`): `runMrp(serviceRole, db, { type: "company", … })`, then `runLocationSchedule` for every location with Ready/In Progress/Paused jobs — the same calls the cron and `api+/schedule.ts` make. Callers:+- `companyTemplateFunction`: a new `step.run("plan-template")` after `apply-template`, **non-fatal** (logs + `metadata.planningError`; the 3-hourly MRP cron is the backstop). Revert/finalize unchanged.+- Dev CLI: `seed-dev.ts` (in `@carbon/database`, which cannot import `@carbon/planning` — cycle) spawns `pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id>` after its commit; failure prints a warning and exits 0. `--skip-plan` opts out.++### D. Checks++- `validate.ts`: refs for every new slice field; `REQUIRED_*` for procedure (Draft/Active/Archived), approval request, enforcement-rule family, inspection status list, dispatch shapes; floor rules for "open job due within window", "every work center has open ops", "≥ 18 jobs".+- `coverage.ts`: re-measured floors for every newly written table. Engine outputs (MRP tables, `capacityReservation`) stay OUT of floors (verify.ts rolls back before engines run) and are covered by the screen matrix instead.+- Screen matrix: a script (scratchpad; evidence in `.ai/runs/`) that, against a real seeded + planned company, runs one count query per screen data source with the screen's own filters (from the audits) and asserts non-zero for every in-scope screen, for all four datasets.++## Design Decisions++| # | Decision | Rationale |+|---|---|---|+| 1 | Engines run post-commit, in-process, non-fatal | real engine output, zero drift; in-transaction run impossible (PostgREST reads + own transactions — research §3a) |+| 2 | Wipe refuses IC partners and posted card transactions | both are immutable by trigger and FK-linked to rows the wipe must delete; preserving them cannot satisfy the trigger |+| 3 | Slides deleted before FK nulling | CHECK `imagePath OR modelUploadId` cannot survive nulling; the slide is business data the wipe deletes anyway |+| 4 | No new global `user` rows | tenancy + identity safety (H3) |+| 5 | Journals authored for posted docs | Revenue/AR/AP would otherwise read $0 on every financial report |+| 6 | Dates stay `DayOffset`; engine output uses the engine's own clock | engines run "now"; seed anchor is "today" — same day |+| 7 | Shifts move to the plant | every work center is at the plant; scheduler + resource planning read plant shifts |++## Acceptance criteria++1. For each dataset, after `pnpm db:seed:dev -- --email [email protected] --dataset <key>` (engines included), the screen matrix reports 0 in-scope screens with 0 rows; evidence `.ai/runs/2026-09-2x-screen-matrix-<key>.txt`.+2. MES operations board for the applying user shows ops on every plant work center, with start dates within ±3 weeks and ≥ 1 running op on 3+ work centers.+3. Production › Priorities shows jobs in the current week and ≥ 1 Unscheduled job; Scheduling › Forecast and Resource Planning show reservations/assignments; both Material Planning screens show week columns with demand.+4. Sales rules, storage rules, customer portals, approval rules, procedures (Active + Archived), configurator all list rows.+5. Income statement revenue ≠ 0; receivables aging has rows in ≥ 3 buckets.+6. The four wipe cases in §A behave as specified in a rolled-back apply against a company constructed in each state.+7. `pnpm --filter @carbon/database typecheck`, `test`, `pnpm db:check:datasets` (all four), `turbo typecheck` for `@carbon/jobs` pass; a real re-apply over a seeded company exits 0.+8. A deliberately broken new ref / removed required status blocks `sh .husky/pre-commit`.++## Autonomous Decisions (high-stakes first)++- **H1 — Reverses 2026-09-22 non-goals.** Approval rules, enforcement rules, demand/supply forecasts, `printJob` and a webhook were out of scope; the user's report puts them in. — **Autonomous:** in scope — rung 1 (user's stated intent: "every feature visible").+- **H2 — Engines outside the all-or-nothing apply (public behaviour of the template job).** Options: (a) run in-transaction (impossible, research §3a), (b) hand-author MRP/scheduler output (drift from the real engine), (c) run post-commit non-fatal. — **Autonomous:** (c) — rung 2 (the cron and `api+/schedule.ts` already run the same functions after commit) + rung 5 (real numbers beat plausible ones). Consequence: a planning failure leaves a seeded but unplanned company, healed by the cron.+- **H3 — No synthetic people (narrows the ask).** Options: create `user`+`employee` rows per template (global identity table, unique emails, the company wipe cannot remove them, rows accumulate per apply, they can never log in) vs keep the applying user as the only person. — **Autonomous:** no new `user` rows — rung 5 (tenancy/identity safety outweighs a longer People list). People screens render the applying user fully (job, shift, attributes, timecards, assignments).+- **H4 — Wipe refuses two company states (public contract of apply).** Options: preserve, refuse, or force-delete. Force-delete breaks immutability triggers; preserving fails the FK-nulling UPDATE. — **Autonomous:** refuse with a clear message — rung 5 (reversible, no data loss; demo templates target fresh/test companies).+- **H5 — Journals for posted documents (accounting shape).** Options: leave GL empty (Revenue $0), author journals shaped like the posting paths, or run posting functions (impossible in-transaction). — **Autonomous:** author them, `payment.journalId` set — rung 2 (tier 09 already hand-authors posted journals in the posting shape). Changes the prior "payments carry `journalId` NULL / accounting disabled" convention; the rule doc is updated.+- **H6 — Quote methods now seeded** (reverses 2026-09-22 Decision 9). — **Autonomous:** copy item methods into quotes — rung 1 (quote BoM/BoP tabs are screens the user can open).+- D7 — Audit log, API keys, documents stay excluded — rung 5 (DDL per company / credential / files).+- D8 — Dev CLI reaches the engines by spawning a `@carbon/jobs` script, not importing — rung 2 (package graph: `@carbon/planning` → `@carbon/database`).+- D9 — Engine tables stay out of `COVERAGE_FLOORS`; covered by the screen matrix — rung 5 (verify.ts cannot run engines inside its rollback).+- D10 — Shifts move to the plant; HQ gets one work center + maintenance so location-defaulted lists aren't empty — rung 5.+- D11 — Volume: ≥ 18 jobs per dataset (today 8) — rung 4 (research §5.2 load per work center).+- D12 — Task 2: `plan-company.ts` loads `demo-planning.ts` through `createRequire`, so tsx compiles the graph as CJS; as ESM, `@carbon/planning`'s named imports from `@carbon/database` (no `"type":"module"`) fail to link (`SyntaxError … supersession-pick does not provide an export named buildConsumeFirstHops`, reproduced). Rejected: adding a `jiti` dependency, or `"type":"module"` on `@carbon/database`. — rung 2 (`packages/jobs/AGENTS.md`: bare tsx scripts cannot rely on Vite's interop).+- D13 — Task 2: `seed-dev.ts` spawns the planning script with `NODE_EXTRA_CA_CERTS=~/.portless/ca.pem` when that file exists and the var is unset; without it `runMrp`'s supabase-js reads failed with `fetch failed` (`SELF_SIGNED_CERT_IN_CHAIN`) against the portless `SUPABASE_URL`. The direct CLI's usage text says to set it. — rung 2 (`packages/dev/src/services/apps.ts` gives the apps the same CA).+- D14 — Task 2: `metadata.planningError` is written only while the marker still belongs to this run (snapshot path, `ready`); on the `snapshot: false` path the marker is already cleared, and `writeTemplateMarker` would re-insert it as `running`, so the failure is only logged. A new apply resets `planningError: null`. — rung 5 (the plan requires the post-apply status to be unchanged).+- D15 — Task 3: floor jobs need sales orders (the plan wants only 2 make-to-stock; `JobSpec` required one). Added two In Progress "floor-load" orders per dataset to `data/*/sales.ts` `releasedOrders` (one line per job item); `JobSpec.salesOrder/salesOrderLine/customer` became an all-or-none triple (none = make-to-stock). — rung 2 (every existing job hangs off an SO line).+- D16 — Task 3: "the seeded inspection document" is quality's receipt plan for a bought part, but the BOP picker lists only plans whose `partId` is the item (`getInspectionDocumentsForItem`). New shape `ItemsData.inspectionPlans` (file-less plan + features, tier 02) named by `BopOperationSpec.inspectionPlan` on one Final Inspection op per dataset; `copyMethodToJob` copies `inspectionDocumentId` + `assemblyInstructionId`. — rung 2.+- D17 — Task 3: reverses the 2026-09-22 "leave Draft so the demo can edit" choices for make methods (authored methods only — buy parts' interceptor methods stay Draft; tier 08 still cuts its Draft versions from the Active base) and the assembly instruction (Published). Procedures: v1 Archived / v2 Active on the first, Active on the second, rest Draft. — rung 1 (plan).+- D18 — Task 3: completed jobs' actuals are engine-derived (`JobSpec.loggedTime {startOffset, efficiency}` × makeDurations' unit math per staffed op), not authored events. Setup/Machine events need estimates, so a few ops per dataset gained `setupTime`/`machineTime` (precision already had them); a validator rule pins it. Outside-processing ops (no work center) log nothing. — rung 5.+- D19 — Task 3: robotics `CTRL-100` gained op 3 "Cabinet power-up and safety I/O check" at Integration Cell 1 — otherwise that cell had one open op and research caps ROB-2000 jobs at two. — rung 4.+- D20 — Task 3: validator floor thresholds follow the capability list (≥ 2 open ops per work center, ≥ 4 running work centers incl. the existing open event, ≥ 6 assigned open ops, all open jobs due −3…+21, release ≥ SO order date). Historical release dates stay (picking lists, NCR links and shift events hang off them); only due dates were re-dated, plus the Ready job released at −4. — rung 1 + 5.+- D21 — Task 3: `jobOperationTool`/`jobOperationParameter` come from copying the method's tools/parameters in `copyMethodToJob` (as get-method's itemToJob does); the batch is authored as ≥ 2 unstarted root ops of released jobs on one process (replacing the one-member batch on a Done op), and that process is flagged `batchable`. — rung 2 (batch-operations create rules).+- D22 — Task 3: step records — one row (index 0) per step of every Done op; File steps skipped (needs an upload); Value "OK", List first option, Measurement mid-range, Person = applying user, Timestamp = the op's last event end. Running timers start 06:45–08:15 UTC like the existing open event (in the past for US companies' mornings). — rung 5.+- D23 — Task 4: the open time card clocks in at 05:57–06:33 **UTC** today (`OpsData.openTimecard`), not the plan's "07:00 company TZ". 07:00 local is 11:00–12:00 UTC for the four US plants: after the running production timers (06:45 UTC earliest, D22) and in the future for a seed run before 07:00 local. UTC matches `TimecardSpec` and D22; the validator pins clockIn ≤ the earliest running timer (incl. the 08:00 open event). — rung 2.+- D24 — Task 4: `peopleAssignment` for the applying user on days −2, −1, +1…+4, never today (validator): a today row pre-filters the MES schedule to one work center (`apps/mes/app/routes/x+/operations.tsx:217-241`, research MES §1.5). One row per day (one person; unique `(employee, date, shift)`), ≥ 3 work centers, one row with overtime; one `peopleAbsence` in +7…+13 on a day with no assignment. Dates are anchor-relative, so a row can land on a weekend for a Mon–Fri shift; the board accepts any date (`runsOn` feeds only the capacity calendar, `apps/erp/app/routes/x+/priority+/people.tsx:365`). — rung 1 + 2.+- D25 — Task 4: tier 01 upserts the applying user's `employeeJob` (plant, title, department, shift, start date, `managerId` NULL) with `ON CONFLICT (id, companyId) DO UPDATE`; the company-wide `locationId` UPDATE stays for other employees (the wipe re-points everyone to HQ). `employeeShift` now follows `employeeJob.shift` (was `shifts[0]`). Proven on `dap2gkh860gg2ccl14sg` (0 rows for the user) in a rolled-back `wipeFirst` apply: row created at "Meridian Machining Plant" with First Shift / Machining, 0 rows after ROLLBACK. — rung 2.+- D26 — Task 4: HQ planning = one make part + one buy part on Fixed Reorder Quantity at HQ (so both Material Planning screens list a row there) + a 4-week `demandProjection` for the make part (`PlanningData.hq`). The tier throws when the item has no HQ `itemPlanning` row instead of a silent 0-row UPDATE. — rung 1 + 5.+- D27 — Task 4: `FoundationData.workCenterShifts` is authored per dataset (every work center ≥ 1 shift, validator) rather than every shift × every work center, so second/weekend shifts staff only the cells that plausibly run them. Shifts are created at the plant (D10). — rung 4.+- D28 — Task 5: five `enforcementRule`s per dataset — sales `error` (ship-to country `in` a list, on SO/invoice lines), sales `warn` (customer type `notIn`, on quote/SO lines), two item storage rules (`storageUnit.locationId` = plant; `storageUnit.storageTypeId` = a type) and one work-center rule (`workCenter.active` = true on `operationStart`). Conditions hold for the seeded data (US customers, active work centers) so a demo is never blocked; ids are authored by name (`{storageType}`, `{customerTypes}`, `{location}`) and resolved in tier 02. `@carbon/database` cannot import `@carbon/utils`, so `validate.ts` mirrors the field registry (fields × rule shape × operators × value kind). `REQUIRED_ENFORCEMENT_RULE_FAMILIES` = `sales`, `storage:item`, `storage:workCenter`, plus both sales severities. — rung 2 + 5.+- D29 — Task 5: the configured quote line's values are chosen so every `configurationRule` yields the method's own number: tier 04 copies the method as authored (get-method runs rule code through `importTypeScript`, which the seed transaction cannot), so any other value would leave the quote's BoM/BoP disagreeing with its configuration. The validator evaluates each rule body (`new Function("params", code)`) against the line and pins it. Robotics/precision/motor configurations were changed accordingly (sensor/cert/brake off, 60 mm shaft). — rung 2 + 5.+- D30 — Task 5: approval rules use `approverGroupIds` = the Admin employee-type group resolved by `employeeType."systemType" = 'Admin'` plus `defaultApproverId` = applying user (the "Needs my approval" window check passes without relying on membership). PO finalize asks for approval only at/above the lowest tier, so each dataset's Needs Approval PO was raised over $5,000 (satellite laminate 4→20, robotics billet 120→1200, precision cylinders 2→18, motor bearings 24→160) and given ref `po:needs-approval`; the request amount is the `purchaseOrders` view's `orderTotal`. — rung 2.+- D31 — Task 5: supplier-return Issues tab — each dataset gets a new Draft return-to-vendor to its supplier NCR's supplier for the NCR's quarantined item/quantity (`*-rtv`), linked by `nonConformancePurchaseReturnOrderLine`, instead of linking an unrelated line of an existing return. closeIssue refuses while a linked return is open, so the validator forbids a Closed NCR on an open return. RMA Issues tab: the existing Closed customer-complaint NCR links its own customer's RMA line. — rung 2 + 4.+- D32 — Task 5: return Credits tabs get new memos in the Issue Credit shape (`helpers/return-credit.ts`), only on Completed returns (the app caps credit at received/shipped): the RMA credit is Posted, the supplier-return debit memo Draft. The research's "re-link CR-…-000001" was not followed: that memo is an invoice credit a payment applies (tier 09), so re-purposing it would break its settlement. Posted return memos keep `journalId` NULL like tier 09's (journals are Task 6). — rung 2.+- D33 — Task 5: every quote carries `createdOffset` (validator: required, ≤ 0, after its RFQ, not after its order, before expiry, ≥ 2 in the last 30 days); sales and purchasing RFQs take `createdAt` from `rfqDate`, supplier quotes from `quotedDate` — no new field. — rung 2.+- D34 — Task 5: "open" for assignees = the dashboards' own status lists (`sales+/_index.tsx`, `purchasing+/_index.tsx`); the validator rejects an assignee on a closed document and wants ≥ 2 assigned per quote / sales RFQ / SO / PO / purchasing RFQ (tier 05's Draft lifecycle RFQ counts) / supplier quote. — rung 2.+- D35 — Task 5: `customerBankAccount` / `supplierBankAccount` are tenant data (`companyId`, PK `(id, companyId)`), so seeded: 4 + 4 per dataset incl. a EUR supplier account; account numbers and bank codes start `DEMO-`, SWIFT `DEMO…` (validator) — nothing resembles a real account. — rung 1 + 5.+- D36 — Task 5: `PricingRuleSpec` generalized (type, amount type, customer | customer type | items scope, `minQuantity`, `priority`); each dataset adds a Markup rule and a quantity-break rule; the validator requires both rule types and a break. — rung 1.+- D37 — Task 6: document journals are generated in tier 09 from the seeded rows, not authored — through the edge functions' own pure builders (`buildSalesPostingLines`, `buildPaymentJournal`, `buildMemoJournal`) and copies of post-purchase-invoice / post-receipt / post-shipment's inline line shapes (`helpers/posting-journals.ts`, DB side `helpers/post-documents.ts`); the validator re-derives every one from the literals with the same helper. `journalLineReference` = `<journalEntryId>-<group>` instead of a nanoid. — rung 2.+- D38 — Task 6: journals are written whether or not `companySettings.accountingEnabled` is on (production default off; the posting functions gate on it), so the demo GL agrees with its documents the moment accounting is enabled; the manual journals were already unconditional and `get_ar_open_by_customer` reads the AR lines with the same totals either way. — rung 5.+- D39 — Task 6 (widens the plan's list): Posted credit/debit memos (D32 deferred them here) and posted PO receipts / SO shipments are journaled too (DR inventory / CR GR/IR; DR COGS / CR inventory), so GR/IR clears and COGS/Inventory are not $0. Other inventory postings (RMA receipt, returns, job, adjustments, opening stock) still carry no GL; opening stock value sits in the Opening Balance entry. — rung 1 (research gap 11: "COGS and inventory") + 5.+- D40 — Task 6: the plan's "Purchase Invoice (Inventory or Expense / AP)" is the direct-invoice path; seeded invoices bill PO lines, whose real path is DR GR/IR Clearing / CR AP (`accrual` for the unreceived share). Tier 05 now sets `purchaseInvoiceLine.purchaseOrderLineId` (unset before, which reads as a direct invoice that would also create a receipt). Received share = posted receipts of the line on/before the invoice date; the validator requires the invoice to bill at the receipt price (no PPV / layer-adjustment branch). — rung 2.+- D41 — Task 6 (re-apply contract): posted journals survive the wipe and cannot be deleted, so the wipe now voids every Posted journal linked to a document it deletes — a negated Posted "VOID …" entry today, original left Posted, exactly as post-*-invoice / post-payment void (the tie-out and aging RPCs count `status = 'Posted'` only). `journalEntry` is excluded from `resetSequences` (a rewound counter collides with preserved journals: the user's company `dap2gkh860gg2ccl14sg` holds `JE-2026-09-000001` with its counter at 0), and `nextJournalEntryId` skips taken ids. Rejected: adopt-and-skip (GL of the previous dataset after a cross-dataset apply) and Reversed-status reversals (tie-out excludes Reversed originals but counts the reversal — tried first; the scratch company keeps that interim run's journals, so its tie-out is off by that run: AR 1307.5 / AP 982.5). Proven in a rolled-back satellite → precision → precision apply: AR and AP tie-out variance 0 after each. — rung 2 + 5.+- D42 — Task 6: one authored Posted Opening Balance per dataset (`JE-SEED-006`, offset −242: cash, raw materials, finished goods, plant, accumulated depreciation, term loan, capital, retained earnings); a company's existing Posted Opening Balance is adopted (unique index `journal_one_posted_opening_balance_per_company`). — rung 2.+- D43 — Task 6: make parts carried `standardCost: 0`; now 55 % of their `unitSalePrice` (BOM roll-ups were implausible, e.g. satellite ADCS 114 k cost vs 95 k price), and `createItem` writes `itemCost.unitCost` = `standardCost` (FIFO valuation and calculateCOGS fall back to it); a change-order revision starts at its predecessor's cost. Validator: every stocked item has `standardCost > 0`. — rung 5.+- D44 — Task 6: two more Overdue sales invoices per dataset (issued −75 / due −45, issued −105 / due −75) so receivables aging fills Current, 1–30, 31–60 and 61–90; `REQUIRED_AR_AGING_BUCKETS` pins all four (stronger than "≥ 3"). A Voided invoice's VOID journal is dated its issue date (the data has no void date). — rung 1.+- D45 — Task 6: the Draft Receipt / Disbursement are unapplied (no settlements) and name a party with an open posted invoice, which the apply table lists; pre-staged Draft settlements would enter the settlement-vs-status checks for nothing. — rung 5.+- D46 — Task 6: AR / AP billing addresses = the company address with reserved `.example` mailboxes, upserted by tier 09 (keyed `id = companyId`, outside the company wipe); floors counted through `COVERAGE_SCOPES` `id = $1`. — rung 2.+- D47 — Task 7: `QualityData.inspections` holds 4 lots per dataset: the existing Partial receipt lot (NCR-linked), a Passed and a Pending receipt lot, and a Job Operation lot. No dataset had a second posted untracked receipt line with n ≤ 5 (precision/motor had none), so each gained one "To Invoice" PO whose receipt posted −1/−2 (satellite/robotics: a repeat bare-board delivery; precision: PTFE bushings + replacement HK1512s from Midway; motor: terminal blocks + replacement Nomex from Copperline). Lots of one item share its one Receipt-usage plan (`itemInspectionDocumentAssignment` PK `(itemId, usage)`), so the validator requires identical drawing / aql / features and tier 07 creates the document once per item. — rung 2 + 5.+- D48 — Task 7: the Job Operation lot mirrors `getOrCreateJobOperationInspection` on the floor job's root Inspection op (plan = its `items.inspectionPlans` document, lot = operation quantity). Satellite/robotics: In Progress with 1 of n=2 samples, and that op's override moved Waiting → In Progress (no timer); precision/motor: Pending, no samples (their Inspection op follows an outside-processing op still Waiting). Dispositioned job-op lots are rejected (their `productionQuantity` postings are not authored); "Failed" left the type (it was already rejected). `REQUIRED_INSPECTION_STATUSES` = Pending/Passed/Partial, `REQUIRED_INSPECTION_SOURCES` = Receipt/Job Operation. — rung 2 + 5.+- D49 — Task 7: `NonConformanceSpec.items` is now required and non-empty; dispositions come from the picker's active subset. A Closed NCR's rows are Use As Is / Rework only (other dispositions make `closeIssue` post inventory value the seed does not author) and it carries no assignee (close clears it); supplier-escape rows are Return to Supplier (D31's Draft RTV). Two open NCRs per dataset are assigned to the applying user. — rung 2.+- D50 — Task 7: 3 issue workflows per dataset (supplier escape, customer complaint, incoming hold), each linked from one NCR (3 linked). A linked NCR must carry the workflow's source, required actions (same order) and MRB, which the new-issue form copies; priority stays free (the form lets it be edited). — rung 2.+- D51 — Task 7: "nonConformanceSupplier in the current month" = the incoming-lot-hold NCR (opened −5/−6) now names its lot's supplier; the validator window is the last 28 days (the supplier KPI's default is the last month; DayOffsets cannot pin a calendar month). The motor seed shows it on 2026-09-18. — rung 5.+- D52 — Task 7: `nonConformanceActionProcess` links the supplier escape's In Progress Root Cause Analysis task to a process some BOP operation uses (validator: open task, process in use). — rung 1.+- D53 — Task 7 maintenance shapes, per dataset: a Scheduled Assigned dispatch planned today 14:00 UTC (same local day at all four US plants — MES Today tab, Open Scheduled tile) from the Daily schedule, which now runs weekends (`weekends: false` dropped) so "due today" holds on any anchor weekday, next due tomorrow; an In Progress + Down Reactive dispatch (`takesWorkCenterOffline`, planned end +1) on a plant work center with no In Progress operation and few open ops (satellite TIG Welder Cell 3, robotics Harness Bench 7, precision Wire EDM Cell 3, motor Lamination Press 8) — the scheduler subtracts only actualStart…plannedEnd, and the real motor seed + schedule step placed Lamination Press ops from +1; a Completed Reactive dispatch created on a shift-event day at that event's work center (MTBF); 2 Completed dispatches finished −40…−53 (one Scheduled with a spare part, one Reactive Down); an Open Reactive dispatch + a schedule at the HQ work center. The validator pins each shape (`BACKDATED_COMPLETION_WINDOW`, `MAX_DOWN_OUTAGE_DAYS`, event-day match). — rung 1 + 2.+- D54 — Task 7: `maintenanceDispatchItem.unitCost` = the item's standard cost (tier throws on 0; validator requires `standardCost > 0`). Satellite `CN-GREASE-001` opening stock 2 → 3 so the back-dated re-grease draws one while the "next kit is short of Krytox" story holds (net 0). — rung 2.+- D55 — Task 7: `workCenterReplacementPart` from `OpsData.replacementParts` — ≥ 3 rows on ≥ 2 work centers, one on a work center with an open dispatch — using existing items (no new items or thumbnails); satellite lists `VLV-SOLENOID-LP2`, the current revision, not the superseded valve. — rung 5.+- D56 — Task 7: `FoundationData.hqWorkCenter` is created at `ctx.locationId` with no shift, process or operations (kept out of the floor and shift rules); schedules and dispatches now take their work center's location instead of always the Plant; an HQ dispatch may not issue spare parts (the shelves are at the plant). — rung 2 (D10).+- D57 — Task 7: `FoundationData.partners` — id = the supplier's supplierLocation (so the supplier needs a supplierContact), ability, hours/week; ≥ 2 per dataset, shown by the `partners` view. — rung 2.+- D58 — Task 7: `ProcedureSpec.parameters` are written on every version row, as creating a version copies them; ≥ 2 procedures per dataset carry them. — rung 2.+- D59 — Task 8: every B6-remainder shape lives in `OpsData` / tier 10 (`userAttributeCategories`, `customFields`, `serialSequences`, `printJobs`, `webhook`) — print jobs reference receipts, jobs and shelves, which only exist after tiers 01–06. — rung 2.+- D60 — Task 8 (re-apply contract for preserved tables): `userAttributeCategory` and `customField` are in the wipe's `PRESERVED_TABLES`, and `userAttribute` / `userAttributeValue` have no `companyId` so the wipe never sees them. All four are seeded and ADOPTED on re-apply, then updated to the dataset's values: category by `(companyId, name)`, attribute by `(category, name)`, value `ON CONFLICT (userAttributeId, userId)`, customField `ON CONFLICT (table, name, companyId)` (the webhook was dropped, D66). `tableView` is NOT seeded (saved list views are the user's own; no B6 screen needs one). A cross-dataset apply leaves the previous dataset's category and fields, like its journals — rows in these tables may be the user's, so the seed never deletes them. Proven: two consecutive applies in one rolled-back transaction ×4 datasets, and two real robotics seeds — every new row exactly once. (A same-transaction double apply needs HQ's `createdAt` nudged back first: `buildCtx` picks HQ by `ORDER BY "createdAt", id`, and one transaction gives the plant the same `now()`; separate real applies are unaffected.) — rung 2 + 5.+- ~~D61~~ **Superseded by D66.** — Task 8: the webhook's sync interceptor (`sync_webhook_subscription`) raises "Not authorized to manage event subscriptions" for the seed's session (no `auth.role()`, no `auth.uid()`), even with every event off. Tier 10 raises `request.jwt.claim.role` to `service_role` with `set_config(…, true)` for that one statement and restores the previous value; the interceptor then creates the `eventSystemSubscription` inactive (`dispatch_event_batch` only fans out `active = TRUE`). URL is https on a reserved `.example` host and `active = false` always (validator). Rejected: disabling the trigger (DDL), `session_replication_role` (also skips FKs), an event-less webhook (still raises; the app's validator requires one event). — rung 2 + 5.+- D62 — Task 8: one public attribute category per dataset with four attributes (Date, List, User, Yes/No) valued for the applying user; the User attribute names the applying user, the only person the seed may name (H3). `REQUIRED_USER_ATTRIBUTE_TYPES` = Date/List/User. — rung 1.+- D63 — Task 8: serial sequences continue each dataset's seeded pattern (`<CODE>-SN-` + 4 digits). `next` is the last counter issued (`get-next-serial-number` hands out `next + step`), so the validator scans every string in the dataset matching prefix + counter + suffix and requires `next` ≥ its counter; every Serial-tracked item needs exactly one sequence (motor's MTR-4500, with no seeded serials, starts at 0). — rung 2.+- D64 — Task 8: five print jobs per dataset on `foundation.printerRoute`: completed/auto Receipt label (the latest posted receipt), completed/manual Job label (a Completed job), completed/manual storage-unit label, failed/auto Job label (3 attempts, delivery timeout) and its queued reprint today at ≤ 08:00 UTC. Content is a small ZPL label built by the tier (a reprint needs content); `completedAt` = `createdAt`. Window −20…0 because the cleanup job deletes completed jobs after 30 days. Seeded queued rows are inert: delivery is triggered by an event (`print-job-deliver`), never polled. — rung 2 + 5.+- D65 — Task 8: custom field VALUES (the `customFields` JSON on part / customer / job rows) are not seeded — the plan asks for the three field definitions, which is what Settings › Custom Fields lists; the fields render empty on the entity forms. — rung 1 (plan scope).+- D66 — Task 8 (supersedes D61; narrows H1): webhook not seeded — seeding it required spoofing the service_role claim to bypass the interceptor's authorization guard; the Webhooks settings screen stays empty by design (developer infrastructure, which the wipe preserves on purpose). The scratch company's one seeded webhook and its subscription were removed. — rung 5 (security).+- D67 — Task 9 (matrix scope): Reports › saved report views (`reportView`) are EXCLUDED — user-owned saved views, like `tableView`, which D60 already leaves unseeded; the Reports hub itself renders its catalog. — rung 2 (D60 precedent).+- D68 — Task 9 (matrix method): GL checks (tie-out control lines, journals without `accountingPeriodId`) count only the journals written by the apply under test (`journal.createdAt` ≥ the plant's `createdAt` — one apply is one transaction, one `now()`). The scratch company keeps immutable Posted journals from runs before Task 6 (period-less `JE-SEED-00x`, the interim run's reversals, D41) that no apply can remove; on a fresh company the unscoped and scoped counts are equal. — rung 5.+- D69 — Task 9: assembly detail › units (`assemblyUnit`) EXCLUDED — "plan as one component" overrides are input to the assembler planner (`loadPlanUnits`, packages/jobs plan-units.ts), whose plan/plan job are already a non-goal (integration). Step materials, step tools and component mappings are seeded instead (D76). — rung 2 + spec Non-goals.+- D70 — Task 9 (batch detail › events): the Active batch now runs — `ProductionData.batch.running` (type + UTC start today) puts a batch-tagged open `productionEvent` on the first member (MES event.tsx shape: `jobOperationBatchId` set, sliced at completion) and every member operation In Progress; the validator requires member jobs "In Progress", earlier root operations Done, and counts the lead's work center as running and its start in the open-time-card rule. Data: member jobs moved Ready → In Progress; precision's turning ops before the deburr batch are Done; motor's batch moved from the lamination press (Down for maintenance, D53) to the two terminal-box jobs at the CNC turning cell. — rung 2.+- D71 — Task 9 (Reports › Scrap was EMPTY): tier 09 journals each scrapped lot as post-inventory-adjustment's Scrap does — a `Negative Adjmt.` Direct Cost `costLedger` row drawn FIFO like shipments, and an `Inventory Adjustment` journal (CR inventory / DR `accountDefault.scrapAccount`, line documentType `Scrap`, documentId = the ledger row). The wipe now also voids Posted `Inventory Adjustment` journals whose lines point at item-ledger rows it deletes (D41's re-apply contract; proven: a re-apply nets the scrap account to the current dataset's write-off only). Validator: the scrap journal balances, sits in an open period, and ≥ 1 scrap falls in the report's trailing six months. ScrapReason dimension tags are not written (the report shows the amount under "Unassigned"). Refines D39. — rung 2.+- D72 — Task 9 (MES operation › issue actions was EMPTY): `get_action_tasks_by_item_and_process` matches the operation's make-method item, so D52's link to a process could never show on a bought part's issue. Each supplier-escape NCR now also lists the WIP item built from the suspect lot (satellite PROP-001, robotics DRV-J2-MOD, precision MCH-HSG-PUMP, motor COIL-9000; disposition Pending), and satellite's task process moved Welding → Clean Room Assembly (where PROP-001 is built). New validator rule: an open task's process runs on an open root operation of a released job building one of the issue's items. — rung 2 + 4 (containment extends to WIP).+- D73 — Task 9 (motor MES assembly 3D was FILTERED-EMPTY): motor's only MTR-9000 job has its Assembly operation Done, so a make-to-stock "service-pool" MTR-9000 job (Ready, due +19, priority 15) was added; validator: some released job of the instruction's item has its Assembly operation still open. — rung 2.+- D74 — Task 9 (job › Quantities tab): recently completed jobs record a Production quantity for the full operation quantity on every logged operation, as the operator does at the end of a run (the interceptor then fills `jobOperation.quantityComplete`, which read 0 on Done operations). — rung 2.+- D75 — Task 9 (item › Purchasing › batch properties was EMPTY): `ItemsData.batchProperties` — per-lot attributes (heat number, date code, list grades, …) on every Batch-tracked item; validator: Batch-tracked item, unique label, `listOptions` exactly for list (≥ 2), every Batch-tracked item has one. — rung 1.+- D76 — Task 9 (assembly detail step panels / BOM tree were EMPTY): `AssemblyStepSpec.materials` / `tools` and `AssemblySpec.componentMappings` (leaf `geometryHash` of the bundled graph → a component of the assembly item's BOM, confidence high). The bundled models are stand-ins (a radial engine for SAT-1000, …), so mappings pair each item with the model part that plays it in the build sequence. Validator: materials on the item's BOM, tools are Tool items, hashes are leaf hashes of the graph, ≥ 2 materials, ≥ 1 tool, ≥ 2 mappings. — rung 2 + 5.++- D77 — Task 11: the demo-data docs page quotes both wipe refusals verbatim (with `N` for the count) in a reader-visible Callout — the review card shows the raw job error — and again as `<AgentContext>` troubleshooting entries; it states that only MRP has a 3-hourly backstop (the cron runs `runMrp` only, `scheduled/mrp.ts`), not scheduling. — rung 2.+- D78 — Task 11: `generate:agent-kb` writes `manifest.json` unformatted (660 lines of array-wrapping churn against HEAD); `biome format --write` on it restores the committed shape, leaving only the demo-data entry changed. — rung 2 (the committed manifest is biome-formatted).++- D79 — R1 (review #8/#12/#13): one method copier, `helpers/method-copy.ts` (`copyMethodToJob` / `copyMethodToQuoteLine` / `copyMethodToMethod`), replaces `job-method.ts`, `quote-method.ts` and tier 08's `cloneMethodRows`. Operation rows copy every column the target shares with `methodOperation` (via `sharedColumns`), so workInstruction / procedure / inspection / assembly links cannot drift from a migration. — rung 2 (get-method's own `...operation` spread).+- D80 — R1: per-operation children follow get-method exactly — tools always; method parameters only without a procedure; a JOB operation with a procedure takes the procedure's steps, parameters and `content` (as `workInstruction`); quotes and method→method copies take nothing from the procedure. Outside rates: named supplier process, else the process's supplier-process average, else 0 (`getRatesFromSupplierProcesses`); a quote keeps the method's own `operationMinimumCost` (get-method overrides it after the spread). — rung 2.+- D81 — R1: kept on purpose where get-method differs: job `operationUnitCost` is still copied (`itemToJobMakeMethod` copies it, `itemToJob` does not — get-method is inconsistent with itself); work-center rates stay by-id (no process-average fallback); no assembly-instruction step expansion and no `methodOperationStep` copy (no dataset authors either — adding them would change jobOperationStep/Tool counts beyond R1's scope); materials keep their existing column set. A missing root/child make method, an absent interceptor row, a BOM cycle, an unmapped material operation or a cross-tenant procedure now THROW (the job copy used to skip silently). — rung 4 (smallest change that closes the reviewed drift).+- D82 — R1 (#13): `assembly` moved from `ProductionData` to `ItemsData` and `seedAssembly` from tier 06 to tier 02, where it links the Assembly `methodOperation` before release; tier 06 no longer mutates a released method, and quote operations now carry the link. Validator messages read `items.assembly`; its job-parameter floor now counts procedure parameters for procedure operations. — rung 2 (review M8's own restructure).+- D83 — R2 (review #2): `datasets/types.ts` is gone, with no barrel — every importer names the precise module (`types/<slice>.ts`, `types/primitives.ts`, `types/dataset.ts`, `types/engine.ts`, `context.ts`). A barrel would keep two ways to import the same type; the rewrite was mechanical (84 sites) and each data file imports exactly its own slice. Package entry points are unchanged: `datasets/index.ts` still re-exports `Ctx` / `Dataset` / `DatasetKey` / `resolveCompanyTimeZone`, and `seed-workflows` keeps its value exports (no consumer imported its types). — rung 4 (smallest consistent shape).+- D84 — R2: the `Ctx` / `SeedRefs` / `ItemRef` / `Tier` types live in `types/engine.ts`, not `context.ts`: `sql.ts` needs `Ctx` and `context.ts` needs `sql.ts`, so a `Ctx` in `context.ts` would keep the type-level cycle the review flagged. Runtime ctx construction (`emptyRefs`, `resolveCompany`, `resolveCompanyTimeZone`, `buildCtx`, `Resolved`) is `context.ts`. Spec types that lived in implementation files moved with their doc comments: `ItemSpec` / `MaterialClassificationSpec` / `MethodType` / `OperationType` from `helpers/items.ts` and `ItemType` to `types/items.ts`; `SeedWorkflow` / `Node` / `Edge` from `tiers/workflow-definitions.ts` to `types/workflows.ts`; `DayOffset` from `dates.ts` and `InstantSpec` (shared by ops + workflows) to `types/primitives.ts`. Declarations moved verbatim except the "Slice shapes" banner. `madge --circular` on `src/datasets`: 10 cycles before, 0 after. — rung 2 (review B1's own restructure).+- D85 — R3 (review #1): `datasets/validate.ts` (6,742 lines) is `datasets/validate/`: `dataset-index.ts` builds every projection once (named ref sets behind `need(kind, where, id)`, document refs, the on-hand ledger, the tracked-lot registry, BOM walks, floor state), and 22 `rules/<slice>.ts` modules only read it (largest 546 lines). The four cross-slice registries that forced the slice order — `registerRef`, `addOnHand`, `trackedEntityQty` / `receiptLotIds`, `validateFloor`'s returned active set — are projections now; `RULES` in `index.ts` is report order only. Message strings were copied by line range, not retyped; `need()` replaced an inline check only where the message is exactly `unknown <label> "<id>"`. Public API: `validateDataset` + `MIN_JOBS`; `REQUIRED_*` moved intact to `validate/required.ts` for R4; every other constant is module-private. — rung 2 (review A-B1's own restructure).+- D86 — R3: kept exact, not simplified: a document ref is visible to a reader only if registered before it in tier order (an RMA / job / NCR sees refs up to its own registration, risks the whole quality slice, workflow runs everything through accounting — `document-refs.ts` `seenBy`), because that is what `ctx.refs.documents` holds when the tier resolves it; coarse per-slice phases would have accepted forward refs the old code rejected. One deliberate change: "duplicate document ref" violations are now all listed at the start of the sales slice (the old code listed each where it was registered). Proof: the 116 validator calls of the old test file give identical ordered arrays; 12,008 seeded random mutations old vs new — 11,984 identical, 9 differ only in that ordering (all duplicate refs), 15 are type-invalid inputs (a required array deleted) on which both versions throw; 5,248 targeted ref-visibility probes identical. — rung 2.+- D87 — R3 (review #3): `validate.test.ts` → `validate/validate.test.ts`, one `CASES` table (`[name, dataset, mutate in place, expected]`, expected may be a list or a function of the mutated dataset) run by `it.each` on `cloneDataset`, a recursive copy that keeps functions (`structuredClone` rejects `workflows.build`); the every-dataset test also validates each clone. 108 negative cases before and after; each builds a byte-identical mutated dataset (JSON sha1) to its original test and gets the identical violation array. — rung 2 (review A-M6's own shape).+- D88 — R4 (review #4): the ~55 `REQUIRED_*` arrays are one `COVERAGE` table in `validate/required.ts`, each entry `{ values, missing }`. An enum-backed set is `enumValues(<generated enum>, { <value>: "<reason>" })` over `Constants.public.Enums` (the generated DB types), so every exclusion carries its reason, a renamed enum value breaks typecheck, and a new enum value fails every dataset until one exhibits it or it is excluded. Nine sets whose columns are free text stay explicit (AR aging buckets, close-task / workflow-run / print-job statuses, print origins, user-attribute types, custom fields as `table|dataType`, rule shapes, sales-rule severities). One loop, `checkCoverage(fail, exhibited)`: rule modules still collect what they exhibit while they walk and call it where their old loop sat, so the cross-slice report order D86 proved is unchanged (one end-of-run pass would have reordered it). 28 loops and the per-slice mini-registries are gone. Proof: 6,816 old-vs-new validator runs (1,500 random mutations per dataset plus every string key blanked dataset-wide): every coverage message is byte-identical; within one set the order is now the enum's (8 order-only diffs); the one changed text is "no Active training covers every trainingQuestionType (…)", which now lists the types in enum order. — rung 2 (review A-M2's restructure; per-module call sites chosen to keep D86's order).+- D89 — R4 (review #6): one GL sign rule: `signedNet(lines)` in `helpers/posting-journals.ts` = `round(Σ debit(accountTypeFromClass(class), amount))` over `lib/utils.ts`'s canonical helpers; `postingImbalance` and the validator's `journalImbalance` both use it, and both `DEBIT_CLASSES` copies are gone. The validator's manual-journal tolerance is `EPSILON` (was 0.01): stricter than the app's manual-journal 0.001 (`accounting.service.ts` `JOURNAL_BALANCE_TOLERANCE`) because authored amounts are exact, so any residual is an authoring error (one comment says so). `cents()` (`Math.round`) is `precision.round(x, USD_DECIMALS)`, with the decimals read from the bootstrap USD row rather than a literal; messages that printed `cents / 100` print the rounded value. A type-invalid `accountClass` now throws `Unknown GL account class` instead of reporting an imbalance. — rung 2.+- D90 — R4 (review #7): the pure verdict core (`parseSpecNumber`, `valuateMeasurement`, `deriveSampleStatus`, `computeLotStatus`) is `supabase/functions/shared/inspection-verdict.ts` (no kysely, no I/O). `quality.ts` imports it and re-exports `valuateMeasurement`, so `@carbon/database/quality` is unchanged for ERP/MES; no new package subpath, because nothing else needs one (sampling-engine's re-export exists for app consumers). `helpers/inspection.ts` is two thin adapters over it (a seeded feature is a numeric Measurement), and dead `openLotStatus` is deleted. Drift fixed to the engine's behaviour: a lot with no features never passes a sample, an unparseable nominal gives Pending rather than judging against 0, and a missing reading value is Pending rather than Failed. No seeded value changes: all 60 seeded readings valuate identically and every dataset still validates. Proof of the engine: `quality.server.test.ts` (6) plus the new `src/inspection-verdict.test.ts`. — rung 2 (review A-M4's restructure).+- D91 — R4 (review #9): `bootstrapIdByName(ctx, table, name)` is the one lookup of a company-scoped row by name. It replaced `scrapReasonIdByName` (tier 06), `taxonomyId` (tier 01, which also interpolated the table name without `quote()`), `failureModeId` (tier 10) and the `pterm:` / `cstatus:` / `rreason:` / `mat*:` preloads. `helpers/items.ts` resolves a material classification through it too. `userAttributeCategory`'s adopt-by-name stays as it is, because it is an adopt-or-insert (`ORDER BY "createdAt"`) and not a lookup. Its error now reads `Seed: no <table> named "<name>"`. — rung 2 (review B-M4's restructure).+- D92 — R4 (reviews #10, #11): both drift tests live on the canonical side, because `@carbon/database` cannot import either package without a cycle. `RULE_FIELDS` moved to `validate/rule-fields.ts`, exported as `@carbon/database/dataset-rule-fields` (type-only imports, so it loads nothing at runtime). `packages/utils/src/field-registry.test.ts` asserts that every field × shape exists in the builder's list for that shape (`getFieldsForSalesRules` / `getFieldsForTargetType`) and every operator is in its `availableOperators` (15 cases). `packages/ee/src/workflows/seed-workflows.test.ts` asserts that each `EVENT_SOURCES` entry equals the catalog event's `match` (table + operation, or `null` for a moment) and that every seeded trigger event has a source. Both were red-checked by a temporary edit, then restored. utils and ee already depended on `@carbon/database`, so no new package edge. — rung 3 (the step's stated fallback).+- D93 — R4 (review #21): `helpers/memo.ts` `insertMemo` is the one memo writer (tier 09's invoice memos and `seedReturnCredit`). It stamps post-memo's `postingDate`, 16:00 `postedAt` and `postedBy` on a Posted memo, and resolves post-memo's reason account (return order's, else the party side's discount account); a missing default now throws there instead of surfacing later in `postMemos`. The false "no journal (accounting disabled)" comment is gone. `seedReturnCredit` now follows `createSalesReturnOrderCredit` / `createPurchaseReturnOrderCredit`: it reads the return order's `currencyCode` / `exchangeRate` and each line's `unitPrice` / `restockFeePercent` back from the rows tier 04/05 wrote, and sets restockFee = gross × percent, amount = round(Σ gross − fee, the currency's `decimalPlaces` ?? 2). The tiers no longer pass line prices. No seeded value changes: the returns are USD with a 0% fee, and all 8 credits' amounts are already exact. — rung 2.++## Open Questions (audit trail — all resolved autonomously)++- [x] Run MRP inside the seed? — **Autonomous:** no; post-commit (H2).+- [x] Fake employees? — **Autonomous:** no (H3).+- [x] IC partners / card transactions: preserve or refuse? — **Autonomous:** refuse (H4).+- [x] Seed GL for posted docs? — **Autonomous:** yes (H5).+- [x] How does the dev CLI reach `@carbon/planning`? — **Autonomous:** spawn a jobs-package script (D8).+- [x] Cover engine output in floors? — **Autonomous:** no; screen matrix (D9).++## Changelog++- 2026-09-23 — Spec written from five screen audits; approved autonomously.+- 2026-09-23 — Implemented autonomously (D12–D78; plan Tasks 1–9 and 11 ticked, Task 10 full-verification box still open when this entry was written): wipe refusals + slide pre-delete + journal voiding, post-commit `planDemoCompany` for the template job and dev CLI (`--skip-plan`), B1–B6 data and tier shapes across all four datasets, validator/coverage floors (213 → 255 tables), screen matrix FAIL 0 ×4 (`.ai/runs/2026-09-23-screen-matrix-*.txt`), docs + agent KB. Uncommitted — awaiting the user's commit.+- 2026-09-23 — Task 10 verified by the orchestrator: typecheck 0, 119/119 tests, db:check ✓×4, @carbon/jobs typecheck 2/2, biome 0 errors; real re-apply robotics → satellite (MRP ✓, Schedule ✓, 0 robotics items left); screen matrix on the final satellite seed FAIL 0 (204 PASS, 16 EXCLUDED); wipe probes re-run on final code (satellite + motor); pre-commit drill blocked; baselines refreshed; structural sums from a fresh rolled-back company (0 unbalanced journals). Evidence: `.ai/runs/2026-09-23-screen-coverage-verification.txt`.diff --git a/.ai/specs/2026-09-24-demo-data-orphan-recovery.md b/.ai/specs/2026-09-24-demo-data-orphan-recovery.mdnew file mode 100644index 0000000000..960f737371--- /dev/null+++ b/.ai/specs/2026-09-24-demo-data-orphan-recovery.md@@ -0,0 +1,186 @@+# Demo data: stop leaving orphan rows on revert, and recover when they exist++> Status: draft+> Author: Aashu+> Date: 2026-09-24++## TLDR++Reverting demo data (and any own-backup restore) can leave per-user rows+(`employeeAbility`, `employeeShift`, `trainingCompletion`) pointing at parents+the revert deleted. The next demo apply then fails at its safety snapshot with+"NOT-NULL reference(s) escape company scope". Fix the cause in `wipeAndLoad`+(drop rows whose parent no longer exists, in the same transaction), and give the+demo-data page the same "Remove corrupted data" recovery the Backups restore+flow already has.++## Problem Statement++Seen on dev company `dap2gkh860gg2ccl14sg` (Carbon Development): applying+"Aerospace & Satellite" failed with++```+Refusing to export dap2gkh860gg2ccl14sg: 3 NOT-NULL reference(s) escape company scope …+ employeeAbility.abilityId → ability (2 rows)+ employeeShift.shiftId → shift (1 row)+ trainingCompletion.trainingAssignmentId → trainingAssignment (1 row)+```++Verified in the DB: the 4 rows reference `ability` / `shift` /+`trainingAssignment` ids that do not exist at all (FKs are validated, so the+rows were orphaned while FK triggers were off). The counts match exactly what+the demo seed inserts (`packages/database/src/datasets/tiers/01-foundation.ts`+L648-659: 2 abilities + 1 shift; `10-ops.ts` L621: 1 completion).++How it happens:++1. Demo apply seeds abilities/shifts/training + the per-user links above.+2. Revert calls `wipeAndLoad(..., remap: false)` (`company-template.ts` ~L493).+3. On `remap: false`, `selectWipeableTables` keeps user-scoped identity tables+ (`isUserScopedIdentityTable`, `company-backup.ts` ~L544) but wipes their+ parents. The wipe runs with `session_replication_role = 'replica'`, so+ `ON DELETE CASCADE` never fires. The parents are not in the pre-apply+ snapshot, so the reload doesn't bring them back. Result: orphans.+4. The next apply's pre-template snapshot (`buildCompanyBackup`) hits the export+ closure guard and refuses.++The same bug hits a normal Backups restore of an own backup: any per-user link+created after the backup, to a parent also created after the backup, is+orphaned.++Second problem: when the guard does fire during a demo apply, the demo page only+shows the raw error. The restore flow already handles this exact failure+(marker `reason: "scope-violations"` + a confirmed "Remove corrupted data and+restore" action); demo data doesn't.++## Proposed Solution++### Part 1: root cause (jobs)++After the load in `wipeAndLoad`, inside the same transaction and only when+`remap === false`, delete rows of the **kept** user-scoped identity tables whose+NOT-NULL FK points at a row that no longer exists. This does exactly what the+suppressed `ON DELETE CASCADE` would have done.++- New helper in `packages/jobs/src/backups/scope.ts`:+ `deleteDanglingRows(trx, tables, byName, companyId, companyGroupId)`, which returns+ `Array<{ table; rows }>`. For each table (reverse catalog order), for each NOT-NULL+ FK (`refColumn = "id"`, ref table not in `RETAINED_REF_TABLES`):+ `DELETE … WHERE <table scope> AND <col> NOT IN (SELECT id FROM <parent>)`.+ "Missing" means **missing anywhere**, not "outside company scope". Pre-existing+ cross-company references are real corruption and stay behind the+ user-confirmed purge (Part 2); this helper only cleans up what the wipe itself+ broke.+- `wipeAndLoad` calls it with+ `catalog.tables.filter(t => isUserScopedIdentityTable(t) && scopeColumn === "companyId")`+ when `!remap` (on remap those tables are already wiped). Logs the deleted+ counts when non-zero.++### Part 2: reuse the scope-violation recovery (demo data)++**Job (`company-template.ts`)**+- `TemplateMeta` gains `reason?: "scope-violations"`, `violations?`,+ `violationRowsByTable?` (same shape as `RestoreMeta`).+- Apply's `catch`: when `err instanceof ExportScopeViolationError`, write those+ fields and throw `NonRetriableError` (same as restore at ~L580-605: the+ verdict is deterministic, so a retry would only flicker the marker).+- Apply's `running` patch resets `reason`/`violations`/`violationRowsByTable` to+ null so a new run never inherits a previous failure's reason+ (`writeTemplateMarker` merges the existing metadata).++**App service (`backups.service.ts`)**+- `CompanyTemplateRun` gains `reason`, `violations`, `violationRowsByTable`+ (typed like `CompanyExportRun`), projected in `getCompanyTemplateRun`.++**Route (`demo-data.tsx`)**: new `purgeAndApply` intent, mirroring+`purgeAndRestore` (`backups.tsx` ~L349):+1. Load the marker; refuse unless `status === "failed"`,+ `reason === "scope-violations"`, `templateRunId` matches, and+ `datasetKey` is present.+2. `purgeCorruptedRows(companyId)` (reused as is). On throw: return its message+ ("nothing was deleted").+3. `startCompanyTemplate({ companyId, userId, datasetKey })`. There is no separate+ finalize: apply already accepts a `failed` marker and overwrites it, and a+ scope-violation run never recorded a snapshot. That avoids racing a+ finalize job against the new apply on the single per-company marker. If this+ half fails, the message says the rows were removed but the apply didn't start+ (same two-step wording as restore).++**UI**+- Extract the purge confirmation modal from `backups.tsx` (~L737-800) into+ `ui/Backups/PurgeCorruptedRowsModal.tsx`. Props: `rowsByTable`, `body` text,+ `confirmText`, `onConfirm`, `onCancel`, `isSubmitting`. Backups keeps its current+ copy; demo data passes its own.+- `TemplateReviewRow`: on `status === "failed"` with+ `reason === "scope-violations"`, show the plain-language line (same `Plural`+ wording as `RestoreReviewRow`) plus the `ExcludedRowsInfo` popover with the+ raw error. Add a destructive **"Remove corrupted data and apply"** button that+ opens the modal; on confirm, submit `intent=purgeAndApply`. Other failures+ keep today's rendering.+- All new copy goes through Lingui (`Trans` / `Plural` / `t`).++### Design Decisions++| Decision | Choice | Rationale |+|----------|--------|-----------|+| Root-cause fix shape | Delete dangling kept identity rows after an own-restore load | User choice. Smallest change; keeps today's "identity rows are kept" semantics; also fixes plain Backups restore. |+| What counts as dangling | Parent row missing entirely (not "outside company scope") | Matches what CASCADE would have done. Deleting real cross-company references stays user-confirmed via the purge. |+| Where the fix lives | `wipeAndLoad` (shared by restore + template revert) | One place covers both callers. |+| Recovery after confirm | Purge, then re-apply the same dataset (the new run overwrites the failed marker) | User choice. Matches `purgeAndRestore`. |+| Purge implementation | Reuse `purgeCorruptedRows` unchanged | Same guard, same data, same group-shared refusal. |+| Confirm modal | Extract a shared component from `backups.tsx` | "Reuse the exact same functionality"; avoids two copies of the destructive-confirm UI. |+| Marker fields | Same names/shapes as restore's (`reason`, `violations`, `violationRowsByTable`) | Lets UI helpers (`totalScopeRows`, `ExcludedRowsInfo`) work unchanged. |++## Data Model Changes++N/A. No schema change; marker metadata is JSON.++## API / Service Changes++- `scope.ts`: `+ deleteDanglingRows`+- `company-restore.ts` `wipeAndLoad`: call it when `!remap`+- `company-template.ts`: `TemplateMeta` fields; catch branch; running-patch reset+- `backups.service.ts`: `CompanyTemplateRun` fields + projection+- `demo-data.tsx`: `purgeAndApply` action++## UI Changes++- New `ui/Backups/PurgeCorruptedRowsModal.tsx`; `backups.tsx` switches to it.+- `TemplateReviewRow.tsx`: scope-violation failure line, info popover, and+ "Remove corrupted data and apply" button + modal.++## Acceptance Criteria++- [ ] Unit test: `deleteDanglingRows` deletes an `employeeAbility` row whose+ `abilityId` doesn't exist, and leaves one whose ability exists (in this or another+ company).+- [ ] Unit/closure test: an own-restore `wipeAndLoad` where the backup lacks an+ `ability` that a live `employeeAbility` references ends with no orphan+ and a clean `findExportScopeViolations`.+- [ ] Manual: apply a demo dataset, revert, apply again: the second apply succeeds+ (no scope-violation error).+- [ ] Manual (dev company `dap2gkh860gg2ccl14sg`, existing orphans): apply shows+ "4 rows link to data outside this company…", an info popover listing the 3+ edges, and a "Remove corrupted data and apply" button. The confirm modal lists+ `employeeAbility 2`, `employeeShift 1`, `trainingCompletion 1`. Confirming deletes+ them and the apply runs to `ready`.+- [ ] A failed apply for any other reason still shows today's error + Dismiss,+ with no purge button.+- [ ] Backups page purge modal looks and behaves as before (shared component).+- [ ] `purgeAndApply` refuses when the marker isn't a failed scope-violation run.+- [ ] All new strings extracted by Lingui; typecheck + existing backup tests pass.++## Open Questions++- [x] How should own-restore handle kept identity rows whose parent it wipes?+ **Answer:** Drop dangling rows after the load (not wipe + reload them);+ smallest change, and it also fixes normal restore.+- [x] After confirming "Remove corrupted data", re-apply automatically or not?+ **Answer:** Purge, drop the failed run, re-apply the same dataset in one+ click, as `purgeAndRestore` does.++## Changelog++- 2026-09-24: Initial draft (both questions resolved with Aashu).+- 2026-09-24: Planning: `purgeAndApply` no longer finalizes the failed run first+ (apply overwrites a failed marker; avoids a finalize/apply race).diff --git a/.claude/rules/onboarding-company-templates.md b/.claude/rules/onboarding-company-templates.mdindex 7cc578e0ea..0195f03b9c 100644--- a/.claude/rules/onboarding-company-templates.md+++ b/.claude/rules/onboarding-company-templates.md@@ -1,14 +1,21 @@paths:- "packages/database/src/datasets/**"- "packages/jobs/src/inngest/functions/tasks/company-template.ts"+ - "packages/jobs/src/demo-planning.ts"+ - "packages/jobs/src/scripts/plan-company.ts"- "apps/erp/app/routes/onboarding+/industry.tsx"- "apps/erp/app/services/onboarding.server.ts"# Onboarding Company TemplatesOnboarding's third data choice — "Use a demo template" — fills a brand-new company with a-full industry story: items, BOMs, customers, quotes, orders, jobs, non-conformances,-change orders, ledger entries, workflows. The same data and the same insertion code back+full industry story: items, BOMs, customers, quotes, orders, returns, jobs, picking,+inspections, non-conformances, gauges, change orders, maintenance, training, timecards,+posted journals, payments, accounting periods, workflows and their run history, sales /+storage rules, approvals, customer portals, and a live shop floor whose schedule and+material plan come from a post-commit MRP + scheduler run — with every user-reachable+status of the major documents represented and every in-scope ERP / MES screen showing+rows. The same data and the same insertion code back`pnpm db:seed:dev`. **There is exactly one copy of both.**Grounded against `packages/database/src/datasets/`,@@ -18,10 +25,13 @@ Grounded against `packages/database/src/datasets/`,## The shape of itA **dataset** is data only — plain TypeScript literals, no SQL, no ids. It is a `Dataset`-object (`packages/database/src/datasets/types.ts`) with eleven slices: `foundation`,+object (`packages/database/src/datasets/types.ts`) with twelve slices: `foundation`,`items`, `inventory`, `sales`, `purchasing`, `production`, `quality`, `changeOrders`,-`accounting`, `workflows`, `planning`. Each slice lives in its own file under-`data/<key>/`, and `data/<key>/index.ts` assembles them.+`accounting`, `ops`, `workflows`, `planning`. Each slice lives in its own file under+`data/<key>/` (the items slice's CAD assembly additionally in `assembly.ts`), and+`data/<key>/index.ts` assembles them. `ops` (tier 10) holds maintenance schedules and+dispatches, trainings, timecards, suggestions and person notes; `workflows` also carries+the seeded run history (`runs`).The **tiers** are the engine — `tiers/01-foundation.ts` … `tiers/12-planning.ts`, run innumeric order. The ordering IS the contract: tier 4 can only build a sales order because@@ -63,6 +73,61 @@ asymmetry is deliberate: each wipe is paired with whatever repopulates after it.`wipeCompanyBusinessData` is NOT exported on its own — `wipeFirst` is the only way toreach it, so no caller can wipe without also re-seeding.+Because the datasets now seed posted/paid documents, the dataset wipe does these things+around its generic FK-null + topological delete, all inside the apply transaction:++0. **It refuses two company states before any write** (`assertWipeable`): intercompany+ customers/suppliers (`intercompanyCompanyId` set) and non-Draft `cardTransaction` rows.+ Both are trigger-protected and FK-linked to rows the wipe must delete, so the apply+ throws a `Seed: this company trades with other companies in its group …` /+ `Seed: this company has N posted or voided card transaction(s) …` error, which the+ template job writes to its marker as `failed`. Then it **voids posted document+ journals** (`reverseDocumentJournals`): every Posted journal of a `DOCUMENT_JOURNAL_SOURCES`+ type (invoices, payments, memos, receipts, shipments, `Inventory Adjustment`) whose+ lines — or `payment`/`memo.journalId` — point at a row it is about to delete gets a+ negated Posted `VOID …` entry dated today, the original left Posted, as the posting+ functions void.+1. **Non-Draft `salesInvoice` / `purchaseInvoice` rows are set back to `Draft`.** The+ `prevent_posted_{sales,purchase}_invoice_deletion` sync interceptors refuse deleting any+ other status and run even under `app.sync_in_progress`. This is a re-seed clear, not an+ app-level delete of a posted document.+2. **`invoiceSettlement`, `payment` and `memo` are deleted first.** Settlements hold+ ON DELETE RESTRICT FKs to their invoice/memo; payment and memo carry a+ customer-XOR-supplier CHECK the FK-nulling pass would violate.+3. The existing header-first deletes (invoices, orders, quotes, RFQs), MRP output, and+ the four model-only step-slide tables (`MODEL_SLIDE_TABLES`) — their+ `imagePath OR modelUploadId` CHECK cannot survive the FK-nulling pass.+4. After the delete pass, **orphaned customer/supplier org groups and customer/supplier+ type groups are removed** — the partner interceptors mint one `group` per partner and+ type, and `group` is preserved, so without this every re-apply left the previous+ story's partners in the group pickers. Bootstrap's root groups (kept by their+ `getGroupId` ids) and employee-type groups are untouched.++These deliberately survive a cross-dataset re-apply:++- **`journal` / `journalLine` / `accountingPeriod`** are in `PRESERVED_TABLES` (posted+ journals are trigger-immutable — `journal_posted_immutable` refuses even the UPDATE that+ nulling their `accountingPeriodId` would be, so the periods they point at must survive+ too; a company that posted real material issues before applying hit exactly that). Tier+ 09 adopts each month's existing period — by `(fiscalYear, periodNumber)`, else by+ `startDate`, since job-costing SQL mints periods with no fiscal numbers and the app+ resolves a period by date range — rather than insert an overlapping one. Tier 09 also+ adopts an existing authored entry by `journalEntryId` (`JE-SEED-00x`; a company's one+ Posted Opening Balance by source type) and skips it, so after applying dataset B over dataset A the journal+ text is still A's, and a re-seed will not pick up a journal you just edited in the+ data — delete those rows by hand first. Because journals survive, the `journalEntry`+ counter does too: `sql.ts` `PRESERVED_SEQUENCES` keeps `resetSequences` from rewinding+ it, and `nextJournalEntryId` skips any id a preserved journal already holds.+- **`customField` / `userAttributeCategory`** are preserved too (they may be the user's);+ tier 10 adopts its rows by name (category by `(companyId, name)`, attribute by+ `(category, name)`, value `ON CONFLICT (userAttributeId, userId)`, custom field+ `ON CONFLICT (table, name, companyId)`) and updates them to the dataset's values, never+ deleting. `webhook` is preserved and deliberately NOT seeded — its sync interceptor+ refuses the seed's session, and spoofing `service_role` to get past it was rejected.+- **`dimension` / `dimensionValue`** are `companyGroupId`-scoped, and a company wipe must+ never touch group-shared rows. Each distinct dataset applied adds its own name-keyed+ custom dimension (bounded at one per dataset); tier 09 looks it up before inserting.+`externalIntegrationMapping` is in that wipe's `PRESERVED_TABLES` because the wipe runsINSIDE the job whose own marker lives in that table. Without it the apply deleted the rowholding `snapshotPath`, the `ready` write re-inserted a bare one, and the revert then had@@ -78,8 +143,15 @@ pnpm db:seed:dev -- --email [email protected] --dataset satellite````--tiers 1,2,3` and `--skip-wipe` are dev-only conveniences (`--skip-wipe` just passes-`wipeFirst: false`). `bootstrap.ts` and `cli.ts` are dev-only; `wipe.ts` is now shared,-reachable only through `wipeFirst`.+`wipeFirst: false`). After the seed commits, the CLI runs the planning step below by+spawning `pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id>`+(`@carbon/database` cannot import `@carbon/planning`, which depends on it); `--skip-plan`+opts out, and a failed run only prints a warning with that command to re-run. Under+portless the spawn adds `NODE_EXTRA_CA_CERTS=~/.portless/ca.pem` when that file exists and+the variable is unset — without it the engines' supabase-js reads fail with+`SELF_SIGNED_CERT_IN_CHAIN`; run the script directly and you must set it yourself. `bootstrap.ts` and `cli.ts` are dev tooling — used by `seed-dev.ts`+and the drift check (`verify.ts` / `check-datasets.ts`), never by the `./datasets` export;+`wipe.ts` is shared, reachable only through `wipeFirst`.**Onboarding** — the browser flow. `industry.tsx` maps the chosen industry to a datasetkey with `datasetForIndustry(companyData.industryId)`, passes it to@@ -94,6 +166,31 @@ apply two templates at once, and calls the same `applyDataset`. It runs in Node`@carbon/jobs` — **not** in a Supabase edge function, and it does not go through anarchive, an upload, or an import.+### Planning runs after the commit++The planning screens (Material Planning, Demand Forecasts, Scheduling, Priorities, Resource+Planning, the MES schedule) are filled by the **real engines**, not seeded rows.+`planDemoCompany({ companyId, userId })` (`packages/jobs/src/demo-planning.ts`) calls+`runMrp(…, { type: "company", … })`, then `runLocationSchedule` for every location with a+Ready / In Progress / Paused job — the same calls the MRP cron and `api+/schedule.ts` make.+It must run after the seed commits (both engines read over PostgREST and open their own+transactions), and it never throws: it returns `{ mrp, schedule[] }` with `"ok"` or the+error message per step.++- **Template job** — a second `step.run("plan-template")` after `apply-template`,+ **non-fatal**: a failure is logged and, only while the marker still belongs to this run,+ written as `metadata.planningError` (a new apply resets it to `null`); marker status is+ never changed. On the `snapshot: false` path the marker is already cleared, so the+ failure is only logged (re-writing it would resurrect the marker as `running`). The+ 3-hourly MRP cron is the backstop — for MRP only.+- **Dev CLI** — the spawned `plan:company` script (above). `plan-company.ts` loads+ `demo-planning.ts` through `createRequire` so tsx compiles the graph as CJS; as ESM,+ `@carbon/planning`'s named imports from `@carbon/database` fail to link. It exits 0 even+ when a step fails, 1 only on bad arguments.++Engine output is therefore invisible to the drift check (`verify.ts` rolls back before any+engine could run), which is why the screen matrix below exists.+**Settings → Demo Data** — `apps/erp/app/routes/x+/settings+/demo-data.tsx`, gated by`canAccessBackups` (internal email or local dev), the same gate Backups uses. Lists everykey in `DATASETS` by its own `label`, read in the loader so a new dataset appears with no@@ -189,14 +286,87 @@ against `ctx.anchor` (today in the company's timezone). A template seeded next yorders from last month, not from 2025. The satellite offsets were derived against areference date of 2026-08-13, so every interval between two dates is preserved exactly.-`previousMonthEnd(anchor)` is the one exception-shaped helper: the depreciation period end-must land on a real month end, so it is derived rather than offset.+`previousMonthEnd(anchor)` and `monthBack(anchor, n)` are the exception-shaped helpers:+depreciation period ends, the 12 seeded `accountingPeriod` months and fixed-asset usage+logs must land on real month boundaries, so they are derived rather than offset.++Seeded periods are Closed at months −11/−10, Locked at −9 and Open after, so posting+dates are constrained: `dates.ts` exports `NOT_CLOSED_MIN_OFFSET` (−273, never in a Closed+month — the floor for Draft journals) and `OPEN_PERIOD_MIN_OFFSET` (−242, always in an+Open month — the floor for posted journals, payments, memos and disposals), both proven+for any anchor, and the validator enforces them.Never use JavaScript `Date` here, and never `CURRENT_DATE` in a tier's SQL — the anchor isthe company's day, the database session's is UTC, and the two disagree for a slice of every-day. Note there is NO automated guard: `@carbon/checks` scans `apps/mes/app/services`,-`packages/jobs/src`, `packages/database/supabase/functions` and the ERP module/route files,-none of which covers `packages/database/src/**`. This is convention only.+day. The pure validator checks offset VALUES (planning horizon, period floors, document+chronology) but nothing scans for `Date` / `CURRENT_DATE` usage: `@carbon/checks` covers+`apps/mes/app/services`, `packages/jobs/src`, `packages/database/supabase/functions` and+the ERP module/route files, none of which is `packages/database/src/**`. That part is+convention only.++## The shop floor lives at the plant++Every job and work center is at the dataset's plant, so tier 01 creates the **shifts at the+plant** (the work-center shift picker, the scheduler and Resource Planning read the work+centers' own location) and links them per work center (`FoundationData.workCenterShifts`).+It **upserts** the applying user's `employeeJob` (plant, title, department, shift, start+date — `ON CONFLICT ("id", "companyId") DO UPDATE`), because a company created outside+bootstrap has no row and the old UPDATE was a silent no-op; the MES and the ERP's+location-scoped pages read the user's default location from it. HQ keeps one work center+(`FoundationData.hqWorkCenter`, no shift or operations) with maintenance, plus HQ planning+rows, so lists that default to the first location are not empty.++No other person is ever created (no new global `user` rows) — the applying user is the one+employee every people screen shows. Volume: `validate.ts` requires `MIN_JOBS` (18) jobs per+dataset, every open job due within `OPEN_JOB_DUE_WINDOW` (−3…+21 days), open operations on+every plant work center and running work on several.++## Posted documents carry their downstream rows++Posted receipts and shipments, completed returns / transfers / picking lists / counts,+Paid and Partially Paid invoices, disposed assets and Posted journals are all seeded. The+posting edge functions cannot run inside the one seed transaction (and a post-commit call+would break all-or-nothing apply and the drift check's rollback), so each posted state is+**hand-authored together with the rows its posting path would have written** —+`itemLedger`, `invoiceSettlement`, tracked entities/activities, receipt/shipment lines —+in the same tier. Conventions, each mirroring the real code path:++- **Ledger rows copy the posting function's `entryType` / `documentType`**, not a guess:+ posted shipment `Negative Adjmt.` / `Sales Shipment`; posted receipt `Positive Adjmt.` /+ `Purchase Receipt`; completed RMA `Positive Adjmt.` / `Sales Return Receipt`; completed+ purchase return `Negative Adjmt.` / `Purchase Return Shipment`; picking and stock+ transfers `Transfer` / `Direct Transfer`; warehouse transfers `Transfer` /+ `Transfer Shipment` + `Transfer Receipt`; maintenance spare-part issue `Consumption` / `Maintenance+ Consumption`; scrapped lot `Negative Adjmt.` / `Scrap`. Posted PO receipts, SO+ shipments and scrapped lots carry GL and `costLedger` rows (below); other inventory+ postings (RMA receipts, returns, jobs, adjustments, opening stock) carry none — opening+ stock value sits in the authored Opening Balance entry.+- **Posted documents carry their journal, as with accounting enabled** — tier 09+ (`helpers/post-documents.ts`) journals every non-Draft sales/purchase invoice (plus a+ `VOID` entry for a Voided one), Posted memo, Posted payment (`payment.journalId` /+ `memo.journalId` set), posted PO receipt (plus its FIFO `costLedger` layer) and SO+ shipment (a `costLedger` draw on those layers, else `itemCost.unitCost` = the item's+ `standardCost`) and scrapped lot (post-inventory-adjustment's `Inventory Adjustment`+ shape, CR inventory / DR `scrapAccount`), whether or not `accountingEnabled` is on,+ through the edge functions'+ own builders (`buildSalesPostingLines`, `buildPaymentJournal`, `buildMemoJournal`) or+ copies of their inline shapes (`helpers/posting-journals.ts`). Ids come from the+ `journalEntry` sequence, which the wipe never rewinds. Payments stay USD at rate 1,+ `bankAccount` = `accountDefault.bankCashAccount`; `invoiceSettlement` rows ARE the+ allocation (validator: Paid = fully settled, Partially Paid = strictly between, others+ unsettled). Draft payments are unapplied and unjournaled. Memos tie to their invoice+ through a zero-cash Posted payment's credit settlement (`memoId` + `appliedViaPaymentId`).+- **Journals carry the adopted period's `accountingPeriodId`**. A Reversed manual entry+ is inserted Posted then flipped with `reversedById` (the one UPDATE the trigger allows).+ On re-apply the wipe voids every journal of a document it is about to delete (see the+ wipe list above).+- **Company exchange rates go to `exchangeRateOverride`**, never the platform-global+ `exchangeRate` table (a tenant template must not publish rates to every company). Rates+ are foreign units per 1 base unit (EUR ≈ 0.92).++The full decision log, with the code each convention was copied from, is+`.ai/specs/2026-09-22-demo-data-completeness.md` and+`.ai/specs/2026-09-23-demo-data-screen-coverage.md` → Autonomous Decisions.## Part thumbnails ship with the app@@ -225,16 +395,18 @@ viewer and step through in the assembler. It rides the exact mechanism the thumb`assets/<industryId>/models/<name>.glb` plus its `<name>.graph.json` sidecar are committed,`assets.ts` globs them alongside the SVGs, and `getDatasetAssetUrl` resolves the `_templates/`path before the storage proxy is ever reached. So there is **no bucket object, no upload, and no-assembler run at seed time** — `seedAssembly` in `tiers/06-production.ts` writes a `modelUpload`+assembler run at seed time** — `seedAssembly` in `tiers/02-items.ts` writes a `modelUpload`row whose `modelPath`/`glbPath`/`graphPath` are those bundled paths, `processingStatus` already-`Success`, then an `assemblyInstruction` + its `assemblyInstructionStep` rows, and finally points-`item.modelUploadId` at it.+`Success`, then an `assemblyInstruction` + its `assemblyInstructionStep` rows, points+`item.modelUploadId` at it, and links the item's Assembly `methodOperation` — before the method+is released, so quote lines (tier 04) and jobs (tier 06) both copy the link.-The data is `ProductionData.assembly` (`AssemblySpec`), authored in `data/<key>/assembly.ts`. It+The data is `ItemsData.assembly` (`AssemblySpec`), authored in `data/<key>/assembly.ts`. Itis **optional** — a dataset with a null `industryId` has nowhere to resolve a model from and isskipped. A step's `componentNodeIds` are real node ids read out of that exact `graph.json`; theyare the frozen join key between the graph, the GLB node extras and the step rows, so a step-naming an absent node renders but animates nothing. Regenerate them from the graph rather than+naming an absent node would render but animate nothing — the pure validator now fails it+(and a `componentCount` that disagrees with the graph) before commit. Regenerate them from the graph rather thanhand-editing, and never re-bake a model without re-deriving them — `nodeId` is a hash of thetessellation, so ANY change to the mesh (including a different `linearDeflection`) invalidatesevery id in the dataset.@@ -255,14 +427,24 @@ carries the paths across intact with nothing to re-upload.## Adding an industry-1. `data/<key>/` — one file per slice, mirroring `data/robotics/` (the newest and closest- model). All eleven slices are required; none may be empty.+1. `data/<key>/` — one file per slice, mirroring `data/satellite/` (the canonical pattern;+ the other three mirror its shape). All twelve slices, `ops` included, are required, and+ the new-shape fields are non-optional, so the compiler enforces parity. The validator+ additionally requires the listed arrays to be non-empty and every `COVERAGE` set+ in `validate.ts` (quote / sales-order / invoice / PO / receipt / job-op /+ NCR / change-order / journal / dispatch / workflow-run statuses and more) to be exhibited+ somewhere in the dataset — so a new dataset must cover the full status matrix, not just+ type-check.2. Register it in `DATASETS` in `datasets/index.ts`.3. Add `"<key>"` to `DatasetKey` in `types.ts`.4. Set `industryId` on the dataset to the matching `industry` row id, and add that row ina migration if it does not exist yet (`aerospace_satellite` was added by`20260813023744_add-aerospace-industry.sql`; the other three shipped in`20260617100002_onboarding-and-backups.sql`).+5. Add its workflow builder to `SEED_WORKFLOW_BUILDERS` (`tiers/workflow-definitions.ts`)+ so `packages/ee/src/workflows/seed-workflows.test.ts` validates its definitions.+6. Verify: `pnpm db:check:datasets -- --dataset <key>` (runs the validator, then applies it and checks+ the `coverage.ts` row-count floors).Volume is the coverage contract: match the existing datasets' row counts roughly, so everylist screen in the ERP has rows and every detail screen opens.@@ -274,15 +456,42 @@ than no card.## The drift check-The tiers build every INSERT from `information_schema` at runtime (`datasets/sql.ts`), so no-typecheck knows a dataset references a column — a migration that drops one breaks the demo-templates silently, and only when somebody seeds.-```bashpnpm db:check:datasets # all fourpnpm db:check:datasets -- --dataset motor # one```+`src/check-datasets.ts` runs two layers, in this order.++### Layer 1 — the pure validator (no database)++`validateDataset` (`datasets/validate.ts`) runs FIRST, before any connection is opened, and+needs nothing but the dataset literals. So it blocks the commit even when the local stack is+down — the DB-down skip below applies only to layer 2. It returns a list of violations, each+naming the slice and the offending key (`purchasing.lifecycleRfqs "prfq:star-tracker":+unknown item "ST-050-BOGUS"`), and on any violation the script prints them all, says "The demo+datasets are internally inconsistent", and exits 1 without touching the database.++What it checks, in summary: every string reference resolves inside the dataset (items,+parties, processes, work centers, shelves, document refs, bootstrap names such as scrap /+return reasons, NCR / change-order types, UoM codes, CoA account numbers); required arrays+are non-empty; every `COVERAGE` status/enum set is exhibited (an enum-backed set is the+generated DB enum minus its reasoned `except` entries, so a new enum value fails until a+dataset exhibits it); net on-hand per+(item, shelf) stays ≥ 0 after every authored movement (opening stock, counts, transfers,+posted receipts and shipments, returns, picks, scraps, maintenance issues); every journal+balances; invoice status agrees with its settlements (Paid fully settled, Partially Paid+strictly between, others unsettled); the EUR rate is in the "EUR per 1 USD" direction+(0.5–1, "is it inverted?"); document chronology and the period-offset floors; planning+horizon; assembly `componentNodeIds` exist in the bundled `graph.json`; inspection sample+statuses equal what the engine's rules derive.++### Layer 2 — apply and roll back (needs the database)++The tiers build every INSERT from `information_schema` at runtime (`datasets/sql.ts`), so no+typecheck knows a dataset references a column — a migration that drops one breaks the demo+templates silently, and only when somebody seeds.+It applies each dataset to a throwaway company and **always rolls back**(`datasets/verify.ts` — there is no `COMMIT` in that file, and the `ROLLBACK` is in a`finally`), so it writes nothing and is safe to point at your own development database. It is@@ -292,27 +501,61 @@ which is exactly what lets one caller commit and the other roll back.The scratch company is attributed to the `system` user, never a real developer's.+After the tiers and before the rollback, `findCoverageShortfalls` (`verify.ts`) counts every+table in `COVERAGE_FLOORS` (`datasets/coverage.ts` — 255 tables, measured across all four+datasets: floor = the smallest count any dataset produced, ×0.8 for volume tables) in one+`UNION ALL` query and fails the dataset with every shortfall listed as+`table: expected ≥ N, got M`. That is what catches a tier that silently writes nothing. Most+tables are counted by `companyId`; `COVERAGE_SCOPES` counts `dimension` / `dimensionValue`+by the scratch company's `companyGroupId` and the three favorites tables through their parent+document; the global `period` table is not counted. Removing data on purpose means lowering+the floor in the same change; adding a table means measuring and adding it.++Tier `ctx.log` lines are buffered per dataset and printed (the last 12) only when that+dataset fails, so the error is placed inside the tier sequence without drowning a green run.+It runs from `.husky/pre-commit` whenever a staged file is under `packages/database/`-(~3s for all four); `CARBON_SKIP_DATASET_CHECK=1` skips it. It exits 0 with a warning when-the database is unreachable, has no `user` table, or has no users — a hook that fails for-reasons you cannot fix is a hook you learn to bypass, and every one of those is the-developer's environment rather than drift.--Three honest limits. A hook is bypassable with `--no-verify`, so this is a safety net rather-than a gate (CI was declined on cost). It proves only that the datasets still APPLY — not-that they still produce the same rows; that is the baseline diff below. And it reads the-LIVE schema, so a migration you have written but not yet applied is invisible to it — commit-a column drop before `pnpm db:migrate` and the check passes green, which is exactly the state-the migration's own author is most likely to be in.+(a few seconds for all four); `CARBON_SKIP_DATASET_CHECK=1` skips both layers. Layer 2 exits+0 with a warning when the database is unreachable, has no `user` table, or has no users — a+hook that fails for reasons you cannot fix is a hook you learn to bypass, and every one of+those is the developer's environment rather than drift. Layer 1 never skips.++Honest limits. A hook is bypassable with `--no-verify`, so this is a safety net rather than+a gate (CI was declined on cost). With the database down only layer 1 runs, so schema drift+and floor shortfalls go unnoticed until someone commits with the stack up. Layer 2 proves the+datasets still APPLY and meet their floors — not that they produce the same rows; that is the+baseline diff below. And it reads the LIVE schema, so a migration you have written but not+yet applied is invisible to it — commit a column drop before `pnpm db:migrate` and the check+passes green, which is exactly the state the migration's own author is most likely to be in.+When layer 2 fails and migrations are pending on disk, the message says so first.## Verifying a change to the tiersThe tiers are shared, so a refactor that "looks fine" can silently drop rows. Seed, thendiff the printed `Seeded row counts` block against a known-good run, and check thestructural sums that counts alone would not catch (`methodMaterial` count + quantity sum,-`methodOperation` count + time sums, `salesOrderLine` count + quantity sum). Baselines-live in `.ai/runs/2026-08-13-seed-baseline.txt` (satellite, with structural sums in the-sibling `-structural.txt`), plus `-robotics-`, `-precision-` and `-motor-baseline.txt`.+`methodOperation` count + time sums, `salesOrderLine` count + quantity sum, `itemLedger`+count + quantity sum per entry/document type, per-journal balance). Current baselines:+`.ai/runs/2026-09-23-seed-baseline-{satellite,robotics,precision,motor}.txt`, with+satellite's structural sums (and the exact queries) in+`.ai/runs/2026-09-23-seed-baseline-satellite-structural.txt`. Journal amounts are signed by+the account's natural balance, so a raw Σ`amount` is non-zero by design; the per-journal+debit-minus-credit is what must be 0.++The status matrix — every DISTINCT status per document table after a satellite seed, each+absent value classified — is `.ai/runs/2026-09-23-demo-data-status-audit.txt`. Re-run the+same query when you add or remove a status. Enum-backed `COVERAGE` sets in+`validate.ts` pick up a new enum value on their own; for a text-typed set, add+the value by hand so it cannot silently disappear.++The screen-level reference is the **screen matrix**:+`.ai/runs/2026-09-23-screen-matrix-{satellite,robotics,precision,motor}.txt` — one count+query per ERP/MES screen data source, with the screen's own filters, against a real seeded+AND planned company (so it covers the engine output the floors cannot), each row PASS /+FAIL / EXCLUDED with the exclusion's reason. All four read FAIL 0. Its script lived in a+session scratchpad and is not committed, so rebuild the checks from those rows when you+change what a screen shows. The status audit answers "is every status present", the matrix+answers "does every screen have rows".## What is NOT how this worksdiff --git a/.claude/rules/workflow-database-migration.md b/.claude/rules/workflow-database-migration.mdindex ccff90c143..2c286fdffc 100644--- a/.claude/rules/workflow-database-migration.md+++ b/.claude/rules/workflow-database-migration.md@@ -119,6 +119,20 @@ Applies pending migrations against the worktree's local DB and (only if newmigrations were applied) regenerates DB types + swagger. To regenerate typesalone, `pnpm db:types`. **Do NOT run `npm run db:build` — it does not exist.**+### 6. Update the demo data++The four demo datasets (`packages/database/src/datasets/`) must keep showing every+screen. When a migration adds, renames or drops a table or column, or changes a status+enum or CHECK constraint:++- **New table or feature a user can see:** add realistic rows to all four datasets+ (`data/<key>/`, plus the tier that inserts them), and a floor in `datasets/coverage.ts`.+- **Renamed/dropped column or table:** update the tier and data that write it.+- **New enum value a user can reach:** make it appear in the demo data.++Then run `pnpm db:check:datasets` — it applies every dataset and rolls back, and the+pre-commit hook runs it anyway. Details: `onboarding-company-templates.md`.+## Checklist- [ ] File created with `pnpm db:migrate:new <name>` (HHMMSS not `000000`)@@ -133,3 +147,4 @@ alone, `pnpm db:types`. **Do NOT run `npm run db:build` — it does not exist.**(`packages/jobs/src/backups/renames.ts`) — new name, or `null` if dropped with its feature- [ ] Zod validators updated in `{module}.models.ts`- [ ] Applied locally with `pnpm db:migrate` (regenerates types) — never `db:build`+- [ ] Demo data updated for the new/changed tables, and `pnpm db:check:datasets` ✓×4diff --git a/.claude/rules/workflow-run-history.md b/.claude/rules/workflow-run-history.mdindex 540dd006ed..5191f8fb2d 100644--- a/.claude/rules/workflow-run-history.md+++ b/.claude/rules/workflow-run-history.md@@ -89,8 +89,16 @@ The `detail` JSON shape is `NodeDetail` (`packages/ee/src/workflows/runtime/typePass 3 runs **before** pass 4 so `compactedAt` is always set on the `workflowRun` row before its step rows are deleted. The UI uses `run.compactedAt !== null` to distinguish "steps purged" from "run has no steps yet".-Age is always `COALESCE("completedAt", "createdAt")` — `Blocked` and `Skipped` runs never set-`completedAt`, and `workflowRun_retention_idx` is the index for it.+Age is always `COALESCE("completedAt", "createdAt")`, and `workflowRun_retention_idx` is the+index for it. Some terminal runs are INSERTED terminal and never get `completedAt` (or+`startedAt`): **`Blocked`** runs (the matcher's loop guard, `planRuns` in `matcher.ts`) and+the scheduler's **`Skipped`** runs (`TOO_LATE`, `PREVIOUS_RUN_ACTIVE` in `scheduler.ts`), both+written by `insertRunsAndBuildEvents` with no timestamp. A `Skipped` run settled at the engine's+`load` step (`NOT_ENTITLED`, `UNPUBLISHED` in `engine/execute.ts`) goes through `finishRun`+(`engine/log.ts`), which ALWAYS sets `completedAt` and `durationMs` — but `claimRun` never ran,+so its `startedAt` stays null. The migration's own comment+(`20260810100200_workflow-run-history.sql`: "Blocked and Skipped runs never set completedAt")+is wrong for that load-time skip; the COALESCE covers both shapes either way.Every pass selects `ORDER BY` that age ascending, so a backlog drains oldest-first instead ofre-reading the same page each night. Each pass must also be able to *leave* its own candidatediff --git a/apps/erp/app/modules/agent/kb/docs/platform/demo-data.md b/apps/erp/app/modules/agent/kb/docs/platform/demo-data.mdindex 7df3d58a51..43e835c3e0 100644--- a/apps/erp/app/modules/agent/kb/docs/platform/demo-data.md+++ b/apps/erp/app/modules/agent/kb/docs/platform/demo-data.md@@ -2,7 +2,9 @@> Fill a company with a realistic industry story, so every screen has something in it, and put back exactly what was there before with one click.-Demo data fills a company with a full, coherent industry story: items with BOMs and routings, customers and suppliers, quotes, orders, jobs, inspections, change orders and ledger entries. Every list screen has rows and every detail screen opens, which makes it the fastest way to explore Carbon, demo it, or test against realistic data. You apply it from **Settings → Demo Data**, or pick it at sign-up as **"Use a demo template"**.+Demo data fills a company with a full, coherent industry story: items with BOMs and routings, customers and suppliers, quotes, orders and returns, jobs and picking lists, inspections, non-conformances and gauges, change orders, maintenance and training, timecards, the accounting side with posted journals, payments and accounting periods, and a busy shop floor with its schedule and material plan.++Every list screen has rows and every detail screen opens, which makes it the fastest way to explore Carbon, demo it, or test against realistic data. You apply it from **Settings → Demo Data**, or pick it at sign-up as **"Use a demo template"**.## The templates@@ -15,12 +17,28 @@ Each template tells one industry's story, end to end, across sales, purchasing,Every seeded date is relative to the day you apply the template, so the company always looks live: recent orders, jobs in progress, upcoming due dates. Parts come with real thumbnails, and each industry includes a 3D assembly you can open in the viewer.+Records show up in the statuses you meet in daily work, not only the happy path. You get lost and expired quotes, partly shipped orders, paid and partially paid invoices, voided receipts, closed accounting periods, and workflows with succeeded, failed and skipped runs in their history.++The stock movements and payment settlements behind those statuses are filled in too, so on-hand quantities and invoice balances agree. Every posted invoice, payment, memo, receipt and shipment also carries its journal entry, so the income statement, balance sheet and receivables aging show real numbers.++The shop floor looks like a working day. Jobs are due over the next three weeks across every work center, some operations are running right now, and a few jobs finished recently.++You are the employee on the floor: you get a job, a shift, people assignments and an open time card. Sales and storage rules, purchase approval rules with requests waiting for you, and customer portals are set up as well. The templates add no uploaded files, so `docs/reference/documents` starts empty.+Demo data is seeded fresh from Carbon's own dataset definitions each time, not imported from a stored backup file. That's why it always matches the current version of the app. To stand a company up from another company's actual data, use a `docs/platform/backups` instead.## Apply a templateOn **Settings → Demo Data**, the "Apply a demo template" card lists the templates; select **"Apply"** on one. It is safe to try on a company that already has data: Carbon saves a copy of your current data first, then replaces it with the demo story. The page shows each phase as it runs, from **"Saving a copy of your current data"** through **"Adding demo records"**, and it keeps running if you leave the page.+Right after the demo data is applied, Carbon runs MRP and scheduling once over the company in the background. That run is what fills Material Planning, Demand Forecasts, Scheduling and Priorities, so those screens can take a moment longer than the rest. If it fails, the demo data still stands and MRP catches up on its regular run every three hours.++Two kinds of records can never be deleted, so Carbon refuses to apply a template over them and writes nothing.++A company with intercompany customers or suppliers fails with "Seed: this company trades with other companies in its group (N intercompany customer/supplier record(s)). Demo data can only be applied to a company without intercompany partners."++A company with posted card transactions fails with "Seed: this company has N posted or voided card transaction(s), which cannot be deleted. Demo data can only be applied to a company without posted card transactions."+When it finishes, the **"Demo data applied"** card asks you to decide:- **"Keep"** accepts the demo data.@@ -59,5 +77,20 @@ Only one demo-data change can be open per company. Resolve the pending one first### Applying failed with an errorApplying is all-or-nothing: a failure writes no rows and your data is unchanged. The card shows the job's error next to "Failed"; Dismiss clears it, and you can apply again.+### Applying failed with "Seed: this company trades with other companies in its group"+Expected refusal. The company has customers or suppliers linked to another company in its group (intercompany partners), which the demo-data wipe cannot remove. Nothing was written. Apply the template to a company without intercompany partners.++### Applying failed with "Seed: this company has N posted or voided card transaction(s)"+Expected refusal. Posted and voided card transactions cannot be deleted, so the demo-data wipe cannot clear the company. Nothing was written. Apply the template to a company without posted card transactions.++### Material Planning, Scheduling or Priorities are empty right after applying+Planning runs as a separate background step once the demo data is committed: MRP for the company, then scheduling for every location with Ready, In Progress or Paused jobs. Give it a moment. If that step failed, the demo data stays and MRP fills in on its regular run every three hours.++### The Webhooks, API keys or Audit log screens are empty after applying+Expected. Templates never seed credentials, webhooks or audit history, and applying a template leaves any existing webhooks and API keys in place.++### The Documents list is empty after applying a template+Expected. Templates seed records, not files: no uploads are added, so Documents and file attachments stay empty. Part thumbnails and the 3D assembly ship with the app rather than as uploaded files.+### The demo dates look recent — is that real activity?Yes, by design: every seeded date is relative to the day the template was applied, so the company always looks live with recent orders and jobs in progress.diff --git a/apps/erp/app/modules/agent/kb/manifest.json b/apps/erp/app/modules/agent/kb/manifest.jsonindex 98cc089b1f..1281c534e3 100644--- a/apps/erp/app/modules/agent/kb/manifest.json+++ b/apps/erp/app/modules/agent/kb/manifest.json@@ -192,6 +192,11 @@"The apply or revert looks stuck","Can't apply a second template","Applying failed with an error",+ "Applying failed with \"Seed: this company trades with other companies in its group\"",+ "Applying failed with \"Seed: this company has N posted or voided card transaction(s)\"",+ "Material Planning, Scheduling or Priorities are empty right after applying",+ "The Webhooks, API keys or Audit log screens are empty after applying",+ "The Documents list is empty after applying a template","The demo dates look recent — is that real activity?"]},diff --git a/apps/erp/app/modules/settings/backups.service.ts b/apps/erp/app/modules/settings/backups.service.tsindex 0d296af91e..60e8d63ed5 100644--- a/apps/erp/app/modules/settings/backups.service.ts+++ b/apps/erp/app/modules/settings/backups.service.ts@@ -381,6 +381,9 @@ export type CompanyTemplateRun = {/** Whether a pre-apply snapshot exists yet — the UI offers a revert retry on a* stalled run only when there is actually something to put back. */hasSnapshot: boolean;+ reason: "scope-violations" | null;+ violations: ScopeViolationSummary[];+ violationRowsByTable: RowsByTable[];};/**@@ -416,6 +419,9 @@ export async function getCompanyTemplateRun(error?: string;progress?: { phase: string; done: number; total: number } | null;snapshotPath?: string;+ reason?: "scope-violations" | null;+ violations?: ScopeViolationSummary[] | null;+ violationRowsByTable?: RowsByTable[] | null;};// Only whether a snapshot EXISTS is projected, never where — the job owns its@@ -428,7 +434,10 @@ export async function getCompanyTemplateRun(startedAt: meta.startedAt ?? marker.data.createdAt,error: meta.error ?? null,progress: meta.progress ?? null,- hasSnapshot: Boolean(meta.snapshotPath)+ hasSnapshot: Boolean(meta.snapshotPath),+ reason: meta.reason ?? null,+ violations: meta.violations ?? [],+ violationRowsByTable: meta.violationRowsByTable ?? []},error: null};diff --git a/apps/erp/app/modules/settings/ui/Backups/PurgeCorruptedRowsModal.tsx b/apps/erp/app/modules/settings/ui/Backups/PurgeCorruptedRowsModal.tsxnew file mode 100644index 0000000000..8bbd44bdd6--- /dev/null+++ b/apps/erp/app/modules/settings/ui/Backups/PurgeCorruptedRowsModal.tsx@@ -0,0 +1,78 @@+import {+ Button,+ Modal,+ ModalBody,+ ModalContent,+ ModalFooter,+ ModalHeader,+ ModalOverlay,+ ModalTitle+} from "@carbon/react";+import { Plural, Trans } from "@lingui/react/macro";+import type { ReactNode } from "react";+import { type RowsByTable, totalScopeRows } from "../../backups.service";++// Shared by a failed restore and a failed demo data apply, whose safety snapshots+// refuse on the same out-of-scope rows. Callers own the differing copy and the submit.+export function PurgeCorruptedRowsModal({+ rowsByTable,+ description,+ confirmLabel,+ onConfirm,+ onCancel+}: {+ rowsByTable: RowsByTable[];+ description: ReactNode;+ confirmLabel: ReactNode;+ onConfirm: () => void;+ onCancel: () => void;+}) {+ // Distinct ROWS, not per-edge violations — a row escaping scope through three+ // of its FKs is one row, and this number sits on an irreversible-delete button.+ const purgeRowCount = totalScopeRows(rowsByTable);+ return (+ <Modal+ open+ onOpenChange={(open) => {+ if (!open) onCancel();+ }}+ >+ <ModalOverlay />+ <ModalContent>+ <ModalHeader>+ <ModalTitle>+ <Plural+ value={purgeRowCount}+ one="Permanently delete # row?"+ other="Permanently delete # rows?"+ />+ </ModalTitle>+ </ModalHeader>+ <ModalBody>+ <p className="text-sm text-muted-foreground">{description}</p>+ {/* Per TABLE, not per FK edge: the title counts distinct rows,+ and a per-edge list beside it would show larger numbers for+ the same delete. */}+ <ul className="mt-3 flex flex-col gap-1 text-xs font-mono">+ {rowsByTable.map((t) => (+ <li key={t.table} className="flex justify-between gap-3">+ <span className="break-all">{t.table}</span>+ <span className="tabular-nums shrink-0">+ {t.rows.toLocaleString()}+ </span>+ </li>+ ))}+ </ul>+ </ModalBody>+ <ModalFooter>+ <Button variant="secondary" onClick={onCancel}>+ <Trans>Cancel</Trans>+ </Button>+ <Button variant="destructive" onClick={onConfirm}>+ {confirmLabel}+ </Button>+ </ModalFooter>+ </ModalContent>+ </Modal>+ );+}diff --git a/apps/erp/app/modules/settings/ui/Backups/index.ts b/apps/erp/app/modules/settings/ui/Backups/index.tsindex 92a6c6af12..583d3cee72 100644--- a/apps/erp/app/modules/settings/ui/Backups/index.ts+++ b/apps/erp/app/modules/settings/ui/Backups/index.ts@@ -4,5 +4,6 @@ export * from "./BackupProgressModal";export * from "./BackupSourcePicker";export * from "./ExcludedRowsInfo";export * from "./format";+export * from "./PurgeCorruptedRowsModal";export * from "./RestoreDisclosure";export * from "./RestoreReviewRow";diff --git a/apps/erp/app/modules/settings/ui/DemoData/TemplateReviewRow.tsx b/apps/erp/app/modules/settings/ui/DemoData/TemplateReviewRow.tsxindex 79eb82b5c7..dccc139b16 100644--- a/apps/erp/app/modules/settings/ui/DemoData/TemplateReviewRow.tsx+++ b/apps/erp/app/modules/settings/ui/DemoData/TemplateReviewRow.tsx@@ -8,13 +8,18 @@ import {HStack,VStack} from "@carbon/react";-import { Trans, useLingui } from "@lingui/react/macro";+import { Plural, Trans, useLingui } from "@lingui/react/macro";import { useEffect, useState } from "react";import { useFetcher } from "react-router";import { DateTime } from "~/components";import type { CompanyTemplateRun } from "~/modules/settings";+import {+ ExcludedRowsInfo,+ PurgeCorruptedRowsModal+} from "~/modules/settings/ui/Backups";import { formatElapsed } from "~/modules/settings/ui/Backups/format";import { path } from "~/utils/path";+import { totalScopeRows } from "../../backups.service";/** A run with no completion after this long is treated as stalled, and offered a* revert retry — the job's own crash handler can't fire if the process died. */@@ -23,13 +28,16 @@ const STALLED_AFTER_MS = 5 * 60 * 1000;export function TemplateReviewRow({run,datasetLabel,- onResolve+ onResolve,+ onPurgeAndApply}: {run: CompanyTemplateRun;datasetLabel: string | null;/** Hides the row for a keep/dismiss, which clear the marker asynchronously —* a revert must NOT use this: it keeps running, and the row is what reports it. */onResolve: (templateRunId: string) => void;+ /** The route submits, so it can put the run back if the purge is refused. */+ onPurgeAndApply: () => void;}) {const { t } = useLingui();const fetcher = useFetcher();@@ -45,6 +53,9 @@ export function TemplateReviewRow({);const isReverting = run.status === "reverting" || revertRequestedAt !== null;const busy = run.status === "running" || isReverting;+ const scopeViolations =+ run.status === "failed" && run.reason === "scope-violations";+ const [confirmPurge, setConfirmPurge] = useState(false);useEffect(() => {// Any status but `ready` means the server has taken over the story —// including `failed`, where the optimistic spinner must not hide the error.@@ -125,7 +136,28 @@ export function TemplateReviewRow({<span className="text-sm font-medium truncate">{datasetLabel ?? run.datasetKey ?? t`Demo data`}</span>- {run.status === "failed" ? (+ {scopeViolations ? (+ // Exact tables and the raw error live in the popover, as in RestoreReviewRow.+ <span className="break-words text-xs text-destructive">+ <Plural+ value={totalScopeRows(run.violationRowsByTable)}+ one="# row links to data outside this company, so a safety copy of your current data can't be made."+ other="# rows link to data outside this company, so a safety copy of your current data can't be made."+ />{" "}+ <ExcludedRowsInfo+ excludedRows={run.violations}+ title={<Trans>Why this failed</Trans>}+ description={+ <Trans>+ Each line is a link from this company's data to a row it+ doesn't own. Removing those rows lets the demo data+ apply.+ </Trans>+ }+ technical={run.error}+ />+ </span>+ ) : run.status === "failed" ? (<span className="text-xs text-destructive">{t`Failed`} — {run.error ?? t`unknown error`}</span>@@ -161,6 +193,15 @@ export function TemplateReviewRow({</Button></>)}+ {scopeViolations && (+ <Button+ variant="destructive"+ isDisabled={submitting}+ onClick={() => setConfirmPurge(true)}+ >+ <Trans>Remove corrupted data and apply</Trans>+ </Button>+ )}{run.status === "failed" && (<Buttonvariant="secondary"@@ -197,6 +238,27 @@ export function TemplateReviewRow({</HStack></HStack>+ {confirmPurge && (+ <PurgeCorruptedRowsModal+ rowsByTable={run.violationRowsByTable}+ description={+ <Trans>+ These rows link to data outside this company, so a safety copy+ of your current data can't be made. Deleting them cannot be+ undone. If they turn out to be shared with other companies in+ this group, nothing is deleted and the demo data isn't+ applied.+ </Trans>+ }+ confirmLabel={<Trans>Delete and apply</Trans>}+ onCancel={() => setConfirmPurge(false)}+ onConfirm={() => {+ setConfirmPurge(false);+ onPurgeAndApply();+ }}+ />+ )}+{stalled && (<span className="text-xs text-muted-foreground"><Trans>diff --git a/apps/erp/app/routes/x+/settings+/backups.tsx b/apps/erp/app/routes/x+/settings+/backups.tsxindex 3c76e1db9a..cdee5f538a 100644--- a/apps/erp/app/routes/x+/settings+/backups.tsx+++ b/apps/erp/app/routes/x+/settings+/backups.tsx@@ -23,13 +23,6 @@ import {CardTitle,Heading,HStack,- Modal,- ModalBody,- ModalContent,- ModalFooter,- ModalHeader,- ModalOverlay,- ModalTitle,ScrollArea,toast,useDisclosure,@@ -79,6 +72,7 @@ import {formatBackupName,IncludeStorageChoice,JobProgressModal,+ PurgeCorruptedRowsModal,RestoreDisclosure,RestoreIncludeChoice,RestoreReviewRow@@ -554,9 +548,6 @@ export default function BackupsRoute() {const [purgeRun, setPurgeRun] = useState<(typeof visibleRestoreRuns)[number] | null>(null);- // Distinct ROWS, not per-edge violations — a row escaping scope through three- // of its FKs is one row, and this number sits on an irreversible-delete button.- const purgeRowCount = totalScopeRows(purgeRun?.violationRowsByTable ?? []);const exportChoices = useExportChoices();// A failed run's label and include setting seed the form, so "Skip corrupted// rows and retry" reuses what that run asked for and the person can see it.@@ -735,70 +726,30 @@ export default function BackupsRoute() {)}{purgeRun && (- <Modal- open- onOpenChange={(open) => {- if (!open) setPurgeRun(null);+ <PurgeCorruptedRowsModal+ rowsByTable={purgeRun.violationRowsByTable}+ description={+ <Trans>+ These rows link to data outside this company, so a safety copy+ of your current data can't be made. Deleting them cannot be+ undone. If they turn out to be shared with other companies in+ this group, nothing is deleted and the restore doesn't start.+ </Trans>+ }+ confirmLabel={<Trans>Delete and restore</Trans>}+ onCancel={() => setPurgeRun(null)}+ onConfirm={() => {+ fetcher.submit(+ {+ intent: "purgeAndRestore",+ restoreRunId: purgeRun.restoreRunId+ },+ { method: "post" }+ );+ resolveRun(purgeRun.restoreRunId);+ setPurgeRun(null);}}- >- <ModalOverlay />- <ModalContent>- <ModalHeader>- <ModalTitle>- <Plural- value={purgeRowCount}- one="Permanently delete # row?"- other="Permanently delete # rows?"- />- </ModalTitle>- </ModalHeader>- <ModalBody>- <p className="text-sm text-muted-foreground">- <Trans>- These rows link to data outside this company, so a safety- copy of your current data can't be made. Deleting them- cannot be undone. If they turn out to be shared with other- companies in this group, nothing is deleted and the restore- doesn't start.- </Trans>- </p>- {/* Per TABLE, not per FK edge: the title counts distinct rows,- and a per-edge list beside it would show larger numbers for- the same delete. */}- <ul className="mt-3 flex flex-col gap-1 text-xs font-mono">- {purgeRun.violationRowsByTable.map((t) => (- <li key={t.table} className="flex justify-between gap-3">- <span className="break-all">{t.table}</span>- <span className="tabular-nums shrink-0">- {t.rows.toLocaleString()}- </span>- </li>- ))}- </ul>- </ModalBody>- <ModalFooter>- <Button variant="secondary" onClick={() => setPurgeRun(null)}>- <Trans>Cancel</Trans>- </Button>- <Button- variant="destructive"- onClick={() => {- fetcher.submit(- {- intent: "purgeAndRestore",- restoreRunId: purgeRun.restoreRunId- },- { method: "post" }- );- resolveRun(purgeRun.restoreRunId);- setPurgeRun(null);- }}- >- <Trans>Delete and restore</Trans>- </Button>- </ModalFooter>- </ModalContent>- </Modal>+ />)}{active && (diff --git a/apps/erp/app/routes/x+/settings+/demo-data.tsx b/apps/erp/app/routes/x+/settings+/demo-data.tsxindex b97927e2e3..e897fda1ac 100644--- a/apps/erp/app/routes/x+/settings+/demo-data.tsx+++ b/apps/erp/app/routes/x+/settings+/demo-data.tsx@@ -3,14 +3,21 @@ import { assertIsPost, error } from "@carbon/auth";import { requirePermissions } from "@carbon/auth/auth.server";import { flash } from "@carbon/auth/session.server";import { DATASETS, datasetKeys } from "@carbon/database/datasets";-import { Heading, VStack } from "@carbon/react";+import { Heading, toast, VStack } from "@carbon/react";import { msg } from "@lingui/core/macro";import { Trans } from "@lingui/react/macro";-import { useEffect, useMemo, useState } from "react";+import { useEffect, useMemo, useRef, useState } from "react";import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";-import { data, redirect, useLoaderData, useRevalidator } from "react-router";+import {+ data,+ redirect,+ useFetcher,+ useLoaderData,+ useRevalidator+} from "react-router";import type { CompanyTemplateRun } from "~/modules/settings";import { getCompanyTemplateRun } from "~/modules/settings";+import { purgeCorruptedRows } from "~/modules/settings/backups.server";import {finalizeCompanyTemplate,revertCompanyTemplate,@@ -149,6 +156,66 @@ export async function action({ request }: ActionFunctionArgs) {}}+ // Mirrors Backups' purgeAndRestore. No finalize first: apply overwrites a+ // failed marker, and a snapshot-guard failure never recorded a snapshot.+ case "purgeAndApply": {+ const datasetKey = String(formData.get("datasetKey") ?? "");+ const current = await getCompanyTemplateRun(client, companyId);+ const failed = current.data;+ if (+ !failed ||+ !templateRunId ||+ failed.templateRunId !== templateRunId ||+ failed.status !== "failed" ||+ failed.reason !== "scope-violations" ||+ failed.datasetKey !== datasetKey ||+ !datasetKeys().includes(datasetKey as never)+ ) {+ return {+ success: false,+ message: "This demo data change can't be retried this way"+ };+ }++ // The delete commits on its own; the apply is enqueued after. Two steps,+ // not one transaction, so the messages say WHICH half happened.+ let deleted: Array<{ table: string; rows: number }>;+ try {+ ({ deleted } = await purgeCorruptedRows(companyId));+ } catch (err) {+ return {+ success: false,+ message:+ err instanceof Error+ ? err.message+ : "Failed to remove corrupted data — nothing was deleted"+ };+ }++ const rows = deleted.reduce((sum, d) => sum + d.rows, 0);+ try {+ const startedRunId = await startCompanyTemplate({+ companyId,+ userId,+ datasetKey+ });+ return {+ success: true,+ message: `Removed ${rows} row${rows === 1 ? "" : "s"} — applying demo data`,+ templateRunId: startedRunId+ };+ } catch (err) {+ return {+ success: false,+ message:+ `Removed ${rows} row${rows === 1 ? "" : "s"}, but the demo data did not start` ++ ` — apply it again. (${+ err instanceof Error ? err.message : "unknown error"+ })`+ };+ }+ }+default:return { success: false, message: "Unknown action" };}@@ -167,13 +234,16 @@ export default function DemoDataRoute() {// marker written yet — without this the button's spinner vanishes and the page// looks like nothing happened. Stands in until the loader sees a real run.const [pendingApplyKey, setPendingApplyKey] = useState<string | null>(null);- const hasRun = run !== null;+ // A run the user already resolved (a failed run being purged and re-applied)+ // doesn't count — the optimistic row stands in until the NEW run appears.+ const hasLiveRun =+ run !== null && !resolvedRunIds.includes(run.templateRunId);useEffect(() => {- if (hasRun) setPendingApplyKey(null);- }, [hasRun]);+ if (hasLiveRun) setPendingApplyKey(null);+ }, [hasLiveRun]);const optimisticRun: CompanyTemplateRun | null =- !hasRun && pendingApplyKey !== null+ !hasLiveRun && pendingApplyKey !== null? {templateRunId: "",status: "running",@@ -181,7 +251,10 @@ export default function DemoDataRoute() {startedAt: null,error: null,progress: null,- hasSnapshot: false+ hasSnapshot: false,+ reason: null,+ violations: [],+ violationRowsByTable: []}: null;@@ -201,6 +274,43 @@ export default function DemoDataRoute() {return () => clearInterval(id);}, [active, revalidator]);+ const purgeFetcher = useFetcher<{ success: boolean; message: string }>();+ const [purgingRun, setPurgingRun] = useState<CompanyTemplateRun | null>(null);+ // The response a previous purge left on the fetcher — ignored, so a retry+ // doesn't settle on the old result before its own arrives.+ const staleResult = useRef<typeof purgeFetcher.data>(undefined);+ const purgeAndApply = (failed: CompanyTemplateRun) => {+ staleResult.current = purgeFetcher.data;+ setPurgingRun(failed);+ setResolvedRunIds((prev) => [...prev, failed.templateRunId]);+ setPendingApplyKey(failed.datasetKey);+ purgeFetcher.submit(+ {+ intent: "purgeAndApply",+ templateRunId: failed.templateRunId,+ datasetKey: failed.datasetKey ?? ""+ },+ { method: "post", action: path.to.demoData }+ );+ };+ const purgeResult =+ purgeFetcher.state === "idle" && purgeFetcher.data !== staleResult.current+ ? purgeFetcher.data+ : null;+ useEffect(() => {+ if (!purgeResult || !purgingRun) return;+ if (purgeResult.success) {+ toast.success(purgeResult.message);+ } else {+ toast.error(purgeResult.message);+ setResolvedRunIds((prev) =>+ prev.filter((id) => id !== purgingRun.templateRunId)+ );+ setPendingApplyKey(null);+ }+ setPurgingRun(null);+ }, [purgeResult, purgingRun]);+const datasetLabel = useMemo(() => datasets.find((d) => d.key === pending?.datasetKey)?.label ?? null,[datasets, pending]@@ -225,6 +335,7 @@ export default function DemoDataRoute() {run={pending}datasetLabel={datasetLabel}onResolve={(id) => setResolvedRunIds((prev) => [...prev, id])}+ onPurgeAndApply={() => purgeAndApply(pending)}/>)}diff --git a/docs/content/docs/platform/demo-data.mdx b/docs/content/docs/platform/demo-data.mdxindex 69d6bd8a36..2f5f712a60 100644--- a/docs/content/docs/platform/demo-data.mdx+++ b/docs/content/docs/platform/demo-data.mdx@@ -3,7 +3,9 @@ title: Demo datadescription: Fill a company with a realistic industry story, so every screen has something in it, and put back exactly what was there before with one click.----Demo data fills a company with a full, coherent industry story: items with BOMs and routings, customers and suppliers, quotes, orders, jobs, inspections, change orders and ledger entries. Every list screen has rows and every detail screen opens, which makes it the fastest way to explore Carbon, demo it, or test against realistic data. You apply it from **Settings → Demo Data**, or pick it at sign-up as **"Use a demo template"**.+Demo data fills a company with a full, coherent industry story: items with BOMs and routings, customers and suppliers, quotes, orders and returns, jobs and picking lists, inspections, non-conformances and gauges, change orders, maintenance and training, timecards, the accounting side with posted journals, payments and accounting periods, and a busy shop floor with its schedule and material plan.++Every list screen has rows and every detail screen opens, which makes it the fastest way to explore Carbon, demo it, or test against realistic data. You apply it from **Settings → Demo Data**, or pick it at sign-up as **"Use a demo template"**.## The templates@@ -18,6 +20,14 @@ Each template tells one industry's story, end to end, across sales, purchasing,Every seeded date is relative to the day you apply the template, so the company always looks live: recent orders, jobs in progress, upcoming due dates. Parts come with real thumbnails, and each industry includes a 3D assembly you can open in the viewer.+Records show up in the statuses you meet in daily work, not only the happy path. You get lost and expired quotes, partly shipped orders, paid and partially paid invoices, voided receipts, closed accounting periods, and workflows with succeeded, failed and skipped runs in their history.++The stock movements and payment settlements behind those statuses are filled in too, so on-hand quantities and invoice balances agree. Every posted invoice, payment, memo, receipt and shipment also carries its journal entry, so the income statement, balance sheet and receivables aging show real numbers.++The shop floor looks like a working day. Jobs are due over the next three weeks across every work center, some operations are running right now, and a few jobs finished recently.++You are the employee on the floor: you get a job, a shift, people assignments and an open time card. Sales and storage rules, purchase approval rules with requests waiting for you, and customer portals are set up as well. The templates add no uploaded files, so [Documents](/docs/reference/documents) starts empty.+<Callout type="note" title="A template is not a backup">Demo data is seeded fresh from Carbon's own dataset definitions each time, not imported from a stored backup file. That's why it always matches the current version of the app. To stand a company up from another company's actual data, use a [backup](/docs/platform/backups) instead.</Callout>@@ -26,6 +36,16 @@ Demo data is seeded fresh from Carbon's own dataset definitions each time, not iOn **Settings → Demo Data**, the "Apply a demo template" card lists the templates; select **"Apply"** on one. It is safe to try on a company that already has data: Carbon saves a copy of your current data first, then replaces it with the demo story. The page shows each phase as it runs, from **"Saving a copy of your current data"** through **"Adding demo records"**, and it keeps running if you leave the page.+Right after the demo data is applied, Carbon runs MRP and scheduling once over the company in the background. That run is what fills Material Planning, Demand Forecasts, Scheduling and Priorities, so those screens can take a moment longer than the rest. If it fails, the demo data still stands and MRP catches up on its regular run every three hours.++<Callout type="warn" title="Some companies can't take demo data">+Two kinds of records can never be deleted, so Carbon refuses to apply a template over them and writes nothing.++A company with intercompany customers or suppliers fails with "Seed: this company trades with other companies in its group (N intercompany customer/supplier record(s)). Demo data can only be applied to a company without intercompany partners."++A company with posted card transactions fails with "Seed: this company has N posted or voided card transaction(s), which cannot be deleted. Demo data can only be applied to a company without posted card transactions."+</Callout>+<Screenshot src="/screens/platform-demo-data.png" label="Settings → Demo Data, the Apply a demo template card listing the four industry templates with their Apply buttons" caption="Applying a template snapshots the company first, then seeds the industry story." ratio="wide" />When it finishes, the **"Demo data applied"** card asks you to decide:@@ -73,6 +93,21 @@ Only one demo-data change can be open per company. Resolve the pending one first### Applying failed with an errorApplying is all-or-nothing: a failure writes no rows and your data is unchanged. The card shows the job's error next to "Failed"; Dismiss clears it, and you can apply again.+### Applying failed with "Seed: this company trades with other companies in its group"+Expected refusal. The company has customers or suppliers linked to another company in its group (intercompany partners), which the demo-data wipe cannot remove. Nothing was written. Apply the template to a company without intercompany partners.++### Applying failed with "Seed: this company has N posted or voided card transaction(s)"+Expected refusal. Posted and voided card transactions cannot be deleted, so the demo-data wipe cannot clear the company. Nothing was written. Apply the template to a company without posted card transactions.++### Material Planning, Scheduling or Priorities are empty right after applying+Planning runs as a separate background step once the demo data is committed: MRP for the company, then scheduling for every location with Ready, In Progress or Paused jobs. Give it a moment. If that step failed, the demo data stays and MRP fills in on its regular run every three hours.++### The Webhooks, API keys or Audit log screens are empty after applying+Expected. Templates never seed credentials, webhooks or audit history, and applying a template leaves any existing webhooks and API keys in place.++### The Documents list is empty after applying a template+Expected. Templates seed records, not files: no uploads are added, so Documents and file attachments stay empty. Part thumbnails and the 3D assembly ship with the app rather than as uploaded files.+### The demo dates look recent — is that real activity?Yes, by design: every seeded date is relative to the day the template was applied, so the company always looks live with recent orders and jobs in progress.</AgentContext>diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.mdindex 7d8b001c8b..e96581b2f5 100644--- a/packages/database/AGENTS.md+++ b/packages/database/AGENTS.md@@ -38,8 +38,9 @@ DB types, Supabase/Kysely clients, audit config, event system types, rate limiti```bashpnpm db:migrate # Apply pending migrations + regenerate typespnpm db:types # Regenerate types only-pnpm db:check:datasets # Dry-run every demo dataset against the schema (writes nothing)+pnpm db:check:datasets # Validate + dry-run every demo dataset against the schema (writes nothing)pnpm --filter @carbon/database typecheck+pnpm --filter @carbon/database test```## Key Exports@@ -57,12 +58,13 @@ pnpm --filter @carbon/database typecheck| `./picked-consumption` | Node re-export of `supabase/functions/lib/picked-consumption.ts` (`linesideCredit`, `getPickedBudgets`, `allocateAcrossBudgets`, …) — the one definition of usable lineside stock shared by the pick-list generator and the `issue` backflush || *(no subpath)* | `supabase/functions/shared/image-pipeline.ts` — the codebase-wide image pipeline (decode HEIC/JPEG/PNG/WebP → shape → encode), re-exported by `@carbon/files/media` (NOT by this package). Unlike `precision.ts` it has npm deps (`libheif-js`, `@jsquash/*`) which are pinned in BOTH this package.json and `functions/deno.json` `imports` — keep the versions identical. Its `.d.ts` sits beside it (`wasm-codecs.d.ts`, triple-slash referenced). Consumed by the `process-image`, `logo-resizer` and `thumbnail` edge functions || `./event` | `QueueMessage`, `EventSchema`, `createEventSystemSubscription`, `deleteEventSystemSubscription` |-| `./quality` | Inspection execution engine shared by ERP + MES (`upsertInspectionSample`, `upsertInspectionMeasurement`, `dispositionInspection` — optional one-shot `requireOpen`, `reconcileInspectionSamplingPlans`, `changeInspectionDocument`, `getOrCreateJobOperationInspection`, pure `valuateMeasurement`); Passed/Failed/Partial are all hard-terminal and samples linked from `productionQuantity.inspectionSampleId` are locked; every fn takes a `Kysely<KyselyDatabase>` first arg — authorize at the route, see `.claude/rules/inspection-system.md` |+| `./quality` | Inspection execution engine shared by ERP + MES (`upsertInspectionSample`, `upsertInspectionMeasurement`, `dispositionInspection` — optional one-shot `requireOpen`, `reconcileInspectionSamplingPlans`, `changeInspectionDocument`, `getOrCreateJobOperationInspection`, pure `valuateMeasurement`, re-exported from `supabase/functions/shared/inspection-verdict.ts`, which the dataset seed shares); Passed/Failed/Partial are all hard-terminal and samples linked from `productionQuantity.inspectionSampleId` are locked; every fn takes a `Kysely<KyselyDatabase>` first arg — authorize at the route, see `.claude/rules/inspection-system.md` || `./sampling` | Node-side re-export of `supabase/functions/shared/sampling-engine.ts` (Z1.4 / ISO 2859-1 resolvers) || `./audit.config` / `./audit.types` | `auditConfig`, `AuditEntityType`, `getAuditableTableNames`, and the audit type surface. The audit ENGINE (`getEntityAuditLog`, `enableAuditLog`, `insertAuditLogEntries`, …) MOVED to the commercial `@carbon/ee/audit.server`; config + types stay here (client-safe, generic schema types consumed by CE packages) || `./ratelimit` | `checkApiKeyRateLimit` (Postgres RPC wrapper) || `./datasets` | `applyDataset(pgClient, { companyId, userId, dataset, timeZone, wipeFirst? })` — the one entry point that fills a company with an industry dataset, in a single transaction; `wipeFirst` clears prior business data inside that same transaction while preserving bootstrap config. Plus `DATASETS`, `getDataset`, `datasetKeys`, `datasetForIndustry`. Consumed by onboarding (`industry.tsx`) and the `company-template` Inngest job. See Dev Seed below |-| `./seed-workflows` | `buildSeedWorkflows` — the seeded workflow definitions (`datasets/tiers/workflow-definitions.ts`) |+| `./seed-workflows` | `buildSeedWorkflows`, `SEED_WORKFLOW_BUILDERS`, `EVENT_SOURCES` — the seeded workflow definitions and tier 11's event→table map (`datasets/tiers/workflow-definitions.ts`); `@carbon/ee`'s `seed-workflows.test.ts` pins both to the workflow catalog |+| `./dataset-rule-fields` | `RULE_FIELDS` — the rule-builder fields a seeded sales/storage rule may test (`datasets/rule-fields.ts`); `@carbon/utils`'s `field-registry.test.ts` pins it to `field-registry.ts` || `.` (root, from `src/timezone.ts` + `src/utils.ts`) | `getCompanyTimeZone(db, companyId)` / `getLocationTimeZone(db, locationId, companyId)` — business-timezone resolvers, overloaded for Supabase client or Kysely handle (they throw on query failure rather than silently falling back); `AnyPostgresClient` + `isKysely` guard for writing such overloads. SQL siblings: `company_today(companyId)` / `location_today(locationId, companyId)` replace `CURRENT_DATE` for business dates in DB functions (SECURITY INVOKER — callers must be SECURITY DEFINER or service-role). ERP routes should prefer the Redis-cached wrappers in `~/modules/shared/timezone.server` |## Dev Seed@@ -77,7 +79,8 @@ pnpm --filter @carbon/database typecheckindustry's content into them breaks every other dataset.- **Engine** — `tiers/01-foundation.ts` … `tiers/12-planning.ts`, run in numeric order becauseeach tier depends on ids the earlier ones put in `ctx.refs`. The ordering IS the contract.- Change a tier only to support a new *shape* of data.+ Change a tier only to support a new *shape* of data. A `Dataset` has twelve slices; `ops`+ (tier 10) carries maintenance, training, timecards, suggestions and notes.Dates are signed day-offsets resolved against the company's today — never JS `Date`, never`CURRENT_DATE` in a tier's SQL. Primary keys must never be literals: several tables@@ -86,12 +89,23 @@ company seeded into the same database.`pnpm db:seed:dev` runs `src/seed-dev.ts` (the dev CLI); `cli.ts` parses its args,`bootstrap.ts` sets up the company and `wipe.ts` clears prior data. `cli.ts` and `bootstrap.ts`-are dev-only. `wipe.ts` is reached from the shared engine via `applyDataset`'s `wipeFirst`-option, which both the dev CLI and the `company-template` job use; it is not exported on its own.--`pnpm db:check:datasets` (`src/check-datasets.ts` → `datasets/verify.ts`) catches schema drift:-it applies every dataset to a scratch company inside a transaction it always rolls back, so it-writes nothing. The pre-commit hook runs it on any `packages/database/**` change.+are dev tooling (the dev CLI and the drift check), outside the `./datasets` export. `wipe.ts` is+reached from the shared engine via `applyDataset`'s `wipeFirst` option, which both the dev CLI+and the `company-template` job use; it is not exported on its own.++After its seed commits, `seed-dev.ts` spawns `pnpm --filter @carbon/jobs plan:company --+--company <id> --user <id>` to run MRP + the scheduler (a spawn, not an import:+`@carbon/planning` depends on this package). `--skip-plan` opts out; a failed run only prints+a warning with the command to re-run. Under portless it passes+`NODE_EXTRA_CA_CERTS=~/.portless/ca.pem` when that file exists and the variable is unset.++`pnpm db:check:datasets` (`src/check-datasets.ts`) has two layers. First the pure+`validateDataset` (`datasets/validate.ts`) cross-checks every dataset with no database —+ref resolution, required status coverage, on-hand ≥ 0, journal balance, settlement+consistency — so a broken dataset blocks the commit even when the stack is down. Then `datasets/verify.ts` applies every dataset to+a scratch company, asserts the `datasets/coverage.ts` row-count floors, and always rolls back,+so it writes nothing; this layer skips with a warning when there is no database. The pre-commit+hook runs it on any `packages/database/**` change.Per-module seed scripts were folded into this structure: `seed-change-orders.ts` and its`db:seed:change-orders` script are gone, replaced by `tiers/08-change-orders.ts`.diff --git a/packages/database/package.json b/packages/database/package.jsonindex 54f76260d4..e716a3394b 100644--- a/packages/database/package.json+++ b/packages/database/package.json@@ -36,7 +36,8 @@"./audit.config": "./src/audit.config.ts","./audit.types": "./src/audit.types.ts","./swagger-docs-schema": "./src/swagger-docs-schema.ts",- "./dataset-assets": "./src/datasets/assets.ts"+ "./dataset-assets": "./src/datasets/assets.ts",+ "./dataset-rule-fields": "./src/datasets/rule-fields.ts"},"private": true,"scripts": {diff --git a/packages/database/src/check-datasets.ts b/packages/database/src/check-datasets.tsindex bc2b5559d4..81fe746f69 100644--- a/packages/database/src/check-datasets.ts+++ b/packages/database/src/check-datasets.ts@@ -22,6 +22,7 @@ import type { PoolClient } from "pg";import { getPostgresConnectionPool } from "./client.ts";import { loadEnv } from "./datasets/cli.ts";import { datasetKeys, getDataset } from "./datasets/index.ts";+import { validateDataset } from "./datasets/validate.ts";import { resolveCheckUserId, verifyDataset } from "./datasets/verify.ts";loadEnv();@@ -99,6 +100,30 @@ async function main() {}}+ // Pure validation first: it needs no database, so a broken dataset blocks the+ // commit even when the DB layer below skips.+ let inconsistent = false;+ for (const key of selected) {+ const violations = validateDataset(getDataset(key)!);+ if (violations.length > 0) {+ inconsistent = true;+ console.error(+ ` ✗ ${key} — ${violations.length} consistency violation(s):`+ );+ for (const violation of violations) console.error(` ${violation}`);+ }+ }+ if (inconsistent) {+ console.error(+ `\nThe demo datasets are internally inconsistent. Fix them in packages/database/src/datasets/data/ before committing.`+ );+ console.error(+ `Re-run on its own with: pnpm db:check:datasets\nCommit anyway with: CARBON_SKIP_DATASET_CHECK=1 git commit ...`+ );+ process.exitCode = 1;+ return;+ }+// No connection string configured at all (fresh worktree, no .env.local).// getPostgresConnectionPool dereferences it before any connect() can fail,// so without this the hook blocks the commit on "Cannot read properties of@@ -127,10 +152,14 @@ async function main() {console.log(`Checking ${selected.length} dataset(s) against the schema...`);let failed = false;for (const key of selected) {+ // Buffer tier logs and surface them only on failure — they place the+ // error inside the tier sequence without drowning a green run.+ const tierLog: string[] = [];const result = await verifyDataset(client, {dataset: getDataset(key)!,key,- userId+ userId,+ log: (message) => tierLog.push(message)});const seconds = (result.durationMs / 1000).toFixed(1);if (result.ok) {@@ -138,6 +167,11 @@ async function main() {} else {failed = true;console.error(` ✗ ${key} (${seconds}s) — ${result.error}`);+ const tail = tierLog.slice(-12);+ if (tail.length > 0) {+ console.error(` last tier steps:`);+ for (const line of tail) console.error(` ${line}`);+ }}}@@ -146,7 +180,7 @@ async function main() {console.error(pending > 0? `\nYour database is ${pending} migration(s) behind, so this may not be dataset drift at all — run pnpm db:migrate and check again before changing anything.`- : `\nThe demo datasets no longer match the schema. Fix them in packages/database/src/datasets/ — onboarding's demo templates and pnpm db:seed:dev both run this code.`+ : `\nThe demo datasets no longer match the schema, or a table fell below its row-count floor (datasets/coverage.ts). Fix them in packages/database/src/datasets/ — onboarding's demo templates and pnpm db:seed:dev both run this code.`);console.error(`Re-run on its own with: pnpm db:check:datasets\nCommit anyway with: CARBON_SKIP_DATASET_CHECK=1 git commit ...`diff --git a/packages/database/src/datasets/AGENTS.md b/packages/database/src/datasets/AGENTS.mdindex 7e2ebe55e5..28640d0025 100644--- a/packages/database/src/datasets/AGENTS.md+++ b/packages/database/src/datasets/AGENTS.md@@ -1,23 +1,49 @@# datasets — industry demo data + the engine that inserts it-Fills a company with one industry's worth of a working ERP: items, BOMs, customers, quotes,-orders, jobs, non-conformances, change orders, ledger entries, workflows. Two callers share-every line of it — `pnpm db:seed:dev` and onboarding's `company-template` Inngest job.+Fills a company with one industry's worth of a working ERP + MES: items, BOMs, customers,+quotes, orders, returns, jobs, picking, inspections, non-conformances, gauges, change orders,+maintenance, training, timecards, posted journals, payments, accounting periods, workflows and+their run history, sales/storage rules, approvals, customer portals and a busy shop floor —+every user-reachable status of the major documents included. Two callers share every line of+it — `pnpm db:seed:dev` and onboarding's `company-template` Inngest job — and both then run+MRP + the scheduler over the committed company (`planDemoCompany`, `@carbon/jobs`), which is+what fills the planning screens; nothing here writes engine output.Four datasets ship today, one per onboarding industry: `satellite` (Orbital Systems, HoustonTX), `robotics` (Helix Robotics, Pittsburgh PA), `precision` (Meridian Precision Works,Rockford IL) and `motor` (Torque Dynamics, Fort Wayne IN).-Feature-level context (how onboarding reaches this, the failure marker, adding an industry)-lives in `.claude/rules/onboarding-company-templates.md`. This file is about the code shape.+Feature-level context (how onboarding reaches this, the two wipes, posted-document+conventions, the drift check, adding an industry) lives in+`.claude/rules/onboarding-company-templates.md`. This file is about the code shape.-## Two layers, and the boundary matters+## Layers, and the boundary matters| Layer | Where | What it may contain ||-------|-------|---------------------|-| **Data** | `data/<key>/` | Plain TypeScript literals. No SQL, no ids, no `Date`. One file per slice; `index.ts` assembles them into a `Dataset`. |+| **Data** | `data/<key>/` | Plain TypeScript literals. No SQL, no ids, no `Date`. One file per slice (twelve: `foundation`, `items`, `inventory`, `sales`, `purchasing`, `production` + `assembly.ts`, `quality`, `change-orders`, `accounting`, `ops`, `workflows`, `planning`); `index.ts` assembles them into a `Dataset`. |+| **Contract** | `types.ts` | One file: the primitives (`DayOffset`, `InstantSpec`), each slice's `…Data` type and its specs in tier order, `Dataset` / `DatasetKey`, the engine types (`Ctx`, `SeedRefs`, `ItemRef`, `Tier`), and the context functions (`buildCtx`, `emptyRefs`, `resolveCompany`, `resolveCompanyTimeZone`). || **Art** | `assets/<industryId>/<readableId>.svg` | One vector thumbnail per item, keyed on the dataset's `industryId` and the item's `readableId`. |-| **Engine** | `tiers/01-…` … `tiers/12-…`, `sql.ts`, `helpers/` | Insertion logic. Industry-agnostic — a tier reads `ctx.dataset.<slice>` and knows nothing about which industry it is inserting. |+| **Engine** | `tiers/01-…` … `tiers/12-…`, `sql.ts`, `dates.ts`, `helpers/` | Insertion logic. Industry-agnostic — a tier reads `ctx.dataset.<slice>` and knows nothing about which industry it is inserting. |+| **Checks** | `validate.ts` (+ `rule-fields.ts`), `coverage.ts`, `verify.ts` | Pure consistency validator; row-count floors; the apply-and-roll-back drift check. |++`helpers/`: `items.ts` (`createItem`, `addBomLine`, `addBopOperation`, material classification), `method-copy.ts`+(the seed's ONE copy of `get-method`: `copyMethodToJob` / `copyMethodToQuoteLine` /+`copyMethodToMethod` mirror `itemToJob` / `itemToQuoteLine` / `makeMethodToMakeMethod` —+tools always, method parameters only without a procedure, a job's procedure steps ++parameters + content, supplier-process rates; no rule code, no method steps), `return-credit.ts`+(`seedReturnCredit` — the memo a return's "Issue Credit" writes), `posting-journals.ts` (PURE+journal builders — `salesInvoiceJournal`, `purchaseInvoiceJournal`, `paymentJournal`,+`memoJournal`, `receiptJournal`, `shipmentJournal`, `scrapJournal`, `voidJournal`,+`consumeFifo` — wrapping the edge functions' own builders or copying their inline shapes, and+imported by BOTH tier 09 and the validator so the two derive identical lines),+`post-documents.ts` (the DB side tier 09 calls: `loadPostingContext`, `postInventoryDocuments`,+`postSalesInvoices`, `postPurchaseInvoices`, `postMemos`, `postPayment` — they read the seeded+rows back, insert the journal via `nextJournalEntryId`, and set `journalId`),+`inspection.ts` (pure sampling-plan / sample-status math shared by tier 07 AND the validator,+so seeded sample statuses equal what the engine derives) and `bootstrap-lookup.ts`+(`bootstrapIdByName` — a bootstrap lookup row by name, cached in `ctx.refs.misc`, never module+scope, which would leak across the drift check's four scratch companies).## Part thumbnails are bundled, not uploaded@@ -37,60 +63,77 @@ undefined. It IS safe in `path.ts` (a loader/action graph module) because vite tworkspace packages as non-external and so bundles it, transforming the glob at build time —the literal asset map is in both apps' `build/server/index.js`. Adding `@carbon/database` to`ssr.external` in either app's `vite.config.ts` would break that and crash the server on boot.+(`validate.ts`'s `loadAssemblyGraph` reads `graph.json` sidecars with `node:fs` for the same reason.)New content goes in `data/`. Touch a tier only to support a new *shape* of data. The onestanding violation is `tiers/workflow-definitions.ts`, which re-exports satellite's workflowsso `@carbon/database/seed-workflows` stays a single import. It also exports-`SEED_WORKFLOW_BUILDERS`, so `seed-workflows.test.ts` validates all four datasets' definitions-— add a new dataset's builder there or its workflows go unchecked.+`SEED_WORKFLOW_BUILDERS`, so `packages/ee/src/workflows/seed-workflows.test.ts` validates all+four datasets' definitions — add a new dataset's builder there or its workflows go unchecked.## `applyDataset` is the only entry point```typescript-await applyDataset(pgClient, { companyId, userId, dataset, timeZone, tiers?, log?, beforeTiers? });+await applyDataset(pgClient, { companyId, userId, dataset, timeZone, tiers?, log?, onProgress?, wipeFirst? });```Resolves the anchor, builds `ctx`, opens ONE transaction, sets `app.sync_in_progress`, ensures-sequences, runs the tiers in order, commits — or rolls everything back. A half-seeded company-is not a reachable state. `tiers` and `beforeTiers` are dev-only (`beforeTiers` exists solely so-the CLI's wipe shares the transaction); the job passes neither.+sequences, optionally wipes (`wipeFirst`), runs the tiers in order, commits — or rolls+everything back. A half-seeded company is not a reachable state. `tiers` is dev-only;+`onProgress` feeds the template job's progress UI and must not touch the client.+`applyDatasetTiers` is the same run WITHOUT the transaction, for `verify.ts` to roll back.-`bootstrap.ts`, `wipe.ts` and `cli.ts` are imported only by `src/seed-dev.ts` and are-unreachable from the `./datasets` export graph. Keep it that way — `bootstrap.ts` contains a-hardcoded dev password.+`bootstrap.ts` and `cli.ts` are dev tooling (`src/seed-dev.ts`, and the drift check:+`verify.ts` uses `seedCompanyReferenceData`, `check-datasets.ts` uses `loadEnv`); neither is+reachable from the `./datasets` export graph. Keep it that way — `bootstrap.ts` contains a+hardcoded dev password. `wipe.ts` IS in that graph (imported by `index.ts`) but not exported:+`wipeFirst` is the only way in.## Tier order IS the contractTiers run in numeric order because each publishes ids the later ones read out of `ctx.refs`.Tier 4 can build a sales order only because tier 2 already created the item. Reordering them,-or adding a tier that reads a ref an earlier tier didn't write, breaks silently.+or adding a tier that reads a ref an earlier tier didn't write, breaks.`ctx.refs` is keyed by convention, and the prefixes are load-bearing:| Prefix | Holds ||--------|-------|| `refs.items[readableId]` | `ItemRef` — id, name, type, unitOfMeasureCode, unitCost |-| `refs.documents[ref]` | Any seeded document id, under the `ref` its spec declares (`quote:novasat`, `job:in-progress`, `so:polar`) |+| `refs.documents[ref]` | Any seeded document id, under the `ref` its spec declares (`quote:novasat`, `job:in-progress`, `so:polar`); plus `poline:<poRef>:<item>`, `rline:<receiptRef>:<item>`, `memo:<key>`, and return lines by 1-based position `rmaline:<key>:<n>` (tier 04) / `pretline:<key>:<n>` (tier 05), which tier 07's NCR links read || `refs.misc["sp:<supplier>:<process>"]` | supplierProcess || `refs.misc["cloc:<customer>"]` / `["sloc:<supplier>"]` | customer / supplier location |-| `refs.misc["procedure:<name>"]`, `["period:weekN"]`, `["sqlink:<key>"]` | as named |+| `refs.misc["sinv:<key>"]` / `["pinv:<key>"]` | keyed sales / purchase invoices the payments settle |+| `refs.misc["te:<readableId>"]` | a seeded lot / serial (trackedEntity) |+| `refs.misc["ctype:"/"stype:"/"nqr:"…]` | foundation rows by name (customer/supplier type, no-quote reason) |+| `refs.misc["<table>:<name>"]` | `bootstrapIdByName(ctx, table, name)`'s cache — every company-scoped lookup by name (payment term, customer status, return / scrap reason, failure mode, material taxonomy, …); call the helper, never read the key |+| `refs.misc["procedure:<name>"]`, `["period:weekN"]`, `["sqlink:<key>"]`, `["storagetype:<name>"]`, `["attributeDataType:<label>"]` | as named (the last is a global lookup cached per ctx) |+| `refs.locations.Plant` / `.HQ`, `refs.workCenters[name]` | the plant and the bootstrap HQ; `workCenters` includes the one HQ work center (`foundation.hqWorkCenter`) |Use `need(map, key)` from `sql.ts` rather than `map[key]!` or a `continue` — node-postgres turnsan `undefined` parameter into `NULL`, so a missing ref writes a null FK instead of failing, and a-silent `continue` drops the row entirely. Tiers 2/3/4/5/6/12 do this; tier 1 still has non-null-assertions in places.+silent `continue` drops the row entirely. Every tier resolves authored refs through `need()`+now; the former silent skips in tiers 01/03/04/06/09/12 throw a named `Seed:` error.## Rules that are not optional- **No JavaScript `Date`, and no `CURRENT_DATE` in a tier's SQL.** Every date is a signed- `DayOffset` resolved against `ctx.anchor` (today in the *company's* timezone) via `dates.ts`.- The database session's date is UTC and disagrees with the anchor for part of every day.- Nothing enforces this — `@carbon/checks` does not scan `packages/database/src/**`.+ `DayOffset` resolved against `ctx.anchor` (today in the *company's* timezone) via `dates.ts`+ (`resolveDate`, `resolveTimestamp`, `previousMonthEnd`, `monthBack`). The database session's+ date is UTC and disagrees with the anchor for part of every day. The validator bounds offset+ values (planning horizon, `NOT_CLOSED_MIN_OFFSET` / `OPEN_PERIOD_MIN_OFFSET` against the+ seeded Closed/Locked periods, chronology), but nothing scans for `Date` usage —+ `@carbon/checks` does not cover `packages/database/src/**`.+- **Posted states carry their downstream rows**, authored in the same tier in the shape the+ posting function writes them (`itemLedger` entry/document types, `invoiceSettlement`,+ tracked entities). Details in the rule file.- **Never write a literal primary key.** `externalLink` and `period` are keyed on `id` alone, soa fixed literal collides on the second company seeded into the same database. Let the columndefault mint it and read it back with `insertId`.-- **`account` is scoped by `companyGroupId`**, not `companyId`. The client bypasses RLS, so an- unscoped `LIMIT 1` reaches into another tenant's chart of accounts.+- **`account` is scoped by `companyGroupId`**, not `companyId` — as are `dimension` /+ `dimensionValue`. The client bypasses RLS, so an unscoped `LIMIT 1` reaches into another+ tenant's rows.+- **Never write the global `exchangeRate` table** — company rates go to `exchangeRateOverride`.- **Every query gets a tenancy predicate**, even when the id it pins is globally unique. RLS isoff here; the predicate is the only boundary left.- **`period` is global** — no `companyId`, no unique key. Tier 12 takes `pg_advisory_xact_lock`@@ -98,29 +141,61 @@ assertions in places.same 48 weeks, visible to every tenant.- **Shelves are declared, not generated.** `FoundationData.shelves` lists every storage unit byname, in an order where a parent precedes its children, and `openingStock[].shelf` joins on- that name. A name with no matching `ShelfSpec` is a hard error — it used to silently drop the- company's entire opening stock while still looking provisioned.+ that name. A name with no matching `ShelfSpec` is a hard error.## Verifying a change-The tiers are shared, so a refactor that "looks fine" can silently drop rows.-```bash+pnpm --silent db:check:datasets # pure validator, then apply + floors + rollback, ×4pnpm db:seed:dev -- --email [email protected] --dataset satellite```-Diff the printed `Seeded row counts` block against `.ai/runs/2026-08-13-seed-baseline.txt`, and-check the structural sums that counts alone miss (`.ai/runs/2026-08-13-seed-baseline-structural.txt`).-`--tiers 1,2,3` and `--skip-wipe` are dev-only conveniences.--Note `journal` survives the wipe: tier 9 skips an entry whose `journalEntryId` already exists, so-a re-seed will NOT correct a journal you just fixed in the data. Delete the rows first.+`validate.ts` is two layers. `buildIndex` builds every projection once — the named+reference sets behind `need(kind, where, id)`, `documentRefs` (every+declared ref in tier order, and which refs each reader may see), `onHandLedger` (net+on-hand per (item, shelf)), `lotRegistry`, `bomWalks`, `floorState`. Each slice's rule+only reads those and reports; the `RULES` order is the order violations are listed+in, not a dependency. A new check goes in its slice's rule; a fact two slices share+goes in the index.++`db:check:datasets` runs `validateDataset` first with no database (it still blocks when the+stack is down), then applies each dataset to a scratch company, asserts the `COVERAGE_FLOORS`+row counts, and rolls back. On failure it prints the violation list or the error plus the last+12 tier log lines.++After a real seed, diff the printed `Seeded row counts` block against+`.ai/runs/2026-09-23-seed-baseline-<key>.txt`, and check the structural sums counts alone miss+(`.ai/runs/2026-09-23-seed-baseline-satellite-structural.txt`, queries included). Changed a+status? Compare with `.ai/runs/2026-09-23-demo-data-status-audit.txt` and the `COVERAGE`+table in `validate.ts`. Added or removed rows on purpose? Update `coverage.ts` in the same+change. `--tiers 1,2,3` and `--skip-wipe` are dev-only conveniences.++Note `journal` / `journalLine` / `accountingPeriod` survive the wipe: tier 9 adopts an+authored entry whose `journalEntryId` already exists and skips it, so a re-seed will NOT+correct a journal you just fixed in the data, and a second dataset applied over the first+keeps the first one's journal text. Delete the rows first. Document journals are different:+the wipe voids them (`reverseDocumentJournals`, a negated Posted `VOID …` entry) and tier 9+generates fresh ones, so never rewind the `journalEntry` counter — `sql.ts`+`PRESERVED_SEQUENCES` keeps `resetSequences` off it and `nextJournalEntryId` skips taken ids.+`customField` / `userAttributeCategory` survive too, and tier 10 adopts them by name.++`verify.ts` cannot see engine output (it rolls back before MRP or the scheduler could run),+so screen-level coverage is the screen matrix:+`.ai/runs/2026-09-23-screen-matrix-<key>.txt`, one count per ERP/MES screen after a real seed++ plan. Its script lived in a session scratchpad and is not committed — the evidence files+name every screen and filter it checked.## Known rough edges+- `wipe.ts` `assertWipeable` refuses a company with intercompany customers/suppliers or a+ non-Draft `cardTransaction` — no dataset can be applied there, by design.+- `helpers/return-credit.ts`'s header says a Posted return memo has "no journal"; that is only+ its state at insert — tier 09's `postMemos` journals every Posted memo still without one.+- `rule-fields.ts` `RULE_FIELDS` hand-mirrors `@carbon/utils`' rule field registry (this package+ cannot import it); a registry change there needs the mirror updated here.+- `04-sales.ts` / `05-purchasing.ts` key their order-line maps by item, so two lines for the sameitem collapse to the last one — a shipment or invoice line would attach to the wrong order line.Key on the line's `ref` if a dataset ever needs that.-- `10-ops.ts` is a reserved, empty slot; it logs and does nothing.- `sql.ts`'s `columnCache` is module-global and never invalidated. Harmless in the short-livedCLI; in the long-running Inngest worker a deploy that adds a column needs a restart.diff --git a/packages/database/src/datasets/cli.ts b/packages/database/src/datasets/cli.tsindex b86a6812f2..88802e5edd 100644--- a/packages/database/src/datasets/cli.ts+++ b/packages/database/src/datasets/cli.ts@@ -27,11 +27,12 @@ export type SeedArgs = {dataset: string;tiers: number[] | null;skipWipe: boolean;+ skipPlan: boolean;};function printUsage(datasets: string[]) {console.log(`-Usage: pnpm run db:seed:dev -- --email <email> [--dataset <key>] [--tiers 1,2,3] [--skip-wipe]+Usage: pnpm run db:seed:dev -- --email <email> [--dataset <key>] [--tiers 1,2,3] [--skip-wipe] [--skip-plan]Arguments:--email, -e Required. Seeds the company this user belongs to.@@ -40,6 +41,7 @@ Arguments:Available: ${datasets.join(", ")}--tiers Dev only. Comma-separated tier numbers to run (default: all).--skip-wipe Dev only. Leave existing business data in place.+ --skip-plan Skip the MRP + scheduler run that follows the seed.Example:pnpm run db:seed:dev -- --email [email protected] --dataset satellite@@ -54,7 +56,8 @@ export function parseSeedArgs(datasets: string[]): SeedArgs {email: { type: "string", short: "e" },dataset: { type: "string", default: "satellite" },tiers: { type: "string" },- "skip-wipe": { type: "boolean", default: false }+ "skip-wipe": { type: "boolean", default: false },+ "skip-plan": { type: "boolean", default: false }},strict: true});@@ -90,5 +93,11 @@ export function parseSeedArgs(datasets: string[]): SeedArgs {}}- return { email, dataset, tiers, skipWipe: values["skip-wipe"] ?? false };+ return {+ email,+ dataset,+ tiers,+ skipWipe: values["skip-wipe"] ?? false,+ skipPlan: values["skip-plan"] ?? false+ };}diff --git a/packages/database/src/datasets/coverage.ts b/packages/database/src/datasets/coverage.tsnew file mode 100644index 0000000000..a6eb4190be--- /dev/null+++ b/packages/database/src/datasets/coverage.ts@@ -0,0 +1,278 @@+/**+ * Row-count floors, so a tier that silently writes nothing fails. Counts are absolute+ * (bootstrap rows included). Floor = the smallest count any dataset produced+ * (`// min` = that count when ≥ 20, floored at 80%). The shared `period` table is omitted.+ */+export const COVERAGE_FLOORS: Record<string, number> = {+ ability: 6,+ accountingPeriod: 12,+ address: 14,+ approvalRequest: 2,+ approvalRule: 3,+ assemblyComponentMapping: 3,+ assemblyInstruction: 1,+ assemblyInstructionStep: 5,+ assemblyInstructionStepMaterial: 3,+ assemblyInstructionStepTool: 2,+ batchProperty: 4,+ changeOrder: 6,+ changeOrderActionTask: 6,+ changeOrderAffectedItem: 3,+ companyAccountsPayableBillingAddress: 1,+ companyAccountsReceivableBillingAddress: 1,+ configurationParameter: 3,+ configurationParameterGroup: 1,+ configurationRule: 2,+ consumable: 2,+ contact: 16,+ contractor: 2,+ contractorAbility: 2,+ costCenter: 4,+ costLedger: 7,+ customField: 3,+ customer: 4,+ customerBankAccount: 4,+ customerContact: 4,+ customerItemPriceOverride: 1,+ customerItemPriceOverrideBreak: 2,+ customerLocation: 4,+ customerPartToItem: 2,+ customerPayment: 4,+ customerShipping: 4,+ customerTax: 4,+ customerType: 4,+ demandProjection: 22, // min 28+ department: 4,+ depreciationRun: 1,+ depreciationRunLine: 3,+ dimension: 16,+ dimensionValue: 2,+ employeeAbility: 2,+ employeeJob: 1,+ employeeShift: 1,+ enforcementRule: 5,+ enforcementRuleItemAssignment: 5,+ enforcementRuleWorkCenterAssignment: 1,+ eventSystemSubscription: 18,+ exchangeRateOverride: 1,+ externalLink: 7,+ fixedAsset: 6,+ fixedAssetDisposal: 1,+ fixedAssetUsageLog: 2,+ gauge: 3,+ gaugeCalibrationRecord: 4,+ group: 23, // min 29+ holiday: 3,+ inspection: 4,+ inspectionDocument: 3,+ inspectionFeature: 6,+ inspectionHistory: 2,+ inspectionMeasurement: 12,+ inspectionSample: 6,+ inspectionSamplingPlan: 8,+ inventoryCount: 2,+ inventoryCountLine: 11,+ invoiceSettlement: 6,+ item: 29, // min 37+ itemCost: 29, // min 37+ itemInspectionDocumentAssignment: 2,+ itemLedger: 32, // min 40+ itemPlanning: 59, // min 74+ itemPostingGroup: 5,+ itemReplenishment: 29, // min 37+ itemSerialSequence: 2,+ itemShelfLife: 1,+ itemStockQuantities: 16, // min 20+ itemSupersession: 1,+ itemUnitSalePrice: 29, // min 37+ job: 16, // min 21+ jobFavorite: 1,+ jobMakeMethod: 30, // min 38+ jobMaterial: 77, // min 97+ jobOperation: 76, // min 96+ jobOperationBatch: 1,+ jobOperationNote: 2,+ jobOperationParameter: 16,+ jobOperationStep: 35, // min 44+ jobOperationStepRecord: 10,+ jobOperationTool: 4,+ journal: 29, // min 37+ journalLine: 64, // min 80+ journalLineDimension: 2,+ kanban: 5,+ location: 2,+ maintenanceDispatch: 11,+ maintenanceDispatchComment: 4,+ maintenanceDispatchEvent: 6,+ maintenanceDispatchItem: 2,+ maintenanceDispatchWorkCenter: 4,+ maintenanceSchedule: 6,+ maintenanceScheduleItem: 1,+ makeMethod: 24, // min 30+ material: 6,+ materialDimension: 2,+ materialFinish: 2,+ materialForm: 1,+ materialGrade: 3,+ materialSubstance: 2,+ materialType: 1,+ memo: 4,+ methodMaterial: 40, // min 51+ methodOperation: 26, // min 33+ methodOperationParameter: 4,+ methodOperationTool: 1,+ modelUpload: 1,+ nonConformance: 5,+ nonConformanceActionProcess: 1,+ nonConformanceActionTask: 7,+ nonConformanceApprovalTask: 1,+ nonConformanceCustomer: 1,+ nonConformanceInspection: 1,+ nonConformanceItem: 6,+ nonConformanceJobOperation: 1,+ nonConformancePurchaseOrderLine: 1,+ nonConformancePurchaseReturnOrderLine: 1,+ nonConformanceReviewer: 2,+ nonConformanceSalesOrderLine: 1,+ nonConformanceSalesReturnOrderLine: 1,+ nonConformanceSupplier: 2,+ nonConformanceTrackedEntity: 1,+ nonConformanceWorkflow: 3,+ noQuoteReason: 4,+ note: 2,+ opportunity: 25, // min 32+ part: 18, // min 23+ partner: 2,+ payment: 8,+ peopleAbsence: 1,+ peopleAssignment: 6,+ periodCloseTask: 3,+ pickMethod: 19,+ pickingList: 2,+ pickingListLine: 4,+ pricingRule: 3,+ printJob: 5,+ printerRoute: 1,+ procedure: 4,+ procedureParameter: 9,+ procedureStep: 19,+ process: 11,+ productionEvent: 19, // min 24+ productionQuantity: 11,+ project: 2,+ purchaseInvoice: 7,+ purchaseInvoiceDelivery: 7,+ purchaseInvoiceLine: 8,+ purchaseOrder: 18,+ purchaseOrderDelivery: 18,+ purchaseOrderLine: 16, // min 21+ purchaseOrderPayment: 18,+ purchaseOrderStatusHistory: 3,+ purchaseReturnOrder: 4,+ purchaseReturnOrderCreditLine: 1,+ purchaseReturnOrderLine: 4,+ purchasingRfq: 3,+ purchasingRfqLine: 5,+ purchasingRfqSupplier: 7,+ purchasingRfqToPurchaseOrder: 1,+ purchasingRfqToSupplierQuote: 3,+ qualityDocument: 3,+ qualityDocumentStep: 3,+ quote: 8,+ quoteFavorite: 1,+ quoteLine: 10,+ quoteLinePrice: 13,+ quoteMakeMethod: 32, // min 40+ quoteMaterial: 105, // min 132+ quoteOperation: 85, // min 107+ quoteOperationParameter: 8,+ quoteOperationTool: 4,+ quotePayment: 8,+ quoteShipment: 8,+ receipt: 6,+ receiptLine: 7,+ rework: 1,+ riskRegister: 5,+ salesInvoice: 9,+ salesInvoiceLine: 9,+ salesInvoiceShipment: 9,+ salesOrder: 19, // min 24+ salesOrderFavorite: 1,+ salesOrderLine: 28, // min 36+ salesOrderPayment: 19, // min 24+ salesOrderShipment: 19, // min 24+ salesOrderStatusHistory: 3,+ salesReturnOrder: 3,+ salesReturnOrderCreditLine: 1,+ salesReturnOrderLine: 3,+ salesRfq: 4,+ salesRfqLine: 4,+ service: 1,+ shift: 2,+ shipment: 5,+ shipmentLine: 5,+ shippingMethod: 5,+ shippingTerm: 4,+ stockTransfer: 3,+ stockTransferLine: 3,+ storageType: 3,+ storageUnit: 18,+ suggestion: 2,+ supplier: 11,+ supplierBankAccount: 4,+ supplierContact: 12,+ supplierInteraction: 17, // min 22+ supplierLocation: 10,+ supplierPart: 14,+ supplierPartPrice: 14,+ supplierPayment: 11,+ supplierProcess: 3,+ supplierQuote: 6,+ supplierQuoteLine: 9,+ supplierQuoteLinePrice: 17, // min 22+ supplierShipping: 11,+ supplierTax: 11,+ supplierType: 6,+ tag: 5,+ timeCardEntry: 7,+ tool: 2,+ trackedActivity: 7,+ trackedActivityInput: 6,+ trackedActivityOutput: 6,+ trackedEntity: 49, // min 62+ training: 3,+ trainingAssignment: 2,+ trainingCompletion: 1,+ trainingQuestion: 8,+ userAttribute: 4,+ userAttributeCategory: 1,+ userAttributeValue: 4,+ warehouse: 3,+ warehouseTransfer: 3,+ warehouseTransferLine: 3,+ workCenter: 8,+ workCenterProcess: 14,+ workCenterReplacementPart: 3,+ workCenterShift: 9,+ workflow: 7,+ workflowRun: 3,+ workflowStepRun: 4,+ workflowTriggerEvent: 1,+ workflowVersion: 7+};++/**+ * `$1` = scratch company id. Group-scoped dimension rows are exact: the scratch+ * company gets a fresh group.+ */+export const COVERAGE_SCOPES: Record<string, string> = {+ companyAccountsPayableBillingAddress: `id = $1`,+ companyAccountsReceivableBillingAddress: `id = $1`,+ dimension: `"companyGroupId" = (SELECT "companyGroupId" FROM company WHERE id = $1)`,+ dimensionValue: `"companyGroupId" = (SELECT "companyGroupId" FROM company WHERE id = $1)`,+ jobFavorite: `"jobId" IN (SELECT id FROM job WHERE "companyId" = $1)`,+ quoteFavorite: `"quoteId" IN (SELECT id FROM quote WHERE "companyId" = $1)`,+ salesOrderFavorite: `"salesOrderId" IN (SELECT id FROM "salesOrder" WHERE "companyId" = $1)`,+ userAttribute: `"userAttributeCategoryId" IN (SELECT id FROM "userAttributeCategory" WHERE "companyId" = $1)`,+ userAttributeValue: `"userAttributeId" IN (SELECT ua.id FROM "userAttribute" ua JOIN "userAttributeCategory" c ON c.id = ua."userAttributeCategoryId" WHERE c."companyId" = $1)`+};diff --git a/packages/database/src/datasets/data/motor/accounting.ts b/packages/database/src/datasets/data/motor/accounting.tsindex 3a4516a668..3803a3bbfb 100644--- a/packages/database/src/datasets/data/motor/accounting.ts+++ b/packages/database/src/datasets/data/motor/accounting.ts@@ -1,7 +1,11 @@import type {AccountingData,FixedAssetSpec,- JournalEntrySpec+ JournalEntrySpec,+ MemoSpec,+ PaymentSpec,+ PeriodCloseTaskSpec,+ ProjectSpec} from "../../types.ts";export const FIXED_ASSETS: FixedAssetSpec[] = [@@ -78,6 +82,50 @@ export const FIXED_ASSETS: FixedAssetSpec[] = [acquisitionOffset: -2617,depreciationStartOffset: -2586,accumulatedDepreciation: 52000+ },+ {+ key: "winder-gen1",+ className: "Machinery & Equipment",+ location: "Plant",+ name: "Coil Winding Machine (Gen 1)",+ description:+ "First-generation coil winder replaced by the automatic winder; sold to a rewind shop",+ serialNumber: "CW-G1-20944",+ status: "Disposed",+ depreciationMethod: "Straight Line",+ usefulLifeMonths: 120,+ residualValuePercent: 0,+ acquisitionCost: 72000,+ acquisitionOffset: -3100,+ depreciationStartOffset: -3080,+ // 72,000 / 120 = 600 per month x the 100 months depreciated before sale.+ // NBV 12,000 against 9,000 proceeds books a 3,000 loss.+ accumulatedDepreciation: 60000,+ disposal: { dateOffset: -40, method: "Sale", saleProceeds: 9000 }+ },+ {+ key: "balancer",+ className: "Machinery & Equipment",+ location: "Plant",+ name: "Rotor Balancing Machine",+ description: "Dynamic rotor balancer, depreciated by balancing cycles",+ serialNumber: "RBM-2P-61507",+ status: "Active",+ depreciationMethod: "Units of Production",+ usefulLifeMonths: 96,+ residualValuePercent: 0,+ acquisitionCost: 84000,+ acquisitionOffset: -120,+ depreciationStartOffset: -100,+ // 84,000 / 420,000 cycles = 0.20 per cycle. The first logged month (3,800)+ // was booked on registration; the run's month (4,100) is the charge.+ assetLifetimeUsage: 420000,+ accumulatedDepreciation: 760,+ usageLogs: [+ { monthsBack: 2, unitsProduced: 3800 },+ { monthsBack: 1, unitsProduced: 4100 }+ ],+ depreciationCharge: 820}];@@ -107,10 +155,320 @@ export const JOURNAL_ENTRIES: JournalEntrySpec[] = [journalLineReference: "JE-SEED-001"}]+ },+ {+ ref: "journal:payroll-accrual",+ journalEntryId: "JE-SEED-002",+ description: "Payroll accrual — winding and assembly crew, final week",+ status: "Posted",+ postingOffset: -12,+ lines: [+ {+ account: "6060",+ description: "Accrued winding and assembly wages",+ amount: 29400,+ quantity: 1,+ journalLineReference: "JE-SEED-002-1",+ dimensions: [+ { dimension: "Project", value: "ridgeline-traction" },+ { dimension: "Motor Family", value: "Traction Motors" }+ ]+ },+ {+ account: "2150",+ description: "Accrued winding and assembly wages",+ amount: 29400,+ quantity: 1,+ journalLineReference: "JE-SEED-002-2"+ }+ ]+ },+ {+ ref: "journal:amortization",+ journalEntryId: "JE-SEED-003",+ description: "Monthly amortization — winding pattern design license",+ status: "Posted",+ postingOffset: -23,+ lines: [+ {+ account: "6310",+ description: "Winding pattern design license amortization",+ amount: 720,+ quantity: 1,+ journalLineReference: "JE-SEED-003"+ },+ {+ // A credit on the contra-asset: negative on a debit-normal class.+ account: "1420",+ description: "Winding pattern design license amortization",+ amount: -720,+ quantity: 1,+ journalLineReference: "JE-SEED-003"+ }+ ]+ },+ {+ ref: "journal:freight-accrual",+ journalEntryId: "JE-SEED-004",+ description: "Accrued outbound freight — duplicate of carrier invoice",+ status: "Reversed",+ postingOffset: -40,+ lines: [+ {+ account: "6040",+ description: "Outbound LTL freight",+ amount: 2860,+ quantity: 1,+ journalLineReference: "JE-SEED-004"+ },+ {+ account: "2140",+ description: "Outbound LTL freight",+ amount: 2860,+ quantity: 1,+ journalLineReference: "JE-SEED-004"+ }+ ],+ reversal: {+ ref: "journal:freight-accrual-reversal",+ journalEntryId: "JE-SEED-005",+ postingOffset: -33+ }+ },+ {+ ref: "journal:opening-balance",+ journalEntryId: "JE-SEED-006",+ description: "Opening balances — cutover from the legacy ledger",+ status: "Posted",+ sourceType: "Opening Balance",+ postingOffset: -242,+ lines: [+ {+ account: "1010",+ description: "Operating cash",+ amount: 610000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-1"+ },+ {+ account: "1210",+ description: "Raw materials on hand",+ amount: 180000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-2"+ },+ {+ account: "1220",+ description: "Finished goods on hand",+ amount: 140000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-3"+ },+ {+ account: "1350",+ description: "Machinery & equipment at cost",+ amount: 1120000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-4"+ },+ {+ account: "1330",+ description: "Accumulated depreciation to date",+ amount: -290000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-5"+ },+ {+ account: "2410",+ description: "Equipment term loan",+ amount: 650000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-6"+ },+ {+ account: "3010",+ description: "Paid-in capital",+ amount: 600000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-7"+ },+ {+ account: "3100",+ description: "Retained earnings brought forward",+ amount: 510000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-8"+ }+ ]+ }+];++// Credit/Debit Note Issued invoices settle by their memos as zero-cash credit+// applications, the way applyCreditsToInvoices records them.+export const PAYMENTS: PaymentSpec[] = [+ {+ key: "wabash-ach",+ type: "Receipt",+ customer: "Wabash Industrial Supply",+ dateOffset: -45,+ amount: 300,+ reference: "ACH 9021-3345",+ applies: [{ invoiceKey: "paid", amount: 300 }]+ },+ {+ key: "ridgeline-wire",+ type: "Receipt",+ customer: "Ridgeline Drive Systems",+ dateOffset: -10,+ amount: 710,+ reference: "WIRE 61188",+ applies: [{ invoiceKey: "partial", amount: 710 }]+ },+ {+ key: "cardinal-credit",+ type: "Receipt",+ customer: "Cardinal Motorworks",+ dateOffset: -49,+ amount: 0,+ reference: "Credit application",+ applies: [],+ credits: [{ memoKey: "cardinal-shafts", invoiceKey: "credit", amount: 410 }]+ },+ {+ key: "copperline-ach",+ type: "Disbursement",+ supplier: "Copperline Wire Works",+ dateOffset: -31,+ amount: 1036,+ reference: "ACH 2217-8806",+ applies: [{ invoiceKey: "paid", amount: 1036 }]+ },+ {+ key: "copperline-check",+ type: "Disbursement",+ supplier: "Copperline Wire Works",+ dateOffset: -12,+ amount: 178,+ reference: "CHK 41209",+ applies: [{ invoiceKey: "partial", amount: 178 }]+ },+ {+ key: "lakeland-debit",+ type: "Disbursement",+ supplier: "Lakeland Electrical Steel",+ dateOffset: -66,+ amount: 0,+ reference: "Debit application",+ applies: [],+ credits: [+ { memoKey: "lakeland-bar", invoiceKey: "debit-note", amount: 975 }+ ]+ },+ {+ key: "draft-receipt",+ type: "Receipt",+ status: "Draft",+ customer: "Cardinal Motorworks",+ dateOffset: -1,+ amount: 780,+ reference: "ACH advice 5580 — 4500 stator",+ applies: []+ },+ {+ key: "draft-disbursement",+ type: "Disbursement",+ status: "Draft",+ supplier: "Lakeland Electrical Steel",+ dateOffset: 0,+ amount: 540,+ reference: "ACH batch 0930 — lamination steel",+ applies: []+ }+];++export const MEMOS: MemoSpec[] = [+ {+ key: "cardinal-shafts",+ direction: "Credit",+ customer: "Cardinal Motorworks",+ invoiceKey: "credit",+ dateOffset: -52,+ amount: 410,+ notes:+ "Full credit — precision shafts returned with bearing-seat runout out of tolerance"+ },+ {+ key: "lakeland-bar",+ direction: "Debit",+ supplier: "Lakeland Electrical Steel",+ invoiceKey: "debit-note",+ dateOffset: -70,+ amount: 975,+ notes: "Bar stock failed the mill-cert review at Lakeland — billing debited"+ }+];++export const PROJECTS: ProjectSpec[] = [+ {+ key: "ridgeline-traction",+ name: "Ridgeline EV Traction Motor Launch",+ description:+ "Production launch of the 9000-series traction motor for Ridgeline",+ purchaseInvoiceLine: { invoiceKey: "paid", item: "MAT-CU-18AWG" }+ },+ {+ key: "dyno-automation",+ name: "Dyno Cell Automation",+ description:+ "Automated load profiles and data capture for end-of-line testing"+ }+];++export const CLOSE_TASKS: PeriodCloseTaskSpec[] = [+ { definition: "Post pending operational documents", status: "Done" },+ {+ definition: "Review negative on-hand inventory",+ status: "Skipped",+ skippedReason: "Physical count at month end found no negative bins"+ },+ {+ definition: "Review financial statements",+ status: "Open",+ notes: "Plant controller to review absorption variance"}];export const motorAccounting: AccountingData = {fixedAssets: FIXED_ASSETS,- journalEntries: JOURNAL_ENTRIES+ journalEntries: JOURNAL_ENTRIES,+ payments: PAYMENTS,+ memos: MEMOS,+ projects: PROJECTS,+ customDimension: {+ name: "Motor Family",+ values: ["Traction Motors", "Industrial Servo"]+ },+ closeTasks: CLOSE_TASKS,+ // EUR per 1 USD (foreign units per base unit), the same direction as the EUR purchase order's 0.92 snapshot.+ exchangeRateOverrides: [{ currencyCode: "EUR", rate: 0.9215 }],+ billingAddresses: {+ receivable: {+ addressLine1: "1450 Meyer Industrial Road",+ city: "Fort Wayne",+ state: "IN",+ postalCode: "46803",+ countryCode: "US",+ phone: "+1-260-555-0174",+ email: "[email protected]"+ },+ payable: {+ addressLine1: "1450 Meyer Industrial Road",+ city: "Fort Wayne",+ state: "IN",+ postalCode: "46803",+ countryCode: "US",+ phone: "+1-260-555-0175",+ email: "[email protected]"+ }+ }};diff --git a/packages/database/src/datasets/data/motor/assembly.ts b/packages/database/src/datasets/data/motor/assembly.tsindex 7ee135c5e0..0fc9f1b405 100644--- a/packages/database/src/datasets/data/motor/assembly.ts+++ b/packages/database/src/datasets/data/motor/assembly.ts@@ -7,12 +7,19 @@ export const motorAssembly: AssemblySpec = {name: "EV Drive Unit — Build Sequence",item: "MTR-9000",componentCount: 53,+ // The Assembly operation of the MTR-9000 method.+ operation: 1,steps: [{title: "Set the rotor shaft into the case",instruction:"Lower the rotor shaft in drive-end down, supporting it by the shaft and never by the magnets. The 6208 bearing must seat the last 2mm under hand pressure — if it needs tapping, the bore is not square and the shaft comes back out.",- componentNodeIds: ["6de0ee0cd9763f34"]+ componentNodeIds: ["6de0ee0cd9763f34"],+ materials: [+ { item: "ROT-9000", quantity: 1 },+ { item: "BRG-6308-C3", quantity: 1 }+ ],+ tools: [{ item: "TL-ARBOR-PRESS", quantity: 1 }]},{title: "Roll the counter shaft into mesh",@@ -24,7 +31,8 @@ export const motorAssembly: AssemblySpec = {title: "Seat the output gear and differential",instruction:"Drop the output gear and differential group onto their bearing bores. Turn the rotor one full revolution by hand: the whole train must run free with no tight spot. A tight spot here is a misaligned bore, not a run-in issue.",- componentNodeIds: ["c227f36952b482ec"]+ componentNodeIds: ["c227f36952b482ec"],+ materials: [{ item: "BRG-6308-C3", quantity: 1 }]},{title: "Fit the short axle shaft",@@ -36,7 +44,26 @@ export const motorAssembly: AssemblySpec = {title: "Fit the long axle shaft and check end float",instruction:"Fit the long axle the same way, then dial-indicate end float at both output flanges. 0.05–0.20mm each side. Record both readings on the traveler before the case halves go together.",- componentNodeIds: ["b60a9d16191bdd92"]+ componentNodeIds: ["b60a9d16191bdd92"],+ materials: [{ item: "ENC-INC-2048", quantity: 1 }],+ tools: [{ item: "TL-BAL-MANDREL", quantity: 1 }]+ }+ ],+ componentMappings: [+ // model part "rotor shaft"+ {+ geometryHash: "2ba110d7ca24b04bdd9b1b8a4d4972be1b5315b7",+ item: "ROT-9000"+ },+ // model part "6308 bearing"+ {+ geometryHash: "f3596194138d8700a03701246925e34897bb07e2",+ item: "BRG-6308-C3"+ },+ // model part "resolver"+ {+ geometryHash: "f5192d79c105b37223aeee05dabcdebf7a9106e1",+ item: "ENC-INC-2048"}]};diff --git a/packages/database/src/datasets/data/motor/change-orders.ts b/packages/database/src/datasets/data/motor/change-orders.tsindex 68164cc6f6..459feaa71e 100644--- a/packages/database/src/datasets/data/motor/change-orders.ts+++ b/packages/database/src/datasets/data/motor/change-orders.ts@@ -64,6 +64,73 @@ export const CHANGE_ORDERS: ChangeOrderSpec[] = [sortOrder: 1}]+ },+ // Lifecycle-only notices: no affected items yet (every change type spins a+ // method draft), so they exercise the stage flow + action tasks alone.+ {+ ref: "co:start",+ name: "Add strain-relief boss at the HSG-9000 encoder cable exit",+ type: "Engineering",+ changeOrderType: "Design Improvement",+ status: "Start",+ priority: "Medium",+ openDateOffset: -9,+ dueDateOffset: 30,+ reasonForChange:+ "Dyno vibration runs showed the encoder cable flexing at the end-bell exit; two line-driver conductors fatigued inside the jacket.",+ affectedItems: [],+ actionTasks: [+ { action: "Engineering Review", status: "In Progress", dueDateOffset: 5 },+ { action: "Update Drawings / CAD", status: "Pending", dueDateOffset: 20 }+ ]+ },+ {+ ref: "co:eng-complete",+ name: "Add slot-liner thickness check to the Nomex receiving plan",+ type: "Manufacturing",+ changeOrderType: "Quality / Reliability Improvement",+ status: "Engineering Complete",+ priority: "High",+ openDateOffset: -60,+ dueDateOffset: 14,+ reasonForChange:+ "The Copperline Nomex escape showed a label and cert review alone cannot catch under-thickness slot liner before it reaches the winding line.",+ nonConformance: "ncr:nomex-thin",+ affectedItems: [],+ actionTasks: [+ {+ action: "Quality Review",+ status: "Completed",+ dueDateOffset: -45,+ completedOffset: -48+ },+ {+ action: "Notify Affected Parties",+ status: "In Progress",+ dueDateOffset: 7+ }+ ]+ },+ {+ ref: "co:cancelled",+ name: "Revise the TD-4500 nameplate drawing for a dual-voltage rating",+ type: "Documentation",+ changeOrderType: "Documentation Error / Correction",+ status: "Cancelled",+ priority: "Low",+ openDateOffset: -120,+ reasonForChange:+ "Sales asked for a 230/460 V dual rating on the TD-4500; the customer later standardized on 460 V only and the single-voltage plate stays.",+ affectedItems: [],+ actionTasks: [+ {+ action: "Cost Impact Review",+ status: "Completed",+ dueDateOffset: -110,+ completedOffset: -112+ },+ { action: "Update Drawings / CAD", status: "Skipped" }+ ]}];diff --git a/packages/database/src/datasets/data/motor/foundation.ts b/packages/database/src/datasets/data/motor/foundation.tsindex bb5d88d45d..70083297e5 100644--- a/packages/database/src/datasets/data/motor/foundation.ts+++ b/packages/database/src/datasets/data/motor/foundation.ts@@ -1,13 +1,19 @@import type {ContractorAgencySpec,+ EmployeeJobSpec,FoundationData,+ HolidaySpec,+ MaterialTaxonomySpec,+ PartnerSpec,PlantSpec,PrinterRouteSpec,ProcedureSpec,ProcedureStepSpec,ShelfSpec,ShiftSpec,- WarehouseSpec+ TagSpec,+ WarehouseSpec,+ WorkCenterSpec} from "../../types.ts";// ---------------------------------------------------------------------------@@ -137,6 +143,29 @@ export const WORK_CENTER_PROCESS_LINKS: Array<[string, string]> = [["CMM Inspection Bench", "Final Test & Inspection"]];+export const WORK_CENTER_SHIFTS: Array<[string, string]> = [+ ["CNC Turning Cell", "A Shift"],+ ["CNC Turning Cell", "B Shift"],+ ["Lamination Press", "A Shift"],+ ["Winding Line 1", "A Shift"],+ ["Winding Line 1", "B Shift"],+ ["Impregnation Oven", "A Shift"],+ ["Impregnation Oven", "B Shift"],+ ["Balancing Cell", "A Shift"],+ ["Motor Assembly Bench", "A Shift"],+ ["Motor Assembly Bench", "Saturday Shift"],+ ["Dyno Test Cell", "A Shift"],+ ["Dyno Test Cell", "Saturday Shift"],+ ["CMM Inspection Bench", "A Shift"]+];++export const EMPLOYEE_JOB: EmployeeJobSpec = {+ title: "Production Supervisor",+ department: "Assembly",+ shift: "A Shift",+ startDateOffset: -1250+};+export const PLANT: PlantSpec = {name: "Motor Assembly Plant",addressLine1: "1450 Meyer Industrial Road",@@ -342,6 +371,37 @@ export const SUPPLIERS = [type: "Services",phone: "+1-937-555-1170",website: "https://anchormetrology.com"+ },+ // Status showcases + the EUR vendor. None of these may be referenced by+ // purchasing data — they exist so every supplier status renders somewhere.+ {+ name: "Rustbelt Laminations",+ type: "Materials",+ phone: "+1-216-555-1280",+ website: "https://rustbeltlaminations.com",+ status: "Inactive" as const+ },+ {+ name: "Amperon Winding Works",+ type: "Electrical",+ phone: "+1-317-555-1390",+ website: "https://amperonwindings.com",+ status: "Pending" as const+ },+ {+ name: "Budget Bearing Depot",+ type: "Hardware",+ phone: "+1-614-555-1410",+ website: "https://budgetbearing.com",+ status: "Rejected" as const+ },+ {+ name: "Euromag Ferrite Werke GmbH",+ type: "Magnets",+ phone: "+49-231-555-1520",+ website: "https://euromag-ferrite.de",+ status: "Active" as const,+ currencyCode: "EUR"}];@@ -394,6 +454,34 @@ export const SUPPLIER_CONTACTS = [lastName: "Kaminski",email: "[email protected]",title: "Calibration Coordinator"+ },+ {+ supplier: "Rustbelt Laminations",+ firstName: "Dale",+ lastName: "Hoffman",+ email: "[email protected]",+ title: "Sales Manager"+ },+ {+ supplier: "Amperon Winding Works",+ firstName: "Grace",+ lastName: "Nakamura",+ email: "[email protected]",+ title: "Business Development"+ },+ {+ supplier: "Budget Bearing Depot",+ firstName: "Vince",+ lastName: "Talley",+ email: "[email protected]",+ title: "Account Executive"+ },+ {+ supplier: "Euromag Ferrite Werke GmbH",+ firstName: "Annika",+ lastName: "Richter",+ email: "[email protected]",+ title: "Export Sales"}];@@ -404,6 +492,32 @@ export const SUPPLIER_PROCESSES = [{ supplier: "Maumee Contract Machining", process: "Outside Processing" }];+export const PARTNERS: PartnerSpec[] = [+ {+ supplier: "Maumee Contract Machining",+ ability: "CNC Machining",+ hoursPerWeek: 40+ },+ {+ supplier: "Anchor Metrology Services",+ ability: "Inspection",+ hoursPerWeek: 16+ },+ {+ supplier: "Amperon Winding Works",+ ability: "Coil Winding",+ hoursPerWeek: 24+ }+];++export const HQ_WORK_CENTER: WorkCenterSpec = {+ name: "Prototype Winding Lab",+ dept: "Engineering",+ ability: "Coil Winding",+ laborRate: 82,+ machineRate: 30+};+export const CONTRACTORS = [{firstName: "Elena",@@ -464,10 +578,15 @@ export const PROCEDURES: ProcedureSpec[] = [process: "Coil Winding",description:"Coil insertion, lacing and Class H varnish impregnation for a 9000-frame stator.",+ parameters: [+ { key: "Varnish", value: "Class H polyester, VPI" },+ { key: "Cure profile", value: "4 h at 160 °C" },+ { key: "Hipot after cure", value: "2,000 V for 60 s" }+ ],versions: [{version: 1,- status: "Draft",+ status: "Archived",steps: [{name: "Verify slot liner installation",@@ -485,7 +604,7 @@ export const PROCEDURES: ProcedureSpec[] = [}]},- { version: 2, status: "Draft", steps: STATOR_WINDING_STEPS_V2 }+ { version: 2, status: "Active", steps: STATOR_WINDING_STEPS_V2 }]},{@@ -496,7 +615,7 @@ export const PROCEDURES: ProcedureSpec[] = [versions: [{version: 1,- status: "Draft",+ status: "Active",steps: [{name: "Measure bore diameter after impregnation",@@ -652,6 +771,11 @@ export const PROCEDURES: ProcedureSpec[] = [process: "Final Test & Inspection",description:"No-load, loaded and thermal acceptance run on the dyno before the motor is released to stock.",+ parameters: [+ { key: "Rated load", value: "90 kW at 3,000 rpm" },+ { key: "Thermal run", value: "Until ΔT < 1 °C over 30 min" },+ { key: "Vibration limit", value: "1.8 mm/s RMS" }+ ],versions: [{version: 1,@@ -695,6 +819,26 @@ export const PROCEDURES: ProcedureSpec[] = [type: "Checkbox",instruction:"Print the dyno curve, stamp the nameplate serial on it and file it against the job."+ },+ {+ name: "Stamp hipot test pass time",+ type: "Timestamp",+ instruction:+ "Run the 1.8 kV dielectric withstand test after the thermal run and stamp the moment it passes — the winding must not be re-energised for ten minutes after the stamp."+ },+ {+ name: "Attach dyno curve export",+ type: "File",+ instruction:+ "Export the torque-speed and efficiency curves from the dyno DAQ and attach them to the acceptance record.",+ fileTypes: ["csv", "pdf"]+ },+ {+ name: "Final visual inspection",+ type: "Inspection",+ instruction:+ "Inspect paint, nameplate stamping, shaft key fit and terminal box sealing before release to stock. Photograph any finding.",+ required: false}]}@@ -739,11 +883,59 @@ export const NO_QUOTE_REASONS = ["Tooling Cost"];+// Offsets are positive (upcoming) and distinct — holiday has UNIQUE (date).+export const HOLIDAYS: HolidaySpec[] = [+ { name: "Founders Day", dateOffset: 40 },+ { name: "Plant Retooling Shutdown", dateOffset: 100 },+ { name: "Year-End Shutdown", dateOffset: 160 }+];++export const TAGS: TagSpec[] = [+ { name: "High Voltage", table: "operation" },+ { name: "UL Listed", table: "procedure" },+ { name: "Winding Certified", table: "training" },+ { name: "Magnet Handling", table: "material" },+ { name: "Calibrated", table: "tool" }+];++// Names deliberately avoid the GLOBAL substances/forms migrations seed (Steel,+// Aluminum, Sheet, Plate, …) so the settings screens don't show duplicates.+export const MATERIAL_TAXONOMY: MaterialTaxonomySpec = {+ substances: [+ { name: "Electrical Steel", code: "ESTL" },+ // Backs the magnet wire classification on MAT-CU-18AWG (items.ts).+ { name: "Enameled Copper", code: "ENCU" }+ ],+ forms: [{ name: "Lamination Coil", code: "LAMCOIL" }],+ types: [+ {+ name: "Electrical Steel Lamination Coil",+ code: "ESTL-LAM",+ substance: "Electrical Steel",+ form: "Lamination Coil"+ }+ ],+ grades: [+ { name: "M19", substance: "Electrical Steel" },+ { name: "M27", substance: "Electrical Steel" },+ { name: "MW 35-C", substance: "Enameled Copper" }+ ],+ finishes: [+ { name: "C5 Insulation Coating", substance: "Electrical Steel" },+ { name: "Polyamide-Imide Overcoat", substance: "Enameled Copper" }+ ],+ dimensions: [+ { name: "0.35mm x 200mm", form: "Lamination Coil", isMetric: true },+ { name: "0.50mm x 150mm", form: "Lamination Coil", isMetric: true }+ ]+};+export const motorFoundation: FoundationData = {departments: DEPT_NAMES,abilities: ABILITIES,processes: PROCESSES,workCenters: WORK_CENTERS,+ hqWorkCenter: HQ_WORK_CENTER,customers: CUSTOMERS,customerContacts: CUSTOMER_CONTACTS,suppliers: SUPPLIERS,@@ -759,12 +951,18 @@ export const motorFoundation: FoundationData = {costCenters: COST_CENTERS,noQuoteReasons: NO_QUOTE_REASONS,contractors: CONTRACTORS,+ partners: PARTNERS,plant: PLANT,shifts: SHIFTS,+ workCenterShifts: WORK_CENTER_SHIFTS,+ employeeJob: EMPLOYEE_JOB,warehouses: WAREHOUSES,storageTypes: STORAGE_TYPES,shelves: SHELVES,printerRoute: PRINTER_ROUTE,+ holidays: HOLIDAYS,+ tags: TAGS,+ materialTaxonomy: MATERIAL_TAXONOMY,defaultShippingMethod: "UPS Ground",contractorAgency: CONTRACTOR_AGENCY,partyAddressCity: "Fort Wayne",diff --git a/packages/database/src/datasets/data/motor/index.ts b/packages/database/src/datasets/data/motor/index.tsindex 4f78b4712b..294a76158d 100644--- a/packages/database/src/datasets/data/motor/index.ts+++ b/packages/database/src/datasets/data/motor/index.ts@@ -4,6 +4,7 @@ import { motorChangeOrders } from "./change-orders.ts";import { motorFoundation } from "./foundation.ts";import { motorInventory } from "./inventory.ts";import { motorItems } from "./items.ts";+import { motorOps } from "./ops.ts";import { motorPlanning } from "./planning.ts";import { motorProduction } from "./production.ts";import { motorPurchasing } from "./purchasing.ts";@@ -27,6 +28,7 @@ export const motor: Dataset = {quality: motorQuality,changeOrders: motorChangeOrders,accounting: motorAccounting,+ ops: motorOps,workflows: motorWorkflows,planning: motorPlanning};diff --git a/packages/database/src/datasets/data/motor/inventory.ts b/packages/database/src/datasets/data/motor/inventory.tsindex e20020e4be..e524027489 100644--- a/packages/database/src/datasets/data/motor/inventory.ts+++ b/packages/database/src/datasets/data/motor/inventory.ts@@ -3,7 +3,10 @@ import type {InventoryData,KanbanItemSpec,OpeningStockSpec,- TrackedStockSpec+ ShelfLifeSpec,+ StockTransferSpec,+ TrackedStockSpec,+ WarehouseTransferSpec} from "../../types.ts";// Opening inventory — realistic quantities for a precision motor shop.@@ -21,7 +24,7 @@ export const OPENING_STOCK: OpeningStockSpec[] = [{ item: "FST-M6-SS", qty: 900, shelf: "A1-L1" },{ item: "FST-M10-SS", qty: 500, shelf: "A1-L1" },{ item: "NPL-SS-STD", qty: 150, shelf: "A1-L3" },- { item: "MAT-LAM-M19", qty: 2400, shelf: "A3-L1" },+ { item: "MAT-LAM-M19", qty: 2440, shelf: "A3-L1" },{ item: "MAT-CU-18AWG", qty: 640, shelf: "Winding-Crib" },{ item: "MAT-INS-NOMEX", qty: 85, shelf: "Winding-Crib" },{ item: "MAT-VARNISH", qty: 22, shelf: "A3-L3" },@@ -31,14 +34,14 @@ export const OPENING_STOCK: OpeningStockSpec[] = [{ item: "CN-BRG-GREASE", qty: 12, shelf: "A2-L2" }];-// Lots/serials that back the tracked slice of the opening stock above; each-// group's quantities add up to that item's opening quantity.+// Backs the tracked slice of the opening stock above.export const ON_HAND_TRACKED: TrackedStockSpec[] = [{item: "MAG-NDFB-45",entities: [{ readableId: "LOT-MAG45-2607", quantity: 300 },- { readableId: "LOT-MAG45-2608", quantity: 180 }+ { readableId: "LOT-MAG45-2608", quantity: 180 },+ { readableId: "LOT-MAG45-2609", quantity: 3, status: "On Hold" }]},{@@ -63,33 +66,197 @@ export const ON_HAND_TRACKED: TrackedStockSpec[] = [item: "MAT-LAM-M19",entities: [{ readableId: "LOT-M19-2606", quantity: 1400 },- { readableId: "LOT-M19-2607", quantity: 1000 }+ { readableId: "LOT-M19-2607", quantity: 1000 },+ { readableId: "LOT-M19-2608", quantity: 3, status: "Rejected" },+ {+ readableId: "LOT-M19-2601",+ quantity: 40,+ status: "Scrapped",+ scrap: {+ shelf: "A3-L1",+ reason: "Quality",+ dateOffset: -36,+ comment:+ "Insulating coating flaked after a humidity excursion in storage"+ }+ }]},{item: "MAT-CU-18AWG",entities: [{ readableId: "LOT-CU18-2608", quantity: 400 },- { readableId: "LOT-CU18-2609", quantity: 240 }+ { readableId: "LOT-CU18-2609", quantity: 240, expiresOffset: 30 }]}];-// Kanbans (auto-replenishment cards) for high-usage buy parts.+// LOT-CU18-2609 above expires in 30 days so the expiry chips show amber.+export const SHELF_LIVES: ShelfLifeSpec[] = [+ { item: "MAT-CU-18AWG", days: 270 }+];+export const KANBAN_ITEMS: KanbanItemSpec[] = [{ item: "FST-M6-SS", qty: 300, supplier: "Ironwood Fasteners" },{ item: "FST-M10-SS", qty: 150, supplier: "Ironwood Fasteners" },- { item: "SEAL-VR-45", qty: 40, supplier: "Summit Bearing Supply" }+ { item: "SEAL-VR-45", qty: 40, supplier: "Summit Bearing Supply" },+ { item: "SHF-9000", qty: 2, replenishmentSystem: "Make" },+ {+ item: "MAT-VARNISH",+ qty: 5,+ replenishmentSystem: "Transfer",+ fromShelf: "A3-L3",+ toShelf: "Winding-Crib"+ }];-export const INVENTORY_COUNT: InventoryCountSpec = {- status: "Draft",- notes: "Quarterly physical count — magnet vault and winding crib"-};+export const INVENTORY_COUNTS: InventoryCountSpec[] = [+ {+ // The first six opening-stock rows.+ key: "q3-draft",+ status: "Draft",+ notes: "Quarterly physical count — magnet vault and winding crib",+ lines: [+ {+ item: "MAG-NDFB-45",+ shelf: "Magnet-Vault",+ snapshotQuantity: 480,+ countedQuantity: 480+ },+ {+ item: "MAG-NDFB-38",+ shelf: "Magnet-Vault",+ snapshotQuantity: 360,+ countedQuantity: 360+ },+ {+ item: "BRG-6206-C3",+ shelf: "A2-L1",+ snapshotQuantity: 60,+ countedQuantity: 60+ },+ {+ item: "BRG-6308-C3",+ shelf: "A2-L1",+ snapshotQuantity: 44,+ countedQuantity: 44+ },+ {+ item: "SEAL-VR-45",+ shelf: "A1-L2",+ snapshotQuantity: 120,+ countedQuantity: 120+ },+ {+ item: "ENC-INC-2048",+ shelf: "A1-L3",+ snapshotQuantity: 6,+ countedQuantity: 6+ }+ ]+ },+ {+ key: "aug-cycle",+ status: "Posted",+ notes: "Cycle count — fastener & seal bins",+ postedOffset: -20,+ lines: [+ {+ item: "FST-M6-SS",+ shelf: "A1-L1",+ snapshotQuantity: 900,+ countedQuantity: 898+ },+ {+ item: "FST-M10-SS",+ shelf: "A1-L1",+ snapshotQuantity: 500,+ countedQuantity: 500+ },+ {+ item: "SEAL-VR-45",+ shelf: "A1-L2",+ snapshotQuantity: 120,+ countedQuantity: 122+ },+ {+ item: "NPL-SS-STD",+ shelf: "A1-L3",+ snapshotQuantity: 150,+ countedQuantity: 150+ },+ {+ item: "CN-BRG-GREASE",+ shelf: "A2-L2",+ snapshotQuantity: 12,+ countedQuantity: 12+ }+ ]+ }+];++// Only the Completed move changes stock, so it's dated after the posted count above.+export const STOCK_TRANSFERS: StockTransferSpec[] = [+ {+ key: "st-completed",+ status: "Completed",+ fromShelf: "A1-L1",+ toShelf: "A2-L2",+ dateOffset: -10,+ lines: [{ item: "FST-M6-SS", quantity: 60 }]+ },+ {+ key: "st-released",+ status: "Released",+ fromShelf: "A3-L2",+ toShelf: "A3-L1",+ dateOffset: -1,+ lines: [{ item: "MAT-AL6061-BAR", quantity: 40 }]+ },+ {+ key: "st-draft",+ status: "Draft",+ fromShelf: "A2-L2",+ toShelf: "A2-L1",+ dateOffset: 0,+ lines: [{ item: "CN-BRG-GREASE", quantity: 2 }]+ }+];++// HQ has no bins, so completed receipts land shelfless.+export const WAREHOUSE_TRANSFERS: WarehouseTransferSpec[] = [+ {+ key: "wt-completed",+ status: "Completed",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: -12,+ lines: [{ item: "FST-M10-SS", quantity: 30, fromShelf: "A1-L1" }]+ },+ {+ key: "wt-toship",+ status: "To Ship",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: 0,+ lines: [{ item: "MAT-VARNISH", quantity: 2, fromShelf: "A3-L3" }]+ },+ {+ key: "wt-draft",+ status: "Draft",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: 2,+ lines: [{ item: "TRM-BLK-6P", quantity: 6, fromShelf: "A1-L2" }]+ }+];export const motorInventory: InventoryData = {openingStock: OPENING_STOCK,onHandTracked: ON_HAND_TRACKED,kanbanItems: KANBAN_ITEMS,- inventoryCount: INVENTORY_COUNT+ inventoryCounts: INVENTORY_COUNTS,+ shelfLives: SHELF_LIVES,+ stockTransfers: STOCK_TRANSFERS,+ warehouseTransfers: WAREHOUSE_TRANSFERS};diff --git a/packages/database/src/datasets/data/motor/items.ts b/packages/database/src/datasets/data/motor/items.tsindex f0df396885..7e72e552ef 100644--- a/packages/database/src/datasets/data/motor/items.ts+++ b/packages/database/src/datasets/data/motor/items.ts@@ -1,9 +1,19 @@-import type { ItemSpec } from "../../helpers/items.ts";import type {+ BatchPropertySpec,+ ConfigurationSpec,+ CustomerPartSpec,+ EnforcementRuleSpec,+ InspectionPlanSpec,+ ItemSpec,ItemsData,MakeMethodSpec,+ PriceOverrideSpec,+ PricingRuleSpec,+ RevisionLadderSpec,+ SupersessionSpec,SupplierLinkSpec} from "../../types.ts";+import { motorAssembly } from "./assembly.ts";// ---------------------------------------------------------------------------// Motor item catalog for Torque Dynamics LLC.@@ -126,6 +136,16 @@ export const BUY_PARTS: ItemSpec[] = [standardCost: 2.25,unitSalePrice: 3.8,leadTime: 12+ },+ // Deliberately absent from every BOM: job creation and picking redirect to it via SUPERSESSIONS.+ {+ readableId: "BRG-6206-HYB",+ name: "Hybrid Ceramic Bearing 6206 (Si3N4 balls)",+ type: "Part",+ replenishment: "Buy",+ standardCost: 34,+ unitSalePrice: 52,+ leadTime: 28}];@@ -137,7 +157,15 @@ export const MATERIALS: ItemSpec[] = [trackingType: "Batch",standardCost: 1.85,unitOfMeasureCode: "LB",- leadTime: 28+ leadTime: 28,+ material: {+ substance: "Electrical Steel",+ form: "Lamination Coil",+ materialType: "Electrical Steel Lamination Coil",+ grade: "M19",+ finish: "C5 Insulation Coating",+ dimension: "0.35mm x 200mm"+ }},{readableId: "MAT-CU-18AWG",@@ -147,7 +175,13 @@ export const MATERIALS: ItemSpec[] = [trackingType: "Batch",standardCost: 6.4,unitOfMeasureCode: "LB",- leadTime: 21+ leadTime: 21,+ // Partially classified on purpose.+ material: {+ substance: "Enameled Copper",+ grade: "MW 35-C",+ finish: "Polyamide-Imide Overcoat"+ }},{readableId: "MAT-INS-NOMEX",@@ -235,7 +269,7 @@ export const MAKE_PARTS: ItemSpec[] = [replenishment: "Make",// Serial-tracked: every finished motor gets its own genealogy and nameplate.trackingType: "Serial",- standardCost: 0,+ standardCost: 2670,unitSalePrice: 4850},{@@ -244,7 +278,7 @@ export const MAKE_PARTS: ItemSpec[] = [type: "Part",replenishment: "Make",trackingType: "Serial",- standardCost: 0,+ standardCost: 1620,unitSalePrice: 2950},{@@ -252,7 +286,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Stator Assembly (9000 Frame)",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 649,unitSalePrice: 1180},{@@ -260,7 +294,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Stator Assembly (4500 Frame)",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 429,unitSalePrice: 780},{@@ -268,7 +302,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Rotor Assembly (9000 Frame)",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 781,unitSalePrice: 1420},{@@ -276,7 +310,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Motor Housing & End Bells (9000 Frame)",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 352,unitSalePrice: 640},{@@ -284,7 +318,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Precision Motor Shaft (9000 Frame)",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 116,unitSalePrice: 210},{@@ -292,7 +326,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Wound Coil Set (9000 Frame)",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 264,unitSalePrice: 480},{@@ -300,7 +334,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Stator Lamination Stack",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 143,unitSalePrice: 260},{@@ -308,7 +342,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Rotor Lamination Stack",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 105,unitSalePrice: 190},{@@ -316,7 +350,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Terminal Box Assembly",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 90.75,unitSalePrice: 165}];@@ -356,6 +390,8 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "Lamination Press",description: "Blank, stack and bond rotor laminations",order: 1,+ setupTime: 0.75,+ machineTime: 0.5,laborTime: 1},{@@ -376,6 +412,8 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "CNC Turning Cell",description: "Turn and grind shaft journals and keyway",order: 1,+ setupTime: 0.5,+ machineTime: 1.25,laborTime: 1.5},// Sent out to Maumee for nitride between turning and final inspection.@@ -395,7 +433,9 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "CMM Inspection Bench",description: "Journal diameter and runout check",order: 3,- laborTime: 0.5+ laborTime: 0.5,+ operationType: "Inspection",+ inspectionPlan: "SHF-9000-JOURNAL"}]},@@ -411,6 +451,8 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "Winding Line 1",description: "Wind and form the coil set",order: 1,+ setupTime: 0.5,+ machineTime: 2,laborTime: 2.5},{@@ -472,7 +514,13 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "Motor Assembly Bench",description: "Press stack to shaft and bond magnet segments",order: 1,- laborTime: 2.5+ setupTime: 0.5,+ laborTime: 2.5,+ tools: [{ tool: "TL-ARBOR-PRESS", quantity: 1 }],+ parameters: [+ { key: "Press-Fit Force", value: "35 kN max" },+ { key: "Epoxy Cure", value: "80 degC for 2 hours" }+ ]},{process: "Rotor Balancing",@@ -480,7 +528,14 @@ export const METHODS: MakeMethodSpec[] = [description: "Two-plane dynamic balance",order: 2,laborTime: 1,- procedure: "procedure:Rotor Balance Verification"+ procedure: "procedure:Rotor Balance Verification",+ parameters: [+ { key: "Balance Grade", value: "ISO 21940 G2.5 at 3000 rpm" },+ {+ key: "Correction Method",+ value: "Material removal, drive-end plane first"+ }+ ]},{process: "In-Process Inspection",@@ -761,10 +816,265 @@ export const SUPPLIER_LINKS: SupplierLinkSpec[] = [item: "FST-M10-SS",price: 1.15,leadTime: 10+ },+ {+ supplier: "Summit Bearing Supply",+ item: "BRG-6206-HYB",+ price: 34,+ leadTime: 28+ }+];++// MTR-4500 still names BRG-6206-C3 (60 on shelf A2-L1), so Consume First+// keeps pulling the steel bearing until the shelf is empty, then swaps to+// the hybrid ceramic.+export const SUPERSESSIONS: SupersessionSpec[] = [+ {+ predecessor: "BRG-6206-C3",+ successor: "BRG-6206-HYB",+ mode: "Consume First",+ successorEffectivityOffset: -14+ }+];++export const CUSTOMER_PARTS: CustomerPartSpec[] = [+ {+ item: "MTR-9000",+ customer: "Ridgeline Drive Systems",+ customerPartId: "RDS-MTR-9000",+ customerRevision: "B"+ },+ {+ item: "MTR-4500",+ customer: "Cardinal Motorworks",+ customerPartId: "CMW-SRV-4500"+ }+];++export const PRICE_OVERRIDES: PriceOverrideSpec[] = [+ {+ item: "MTR-4500",+ customer: "Cardinal Motorworks",+ notes: "Blanket-order pricing for the CY conveyor retrofit program.",+ breaks: [+ { quantity: 10, overridePrice: 2900 },+ { quantity: 50, overridePrice: 2760 }+ ]+ }+];++export const PRICING_RULES: PricingRuleSpec[] = [+ {+ name: "Ridgeline OEM volume discount",+ ruleType: "Discount",+ amountType: "Percentage",+ amount: 5,+ customer: "Ridgeline Drive Systems",+ minQuantity: 10,+ priority: 10+ },+ {+ name: "Aerospace documentation markup",+ ruleType: "Markup",+ amountType: "Percentage",+ amount: 8,+ customerType: "Aerospace",+ items: ["MTR-4500", "MTR-9000"],+ priority: 5+ },+ {+ name: "Distributor spares case break",+ ruleType: "Discount",+ amountType: "Percentage",+ amount: 6,+ customerType: "Distribution",+ items: ["BRG-6206-C3", "BRG-6308-C3", "FAN-AX-160"],+ minQuantity: 20,+ priority: 1+ }+];++export const CONFIGURATION: ConfigurationSpec = {+ item: "MTR-9000",+ group: "Drive Configuration",+ parameters: [+ {+ key: "shaft_extension_mm",+ label: "Shaft Extension Length (mm)",+ dataType: "numeric"+ },+ {+ key: "mounting_flange",+ label: "Mounting Flange",+ dataType: "list",+ listOptions: ["IEC B5", "IEC B14", "NEMA C-Face"]+ },+ {+ key: "holding_brake",+ label: "Include Holding Brake",+ dataType: "boolean"+ }+ ],+ rules: [+ {+ target: { operation: 1 },+ field: "laborTime",+ code: "return params.holding_brake ? 5 : 4;"+ },+ {+ target: { operation: 2 },+ field: "laborTime",+ code: "return params.shaft_extension_mm > 80 ? 3.5 : 3;"+ }+ ]+};++export const REVISION_LADDER: RevisionLadderSpec[] = [+ {+ item: "HSG-9000",+ obsoleteRevision: "A",+ nextRevision: "B",+ nextStatus: "Prototype"+ }+];++// A sampling plan of its own makes the MES open an inspection lot, not a plain operation.+export const INSPECTION_PLANS: InspectionPlanSpec[] = [+ {+ key: "SHF-9000-JOURNAL",+ item: "SHF-9000",+ drawingNumber: "TD-9000-SH Rev E",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Drive-end bearing journal diameter",+ nominalValue: "40.010",+ tolerancePlus: "0.008",+ toleranceMinus: "0.008",+ unit: "mm"+ },+ {+ label: "2",+ description: "Journal runout, drive end to non-drive end",+ nominalValue: "0.008",+ tolerancePlus: "0.007",+ toleranceMinus: "0.008",+ unit: "mm"+ }+ ]+ }+];++export const ENFORCEMENT_RULES: EnforcementRuleSpec[] = [+ {+ family: "sales",+ name: "Traction motor — US and Canada ship-to only",+ description: "EAR99 review pending for the 9000-series drive.",+ message:+ "The MTR-9000 is cleared for US and Canadian customers only. Route export requests through Trade Compliance.",+ severity: "error",+ surfaces: ["salesOrderLine", "salesInvoiceLine"],+ match: "all",+ conditions: [+ {+ field: "customer.location.countryCode",+ op: "in",+ value: ["US", "CA"]+ }+ ],+ items: ["MTR-9000"]+ },+ {+ family: "sales",+ name: "Distributors order the 4500 by the pallet",+ message:+ "Distribution partners order the MTR-4500 in pallet quantities (4 or more).",+ severity: "warn",+ surfaces: ["quoteLine", "salesOrderLine"],+ match: "any",+ conditions: [+ {+ field: "customer.customerTypeId",+ op: "notIn",+ value: { customerTypes: ["Distribution"] }+ },+ { field: "transaction.quantity", op: "gt", value: 3 }+ ],+ items: ["MTR-4500"]+ },+ {+ family: "storage",+ targetType: "item",+ name: "Magnets in the cabinet",+ message:+ "Sintered NdFeB magnets are stored in the shielded cabinet, never on open shelving.",+ severity: "warn",+ surfaces: ["place"],+ match: "all",+ conditions: [+ {+ field: "storageUnit.storageTypeId",+ op: "eq",+ value: { storageType: "Cabinet" }+ }+ ],+ items: ["MAG-NDFB-45", "MAG-NDFB-38"]+ },+ {+ family: "storage",+ targetType: "item",+ name: "Encoders stay at the plant",+ message:+ "Encoders are kitted at the Fort Wayne plant only — pick a plant bin.",+ severity: "warn",+ surfaces: ["receipt", "stockTransfer"],+ match: "all",+ conditions: [+ {+ field: "storageUnit.locationId",+ op: "eq",+ value: { location: "Plant" }+ }+ ],+ items: ["ENC-INC-2048"]+ },+ {+ family: "storage",+ targetType: "workCenter",+ name: "Impregnation oven in service",+ message:+ "The impregnation oven is out of service — hold the cure until maintenance releases it.",+ severity: "error",+ surfaces: ["operationStart"],+ match: "all",+ conditions: [{ field: "workCenter.active", op: "eq", value: true }],+ workCenters: ["Impregnation Oven"]+ }+];++export const BATCH_PROPERTIES: BatchPropertySpec[] = [+ { item: "MAG-NDFB-45", label: "Magnetization lot", dataType: "text" },+ {+ item: "MAG-NDFB-45",+ label: "Coercivity grade",+ dataType: "list",+ listOptions: ["SH", "UH"]+ },+ { item: "MAG-NDFB-38", label: "Magnetization lot", dataType: "text" },+ { item: "MAT-LAM-M19", label: "Coil number", dataType: "text" },+ { item: "MAT-LAM-M19", label: "Core loss (W/kg)", dataType: "numeric" },+ { item: "MAT-CU-18AWG", label: "Spool number", dataType: "text" },+ {+ item: "MAT-CU-18AWG",+ label: "Insulation class",+ dataType: "list",+ listOptions: ["H", "N"]}];export const motorItems: ItemsData = {+ assembly: motorAssembly,buyParts: BUY_PARTS,materials: MATERIALS,consumables: CONSUMABLES,@@ -772,5 +1082,14 @@ export const motorItems: ItemsData = {services: SERVICES,makeParts: MAKE_PARTS,methods: METHODS,- supplierLinks: SUPPLIER_LINKS+ supplierLinks: SUPPLIER_LINKS,+ supersessions: SUPERSESSIONS,+ customerParts: CUSTOMER_PARTS,+ priceOverrides: PRICE_OVERRIDES,+ pricingRules: PRICING_RULES,+ configuration: CONFIGURATION,+ revisionLadder: REVISION_LADDER,+ inspectionPlans: INSPECTION_PLANS,+ enforcementRules: ENFORCEMENT_RULES,+ batchProperties: BATCH_PROPERTIES};diff --git a/packages/database/src/datasets/data/motor/ops.ts b/packages/database/src/datasets/data/motor/ops.tsnew file mode 100644index 0000000000..a8f257a809--- /dev/null+++ b/packages/database/src/datasets/data/motor/ops.ts@@ -0,0 +1,592 @@+import type {+ CustomFieldSpec,+ MaintenanceDispatchSpec,+ MaintenanceScheduleSpec,+ NoteSpec,+ OpenTimecardSpec,+ OpsData,+ PeopleAbsenceSpec,+ PeopleAssignmentSpec,+ PrintJobSpec,+ ReplacementPartSpec,+ SerialSequenceSpec,+ SuggestionSpec,+ TimecardSpec,+ TrainingSpec,+ UserAttributeCategorySpec+} from "../../types.ts";++export const MAINTENANCE_SCHEDULES: MaintenanceScheduleSpec[] = [+ {+ key: "winding-tension",+ name: "Winding line wire-tensioner & nozzle check",+ description:+ "Verify the tensioner setpoint with the gauge, inspect the needle nozzles for enamel scrape and clear the wire guides.",+ workCenter: "Winding Line 1",+ frequency: "Daily",+ priority: "Medium",+ estimatedDuration: 20,+ nextDueOffset: 1+ },+ {+ key: "oven-profile",+ name: "Impregnation oven zone temperature check",+ description:+ "Log each zone against the varnish cure profile with the reference thermocouple and clean the exhaust filter.",+ workCenter: "Impregnation Oven",+ frequency: "Weekly",+ priority: "Medium",+ estimatedDuration: 45,+ nextDueOffset: 2+ },+ {+ key: "balancer-spindle",+ name: "Balancing machine spindle bearing re-grease",+ description:+ "Re-grease the balancer's drive-end bearings and run the reference rotor to confirm the unbalance reading.",+ workCenter: "Balancing Cell",+ frequency: "Monthly",+ priority: "High",+ estimatedDuration: 60,+ nextDueOffset: 17,+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-BRG-GREASE", quantity: 1 }]+ },+ {+ key: "press-die",+ name: "Lamination press die sharpen & shim",+ description:+ "Measure burr height on the stator laminations and send the die out for sharpening when it passes 25 µm.",+ workCenter: "Lamination Press",+ frequency: "Quarterly",+ priority: "High",+ estimatedDuration: 240,+ nextDueOffset: 39,+ takesWorkCenterOffline: true+ },+ {+ key: "dyno-cert",+ name: "Annual dynamometer torque-cell calibration",+ description:+ "Third-party calibration of the dyno torque transducer and speed encoder against traceable standards.",+ workCenter: "Dyno Test Cell",+ frequency: "Annual",+ priority: "High",+ estimatedDuration: 420,+ nextDueOffset: 155,+ takesWorkCenterOffline: true+ },+ {+ key: "proto-winder-cal",+ name: "Prototype winder tension calibration",+ description:+ "Check the lab winder's tensioner against the reference spring gauge at three setpoints and log the correction.",+ workCenter: "Prototype Winding Lab",+ frequency: "Monthly",+ priority: "Medium",+ estimatedDuration: 45,+ nextDueOffset: 9+ }+];++// Shapes the maintenance KPIs and boards read: a failure on a production day,+// back-dated completions, today's scheduled task, a machine down now, one at HQ.+export const MAINTENANCE_DISPATCHES: MaintenanceDispatchSpec[] = [+ {+ key: "winding-nozzle",+ status: "Open",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Winding Line 1",+ suspectedFailureMode: "Excessive Wear",+ content:+ "Needle nozzle on head 2 scraping enamel — two stators failed the surge test on the first shift. Running head 1 only until it's swapped.",+ created: { offset: -1, time: "08:15:00" },+ plannedStart: { offset: 1, time: "06:00:00" },+ plannedEnd: { offset: 1, time: "08:00:00" }+ },+ {+ key: "balancer-vibration",+ status: "Assigned",+ priority: "Critical",+ severity: "OEM Required",+ source: "Non-Conformance",+ oeeImpact: "Down",+ workCenter: "Balancing Cell",+ nonConformance: "ncr:fan-noise",+ suspectedFailureMode: "Excessive Vibration",+ content:+ "Balancer reading 40% high on the reference rotor after the fan-noise escapes. Cell locked out; OEM field service booked to check the sensor and drive belt.",+ created: { offset: -5, time: "15:10:00" },+ plannedStart: { offset: 2, time: "08:00:00" },+ plannedEnd: { offset: 2, time: "14:00:00" },+ takesWorkCenterOffline: true,+ comments: [+ "OEM confirmed a replacement velocity sensor is on the truck.",+ "Rotors are balanced on the backup machine at half rate until then."+ ]+ },+ {+ key: "cmm-temp-comp",+ status: "In Progress",+ priority: "Low",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "No Impact",+ workCenter: "CMM Inspection Bench",+ suspectedFailureMode: "Misalignment",+ content:+ "Shaft journal readings drifting 3 µm between morning and afternoon. Re-running the temperature compensation and re-qualifying the probe.",+ created: { offset: -1, time: "12:50:00" },+ plannedStart: { offset: -1, time: "13:00:00" },+ plannedEnd: { offset: -1, time: "14:00:00" },+ actualStart: { offset: -1, time: "13:10:00" }+ },+ {+ key: "balancer-regrease",+ status: "Completed",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Balancing Cell",+ schedule: "balancer-spindle",+ actualFailureMode: "Overheating",+ content:+ "Monthly spindle re-grease. Drive-end bearing housing was running hot at 68 °C — purged the old grease, re-packed and re-ran the reference rotor.",+ created: { offset: -11, time: "06:00:00" },+ plannedStart: { offset: -10, time: "12:00:00" },+ plannedEnd: { offset: -10, time: "13:00:00" },+ actualStart: { offset: -10, time: "12:05:00" },+ actualEnd: { offset: -10, time: "13:40:00" },+ takesWorkCenterOffline: true,+ // Deliberately more than the kit's one pound.+ spareParts: [{ item: "CN-BRG-GREASE", quantity: 2, shelf: "A2-L2" }],+ comments: ["Bearing housing after re-pack: 41 °C at full speed."]+ },+ {+ key: "oven-profile-skip",+ status: "Cancelled",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Impregnation Oven",+ schedule: "oven-profile",+ content:+ "Weekly zone check. Cancelled — the oven was profiled the day before during the varnish-lot changeover.",+ created: { offset: -7, time: "06:00:00" },+ plannedStart: { offset: -6, time: "10:00:00" },+ plannedEnd: { offset: -6, time: "10:45:00" }+ },+ {+ key: "winding-tension-today",+ status: "Assigned",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Winding Line 1",+ schedule: "winding-tension",+ content:+ "Daily tensioner and nozzle check: verify the setpoint with the gauge, inspect the needle nozzles for enamel scrape, clear the wire guides.",+ created: { offset: -1, time: "06:00:00" },+ plannedStart: { offset: 0, time: "14:00:00" },+ plannedEnd: { offset: 0, time: "14:20:00" }+ },+ {+ key: "press-lube-pump",+ status: "In Progress",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Down",+ workCenter: "Lamination Press",+ suspectedFailureMode: "Lubrication Failure",+ content:+ "Die lubrication pump lost prime — the press faulted on low lube pressure mid-run. Press locked out while the pump is primed and the check valve replaced.",+ created: { offset: -1, time: "15:10:00" },+ plannedStart: { offset: -1, time: "15:30:00" },+ plannedEnd: { offset: 1, time: "10:00:00" },+ actualStart: { offset: -1, time: "15:35:00" },+ takesWorkCenterOffline: true,+ comments: [+ "Check valve on order; die clamp bolts re-torqued while the press is open."+ ]+ },+ {+ key: "assembly-bearing-heater",+ status: "Completed",+ priority: "Medium",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Motor Assembly Bench",+ suspectedFailureMode: "Electrical Fault",+ actualFailureMode: "Electrical Fault",+ content:+ "Induction bearing heater stopped at 60 °C mid-cycle — thermocouple lead broken at the magnetic probe. Lead replaced; heater reaching 110 °C again.",+ created: { offset: -9, time: "14:15:00" },+ plannedStart: { offset: -9, time: "14:20:00" },+ plannedEnd: { offset: -9, time: "15:00:00" },+ actualStart: { offset: -9, time: "14:25:00" },+ actualEnd: { offset: -9, time: "14:55:00" }+ },+ {+ key: "balancer-regrease-prior",+ status: "Completed",+ priority: "High",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Balancing Cell",+ schedule: "balancer-spindle",+ content:+ "Monthly balancer spindle re-grease; reference rotor read 0.4 g·mm after the run-in.",+ created: { offset: -44, time: "06:00:00" },+ plannedStart: { offset: -43, time: "10:00:00" },+ plannedEnd: { offset: -43, time: "11:00:00" },+ actualStart: { offset: -43, time: "10:05:00" },+ actualEnd: { offset: -43, time: "10:55:00" },+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-BRG-GREASE", quantity: 1, shelf: "A2-L2" }]+ },+ {+ key: "oven-door-seal",+ status: "Completed",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Down",+ workCenter: "Impregnation Oven",+ suspectedFailureMode: "Leak",+ actualFailureMode: "Leak",+ content:+ "Oven door gasket split along the hinge side — zone 2 could not hold 160 °C for the cure. Gasket replaced and the zone re-profiled before releasing the oven.",+ created: { offset: -53, time: "08:30:00" },+ plannedStart: { offset: -53, time: "09:00:00" },+ plannedEnd: { offset: -53, time: "15:00:00" },+ actualStart: { offset: -53, time: "09:10:00" },+ actualEnd: { offset: -52, time: "09:40:00" },+ takesWorkCenterOffline: true+ },+ {+ key: "proto-winder-encoder",+ status: "Open",+ priority: "Medium",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Prototype Winding Lab",+ suspectedFailureMode: "Electrical Fault",+ content:+ "The lab winder's turn counter skips counts above 600 rpm — encoder cable shield looks chafed at the drag chain.",+ created: { offset: -2, time: "13:00:00" },+ plannedStart: { offset: 2, time: "09:00:00" },+ plannedEnd: { offset: 2, time: "10:30:00" }+ }+];++export const REPLACEMENT_PARTS: ReplacementPartSpec[] = [+ { workCenter: "Balancing Cell", item: "BRG-6206-C3", quantity: 2 },+ { workCenter: "Impregnation Oven", item: "FAN-AX-160", quantity: 1 },+ { workCenter: "Lamination Press", item: "FST-M10-SS", quantity: 8 }+];++export const TRAININGS: TrainingSpec[] = [+ {+ name: "Rare-Earth Magnet Handling",+ description: "Safe handling, storage and bonding of NdFeB rotor magnets.",+ status: "Active",+ frequency: "Once",+ type: "Mandatory",+ estimatedDuration: "30m",+ content: [+ "Rotor magnets pinch hard and chip easily. Keep them in their spacers until they go into the rotor, and never let two free magnets meet.",+ "Magnetized rotors stay away from the CMM and anyone with an implanted medical device."+ ],+ questions: [+ {+ type: "MultipleChoice",+ question:+ "How are loose magnets moved between the bench and the rotor?",+ options: [+ "In a pocket",+ "In their non-magnetic spacers",+ "Stacked together",+ "On a steel tray"+ ],+ correct: "In their non-magnetic spacers"+ },+ {+ type: "TrueFalse",+ question:+ "A chipped magnet may still be bonded if the chip is on the inner face.",+ answer: false+ },+ {+ type: "MultipleAnswers",+ question:+ "Which of these must stay clear of a magnetized rotor? Select all that apply.",+ options: [+ "Pacemakers",+ "Steel hand tools",+ "The CMM probe",+ "Nitrile gloves",+ "Magnetic ID badges"+ ],+ correct: [+ "Pacemakers",+ "Steel hand tools",+ "The CMM probe",+ "Magnetic ID badges"+ ]+ },+ {+ type: "MatchingPairs",+ question: "Match each step to its purpose.",+ pairs: [+ { left: "Spacer", right: "Keeps magnets from snapping together" },+ {+ left: "Bonding epoxy",+ right: "Holds the magnet to the rotor core"+ },+ { left: "Magnetizer", right: "Charges the finished rotor" }+ ]+ },+ {+ type: "Numerical",+ question:+ "What is the minimum epoxy cure time before a bonded rotor can be balanced, in hours?",+ answer: 24,+ tolerance: 0+ }+ ],+ assignment: { completedOffset: -18 }+ },+ {+ name: "Winding & Surge Test Basics",+ description:+ "Coil winding, enamel care and the surge test acceptance limits.",+ status: "Active",+ frequency: "Annual",+ type: "Mandatory",+ estimatedDuration: "40m",+ content: [+ "Every stator gets a surge test before impregnation. A scraped enamel turn shows up as a waveform mismatch — scrap it, never re-varnish over it."+ ],+ questions: [+ {+ type: "MultipleChoice",+ question: "When does a stator get its surge test?",+ options: [+ "After impregnation",+ "Before impregnation",+ "Only on customer request"+ ],+ correct: "Before impregnation"+ },+ {+ type: "TrueFalse",+ question:+ "A stator with a failed surge test can be re-varnished and shipped.",+ answer: false+ }+ ],+ assignment: {}+ },+ {+ name: "Dynamometer Test Cell Operation",+ description:+ "Operator qualification for running motor performance curves on the dyno.",+ status: "Draft",+ frequency: "Once",+ type: "Optional",+ estimatedDuration: "60m",+ content: [+ "Draft — mounting, coupling alignment and the torque-speed sweep for production motors."+ ],+ questions: [+ {+ type: "Numerical",+ question:+ "What is the maximum coupling misalignment allowed on the dyno, in mm?",+ answer: 0.05,+ tolerance: 0.01+ }+ ]+ }+];++export const TIMECARDS: TimecardSpec[] = [+ { dayOffset: -5, clockIn: "06:30:00", clockOut: "15:02:00" },+ { dayOffset: -4, clockIn: "06:28:00", clockOut: "15:05:00" },+ { dayOffset: -3, clockIn: "06:33:00", clockOut: "15:00:00" },+ {+ dayOffset: -2,+ clockIn: "06:25:00",+ clockOut: "17:40:00",+ note: "Stayed to run the Halcyon actuator motors through the dyno."+ },+ { dayOffset: -1, clockIn: "06:31:00", clockOut: "11:00:00" },+ { dayOffset: -1, clockIn: "11:30:00", clockOut: "15:03:00" }+];++// Clocked in before the first timer on the floor started this morning.+export const OPEN_TIMECARD: OpenTimecardSpec = { clockIn: "06:29:00" };++// None on today, so the MES schedule opens on every work center, not one station.+export const PEOPLE_ASSIGNMENTS: PeopleAssignmentSpec[] = [+ { dayOffset: -2, workCenter: "Winding Line 1", shift: "A Shift" },+ { dayOffset: -1, workCenter: "Motor Assembly Bench", shift: "A Shift" },+ {+ dayOffset: 1,+ workCenter: "CNC Turning Cell",+ shift: "A Shift",+ note: "Cover shaft turning while the setter is on leave."+ },+ { dayOffset: 2, workCenter: "Winding Line 1", shift: "A Shift" },+ {+ dayOffset: 3,+ workCenter: "Dyno Test Cell",+ shift: "A Shift",+ overtimeHours: 2,+ note: "Witness the Halcyon actuator dyno run."+ },+ { dayOffset: 4, workCenter: "Motor Assembly Bench", shift: "A Shift" }+];++export const PEOPLE_ABSENCES: PeopleAbsenceSpec[] = [+ {+ dayOffset: 9,+ note: "NFPA 70E arc-flash safety training."+ }+];++export const SUGGESTIONS: SuggestionSpec[] = [+ {+ suggestion:+ "Warn on the maintenance list when a dispatch takes the balancing cell offline while rotor jobs are queued for it.",+ emoji: "⚙️",+ path: "/x/resources/maintenance",+ tags: ["Maintenance"]+ },+ {+ suggestion:+ "Let planners see magnet lot shelf life on the purchasing planning screen.",+ emoji: "🧲",+ path: "/x/purchasing/planning"+ }+];++export const NOTES: NoteSpec[] = [+ {+ text: "Qualified on the new surge tester — can release stators to impregnation on second shift."+ },+ {+ text: "Point of contact for the balancer OEM visit while the maintenance lead is out."+ }+];++export const USER_ATTRIBUTE_CATEGORIES: UserAttributeCategorySpec[] = [+ {+ name: "Winding & Electrical Safety",+ emoji: "⚡",+ public: true,+ attributes: [+ {+ name: "NFPA 70E arc-flash training expires",+ dataType: "Date",+ valueOffset: 61+ },+ {+ name: "Hipot tester authorization",+ dataType: "List",+ listOptions: ["None", "Supervised", "Independent"],+ value: "Independent"+ },+ { name: "Electrical work permit signer", dataType: "User" },+ {+ name: "Qualified electrical worker",+ dataType: "Yes/No",+ value: true,+ canSelfManage: true+ }+ ]+ }+];++export const CUSTOM_FIELDS: CustomFieldSpec[] = [+ { table: "part", name: "NEMA frame", dataType: "Text" },+ { table: "customer", name: "Application engineer", dataType: "User" },+ { table: "job", name: "Hipot witness required", dataType: "Yes/No" }+];++export const SERIAL_SEQUENCES: SerialSequenceSpec[] = [+ // Continues the supplier's numbering already on the shelf (…-0036).+ { item: "ENC-INC-2048", prefix: "ENC2048-SN-", size: 4, next: 36 },+ { item: "MTR-9000", prefix: "MTR9000-SN-", size: 4, next: 1 },+ { item: "MTR-4500", prefix: "MTR4500-SN-", size: 4, next: 0 }+];++export const PRINT_JOBS: PrintJobSpec[] = [+ {+ source: { kind: "Receipt", receipt: "receipt:copperline-restock" },+ item: "TRM-BLK-6P",+ status: "completed",+ origin: "auto",+ at: { offset: -2, time: "15:26:00" },+ attempts: 1+ },+ {+ source: { kind: "Job", job: "done-rotor" },+ item: "ROT-9000",+ status: "completed",+ origin: "manual",+ at: { offset: -3, time: "19:55:00" },+ attempts: 1+ },+ {+ source: { kind: "StorageUnit", shelf: "A1-L1" },+ status: "completed",+ origin: "manual",+ at: { offset: -6, time: "16:30:00" },+ attempts: 1+ },+ {+ source: { kind: "Job", job: "floor-stator" },+ item: "STA-4500",+ status: "failed",+ origin: "auto",+ at: { offset: -1, time: "13:50:00" },+ attempts: 3,+ error: "Printer did not respond after 3 attempts (connection timed out)"+ },+ {+ source: { kind: "Job", job: "floor-stator" },+ item: "STA-4500",+ status: "queued",+ origin: "reprint",+ at: { offset: 0, time: "06:48:00" },+ attempts: 0+ }+];++export const motorOps: OpsData = {+ userAttributeCategories: USER_ATTRIBUTE_CATEGORIES,+ customFields: CUSTOM_FIELDS,+ serialSequences: SERIAL_SEQUENCES,+ printJobs: PRINT_JOBS,+ maintenanceSchedules: MAINTENANCE_SCHEDULES,+ maintenanceDispatches: MAINTENANCE_DISPATCHES,+ replacementParts: REPLACEMENT_PARTS,+ trainings: TRAININGS,+ timecards: TIMECARDS,+ openTimecard: OPEN_TIMECARD,+ peopleAssignments: PEOPLE_ASSIGNMENTS,+ peopleAbsences: PEOPLE_ABSENCES,+ suggestions: SUGGESTIONS,+ notes: NOTES+};diff --git a/packages/database/src/datasets/data/motor/planning.ts b/packages/database/src/datasets/data/motor/planning.tsindex 0c1d9b8de8..3d5686aa40 100644--- a/packages/database/src/datasets/data/motor/planning.ts+++ b/packages/database/src/datasets/data/motor/planning.ts@@ -1,6 +1,7 @@import type {DemandOrderSpec,DemandProjectionSpec,+ HqPlanningSpec,PlanningData} from "../../types.ts";@@ -62,9 +63,15 @@ export const DEMAND_ORDER: DemandOrderSpec = {]};+export const HQ_PLANNING: HqPlanningSpec = {+ reorderItemIds: ["MTR-4500", "ENC-INC-2048"],+ demandProjections: [{ readableId: "MTR-4500", quantities: [2, 2, 2, 3] }]+};+export const motorPlanning: PlanningData = {buyItemIds: BUY_ITEM_IDS,makeItemIds: MAKE_ITEM_IDS,demandProjections: DEMAND_PROJECTIONS,- demandOrder: DEMAND_ORDER+ demandOrder: DEMAND_ORDER,+ hq: HQ_PLANNING};diff --git a/packages/database/src/datasets/data/motor/production.ts b/packages/database/src/datasets/data/motor/production.tsindex e741f68727..853b805cf2 100644--- a/packages/database/src/datasets/data/motor/production.ts+++ b/packages/database/src/datasets/data/motor/production.ts@@ -2,10 +2,10 @@ import type {GenealogyAssemblySpec,GenealogyInputSpec,JobSpec,+ PickingListSpec,ProductionData,ShiftEventSpec} from "../../types.ts";-import { motorAssembly } from "./assembly.ts";export const JOBS: JobSpec[] = [{@@ -17,8 +17,31 @@ export const JOBS: JobSpec[] = [salesOrder: "so:ridgeline",salesOrderLine: "soline:ridgeline:mtr",customer: "Ridgeline Drive Systems",- dueDateOffset: -167,- releasedDateOffset: -297+ deadlineType: "Hard Deadline",+ dueDateOffset: 6,+ releasedDateOffset: -297,+ priority: 3,+ assignee: "self",+ operationOverrides: [+ { order: 1, status: "Done" },+ { order: 2, status: "In Progress", assignee: "self" },+ { order: 3, status: "Waiting" }+ ],+ quantities: [+ { order: 1, type: "Production", quantity: 1 },+ { order: 1, type: "Scrap", quantity: 2, scrapReason: "Defective" },+ { order: 2, type: "Rework", quantity: 1 }+ ],+ operationNotes: [+ {+ order: 1,+ note: "Bearing fit measured at 12 microns interference on units 1-3 — arbor press logs attached to the traveler for the Ridgeline data package."+ },+ {+ order: 2,+ note: "Loaded dyno run at 75% torque holding steady. Winding temp plateaued at 96C, well inside the Class H limit — thermal soak continues overnight."+ }+ ]},{key: "ready",@@ -28,8 +51,10 @@ export const JOBS: JobSpec[] = [salesOrder: "so:halcyon",salesOrderLine: "soline:halcyon:mtr",customer: "Halcyon Aerospace Actuation",- dueDateOffset: -153,- releasedDateOffset: -251+ deadlineType: "ASAP",+ dueDateOffset: 14,+ releasedDateOffset: -4,+ priority: 10},{key: "planned",@@ -39,7 +64,9 @@ export const JOBS: JobSpec[] = [salesOrder: "so:planned",salesOrderLine: "soline:planned",customer: "Cardinal Motorworks",- dueDateOffset: -90+ deadlineType: "Soft Deadline",+ dueDateOffset: 18,+ priority: 12},{key: "draft",@@ -49,7 +76,7 @@ export const JOBS: JobSpec[] = [salesOrder: "so:draft",salesOrderLine: "soline:draft",customer: "Wabash Industrial Supply",- dueDateOffset: -125+ deadlineType: "No Deadline"},{key: "paused",@@ -59,8 +86,9 @@ export const JOBS: JobSpec[] = [salesOrder: "so:paused",salesOrderLine: "soline:paused",customer: "Ridgeline Drive Systems",- dueDateOffset: -139,- releasedDateOffset: -266+ dueDateOffset: 9,+ releasedDateOffset: -266,+ priority: 6},{key: "completed",@@ -98,6 +126,215 @@ export const JOBS: JobSpec[] = [customer: "Wabash Industrial Supply",dueDateOffset: -314,releasedDateOffset: -337+ },++ // Released over the last few weeks so every cell has a queue and something running today.+ {+ key: "floor-stator",+ item: "STA-4500",+ status: "In Progress",+ quantity: 4,+ salesOrder: "so:floor-ridgeline",+ salesOrderLine: "soline:floor-ridgeline:stator",+ customer: "Ridgeline Drive Systems",+ dueDateOffset: 2,+ releasedDateOffset: -6,+ priority: 2,+ assignee: "self",+ operationOverrides: [+ { order: 1, status: "Done" },+ { order: 2, status: "Done" },+ {+ order: 3,+ status: "In Progress",+ assignee: "self",+ running: { type: "Machine", startTimeOfDay: "07:30:00" }+ },+ { order: 4, status: "Waiting" }+ ]+ },+ {+ key: "floor-lam-rotor",+ item: "LAM-STK-ROT",+ status: "Ready",+ quantity: 12,+ salesOrder: "so:floor-halcyon",+ salesOrderLine: "soline:floor-halcyon:lam-rotor",+ customer: "Halcyon Aerospace Actuation",+ dueDateOffset: 5,+ releasedDateOffset: -2,+ priority: 4,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ {+ key: "floor-shaft",+ item: "SHF-9000",+ status: "In Progress",+ quantity: 8,+ salesOrder: "so:floor-ridgeline",+ salesOrderLine: "soline:floor-ridgeline:shaft",+ customer: "Ridgeline Drive Systems",+ deadlineType: "Soft Deadline",+ dueDateOffset: 12,+ releasedDateOffset: -9,+ priority: 8,+ assignee: "self",+ operationOverrides: [+ {+ order: 1,+ status: "In Progress",+ assignee: "self",+ running: { type: "Setup", startTimeOfDay: "06:45:00" }+ },+ { order: 2, status: "Waiting" }+ ]+ },+ {+ key: "floor-coil",+ item: "COIL-9000",+ status: "In Progress",+ quantity: 6,+ salesOrder: "so:floor-halcyon",+ salesOrderLine: "soline:floor-halcyon:coil",+ customer: "Halcyon Aerospace Actuation",+ dueDateOffset: 7,+ releasedDateOffset: -5,+ priority: 5,+ operationOverrides: [+ {+ order: 1,+ status: "In Progress",+ running: { type: "Labor", startTimeOfDay: "08:15:00" }+ },+ { order: 2, status: "Waiting" }+ ]+ },+ {+ key: "floor-termbox",+ item: "TRM-BOX-9000",+ status: "In Progress",+ quantity: 10,+ salesOrder: "so:floor-ridgeline",+ salesOrderLine: "soline:floor-ridgeline:termbox",+ customer: "Ridgeline Drive Systems",+ deadlineType: "ASAP",+ dueDateOffset: 0,+ releasedDateOffset: -1,+ priority: 1,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ {+ key: "floor-housing",+ item: "HSG-9000",+ status: "Ready",+ quantity: 4,+ salesOrder: "so:floor-halcyon",+ salesOrderLine: "soline:floor-halcyon:housing",+ customer: "Halcyon Aerospace Actuation",+ dueDateOffset: 21,+ releasedDateOffset: -3,+ priority: 13+ },+ {+ key: "floor-rotor",+ item: "ROT-9000",+ status: "Ready",+ quantity: 2,+ salesOrder: "so:floor-halcyon",+ salesOrderLine: "soline:floor-halcyon:rotor",+ customer: "Halcyon Aerospace Actuation",+ deadlineType: "Soft Deadline",+ dueDateOffset: 16,+ releasedDateOffset: -4,+ priority: 11,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ // No deadline, so it lands in Priorities' Unscheduled column.+ {+ key: "floor-lam-stator",+ item: "LAM-STK-STA",+ status: "Ready",+ quantity: 6,+ salesOrder: "so:floor-halcyon",+ salesOrderLine: "soline:floor-halcyon:lam-stator",+ customer: "Halcyon Aerospace Actuation",+ deadlineType: "No Deadline",+ releasedDateOffset: -1,+ priority: 14+ },+ {+ key: "stock-lam-stator",+ item: "LAM-STK-STA",+ status: "Ready",+ quantity: 16,+ dueDateOffset: 11,+ releasedDateOffset: -2,+ priority: 9+ },+ {+ key: "stock-termbox",+ item: "TRM-BOX-9000",+ status: "In Progress",+ quantity: 20,+ deadlineType: "Soft Deadline",+ dueDateOffset: 9,+ releasedDateOffset: -3,+ priority: 7,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ // Feeds the completion-time and estimates-vs-actuals KPIs.+ {+ key: "done-coil",+ item: "COIL-9000",+ status: "Completed",+ quantity: 4,+ quantityComplete: 4,+ salesOrder: "so:floor-ridgeline",+ salesOrderLine: "soline:floor-ridgeline:coil",+ customer: "Ridgeline Drive Systems",+ dueDateOffset: -8,+ releasedDateOffset: -16,+ completedDateOffset: -11,+ loggedTime: { startOffset: -14, efficiency: 0.92 }+ },+ {+ key: "done-lam-rotor",+ item: "LAM-STK-ROT",+ status: "Completed",+ quantity: 10,+ quantityComplete: 10,+ salesOrder: "so:floor-ridgeline",+ salesOrderLine: "soline:floor-ridgeline:lam-rotor",+ customer: "Ridgeline Drive Systems",+ dueDateOffset: -20,+ releasedDateOffset: -28,+ completedDateOffset: -24,+ loggedTime: { startOffset: -27, efficiency: 1.18 }+ },+ {+ key: "done-rotor",+ item: "ROT-9000",+ status: "Completed",+ quantity: 1,+ quantityComplete: 1,+ salesOrder: "so:floor-ridgeline",+ salesOrderLine: "soline:floor-ridgeline:rotor",+ customer: "Ridgeline Drive Systems",+ dueDateOffset: -2,+ releasedDateOffset: -12,+ completedDateOffset: -4,+ loggedTime: { startOffset: -9, efficiency: 1.07 }+ },+ // Rotor insertion is still ahead, so the assembly bench has a build to play the 3D sequence on.+ {+ key: "stock-mtr",+ item: "MTR-9000",+ status: "Ready",+ quantity: 1,+ deadlineType: "Soft Deadline",+ dueDateOffset: 19,+ releasedDateOffset: -2,+ priority: 15}];@@ -187,12 +424,75 @@ export const GENEALOGY_ASSEMBLY: GenealogyAssemblySpec = {}};+export const PICKING_LISTS: PickingListSpec[] = [+ {+ key: "mtr-kit-1",+ status: "Completed",+ job: "in-progress",+ dateOffset: -20,+ lines: [+ {+ item: "FST-M6-SS",+ quantityRequired: 36,+ quantityPicked: 36,+ status: "Picked",+ fromShelf: "A1-L1"+ },+ {+ item: "FST-M10-SS",+ quantityRequired: 24,+ quantityPicked: 24,+ status: "Picked",+ fromShelf: "A1-L1"+ }+ ]+ },+ {+ key: "mtr-kit-2",+ status: "In Progress",+ job: "in-progress",+ dateOffset: -2,+ lines: [+ {+ item: "BRG-6308-C3",+ quantityRequired: 2,+ quantityPicked: 0,+ status: "Pending",+ fromShelf: "A2-L1"+ },+ {+ item: "CN-BRG-GREASE",+ quantityRequired: 1,+ quantityPicked: 0,+ status: "Short",+ fromShelf: "A2-L2"+ }+ ]+ }+];+export const motorProduction: ProductionData = {- assembly: motorAssembly,jobs: JOBS,shifts: SHIFTS,genealogyInputs: GENEALOGY_INPUTS,genealogyAssembly: GENEALOGY_ASSEMBLY,eventsJobKey: "in-progress",- genealogyJobKey: "in-progress"+ genealogyJobKey: "in-progress",+ // Must match the operation overridden to In Progress.+ openEvent: { operationOrder: 2 },+ batch: {+ members: [+ { job: "floor-termbox", order: 1 },+ { job: "stock-termbox", order: 1 }+ ],+ running: { type: "Machine", startTimeOfDay: "07:00:00" }+ },+ rework: {+ quantity: 1,+ reason:+ "Loaded dyno run flagged bearing noise on unit 3 — return it to the assembly bench for a drive-end bearing re-fit.",+ targetOperationOrder: 1,+ triggeredAtOperationOrder: 2+ },+ pickingLists: PICKING_LISTS};diff --git a/packages/database/src/datasets/data/motor/purchasing.ts b/packages/database/src/datasets/data/motor/purchasing.tsindex 9819017b36..c2d5139ae1 100644--- a/packages/database/src/datasets/data/motor/purchasing.ts+++ b/packages/database/src/datasets/data/motor/purchasing.ts@@ -1,9 +1,12 @@import type {+ LifecycleRfqSpec,PurchaseOrderSpec,+ PurchaseReturnSpec,PurchasingData,RfqHeaderSpec,RfqLineSpec,- RfqQuoteSpec+ RfqQuoteSpec,+ StandaloneSupplierQuoteSpec} from "../../types.ts";// Every RFQ line and every supplier quote prices the same quantity breaks, so@@ -26,6 +29,7 @@ export const RFQ_LINES: RfqLineSpec[] = [export const RFQ_QUOTES: RfqQuoteSpec[] = [{key: "meridian",+ assignee: "self",supplier: "Meridian Magnetics",supplierReference: "MM-Q-8812",shippingCost: 320,@@ -110,6 +114,7 @@ export const RFQ_ORDER_QUANTITY = 250;// 2 lines, finalized (Requested), fanned out to 3 suppliers.export const RFQ_HEADER: RfqHeaderSpec = {ref: "prfq:magnets",+ assignee: "self",status: "Requested",rfqDateOffset: -24,expirationOffset: 48,@@ -118,6 +123,42 @@ export const RFQ_HEADER: RfqHeaderSpec = {internalNotes: "Award on landed cost at 250 pcs unless the lot certs slip."};+export const LIFECYCLE_RFQS: LifecycleRfqSpec[] = [+ {+ ref: "prfq:bearings",+ status: "Draft",+ rfqDateOffset: -2,+ expirationOffset: 28,+ notes: "C3-clearance bearings for next quarter's frame builds.",+ internalNotes: "Ask for hybrid-ceramic pricing as an alternate.",+ quantities: [100, 250],+ lines: [+ {+ item: "BRG-6206-C3",+ description: "6206 deep groove ball bearing, C3 clearance"+ },+ {+ item: "BRG-6308-C3",+ description: "6308 deep groove ball bearing, C3 clearance"+ }+ ],+ suppliers: ["Summit Bearing Supply", "Ironwood Fasteners"]+ },+ {+ ref: "prfq:cooling-fan",+ status: "Closed",+ rfqDateOffset: -58,+ expirationOffset: -28,+ notes: "Axial cooling fans for the TEFC frame.",+ internalNotes: "Cancelled — TEFC redesign moved to an integral shaft fan.",+ quantities: [50, 150],+ lines: [+ { item: "FAN-AX-160", description: "160mm axial cooling fan, IP55" }+ ],+ suppliers: ["Summit Bearing Supply", "Maumee Contract Machining"]+ }+];+export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [{source: "direct",@@ -171,6 +212,7 @@ export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [source: "direct",log: "purchase order 3 — Draft (Summit Bearing)",ref: "po:summit",+ assignee: "self",supplier: "Summit Bearing Supply",purchaseOrderType: "Purchase",status: "Draft",@@ -187,6 +229,413 @@ export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [orderDateOffset: -8,currencyCode: "USD",exchangeRate: 1+ },++ {+ source: "direct",+ log: "purchase order — Planned (Meridian N45SH restock)",+ supplier: "Meridian Magnetics",+ purchaseOrderType: "Purchase",+ status: "Planned",+ orderDateOffset: -1,+ lines: [+ { item: "MAG-NDFB-45", purchaseQuantity: 120, supplierUnitPrice: 18.5 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — To Review (Copperline magnet wire)",+ assignee: "self",+ supplier: "Copperline Wire Works",+ purchaseOrderType: "Purchase",+ status: "To Review",+ orderDateOffset: -2,+ lines: [+ { item: "MAT-CU-18AWG", purchaseQuantity: 200, supplierUnitPrice: 6.4 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — Needs Approval (Summit hybrid ceramic bearings)",+ ref: "po:needs-approval",+ supplier: "Summit Bearing Supply",+ purchaseOrderType: "Purchase",+ status: "Needs Approval",+ orderDateOffset: -1,+ lines: [+ // Over the $5,000 approval tier.+ { item: "BRG-6206-HYB", purchaseQuantity: 160, supplierUnitPrice: 34 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — Rejected (Lakeland M19 surcharge too steep)",+ supplier: "Lakeland Electrical Steel",+ purchaseOrderType: "Purchase",+ status: "Rejected",+ orderDateOffset: -13,+ lines: [+ { item: "MAT-LAM-M19", purchaseQuantity: 1000, supplierUnitPrice: 2.05 }+ ]+ },++ {+ source: "direct",+ log: "purchase order — Completed, received in full and paid (Copperline)",+ ref: "po:wire-paid",+ supplier: "Copperline Wire Works",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -75,+ lines: [+ { item: "MAT-CU-18AWG", purchaseQuantity: 120, supplierUnitPrice: 6.55 },+ { item: "MAT-INS-NOMEX", purchaseQuantity: 20, supplierUnitPrice: 12.5 }+ ],+ receipt: {+ ref: "receipt:wire-paid",+ status: "Posted",+ postedOffset: -68,+ lines: [+ {+ item: "MAT-CU-18AWG",+ orderQuantity: 120,+ outstandingQuantity: 0,+ receivedQuantity: 120,+ unitPrice: 6.55,+ requiresBatchTracking: true,+ toShelf: "Winding-Crib",+ // Received -68 with the 270-day solderability cert → expires at +202.+ lotNumber: "LOT-CU18-2610",+ lotExpiresOffset: 202+ },+ {+ item: "MAT-INS-NOMEX",+ orderQuantity: 20,+ outstandingQuantity: 0,+ receivedQuantity: 20,+ unitPrice: 12.5,+ toShelf: "Winding-Crib"+ }+ ]+ },+ invoice: {+ ref: "pinvoice:paid",+ key: "paid",+ status: "Paid",+ currencyCode: "USD",+ subtotal: 1036,+ totalAmount: 1036,+ dateIssuedOffset: -60,+ dueDateOffset: -30,+ lines: [+ { item: "MAT-CU-18AWG", quantity: 120, supplierUnitPrice: 6.55 },+ { item: "MAT-INS-NOMEX", quantity: 20, supplierUnitPrice: 12.5 }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Closed short after a partial receipt (Lakeland bar)",+ ref: "po:closed-short",+ supplier: "Lakeland Electrical Steel",+ purchaseOrderType: "Purchase",+ status: "Closed",+ orderDateOffset: -88,+ lines: [+ { item: "MAT-AL6061-BAR", purchaseQuantity: 400, supplierUnitPrice: 3.9 }+ ],+ receipt: {+ ref: "receipt:short",+ status: "Posted",+ postedOffset: -80,+ lines: [+ {+ item: "MAT-AL6061-BAR",+ orderQuantity: 400,+ outstandingQuantity: 150,+ receivedQuantity: 250,+ unitPrice: 3.9,+ toShelf: "A3-L2"+ }+ ]+ },+ invoice: {+ ref: "pinvoice:debit-note",+ key: "debit-note",+ status: "Debit Note Issued",+ currencyCode: "USD",+ subtotal: 975,+ totalAmount: 975,+ dateIssuedOffset: -72,+ lines: [{ item: "MAT-AL6061-BAR", quantity: 250, supplierUnitPrice: 3.9 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — To Receive with a voided receipt (Ironwood)",+ supplier: "Ironwood Fasteners",+ purchaseOrderType: "Purchase",+ status: "To Receive",+ orderDateOffset: -21,+ lines: [+ { item: "FST-M10-SS", purchaseQuantity: 200, supplierUnitPrice: 1.15 }+ ],+ receipt: {+ ref: "receipt:voided",+ status: "Voided",+ lines: [+ {+ item: "FST-M10-SS",+ orderQuantity: 200,+ outstandingQuantity: 200,+ receivedQuantity: 0,+ unitPrice: 1.15+ }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice open (Summit 6308 bearings)",+ supplier: "Summit Bearing Supply",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -30,+ lines: [+ { item: "BRG-6308-C3", purchaseQuantity: 20, supplierUnitPrice: 26.8 }+ ],+ invoice: {+ ref: "pinvoice:open",+ key: "open",+ status: "Open",+ currencyCode: "USD",+ subtotal: 536,+ totalAmount: 536,+ dateIssuedOffset: -9,+ dueDateOffset: 21,+ lines: [{ item: "BRG-6308-C3", quantity: 20, supplierUnitPrice: 26.8 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice overdue (Lakeland shaft bar)",+ supplier: "Lakeland Electrical Steel",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -60,+ lines: [+ { item: "MAT-STL-4140", purchaseQuantity: 200, supplierUnitPrice: 2.7 }+ ],+ invoice: {+ ref: "pinvoice:overdue",+ key: "overdue",+ status: "Overdue",+ currencyCode: "USD",+ subtotal: 540,+ totalAmount: 540,+ dateIssuedOffset: -45,+ dueDateOffset: -15,+ lines: [{ item: "MAT-STL-4140", quantity: 200, supplierUnitPrice: 2.7 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice partially paid (Copperline)",+ supplier: "Copperline Wire Works",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -55,+ lines: [+ { item: "TRM-BLK-6P", purchaseQuantity: 40, supplierUnitPrice: 8.9 }+ ],+ invoice: {+ ref: "pinvoice:partial",+ key: "partial",+ status: "Partially Paid",+ currencyCode: "USD",+ subtotal: 356,+ totalAmount: 356,+ dateIssuedOffset: -40,+ dueDateOffset: -10,+ lines: [{ item: "TRM-BLK-6P", quantity: 40, supplierUnitPrice: 8.9 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Closed, invoice voided over a billing error (Ironwood)",+ supplier: "Ironwood Fasteners",+ purchaseOrderType: "Purchase",+ status: "Closed",+ orderDateOffset: -66,+ lines: [+ { item: "FST-M6-SS", purchaseQuantity: 500, supplierUnitPrice: 0.42 }+ ],+ invoice: {+ ref: "pinvoice:voided",+ key: "voided",+ status: "Voided",+ currencyCode: "USD",+ subtotal: 210,+ totalAmount: 210,+ dateIssuedOffset: -58,+ lines: [{ item: "FST-M6-SS", quantity: 500, supplierUnitPrice: 0.42 }]+ }+ },++ // Mirrors the OSP orders the create function raises from a job's outside operations.+ {+ source: "direct",+ log: "purchase order — Outside Processing, shaft nitride at Maumee",+ assignee: "self",+ supplier: "Maumee Contract Machining",+ purchaseOrderType: "Outside Processing",+ status: "To Receive",+ orderDateOffset: -9,+ lines: [{ item: "SHF-9000", purchaseQuantity: 4, supplierUnitPrice: 48 }]+ },++ {+ source: "direct",+ log: "purchase order — EUR order, unpaid (Euromag ferrite segments)",+ ref: "po:eur",+ supplier: "Euromag Ferrite Werke GmbH",+ purchaseOrderType: "Purchase",+ status: "To Invoice",+ orderDateOffset: -18,+ currencyCode: "EUR",+ exchangeRate: 0.92,+ lines: [+ { item: "MAG-NDFB-38", purchaseQuantity: 60, supplierUnitPrice: 13.2 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — To Invoice, terminal blocks and a replacement Nomex roll received (Copperline)",+ ref: "po:copperline-restock",+ supplier: "Copperline Wire Works",+ purchaseOrderType: "Purchase",+ status: "To Invoice",+ orderDateOffset: -12,+ lines: [+ { item: "TRM-BLK-6P", purchaseQuantity: 20, supplierUnitPrice: 8.9 },+ { item: "MAT-INS-NOMEX", purchaseQuantity: 20, supplierUnitPrice: 12.5 }+ ],+ receipt: {+ ref: "receipt:copperline-restock",+ status: "Posted",+ postedOffset: -2,+ lines: [+ {+ item: "TRM-BLK-6P",+ orderQuantity: 20,+ outstandingQuantity: 0,+ receivedQuantity: 20,+ unitPrice: 8.9,+ toShelf: "A1-L2"+ },+ {+ item: "MAT-INS-NOMEX",+ orderQuantity: 20,+ outstandingQuantity: 0,+ receivedQuantity: 20,+ unitPrice: 12.5,+ toShelf: "Winding-Crib"+ }+ ]+ }+ }+];++export const STANDALONE_SUPPLIER_QUOTES: StandaloneSupplierQuoteSpec[] = [+ {+ key: "ironwood-hardware-blanket",+ assignee: "self",+ supplier: "Ironwood Fasteners",+ status: "Draft",+ supplierReference: "IWF-2026-0781",+ quotedOffset: -3,+ expirationOffset: 60,+ lines: [+ {+ item: "FST-M10-SS",+ supplierPartId: "IWF-M10X35-A2",+ prices: [+ { quantity: 500, unitPrice: 1.08, leadTime: 10 },+ { quantity: 1500, unitPrice: 1.02, leadTime: 10 }+ ]+ }+ ]+ },+ {+ key: "lakeland-m19-annual",+ supplier: "Lakeland Electrical Steel",+ status: "Expired",+ supplierReference: "LES-Q-5523",+ quotedOffset: -220,+ expirationOffset: -25,+ lines: [+ {+ item: "MAT-LAM-M19",+ supplierPartId: "LES-M19-035C5",+ prices: [{ quantity: 2000, unitPrice: 1.78, leadTime: 28 }]+ }+ ]+ },+ {+ key: "summit-hybrid-study",+ supplier: "Summit Bearing Supply",+ status: "Declined",+ supplierReference: "SBS-2026-0114",+ quotedOffset: -40,+ expirationOffset: 20,+ lines: [+ {+ item: "BRG-6206-HYB",+ supplierPartId: "SBS-6206-HC5",+ prices: [{ quantity: 50, unitPrice: 32.5, leadTime: 28 }]+ }+ ]+ }+];++// The completed return is dated after the posted cycle count so the count's+// snapshot stays the opening balance.+export const PURCHASE_RETURNS: PurchaseReturnSpec[] = [+ {+ key: "bolt-plating",+ credit: {+ status: "Draft",+ dateOffset: -4,+ lines: [{ line: 1, quantity: 40 }]+ },+ status: "Completed",+ supplier: "Ironwood Fasteners",+ dateOffset: -6,+ lines: [+ { item: "FST-M10-SS", quantity: 40, unitPrice: 1.15, fromShelf: "A1-L1" }+ ]+ },+ {+ key: "bearing-brinelling",+ status: "To Ship",+ supplier: "Summit Bearing Supply",+ dateOffset: -2,+ lines: [{ item: "BRG-6308-C3", quantity: 2, unitPrice: 26.8 }]+ },+ {+ key: "terminal-block-recall",+ status: "Draft",+ supplier: "Copperline Wire Works",+ dateOffset: 0,+ lines: [{ item: "TRM-BLK-6P", quantity: 3, unitPrice: 8.9 }]+ },+ // Stays Draft while MRB decides; quality's ncr:nomex-thin links this line.+ {+ key: "nomex-rtv",+ status: "Draft",+ supplier: "Copperline Wire Works",+ dateOffset: -3,+ lines: [{ item: "MAT-INS-NOMEX", quantity: 4, unitPrice: 12.5 }]}];@@ -197,5 +646,65 @@ export const motorPurchasing: PurchasingData = {rfqWinningQuote: RFQ_WINNING_QUOTE,rfqOrderQuantity: RFQ_ORDER_QUANTITY,rfqHeader: RFQ_HEADER,- purchaseOrders: PURCHASE_ORDERS+ lifecycleRfqs: LIFECYCLE_RFQS,+ purchaseOrders: PURCHASE_ORDERS,+ standaloneSupplierQuotes: STANDALONE_SUPPLIER_QUOTES,+ purchaseReturns: PURCHASE_RETURNS,+ approvalRules: [+ { documentType: "purchaseOrder", lowerBoundAmount: 5000 },+ {+ documentType: "purchaseOrder",+ lowerBoundAmount: 25000,+ escalationDays: 3+ },+ { documentType: "supplier", lowerBoundAmount: 0 }+ ],+ approvalRequests: [+ { purchaseOrder: "po:needs-approval", requestedOffset: -1 },+ { supplier: "Amperon Winding Works", requestedOffset: -4 }+ ],+ supplierBankAccounts: [+ {+ supplier: "Meridian Magnetics",+ name: "Meridian remittance",+ bankName: "Summit City Bank (demo)",+ accountHolderName: "Meridian Magnetics Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-7745-1068",+ bankCode: "DEMO-074100",+ isPrimary: true+ },+ {+ supplier: "Copperline Wire Works",+ name: "Copperline operating",+ bankName: "Maumee Valley Savings (demo)",+ accountHolderName: "Copperline Wire Works LLC",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-8856-2179",+ isPrimary: true+ },+ {+ supplier: "Summit Bearing Supply",+ name: "Summit remittance",+ bankName: "Hoosier Commerce (demo)",+ accountHolderName: "Summit Bearing Supply Co.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-9967-3280",+ isPrimary: true+ },+ {+ supplier: "Euromag Ferrite Werke GmbH",+ name: "Euromag EUR account",+ bankName: "Rhein-Ruhr Handelsbank (demo)",+ accountHolderName: "Euromag Ferrite Werke GmbH",+ countryCode: "DE",+ currencyCode: "EUR",+ accountNumber: "DEMO-DE00-0000-6634",+ swiftBic: "DEMODEXX",+ isPrimary: true+ }+ ]};diff --git a/packages/database/src/datasets/data/motor/quality.ts b/packages/database/src/datasets/data/motor/quality.tsindex 6195d6f928..d4288a89a6 100644--- a/packages/database/src/datasets/data/motor/quality.ts+++ b/packages/database/src/datasets/data/motor/quality.ts@@ -1,8 +1,58 @@-import type { NonConformanceSpec, QualityData } from "../../types.ts";+import type {+ GaugeSpec,+ InspectionFeatureSpec,+ InspectionSpec,+ NonConformanceSpec,+ NonConformanceWorkflowSpec,+ QualityData,+ QualityDocumentSpec,+ RiskSpec+} from "../../types.ts";++// The new-issue form copies source, required actions and MRB from these templates onto the issue.+export const WORKFLOWS: NonConformanceWorkflowSpec[] = [+ {+ key: "supplier-escape",+ name: "Supplier Escape — Winding Materials",+ description:+ "A purchased material failed receiving inspection. Quarantine the roll or lot, work the root cause with the supplier, and record their corrective action before MRB closes it out.",+ priority: "High",+ source: "External",+ requiredActions: [+ "Containment Action",+ "Root Cause Analysis",+ "Corrective Action"+ ],+ mrb: true+ },+ {+ key: "customer-return",+ name: "Customer Complaint — Returned Spare",+ description:+ "A customer reported a fault on a delivered motor or spare. Acknowledge within one business day, contain sister units, and verify the fix before closing.",+ priority: "Medium",+ source: "External",+ requiredActions: [+ "Customer Communication",+ "Containment Action",+ "Verification"+ ]+ },+ {+ key: "magnet-hold",+ name: "Magnet Lot Hold",+ description:+ "A magnet lot arrived without its flux report or read low on a spot check. Hold it in the vault and run the incoming-materials test before any rotor bonding.",+ priority: "Medium",+ source: "Internal",+ requiredActions: ["Containment Action", "Incoming Materials"]+ }+];export const NON_CONFORMANCES: NonConformanceSpec[] = [{ref: "ncr:insulation",+ assignee: "self",name: "Stator insulation resistance below spec after impregnation",source: "Internal",status: "In Progress",@@ -18,15 +68,470 @@ export const NON_CONFORMANCES: NonConformanceSpec[] = [},{ref: "ncr:magnet",+ items: [{ item: "MAG-NDFB-45", quantity: 36 }],name: "Magnet lot received with chipped nickel plating",source: "External",status: "Registered",openDateOffset: -281,quantity: 36,priority: "Medium"+ },+ {+ ref: "ncr:nomex-thin",+ items: [+ { item: "MAT-INS-NOMEX", quantity: 4, disposition: "Return to Supplier" },+ { item: "COIL-9000", quantity: 6 }+ ],+ assignee: "self",+ workflow: "supplier-escape",+ purchaseReturnLine: { purchaseReturn: "nomex-rtv", line: 1, quantity: 4 },+ name: "Nomex 410 slot liner under minimum thickness on incoming roll",+ description:+ "Receiving inspection on the Copperline wire-and-insulation delivery measured 0.21 mm on one sample of MAT-INS-NOMEX against a 0.22 mm minimum. Thin liner cuts the slot-to-winding creepage margin and risks hipot failure after impregnation. Roll quarantined at the winding crib; MRB to decide return-to-vendor vs. restricted use on the 4500 frame.",+ type: "Supplier Issue",+ source: "External",+ status: "In Progress",+ openDateOffset: -66,+ dueDateOffset: 14,+ quantity: 4,+ priority: "Critical",+ supplier: "Copperline Wire Works",+ purchaseOrderLine: { po: "po:wire-paid", item: "MAT-INS-NOMEX" },+ inspection: "insp:nomex",+ actionTasks: [+ {+ action: "Containment Action",+ status: "Completed",+ dueDateOffset: -64,+ completedOffset: -65+ },+ {+ action: "Root Cause Analysis",+ status: "In Progress",+ dueDateOffset: 7,+ processes: ["Coil Winding"]+ },+ { action: "Corrective Action", status: "Pending", dueDateOffset: 21 }+ ],+ mrb: {+ status: "In Progress",+ dueDateOffset: 10,+ reviewers: [+ { title: "Engineering", status: "Completed", completedOffset: -58 },+ { title: "Quality", status: "In Progress" }+ ]+ }+ },+ {+ ref: "ncr:fan-noise",+ items: [{ item: "FAN-AX-160", quantity: 1, disposition: "Rework" }],+ workflow: "customer-return",+ salesReturnLine: { salesReturn: "fan", line: 1 },+ name: "Customer-reported axial cooling fan spare noisy at start-up",+ description:+ "Cardinal Motorworks reported one of two FAN-AX-160 spares ticking at start-up once fitted to a TD-9000 non-drive end. Unit returned for evaluation; a blade tip was rubbing the shroud after a dropped carton bent the guard ring in transit.",+ type: "Customer Complaint",+ source: "External",+ status: "Closed",+ openDateOffset: -12,+ dueDateOffset: 2,+ closeDateOffset: -3,+ quantity: 1,+ priority: "Low",+ customer: "Cardinal Motorworks",+ salesOrderLine: "soline:cardinal-fans:fan",+ actionTasks: [+ {+ action: "Customer Communication",+ status: "Completed",+ dueDateOffset: -11,+ completedOffset: -11+ },+ {+ action: "Containment Action",+ status: "Completed",+ dueDateOffset: -9,+ completedOffset: -10+ },+ {+ action: "Verification",+ status: "Completed",+ dueDateOffset: -4,+ completedOffset: -4+ }+ ]+ },+ {+ ref: "ncr:mag-lot",+ items: [{ item: "MAG-NDFB-45", quantity: 3 }],+ // Feeds the supplier-quality KPI's issue this month.+ supplier: "Meridian Magnetics",+ workflow: "magnet-hold",+ name: "N45SH magnet lot on hold — flux report missing, low remanence on spot check",+ description:+ "Lot LOT-MAG45-2609 arrived without the vendor's magnetization flux report, and a Gaussmeter spot check read surface flux 4% below the other N45SH lots. Lot held in the magnet vault pending the report and a sample demagnetization-curve test before any rotor bonding.",+ type: "Material Issue",+ source: "Internal",+ status: "Registered",+ openDateOffset: -5,+ dueDateOffset: 21,+ quantity: 3,+ priority: "Medium",+ trackedEntity: "LOT-MAG45-2609",+ actionTasks: [+ { action: "Containment Action", status: "Pending", dueDateOffset: 2 },+ { action: "Incoming Materials", status: "Pending", dueDateOffset: 9 }+ ]+ }+];++// Lot of 20 at AQL 1.0 / level II → code letter C, n = 5.+const NOMEX_PLAN = {+ drawingNumber: "SPEC-INS-410 Rev B",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Paper thickness (10 mil grade), deadweight micrometer",+ nominalValue: "0.25",+ tolerancePlus: "0.03",+ toleranceMinus: "0.03",+ unit: "mm"+ },+ {+ label: "2",+ description: "Slit width for the 9000-frame slot cuff",+ nominalValue: "38.0",+ tolerancePlus: "0.3",+ toleranceMinus: "0.3",+ unit: "mm"+ }+ ] satisfies InspectionFeatureSpec[]+};++export const INSPECTIONS: InspectionSpec[] = [+ {+ source: "Receipt",+ ref: "insp:nomex",+ receipt: "receipt:wire-paid",+ item: "MAT-INS-NOMEX",+ ...NOMEX_PLAN,+ status: "Partial",+ dispositionOffset: -66,+ notes:+ "Four coupons in tolerance. Coupon 3 measured 0.21 mm — under the 0.22 mm minimum. Roll quarantined and raised to MRB.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 0.25 },+ { feature: "2", value: 38.1 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 0.24 },+ { feature: "2", value: 37.9 }+ ]+ },+ {+ status: "Failed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 0.21 },+ { feature: "2", value: 38.0 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 0.26 },+ { feature: "2", value: 38.2 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -66,+ measurements: [+ { feature: "1", value: 0.25 },+ { feature: "2", value: 37.8 }+ ]+ }+ ]+ },+ // 20 pieces at AQL 1.0 → n = 5.+ {+ source: "Receipt",+ ref: "insp:terminal-blocks",+ receipt: "receipt:copperline-restock",+ item: "TRM-BLK-6P",+ drawingNumber: "CW-TB6-35 Rev C",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Stud pitch, M5 studs",+ nominalValue: "12.0",+ tolerancePlus: "0.2",+ toleranceMinus: "0.2",+ unit: "mm"+ },+ {+ label: "2",+ description: "Mounting hole centers",+ nominalValue: "70.0",+ tolerancePlus: "0.3",+ toleranceMinus: "0.3",+ unit: "mm"+ }+ ],+ status: "Passed",+ dispositionOffset: -1,+ notes: "Five blocks measured; stud pitch and mounting holes nominal.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 12.05 },+ { feature: "2", value: 70.1 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 11.96 },+ { feature: "2", value: 69.9 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 12.02 },+ { feature: "2", value: 70.0 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 12.1 },+ { feature: "2", value: 70.2 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 11.98 },+ { feature: "2", value: 69.8 }+ ]+ }+ ]+ },+ {+ source: "Receipt",+ ref: "insp:nomex-restock",+ receipt: "receipt:copperline-restock",+ item: "MAT-INS-NOMEX",+ ...NOMEX_PLAN,+ status: "Pending",+ samples: []+ },+ {+ source: "Job Operation",+ ref: "insp:shaft-journal",+ job: "floor-shaft",+ status: "Pending",+ samples: []+ }+];++export const QUALITY_DOCUMENTS: QualityDocumentSpec[] = [+ {+ name: "Magnet Wire & Insulation Receiving Inspection",+ version: 1,+ status: "Archived",+ description:+ "Superseded receiving procedure for winding materials — label and certificate review only.",+ steps: []+ },+ {+ name: "Magnet Wire & Insulation Receiving Inspection",+ version: 2,+ status: "Active",+ description:+ "Receiving procedure for magnet wire and slot insulation: paperwork, spool condition and conductor size before release to the winding crib.",+ steps: [+ {+ name: "Mill certificate matches PO, NEMA MW 35-C grade and thermal class",+ type: "Checkbox",+ required: true+ },+ {+ name: "Spool condition on arrival",+ type: "List",+ required: true,+ listValues: ["Intact", "Flange damaged", "Wire crossed or kinked"]+ },+ {+ name: "Bare conductor diameter (18 AWG)",+ description: "Strip the enamel and measure with the bench micrometer.",+ type: "Measurement",+ required: true,+ unitOfMeasureCode: "INCH",+ minValue: 0.04,+ maxValue: 0.0406+ }+ ]+ },+ {+ name: "Stator Hipot & Surge Test Procedure (IEC 60034-1)",+ version: 0,+ status: "Draft",+ description:+ "Draft end-of-line procedure for wound stators — insulation resistance, hipot to frame and surge comparison between phases.",+ steps: []+ }+];++export const GAUGES: GaugeSpec[] = [+ {+ key: "gauge-blocks",+ gaugeType: "Gauge Block",+ description:+ "Grade 0 steel gauge block set, 47 pc — inspection bench master",+ modelNumber: "GBS-47-0",+ serialNumber: "GB-21-0388",+ role: "Master",+ status: "Active",+ calibrationIntervalInMonths: 12,+ acquiredOffset: -720,+ calibrations: [+ {+ dateOffset: -540,+ result: "Pass",+ temperature: 20,+ humidity: 44,+ measurementStandard: "ISO 3650, NIST-traceable comparison"+ },+ {+ dateOffset: -180,+ result: "Pass",+ temperature: 20,+ humidity: 42,+ measurementStandard: "ISO 3650, NIST-traceable comparison"+ }+ ]+ },+ {+ key: "magnet-micrometer",+ gaugeType: "Micrometer - Outside",+ description:+ "0–25 mm outside micrometer — new unit for magnet segment thickness at incoming",+ modelNumber: "OM-25D",+ serialNumber: "M26-11907",+ role: "Standard",+ status: "Active",+ calibrationIntervalInMonths: 6,+ acquiredOffset: -8,+ calibrations: []+ },+ {+ key: "stator-bore-gauge",+ gaugeType: "Bore Gauge",+ description:+ "150–200 mm dial bore gauge for stator bore after impregnation — retired after failed calibration",+ modelNumber: "DBG-200",+ serialNumber: "BG18-30271",+ role: "Standard",+ status: "Inactive",+ calibrationIntervalInMonths: 6,+ acquiredOffset: -880,+ calibrations: [+ { dateOffset: -390, result: "Pass", temperature: 20, humidity: 47 },+ {+ dateOffset: -210,+ result: "Fail",+ requiresAction: true,+ requiresRepair: true,+ temperature: 20,+ humidity: 45,+ notes:+ "Centralizing plunger sticking after varnish contamination — repeatability 9 µm, limit 3 µm. Retired."+ }+ ]+ }+];++export const RISKS: RiskSpec[] = [+ {+ title: "Single-source N45SH magnet supplier lot consistency",+ description:+ "Meridian is the only qualified source for MAG-NDFB-45 and has shipped one plated-chip lot and one lot without a flux report this year.",+ type: "Risk",+ status: "Mitigating",+ severity: 5,+ likelihood: 3,+ source: "Supplier",+ supplier: "Meridian Magnetics"+ },+ {+ title: "AS9100 first-article flow-down on actuation motors",+ description:+ "Halcyon's purchase terms may require a full AS9102 first-article report on every TD-9000 revision — confirm scope before the next shipment.",+ type: "Risk",+ status: "In Review",+ severity: 4,+ likelihood: 2,+ source: "Customer",+ customer: "Halcyon Aerospace Actuation"+ },+ {+ title: "Dysprosium price swing on high-temperature magnet grade",+ description:+ "The SH grade depends on dysprosium; a rare-earth price spike would push MAG-NDFB-45 cost past the TD-9000 quoted margin.",+ type: "Risk",+ status: "Open",+ severity: 3,+ likelihood: 3,+ source: "Item",+ item: "MAG-NDFB-45"+ },+ {+ title: "Impregnation oven slot for the in-progress TD-9000 stator",+ description:+ "The VPI oven was double-booked for the stator's Class H bake cycle; a night-shift slot was confirmed and the bake completed.",+ type: "Risk",+ status: "Closed",+ severity: 3,+ likelihood: 2,+ source: "Job",+ job: "job:in-progress"+ },+ {+ title: "Move the 9000-frame stator to hairpin winding",+ description:+ "Hairpin conductors would lift slot fill and cut winding labor by roughly a third — accepted into next year's tooling plan.",+ type: "Opportunity",+ status: "Accepted",+ severity: 2,+ likelihood: 4,+ source: "General"}];export const motorQuality: QualityData = {- nonConformances: NON_CONFORMANCES+ workflows: WORKFLOWS,+ nonConformances: NON_CONFORMANCES,+ inspections: INSPECTIONS,+ qualityDocuments: QUALITY_DOCUMENTS,+ gauges: GAUGES,+ risks: RISKS};diff --git a/packages/database/src/datasets/data/motor/sales.ts b/packages/database/src/datasets/data/motor/sales.tsindex b95a9238d3..0fe2c2d593 100644--- a/packages/database/src/datasets/data/motor/sales.ts+++ b/packages/database/src/datasets/data/motor/sales.ts@@ -6,6 +6,7 @@ import type {PriceBreak,SalesData,SalesOpportunitySpec,+ SalesReturnSpec,SalesStatusOrderSpec,StaggeredDeliverySpec} from "../../types.ts";@@ -65,6 +66,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [},quote: {ref: "quote:ridgeline",+ createdOffset: -328,status: "Ordered",externalNotes:"Quote for 6x TD-9000 servo motors, 2048 PPR encoder, IP55 terminal box.",@@ -120,11 +122,18 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Cardinal Motorworks",quote: {ref: "quote:cardinal",+ createdOffset: -19,+ assignee: "self",status: "Sent",expirationOffset: CARDINAL_QUOTE_EXPIRATION_OFFSET,lines: [{ref: "quoteline:cardinal:mtr9000",+ configuration: {+ shaft_extension_mm: 60,+ mounting_flange: "NEMA C-Face",+ holding_brake: false+ },item: "MTR-9000",status: "Complete",sortOrder: 1,@@ -150,6 +159,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Wabash Industrial Supply",rfq: {ref: "rfq:wabash",+ assignee: "self",status: "Ready for Quote",rfqDateOffset: -285,externalNotes:@@ -170,6 +180,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Halcyon Aerospace Actuation",quote: {ref: "quote:halcyon",+ createdOffset: -268,status: "Ordered",lines: [{@@ -195,6 +206,177 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [}]}+ },++ {+ log: "opportunity 5 — RFQ draft (Wabash, spare housing sets)",+ ref: "opp:wabash-housing",+ customer: "Wabash Industrial Supply",+ rfq: {+ ref: "rfq:wabash-housing",+ assignee: "self",+ status: "Draft",+ rfqDateOffset: -3,+ externalNotes:+ "Inquiry being logged — spare housing & end-bell sets for the 9000 frame.",+ lines: [+ {+ item: "HSG-9000",+ customerPartId: "WIS-HSG-9000",+ quantity: [2],+ order: 1+ }+ ]+ }+ },+ {+ log: "opportunity 6 — no-quoted RFQ, lost quote (Ridgeline explosion-proof)",+ ref: "opp:ridgeline-exproof",+ customer: "Ridgeline Drive Systems",+ rfq: {+ ref: "rfq:ridgeline-exproof",+ status: "Closed",+ rfqDateOffset: -95,+ expirationOffset: -50,+ noQuoteReason: "Out of Scope",+ externalNotes:+ "Explosion-proof TD-9000 variant — outside our hazardous-location certification.",+ lines: [+ {+ item: "MTR-9000",+ customerPartId: "RDS-MTR-EXP1",+ quantity: [3],+ order: 1+ }+ ]+ },+ quote: {+ ref: "quote:ridgeline-exproof",+ createdOffset: -78,+ status: "Lost",+ externalNotes: "Declined to bid the explosion-proof line.",+ lines: [+ {+ ref: "quoteline:ridgeline-exproof:mtr",+ item: "MTR-9000",+ status: "No Quote",+ sortOrder: 1,+ priceBreaks: []+ }+ ]+ }+ },+ {+ log: "opportunity 7 — quote draft (Halcyon trainer actuator motor)",+ ref: "opp:halcyon-trainer",+ customer: "Halcyon Aerospace Actuation",+ quote: {+ ref: "quote:halcyon-trainer",+ createdOffset: -6,+ assignee: "self",+ status: "Draft",+ externalNotes:+ "Working draft — trainer-aircraft actuator motor pricing in progress.",+ lines: [+ {+ ref: "quoteline:halcyon-trainer:mtr",+ item: "MTR-4500",+ status: "Not Started",+ sortOrder: 1,+ priceBreaks: [{ quantity: 2, unitPrice: 3050, leadTime: 60 }]+ }+ ]+ }+ },+ {+ log: "opportunity 8 — partial quote (Cardinal driveline subassemblies)",+ ref: "opp:cardinal-driveline",+ customer: "Cardinal Motorworks",+ quote: {+ ref: "quote:cardinal-driveline",+ createdOffset: -10,+ status: "Partial",+ expirationOffset: 45,+ externalNotes:+ "Stator line released to the customer; rotor line still in engineering review.",+ lines: [+ {+ ref: "quoteline:cardinal-driveline:sta",+ item: "STA-9000",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 4, unitPrice: 1150, leadTime: 45 }]+ },+ {+ ref: "quoteline:cardinal-driveline:rot",+ item: "ROT-9000",+ status: "In Progress",+ sortOrder: 2,+ priceBreaks: [{ quantity: 4, unitPrice: 1390, leadTime: 50 }]+ }+ ]+ }+ },+ {+ log: "opportunity 9 — cancelled quote (Wabash shaft stocking program)",+ ref: "opp:wabash-shafts",+ customer: "Wabash Industrial Supply",+ quote: {+ ref: "quote:wabash-shafts",+ createdOffset: -148,+ status: "Cancelled",+ externalNotes: "Stocking program shelved before pricing was issued.",+ lines: [+ {+ ref: "quoteline:wabash-shafts:shf",+ item: "SHF-9000",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 10, unitPrice: 205, leadTime: 30 }]+ }+ ]+ }+ },+ {+ log: "opportunity 10 — expired quote (Ridgeline spare coil sets)",+ ref: "opp:ridgeline-coils",+ customer: "Ridgeline Drive Systems",+ quote: {+ ref: "quote:ridgeline-coils",+ createdOffset: -45,+ status: "Expired",+ expirationOffset: -14,+ externalNotes: "30-day pricing lapsed without a PO.",+ lines: [+ {+ ref: "quoteline:ridgeline-coils:coil",+ item: "COIL-9000",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 6, unitPrice: 470, leadTime: 40 }]+ }+ ]+ }+ },+ {+ log: "sales order — Needs Approval (Halcyon hybrid bearing spares)",+ ref: "opp:halcyon-bearings",+ customer: "Halcyon Aerospace Actuation",+ order: {+ ref: "so:halcyon-bearings",+ assignee: "self",+ status: "Needs Approval",+ orderDateOffset: -2,+ lines: [+ {+ ref: "soline:halcyon-bearings:brg",+ item: "BRG-6206-HYB",+ saleQuantity: 4,+ unitPrice: 52,+ status: "Ordered"+ }+ ]+ }}];@@ -268,6 +450,7 @@ export const RELEASED_ORDERS: SalesOpportunitySpec[] = [customer: "Cardinal Motorworks",order: {ref: "so:toshipinvoice",+ assignee: "self",status: "To Ship and Invoice",orderDateOffset: -10,lines: STAGGERED_DELIVERIES.map((delivery) => ({@@ -282,11 +465,547 @@ export const RELEASED_ORDERS: SalesOpportunitySpec[] = [sortOrder: delivery.sortOrder}))}+ },++ // Shipped items are well-stocked untracked buy parts (spares sold from the+ // shelf), so the ledger rows never overdraw a bin.+ {+ log: "sales order — To Invoice (Cardinal, posted spare-fan shipment)",+ ref: "opp:cardinal-fans",+ customer: "Cardinal Motorworks",+ order: {+ ref: "so:cardinal-fans",+ status: "To Invoice",+ orderDateOffset: -30,+ lines: [+ {+ ref: "soline:cardinal-fans:fan",+ item: "FAN-AX-160",+ saleQuantity: 2,+ unitPrice: 52,+ status: "Completed"+ }+ ]+ },+ shipment: {+ ref: "shp:cardinal-fans",+ status: "Posted",+ postedOffset: -18,+ lines: [+ {+ item: "FAN-AX-160",+ orderQuantity: 2,+ outstandingQuantity: 0,+ shippedQuantity: 2,+ unitPrice: 52,+ fromShelf: "A2-L3"+ }+ ]+ }+ },+ {+ log: "sales order — To Ship and Invoice (Ridgeline, partial bearing shipment)",+ ref: "opp:ridgeline-bearings",+ customer: "Ridgeline Drive Systems",+ order: {+ ref: "so:ridgeline-bearings",+ status: "To Ship and Invoice",+ orderDateOffset: -21,+ lines: [+ {+ ref: "soline:ridgeline-bearings:brg",+ item: "BRG-6308-C3",+ saleQuantity: 4,+ unitPrice: 41,+ status: "In Progress"+ }+ ]+ },+ shipment: {+ ref: "shp:ridgeline-bearings",+ status: "Posted",+ postedOffset: -9,+ lines: [+ {+ item: "BRG-6308-C3",+ orderQuantity: 4,+ outstandingQuantity: 2,+ shippedQuantity: 2,+ unitPrice: 41,+ fromShelf: "A2-L1"+ }+ ]+ }+ },+ {+ log: "sales order — To Ship (Wabash, voided terminal-block shipment)",+ ref: "opp:wabash-terminals",+ customer: "Wabash Industrial Supply",+ order: {+ ref: "so:wabash-terminals",+ status: "To Ship",+ orderDateOffset: -14,+ lines: [+ {+ ref: "soline:wabash-terminals:trm",+ item: "TRM-BLK-6P",+ saleQuantity: 8,+ unitPrice: 14,+ status: "Ordered"+ }+ ]+ },+ shipment: {+ ref: "shp:wabash-terminals",+ status: "Voided",+ lines: [+ {+ item: "TRM-BLK-6P",+ orderQuantity: 8,+ outstandingQuantity: 8,+ shippedQuantity: 0,+ unitPrice: 14+ }+ ]+ }+ },++ // accounting.ts settles "paid" and "partial" by these sinv keys.+ {+ log: "sales invoice — Submitted (Halcyon shaft-seal spares)",+ ref: "opp:halcyon-seals",+ customer: "Halcyon Aerospace Actuation",+ order: {+ ref: "so:halcyon-seals",+ status: "Invoiced",+ orderDateOffset: -35,+ lines: [+ {+ ref: "soline:halcyon-seals:seal",+ item: "SEAL-VR-45",+ saleQuantity: 20,+ unitPrice: 6,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:halcyon-seals",+ key: "submitted",+ status: "Submitted",+ subtotal: 120,+ totalAmount: 120,+ dateIssuedOffset: -20,+ dueDateOffset: 10,+ lines: [{ item: "SEAL-VR-45", quantity: 20, unitPrice: 6 }]+ }+ },+ {+ log: "sales invoice — Overdue (Cardinal spare stator)",+ ref: "opp:cardinal-stator",+ customer: "Cardinal Motorworks",+ order: {+ ref: "so:cardinal-stator",+ status: "Invoiced",+ orderDateOffset: -60,+ lines: [+ {+ ref: "soline:cardinal-stator:sta",+ item: "STA-4500",+ saleQuantity: 1,+ unitPrice: 780,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:cardinal-stator",+ key: "overdue",+ status: "Overdue",+ subtotal: 780,+ totalAmount: 780,+ dateIssuedOffset: -45,+ dueDateOffset: -15,+ lines: [{ item: "STA-4500", quantity: 1, unitPrice: 780 }]+ }+ },+ {+ log: "sales invoice — Paid (Wabash stainless cap-screw lot)",+ ref: "opp:wabash-fasteners",+ customer: "Wabash Industrial Supply",+ order: {+ ref: "so:wabash-fasteners",+ status: "Closed",+ orderDateOffset: -90,+ lines: [+ {+ ref: "soline:wabash-fasteners:fst",+ item: "FST-M6-SS",+ saleQuantity: 400,+ unitPrice: 0.75,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:wabash-fasteners",+ key: "paid",+ status: "Paid",+ subtotal: 300,+ totalAmount: 300,+ dateIssuedOffset: -75,+ dueDateOffset: -45,+ lines: [{ item: "FST-M6-SS", quantity: 400, unitPrice: 0.75 }]+ }+ },+ {+ log: "sales invoice — Partially Paid (Ridgeline spare rotor)",+ ref: "opp:ridgeline-rotor",+ customer: "Ridgeline Drive Systems",+ order: {+ ref: "so:ridgeline-rotor",+ status: "Invoiced",+ orderDateOffset: -50,+ lines: [+ {+ ref: "soline:ridgeline-rotor:rot",+ item: "ROT-9000",+ saleQuantity: 1,+ unitPrice: 1420,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:ridgeline-rotor",+ key: "partial",+ status: "Partially Paid",+ subtotal: 1420,+ totalAmount: 1420,+ dateIssuedOffset: -38,+ dueDateOffset: -8,+ lines: [{ item: "ROT-9000", quantity: 1, unitPrice: 1420 }]+ }+ },+ {+ log: "sales invoice — Voided (Halcyon hex bolts, wrong bill-to)",+ ref: "opp:halcyon-bolts",+ customer: "Halcyon Aerospace Actuation",+ order: {+ ref: "so:halcyon-bolts",+ status: "To Invoice",+ orderDateOffset: -28,+ lines: [+ {+ ref: "soline:halcyon-bolts:fst",+ item: "FST-M10-SS",+ saleQuantity: 100,+ unitPrice: 1.9,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:halcyon-bolts",+ key: "voided",+ status: "Voided",+ subtotal: 190,+ totalAmount: 190,+ dateIssuedOffset: -25,+ lines: [{ item: "FST-M10-SS", quantity: 100, unitPrice: 1.9 }]+ }+ },+ {+ log: "sales invoice — Credit Note Issued (Cardinal precision shafts)",+ ref: "opp:cardinal-shafts",+ customer: "Cardinal Motorworks",+ order: {+ ref: "so:cardinal-shafts",+ status: "Closed",+ orderDateOffset: -70,+ lines: [+ {+ ref: "soline:cardinal-shafts:shf",+ item: "SHF-9000",+ saleQuantity: 2,+ unitPrice: 205,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:cardinal-shafts",+ key: "credit",+ status: "Credit Note Issued",+ subtotal: 410,+ totalAmount: 410,+ dateIssuedOffset: -55,+ dueDateOffset: -25,+ lines: [{ item: "SHF-9000", quantity: 2, unitPrice: 205 }]+ }+ },++ // Older overdue invoices, so receivables aging fills every bucket to 61–90.+ {+ log: "sales invoice — Overdue 31–60 days (Wabash V-ring seals)",+ ref: "opp:wabash-seals",+ customer: "Wabash Industrial Supply",+ order: {+ ref: "so:wabash-seals",+ status: "Invoiced",+ orderDateOffset: -90,+ lines: [+ {+ ref: "soline:wabash-seals:seal",+ item: "SEAL-VR-45",+ saleQuantity: 50,+ unitPrice: 6,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:wabash-seals",+ status: "Overdue",+ subtotal: 300,+ totalAmount: 300,+ dateIssuedOffset: -75,+ dueDateOffset: -45,+ lines: [{ item: "SEAL-VR-45", quantity: 50, unitPrice: 6 }]+ }+ },+ {+ log: "sales invoice — Overdue 61–90 days (Halcyon 4500 stator)",+ ref: "opp:halcyon-stator",+ customer: "Halcyon Aerospace Actuation",+ order: {+ ref: "so:halcyon-stator",+ status: "Invoiced",+ orderDateOffset: -120,+ lines: [+ {+ ref: "soline:halcyon-stator:sta",+ item: "STA-4500",+ saleQuantity: 1,+ unitPrice: 780,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:halcyon-stator",+ status: "Overdue",+ subtotal: 780,+ totalAmount: 780,+ dateIssuedOffset: -105,+ dueDateOffset: -75,+ lines: [{ item: "STA-4500", quantity: 1, unitPrice: 780 }]+ }+ },++ // Each line has a job of its own in production.ts (open or just completed).+ {+ log: "sales order — In Progress (Ridgeline stator and rotor spares, floor load)",+ ref: "opp:floor-ridgeline",+ customer: "Ridgeline Drive Systems",+ order: {+ ref: "so:floor-ridgeline",+ status: "In Progress",+ orderDateOffset: -30,+ lines: [+ {+ ref: "soline:floor-ridgeline:coil",+ item: "COIL-9000",+ saleQuantity: 4,+ unitPrice: 480,+ status: "In Progress",+ promisedDateOffset: 3+ },+ {+ ref: "soline:floor-ridgeline:lam-rotor",+ item: "LAM-STK-ROT",+ saleQuantity: 10,+ unitPrice: 190,+ status: "In Progress",+ promisedDateOffset: 3+ },+ {+ ref: "soline:floor-ridgeline:rotor",+ item: "ROT-9000",+ saleQuantity: 1,+ unitPrice: 1420,+ status: "In Progress",+ promisedDateOffset: 4+ },+ {+ ref: "soline:floor-ridgeline:shaft",+ item: "SHF-9000",+ saleQuantity: 8,+ unitPrice: 210,+ status: "In Progress",+ promisedDateOffset: 15+ },+ {+ ref: "soline:floor-ridgeline:termbox",+ item: "TRM-BOX-9000",+ saleQuantity: 10,+ unitPrice: 165,+ status: "In Progress",+ promisedDateOffset: 2+ },+ {+ ref: "soline:floor-ridgeline:stator",+ item: "STA-4500",+ saleQuantity: 4,+ unitPrice: 780,+ status: "In Progress",+ promisedDateOffset: 5+ }+ ]+ }+ },+ {+ log: "sales order — In Progress (Halcyon actuator motor kits, floor load)",+ ref: "opp:floor-halcyon",+ customer: "Halcyon Aerospace Actuation",+ order: {+ ref: "so:floor-halcyon",+ assignee: "self",+ status: "In Progress",+ orderDateOffset: -15,+ lines: [+ {+ ref: "soline:floor-halcyon:lam-rotor",+ item: "LAM-STK-ROT",+ saleQuantity: 12,+ unitPrice: 190,+ status: "In Progress",+ promisedDateOffset: 8+ },+ {+ ref: "soline:floor-halcyon:coil",+ item: "COIL-9000",+ saleQuantity: 6,+ unitPrice: 480,+ status: "In Progress",+ promisedDateOffset: 10+ },+ {+ ref: "soline:floor-halcyon:housing",+ item: "HSG-9000",+ saleQuantity: 4,+ unitPrice: 640,+ status: "In Progress",+ promisedDateOffset: 24+ },+ {+ ref: "soline:floor-halcyon:rotor",+ item: "ROT-9000",+ saleQuantity: 2,+ unitPrice: 1420,+ status: "In Progress",+ promisedDateOffset: 19+ },+ {+ ref: "soline:floor-halcyon:lam-stator",+ item: "LAM-STK-STA",+ saleQuantity: 6,+ unitPrice: 260,+ status: "In Progress",+ promisedDateOffset: 30+ }+ ]+ }+ }+];++// Quantities come from the posted shipments above; the Completed RMA books+// stock back into the shelf it shipped from.+export const SALES_RETURNS: SalesReturnSpec[] = [+ {+ key: "fan",+ credit: {+ status: "Posted",+ dateOffset: -8,+ lines: [{ line: 1, quantity: 1 }]+ },+ status: "Completed",+ customer: "Cardinal Motorworks",+ returnReason: "Defective",+ dateOffset: -12,+ salesOrder: "so:cardinal-fans",+ lines: [+ { item: "FAN-AX-160", quantity: 1, unitPrice: 52, toShelf: "A2-L3" }+ ]+ },+ {+ key: "bearing",+ status: "To Receive",+ customer: "Ridgeline Drive Systems",+ returnReason: "Damaged in Transit",+ dateOffset: -5,+ salesOrder: "so:ridgeline-bearings",+ lines: [{ item: "BRG-6308-C3", quantity: 1, unitPrice: 41 }]+ },+ {+ key: "seals",+ status: "Draft",+ customer: "Halcyon Aerospace Actuation",+ returnReason: "No Longer Needed",+ dateOffset: -1,+ salesOrder: "so:halcyon-seals",+ lines: [{ item: "SEAL-VR-45", quantity: 4, unitPrice: 6 }]}];export const motorSales: SalesData = {opportunities: OPPORTUNITIES,statusOrders: STATUS_ORDERS,- releasedOrders: RELEASED_ORDERS+ releasedOrders: RELEASED_ORDERS,+ salesReturns: SALES_RETURNS,+ customerPortals: ["Ridgeline Drive Systems", "Cardinal Motorworks"],+ customerBankAccounts: [+ {+ customer: "Ridgeline Drive Systems",+ name: "Ridgeline remittance",+ bankName: "Three Rivers Bank (demo)",+ accountHolderName: "Ridgeline Drive Systems Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-2846-5510",+ bankCode: "DEMO-074000",+ isPrimary: true+ },+ {+ customer: "Cardinal Motorworks",+ name: "Cardinal operating",+ bankName: "Motor City Commerce (demo)",+ accountHolderName: "Cardinal Motorworks LLC",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-3957-6621",+ isPrimary: true+ },+ {+ customer: "Halcyon Aerospace Actuation",+ name: "Halcyon payables",+ bankName: "Front Range Aerospace CU (demo)",+ accountHolderName: "Halcyon Aerospace Actuation Corp.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-5068-7732",+ bankCode: "DEMO-102000",+ isPrimary: true+ },+ {+ customer: "Wabash Industrial Supply",+ name: "Wabash operating",+ bankName: "Wabash Valley Bank (demo)",+ accountHolderName: "Wabash Industrial Supply Co.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-6179-8843",+ isPrimary: true+ }+ ]};diff --git a/packages/database/src/datasets/data/motor/workflows.ts b/packages/database/src/datasets/data/motor/workflows.tsindex 251cacedff..fabd806267 100644--- a/packages/database/src/datasets/data/motor/workflows.ts+++ b/packages/database/src/datasets/data/motor/workflows.ts@@ -1,5 +1,4 @@-import type { Edge, SeedWorkflow } from "../../tiers/workflow-definitions.ts";-import type { WorkflowData } from "../../types.ts";+import type { Edge, SeedWorkflow, WorkflowData } from "../../types.ts";// A factory, not a constant: every definition names ids that only exist once the seed has run.@@ -508,6 +507,38 @@ export function buildMotorWorkflows(refs: {];}+// The queued run was skipped at load while the workflow was briefly unpublished,+// so it has no steps.export const motorWorkflows: WorkflowData = {- build: buildMotorWorkflows+ build: buildMotorWorkflows,+ runs: [+ {+ workflow: "Assign new sales orders",+ status: "Succeeded",+ triggerRef: "so:wabash-terminals",+ at: { offset: -14, time: "11:26:03" },+ steps: [{ nodeId: "action_assign", status: "Succeeded" }]+ },+ {+ workflow: "Assign new sales orders",+ status: "Failed",+ triggerRef: "so:halcyon-bolts",+ at: { offset: -28, time: "15:54:41" },+ steps: [+ {+ nodeId: "action_assign",+ status: "Failed",+ error: "The assignee you chose is not in this company."+ }+ ]+ },+ {+ workflow: "Assign new sales orders",+ status: "Skipped",+ triggerRef: "so:ridgeline-bearings",+ at: { offset: -21, time: "07:39:20" },+ statusReason: "This workflow was unpublished before the run started.",+ steps: []+ }+ ]};diff --git a/packages/database/src/datasets/data/precision/accounting.ts b/packages/database/src/datasets/data/precision/accounting.tsindex 6587f13bef..620b173248 100644--- a/packages/database/src/datasets/data/precision/accounting.ts+++ b/packages/database/src/datasets/data/precision/accounting.ts@@ -1,7 +1,11 @@import type {AccountingData,FixedAssetSpec,- JournalEntrySpec+ JournalEntrySpec,+ MemoSpec,+ PaymentSpec,+ PeriodCloseTaskSpec,+ ProjectSpec} from "../../types.ts";export const FIXED_ASSETS: FixedAssetSpec[] = [@@ -76,6 +80,51 @@ export const FIXED_ASSETS: FixedAssetSpec[] = [acquisitionOffset: -2617,depreciationStartOffset: -2586,accumulatedDepreciation: 58000+ },+ {+ key: "knee-mill",+ className: "Machinery & Equipment",+ location: "Plant",+ name: "Manual Knee Mill",+ description:+ "Toolroom knee mill retired after the second VMC arrived; sold at a machinery auction",+ serialNumber: "KM-3VS-48213",+ status: "Disposed",+ depreciationMethod: "Straight Line",+ usefulLifeMonths: 120,+ residualValuePercent: 0,+ acquisitionCost: 36000,+ acquisitionOffset: -3400,+ depreciationStartOffset: -3380,+ // 36,000 / 120 = 300 per month x the 110 months depreciated before sale.+ // NBV 3,000 against 4,200 proceeds books a 1,200 gain.+ accumulatedDepreciation: 33000,+ disposal: { dateOffset: -35, method: "Sale", saleProceeds: 4200 }+ },+ {+ key: "wire-edm",+ className: "Machinery & Equipment",+ location: "Plant",+ name: "Wire EDM Machine",+ description:+ "Wire EDM for punch and die profiles, depreciated by burn hours",+ serialNumber: "EDM-W4-70316",+ status: "Active",+ depreciationMethod: "Units of Production",+ usefulLifeMonths: 96,+ residualValuePercent: 0,+ acquisitionCost: 88000,+ acquisitionOffset: -120,+ depreciationStartOffset: -100,+ // 88,000 / 20,000 hours = 4.40 per hour. The first logged month (290 h)+ // was booked on registration; the run's month (335 h) is the charge.+ assetLifetimeUsage: 20000,+ accumulatedDepreciation: 1276,+ usageLogs: [+ { monthsBack: 2, unitsProduced: 290 },+ { monthsBack: 1, unitsProduced: 335 }+ ],+ depreciationCharge: 1474}];@@ -105,10 +154,320 @@ export const JOURNAL_ENTRIES: JournalEntrySpec[] = [journalLineReference: "JE-SEED-001"}]+ },+ {+ ref: "journal:payroll-accrual",+ journalEntryId: "JE-SEED-002",+ description: "Payroll accrual — second-shift machinists, final week",+ status: "Posted",+ postingOffset: -12,+ lines: [+ {+ account: "6060",+ description: "Accrued second-shift machinist wages",+ amount: 22800,+ quantity: 1,+ journalLineReference: "JE-SEED-002-1",+ dimensions: [+ { dimension: "Project", value: "solstice-fixture" },+ { dimension: "Work Cell", value: "5-Axis Milling" }+ ]+ },+ {+ account: "2150",+ description: "Accrued second-shift machinist wages",+ amount: 22800,+ quantity: 1,+ journalLineReference: "JE-SEED-002-2"+ }+ ]+ },+ {+ ref: "journal:amortization",+ journalEntryId: "JE-SEED-003",+ description: "Monthly amortization — CAM software license",+ status: "Posted",+ postingOffset: -23,+ lines: [+ {+ account: "6310",+ description: "CAM software license amortization",+ amount: 640,+ quantity: 1,+ journalLineReference: "JE-SEED-003"+ },+ {+ // A credit on the contra-asset: negative on a debit-normal class.+ account: "1420",+ description: "CAM software license amortization",+ amount: -640,+ quantity: 1,+ journalLineReference: "JE-SEED-003"+ }+ ]+ },+ {+ ref: "journal:calibration-accrual",+ journalEntryId: "JE-SEED-004",+ description:+ "Accrued gauge calibration service — duplicate of vendor invoice",+ status: "Reversed",+ postingOffset: -40,+ lines: [+ {+ account: "6080",+ description: "Gauge calibration service",+ amount: 3150,+ quantity: 1,+ journalLineReference: "JE-SEED-004"+ },+ {+ account: "2140",+ description: "Gauge calibration service",+ amount: 3150,+ quantity: 1,+ journalLineReference: "JE-SEED-004"+ }+ ],+ reversal: {+ ref: "journal:calibration-accrual-reversal",+ journalEntryId: "JE-SEED-005",+ postingOffset: -33+ }+ },+ {+ ref: "journal:opening-balance",+ journalEntryId: "JE-SEED-006",+ description: "Opening balances — cutover from the legacy ledger",+ status: "Posted",+ sourceType: "Opening Balance",+ postingOffset: -242,+ lines: [+ {+ account: "1010",+ description: "Operating cash",+ amount: 420000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-1"+ },+ {+ account: "1210",+ description: "Raw materials on hand",+ amount: 95000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-2"+ },+ {+ account: "1220",+ description: "Finished goods on hand",+ amount: 70000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-3"+ },+ {+ account: "1350",+ description: "Machinery & equipment at cost",+ amount: 1250000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-4"+ },+ {+ account: "1330",+ description: "Accumulated depreciation to date",+ amount: -380000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-5"+ },+ {+ account: "2410",+ description: "Equipment term loan",+ amount: 500000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-6"+ },+ {+ account: "3010",+ description: "Paid-in capital",+ amount: 400000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-7"+ },+ {+ account: "3100",+ description: "Retained earnings brought forward",+ amount: 555000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-8"+ }+ ]+ }+];++// Credit/Debit Note Issued invoices settle by their memos as zero-cash credit+// applications, the way applyCreditsToInvoices records them.+export const PAYMENTS: PaymentSpec[] = [+ {+ key: "cedar-ach",+ type: "Receipt",+ customer: "Cedar Valley Hydraulics",+ dateOffset: -44,+ amount: 345,+ reference: "ACH 3308-4410",+ applies: [{ invoiceKey: "paid", amount: 345 }]+ },+ {+ key: "dominion-check",+ type: "Receipt",+ customer: "Dominion Ag Equipment",+ dateOffset: -9,+ amount: 78,+ reference: "CHK 5561",+ applies: [{ invoiceKey: "partial", amount: 78 }]+ },+ {+ key: "granite-credit",+ type: "Receipt",+ customer: "Granite State Instruments",+ dateOffset: -49,+ amount: 0,+ reference: "Credit application",+ applies: [],+ credits: [{ memoKey: "granite-sheet", invoiceKey: "credit", amount: 225 }]+ },+ {+ key: "midway-ach",+ type: "Disbursement",+ supplier: "Midway Bearing & Seal",+ dateOffset: -31,+ amount: 118.2,+ reference: "ACH 6120-7734",+ applies: [{ invoiceKey: "paid", amount: 118.2 }]+ },+ {+ key: "midway-check",+ type: "Disbursement",+ supplier: "Midway Bearing & Seal",+ dateOffset: -13,+ amount: 140,+ reference: "CHK 30871",+ applies: [{ invoiceKey: "partial", amount: 140 }]+ },+ {+ key: "bluestem-debit",+ type: "Disbursement",+ supplier: "Bluestem Alloys",+ dateOffset: -66,+ amount: 0,+ reference: "Debit application",+ applies: [],+ credits: [+ { memoKey: "bluestem-plate", invoiceKey: "debit-note", amount: 500 }+ ]+ },+ {+ key: "draft-receipt",+ type: "Receipt",+ status: "Draft",+ customer: "Granite State Instruments",+ dateOffset: -1,+ amount: 360,+ reference: "Check 30912 — 316 plate",+ applies: []+ },+ {+ key: "draft-disbursement",+ type: "Disbursement",+ status: "Draft",+ supplier: "Rock River Metals",+ dateOffset: 0,+ amount: 442.5,+ reference: "ACH batch 0930 — bar stock",+ applies: []+ }+];++export const MEMOS: MemoSpec[] = [+ {+ key: "granite-sheet",+ direction: "Credit",+ customer: "Granite State Instruments",+ invoiceKey: "credit",+ dateOffset: -52,+ amount: 225,+ notes: "Full credit — 5052 sheet remnant shipped in the wrong temper"+ },+ {+ key: "bluestem-plate",+ direction: "Debit",+ supplier: "Bluestem Alloys",+ invoiceKey: "debit-note",+ dateOffset: -70,+ amount: 500,+ notes:+ "316L plate failed the mill-cert review at the dock — billing debited"+ }+];++export const PROJECTS: ProjectSpec[] = [+ {+ key: "solstice-fixture",+ name: "Solstice Surgical Fixture Program",+ description:+ "Validated fixture family for Solstice Medical's instrument line",+ purchaseInvoiceLine: { invoiceKey: "paid", item: "BRG-DBL-6205" }+ },+ {+ key: "five-axis-expansion",+ name: "Five-Axis Capacity Expansion",+ description: "Second 5-axis cell with pallet automation"+ }+];++export const CLOSE_TASKS: PeriodCloseTaskSpec[] = [+ { definition: "Post pending operational documents", status: "Done" },+ {+ definition: "Review negative on-hand inventory",+ status: "Skipped",+ skippedReason: "Bin audit ran clean the week before month end"+ },+ {+ definition: "Review financial statements",+ status: "Open",+ notes: "Owner to review shop-rate variance"}];export const precisionAccounting: AccountingData = {fixedAssets: FIXED_ASSETS,- journalEntries: JOURNAL_ENTRIES+ journalEntries: JOURNAL_ENTRIES,+ payments: PAYMENTS,+ memos: MEMOS,+ projects: PROJECTS,+ customDimension: {+ name: "Work Cell",+ values: ["Swiss Turning", "5-Axis Milling"]+ },+ closeTasks: CLOSE_TASKS,+ // EUR per 1 USD (foreign units per base unit), the same direction as the EUR purchase order's 0.92 snapshot.+ exchangeRateOverrides: [{ currencyCode: "EUR", rate: 0.9215 }],+ billingAddresses: {+ receivable: {+ addressLine1: "1725 Kishwaukee Street",+ city: "Rockford",+ state: "IL",+ postalCode: "61104",+ countryCode: "US",+ phone: "+1-815-555-0194",+ email: "[email protected]"+ },+ payable: {+ addressLine1: "1725 Kishwaukee Street",+ city: "Rockford",+ state: "IL",+ postalCode: "61104",+ countryCode: "US",+ phone: "+1-815-555-0195",+ email: "[email protected]"+ }+ }};diff --git a/packages/database/src/datasets/data/precision/assembly.ts b/packages/database/src/datasets/data/precision/assembly.tsindex c00592f516..f7c2faa3ba 100644--- a/packages/database/src/datasets/data/precision/assembly.ts+++ b/packages/database/src/datasets/data/precision/assembly.ts@@ -7,12 +7,16 @@ export const precisionAssembly: AssemblySpec = {name: "Extruder Toolhead — Final Assembly",item: "HMA-4000",componentCount: 70,+ // The Assembly operation of the HMA-4000 method.+ operation: 1,steps: [{title: "Clamp the tool plate in the build fixture",instruction:"Set the tool plate in the fixture with the groovemount facing up. Wipe both mating faces with IPA and inspect under light — a single chip trapped under this plate throws the nozzle out of square and shows up as a first-layer defect, not as an assembly fault.",- componentNodeIds: ["650820861e3f30a9"]+ componentNodeIds: ["650820861e3f30a9"],+ materials: [{ item: "FAB-BASE-WLD", quantity: 1 }],+ tools: [{ item: "TL-FIXT-HSG", quantity: 1 }]},{title: "Torque the four M3×10 plate screws",@@ -29,13 +33,16 @@ export const precisionAssembly: AssemblySpec = {title: "Fit the Bondtech drive body",instruction:"Slide the extruder body onto the plate dowels until it bottoms — no rocking. Turn the drive gears by hand with no filament loaded; they must spin freely and re-mesh without a catch.",- componentNodeIds: ["7074c6c564d4c09d"]+ componentNodeIds: ["7074c6c564d4c09d"],+ materials: [{ item: "MCH-MANI-BLK", quantity: 1 }],+ tools: [{ item: "TL-VISE-6IN", quantity: 1 }]},{title: "Install the 1.75mm bowden adaptor",instruction:"Thread the adaptor in until the collet shoulder meets the body, then a quarter turn more — no PTFE tape. Push a 100mm filament offcut through by hand to confirm a clear, straight path before moving on.",- componentNodeIds: ["aac8ae0dc80653bf"]+ componentNodeIds: ["aac8ae0dc80653bf"],+ materials: [{ item: "ASM-VALVE-SUB", quantity: 1 }]},{title: "Secure the fan bracket with two M3×8",@@ -49,5 +56,22 @@ export const precisionAssembly: AssemblySpec = {"Seat the shroud so the outlet aims at the nozzle tip with roughly 2mm clearance. Route the fan lead through the strain relief before closing — a lead pinched at this joint survives the test print and fails in the first 50 hours.",componentNodeIds: ["b9d4cb1e0a50bacf"]}+ ],+ componentMappings: [+ // model part "tool plate"+ {+ geometryHash: "2923220f8a5630d23a966e0442e55145ed73c296",+ item: "FAB-BASE-WLD"+ },+ // model part "drive body"+ {+ geometryHash: "dd8cec0c1daf1ec1de79960d564741193798274b",+ item: "MCH-MANI-BLK"+ },+ // model part "hotend"+ {+ geometryHash: "2217620416b0fc5bdce8e2b865b3496ffcedaded",+ item: "ASM-VALVE-SUB"+ }]};diff --git a/packages/database/src/datasets/data/precision/change-orders.ts b/packages/database/src/datasets/data/precision/change-orders.tsindex faf6c80124..630676cb5c 100644--- a/packages/database/src/datasets/data/precision/change-orders.ts+++ b/packages/database/src/datasets/data/precision/change-orders.ts@@ -64,6 +64,73 @@ export const CHANGE_ORDERS: ChangeOrderSpec[] = [sortOrder: 1}]+ },+ // Lifecycle-only notices: no affected items yet (every change type spins a+ // method draft), so they exercise the stage flow + action tasks alone.+ {+ ref: "co:start",+ name: "Add lead-in chamfer to the pump housing needle-bearing bore",+ type: "Engineering",+ changeOrderType: "Design Improvement",+ status: "Start",+ priority: "Medium",+ openDateOffset: -10,+ dueDateOffset: 30,+ reasonForChange:+ "Assembly is shaving the drawn cup on press-in because the bore has only a break-edge; a 15° lead-in chamfer would guide the cup square.",+ affectedItems: [],+ actionTasks: [+ { action: "Engineering Review", status: "In Progress", dueDateOffset: 5 },+ { action: "Update Drawings / CAD", status: "Pending", dueDateOffset: 20 }+ ]+ },+ {+ ref: "co:eng-complete",+ name: "Add 100% ring-gauge check of HK1512 cup OD to the receiving plan",+ type: "Manufacturing",+ changeOrderType: "Quality / Reliability Improvement",+ status: "Engineering Complete",+ priority: "High",+ openDateOffset: -58,+ dueDateOffset: 14,+ reasonForChange:+ "The Midway needle-bearing escape showed an AQL sample of three cannot reliably catch an oversize drawn cup before it reaches the press.",+ nonConformance: "ncr:needle-od",+ affectedItems: [],+ actionTasks: [+ {+ action: "Quality Review",+ status: "Completed",+ dueDateOffset: -44,+ completedOffset: -46+ },+ {+ action: "Notify Affected Parties",+ status: "In Progress",+ dueDateOffset: 7+ }+ ]+ },+ {+ ref: "co:cancelled",+ name: "Correct the port thread callout on the manifold end cap drawing",+ type: "Documentation",+ changeOrderType: "Documentation Error / Correction",+ status: "Cancelled",+ priority: "Low",+ openDateOffset: -130,+ reasonForChange:+ "Cedar Valley flagged a 1/4 NPT vs. SAE-6 ORB mismatch on MCH-END-CAP; their copy turned out to be a superseded print and our drawing was already correct.",+ affectedItems: [],+ actionTasks: [+ {+ action: "Engineering Review",+ status: "Completed",+ dueDateOffset: -120,+ completedOffset: -124+ },+ { action: "Update Drawings / CAD", status: "Skipped" }+ ]}];diff --git a/packages/database/src/datasets/data/precision/foundation.ts b/packages/database/src/datasets/data/precision/foundation.tsindex 0a0ae39de2..bfa582f1e4 100644--- a/packages/database/src/datasets/data/precision/foundation.ts+++ b/packages/database/src/datasets/data/precision/foundation.ts@@ -1,13 +1,19 @@import type {ContractorAgencySpec,+ EmployeeJobSpec,FoundationData,+ HolidaySpec,+ MaterialTaxonomySpec,+ PartnerSpec,PlantSpec,PrinterRouteSpec,ProcedureSpec,ProcedureStepSpec,ShelfSpec,ShiftSpec,- WarehouseSpec+ TagSpec,+ WarehouseSpec,+ WorkCenterSpec} from "../../types.ts";// ---------------------------------------------------------------------------@@ -121,6 +127,29 @@ export const WORK_CENTER_PROCESS_LINKS: Array<[string, string]> = [["CMM Lab", "Final Inspection"]];+export const WORK_CENTER_SHIFTS: Array<[string, string]> = [+ ["VMC Cell 1", "First Shift"],+ ["VMC Cell 1", "Second Shift"],+ ["VMC Cell 1", "Saturday Overtime"],+ ["VMC Cell 2", "First Shift"],+ ["VMC Cell 2", "Second Shift"],+ ["VMC Cell 2", "Saturday Overtime"],+ ["Turning Cell", "First Shift"],+ ["Turning Cell", "Second Shift"],+ ["Wire EDM Cell", "First Shift"],+ ["Fab & Weld Bay", "First Shift"],+ ["Finish & Assembly Bench", "First Shift"],+ ["CMM Lab", "First Shift"],+ ["CMM Lab", "Saturday Overtime"]+];++export const EMPLOYEE_JOB: EmployeeJobSpec = {+ title: "Machining Supervisor",+ department: "Machining",+ shift: "First Shift",+ startDateOffset: -1460+};+export const PLANT: PlantSpec = {name: "Meridian Machining Plant",addressLine1: "1725 Kishwaukee Street",@@ -329,6 +358,37 @@ export const SUPPLIERS = [type: "Services",phone: "+1-608-555-0770",website: "https://precisiongauge.com"+ },+ // Status showcases + the EUR vendor. None of these may be referenced by+ // purchasing data — they exist so every supplier status renders somewhere.+ {+ name: "Old Mill Steel Supply",+ type: "Materials",+ phone: "+1-563-555-0880",+ website: "https://oldmillsteel.com",+ status: "Inactive" as const+ },+ {+ name: "Prairie Anodizing",+ type: "Finishing",+ phone: "+1-217-555-0990",+ website: "https://prairieanodizing.com",+ status: "Pending" as const+ },+ {+ name: "Cutrate Carbide",+ type: "Tooling",+ phone: "+1-773-555-1010",+ website: "https://cutratecarbide.com",+ status: "Rejected" as const+ },+ {+ name: "Bavaria Werkzeugstahl GmbH",+ type: "Materials",+ phone: "+49-89-555-1120",+ website: "https://bavaria-werkzeugstahl.de",+ status: "Active" as const,+ currencyCode: "EUR"}];@@ -381,6 +441,34 @@ export const SUPPLIER_CONTACTS = [lastName: "Lundqvist",email: "[email protected]",title: "Calibration Manager"+ },+ {+ supplier: "Old Mill Steel Supply",+ firstName: "Chuck",+ lastName: "Danvers",+ email: "[email protected]",+ title: "Sales Manager"+ },+ {+ supplier: "Prairie Anodizing",+ firstName: "Maya",+ lastName: "Sandoval",+ email: "[email protected]",+ title: "Business Development"+ },+ {+ supplier: "Cutrate Carbide",+ firstName: "Lonnie",+ lastName: "Pratt",+ email: "[email protected]",+ title: "Account Executive"+ },+ {+ supplier: "Bavaria Werkzeugstahl GmbH",+ firstName: "Franziska",+ lastName: "Huber",+ email: "[email protected]",+ title: "Export Sales"}];@@ -393,6 +481,27 @@ export const SUPPLIER_PROCESSES = [{ supplier: "Precision Gauge Services", process: "Final Inspection" }];+export const PARTNERS: PartnerSpec[] = [+ {+ supplier: "Anvil Finishing Group",+ ability: "Deburr & Finishing",+ hoursPerWeek: 32+ },+ {+ supplier: "Precision Gauge Services",+ ability: "Inspection",+ hoursPerWeek: 16+ }+];++export const HQ_WORK_CENTER: WorkCenterSpec = {+ name: "Headquarters Toolroom",+ dept: "Machining",+ ability: "CNC Milling",+ laborRate: 78,+ machineRate: 35+};+export const CONTRACTORS = [{firstName: "Ramon",@@ -459,10 +568,15 @@ export const PROCEDURES: ProcedureSpec[] = [process: "CNC Milling",description:"Second-operation milling of the 6061 pump housing, including the bearing bore.",+ parameters: [+ { key: "Bearing bore", value: "Ø 42.000 +0.016 / −0 mm" },+ { key: "Spindle speed, finish bore", value: "3,200 rpm" },+ { key: "Coolant concentration", value: "6–8 %" }+ ],versions: [{version: 1,- status: "Draft",+ status: "Archived",steps: [{name: "Verify the first-operation part against the traveler",@@ -481,7 +595,7 @@ export const PROCEDURES: ProcedureSpec[] = [}]},- { version: 2, status: "Draft", steps: PUMP_HOUSING_OP2_STEPS_V2 }+ { version: 2, status: "Active", steps: PUMP_HOUSING_OP2_STEPS_V2 }]},{@@ -492,7 +606,7 @@ export const PROCEDURES: ProcedureSpec[] = [versions: [{version: 1,- status: "Draft",+ status: "Active",steps: [{name: "Stage the kit at the assembly bench",@@ -538,6 +652,11 @@ export const PROCEDURES: ProcedureSpec[] = [process: "Final Inspection",description:"CMM report and certificate of conformance against the customer-supplied print.",+ parameters: [+ { key: "CMM program", value: "PRG-HSG-OP2 Rev D" },+ { key: "Lab temperature", value: "20 ± 1 °C" },+ { key: "Report format", value: "AS9102 FAI form 3" }+ ],versions: [{version: 1,@@ -572,6 +691,26 @@ export const PROCEDURES: ProcedureSpec[] = [type: "Task",instruction:"Print the CMM report, attach it to the CoC and file both against the job before release to shipping."+ },+ {+ name: "Stamp inspection completion time",+ type: "Timestamp",+ instruction:+ "Record the moment final inspection completes — the CoC ship date and the customer's dock date are measured from here."+ },+ {+ name: "Upload the FAIR package",+ type: "File",+ instruction:+ "Upload the AS9102 first-article inspection report and the raw CMM export against the job record.",+ fileTypes: ["pdf", "csv"]+ },+ {+ name: "Final workmanship inspection",+ type: "Inspection",+ instruction:+ "Inspect deburred edges, anodize coverage and thread condition under magnification. Photograph any finding before release to shipping.",+ required: false}]}@@ -616,11 +755,73 @@ export const NO_QUOTE_REASONS = ["Material Not Sourced"];+// Offsets are positive (upcoming) and distinct — holiday has UNIQUE (date).+export const HOLIDAYS: HolidaySpec[] = [+ { name: "Shop Anniversary Day", dateOffset: 40 },+ { name: "IMTS Week Shutdown", dateOffset: 100 },+ { name: "Year-End Maintenance Shutdown", dateOffset: 160 }+];++export const TAGS: TagSpec[] = [+ { name: "Tight Tolerance", table: "operation" },+ { name: "First Article Required", table: "procedure" },+ { name: "GD&T Certified", table: "training" },+ { name: "Certs Required", table: "material" },+ { name: "Calibrated", table: "tool" }+];++// Names deliberately avoid the GLOBAL substances/forms migrations seed (Steel,+// Aluminum, Sheet, Plate, …) so the settings screens don't show duplicates.+export const MATERIAL_TAXONOMY: MaterialTaxonomySpec = {+ substances: [+ { name: "Tool Steel", code: "TS" },+ // Backs the bar-stock classifications on MAT-4140-BAR and MAT-AL6061-BAR+ // (items.ts).+ { name: "Chromoly Steel", code: "CRMO" },+ { name: "Extruded Aluminum", code: "EXAL" }+ ],+ forms: [+ { name: "Ground Flat Stock", code: "GFS" },+ { name: "Turned & Polished Bar", code: "TGP" }+ ],+ types: [+ {+ name: "Tool Steel Ground Flat Stock",+ code: "TS-GFS",+ substance: "Tool Steel",+ form: "Ground Flat Stock"+ },+ {+ name: "Chromoly TG&P Bar",+ code: "CRMO-TGP",+ substance: "Chromoly Steel",+ form: "Turned & Polished Bar"+ }+ ],+ grades: [+ { name: "A2", substance: "Tool Steel" },+ { name: "D2", substance: "Tool Steel" },+ { name: "4140 Pre-Hard", substance: "Chromoly Steel" },+ { name: "6061-T6", substance: "Extruded Aluminum" }+ ],+ finishes: [+ { name: "Precision Ground", substance: "Tool Steel" },+ { name: "Rust-Preventive Oil", substance: "Chromoly Steel" },+ { name: "Mill Finish", substance: "Extruded Aluminum" }+ ],+ dimensions: [+ { name: '1/2" x 2"', form: "Ground Flat Stock", isMetric: false },+ { name: '3/4" x 3"', form: "Ground Flat Stock", isMetric: false },+ { name: '2.500" dia', form: "Turned & Polished Bar", isMetric: false }+ ]+};+export const precisionFoundation: FoundationData = {departments: DEPT_NAMES,abilities: ABILITIES,processes: PROCESSES,workCenters: WORK_CENTERS,+ hqWorkCenter: HQ_WORK_CENTER,customers: CUSTOMERS,customerContacts: CUSTOMER_CONTACTS,suppliers: SUPPLIERS,@@ -636,12 +837,18 @@ export const precisionFoundation: FoundationData = {costCenters: COST_CENTERS,noQuoteReasons: NO_QUOTE_REASONS,contractors: CONTRACTORS,+ partners: PARTNERS,plant: PLANT,shifts: SHIFTS,+ workCenterShifts: WORK_CENTER_SHIFTS,+ employeeJob: EMPLOYEE_JOB,warehouses: WAREHOUSES,storageTypes: STORAGE_TYPES,shelves: SHELVES,printerRoute: PRINTER_ROUTE,+ holidays: HOLIDAYS,+ tags: TAGS,+ materialTaxonomy: MATERIAL_TAXONOMY,defaultShippingMethod: "UPS Ground",contractorAgency: CONTRACTOR_AGENCY,partyAddressCity: "Rockford",diff --git a/packages/database/src/datasets/data/precision/index.ts b/packages/database/src/datasets/data/precision/index.tsindex 457bbf4ee6..792171f192 100644--- a/packages/database/src/datasets/data/precision/index.ts+++ b/packages/database/src/datasets/data/precision/index.ts@@ -4,6 +4,7 @@ import { precisionChangeOrders } from "./change-orders.ts";import { precisionFoundation } from "./foundation.ts";import { precisionInventory } from "./inventory.ts";import { precisionItems } from "./items.ts";+import { precisionOps } from "./ops.ts";import { precisionPlanning } from "./planning.ts";import { precisionProduction } from "./production.ts";import { precisionPurchasing } from "./purchasing.ts";@@ -29,6 +30,7 @@ export const precision: Dataset = {quality: precisionQuality,changeOrders: precisionChangeOrders,accounting: precisionAccounting,+ ops: precisionOps,workflows: precisionWorkflows,planning: precisionPlanning};diff --git a/packages/database/src/datasets/data/precision/inventory.ts b/packages/database/src/datasets/data/precision/inventory.tsindex d5251c6154..62380d4c5f 100644--- a/packages/database/src/datasets/data/precision/inventory.ts+++ b/packages/database/src/datasets/data/precision/inventory.ts@@ -3,7 +3,10 @@ import type {InventoryData,KanbanItemSpec,OpeningStockSpec,- TrackedStockSpec+ ShelfLifeSpec,+ StockTransferSpec,+ TrackedStockSpec,+ WarehouseTransferSpec} from "../../types.ts";// Opening inventory — realistic quantities for a contract machine shop.@@ -21,7 +24,7 @@ export const OPENING_STOCK: OpeningStockSpec[] = [{ item: "PIN-CLEVIS-12", qty: 90, shelf: "B2-L2" },{ item: "BSH-BRZ-2012", qty: 140, shelf: "B2-L2" },{ item: "CYL-HYD-40", qty: 6, shelf: "B2-L3" },- { item: "MAT-AL6061-BAR", qty: 620, shelf: "Bar-Stock" },+ { item: "MAT-AL6061-BAR", qty: 626, shelf: "Bar-Stock" },{ item: "MAT-AL5052-SHT", qty: 380, shelf: "Bar-Stock" },{ item: "MAT-SS304-BAR", qty: 260, shelf: "Bar-Stock" },{ item: "MAT-SS316-PLT", qty: 210, shelf: "Bar-Stock" },@@ -31,13 +34,14 @@ export const OPENING_STOCK: OpeningStockSpec[] = [{ item: "CN-DEBURR-MED", qty: 90, shelf: "B3-L1" }];-// Lots/serials that back the tracked slice of the opening stock above.+// Backs the tracked slice of the opening stock above.export const ON_HAND_TRACKED: TrackedStockSpec[] = [{item: "BRG-DBL-6205",entities: [{ readableId: "LOT-BRG-2611", quantity: 16 },- { readableId: "LOT-BRG-2612", quantity: 8 }+ { readableId: "LOT-BRG-2612", quantity: 8, expiresOffset: 30 },+ { readableId: "LOT-BRG-2613", quantity: 2, status: "On Hold" }]},{@@ -55,26 +59,190 @@ export const ON_HAND_TRACKED: TrackedStockSpec[] = [item: "MAT-AL6061-BAR",entities: [{ readableId: "LOT-AL6061-2610", quantity: 400 },- { readableId: "LOT-AL6061-2611", quantity: 220 }+ { readableId: "LOT-AL6061-2611", quantity: 220 },+ { readableId: "LOT-AL6061-2612", quantity: 3, status: "Rejected" },+ {+ readableId: "LOT-AL6061-2605",+ quantity: 6,+ status: "Scrapped",+ scrap: {+ shelf: "Bar-Stock",+ reason: "Damaged",+ dateOffset: -41,+ comment:+ "Bars bowed beyond straightness tolerance after a rack collapse"+ }+ }]}];-// Kanbans (auto-replenishment cards) for high-usage buy parts.+// LOT-BRG-2612 above expires in 30 days so the expiry chips show amber.+export const SHELF_LIVES: ShelfLifeSpec[] = [+ { item: "BRG-DBL-6205", days: 365 }+];+export const KANBAN_ITEMS: KanbanItemSpec[] = [{ item: "HW-SHCS-M6", qty: 250, supplier: "Fastline Industrial Supply" },{ item: "HW-SHCS-M10", qty: 150, supplier: "Fastline Industrial Supply" },- { item: "SEAL-ORING-224", qty: 200, supplier: "Midway Bearing & Seal" }+ { item: "SEAL-ORING-224", qty: 200, supplier: "Midway Bearing & Seal" },+ { item: "MCH-SPACER-KIT", qty: 5, replenishmentSystem: "Make" },+ {+ item: "CN-DEBURR-MED",+ qty: 20,+ replenishmentSystem: "Transfer",+ fromShelf: "B3-L1",+ toShelf: "B3-L2"+ }];-export const INVENTORY_COUNT: InventoryCountSpec = {- status: "Draft",- notes: "Cycle count — hardware bins and bar stock racking"-};+export const INVENTORY_COUNTS: InventoryCountSpec[] = [+ {+ // The first six opening-stock rows.+ key: "q3-draft",+ status: "Draft",+ notes: "Cycle count — hardware bins and bar stock racking",+ lines: [+ {+ item: "HW-SHCS-M6",+ shelf: "B1-L1",+ snapshotQuantity: 800,+ countedQuantity: 800+ },+ {+ item: "HW-SHCS-M10",+ shelf: "B1-L1",+ snapshotQuantity: 500,+ countedQuantity: 500+ },+ {+ item: "HW-DOWEL-8",+ shelf: "B1-L2",+ snapshotQuantity: 300,+ countedQuantity: 300+ },+ {+ item: "INS-HELI-M6",+ shelf: "B1-L2",+ snapshotQuantity: 400,+ countedQuantity: 400+ },+ {+ item: "BRG-DBL-6205",+ shelf: "B1-L3",+ snapshotQuantity: 24,+ countedQuantity: 24+ },+ {+ item: "BRG-NDL-HK1512",+ shelf: "B1-L3",+ snapshotQuantity: 30,+ countedQuantity: 30+ }+ ]+ },+ {+ key: "aug-cycle",+ status: "Posted",+ notes: "Cycle count — fastener & hardware bins",+ postedOffset: -20,+ lines: [+ {+ item: "HW-SHCS-M6",+ shelf: "B1-L1",+ snapshotQuantity: 800,+ countedQuantity: 798+ },+ {+ item: "HW-SHCS-M10",+ shelf: "B1-L1",+ snapshotQuantity: 500,+ countedQuantity: 500+ },+ {+ item: "HW-DOWEL-8",+ shelf: "B1-L2",+ snapshotQuantity: 300,+ countedQuantity: 302+ },+ {+ item: "INS-HELI-M6",+ shelf: "B1-L2",+ snapshotQuantity: 400,+ countedQuantity: 400+ },+ {+ item: "SEAL-ORING-224",+ shelf: "B2-L1",+ snapshotQuantity: 600,+ countedQuantity: 600+ }+ ]+ }+];++// Only the Completed move changes stock, so it's dated after the posted count above.+export const STOCK_TRANSFERS: StockTransferSpec[] = [+ {+ key: "st-completed",+ status: "Completed",+ fromShelf: "B1-L1",+ toShelf: "B1-L2",+ dateOffset: -10,+ lines: [{ item: "HW-SHCS-M6", quantity: 100 }]+ },+ {+ key: "st-released",+ status: "Released",+ fromShelf: "B1-L1",+ toShelf: "B2-L3",+ dateOffset: -1,+ lines: [{ item: "HW-SHCS-M10", quantity: 50 }]+ },+ {+ key: "st-draft",+ status: "Draft",+ fromShelf: "B2-L1",+ toShelf: "B2-L2",+ dateOffset: 0,+ lines: [{ item: "SPR-DIE-25", quantity: 12 }]+ }+];++// HQ has no bins, so completed receipts land shelfless.+export const WAREHOUSE_TRANSFERS: WarehouseTransferSpec[] = [+ {+ key: "wt-completed",+ status: "Completed",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: -12,+ lines: [{ item: "HW-SHCS-M10", quantity: 25, fromShelf: "B1-L1" }]+ },+ {+ key: "wt-toship",+ status: "To Ship",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: 0,+ lines: [{ item: "PIN-CLEVIS-12", quantity: 10, fromShelf: "B2-L2" }]+ },+ {+ key: "wt-draft",+ status: "Draft",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: 2,+ lines: [{ item: "BSH-BRZ-2012", quantity: 8, fromShelf: "B2-L2" }]+ }+];export const precisionInventory: InventoryData = {openingStock: OPENING_STOCK,onHandTracked: ON_HAND_TRACKED,kanbanItems: KANBAN_ITEMS,- inventoryCount: INVENTORY_COUNT+ inventoryCounts: INVENTORY_COUNTS,+ shelfLives: SHELF_LIVES,+ stockTransfers: STOCK_TRANSFERS,+ warehouseTransfers: WAREHOUSE_TRANSFERS};diff --git a/packages/database/src/datasets/data/precision/items.ts b/packages/database/src/datasets/data/precision/items.tsindex 5715e2d8db..0a31ee3252 100644--- a/packages/database/src/datasets/data/precision/items.ts+++ b/packages/database/src/datasets/data/precision/items.ts@@ -1,9 +1,19 @@-import type { ItemSpec } from "../../helpers/items.ts";import type {+ BatchPropertySpec,+ ConfigurationSpec,+ CustomerPartSpec,+ EnforcementRuleSpec,+ InspectionPlanSpec,+ ItemSpec,ItemsData,MakeMethodSpec,+ PriceOverrideSpec,+ PricingRuleSpec,+ RevisionLadderSpec,+ SupersessionSpec,SupplierLinkSpec} from "../../types.ts";+import { precisionAssembly } from "./assembly.ts";// ---------------------------------------------------------------------------// Job-shop catalog for Meridian Precision Works.@@ -123,6 +133,16 @@ export const BUY_PARTS: ItemSpec[] = [standardCost: 285,unitSalePrice: 430,leadTime: 35+ },+ // Deliberately absent from every BOM: job creation and picking redirect to it via SUPERSESSIONS.+ {+ readableId: "BSH-PTFE-2012",+ name: "PTFE-Lined Composite Bushing 20 x 12",+ type: "Part",+ replenishment: "Buy",+ standardCost: 4.6,+ unitSalePrice: 7.5,+ leadTime: 10}];@@ -134,7 +154,13 @@ export const MATERIALS: ItemSpec[] = [trackingType: "Batch",standardCost: 3.85,unitOfMeasureCode: "LB",- leadTime: 10+ leadTime: 10,+ // Partially classified on purpose.+ material: {+ substance: "Extruded Aluminum",+ grade: "6061-T6",+ finish: "Mill Finish"+ }},{readableId: "MAT-AL5052-SHT",@@ -168,7 +194,15 @@ export const MATERIALS: ItemSpec[] = [trackingType: "Batch",standardCost: 2.75,unitOfMeasureCode: "LB",- leadTime: 14+ leadTime: 14,+ material: {+ substance: "Chromoly Steel",+ form: "Turned & Polished Bar",+ materialType: "Chromoly TG&P Bar",+ grade: "4140 Pre-Hard",+ finish: "Rust-Preventive Oil",+ dimension: '2.500" dia'+ }},{readableId: "MAT-CRS-TUBE",@@ -232,7 +266,7 @@ export const MAKE_PARTS: ItemSpec[] = [replenishment: "Make",// Serial-tracked: each unit gets its own genealogy in traceability.trackingType: "Serial",- standardCost: 0,+ standardCost: 2310,unitSalePrice: 4200},{@@ -240,7 +274,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Manifold Block, 6061-T6",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 539,unitSalePrice: 980},{@@ -248,7 +282,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Pump Housing, 6061-T6",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 632,unitSalePrice: 1150},{@@ -256,7 +290,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Manifold End Cap, 316L",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 132,unitSalePrice: 240},{@@ -264,7 +298,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Drive Shaft, 4140 Pre-Hard",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 176,unitSalePrice: 320},{@@ -272,7 +306,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Piston Rod, 4140 Hard Chrome",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 231,unitSalePrice: 420},{@@ -280,7 +314,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Mounting Flange, 304 Stainless",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 102,unitSalePrice: 185},{@@ -288,7 +322,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Precision Spacer Set",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 57.75,unitSalePrice: 105},{@@ -296,7 +330,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Sheet Metal Enclosure Panel Set",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 352,unitSalePrice: 640},{@@ -304,7 +338,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Welded Base Frame",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 814,unitSalePrice: 1480},{@@ -312,7 +346,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Valve Sub-Assembly",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 490,unitSalePrice: 890}];@@ -386,7 +420,11 @@ export const METHODS: MakeMethodSpec[] = [order: 1,laborTime: 1.5,setupTime: 0.75,- machineTime: 1.25+ machineTime: 1.25,+ parameters: [+ { key: "Workholding", value: "6 in vise, hard jaws on parallels" },+ { key: "Coolant", value: "Flood — semi-synthetic" }+ ]},{process: "CNC Milling",@@ -396,7 +434,13 @@ export const METHODS: MakeMethodSpec[] = [laborTime: 2,machineTime: 1.75,// Gives the MES operation screen an Instructions tab with real steps.- procedure: "procedure:Pump Housing Second Operation"+ procedure: "procedure:Pump Housing Second Operation",+ tools: [{ tool: "TL-FIXT-HSG", quantity: 1 }],+ parameters: [+ { key: "Fixture", value: "TL-FIXT-HSG soft jaws, bored in place" },+ { key: "Finish Bore Speed/Feed", value: "6200 RPM, 18 in/min" },+ { key: "Coolant", value: "Flood — semi-synthetic" }+ ]},{process: "Outside Processing",@@ -475,7 +519,9 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "CMM Lab",description: "Hardness check and runout report",order: 3,- laborTime: 0.5+ laborTime: 0.5,+ operationType: "Inspection",+ inspectionPlan: "SHAFT-DR-RUNOUT"}]},@@ -776,10 +822,257 @@ export const SUPPLIER_LINKS: SupplierLinkSpec[] = [item: "SEAL-ORING-224",price: 0.35,leadTime: 10+ },+ {+ supplier: "Midway Bearing & Seal",+ item: "BSH-PTFE-2012",+ price: 4.6,+ leadTime: 10+ }+];++// MCH-PISTON-ROD still names BSH-BRZ-2012 (140 in bin B2-L2), so Consume First+// keeps pulling the bronze bushing until the bin is empty, then swaps to the+// PTFE-lined replacement.+export const SUPERSESSIONS: SupersessionSpec[] = [+ {+ predecessor: "BSH-BRZ-2012",+ successor: "BSH-PTFE-2012",+ mode: "Consume First",+ successorEffectivityOffset: -14+ }+];++export const CUSTOMER_PARTS: CustomerPartSpec[] = [+ {+ item: "HMA-4000",+ customer: "Cedar Valley Hydraulics",+ customerPartId: "CVH-HPU-4000",+ customerRevision: "C"+ },+ {+ item: "MCH-HSG-PUMP",+ customer: "Granite State Instruments",+ customerPartId: "GSI-PMP-118"}];+export const PRICE_OVERRIDES: PriceOverrideSpec[] = [+ {+ item: "HMA-4000",+ customer: "Dominion Ag Equipment",+ notes: "Season-build blanket pricing per the 2026 supply agreement.",+ breaks: [+ { quantity: 2, overridePrice: 4100 },+ { quantity: 10, overridePrice: 3950 }+ ]+ }+];++export const PRICING_RULES: PricingRuleSpec[] = [+ {+ name: "Cedar Valley volume discount",+ ruleType: "Discount",+ amountType: "Percentage",+ amount: 5,+ customer: "Cedar Valley Hydraulics",+ minQuantity: 10,+ priority: 10+ },+ {+ name: "Medical cleanroom packaging uplift",+ ruleType: "Markup",+ amountType: "Percentage",+ amount: 15,+ customerType: "Medical",+ items: ["MCH-MANI-BLK", "MCH-HSG-PUMP"],+ priority: 5+ },+ {+ name: "Cap screw carton break",+ ruleType: "Discount",+ amountType: "Fixed",+ amount: 0.04,+ items: ["HW-SHCS-M6", "HW-SHCS-M10"],+ minQuantity: 200,+ priority: 1+ }+];++export const CONFIGURATION: ConfigurationSpec = {+ item: "HMA-4000",+ group: "Power Unit Configuration",+ parameters: [+ {+ key: "rated_pressure_psi",+ label: "Rated Pressure (psi)",+ dataType: "numeric"+ },+ {+ key: "port_thread",+ label: "Port Thread Standard",+ dataType: "list",+ listOptions: ["SAE ORB", "BSPP", "NPT"]+ },+ {+ key: "hydro_test_cert",+ label: "Include Hydrostatic Test Certificate",+ dataType: "boolean"+ }+ ],+ rules: [+ {+ target: { operation: 2 },+ field: "laborTime",+ code: "return params.rated_pressure_psi > 3000 ? 6 : 4;"+ },+ {+ target: { operation: 3 },+ field: "laborTime",+ code: "return params.hydro_test_cert ? 2.5 : 1.5;"+ }+ ]+};++export const REVISION_LADDER: RevisionLadderSpec[] = [+ {+ item: "MCH-FLANGE-SS",+ obsoleteRevision: "A",+ nextRevision: "B",+ nextStatus: "Prototype"+ }+];++// A sampling plan of its own makes the MES open an inspection lot, not a plain operation.+export const INSPECTION_PLANS: InspectionPlanSpec[] = [+ {+ key: "SHAFT-DR-RUNOUT",+ item: "MCH-SHAFT-DR",+ drawingNumber: "MPW-2217 Rev B",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Bearing journal diameter after induction harden",+ nominalValue: "25.000",+ tolerancePlus: "0.008",+ toleranceMinus: "0.008",+ unit: "mm"+ },+ {+ label: "2",+ description: "Total indicated runout at the coupling end",+ nominalValue: "0.010",+ tolerancePlus: "0.010",+ toleranceMinus: "0.010",+ unit: "mm"+ }+ ]+ }+];++export const ENFORCEMENT_RULES: EnforcementRuleSpec[] = [+ {+ family: "sales",+ name: "Power units — North America ship-to only",+ description: "CRN / CSA registration covers US, Canada and Mexico.",+ message:+ "HMA-4000 pressure registration covers North American installations only. Route other destinations through engineering.",+ severity: "error",+ surfaces: ["salesOrderLine", "salesInvoiceLine"],+ match: "all",+ conditions: [+ {+ field: "customer.location.countryCode",+ op: "in",+ value: ["US", "CA", "MX"]+ }+ ],+ items: ["HMA-4000"]+ },+ {+ family: "sales",+ name: "Medical manifolds need a cleanliness certificate",+ message:+ "Medical customers require an ISO 16232 cleanliness certificate — add the cleaning and cert to the quote.",+ severity: "warn",+ surfaces: ["quoteLine", "salesOrderLine"],+ match: "all",+ conditions: [+ {+ field: "customer.customerTypeId",+ op: "notIn",+ value: { customerTypes: ["Medical"] }+ }+ ],+ items: ["MCH-MANI-BLK", "MCH-HSG-PUMP"]+ },+ {+ family: "storage",+ targetType: "item",+ name: "Bar stock on racks",+ message: "Bar stock is racked by grade — never binned.",+ severity: "warn",+ surfaces: ["place"],+ match: "all",+ conditions: [+ {+ field: "storageUnit.storageTypeId",+ op: "eq",+ value: { storageType: "Rack" }+ }+ ],+ items: ["MAT-AL6061-BAR", "MAT-SS304-BAR", "MAT-4140-BAR"]+ },+ {+ family: "storage",+ targetType: "item",+ name: "Bearings stay at the plant",+ message:+ "Bearings are kitted at the Rockford plant only — pick a plant bin.",+ severity: "warn",+ surfaces: ["receipt", "stockTransfer"],+ match: "all",+ conditions: [+ {+ field: "storageUnit.locationId",+ op: "eq",+ value: { location: "Plant" }+ }+ ],+ items: ["BRG-DBL-6205", "BRG-NDL-HK1512"]+ },+ {+ family: "storage",+ targetType: "workCenter",+ name: "Wire EDM in service",+ message:+ "The wire EDM is out of service — hold the cut until maintenance releases it.",+ severity: "error",+ surfaces: ["operationStart"],+ match: "all",+ conditions: [{ field: "workCenter.active", op: "eq", value: true }],+ workCenters: ["Wire EDM Cell"]+ }+];++export const BATCH_PROPERTIES: BatchPropertySpec[] = [+ { item: "BRG-DBL-6205", label: "Date code", dataType: "text" },+ {+ item: "BRG-DBL-6205",+ label: "Grease fill",+ dataType: "list",+ listOptions: ["Standard", "Low-temperature"]+ },+ { item: "MAT-AL6061-BAR", label: "Heat number", dataType: "text" },+ { item: "MAT-SS304-BAR", label: "Heat number", dataType: "text" },+ { item: "MAT-SS304-BAR", label: "Mill cert received", dataType: "boolean" },+ { item: "MAT-4140-BAR", label: "Heat number", dataType: "text" },+ { item: "MAT-4140-BAR", label: "Hardness (HRC)", dataType: "numeric" }+];+export const precisionItems: ItemsData = {+ assembly: precisionAssembly,buyParts: BUY_PARTS,materials: MATERIALS,consumables: CONSUMABLES,@@ -787,5 +1080,14 @@ export const precisionItems: ItemsData = {services: SERVICES,makeParts: MAKE_PARTS,methods: METHODS,- supplierLinks: SUPPLIER_LINKS+ supplierLinks: SUPPLIER_LINKS,+ supersessions: SUPERSESSIONS,+ customerParts: CUSTOMER_PARTS,+ priceOverrides: PRICE_OVERRIDES,+ pricingRules: PRICING_RULES,+ configuration: CONFIGURATION,+ revisionLadder: REVISION_LADDER,+ inspectionPlans: INSPECTION_PLANS,+ enforcementRules: ENFORCEMENT_RULES,+ batchProperties: BATCH_PROPERTIES};diff --git a/packages/database/src/datasets/data/precision/ops.ts b/packages/database/src/datasets/data/precision/ops.tsnew file mode 100644index 0000000000..a112904f9f--- /dev/null+++ b/packages/database/src/datasets/data/precision/ops.ts@@ -0,0 +1,573 @@+import type {+ CustomFieldSpec,+ MaintenanceDispatchSpec,+ MaintenanceScheduleSpec,+ NoteSpec,+ OpenTimecardSpec,+ OpsData,+ PeopleAbsenceSpec,+ PeopleAssignmentSpec,+ PrintJobSpec,+ ReplacementPartSpec,+ SerialSequenceSpec,+ SuggestionSpec,+ TimecardSpec,+ TrainingSpec,+ UserAttributeCategorySpec+} from "../../types.ts";++export const MAINTENANCE_SCHEDULES: MaintenanceScheduleSpec[] = [+ {+ key: "vmc1-chip-coolant",+ name: "VMC chip clean-out & coolant concentration",+ description:+ "Clear the chip auger, skim tramp oil and bring the sump back to 6–8% on the refractometer.",+ workCenter: "VMC Cell 1",+ frequency: "Daily",+ priority: "Medium",+ estimatedDuration: 20,+ nextDueOffset: 1+ },+ {+ key: "edm-filter",+ name: "Wire EDM filter & resin check",+ description:+ "Swap the dielectric filters, read the water conductivity and replace the deionizing resin when it runs over 10 µS/cm.",+ workCenter: "Wire EDM Cell",+ frequency: "Weekly",+ priority: "Medium",+ estimatedDuration: 40,+ nextDueOffset: 2+ },+ {+ key: "turning-sump",+ name: "Lathe coolant sump change",+ description:+ "Pump out and clean the turning cell sump, flush the lines and recharge with fresh semi-synthetic at 7%.",+ workCenter: "Turning Cell",+ frequency: "Monthly",+ priority: "High",+ estimatedDuration: 150,+ nextDueOffset: 19,+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-COOLANT-55", quantity: 1 }]+ },+ {+ key: "vmc2-ballbar",+ name: "VMC ballbar test & backlash compensation",+ description:+ "Run the Renishaw ballbar in all three planes and update the backlash comp when circularity drifts past 8 µm.",+ workCenter: "VMC Cell 2",+ frequency: "Quarterly",+ priority: "High",+ estimatedDuration: 180,+ nextDueOffset: 44,+ takesWorkCenterOffline: true+ },+ {+ key: "cmm-cert",+ name: "Annual CMM ISO 10360 re-certification",+ description:+ "Third-party volumetric verification of the CMM with the step gauge and a new calibration certificate.",+ workCenter: "CMM Lab",+ frequency: "Annual",+ priority: "High",+ estimatedDuration: 480,+ nextDueOffset: 140,+ takesWorkCenterOffline: true+ },+ {+ key: "toolroom-grinder",+ name: "Toolroom surface grinder way-lube and wheel dress",+ description:+ "Top off the way-lube reservoir, dress the wheel with the diamond, and check the magnetic chuck for flatness with an indicator sweep.",+ workCenter: "Headquarters Toolroom",+ frequency: "Weekly",+ priority: "Low",+ estimatedDuration: 40,+ nextDueOffset: 3+ }+];++export const MAINTENANCE_DISPATCHES: MaintenanceDispatchSpec[] = [+ {+ key: "edm-wire-break",+ status: "Open",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Wire EDM Cell",+ suspectedFailureMode: "Blockage",+ content:+ "Wire breaking every 20 minutes on the die-block job — flush nozzle looks partly plugged. Running at reduced power until it's cleared.",+ created: { offset: -1, time: "10:20:00" },+ plannedStart: { offset: 1, time: "06:30:00" },+ plannedEnd: { offset: 1, time: "08:30:00" }+ },+ {+ key: "vmc2-spindle",+ status: "Assigned",+ priority: "Critical",+ severity: "OEM Required",+ source: "Non-Conformance",+ oeeImpact: "Down",+ workCenter: "VMC Cell 2",+ nonConformance: "ncr:bore",+ suspectedFailureMode: "Bearing Failure",+ content:+ "Bores on the pump housing coming out 12 µm oversize and chattering. Spindle runout measured at 9 µm TIR — machine down; OEM booked for a spindle bearing replacement.",+ created: { offset: -3, time: "14:05:00" },+ plannedStart: { offset: 2, time: "07:00:00" },+ plannedEnd: { offset: 3, time: "15:00:00" },+ takesWorkCenterOffline: true,+ comments: [+ "OEM quoted a rebuilt cartridge — ships overnight.",+ "Pump housing Op-2 moved to VMC Cell 1 until the spindle is back."+ ]+ },+ {+ key: "cmm-probe-requal",+ status: "In Progress",+ priority: "Low",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "No Impact",+ workCenter: "CMM Lab",+ suspectedFailureMode: "Misalignment",+ content:+ "Star stylus failing qualification on the reference sphere by 3 µm after a crash on the fixture. Re-seating and re-qualifying.",+ created: { offset: -1, time: "12:40:00" },+ plannedStart: { offset: -1, time: "13:00:00" },+ plannedEnd: { offset: -1, time: "14:30:00" },+ actualStart: { offset: -1, time: "13:05:00" }+ },+ {+ key: "turning-sump-change",+ status: "Completed",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Turning Cell",+ schedule: "turning-sump",+ actualFailureMode: "Leak",+ content:+ "Monthly sump change. Found the coolant return hose weeping at the clamp — replaced the clamp, flushed and recharged the sump.",+ created: { offset: -9, time: "06:00:00" },+ plannedStart: { offset: -8, time: "12:30:00" },+ plannedEnd: { offset: -8, time: "15:00:00" },+ actualStart: { offset: -8, time: "12:40:00" },+ actualEnd: { offset: -8, time: "15:25:00" },+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-COOLANT-55", quantity: 1, shelf: "B3-L1" }],+ comments: ["Concentration after recharge: 7.2% on the refractometer."]+ },+ {+ key: "edm-filter-skip",+ status: "Cancelled",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Wire EDM Cell",+ schedule: "edm-filter",+ content:+ "Weekly filter check. Cancelled — filters and resin were replaced by the OEM during the wire-feed service two days earlier.",+ created: { offset: -6, time: "06:00:00" },+ plannedStart: { offset: -5, time: "11:00:00" },+ plannedEnd: { offset: -5, time: "11:40:00" }+ },+ {+ key: "vmc1-chip-today",+ status: "Assigned",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "VMC Cell 1",+ schedule: "vmc1-chip-coolant",+ content:+ "Daily chip clean-out: clear the auger, skim tramp oil and bring the sump back to 6–8% on the refractometer.",+ created: { offset: -1, time: "06:00:00" },+ plannedStart: { offset: 0, time: "14:00:00" },+ plannedEnd: { offset: 0, time: "14:20:00" }+ },+ {+ key: "edm-dielectric-seal",+ status: "In Progress",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Down",+ workCenter: "Wire EDM Cell",+ suspectedFailureMode: "Leak",+ content:+ "Dielectric pump shaft seal weeping into the tank enclosure — machine down while the pump is pulled and the seal kit fitted.",+ created: { offset: -1, time: "15:20:00" },+ plannedStart: { offset: -1, time: "15:30:00" },+ plannedEnd: { offset: 1, time: "12:00:00" },+ actualStart: { offset: -1, time: "15:45:00" },+ takesWorkCenterOffline: true,+ comments: ["Pump is out; O-rings from the cell's spares kit are staged."]+ },+ {+ key: "assembly-arbor-press",+ status: "Completed",+ priority: "Medium",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Finish & Assembly Bench",+ suspectedFailureMode: "Lubrication Failure",+ actualFailureMode: "Lubrication Failure",+ content:+ "Arbor press ram sticking on the return stroke while pressing manifold dowels. Ram cleaned and re-oiled; stroke smooth again.",+ created: { offset: -7, time: "14:30:00" },+ plannedStart: { offset: -7, time: "14:40:00" },+ plannedEnd: { offset: -7, time: "15:30:00" },+ actualStart: { offset: -7, time: "14:45:00" },+ actualEnd: { offset: -7, time: "15:15:00" }+ },+ {+ key: "turning-sump-prior",+ status: "Completed",+ priority: "High",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Turning Cell",+ schedule: "turning-sump",+ content:+ "Monthly sump change on the turning cell: pumped out, lines flushed and recharged at 7%.",+ created: { offset: -45, time: "06:00:00" },+ plannedStart: { offset: -44, time: "11:00:00" },+ plannedEnd: { offset: -44, time: "13:30:00" },+ actualStart: { offset: -44, time: "11:05:00" },+ actualEnd: { offset: -44, time: "13:20:00" },+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-COOLANT-55", quantity: 1, shelf: "B3-L1" }]+ },+ {+ key: "vmc1-way-cover",+ status: "Completed",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Down",+ workCenter: "VMC Cell 1",+ suspectedFailureMode: "Cracking/Fatigue",+ actualFailureMode: "Cracking/Fatigue",+ content:+ "Y-axis telescoping way cover split at the second section — chips reaching the ways. Cover section replaced and the ways cleaned and inspected.",+ created: { offset: -52, time: "10:00:00" },+ plannedStart: { offset: -52, time: "10:30:00" },+ plannedEnd: { offset: -52, time: "17:00:00" },+ actualStart: { offset: -52, time: "10:40:00" },+ actualEnd: { offset: -51, time: "12:10:00" },+ takesWorkCenterOffline: true+ },+ {+ key: "toolroom-presetter",+ status: "Open",+ priority: "Medium",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Headquarters Toolroom",+ suspectedFailureMode: "Misalignment",+ content:+ "Tool presetter camera reads 8 µm long on the reference master — offsets from it can't be trusted until it's re-zeroed.",+ created: { offset: -2, time: "09:30:00" },+ plannedStart: { offset: 1, time: "08:00:00" },+ plannedEnd: { offset: 1, time: "09:30:00" }+ }+];++export const REPLACEMENT_PARTS: ReplacementPartSpec[] = [+ { workCenter: "Wire EDM Cell", item: "SEAL-ORING-224", quantity: 4 },+ { workCenter: "Turning Cell", item: "CN-COOLANT-55", quantity: 1 },+ { workCenter: "VMC Cell 2", item: "SPR-DIE-25", quantity: 2 }+];++export const TRAININGS: TrainingSpec[] = [+ {+ name: "CNC Machine Guarding & Lockout",+ description:+ "OSHA 1910.147 lockout and machine-guarding basics for machinists and setup techs.",+ status: "Active",+ frequency: "Once",+ type: "Mandatory",+ estimatedDuration: "35m",+ content: [+ "Never reach past a door interlock with the spindle turning. Chip clean-out happens with the machine in E-stop, not in feed hold.",+ "Lock out the main disconnect with your own lock before any work inside the enclosure, then try-start to prove zero energy."+ ],+ questions: [+ {+ type: "MultipleChoice",+ question:+ "What state must a VMC be in before you clear chips from the table by hand?",+ options: ["Feed hold", "Single block", "E-stop", "Spindle override 0%"],+ correct: "E-stop"+ },+ {+ type: "TrueFalse",+ question:+ "Gloves are recommended when working near a rotating lathe chuck.",+ answer: false+ },+ {+ type: "MultipleAnswers",+ question:+ "Which of these must be locked out before changing a lathe's coolant pump? Select all that apply.",+ options: [+ "Main electrical disconnect",+ "Hydraulic chuck pressure",+ "Shop air to the bar feeder",+ "The office lights",+ "The CMM"+ ],+ correct: [+ "Main electrical disconnect",+ "Hydraulic chuck pressure",+ "Shop air to the bar feeder"+ ]+ },+ {+ type: "MatchingPairs",+ question: "Match each guard to what it protects against.",+ pairs: [+ { left: "Door interlock", right: "Contact with the moving spindle" },+ { left: "Chip shield", right: "Flying chips and coolant" },+ { left: "Chuck guard", right: "Entanglement on the lathe" }+ ]+ },+ {+ type: "Numerical",+ question:+ "How many seconds must you wait after E-stop for a 12,000 rpm spindle to coast to a full stop before opening the door, per the posted placard?",+ answer: 10,+ tolerance: 2+ }+ ],+ assignment: { completedOffset: -20 }+ },+ {+ name: "First-Article Inspection with the CMM",+ description: "AS9102 first-article flow and CMM report sign-off.",+ status: "Active",+ frequency: "Annual",+ type: "Mandatory",+ estimatedDuration: "50m",+ content: [+ "Every new part number or revision gets a full first article before the lot runs. The CMM report is balloon-for-balloon against the drawing."+ ],+ questions: [+ {+ type: "MultipleChoice",+ question: "When is a new first-article inspection required?",+ options: [+ "Every shift",+ "On a new part number or drawing revision",+ "Only when the customer asks"+ ],+ correct: "On a new part number or drawing revision"+ },+ {+ type: "TrueFalse",+ question:+ "A first article may be signed off with one characteristic still unmeasured if it is non-critical.",+ answer: false+ }+ ],+ assignment: {}+ },+ {+ name: "Wire EDM Setup",+ description:+ "Operator qualification for threading, edge-finding and running the wire EDM.",+ status: "Draft",+ frequency: "Once",+ type: "Optional",+ estimatedDuration: "90m",+ content: [+ "Draft — wire threading, edge-find routine and skim-pass settings for hardened tool steel."+ ],+ questions: [+ {+ type: "Numerical",+ question:+ "What is the maximum dielectric conductivity for a finish skim pass, in µS/cm?",+ answer: 10,+ tolerance: 1+ }+ ]+ }+];++export const TIMECARDS: TimecardSpec[] = [+ { dayOffset: -5, clockIn: "05:58:00", clockOut: "14:32:00" },+ { dayOffset: -4, clockIn: "06:03:00", clockOut: "14:30:00" },+ { dayOffset: -3, clockIn: "06:01:00", clockOut: "14:35:00" },+ {+ dayOffset: -2,+ clockIn: "05:55:00",+ clockOut: "16:48:00",+ note: "Stayed to finish the Cedar Valley first article on the CMM."+ },+ { dayOffset: -1, clockIn: "06:00:00", clockOut: "10:31:00" },+ { dayOffset: -1, clockIn: "11:02:00", clockOut: "14:33:00" }+];++// Clocked in before the first timer on the floor started this morning.+export const OPEN_TIMECARD: OpenTimecardSpec = { clockIn: "05:57:00" };++// None on today itself, so the MES schedule opens on every work center instead of one station.+export const PEOPLE_ASSIGNMENTS: PeopleAssignmentSpec[] = [+ { dayOffset: -2, workCenter: "VMC Cell 1", shift: "First Shift" },+ { dayOffset: -1, workCenter: "Turning Cell", shift: "First Shift" },+ {+ dayOffset: 1,+ workCenter: "VMC Cell 2",+ shift: "First Shift",+ note: "Prove out the new manifold-block fixture."+ },+ { dayOffset: 2, workCenter: "VMC Cell 1", shift: "First Shift" },+ {+ dayOffset: 3,+ workCenter: "CMM Lab",+ shift: "First Shift",+ overtimeHours: 1.5,+ note: "First-article layout for Cedar Valley."+ },+ { dayOffset: 4, workCenter: "Turning Cell", shift: "First Shift" }+];++export const PEOPLE_ABSENCES: PeopleAbsenceSpec[] = [+ {+ dayOffset: 10,+ note: "GD&T refresher at the Rockford technical college."+ }+];++export const SUGGESTIONS: SuggestionSpec[] = [+ {+ suggestion:+ "Track coolant drums used per machine on the maintenance list so we can spot a leaking sump sooner.",+ emoji: "🛢️",+ path: "/x/resources/maintenance",+ tags: ["Maintenance"]+ },+ {+ suggestion:+ "Show each gauge's next calibration date right on the gauge list instead of inside the record.",+ emoji: "📏",+ path: "/x/quality/gauges"+ }+];++export const NOTES: NoteSpec[] = [+ {+ text: "Qualified on the new ballbar routine — can run the quarterly VMC checks without the OEM."+ },+ {+ text: "Covering first-article sign-off on second shift while the quality manager is at the Solstice audit."+ }+];++export const USER_ATTRIBUTE_CATEGORIES: UserAttributeCategorySpec[] = [+ {+ name: "Machinist Credentials",+ emoji: "📐",+ public: true,+ attributes: [+ {+ name: "NIMS Level II credential expires",+ dataType: "Date",+ valueOffset: 210+ },+ {+ name: "Primary machine family",+ dataType: "List",+ listOptions: ["VMC", "HMC", "Lathe", "Swiss", "EDM", "Grinder"],+ value: "VMC",+ canSelfManage: true+ },+ { name: "First-article approver", dataType: "User" },+ { name: "Cleared for CMM programming", dataType: "Yes/No", value: true }+ ]+ }+];++export const CUSTOM_FIELDS: CustomFieldSpec[] = [+ { table: "part", name: "Customer drawing number", dataType: "Text" },+ { table: "customer", name: "Account manager", dataType: "User" },+ { table: "job", name: "First article required", dataType: "Yes/No" }+];++export const SERIAL_SEQUENCES: SerialSequenceSpec[] = [+ // Continues the supplier's numbering already on the shelf (…-0106).+ { item: "CYL-HYD-40", prefix: "CYL40-SN-", size: 4, next: 106 },+ { item: "HMA-4000", prefix: "HMA4000-SN-", size: 4, next: 1 }+];++export const PRINT_JOBS: PrintJobSpec[] = [+ {+ source: { kind: "Receipt", receipt: "receipt:midway-restock" },+ item: "BSH-PTFE-2012",+ status: "completed",+ origin: "auto",+ at: { offset: -2, time: "15:02:00" },+ attempts: 1+ },+ {+ source: { kind: "Job", job: "done-housing" },+ item: "MCH-HSG-PUMP",+ status: "completed",+ origin: "manual",+ at: { offset: -3, time: "20:10:00" },+ attempts: 1+ },+ {+ source: { kind: "StorageUnit", shelf: "B1-L1" },+ status: "completed",+ origin: "manual",+ at: { offset: -7, time: "16:45:00" },+ attempts: 1+ },+ {+ source: { kind: "Job", job: "floor-flange" },+ item: "MCH-FLANGE-SS",+ status: "failed",+ origin: "auto",+ at: { offset: -1, time: "14:15:00" },+ attempts: 3,+ error: "Printer did not respond after 3 attempts (connection timed out)"+ },+ {+ source: { kind: "Job", job: "floor-flange" },+ item: "MCH-FLANGE-SS",+ status: "queued",+ origin: "reprint",+ at: { offset: 0, time: "06:10:00" },+ attempts: 0+ }+];++export const precisionOps: OpsData = {+ userAttributeCategories: USER_ATTRIBUTE_CATEGORIES,+ customFields: CUSTOM_FIELDS,+ serialSequences: SERIAL_SEQUENCES,+ printJobs: PRINT_JOBS,+ maintenanceSchedules: MAINTENANCE_SCHEDULES,+ maintenanceDispatches: MAINTENANCE_DISPATCHES,+ replacementParts: REPLACEMENT_PARTS,+ trainings: TRAININGS,+ timecards: TIMECARDS,+ openTimecard: OPEN_TIMECARD,+ peopleAssignments: PEOPLE_ASSIGNMENTS,+ peopleAbsences: PEOPLE_ABSENCES,+ suggestions: SUGGESTIONS,+ notes: NOTES+};diff --git a/packages/database/src/datasets/data/precision/planning.ts b/packages/database/src/datasets/data/precision/planning.tsindex 6614df64a0..8c13640466 100644--- a/packages/database/src/datasets/data/precision/planning.ts+++ b/packages/database/src/datasets/data/precision/planning.ts@@ -1,6 +1,7 @@import type {DemandOrderSpec,DemandProjectionSpec,+ HqPlanningSpec,PlanningData} from "../../types.ts";@@ -62,9 +63,15 @@ export const DEMAND_ORDER: DemandOrderSpec = {]};+export const HQ_PLANNING: HqPlanningSpec = {+ reorderItemIds: ["MCH-HSG-PUMP", "CYL-HYD-40"],+ demandProjections: [{ readableId: "MCH-HSG-PUMP", quantities: [2, 2, 3, 3] }]+};+export const precisionPlanning: PlanningData = {buyItemIds: BUY_ITEM_IDS,makeItemIds: MAKE_ITEM_IDS,demandProjections: DEMAND_PROJECTIONS,- demandOrder: DEMAND_ORDER+ demandOrder: DEMAND_ORDER,+ hq: HQ_PLANNING};diff --git a/packages/database/src/datasets/data/precision/production.ts b/packages/database/src/datasets/data/precision/production.tsindex 49b13f2791..de6a9cb0ce 100644--- a/packages/database/src/datasets/data/precision/production.ts+++ b/packages/database/src/datasets/data/precision/production.ts@@ -2,10 +2,10 @@ import type {GenealogyAssemblySpec,GenealogyInputSpec,JobSpec,+ PickingListSpec,ProductionData,ShiftEventSpec} from "../../types.ts";-import { precisionAssembly } from "./assembly.ts";export const JOBS: JobSpec[] = [{@@ -17,8 +17,33 @@ export const JOBS: JobSpec[] = [salesOrder: "so:cedarvalley",salesOrderLine: "soline:cedarvalley:hma",customer: "Cedar Valley Hydraulics",- dueDateOffset: -96,- releasedDateOffset: -160+ deadlineType: "Hard Deadline",+ dueDateOffset: 6,+ releasedDateOffset: -160,+ priority: 3,+ assignee: "self",+ // The floor's real mixed state: the manifold build is done, the hydro+ // proof test is running, final inspection waits on it.+ operationOverrides: [+ { order: 1, status: "Done" },+ { order: 2, status: "In Progress", assignee: "self" },+ { order: 3, status: "Waiting" }+ ],+ quantities: [+ { order: 1, type: "Production", quantity: 1 },+ { order: 1, type: "Scrap", quantity: 2, scrapReason: "Quality" },+ { order: 2, type: "Rework", quantity: 1 }+ ],+ operationNotes: [+ {+ order: 1,+ note: "Manifold torqued to spec on the base frame — witness marks on all M10s, torque wrench cal sticker photographed for the Cedar Valley book."+ },+ {+ order: 2,+ note: "Hydro proof at 1.5x rated running on unit 4. Held 10 minutes, no drop on the gauge yet — leaving it on the stand through lunch."+ }+ ]},{key: "ready",@@ -28,8 +53,10 @@ export const JOBS: JobSpec[] = [salesOrder: "so:dominion",salesOrderLine: "soline:dominion:hma",customer: "Dominion Ag Equipment",- dueDateOffset: -60,- releasedDateOffset: -92+ deadlineType: "ASAP",+ dueDateOffset: 14,+ releasedDateOffset: -4,+ priority: 10},{key: "planned",@@ -39,7 +66,9 @@ export const JOBS: JobSpec[] = [salesOrder: "so:planned",salesOrderLine: "soline:planned",customer: "Granite State Instruments",- dueDateOffset: -30+ deadlineType: "Soft Deadline",+ dueDateOffset: 18,+ priority: 12},{key: "draft",@@ -49,7 +78,7 @@ export const JOBS: JobSpec[] = [salesOrder: "so:draft",salesOrderLine: "soline:draft",customer: "Solstice Medical Devices",- dueDateOffset: -24+ deadlineType: "No Deadline"},{key: "paused",@@ -59,8 +88,9 @@ export const JOBS: JobSpec[] = [salesOrder: "so:paused",salesOrderLine: "soline:paused",customer: "Cedar Valley Hydraulics",- dueDateOffset: -70,- releasedDateOffset: -130+ dueDateOffset: 9,+ releasedDateOffset: -130,+ priority: 6},{key: "completed",@@ -98,6 +128,203 @@ export const JOBS: JobSpec[] = [customer: "Solstice Medical Devices",dueDateOffset: -140,releasedDateOffset: -172+ },++ {+ key: "floor-flange",+ item: "MCH-FLANGE-SS",+ status: "In Progress",+ quantity: 12,+ salesOrder: "so:floor-dominion",+ salesOrderLine: "soline:floor-dominion:flange",+ customer: "Dominion Ag Equipment",+ dueDateOffset: 2,+ releasedDateOffset: -6,+ priority: 2,+ assignee: "self",+ operationOverrides: [+ { order: 1, status: "Done" },+ {+ order: 2,+ status: "In Progress",+ assignee: "self",+ running: { type: "Machine", startTimeOfDay: "07:30:00" }+ },+ { order: 3, status: "Waiting" }+ ]+ },+ {+ key: "floor-spacer",+ item: "MCH-SPACER-KIT",+ status: "In Progress",+ quantity: 20,+ salesOrder: "so:floor-dominion",+ salesOrderLine: "soline:floor-dominion:spacer",+ customer: "Dominion Ag Equipment",+ dueDateOffset: 5,+ releasedDateOffset: -2,+ priority: 4,+ // Turned yesterday; the spacers now sit in the running deburr batch.+ operationOverrides: [{ order: 1, status: "Done", assignee: "self" }]+ },+ {+ key: "floor-shaft",+ item: "MCH-SHAFT-DR",+ status: "In Progress",+ quantity: 6,+ salesOrder: "so:floor-cedar",+ salesOrderLine: "soline:floor-cedar:shaft",+ customer: "Cedar Valley Hydraulics",+ deadlineType: "Soft Deadline",+ dueDateOffset: 12,+ releasedDateOffset: -9,+ priority: 8,+ assignee: "self",+ operationOverrides: [+ {+ order: 1,+ status: "In Progress",+ assignee: "self",+ running: { type: "Setup", startTimeOfDay: "06:45:00" }+ },+ { order: 2, status: "Waiting" }+ ]+ },+ {+ key: "floor-panel",+ item: "FAB-ENCL-PNL",+ status: "In Progress",+ quantity: 8,+ salesOrder: "so:floor-dominion",+ salesOrderLine: "soline:floor-dominion:panel",+ customer: "Dominion Ag Equipment",+ dueDateOffset: 7,+ releasedDateOffset: -5,+ priority: 5,+ operationOverrides: [+ {+ order: 1,+ status: "In Progress",+ running: { type: "Labor", startTimeOfDay: "08:15:00" }+ },+ { order: 2, status: "Waiting" }+ ]+ },+ {+ key: "floor-endcap",+ item: "MCH-END-CAP",+ status: "Ready",+ quantity: 10,+ salesOrder: "so:floor-cedar",+ salesOrderLine: "soline:floor-cedar:endcap",+ customer: "Cedar Valley Hydraulics",+ deadlineType: "ASAP",+ dueDateOffset: 0,+ releasedDateOffset: -1,+ priority: 1,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ {+ key: "floor-rod",+ item: "MCH-PISTON-ROD",+ status: "Ready",+ quantity: 4,+ salesOrder: "so:floor-dominion",+ salesOrderLine: "soline:floor-dominion:rod",+ customer: "Dominion Ag Equipment",+ dueDateOffset: 21,+ releasedDateOffset: -3,+ priority: 13+ },+ {+ key: "floor-valve",+ item: "ASM-VALVE-SUB",+ status: "Ready",+ quantity: 3,+ salesOrder: "so:floor-dominion",+ salesOrderLine: "soline:floor-dominion:valve",+ customer: "Dominion Ag Equipment",+ deadlineType: "Soft Deadline",+ dueDateOffset: 16,+ releasedDateOffset: -4,+ priority: 11,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ // Released with no deadline — Priorities' Unscheduled column.+ {+ key: "floor-manifold",+ item: "MCH-MANI-BLK",+ status: "Ready",+ quantity: 2,+ salesOrder: "so:floor-dominion",+ salesOrderLine: "soline:floor-dominion:manifold",+ customer: "Dominion Ag Equipment",+ deadlineType: "No Deadline",+ releasedDateOffset: -1,+ priority: 14+ },+ {+ key: "stock-endcap",+ item: "MCH-END-CAP",+ status: "In Progress",+ quantity: 24,+ dueDateOffset: 11,+ releasedDateOffset: -2,+ priority: 9,+ operationOverrides: [{ order: 1, status: "Done" }]+ },+ {+ key: "stock-housing",+ item: "MCH-HSG-PUMP",+ status: "Ready",+ quantity: 4,+ deadlineType: "Soft Deadline",+ dueDateOffset: 9,+ releasedDateOffset: -3,+ priority: 7,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ {+ key: "done-flange",+ item: "MCH-FLANGE-SS",+ status: "Completed",+ quantity: 8,+ quantityComplete: 8,+ salesOrder: "so:floor-cedar",+ salesOrderLine: "soline:floor-cedar:flange",+ customer: "Cedar Valley Hydraulics",+ dueDateOffset: -8,+ releasedDateOffset: -16,+ completedDateOffset: -11,+ loggedTime: { startOffset: -14, efficiency: 0.92 }+ },+ {+ key: "done-panel",+ item: "FAB-ENCL-PNL",+ status: "Completed",+ quantity: 6,+ quantityComplete: 6,+ salesOrder: "so:floor-cedar",+ salesOrderLine: "soline:floor-cedar:panel",+ customer: "Cedar Valley Hydraulics",+ dueDateOffset: -20,+ releasedDateOffset: -28,+ completedDateOffset: -24,+ loggedTime: { startOffset: -27, efficiency: 1.18 }+ },+ {+ key: "done-housing",+ item: "MCH-HSG-PUMP",+ status: "Completed",+ quantity: 2,+ quantityComplete: 2,+ salesOrder: "so:floor-cedar",+ salesOrderLine: "soline:floor-cedar:housing",+ customer: "Cedar Valley Hydraulics",+ dueDateOffset: -2,+ releasedDateOffset: -12,+ completedDateOffset: -4,+ loggedTime: { startOffset: -9, efficiency: 1.07 }}];@@ -189,12 +416,75 @@ export const GENEALOGY_ASSEMBLY: GenealogyAssemblySpec = {}};+export const PICKING_LISTS: PickingListSpec[] = [+ {+ key: "hma-kit-1",+ status: "Completed",+ job: "in-progress",+ dateOffset: -20,+ lines: [+ {+ item: "INS-HELI-M6",+ quantityRequired: 24,+ quantityPicked: 24,+ status: "Picked",+ fromShelf: "B1-L2"+ },+ {+ item: "SEAL-ORING-224",+ quantityRequired: 16,+ quantityPicked: 16,+ status: "Picked",+ fromShelf: "B2-L1"+ }+ ]+ },+ {+ key: "hma-kit-2",+ status: "In Progress",+ job: "in-progress",+ dateOffset: -2,+ lines: [+ {+ item: "BRG-NDL-HK1512",+ quantityRequired: 12,+ quantityPicked: 0,+ status: "Pending",+ fromShelf: "B1-L3"+ },+ {+ item: "BSH-BRZ-2012",+ quantityRequired: 12,+ quantityPicked: 0,+ status: "Short",+ fromShelf: "B2-L2"+ }+ ]+ }+];+export const precisionProduction: ProductionData = {- assembly: precisionAssembly,jobs: JOBS,shifts: SHIFTS,genealogyInputs: GENEALOGY_INPUTS,genealogyAssembly: GENEALOGY_ASSEMBLY,eventsJobKey: "in-progress",- genealogyJobKey: "in-progress"+ genealogyJobKey: "in-progress",+ // The hydro proof test (position 2) is the one overridden to In Progress.+ openEvent: { operationOrder: 2 },+ batch: {+ members: [+ { job: "floor-spacer", order: 2 },+ { job: "stock-endcap", order: 2 }+ ],+ running: { type: "Machine", startTimeOfDay: "07:20:00" }+ },+ rework: {+ quantity: 1,+ reason:+ "Manifold-to-housing joint seeped at 1.5x proof — send unit 4 back to the bench to reseat the O-rings and retorque the joint.",+ targetOperationOrder: 1,+ triggeredAtOperationOrder: 2+ },+ pickingLists: PICKING_LISTS};diff --git a/packages/database/src/datasets/data/precision/purchasing.ts b/packages/database/src/datasets/data/precision/purchasing.tsindex 8e24680010..df0603918f 100644--- a/packages/database/src/datasets/data/precision/purchasing.ts+++ b/packages/database/src/datasets/data/precision/purchasing.ts@@ -1,9 +1,12 @@import type {+ LifecycleRfqSpec,PurchaseOrderSpec,+ PurchaseReturnSpec,PurchasingData,RfqHeaderSpec,RfqLineSpec,- RfqQuoteSpec+ RfqQuoteSpec,+ StandaloneSupplierQuoteSpec} from "../../types.ts";// Every RFQ line and every supplier quote prices the same quantity breaks, so@@ -26,6 +29,7 @@ export const RFQ_LINES: RfqLineSpec[] = [export const RFQ_QUOTES: RfqQuoteSpec[] = [{key: "bluestem",+ assignee: "self",supplier: "Bluestem Alloys",supplierReference: "BSA-Q-8812",shippingCost: 320,@@ -110,6 +114,7 @@ export const RFQ_ORDER_QUANTITY = 1000;// 2 lines, finalized (Requested), fanned out to 3 suppliers.export const RFQ_HEADER: RfqHeaderSpec = {ref: "prfq:barstock",+ assignee: "self",status: "Requested",rfqDateOffset: -21,expirationOffset: 45,@@ -118,6 +123,42 @@ export const RFQ_HEADER: RfqHeaderSpec = {"Award on landed cost at 1,000 lb unless the mill lead time pushes past three weeks."};+export const LIFECYCLE_RFQS: LifecycleRfqSpec[] = [+ {+ ref: "prfq:fixture-hardware",+ status: "Draft",+ rfqDateOffset: -2,+ expirationOffset: 28,+ notes: "Dowels and die springs for the new fixture-plate program.",+ internalNotes: "Add a second distributor before sending.",+ quantities: [100, 250],+ lines: [+ {+ item: "HW-DOWEL-8",+ description: "8mm x 24 hardened dowel pin, m6 fit"+ },+ { item: "SPR-DIE-25", description: "25mm die spring, medium load" }+ ],+ suppliers: ["Fastline Industrial Supply", "Midway Bearing & Seal"]+ },+ {+ ref: "prfq:hyd-cylinder",+ status: "Closed",+ rfqDateOffset: -58,+ expirationOffset: -28,+ notes: "Hydraulic cylinders for the press-tooling build.",+ internalNotes: "Cancelled — customer dropped the press-tooling job.",+ quantities: [4, 10],+ lines: [+ {+ item: "CYL-HYD-40",+ description: "40mm bore x 200 stroke hydraulic cylinder"+ }+ ],+ suppliers: ["Midway Bearing & Seal", "Fastline Industrial Supply"]+ }+];+export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [{source: "direct",@@ -171,6 +212,7 @@ export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [source: "direct",log: "purchase order 3 — Draft (Rock River Metals)",ref: "po:rockriver",+ assignee: "self",supplier: "Rock River Metals",purchaseOrderType: "Purchase",status: "Draft",@@ -187,6 +229,428 @@ export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [orderDateOffset: -6,currencyCode: "USD",exchangeRate: 1+ },++ {+ source: "direct",+ log: "purchase order — Planned (Rock River frame tube for the base weldment)",+ supplier: "Rock River Metals",+ purchaseOrderType: "Purchase",+ status: "Planned",+ orderDateOffset: -1,+ lines: [+ { item: "MAT-CRS-TUBE", purchaseQuantity: 60, supplierUnitPrice: 2.15 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — To Review (Bluestem 4140 bar, mill certs pending)",+ assignee: "self",+ supplier: "Bluestem Alloys",+ purchaseOrderType: "Purchase",+ status: "To Review",+ orderDateOffset: -3,+ lines: [+ { item: "MAT-4140-BAR", purchaseQuantity: 200, supplierUnitPrice: 2.7 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — Needs Approval (Midway hydraulic cylinders over the buyer's limit)",+ ref: "po:needs-approval",+ supplier: "Midway Bearing & Seal",+ purchaseOrderType: "Purchase",+ status: "Needs Approval",+ orderDateOffset: -2,+ // Over the $5,000 approval tier.+ lines: [+ { item: "CYL-HYD-40", purchaseQuantity: 18, supplierUnitPrice: 289 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — Rejected (Precision Gauge CMM programming quote too high)",+ supplier: "Precision Gauge Services",+ purchaseOrderType: "Purchase",+ status: "Rejected",+ orderDateOffset: -13,+ lines: [+ { item: "SVC-CMM-PROG", purchaseQuantity: 1, supplierUnitPrice: 1450 }+ ]+ },++ {+ source: "direct",+ log: "purchase order — Completed, received in full and paid (Midway bearings)",+ ref: "po:midway-paid",+ supplier: "Midway Bearing & Seal",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -75,+ lines: [+ { item: "BRG-DBL-6205", purchaseQuantity: 4, supplierUnitPrice: 12.55 },+ { item: "BRG-NDL-HK1512", purchaseQuantity: 10, supplierUnitPrice: 6.8 }+ ],+ receipt: {+ ref: "receipt:midway-paid",+ status: "Posted",+ postedOffset: -68,+ lines: [+ {+ item: "BRG-DBL-6205",+ orderQuantity: 4,+ outstandingQuantity: 0,+ receivedQuantity: 4,+ unitPrice: 12.55,+ requiresBatchTracking: true,+ toShelf: "B1-L3",+ // Received -68 with the 365-day grease-fill shelf life → expires +297.+ lotNumber: "LOT-BRG-2607",+ lotExpiresOffset: 297+ },+ {+ item: "BRG-NDL-HK1512",+ orderQuantity: 10,+ outstandingQuantity: 0,+ receivedQuantity: 10,+ unitPrice: 6.8,+ toShelf: "B1-L3"+ }+ ]+ },+ invoice: {+ ref: "pinvoice:midway-paid",+ key: "paid",+ status: "Paid",+ currencyCode: "USD",+ subtotal: 118.2,+ totalAmount: 118.2,+ dateIssuedOffset: -62,+ dueDateOffset: -32,+ lines: [+ { item: "BRG-DBL-6205", quantity: 4, supplierUnitPrice: 12.55 },+ { item: "BRG-NDL-HK1512", quantity: 10, supplierUnitPrice: 6.8 }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Closed short after a partial receipt (Bluestem 316L plate)",+ ref: "po:bluestem-short",+ supplier: "Bluestem Alloys",+ purchaseOrderType: "Purchase",+ status: "Closed",+ orderDateOffset: -88,+ lines: [+ { item: "MAT-SS316-PLT", purchaseQuantity: 120, supplierUnitPrice: 6.25 }+ ],+ receipt: {+ ref: "receipt:bluestem-short",+ status: "Posted",+ postedOffset: -80,+ lines: [+ {+ item: "MAT-SS316-PLT",+ orderQuantity: 120,+ outstandingQuantity: 40,+ receivedQuantity: 80,+ unitPrice: 6.25,+ toShelf: "Bar-Stock"+ }+ ]+ },+ invoice: {+ ref: "pinvoice:bluestem-debit",+ key: "debit-note",+ status: "Debit Note Issued",+ currencyCode: "USD",+ subtotal: 500,+ totalAmount: 500,+ dateIssuedOffset: -72,+ lines: [{ item: "MAT-SS316-PLT", quantity: 80, supplierUnitPrice: 6.25 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — To Receive with a voided receipt (Fastline inserts)",+ supplier: "Fastline Industrial Supply",+ purchaseOrderType: "Purchase",+ status: "To Receive",+ orderDateOffset: -21,+ lines: [+ { item: "INS-HELI-M6", purchaseQuantity: 200, supplierUnitPrice: 0.68 }+ ],+ receipt: {+ ref: "receipt:voided-inserts",+ status: "Voided",+ lines: [+ {+ item: "INS-HELI-M6",+ orderQuantity: 200,+ outstandingQuantity: 200,+ receivedQuantity: 0,+ unitPrice: 0.68+ }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice open (Fastline cap screws)",+ supplier: "Fastline Industrial Supply",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -32,+ lines: [+ { item: "HW-SHCS-M10", purchaseQuantity: 300, supplierUnitPrice: 1.1 }+ ],+ invoice: {+ ref: "pinvoice:fastline-open",+ key: "open",+ status: "Open",+ currencyCode: "USD",+ subtotal: 330,+ totalAmount: 330,+ dateIssuedOffset: -8,+ dueDateOffset: 22,+ lines: [{ item: "HW-SHCS-M10", quantity: 300, supplierUnitPrice: 1.1 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice overdue (Rock River 5052 sheet)",+ supplier: "Rock River Metals",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -60,+ lines: [+ { item: "MAT-AL5052-SHT", purchaseQuantity: 150, supplierUnitPrice: 2.95 }+ ],+ invoice: {+ ref: "pinvoice:rockriver-overdue",+ key: "overdue",+ status: "Overdue",+ currencyCode: "USD",+ subtotal: 442.5,+ totalAmount: 442.5,+ dateIssuedOffset: -45,+ dueDateOffset: -15,+ lines: [+ { item: "MAT-AL5052-SHT", quantity: 150, supplierUnitPrice: 2.95 }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice partially paid (Midway O-rings)",+ supplier: "Midway Bearing & Seal",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -55,+ lines: [+ {+ item: "SEAL-ORING-224",+ purchaseQuantity: 1000,+ supplierUnitPrice: 0.35+ }+ ],+ invoice: {+ ref: "pinvoice:midway-partial",+ key: "partial",+ status: "Partially Paid",+ currencyCode: "USD",+ subtotal: 350,+ totalAmount: 350,+ dateIssuedOffset: -40,+ dueDateOffset: -10,+ lines: [+ { item: "SEAL-ORING-224", quantity: 1000, supplierUnitPrice: 0.35 }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Closed, invoice voided over a billing error (Fastline dowels)",+ supplier: "Fastline Industrial Supply",+ purchaseOrderType: "Purchase",+ status: "Closed",+ orderDateOffset: -66,+ lines: [+ { item: "HW-DOWEL-8", purchaseQuantity: 250, supplierUnitPrice: 0.95 }+ ],+ invoice: {+ ref: "pinvoice:fastline-voided",+ key: "voided",+ status: "Voided",+ currencyCode: "USD",+ subtotal: 237.5,+ totalAmount: 237.5,+ dateIssuedOffset: -58,+ lines: [{ item: "HW-DOWEL-8", quantity: 250, supplierUnitPrice: 0.95 }]+ }+ },++ // Mirrors the OSP orders the create function raises from a job's outside operations.+ {+ source: "direct",+ log: "purchase order — Outside Processing, induction harden at Forge",+ assignee: "self",+ supplier: "Forge Heat Treating",+ purchaseOrderType: "Outside Processing",+ status: "To Receive",+ orderDateOffset: -9,+ lines: [+ { item: "MCH-SHAFT-DR", purchaseQuantity: 12, supplierUnitPrice: 36 }+ ]+ },++ {+ source: "direct",+ log: "purchase order — EUR order, unpaid (Bavaria Werkzeugstahl 4140 bar)",+ ref: "po:bavaria-eur",+ supplier: "Bavaria Werkzeugstahl GmbH",+ purchaseOrderType: "Purchase",+ status: "To Invoice",+ orderDateOffset: -17,+ currencyCode: "EUR",+ exchangeRate: 0.92,+ lines: [+ { item: "MAT-4140-BAR", purchaseQuantity: 250, supplierUnitPrice: 2.45 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — To Invoice, bushings and replacement needle bearings received (Midway)",+ ref: "po:midway-restock",+ supplier: "Midway Bearing & Seal",+ purchaseOrderType: "Purchase",+ status: "To Invoice",+ orderDateOffset: -14,+ lines: [+ { item: "BSH-PTFE-2012", purchaseQuantity: 20, supplierUnitPrice: 4.6 },+ { item: "BRG-NDL-HK1512", purchaseQuantity: 10, supplierUnitPrice: 6.8 }+ ],+ receipt: {+ ref: "receipt:midway-restock",+ status: "Posted",+ postedOffset: -2,+ lines: [+ {+ item: "BSH-PTFE-2012",+ orderQuantity: 20,+ outstandingQuantity: 0,+ receivedQuantity: 20,+ unitPrice: 4.6,+ toShelf: "B1-L3"+ },+ {+ item: "BRG-NDL-HK1512",+ orderQuantity: 10,+ outstandingQuantity: 0,+ receivedQuantity: 10,+ unitPrice: 6.8,+ toShelf: "B1-L3"+ }+ ]+ }+ }+];++export const STANDALONE_SUPPLIER_QUOTES: StandaloneSupplierQuoteSpec[] = [+ {+ key: "fastline-hardware-annual",+ assignee: "self",+ supplier: "Fastline Industrial Supply",+ status: "Draft",+ supplierReference: "FL-2026-2210",+ quotedOffset: -4,+ expirationOffset: 55,+ lines: [+ {+ item: "HW-SHCS-M6",+ supplierPartId: "FL-SHCS-M6X20",+ prices: [+ { quantity: 2500, unitPrice: 0.4, leadTime: 10 },+ { quantity: 5000, unitPrice: 0.38, leadTime: 10 }+ ]+ }+ ]+ },+ {+ key: "bluestem-4140-lapsed",+ supplier: "Bluestem Alloys",+ status: "Expired",+ supplierReference: "BSA-Q-7741",+ quotedOffset: -200,+ expirationOffset: -25,+ lines: [+ {+ item: "MAT-4140-BAR",+ supplierPartId: "BSA-4140-250",+ prices: [{ quantity: 1000, unitPrice: 2.62, leadTime: 14 }]+ }+ ]+ },+ {+ key: "gauge-cmm-program",+ supplier: "Precision Gauge Services",+ status: "Declined",+ supplierReference: "PGS-2026-0330",+ quotedOffset: -35,+ expirationOffset: 15,+ lines: [+ {+ item: "SVC-CMM-PROG",+ supplierPartId: "PGS-CMM-DEV",+ prices: [{ quantity: 4, unitPrice: 1180, leadTime: 10 }]+ }+ ]+ }+];++// The completed return is dated after the posted cycle count so the count's+// snapshot stays the opening balance.+export const PURCHASE_RETURNS: PurchaseReturnSpec[] = [+ {+ key: "oring-cut-lips",+ credit: {+ status: "Draft",+ dateOffset: -4,+ lines: [{ line: 1, quantity: 30 }]+ },+ status: "Completed",+ supplier: "Midway Bearing & Seal",+ dateOffset: -6,+ lines: [+ {+ item: "SEAL-ORING-224",+ quantity: 30,+ unitPrice: 0.35,+ fromShelf: "B2-L1"+ }+ ]+ },+ {+ key: "insert-wrong-pitch",+ status: "To Ship",+ supplier: "Fastline Industrial Supply",+ dateOffset: -2,+ lines: [{ item: "INS-HELI-M6", quantity: 25, unitPrice: 0.68 }]+ },+ {+ key: "plate-laminations",+ status: "Draft",+ supplier: "Bluestem Alloys",+ dateOffset: 0,+ lines: [{ item: "MAT-SS316-PLT", quantity: 15, unitPrice: 6.2 }]+ },+ // Stays Draft while MRB decides; quality's ncr:needle-od links this line.+ {+ key: "needle-od-rtv",+ status: "Draft",+ supplier: "Midway Bearing & Seal",+ dateOffset: -3,+ lines: [{ item: "BRG-NDL-HK1512", quantity: 1, unitPrice: 6.8 }]}];@@ -197,5 +661,65 @@ export const precisionPurchasing: PurchasingData = {rfqWinningQuote: RFQ_WINNING_QUOTE,rfqOrderQuantity: RFQ_ORDER_QUANTITY,rfqHeader: RFQ_HEADER,- purchaseOrders: PURCHASE_ORDERS+ lifecycleRfqs: LIFECYCLE_RFQS,+ purchaseOrders: PURCHASE_ORDERS,+ standaloneSupplierQuotes: STANDALONE_SUPPLIER_QUOTES,+ purchaseReturns: PURCHASE_RETURNS,+ approvalRules: [+ { documentType: "purchaseOrder", lowerBoundAmount: 5000 },+ {+ documentType: "purchaseOrder",+ lowerBoundAmount: 25000,+ escalationDays: 3+ },+ { documentType: "supplier", lowerBoundAmount: 0 }+ ],+ approvalRequests: [+ { purchaseOrder: "po:needs-approval", requestedOffset: -1 },+ { supplier: "Prairie Anodizing", requestedOffset: -4 }+ ],+ supplierBankAccounts: [+ {+ supplier: "Midway Bearing & Seal",+ name: "Midway remittance",+ bankName: "Rock River Bank (demo)",+ accountHolderName: "Midway Bearing & Seal Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-4412-7735",+ bankCode: "DEMO-071100",+ isPrimary: true+ },+ {+ supplier: "Rock River Metals",+ name: "Rock River operating",+ bankName: "Stateline Savings (demo)",+ accountHolderName: "Rock River Metals LLC",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-5523-8846",+ isPrimary: true+ },+ {+ supplier: "Fastline Industrial Supply",+ name: "Fastline remittance",+ bankName: "Prairie Commerce (demo)",+ accountHolderName: "Fastline Industrial Supply Co.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-6634-9957",+ isPrimary: true+ },+ {+ supplier: "Bavaria Werkzeugstahl GmbH",+ name: "Bavaria EUR account",+ bankName: "Isar Handelsbank (demo)",+ accountHolderName: "Bavaria Werkzeugstahl GmbH",+ countryCode: "DE",+ currencyCode: "EUR",+ accountNumber: "DEMO-DE00-0000-5523",+ swiftBic: "DEMODEXX",+ isPrimary: true+ }+ ]};diff --git a/packages/database/src/datasets/data/precision/quality.ts b/packages/database/src/datasets/data/precision/quality.tsindex c0a9dca30e..aa4fdf6862 100644--- a/packages/database/src/datasets/data/precision/quality.ts+++ b/packages/database/src/datasets/data/precision/quality.ts@@ -1,8 +1,58 @@-import type { NonConformanceSpec, QualityData } from "../../types.ts";+import type {+ GaugeSpec,+ InspectionFeatureSpec,+ InspectionSpec,+ NonConformanceSpec,+ NonConformanceWorkflowSpec,+ QualityData,+ QualityDocumentSpec,+ RiskSpec+} from "../../types.ts";++// The new-issue form copies source, required actions and MRB from these templates onto the issue.+export const WORKFLOWS: NonConformanceWorkflowSpec[] = [+ {+ key: "supplier-escape",+ name: "Supplier Escape — Purchased Components",+ description:+ "A purchased component failed receiving inspection. Quarantine it, work the root cause with the supplier, and record their corrective action before MRB closes it out.",+ priority: "High",+ source: "External",+ requiredActions: [+ "Containment Action",+ "Root Cause Analysis",+ "Corrective Action"+ ],+ mrb: true+ },+ {+ key: "customer-complaint",+ name: "Customer Complaint — Delivered Parts",+ description:+ "A customer reported a defect on delivered parts. Acknowledge the same day, contain stock and WIP, and put the corrective action on record before closing.",+ priority: "Medium",+ source: "External",+ requiredActions: [+ "Customer Communication",+ "Containment Action",+ "Corrective Action"+ ]+ },+ {+ key: "incoming-hold",+ name: "Incoming Lot Hold",+ description:+ "An incoming lot is missing a certificate or failed a visual check. Hold it, then verify it before release.",+ priority: "Medium",+ source: "Internal",+ requiredActions: ["Containment Action", "Verification"]+ }+];export const NON_CONFORMANCES: NonConformanceSpec[] = [{ref: "ncr:anodize",+ assignee: "self",name: "Hard anodize thickness below print on manifold blocks",source: "Internal",status: "In Progress",@@ -18,15 +68,467 @@ export const NON_CONFORMANCES: NonConformanceSpec[] = [},{ref: "ncr:bore",+ items: [{ item: "MCH-HSG-PUMP", quantity: 3 }],name: "Pump housing bearing bore oversize at second operation",source: "Internal",status: "Registered",openDateOffset: -142,quantity: 3,priority: "Medium"+ },+ {+ ref: "ncr:needle-od",+ items: [+ {+ item: "BRG-NDL-HK1512",+ quantity: 1,+ disposition: "Return to Supplier"+ },+ { item: "MCH-HSG-PUMP", quantity: 4 }+ ],+ assignee: "self",+ workflow: "supplier-escape",+ purchaseReturnLine: {+ purchaseReturn: "needle-od-rtv",+ line: 1,+ quantity: 1+ },+ name: "HK1512 needle bearing cup OD oversize — press fit out of range",+ description:+ "Receiving inspection on the Midway needle-bearing delivery measured one HK1512 drawn cup at 21.016 mm OD against a 21.000 ±0.010 mm limit. An oversize cup over-closes the rollers when pressed into the pump housing bore. Bearing tagged and quarantined; MRB to decide return-to-vendor vs. 100% ring-gauge sort of the remaining stock.",+ type: "Supplier Issue",+ source: "External",+ status: "In Progress",+ openDateOffset: -66,+ dueDateOffset: 14,+ quantity: 1,+ priority: "Critical",+ supplier: "Midway Bearing & Seal",+ purchaseOrderLine: { po: "po:midway-paid", item: "BRG-NDL-HK1512" },+ inspection: "insp:needle",+ actionTasks: [+ {+ action: "Containment Action",+ status: "Completed",+ dueDateOffset: -64,+ completedOffset: -65+ },+ {+ action: "Root Cause Analysis",+ status: "In Progress",+ dueDateOffset: 7,+ processes: ["CNC Milling"]+ },+ { action: "Corrective Action", status: "Pending", dueDateOffset: 21 }+ ],+ mrb: {+ status: "In Progress",+ dueDateOffset: 10,+ reviewers: [+ { title: "Engineering", status: "Completed", completedOffset: -60 },+ { title: "Quality", status: "In Progress" }+ ]+ }+ },+ {+ ref: "ncr:clevis-pins",+ items: [{ item: "PIN-CLEVIS-12", quantity: 12, disposition: "Rework" }],+ workflow: "customer-complaint",+ salesReturnLine: { salesReturn: "clevis-pins", line: 1 },+ name: "Customer-reported clevis pins with scuffed zinc plating and cross-hole burrs",+ description:+ "Cedar Valley Hydraulics reported that several of the 12 PIN-CLEVIS-12 shipped on the partial delivery arrived with the zinc plating scuffed through at the shank and a burr left in the cotter-pin cross hole. Root cause: pins packed loose in one carton with no dividers. Now bagged in tens with a divider insert.",+ type: "Customer Complaint",+ source: "External",+ status: "Closed",+ openDateOffset: -8,+ dueDateOffset: 5,+ closeDateOffset: -2,+ quantity: 12,+ priority: "Low",+ customer: "Cedar Valley Hydraulics",+ salesOrderLine: "soline:cedarvalley-pins:pin",+ actionTasks: [+ {+ action: "Customer Communication",+ status: "Completed",+ dueDateOffset: -7,+ completedOffset: -8+ },+ {+ action: "Containment Action",+ status: "Completed",+ dueDateOffset: -6,+ completedOffset: -7+ },+ {+ action: "Corrective Action",+ status: "Completed",+ dueDateOffset: -3,+ completedOffset: -3+ }+ ]+ },+ {+ ref: "ncr:brg-lot",+ items: [{ item: "BRG-DBL-6205", quantity: 2 }],+ // Feeds the supplier-quality KPI's issue this month.+ supplier: "Midway Bearing & Seal",+ workflow: "incoming-hold",+ name: "6205-2RS bearing lot on hold — grease-fill certificate missing, seal lip rolled",+ description:+ "Lot LOT-BRG-2613 arrived without the vendor's grease-fill certificate, and one of the two bearings shows a rolled seal lip on visual. Lot placed on hold in B1-L3 pending the certificate and a spin-torque check.",+ type: "Material Issue",+ source: "Internal",+ status: "Registered",+ openDateOffset: -6,+ dueDateOffset: 20,+ quantity: 2,+ priority: "Medium",+ trackedEntity: "LOT-BRG-2613",+ actionTasks: [+ { action: "Containment Action", status: "Pending", dueDateOffset: 2 },+ { action: "Verification", status: "Pending", dueDateOffset: 14 }+ ]+ }+];++// Lot of 10 at AQL 1.0 / level II → code letter B, n = 3.+const NEEDLE_PLAN = {+ drawingNumber: "MW-HK1512 Rev B",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Drawn cup outside diameter (ring gauge, 3-point)",+ nominalValue: "21.000",+ tolerancePlus: "0.010",+ toleranceMinus: "0.010",+ unit: "mm"+ },+ {+ label: "2",+ description: "Cup width",+ nominalValue: "12.00",+ tolerancePlus: "0.00",+ toleranceMinus: "0.30",+ unit: "mm"+ }+ ] satisfies InspectionFeatureSpec[]+};++export const INSPECTIONS: InspectionSpec[] = [+ {+ source: "Receipt",+ ref: "insp:needle",+ receipt: "receipt:midway-paid",+ item: "BRG-NDL-HK1512",+ ...NEEDLE_PLAN,+ status: "Partial",+ dispositionOffset: -66,+ notes:+ "Samples 1 and 3 accepted. Sample 2 cup OD 21.016 mm, over the 21.010 mm upper limit — tagged, quarantined and raised to MRB.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 21.004 },+ { feature: "2", value: 11.88 }+ ]+ },+ {+ status: "Failed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 21.016 },+ { feature: "2", value: 11.91 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 20.997 },+ { feature: "2", value: 11.85 }+ ]+ }+ ]+ },+ // 20 pieces at AQL 1.0 → n = 5.+ {+ source: "Receipt",+ ref: "insp:ptfe-bushings",+ receipt: "receipt:midway-restock",+ item: "BSH-PTFE-2012",+ drawingNumber: "MW-PTFE-2012 Rev A",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Outside diameter",+ nominalValue: "23.000",+ tolerancePlus: "0.020",+ toleranceMinus: "0.020",+ unit: "mm"+ },+ {+ label: "2",+ description: "Overall length",+ nominalValue: "12.00",+ tolerancePlus: "0.25",+ toleranceMinus: "0.25",+ unit: "mm"+ }+ ],+ status: "Passed",+ dispositionOffset: -1,+ notes: "Five bushings measured; OD and length well inside print.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 23.004 },+ { feature: "2", value: 12.02 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 22.998 },+ { feature: "2", value: 11.97 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 23.009 },+ { feature: "2", value: 12.05 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 23.001 },+ { feature: "2", value: 11.99 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 22.995 },+ { feature: "2", value: 12.01 }+ ]+ }+ ]+ },+ {+ source: "Receipt",+ ref: "insp:needle-restock",+ receipt: "receipt:midway-restock",+ item: "BRG-NDL-HK1512",+ ...NEEDLE_PLAN,+ status: "Pending",+ samples: []+ },+ {+ source: "Job Operation",+ ref: "insp:shaft-runout",+ job: "floor-shaft",+ status: "Pending",+ samples: []+ }+];++export const QUALITY_DOCUMENTS: QualityDocumentSpec[] = [+ {+ name: "Machined Part First Article Inspection",+ version: 1,+ status: "Archived",+ description:+ "Superseded first-article procedure — traveler sign-off and visual check only.",+ steps: []+ },+ {+ name: "Machined Part First Article Inspection",+ version: 2,+ status: "Active",+ description:+ "First-article procedure for CNC-machined housings and blocks: material traceability, finish and the critical bearing bore before the lot is released.",+ steps: [+ {+ name: "Mill cert heat number matches the traveler and print revision",+ type: "Checkbox",+ required: true+ },+ {+ name: "Anodize finish on arrival from the finisher",+ type: "List",+ required: true,+ listValues: [+ "Type III hard coat — black",+ "Type II — clear",+ "Out of specification"+ ]+ },+ {+ name: "Bearing bore diameter",+ description:+ "Measured with the dial bore gauge zeroed on the 52 mm setting ring.",+ type: "Measurement",+ required: true,+ unitOfMeasureCode: "INCH",+ minValue: 2.0465,+ maxValue: 2.0475+ }+ ]+ },+ {+ name: "Heat Treat Hardness Verification (Rockwell C)",+ version: 0,+ status: "Draft",+ description:+ "Draft procedure for verifying 4140 drive shafts back from the heat treater — sample plan, test locations and HRC acceptance range.",+ steps: []+ }+];++export const GAUGES: GaugeSpec[] = [+ {+ key: "setting-ring",+ gaugeType: "Ring Gauge",+ description:+ "52 mm class XX master setting ring — zero reference for the bearing-bore gauges",+ modelNumber: "SR-52XX",+ serialNumber: "RG-21-3307",+ supplier: "Precision Gauge Services",+ role: "Master",+ status: "Active",+ calibrationIntervalInMonths: 12,+ acquiredOffset: -720,+ calibrations: [+ {+ dateOffset: -520,+ result: "Pass",+ temperature: 20,+ humidity: 44,+ measurementStandard: "ANSI/ASME B89.1.6, NIST-traceable"+ },+ {+ dateOffset: -160,+ result: "Pass",+ temperature: 20,+ humidity: 42,+ measurementStandard: "ANSI/ASME B89.1.6, NIST-traceable"+ }+ ]+ },+ {+ key: "bore-gauge",+ gaugeType: "Bore Gauge",+ description: "35–60 mm dial bore gauge — new unit for VMC Cell 2",+ modelNumber: "DBG-3560",+ serialNumber: "BG24-10582",+ role: "Standard",+ status: "Active",+ calibrationIntervalInMonths: 6,+ acquiredOffset: -12,+ calibrations: []+ },+ {+ key: "thread-plug",+ gaugeType: "Thread Gauge",+ description:+ "M6 x 1.0 6H GO/NO-GO thread plug — retired after failed calibration",+ modelNumber: "TPG-M6-6H",+ serialNumber: "TP19-00871",+ role: "Standard",+ status: "Inactive",+ calibrationIntervalInMonths: 6,+ acquiredOffset: -820,+ calibrations: [+ { dateOffset: -390, result: "Pass", temperature: 20, humidity: 45 },+ {+ dateOffset: -200,+ result: "Fail",+ requiresAction: true,+ requiresRepair: true,+ temperature: 20,+ humidity: 43,+ notes:+ "GO member pitch diameter worn 0.009 mm below its wear limit. Retired and replaced."+ }+ ]+ }+];++export const RISKS: RiskSpec[] = [+ {+ title: "Needle bearing dimensional escapes from Midway",+ description:+ "Midway is the only stocked source for HK1512 and just shipped an oversize cup — a second escape would stop pump housing assembly.",+ type: "Risk",+ status: "Mitigating",+ severity: 4,+ likelihood: 3,+ source: "Supplier",+ supplier: "Midway Bearing & Seal"+ },+ {+ title: "Passivation and cleanliness certs for medical 316L parts",+ description:+ "Solstice Medical asked for ASTM A967 passivation and cleanliness certificates on stainless parts — confirm Anvil Finishing can certify before the next order.",+ type: "Risk",+ status: "In Review",+ severity: 3,+ likelihood: 3,+ source: "Customer",+ customer: "Solstice Medical Devices"+ },+ {+ title: "Hard chrome plating on piston rods under regulatory pressure",+ description:+ "Hexavalent chrome rules may close our only plater for MCH-PISTON-ROD; nitride or HVOF alternatives need customer approval.",+ type: "Risk",+ status: "Open",+ severity: 4,+ likelihood: 2,+ source: "Item",+ item: "MCH-PISTON-ROD"+ },+ {+ title: "Hydro proof test bench availability for the HMA-4000 lot",+ description:+ "The shared hydrostatic test bench was booked for a rework loop during the HMA-4000 proof-test window; slot moved to second shift.",+ type: "Risk",+ status: "Closed",+ severity: 3,+ likelihood: 2,+ source: "Job",+ job: "job:in-progress"+ },+ {+ title: "Pallet pool on VMC Cell 2 for lights-out manifold blocks",+ description:+ "A 6-pallet pool would let manifold block roughing run unattended overnight — accepted into next year's capital plan.",+ type: "Opportunity",+ status: "Accepted",+ severity: 2,+ likelihood: 4,+ source: "General"}];export const precisionQuality: QualityData = {- nonConformances: NON_CONFORMANCES+ workflows: WORKFLOWS,+ nonConformances: NON_CONFORMANCES,+ inspections: INSPECTIONS,+ qualityDocuments: QUALITY_DOCUMENTS,+ gauges: GAUGES,+ risks: RISKS};diff --git a/packages/database/src/datasets/data/precision/sales.ts b/packages/database/src/datasets/data/precision/sales.tsindex 3c38323230..902fa7d442 100644--- a/packages/database/src/datasets/data/precision/sales.ts+++ b/packages/database/src/datasets/data/precision/sales.ts@@ -6,6 +6,7 @@ import type {PriceBreak,SalesData,SalesOpportunitySpec,+ SalesReturnSpec,SalesStatusOrderSpec,StaggeredDeliverySpec} from "../../types.ts";@@ -65,6 +66,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [},quote: {ref: "quote:cedarvalley",+ createdOffset: -190,status: "Ordered",externalNotes:"Quote for 6 hydraulic power unit manifold assemblies, prints supplied by the customer.",@@ -120,11 +122,18 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Granite State Instruments",quote: {ref: "quote:granite",+ createdOffset: -18,+ assignee: "self",status: "Sent",expirationOffset: GRANITE_QUOTE_EXPIRATION_OFFSET,lines: [{ref: "quoteline:granite:hma",+ configuration: {+ rated_pressure_psi: 3000,+ port_thread: "SAE ORB",+ hydro_test_cert: false+ },item: "HMA-4000",status: "Complete",sortOrder: 1,@@ -150,6 +159,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Solstice Medical Devices",rfq: {ref: "rfq:solstice",+ assignee: "self",status: "Ready for Quote",rfqDateOffset: -42,externalNotes:@@ -170,6 +180,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Dominion Ag Equipment",quote: {ref: "quote:dominion",+ createdOffset: -110,status: "Ordered",lines: [{@@ -195,6 +206,177 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [}]}+ },++ {+ log: "opportunity 5 — RFQ draft (Solstice, second flange variant)",+ ref: "opp:solstice-flange",+ customer: "Solstice Medical Devices",+ rfq: {+ ref: "rfq:solstice-flange",+ assignee: "self",+ status: "Draft",+ rfqDateOffset: -3,+ externalNotes:+ "Inquiry being logged — thin-profile flange variant for the next device rev.",+ lines: [+ {+ item: "MCH-FLANGE-SS",+ customerPartId: "SMD-FLG-0330",+ quantity: [100],+ order: 1+ }+ ]+ }+ },+ {+ log: "opportunity 6 — no-quoted RFQ, lost quote (Cedar Valley mirror rod)",+ ref: "opp:cedarvalley-rod",+ customer: "Cedar Valley Hydraulics",+ rfq: {+ ref: "rfq:cedarvalley-rod",+ status: "Closed",+ rfqDateOffset: -95,+ expirationOffset: -50,+ noQuoteReason: "Tolerance Beyond Capability",+ externalNotes:+ "Mirror-finish piston rod with sub-micron straightness call-out — beyond our grinding capability.",+ lines: [+ {+ item: "MCH-PISTON-ROD",+ customerPartId: "CVH-ROD-7710",+ quantity: [12],+ order: 1+ }+ ]+ },+ quote: {+ ref: "quote:cedarvalley-rod",+ createdOffset: -80,+ status: "Lost",+ externalNotes: "Declined to bid the mirror-finish rod line.",+ lines: [+ {+ ref: "quoteline:cedarvalley-rod:rod",+ item: "MCH-PISTON-ROD",+ status: "No Quote",+ sortOrder: 1,+ priceBreaks: []+ }+ ]+ }+ },+ {+ log: "opportunity 7 — quote draft (Dominion drive shaft)",+ ref: "opp:dominion-shaft",+ customer: "Dominion Ag Equipment",+ quote: {+ ref: "quote:dominion-shaft",+ createdOffset: -5,+ assignee: "self",+ status: "Draft",+ externalNotes:+ "Working draft — drive shaft pricing pending the heat-treat quote.",+ lines: [+ {+ ref: "quoteline:dominion-shaft:shaft",+ item: "MCH-SHAFT-DR",+ status: "Not Started",+ sortOrder: 1,+ priceBreaks: [{ quantity: 25, unitPrice: 305, leadTime: 30 }]+ }+ ]+ }+ },+ {+ log: "opportunity 8 — partial quote (Granite State retrofit kit)",+ ref: "opp:granite-retrofit",+ customer: "Granite State Instruments",+ quote: {+ ref: "quote:granite-retrofit",+ createdOffset: -11,+ status: "Partial",+ expirationOffset: 45,+ externalNotes:+ "End-cap line released to the customer; base frame still in engineering review.",+ lines: [+ {+ ref: "quoteline:granite-retrofit:cap",+ item: "MCH-END-CAP",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 40, unitPrice: 232, leadTime: 35 }]+ },+ {+ ref: "quoteline:granite-retrofit:base",+ item: "FAB-BASE-WLD",+ status: "In Progress",+ sortOrder: 2,+ priceBreaks: [{ quantity: 4, unitPrice: 1450, leadTime: 40 }]+ }+ ]+ }+ },+ {+ log: "opportunity 9 — cancelled quote (Solstice enclosure panels)",+ ref: "opp:solstice-encl",+ customer: "Solstice Medical Devices",+ quote: {+ ref: "quote:solstice-encl",+ createdOffset: -120,+ status: "Cancelled",+ externalNotes: "Program defunded before pricing was issued.",+ lines: [+ {+ ref: "quoteline:solstice-encl:pnl",+ item: "FAB-ENCL-PNL",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 4, unitPrice: 660, leadTime: 25 }]+ }+ ]+ }+ },+ {+ log: "opportunity 10 — expired quote (Dominion spacer sets)",+ ref: "opp:dominion-spacers",+ customer: "Dominion Ag Equipment",+ quote: {+ ref: "quote:dominion-spacers",+ createdOffset: -40,+ status: "Expired",+ expirationOffset: -14,+ externalNotes: "30-day pricing lapsed without a PO.",+ lines: [+ {+ ref: "quoteline:dominion-spacers:kit",+ item: "MCH-SPACER-KIT",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 20, unitPrice: 112, leadTime: 20 }]+ }+ ]+ }+ },+ {+ log: "sales order — Needs Approval (Cedar Valley die-spring spares)",+ ref: "opp:cedarvalley-springs",+ customer: "Cedar Valley Hydraulics",+ order: {+ ref: "so:cedarvalley-springs",+ assignee: "self",+ status: "Needs Approval",+ orderDateOffset: -2,+ lines: [+ {+ ref: "soline:cedarvalley-springs:spr",+ item: "SPR-DIE-25",+ saleQuantity: 40,+ unitPrice: 7,+ status: "Ordered"+ }+ ]+ }}];@@ -268,6 +450,7 @@ export const RELEASED_ORDERS: SalesOpportunitySpec[] = [customer: "Cedar Valley Hydraulics",order: {ref: "so:toshipinvoice",+ assignee: "self",status: "To Ship and Invoice",orderDateOffset: -8,lines: STAGGERED_DELIVERIES.map((delivery) => ({@@ -282,11 +465,547 @@ export const RELEASED_ORDERS: SalesOpportunitySpec[] = [sortOrder: delivery.sortOrder}))}+ },++ // Shipped items are well-stocked untracked buy parts (spares sold from the+ // shelf), so the ledger rows never overdraw a bin.+ {+ log: "sales order — To Invoice (Granite State, posted needle-bearing shipment)",+ ref: "opp:granite-bearings",+ customer: "Granite State Instruments",+ order: {+ ref: "so:granite-bearings",+ status: "To Invoice",+ orderDateOffset: -30,+ lines: [+ {+ ref: "soline:granite-bearings:brg",+ item: "BRG-NDL-HK1512",+ saleQuantity: 6,+ unitPrice: 10.5,+ status: "Completed"+ }+ ]+ },+ shipment: {+ ref: "shp:granite-bearings",+ status: "Posted",+ postedOffset: -18,+ lines: [+ {+ item: "BRG-NDL-HK1512",+ orderQuantity: 6,+ outstandingQuantity: 0,+ shippedQuantity: 6,+ unitPrice: 10.5,+ fromShelf: "B1-L3"+ }+ ]+ }+ },+ {+ log: "sales order — To Ship and Invoice (Cedar Valley, partial clevis-pin shipment)",+ ref: "opp:cedarvalley-pins",+ customer: "Cedar Valley Hydraulics",+ order: {+ ref: "so:cedarvalley-pins",+ status: "To Ship and Invoice",+ orderDateOffset: -21,+ lines: [+ {+ ref: "soline:cedarvalley-pins:pin",+ item: "PIN-CLEVIS-12",+ saleQuantity: 24,+ unitPrice: 4,+ status: "In Progress"+ }+ ]+ },+ shipment: {+ ref: "shp:cedarvalley-pins",+ status: "Posted",+ postedOffset: -9,+ lines: [+ {+ item: "PIN-CLEVIS-12",+ orderQuantity: 24,+ outstandingQuantity: 12,+ shippedQuantity: 12,+ unitPrice: 4,+ fromShelf: "B2-L2"+ }+ ]+ }+ },+ {+ log: "sales order — To Ship (Dominion, voided dowel-pin shipment)",+ ref: "opp:dominion-dowels",+ customer: "Dominion Ag Equipment",+ order: {+ ref: "so:dominion-dowels",+ status: "To Ship",+ orderDateOffset: -14,+ lines: [+ {+ ref: "soline:dominion-dowels:dwl",+ item: "HW-DOWEL-8",+ saleQuantity: 50,+ unitPrice: 1.6,+ status: "Ordered"+ }+ ]+ },+ shipment: {+ ref: "shp:dominion-dowels",+ status: "Voided",+ lines: [+ {+ item: "HW-DOWEL-8",+ orderQuantity: 50,+ outstandingQuantity: 50,+ shippedQuantity: 0,+ unitPrice: 1.6+ }+ ]+ }+ },++ // accounting.ts settles "paid" and "partial" by these sinv keys.+ {+ log: "sales invoice — Submitted (Solstice cap-screw spares)",+ ref: "opp:solstice-screws",+ customer: "Solstice Medical Devices",+ order: {+ ref: "so:solstice-screws",+ status: "Invoiced",+ orderDateOffset: -35,+ lines: [+ {+ ref: "soline:solstice-screws:hw",+ item: "HW-SHCS-M6",+ saleQuantity: 200,+ unitPrice: 0.75,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:solstice-screws",+ key: "submitted",+ status: "Submitted",+ subtotal: 150,+ totalAmount: 150,+ dateIssuedOffset: -20,+ dueDateOffset: 10,+ lines: [{ item: "HW-SHCS-M6", quantity: 200, unitPrice: 0.75 }]+ }+ },+ {+ log: "sales invoice — Overdue (Granite State 316L plate remnant)",+ ref: "opp:granite-plate",+ customer: "Granite State Instruments",+ order: {+ ref: "so:granite-plate",+ status: "Invoiced",+ orderDateOffset: -60,+ lines: [+ {+ ref: "soline:granite-plate:plt",+ item: "MAT-SS316-PLT",+ saleQuantity: 40,+ unitPrice: 9,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:granite-plate",+ key: "overdue",+ status: "Overdue",+ subtotal: 360,+ totalAmount: 360,+ dateIssuedOffset: -45,+ dueDateOffset: -15,+ lines: [{ item: "MAT-SS316-PLT", quantity: 40, unitPrice: 9 }]+ }+ },+ {+ log: "sales invoice — Paid (Cedar Valley threaded-insert lot)",+ ref: "opp:cedarvalley-inserts",+ customer: "Cedar Valley Hydraulics",+ order: {+ ref: "so:cedarvalley-inserts",+ status: "Closed",+ orderDateOffset: -90,+ lines: [+ {+ ref: "soline:cedarvalley-inserts:ins",+ item: "INS-HELI-M6",+ saleQuantity: 300,+ unitPrice: 1.15,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:cedarvalley-inserts",+ key: "paid",+ status: "Paid",+ subtotal: 345,+ totalAmount: 345,+ dateIssuedOffset: -75,+ dueDateOffset: -45,+ lines: [{ item: "INS-HELI-M6", quantity: 300, unitPrice: 1.15 }]+ }+ },+ {+ log: "sales invoice — Partially Paid (Dominion bronze bushings)",+ ref: "opp:dominion-bushings",+ customer: "Dominion Ag Equipment",+ order: {+ ref: "so:dominion-bushings",+ status: "Invoiced",+ orderDateOffset: -50,+ lines: [+ {+ ref: "soline:dominion-bushings:bsh",+ item: "BSH-BRZ-2012",+ saleQuantity: 24,+ unitPrice: 6.5,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:dominion-bushings",+ key: "partial",+ status: "Partially Paid",+ subtotal: 156,+ totalAmount: 156,+ dateIssuedOffset: -38,+ dueDateOffset: -8,+ lines: [{ item: "BSH-BRZ-2012", quantity: 24, unitPrice: 6.5 }]+ }+ },+ {+ log: "sales invoice — Voided (Solstice M10 cap screws, wrong bill-to)",+ ref: "opp:solstice-capscrews",+ customer: "Solstice Medical Devices",+ order: {+ ref: "so:solstice-capscrews",+ status: "To Invoice",+ orderDateOffset: -28,+ lines: [+ {+ ref: "soline:solstice-capscrews:hw",+ item: "HW-SHCS-M10",+ saleQuantity: 100,+ unitPrice: 1.85,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:solstice-capscrews",+ key: "voided",+ status: "Voided",+ subtotal: 185,+ totalAmount: 185,+ dateIssuedOffset: -25,+ lines: [{ item: "HW-SHCS-M10", quantity: 100, unitPrice: 1.85 }]+ }+ },+ {+ log: "sales invoice — Credit Note Issued (Granite State 5052 sheet remnant)",+ ref: "opp:granite-sheet",+ customer: "Granite State Instruments",+ order: {+ ref: "so:granite-sheet",+ status: "Closed",+ orderDateOffset: -70,+ lines: [+ {+ ref: "soline:granite-sheet:sht",+ item: "MAT-AL5052-SHT",+ saleQuantity: 50,+ unitPrice: 4.5,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:granite-sheet",+ key: "credit",+ status: "Credit Note Issued",+ subtotal: 225,+ totalAmount: 225,+ dateIssuedOffset: -55,+ dueDateOffset: -25,+ lines: [{ item: "MAT-AL5052-SHT", quantity: 50, unitPrice: 4.5 }]+ }+ },++ // Older overdue invoices, so receivables aging fills every bucket to 61–90.+ {+ log: "sales invoice — Overdue 31–60 days (Dominion helical inserts)",+ ref: "opp:dominion-inserts",+ customer: "Dominion Ag Equipment",+ order: {+ ref: "so:dominion-inserts",+ status: "Invoiced",+ orderDateOffset: -90,+ lines: [+ {+ ref: "soline:dominion-inserts:ins",+ item: "INS-HELI-M6",+ saleQuantity: 400,+ unitPrice: 1.15,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:dominion-inserts",+ status: "Overdue",+ subtotal: 460,+ totalAmount: 460,+ dateIssuedOffset: -75,+ dueDateOffset: -45,+ lines: [{ item: "INS-HELI-M6", quantity: 400, unitPrice: 1.15 }]+ }+ },+ {+ log: "sales invoice — Overdue 61–90 days (Solstice 316 plate)",+ ref: "opp:solstice-plate",+ customer: "Solstice Medical Devices",+ order: {+ ref: "so:solstice-plate",+ status: "Invoiced",+ orderDateOffset: -120,+ lines: [+ {+ ref: "soline:solstice-plate:plt",+ item: "MAT-SS316-PLT",+ saleQuantity: 30,+ unitPrice: 9,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:solstice-plate",+ status: "Overdue",+ subtotal: 270,+ totalAmount: 270,+ dateIssuedOffset: -105,+ dueDateOffset: -75,+ lines: [{ item: "MAT-SS316-PLT", quantity: 30, unitPrice: 9 }]+ }+ },++ // Each line has a job of its own in production.ts (open or just completed).+ {+ log: "sales order — In Progress (Cedar Valley machined spares, floor load)",+ ref: "opp:floor-cedar",+ customer: "Cedar Valley Hydraulics",+ order: {+ ref: "so:floor-cedar",+ status: "In Progress",+ orderDateOffset: -30,+ lines: [+ {+ ref: "soline:floor-cedar:flange",+ item: "MCH-FLANGE-SS",+ saleQuantity: 8,+ unitPrice: 185,+ status: "In Progress",+ promisedDateOffset: 3+ },+ {+ ref: "soline:floor-cedar:panel",+ item: "FAB-ENCL-PNL",+ saleQuantity: 6,+ unitPrice: 640,+ status: "In Progress",+ promisedDateOffset: 3+ },+ {+ ref: "soline:floor-cedar:housing",+ item: "MCH-HSG-PUMP",+ saleQuantity: 2,+ unitPrice: 1150,+ status: "In Progress",+ promisedDateOffset: 4+ },+ {+ ref: "soline:floor-cedar:endcap",+ item: "MCH-END-CAP",+ saleQuantity: 10,+ unitPrice: 240,+ status: "In Progress",+ promisedDateOffset: 2+ },+ {+ ref: "soline:floor-cedar:shaft",+ item: "MCH-SHAFT-DR",+ saleQuantity: 6,+ unitPrice: 320,+ status: "In Progress",+ promisedDateOffset: 15+ }+ ]+ }+ },+ {+ log: "sales order — In Progress (Dominion loader hydraulics kit, floor load)",+ ref: "opp:floor-dominion",+ customer: "Dominion Ag Equipment",+ order: {+ ref: "so:floor-dominion",+ assignee: "self",+ status: "In Progress",+ orderDateOffset: -15,+ lines: [+ {+ ref: "soline:floor-dominion:flange",+ item: "MCH-FLANGE-SS",+ saleQuantity: 12,+ unitPrice: 185,+ status: "In Progress",+ promisedDateOffset: 5+ },+ {+ ref: "soline:floor-dominion:spacer",+ item: "MCH-SPACER-KIT",+ saleQuantity: 20,+ unitPrice: 105,+ status: "In Progress",+ promisedDateOffset: 8+ },+ {+ ref: "soline:floor-dominion:panel",+ item: "FAB-ENCL-PNL",+ saleQuantity: 8,+ unitPrice: 640,+ status: "In Progress",+ promisedDateOffset: 10+ },+ {+ ref: "soline:floor-dominion:rod",+ item: "MCH-PISTON-ROD",+ saleQuantity: 4,+ unitPrice: 420,+ status: "In Progress",+ promisedDateOffset: 24+ },+ {+ ref: "soline:floor-dominion:valve",+ item: "ASM-VALVE-SUB",+ saleQuantity: 3,+ unitPrice: 890,+ status: "In Progress",+ promisedDateOffset: 19+ },+ {+ ref: "soline:floor-dominion:manifold",+ item: "MCH-MANI-BLK",+ saleQuantity: 2,+ unitPrice: 980,+ status: "In Progress",+ promisedDateOffset: 30+ }+ ]+ }+ }+];++// Quantities come from the posted shipments above; the Completed RMA books+// stock back into the bin it shipped from.+export const SALES_RETURNS: SalesReturnSpec[] = [+ {+ key: "needle-bearing",+ credit: {+ status: "Posted",+ dateOffset: -8,+ lines: [{ line: 1, quantity: 1 }]+ },+ status: "Completed",+ customer: "Granite State Instruments",+ returnReason: "Defective",+ dateOffset: -12,+ salesOrder: "so:granite-bearings",+ lines: [+ { item: "BRG-NDL-HK1512", quantity: 1, unitPrice: 10.5, toShelf: "B1-L3" }+ ]+ },+ {+ key: "clevis-pins",+ status: "To Receive",+ customer: "Cedar Valley Hydraulics",+ returnReason: "Damaged in Transit",+ dateOffset: -5,+ salesOrder: "so:cedarvalley-pins",+ lines: [{ item: "PIN-CLEVIS-12", quantity: 2, unitPrice: 4 }]+ },+ {+ key: "cap-screws",+ status: "Draft",+ customer: "Solstice Medical Devices",+ returnReason: "No Longer Needed",+ dateOffset: -1,+ salesOrder: "so:solstice-screws",+ lines: [{ item: "HW-SHCS-M6", quantity: 40, unitPrice: 0.75 }]}];export const precisionSales: SalesData = {opportunities: OPPORTUNITIES,statusOrders: STATUS_ORDERS,- releasedOrders: RELEASED_ORDERS+ releasedOrders: RELEASED_ORDERS,+ salesReturns: SALES_RETURNS,+ customerPortals: ["Cedar Valley Hydraulics", "Dominion Ag Equipment"],+ customerBankAccounts: [+ {+ customer: "Cedar Valley Hydraulics",+ name: "Cedar Valley remittance",+ bankName: "Prairie State Bank (demo)",+ accountHolderName: "Cedar Valley Hydraulics Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-5521-8804",+ bankCode: "DEMO-071000",+ isPrimary: true+ },+ {+ customer: "Granite State Instruments",+ name: "Granite State operating",+ bankName: "Merrimack Trust (demo)",+ accountHolderName: "Granite State Instruments LLC",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-6640-2217",+ isPrimary: true+ },+ {+ customer: "Dominion Ag Equipment",+ name: "Dominion payables",+ bankName: "Heartland Farm Credit (demo)",+ accountHolderName: "Dominion Ag Equipment Co.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-7719-3358",+ bankCode: "DEMO-051000",+ isPrimary: true+ },+ {+ customer: "Solstice Medical Devices",+ name: "Solstice treasury",+ bankName: "Twin Cities Commerce (demo)",+ accountHolderName: "Solstice Medical Devices Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-9034-4471",+ isPrimary: true+ }+ ]};diff --git a/packages/database/src/datasets/data/precision/workflows.ts b/packages/database/src/datasets/data/precision/workflows.tsindex d58433ba87..d2ecae0696 100644--- a/packages/database/src/datasets/data/precision/workflows.ts+++ b/packages/database/src/datasets/data/precision/workflows.ts@@ -1,5 +1,4 @@-import type { Edge, SeedWorkflow } from "../../tiers/workflow-definitions.ts";-import type { WorkflowData } from "../../types.ts";+import type { Edge, SeedWorkflow, WorkflowData } from "../../types.ts";// A factory, not a constant: every definition names ids that only exist once the seed has run.@@ -508,6 +507,38 @@ export function buildPrecisionWorkflows(refs: {];}+// The queued run was skipped at load while the workflow was briefly unpublished,+// so it has no steps.export const precisionWorkflows: WorkflowData = {- build: buildPrecisionWorkflows+ build: buildPrecisionWorkflows,+ runs: [+ {+ workflow: "Assign new sales orders",+ status: "Succeeded",+ triggerRef: "so:dominion-dowels",+ at: { offset: -14, time: "10:05:39" },+ steps: [{ nodeId: "action_assign", status: "Succeeded" }]+ },+ {+ workflow: "Assign new sales orders",+ status: "Failed",+ triggerRef: "so:solstice-capscrews",+ at: { offset: -28, time: "14:22:17" },+ steps: [+ {+ nodeId: "action_assign",+ status: "Failed",+ error: "The assignee you chose is not in this company."+ }+ ]+ },+ {+ workflow: "Assign new sales orders",+ status: "Skipped",+ triggerRef: "so:cedarvalley-pins",+ at: { offset: -21, time: "08:48:52" },+ statusReason: "This workflow was unpublished before the run started.",+ steps: []+ }+ ]};diff --git a/packages/database/src/datasets/data/robotics/accounting.ts b/packages/database/src/datasets/data/robotics/accounting.tsindex 762499879a..3cd55a583e 100644--- a/packages/database/src/datasets/data/robotics/accounting.ts+++ b/packages/database/src/datasets/data/robotics/accounting.ts@@ -1,7 +1,11 @@import type {AccountingData,FixedAssetSpec,- JournalEntrySpec+ JournalEntrySpec,+ MemoSpec,+ PaymentSpec,+ PeriodCloseTaskSpec,+ ProjectSpec} from "../../types.ts";export const FIXED_ASSETS: FixedAssetSpec[] = [@@ -76,6 +80,51 @@ export const FIXED_ASSETS: FixedAssetSpec[] = [acquisitionOffset: -2617,depreciationStartOffset: -2586,accumulatedDepreciation: 46000+ },+ {+ key: "wave-solder",+ className: "Machinery & Equipment",+ location: "Plant",+ name: "Legacy Wave-Solder Machine",+ description:+ "Through-hole wave solder line retired after the move to selective soldering; sold to a contract assembler",+ serialNumber: "WS-350-11820",+ status: "Disposed",+ depreciationMethod: "Straight Line",+ usefulLifeMonths: 80,+ residualValuePercent: 0,+ acquisitionCost: 64000,+ acquisitionOffset: -2200,+ depreciationStartOffset: -2150,+ // 64,000 / 80 = 800 per month x the 70 months depreciated before sale.+ // NBV 8,000 against 6,500 proceeds books a 1,500 loss.+ accumulatedDepreciation: 56000,+ disposal: { dateOffset: -25, method: "Sale", saleProceeds: 6500 }+ },+ {+ key: "servo-press",+ className: "Machinery & Equipment",+ location: "Plant",+ name: "Servo Press Station",+ description:+ "Gripper sub-assembly servo press, depreciated by press cycles",+ serialNumber: "SPS-40-55120",+ status: "Active",+ depreciationMethod: "Units of Production",+ usefulLifeMonths: 96,+ residualValuePercent: 0,+ acquisitionCost: 150000,+ acquisitionOffset: -120,+ depreciationStartOffset: -100,+ // 150,000 / 2,500,000 cycles = 0.06 per cycle. The first logged month (18,000)+ // was booked on registration; the run's month (22,500) is the charge.+ assetLifetimeUsage: 2500000,+ accumulatedDepreciation: 1080,+ usageLogs: [+ { monthsBack: 2, unitsProduced: 18000 },+ { monthsBack: 1, unitsProduced: 22500 }+ ],+ depreciationCharge: 1350}];@@ -105,10 +154,321 @@ export const JOURNAL_ENTRIES: JournalEntrySpec[] = [journalLineReference: "JE-SEED-001"}]+ },+ {+ ref: "journal:payroll-accrual",+ journalEntryId: "JE-SEED-002",+ description: "Payroll accrual — controls engineering, final week",+ status: "Posted",+ postingOffset: -12,+ lines: [+ {+ account: "6060",+ description: "Accrued controls engineering wages",+ amount: 36200,+ quantity: 1,+ journalLineReference: "JE-SEED-002-1",+ dimensions: [+ { dimension: "Project", value: "lakeshore-cell" },+ { dimension: "Product Line", value: "Collaborative Arms" }+ ]+ },+ {+ account: "2150",+ description: "Accrued controls engineering wages",+ amount: 36200,+ quantity: 1,+ journalLineReference: "JE-SEED-002-2"+ }+ ]+ },+ {+ ref: "journal:amortization",+ journalEntryId: "JE-SEED-003",+ description: "Monthly amortization — motion-control firmware license",+ status: "Posted",+ postingOffset: -23,+ lines: [+ {+ account: "6310",+ description: "Motion-control firmware license amortization",+ amount: 850,+ quantity: 1,+ journalLineReference: "JE-SEED-003"+ },+ {+ // A credit on the contra-asset: negative on a debit-normal class.+ account: "1420",+ description: "Motion-control firmware license amortization",+ amount: -850,+ quantity: 1,+ journalLineReference: "JE-SEED-003"+ }+ ]+ },+ {+ ref: "journal:tradeshow-accrual",+ journalEntryId: "JE-SEED-004",+ description: "Accrued trade-show booth — booked twice",+ status: "Reversed",+ postingOffset: -40,+ lines: [+ {+ account: "6030",+ description: "Automation expo booth",+ amount: 7400,+ quantity: 1,+ journalLineReference: "JE-SEED-004"+ },+ {+ account: "2140",+ description: "Automation expo booth",+ amount: 7400,+ quantity: 1,+ journalLineReference: "JE-SEED-004"+ }+ ],+ reversal: {+ ref: "journal:tradeshow-accrual-reversal",+ journalEntryId: "JE-SEED-005",+ postingOffset: -33+ }+ },+ {+ ref: "journal:opening-balance",+ journalEntryId: "JE-SEED-006",+ description: "Opening balances — cutover from the legacy ledger",+ status: "Posted",+ sourceType: "Opening Balance",+ postingOffset: -242,+ lines: [+ {+ account: "1010",+ description: "Operating cash",+ amount: 850000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-1"+ },+ {+ account: "1210",+ description: "Raw materials on hand",+ amount: 210000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-2"+ },+ {+ account: "1220",+ description: "Finished goods on hand",+ amount: 160000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-3"+ },+ {+ account: "1350",+ description: "Machinery & equipment at cost",+ amount: 940000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-4"+ },+ {+ account: "1330",+ description: "Accumulated depreciation to date",+ amount: -230000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-5"+ },+ {+ account: "2410",+ description: "Equipment term loan",+ amount: 600000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-6"+ },+ {+ account: "3010",+ description: "Paid-in capital",+ amount: 750000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-7"+ },+ {+ account: "3100",+ description: "Retained earnings brought forward",+ amount: 580000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-8"+ }+ ]+ }+];++// Credit/Debit Note Issued invoices settle by their memos as zero-cash credit+// applications, the way applyCreditsToInvoices records them.+export const PAYMENTS: PaymentSpec[] = [+ {+ key: "lakeshore-ach",+ type: "Receipt",+ customer: "Lakeshore Automotive",+ dateOffset: -46,+ amount: 700,+ reference: "ACH 5530-1187",+ applies: [{ invoiceKey: "paid", amount: 700 }]+ },+ {+ key: "alpine-wire",+ type: "Receipt",+ customer: "Alpine Research Institute",+ dateOffset: -15,+ amount: 2040,+ reference: "WIRE 40917 — grant drawdown",+ applies: [{ invoiceKey: "partial", amount: 2040 }]+ },+ {+ key: "cascade-credit",+ type: "Receipt",+ customer: "Cascade Integration Group",+ dateOffset: -49,+ amount: 0,+ reference: "Credit application",+ applies: [],+ credits: [{ memoKey: "cascade-jaws", invoiceKey: "credit", amount: 600 }]+ },+ {+ key: "northgate-ach",+ type: "Disbursement",+ supplier: "Northgate Electronics",+ dateOffset: -34,+ amount: 1858,+ reference: "ACH 7712-0093",+ applies: [{ invoiceKey: "paid", amount: 1858 }]+ },+ {+ key: "kestrel-check",+ type: "Disbursement",+ supplier: "Kestrel Motion",+ dateOffset: -11,+ amount: 2300,+ reference: "CHK 20318",+ applies: [{ invoiceKey: "partial", amount: 2300 }]+ },+ {+ key: "torqline-debit",+ type: "Disbursement",+ supplier: "Torqline Gearing",+ dateOffset: -65,+ amount: 0,+ reference: "Debit application",+ applies: [],+ credits: [+ { memoKey: "torqline-gears", invoiceKey: "debit-note", amount: 2300 }+ ]+ },+ {+ key: "draft-receipt",+ type: "Receipt",+ status: "Draft",+ customer: "Cascade Integration Group",+ dateOffset: -1,+ amount: 465,+ reference: "ACH advice 2217 — servo motor",+ applies: []+ },+ {+ key: "draft-disbursement",+ type: "Disbursement",+ status: "Draft",+ supplier: "Ironbark Metals",+ dateOffset: 0,+ amount: 195,+ reference: "ACH batch 0930 — billet",+ applies: []+ }+];++export const MEMOS: MemoSpec[] = [+ {+ key: "cascade-jaws",+ direction: "Credit",+ customer: "Cascade Integration Group",+ invoiceKey: "credit",+ dateOffset: -52,+ amount: 600,+ notes:+ "Full credit — gripper jaw sets returned with out-of-tolerance finger pitch"+ },+ {+ key: "torqline-gears",+ direction: "Debit",+ supplier: "Torqline Gearing",+ invoiceKey: "debit-note",+ dateOffset: -70,+ amount: 2300,+ notes:+ "Both received gear sets failed the outgoing backlash audit — billing debited"+ }+];++export const PROJECTS: ProjectSpec[] = [+ {+ key: "lakeshore-cell",+ name: "Lakeshore Weld Cell Retrofit",+ description:+ "Six-axis weld cell retrofit for Lakeshore Automotive's body shop",+ purchaseInvoiceLine: { invoiceKey: "paid", item: "ENC-ABS-19" }+ },+ {+ key: "cobot-gen2",+ name: "Cobot Arm Gen-2 Development",+ description:+ "Next-generation collaborative arm with integrated torque sensing"+ }+];++export const CLOSE_TASKS: PeriodCloseTaskSpec[] = [+ { definition: "Post pending operational documents", status: "Done" },+ {+ definition: "Review negative on-hand inventory",+ status: "Skipped",+ skippedReason: "No negative bins after the quarter-end physical count"+ },+ {+ definition: "Review financial statements",+ status: "Open",+ notes: "CFO to review the Lakeshore retrofit margin"}];export const roboticsAccounting: AccountingData = {fixedAssets: FIXED_ASSETS,- journalEntries: JOURNAL_ENTRIES+ journalEntries: JOURNAL_ENTRIES,+ payments: PAYMENTS,+ memos: MEMOS,+ projects: PROJECTS,+ customDimension: {+ name: "Product Line",+ values: ["Collaborative Arms", "Mobile Platforms"]+ },+ closeTasks: CLOSE_TASKS,+ // EUR per 1 USD (foreign units per base unit), the same direction as the EUR purchase order's 0.92 snapshot.+ exchangeRateOverrides: [{ currencyCode: "EUR", rate: 0.9215 }],+ billingAddresses: {+ receivable: {+ addressLine1: "2200 Technology Drive",+ city: "Pittsburgh",+ state: "PA",+ postalCode: "15219",+ countryCode: "US",+ phone: "+1-412-555-0184",+ email: "[email protected]"+ },+ payable: {+ addressLine1: "2200 Technology Drive",+ city: "Pittsburgh",+ state: "PA",+ postalCode: "15219",+ countryCode: "US",+ phone: "+1-412-555-0185",+ email: "[email protected]"+ }+ }};diff --git a/packages/database/src/datasets/data/robotics/assembly.ts b/packages/database/src/datasets/data/robotics/assembly.tsindex 41ba5dc522..44c6a92081 100644--- a/packages/database/src/datasets/data/robotics/assembly.ts+++ b/packages/database/src/datasets/data/robotics/assembly.ts@@ -8,12 +8,16 @@ export const roboticsAssembly: AssemblySpec = {name: "Koch Robot Arm — Final Assembly",item: "ROB-2000",componentCount: 163,+ // The Assembly operation of the ROB-2000 method.+ operation: 1,steps: [{title: "Bolt the base to the work plate",instruction:"Fix the base down and check it sits flat — rock it by hand at all four corners. Every joint above this one inherits whatever tilt is left here, and it cannot be dialled out later in software.",- componentNodeIds: ["cf90798128911226"]+ componentNodeIds: ["cf90798128911226"],+ materials: [{ item: "ARM-BASE-001", quantity: 1 }],+ tools: [{ item: "TL-TORQUE-M1", quantity: 1 }]},{title: "Fit the two XL-430 shoulder servos",@@ -31,7 +35,8 @@ export const roboticsAssembly: AssemblySpec = {title: "Join the upper arm link",instruction:"Fit the XL430-to-XL330 link, feeding the servo cable through the channel as you close it rather than after. A cable pulled through a closed link chafes at the horn and shorts the bus.",- componentNodeIds: ["fdd2780db5fa1b6c"]+ componentNodeIds: ["fdd2780db5fa1b6c"],+ materials: [{ item: "ARM-LINK-001", quantity: 1 }]},{title: "Fit the three XL-330 arm servos",@@ -47,7 +52,8 @@ export const roboticsAssembly: AssemblySpec = {title: "Fit the wrist rotation link",instruction:"Seat the rotation link and leave a service loop in the cable at the joint. Rotate the wrist lock to lock and watch the loop — it should take up slack, never go taut.",- componentNodeIds: ["120fdac57f58744e"]+ componentNodeIds: ["120fdac57f58744e"],+ materials: [{ item: "ARM-WRIST-001", quantity: 1 }]},{title: "Fit the forearm straight link",@@ -59,7 +65,26 @@ export const roboticsAssembly: AssemblySpec = {title: "Fit the gripper and check jaw travel",instruction:"Mount the gripper last. Drive the jaws fully open and fully closed and confirm they meet flat with no gap at the tips. Record the closed position — it is the zero the pick routine is taught against.",- componentNodeIds: ["ad6addc72d92757d"]+ componentNodeIds: ["ad6addc72d92757d"],+ materials: [{ item: "GRP-2F-80", quantity: 1 }],+ tools: [{ item: "TL-BACKLASH-J1", quantity: 1 }]+ }+ ],+ componentMappings: [+ // model part "base"+ {+ geometryHash: "13562648413b92f63ad77c04833a3a757353ddef",+ item: "ARM-BASE-001"+ },+ // model part "shoulder rotation"+ {+ geometryHash: "10c9c4af8e4ca9b6d41e06869b58d452d3e959f6",+ item: "ARM-LINK-001"+ },+ // model part "gripper moving side"+ {+ geometryHash: "a1dc775aa04c0362311a3e2ecd1c67ae859ff91d",+ item: "GRP-2F-80"}]};diff --git a/packages/database/src/datasets/data/robotics/change-orders.ts b/packages/database/src/datasets/data/robotics/change-orders.tsindex 33636b7168..ed8b45bb9c 100644--- a/packages/database/src/datasets/data/robotics/change-orders.ts+++ b/packages/database/src/datasets/data/robotics/change-orders.ts@@ -64,6 +64,73 @@ export const CHANGE_ORDERS: ChangeOrderSpec[] = [sortOrder: 1}]+ },+ // Lifecycle-only notices: no affected items yet (every change type spins a+ // method draft), so they exercise the stage flow + action tasks alone.+ {+ ref: "co:start",+ name: "Add a strain-relief clip at the J4 harness exit",+ type: "Engineering",+ changeOrderType: "Design Improvement",+ status: "Start",+ priority: "Medium",+ openDateOffset: -9,+ dueDateOffset: 30,+ reasonForChange:+ "Life testing showed the arm harness flexing past its minimum bend radius where it exits the J4 housing.",+ affectedItems: [],+ actionTasks: [+ { action: "Engineering Review", status: "In Progress", dueDateOffset: 5 },+ { action: "Update Drawings / CAD", status: "Pending", dueDateOffset: 20 }+ ]+ },+ {+ ref: "co:eng-complete",+ name: "Add a lost-motion bench test to the harmonic gear set receiving plan",+ type: "Manufacturing",+ changeOrderType: "Quality / Reliability Improvement",+ status: "Engineering Complete",+ priority: "High",+ openDateOffset: -70,+ dueDateOffset: 14,+ reasonForChange:+ "The Torqline gear-set escape showed certificate review alone cannot catch lost motion over the 1.0 arc-min limit.",+ nonConformance: "ncr:gear-lost-motion",+ affectedItems: [],+ actionTasks: [+ {+ action: "Quality Review",+ status: "Completed",+ dueDateOffset: -45,+ completedOffset: -48+ },+ {+ action: "Notify Affected Parties",+ status: "In Progress",+ dueDateOffset: 7+ }+ ]+ },+ {+ ref: "co:cancelled",+ name: "Update the servo drive wiring diagram for a revised STO terminal layout",+ type: "Documentation",+ changeOrderType: "Documentation Error / Correction",+ status: "Cancelled",+ priority: "Low",+ openDateOffset: -120,+ reasonForChange:+ "Kestrel proposed moving the safe-torque-off terminals on the DRV-SRV-400; they later withdrew it and kept the existing pinout.",+ affectedItems: [],+ actionTasks: [+ {+ action: "Cost Impact Review",+ status: "Completed",+ dueDateOffset: -110,+ completedOffset: -112+ },+ { action: "Update Drawings / CAD", status: "Skipped" }+ ]}];diff --git a/packages/database/src/datasets/data/robotics/foundation.ts b/packages/database/src/datasets/data/robotics/foundation.tsindex a074d434ab..5eec93ecba 100644--- a/packages/database/src/datasets/data/robotics/foundation.ts+++ b/packages/database/src/datasets/data/robotics/foundation.ts@@ -1,13 +1,19 @@import type {ContractorAgencySpec,+ EmployeeJobSpec,FoundationData,+ HolidaySpec,+ MaterialTaxonomySpec,+ PartnerSpec,PlantSpec,PrinterRouteSpec,ProcedureSpec,ProcedureStepSpec,ShelfSpec,ShiftSpec,- WarehouseSpec+ TagSpec,+ WarehouseSpec,+ WorkCenterSpec} from "../../types.ts";// ---------------------------------------------------------------------------@@ -116,6 +122,26 @@ export const WORK_CENTER_PROCESS_LINKS: Array<[string, string]> = [["Inspection Bench", "Burn-In Test"]];+export const WORK_CENTER_SHIFTS: Array<[string, string]> = [+ ["CNC Mill Cell", "First Shift"],+ ["Gearbox Bench", "First Shift"],+ ["SMT Line", "First Shift"],+ ["SMT Line", "Second Shift"],+ ["Harness Bench", "First Shift"],+ ["Integration Cell 1", "First Shift"],+ ["Integration Cell 1", "Weekend Shift"],+ ["Burn-In Rack", "First Shift"],+ ["Burn-In Rack", "Second Shift"],+ ["Inspection Bench", "First Shift"]+];++export const EMPLOYEE_JOB: EmployeeJobSpec = {+ title: "Cell Lead",+ department: "Assembly & Integration",+ shift: "First Shift",+ startDateOffset: -910+};+export const PLANT: PlantSpec = {name: "Robotics Assembly Plant",addressLine1: "2200 Technology Drive",@@ -323,6 +349,37 @@ export const SUPPLIERS = [type: "Services",phone: "+1-919-555-1100",website: "https://vertexcal.com"+ },+ // Status showcases + the EUR vendor. None of these may be referenced by+ // purchasing data — they exist so every supplier status renders somewhere.+ {+ name: "Allegheny Gearworks",+ type: "Motion Control",+ phone: "+1-412-555-1200",+ website: "https://alleghenygear.com",+ status: "Inactive" as const+ },+ {+ name: "Voltaic Drive Systems",+ type: "Electronics",+ phone: "+1-614-555-1300",+ website: "https://voltaicdrives.com",+ status: "Pending" as const+ },+ {+ name: "Discount Servo Supply",+ type: "Motion Control",+ phone: "+1-216-555-1400",+ website: "https://discountservo.com",+ status: "Rejected" as const+ },+ {+ name: "Schwarzwald Antriebstechnik GmbH",+ type: "Motion Control",+ phone: "+49-761-555-1500",+ website: "https://schwarzwald-antrieb.de",+ status: "Active" as const,+ currencyCode: "EUR"}];@@ -375,6 +432,34 @@ export const SUPPLIER_CONTACTS = [lastName: "Halvorsen",email: "[email protected]",title: "Service Coordinator"+ },+ {+ supplier: "Allegheny Gearworks",+ firstName: "Stan",+ lastName: "Kubiak",+ email: "[email protected]",+ title: "Sales Manager"+ },+ {+ supplier: "Voltaic Drive Systems",+ firstName: "Renee",+ lastName: "Castillo",+ email: "[email protected]",+ title: "Business Development"+ },+ {+ supplier: "Discount Servo Supply",+ firstName: "Terry",+ lastName: "Mullins",+ email: "[email protected]",+ title: "Account Executive"+ },+ {+ supplier: "Schwarzwald Antriebstechnik GmbH",+ firstName: "Jürgen",+ lastName: "Baumann",+ email: "[email protected]",+ title: "Export Sales"}];@@ -389,6 +474,27 @@ export const SUPPLIER_PROCESSES = [{ supplier: "Kappa Contract Machining", process: "Outside Processing" }];+export const PARTNERS: PartnerSpec[] = [+ {+ supplier: "Kappa Contract Machining",+ ability: "CNC Machining",+ hoursPerWeek: 40+ },+ {+ supplier: "Vertex Calibration Services",+ ability: "Inspection",+ hoursPerWeek: 16+ }+];++export const HQ_WORK_CENTER: WorkCenterSpec = {+ name: "Customer Demo Cell",+ dept: "Engineering",+ ability: "Robot Programming",+ laborRate: 85,+ machineRate: 40+};+export const CONTRACTORS = [{firstName: "Victor",@@ -449,10 +555,15 @@ export const PROCEDURES: ProcedureSpec[] = [process: "Gearbox Assembly",description:"Assembly and torque procedure for the J1 base and column of the Vertex 10 arm.",+ parameters: [+ { key: "J1 bolt torque", value: "45 N·m (M8 A2-70)" },+ { key: "Gearbox grease fill", value: "12 g EP-2 per joint" },+ { key: "Thread locker", value: "Loctite 243 on base bolts" }+ ],versions: [{version: 1,- status: "Draft",+ status: "Archived",steps: [{name: "Verify base kit against the pick list",@@ -471,7 +582,7 @@ export const PROCEDURES: ProcedureSpec[] = [}]},- { version: 2, status: "Draft", steps: ARM_BASE_STEPS_V2 }+ { version: 2, status: "Active", steps: ARM_BASE_STEPS_V2 }]},{@@ -482,7 +593,7 @@ export const PROCEDURES: ProcedureSpec[] = [versions: [{version: 1,- status: "Draft",+ status: "Active",steps: [{name: "Stage subassemblies at the integration cell",@@ -526,6 +637,11 @@ export const PROCEDURES: ProcedureSpec[] = [process: "Burn-In Test",description:"Twenty-four hour duty-cycle burn-in and repeatability check for an integrated arm.",+ parameters: [+ { key: "Burn-in duration", value: "24 h" },+ { key: "Chamber ambient", value: "40 °C" },+ { key: "Repeatability limit", value: "±0.02 mm" }+ ],versions: [{version: 1,@@ -557,6 +673,26 @@ export const PROCEDURES: ProcedureSpec[] = [type: "Checkbox",instruction:"Run the ISO 9283 pose set immediately after the burn-in and confirm every axis stays inside +/- 0.03 mm."+ },+ {+ name: "Stamp burn-in completion time",+ type: "Timestamp",+ instruction:+ "Record the moment the 24-hour duty cycle completes — the cool-down clock for the at-temperature repeatability window starts here."+ },+ {+ name: "Attach burn-in data log",+ type: "File",+ instruction:+ "Export the joint temperature and following-error log from the burn-in rack controller and attach it to the test record.",+ fileTypes: ["csv", "pdf"]+ },+ {+ name: "Post-burn-in workmanship inspection",+ type: "Inspection",+ instruction:+ "Inspect harness dress points, cover seams and gearbox output seals for heat or vibration damage. Photograph any finding.",+ required: false}]}@@ -600,11 +736,72 @@ export const NO_QUOTE_REASONS = ["Strategic Hold"];+// Offsets are positive (upcoming) and distinct — holiday has UNIQUE (date).+export const HOLIDAYS: HolidaySpec[] = [+ { name: "Founders Day", dateOffset: 40 },+ { name: "Automation Expo Shutdown", dateOffset: 100 },+ { name: "Year-End Shutdown", dateOffset: 160 }+];++export const TAGS: TagSpec[] = [+ { name: "Safety Critical", table: "operation" },+ { name: "CE Marked", table: "procedure" },+ { name: "Robot Cell Certified", table: "training" },+ { name: "ESD Sensitive", table: "material" },+ { name: "Calibrated", table: "tool" }+];++// Names deliberately avoid the GLOBAL substances/forms migrations seed (Steel,+// Aluminum, Sheet, Plate, …) so the settings screens don't show duplicates.+export const MATERIAL_TAXONOMY: MaterialTaxonomySpec = {+ substances: [+ { name: "Polyoxymethylene", code: "POM" },+ // Backs the servo cable classification on MAT-CBL-16AWG (items.ts).+ { name: "Copper Conductor", code: "CU" },+ // Backs the solder paste classification on MAT-SOLDER-PST (items.ts).+ { name: "Solder Alloy", code: "SAC" }+ ],+ forms: [+ { name: "Extruded Profile", code: "EXTPROF" },+ { name: "Cable Spool", code: "CBLSPOOL" }+ ],+ types: [+ {+ name: "POM Extruded Profile",+ code: "POM-EXT",+ substance: "Polyoxymethylene",+ form: "Extruded Profile"+ },+ {+ name: "Shielded Servo Cable",+ code: "CU-SRVCBL",+ substance: "Copper Conductor",+ form: "Cable Spool"+ }+ ],+ grades: [+ { name: "Delrin 150", substance: "Polyoxymethylene" },+ { name: "Delrin AF", substance: "Polyoxymethylene" },+ { name: "16 AWG Tinned", substance: "Copper Conductor" },+ { name: "SAC305", substance: "Solder Alloy" }+ ],+ finishes: [+ { name: "Machined Smooth", substance: "Polyoxymethylene" },+ { name: "PUR Jacket", substance: "Copper Conductor" }+ ],+ dimensions: [+ { name: "40 x 40mm", form: "Extruded Profile", isMetric: true },+ { name: "80 x 40mm", form: "Extruded Profile", isMetric: true },+ { name: "16 AWG x 4 Core", form: "Cable Spool", isMetric: false }+ ]+};+export const roboticsFoundation: FoundationData = {departments: DEPT_NAMES,abilities: ABILITIES,processes: PROCESSES,workCenters: WORK_CENTERS,+ hqWorkCenter: HQ_WORK_CENTER,customers: CUSTOMERS,customerContacts: CUSTOMER_CONTACTS,suppliers: SUPPLIERS,@@ -620,12 +817,18 @@ export const roboticsFoundation: FoundationData = {costCenters: COST_CENTERS,noQuoteReasons: NO_QUOTE_REASONS,contractors: CONTRACTORS,+ partners: PARTNERS,plant: PLANT,shifts: SHIFTS,+ workCenterShifts: WORK_CENTER_SHIFTS,+ employeeJob: EMPLOYEE_JOB,warehouses: WAREHOUSES,storageTypes: STORAGE_TYPES,shelves: SHELVES,printerRoute: PRINTER_ROUTE,+ holidays: HOLIDAYS,+ tags: TAGS,+ materialTaxonomy: MATERIAL_TAXONOMY,defaultShippingMethod: "UPS Ground",contractorAgency: CONTRACTOR_AGENCY,partyAddressCity: "Pittsburgh",diff --git a/packages/database/src/datasets/data/robotics/index.ts b/packages/database/src/datasets/data/robotics/index.tsindex be3f46e623..1a9e3488f1 100644--- a/packages/database/src/datasets/data/robotics/index.ts+++ b/packages/database/src/datasets/data/robotics/index.ts@@ -4,6 +4,7 @@ import { roboticsChangeOrders } from "./change-orders.ts";import { roboticsFoundation } from "./foundation.ts";import { roboticsInventory } from "./inventory.ts";import { roboticsItems } from "./items.ts";+import { roboticsOps } from "./ops.ts";import { roboticsPlanning } from "./planning.ts";import { roboticsProduction } from "./production.ts";import { roboticsPurchasing } from "./purchasing.ts";@@ -27,6 +28,7 @@ export const robotics: Dataset = {quality: roboticsQuality,changeOrders: roboticsChangeOrders,accounting: roboticsAccounting,+ ops: roboticsOps,workflows: roboticsWorkflows,planning: roboticsPlanning};diff --git a/packages/database/src/datasets/data/robotics/inventory.ts b/packages/database/src/datasets/data/robotics/inventory.tsindex 21ac066bad..14064c6d4c 100644--- a/packages/database/src/datasets/data/robotics/inventory.ts+++ b/packages/database/src/datasets/data/robotics/inventory.ts@@ -3,7 +3,10 @@ import type {InventoryData,KanbanItemSpec,OpeningStockSpec,- TrackedStockSpec+ ShelfLifeSpec,+ StockTransferSpec,+ TrackedStockSpec,+ WarehouseTransferSpec} from "../../types.ts";// Opening inventory — realistic quantities for a robot-arm OEM.@@ -21,7 +24,7 @@ export const OPENING_STOCK: OpeningStockSpec[] = [{ item: "BRG-CRB-100", qty: 16, shelf: "A2-L3" },{ item: "FST-M8-SS", qty: 600, shelf: "A1-L1" },{ item: "FST-M5-SS", qty: 400, shelf: "A1-L1" },- { item: "MAT-AL6061-BIL", qty: 480, shelf: "A3-L1" },+ { item: "MAT-AL6061-BIL", qty: 485, shelf: "A3-L1" },{ item: "MAT-STEEL-SHT", qty: 220, shelf: "A3-L1" },{ item: "MAT-CBL-16AWG", qty: 800, shelf: "A3-L2" },{ item: "MAT-CONN-M23", qty: 60, shelf: "A1-L2" },@@ -31,13 +34,14 @@ export const OPENING_STOCK: OpeningStockSpec[] = [{ item: "CN-GREASE-EP", qty: 6, shelf: "A1-L2" }];-// Lots/serials that back the tracked slice of the opening stock above.+// Backs the tracked slice of the opening stock above.export const ON_HAND_TRACKED: TrackedStockSpec[] = [{item: "ENC-ABS-19",entities: [{ readableId: "LOT-ENC-2607", quantity: 8 },- { readableId: "LOT-ENC-2608", quantity: 4 }+ { readableId: "LOT-ENC-2608", quantity: 4, expiresOffset: 30 },+ { readableId: "LOT-ENC-2609", quantity: 2, status: "On Hold" }]},{@@ -53,26 +57,188 @@ export const ON_HAND_TRACKED: TrackedStockSpec[] = [item: "MAT-AL6061-BIL",entities: [{ readableId: "LOT-AL6061-2608", quantity: 300 },- { readableId: "LOT-AL6061-2609", quantity: 180 }+ { readableId: "LOT-AL6061-2609", quantity: 180 },+ { readableId: "LOT-AL6061-2610", quantity: 3, status: "Rejected" },+ {+ readableId: "LOT-AL6061-2604",+ quantity: 5,+ status: "Scrapped",+ scrap: {+ shelf: "A3-L1",+ reason: "Damaged",+ dateOffset: -38,+ comment:+ "Billets corroded after sitting in the wash bay over a weekend"+ }+ }]}];-// Kanbans (auto-replenishment cards) for high-usage buy parts.+// LOT-ENC-2608 above expires in 30 days so the expiry chips show amber.+export const SHELF_LIVES: ShelfLifeSpec[] = [{ item: "ENC-ABS-19", days: 365 }];+export const KANBAN_ITEMS: KanbanItemSpec[] = [{ item: "FST-M8-SS", qty: 200, supplier: "Precision Fasteners Co" },{ item: "FST-M5-SS", qty: 100, supplier: "Precision Fasteners Co" },- { item: "PCB-BARE-4L", qty: 10, supplier: "Northgate Electronics" }+ { item: "PCB-BARE-4L", qty: 10, supplier: "Northgate Electronics" },+ { item: "ARM-BASE-001", qty: 2, replenishmentSystem: "Make" },+ {+ item: "MAT-CBL-16AWG",+ qty: 100,+ replenishmentSystem: "Transfer",+ fromShelf: "A3-L2",+ toShelf: "A1-L2"+ }];-export const INVENTORY_COUNT: InventoryCountSpec = {- status: "Draft",- notes: "Quarterly physical count — Q3"-};+export const INVENTORY_COUNTS: InventoryCountSpec[] = [+ {+ // The first six opening-stock rows.+ key: "q3-draft",+ status: "Draft",+ notes: "Quarterly physical count — Q3",+ lines: [+ {+ item: "MOT-AC-750W",+ shelf: "ESD-Cage",+ snapshotQuantity: 4,+ countedQuantity: 4+ },+ {+ item: "MOT-AC-200W",+ shelf: "A2-L2",+ snapshotQuantity: 9,+ countedQuantity: 9+ },+ {+ item: "GBX-HD-80",+ shelf: "A2-L1",+ snapshotQuantity: 5,+ countedQuantity: 5+ },+ {+ item: "GBX-HD-50",+ shelf: "A2-L1",+ snapshotQuantity: 8,+ countedQuantity: 8+ },+ {+ item: "ENC-ABS-19",+ shelf: "ESD-Cage",+ snapshotQuantity: 12,+ countedQuantity: 12+ },+ {+ item: "DRV-SRV-400",+ shelf: "ESD-Cage",+ snapshotQuantity: 18,+ countedQuantity: 18+ }+ ]+ },+ {+ key: "aug-cycle",+ status: "Posted",+ notes: "Cycle count — fastener & hardware bins",+ postedOffset: -20,+ lines: [+ {+ item: "FST-M8-SS",+ shelf: "A1-L1",+ snapshotQuantity: 600,+ countedQuantity: 597+ },+ {+ item: "FST-M5-SS",+ shelf: "A1-L1",+ snapshotQuantity: 400,+ countedQuantity: 400+ },+ {+ item: "BRG-CRB-100",+ shelf: "A2-L3",+ snapshotQuantity: 16,+ countedQuantity: 18+ },+ {+ item: "MAT-CONN-M23",+ shelf: "A1-L2",+ snapshotQuantity: 60,+ countedQuantity: 60+ },+ {+ item: "CN-GREASE-EP",+ shelf: "A1-L2",+ snapshotQuantity: 6,+ countedQuantity: 6+ }+ ]+ }+];++// Only the Completed move changes stock, so it's dated after the posted count above.+export const STOCK_TRANSFERS: StockTransferSpec[] = [+ {+ key: "st-completed",+ status: "Completed",+ fromShelf: "A1-L1",+ toShelf: "A1-L2",+ dateOffset: -10,+ lines: [{ item: "FST-M8-SS", quantity: 50 }]+ },+ {+ key: "st-released",+ status: "Released",+ fromShelf: "A1-L2",+ toShelf: "A3-L2",+ dateOffset: -1,+ lines: [{ item: "MAT-CONN-M23", quantity: 12 }]+ },+ {+ key: "st-draft",+ status: "Draft",+ fromShelf: "A3-L1",+ toShelf: "A3-L3",+ dateOffset: 0,+ lines: [{ item: "MAT-STEEL-SHT", quantity: 20 }]+ }+];++// HQ has no bins, so completed receipts land shelfless.+export const WAREHOUSE_TRANSFERS: WarehouseTransferSpec[] = [+ {+ key: "wt-completed",+ status: "Completed",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: -12,+ lines: [{ item: "FST-M5-SS", quantity: 25, fromShelf: "A1-L1" }]+ },+ {+ key: "wt-toship",+ status: "To Ship",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: 0,+ lines: [{ item: "CN-COVER-KIT", quantity: 2, fromShelf: "A1-L3" }]+ },+ {+ key: "wt-draft",+ status: "Draft",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: 2,+ lines: [{ item: "BRG-CRB-100", quantity: 4, fromShelf: "A2-L3" }]+ }+];export const roboticsInventory: InventoryData = {openingStock: OPENING_STOCK,onHandTracked: ON_HAND_TRACKED,kanbanItems: KANBAN_ITEMS,- inventoryCount: INVENTORY_COUNT+ inventoryCounts: INVENTORY_COUNTS,+ shelfLives: SHELF_LIVES,+ stockTransfers: STOCK_TRANSFERS,+ warehouseTransfers: WAREHOUSE_TRANSFERS};diff --git a/packages/database/src/datasets/data/robotics/items.ts b/packages/database/src/datasets/data/robotics/items.tsindex 3cc0541693..7254ad3479 100644--- a/packages/database/src/datasets/data/robotics/items.ts+++ b/packages/database/src/datasets/data/robotics/items.ts@@ -1,9 +1,19 @@-import type { ItemSpec } from "../../helpers/items.ts";import type {+ BatchPropertySpec,+ ConfigurationSpec,+ CustomerPartSpec,+ EnforcementRuleSpec,+ InspectionPlanSpec,+ ItemSpec,ItemsData,MakeMethodSpec,+ PriceOverrideSpec,+ PricingRuleSpec,+ RevisionLadderSpec,+ SupersessionSpec,SupplierLinkSpec} from "../../types.ts";+import { roboticsAssembly } from "./assembly.ts";// ---------------------------------------------------------------------------// Robot item catalog for Helix Robotics Inc.@@ -125,6 +135,16 @@ export const BUY_PARTS: ItemSpec[] = [standardCost: 0.55,unitSalePrice: 0.9,leadTime: 10+ },+ // Deliberately absent from every BOM: job creation and picking redirect to it via SUPERSESSIONS.+ {+ readableId: "DRV-SRV-400G2",+ name: "Servo Drive 400W EtherCAT Gen2",+ type: "Part",+ replenishment: "Buy",+ standardCost: 460,+ unitSalePrice: 690,+ leadTime: 30}];@@ -152,7 +172,15 @@ export const MATERIALS: ItemSpec[] = [type: "Material",standardCost: 2.4,unitOfMeasureCode: "FOOT",- leadTime: 14+ leadTime: 14,+ material: {+ substance: "Copper Conductor",+ form: "Cable Spool",+ materialType: "Shielded Servo Cable",+ grade: "16 AWG Tinned",+ finish: "PUR Jacket",+ dimension: "16 AWG x 4 Core"+ }},{readableId: "MAT-CONN-M23",@@ -168,7 +196,12 @@ export const MATERIALS: ItemSpec[] = [type: "Material",standardCost: 78,unitOfMeasureCode: "EA",- leadTime: 7+ leadTime: 7,+ // Partially classified on purpose.+ material: {+ substance: "Solder Alloy",+ grade: "SAC305"+ }},{readableId: "MAT-COAT-UV",@@ -232,7 +265,7 @@ export const MAKE_PARTS: ItemSpec[] = [replenishment: "Make",// Serial-tracked: each arm gets its own genealogy in traceability.trackingType: "Serial",- standardCost: 0,+ standardCost: 31900,unitSalePrice: 58000},{@@ -240,7 +273,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Base & Column Assembly (J1)",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 3740,unitSalePrice: 6800},{@@ -248,7 +281,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Upper & Lower Link Assembly",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 6820,unitSalePrice: 12400},{@@ -256,7 +289,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Joint Drive Module (J2/J3)",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 2140,unitSalePrice: 3900},{@@ -264,7 +297,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Three-Axis Wrist Assembly",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 5280,unitSalePrice: 9600},{@@ -272,7 +305,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Robot Controller Cabinet",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 6330,unitSalePrice: 11500},{@@ -280,7 +313,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Motion Control PCB Assembly",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 539,unitSalePrice: 980},{@@ -288,7 +321,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Safety I/O Board Assembly",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 341,unitSalePrice: 620},{@@ -296,7 +329,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Arm Cable Harness",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 770,unitSalePrice: 1400},{@@ -304,7 +337,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Two-Finger Parallel Gripper 80mm",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 3800,unitSalePrice: 6900},{@@ -312,7 +345,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Gripper Jaw Set 80mm",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 176,unitSalePrice: 320}];@@ -338,7 +371,13 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "CNC Mill Cell",description: "Machine base casting and column",order: 1,- laborTime: 4+ setupTime: 1,+ machineTime: 3,+ laborTime: 4,+ parameters: [+ { key: "Fixture", value: "FX-BASE-CAST-01" },+ { key: "Coolant", value: "Flood — water-soluble" }+ ]},{process: "Sheet Metal Fabrication",@@ -366,7 +405,12 @@ export const METHODS: MakeMethodSpec[] = [order: 4,laborTime: 3,// Gives the MES operation screen an Instructions tab with real steps.- procedure: "procedure:Arm Base Assembly"+ procedure: "procedure:Arm Base Assembly",+ tools: [{ tool: "TL-TORQUE-M1", quantity: 1 }],+ parameters: [+ { key: "Torque Spec", value: "24 Nm, star pattern" },+ { key: "Gear Grease", value: "EP robot gear grease, 25 g fill" }+ ]}]},@@ -428,7 +472,9 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "Inspection Bench",description: "Flying probe test",order: 3,- laborTime: 1+ laborTime: 1,+ operationType: "Inspection",+ inspectionPlan: "CTRL-PCB-FPT"}]},@@ -445,7 +491,9 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "SMT Line",description: "SMT placement & reflow",order: 1,- laborTime: 1.5+ setupTime: 0.5,+ laborTime: 1.5,+ machineTime: 0.2},{process: "PCB Assembly",@@ -524,7 +572,9 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "CNC Mill Cell",description: "Machine jaw pair and dowel features",order: 1,- laborTime: 1.25+ setupTime: 0.5,+ laborTime: 1.25,+ machineTime: 0.75},{process: "Final Inspection",@@ -582,6 +632,13 @@ export const METHODS: MakeMethodSpec[] = [description: "Mount drives, boards and wire the backplane",order: 2,laborTime: 5+ },+ {+ process: "Robot Integration",+ workCenter: "Integration Cell 1",+ description: "Cabinet power-up and safety I/O check",+ order: 3,+ laborTime: 1.5}]},@@ -731,10 +788,244 @@ export const SUPPLIER_LINKS: SupplierLinkSpec[] = [item: "FST-M5-SS",price: 0.55,leadTime: 10+ },+ {+ supplier: "Kestrel Motion",+ item: "DRV-SRV-400G2",+ price: 460,+ leadTime: 30+ }+];++// CTRL-100 still names DRV-SRV-400 (18 in the ESD cage), so Consume First+// keeps pulling the old drive until the cage is empty, then swaps to Gen2.+export const SUPERSESSIONS: SupersessionSpec[] = [+ {+ predecessor: "DRV-SRV-400",+ successor: "DRV-SRV-400G2",+ mode: "Consume First",+ successorEffectivityOffset: -14+ }+];++export const CUSTOMER_PARTS: CustomerPartSpec[] = [+ {+ item: "ROB-2000",+ customer: "Lakeshore Automotive",+ customerPartId: "LKS-ROB-001",+ customerRevision: "B"+ },+ {+ item: "CTRL-100",+ customer: "Cascade Integration Group",+ customerPartId: "CIG-CTL-4500"+ }+];++export const PRICE_OVERRIDES: PriceOverrideSpec[] = [+ {+ item: "ROB-2000",+ customer: "Cascade Integration Group",+ notes: "Integrator program pricing per 2026 master supply agreement.",+ breaks: [+ { quantity: 1, overridePrice: 55000 },+ { quantity: 10, overridePrice: 51500 }+ ]+ }+];++export const PRICING_RULES: PricingRuleSpec[] = [+ {+ name: "Lakeshore fleet discount",+ ruleType: "Discount",+ amountType: "Percentage",+ amount: 5,+ customer: "Lakeshore Automotive",+ minQuantity: 3,+ priority: 10+ },+ {+ name: "Integrator drive-train markup",+ ruleType: "Markup",+ amountType: "Percentage",+ amount: 10,+ customerType: "System Integrator",+ items: ["DRV-SRV-400", "MOT-AC-750W", "ENC-ABS-19"],+ priority: 5+ },+ {+ name: "Stainless fastener box break",+ ruleType: "Discount",+ amountType: "Fixed",+ amount: 0.05,+ items: ["FST-M8-SS", "FST-M5-SS"],+ minQuantity: 500,+ priority: 1}];+export const CONFIGURATION: ConfigurationSpec = {+ item: "ROB-2000",+ group: "Arm Configuration",+ parameters: [+ { key: "payload_kg", label: "Rated Payload (kg)", dataType: "numeric" },+ {+ key: "controller_voltage",+ label: "Controller Supply Voltage",+ dataType: "list",+ listOptions: ["208V 3-Phase", "400V 3-Phase", "480V 3-Phase"]+ },+ {+ key: "force_torque_sensor",+ label: "Include Force/Torque Sensor",+ dataType: "boolean"+ }+ ],+ rules: [+ {+ target: { component: "GRP-2F-80" },+ field: "quantity",+ code: "return params.payload_kg > 50 ? 0 : 1;"+ },+ {+ target: { operation: 2 },+ field: "laborTime",+ code: "return params.force_torque_sensor ? 30 : 24;"+ }+ ]+};++export const REVISION_LADDER: RevisionLadderSpec[] = [+ {+ item: "GRP-JAW-80",+ obsoleteRevision: "A",+ nextRevision: "B",+ nextStatus: "Prototype"+ }+];++// A sampling plan of its own makes the MES open an inspection lot, not a plain operation.+export const INSPECTION_PLANS: InspectionPlanSpec[] = [+ {+ key: "CTRL-PCB-FPT",+ item: "PCB-CTRL-R1",+ drawingNumber: "HX-MC-410 Rev C",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "24 V logic rail under full I/O load",+ nominalValue: "24.00",+ tolerancePlus: "0.50",+ toleranceMinus: "0.50",+ unit: "V"+ },+ {+ label: "2",+ description: "Encoder interface differential swing",+ nominalValue: "2.50",+ tolerancePlus: "0.30",+ toleranceMinus: "0.30",+ unit: "V"+ }+ ]+ }+];++export const ENFORCEMENT_RULES: EnforcementRuleSpec[] = [+ {+ family: "sales",+ name: "Cobot certification — US and Canada only",+ description: "UL 1740 / CSA Z434 listing covers North America.",+ message:+ "The ROB-2000 listing covers US and Canadian installations only. Export orders need the CE-marked configuration.",+ severity: "error",+ surfaces: ["salesOrderLine", "salesInvoiceLine"],+ match: "all",+ conditions: [+ {+ field: "customer.location.countryCode",+ op: "in",+ value: ["US", "CA"]+ }+ ],+ items: ["ROB-2000"]+ },+ {+ family: "sales",+ name: "Research orders ship with the teaching license",+ message:+ "Research institute orders ship with the academic teaching license — confirm the license terms with the customer.",+ severity: "warn",+ surfaces: ["quoteLine", "salesOrderLine"],+ match: "all",+ conditions: [+ {+ field: "customer.customerTypeId",+ op: "notIn",+ value: { customerTypes: ["Research"] }+ }+ ],+ items: ["CTRL-100", "ARM-BASE-001"]+ },+ {+ family: "storage",+ targetType: "item",+ name: "ESD components stay at the plant",+ message:+ "ESD-sensitive drives and encoders are stored at the Pittsburgh plant only — pick a plant bin.",+ severity: "warn",+ surfaces: ["receipt", "stockTransfer"],+ match: "all",+ conditions: [+ {+ field: "storageUnit.locationId",+ op: "eq",+ value: { location: "Plant" }+ }+ ],+ items: ["DRV-SRV-400", "ENC-ABS-19"]+ },+ {+ family: "storage",+ targetType: "item",+ name: "Bare boards in bins",+ message: "Bare PCBs go into sealed bins, never open shelving.",+ severity: "warn",+ surfaces: ["place"],+ match: "all",+ conditions: [+ {+ field: "storageUnit.storageTypeId",+ op: "eq",+ value: { storageType: "Bin" }+ }+ ],+ items: ["PCB-BARE-4L"]+ },+ {+ family: "storage",+ targetType: "workCenter",+ name: "SMT line in service",+ message:+ "The SMT line is out of service — hold the board run until maintenance releases it.",+ severity: "error",+ surfaces: ["operationStart"],+ match: "all",+ conditions: [{ field: "workCenter.active", op: "eq", value: true }],+ workCenters: ["SMT Line"]+ }+];++export const BATCH_PROPERTIES: BatchPropertySpec[] = [+ { item: "ENC-ABS-19", label: "Firmware build", dataType: "text" },+ { item: "ENC-ABS-19", label: "Calibration date", dataType: "date" },+ { item: "MAT-AL6061-BIL", label: "Heat number", dataType: "text" },+ { item: "MAT-AL6061-BIL", label: "Hardness (HRB)", dataType: "numeric" }+];+export const roboticsItems: ItemsData = {+ assembly: roboticsAssembly,buyParts: BUY_PARTS,materials: MATERIALS,consumables: CONSUMABLES,@@ -742,5 +1033,14 @@ export const roboticsItems: ItemsData = {services: SERVICES,makeParts: MAKE_PARTS,methods: METHODS,- supplierLinks: SUPPLIER_LINKS+ supplierLinks: SUPPLIER_LINKS,+ supersessions: SUPERSESSIONS,+ customerParts: CUSTOMER_PARTS,+ priceOverrides: PRICE_OVERRIDES,+ pricingRules: PRICING_RULES,+ configuration: CONFIGURATION,+ revisionLadder: REVISION_LADDER,+ inspectionPlans: INSPECTION_PLANS,+ enforcementRules: ENFORCEMENT_RULES,+ batchProperties: BATCH_PROPERTIES};diff --git a/packages/database/src/datasets/data/robotics/ops.ts b/packages/database/src/datasets/data/robotics/ops.tsnew file mode 100644index 0000000000..d4c32c3d63--- /dev/null+++ b/packages/database/src/datasets/data/robotics/ops.ts@@ -0,0 +1,586 @@+import type {+ CustomFieldSpec,+ MaintenanceDispatchSpec,+ MaintenanceScheduleSpec,+ NoteSpec,+ OpenTimecardSpec,+ OpsData,+ PeopleAbsenceSpec,+ PeopleAssignmentSpec,+ PrintJobSpec,+ ReplacementPartSpec,+ SerialSequenceSpec,+ SuggestionSpec,+ TimecardSpec,+ TrainingSpec,+ UserAttributeCategorySpec+} from "../../types.ts";++export const MAINTENANCE_SCHEDULES: MaintenanceScheduleSpec[] = [+ {+ key: "smt-nozzle-clean",+ name: "SMT pick-and-place nozzle & feeder clean",+ description:+ "Ultrasonic-clean the placement nozzles, blow out the feeder tracks and check vacuum at each head.",+ workCenter: "SMT Line",+ frequency: "Daily",+ priority: "Medium",+ estimatedDuration: 25,+ nextDueOffset: 1+ },+ {+ key: "cnc-coolant-check",+ name: "CNC coolant concentration & chip-conveyor check",+ description:+ "Refractometer reading on the sump, top off to 7%, and clear the chip conveyor before the Monday gearbox-housing run.",+ workCenter: "CNC Mill Cell",+ frequency: "Weekly",+ priority: "Medium",+ estimatedDuration: 30,+ nextDueOffset: 3+ },+ {+ key: "gearbox-press-regrease",+ name: "Gearbox bench press re-grease & backlash fixture check",+ description:+ "Re-grease the harmonic-drive press ram, then verify the J1 backlash fixture against the master gearset.",+ workCenter: "Gearbox Bench",+ frequency: "Monthly",+ priority: "High",+ estimatedDuration: 90,+ nextDueOffset: 18,+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-GREASE-EP", quantity: 1 }]+ },+ {+ key: "integration-fence",+ name: "Integration cell safety-fence & light-curtain test",+ description:+ "Walk every interlocked gate, break each light-curtain beam and confirm the arm stops within the rated distance.",+ workCenter: "Integration Cell 1",+ frequency: "Quarterly",+ priority: "High",+ estimatedDuration: 120,+ nextDueOffset: 41,+ takesWorkCenterOffline: true+ },+ {+ key: "burn-in-psu",+ name: "Annual burn-in rack power-supply calibration",+ description:+ "Calibrate the programmable supplies and the thermal chamber controller that drive the 48-hour drive burn-in.",+ workCenter: "Burn-In Rack",+ frequency: "Annual",+ priority: "Medium",+ estimatedDuration: 360,+ nextDueOffset: 150,+ takesWorkCenterOffline: true+ },+ {+ key: "demo-cell-scanner",+ name: "Demo cell safety scanner functional test",+ description:+ "Walk-test every protective and warning field of the demo cell's laser scanner and log the stop times against the risk assessment.",+ workCenter: "Customer Demo Cell",+ frequency: "Monthly",+ priority: "High",+ estimatedDuration: 45,+ nextDueOffset: 12+ }+];++// Shapes the maintenance KPIs and boards read: a failure on a production day,+// back-dated completions, today's scheduled task, a machine down now, one at HQ.+export const MAINTENANCE_DISPATCHES: MaintenanceDispatchSpec[] = [+ {+ key: "smt-feeder-jam",+ status: "Open",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "SMT Line",+ suspectedFailureMode: "Blockage",+ content:+ "Feeder 14 mis-picking 0402 caps — three encoder boards came off the line with missing decoupling caps this morning.",+ created: { offset: -1, time: "09:10:00" },+ plannedStart: { offset: 1, time: "07:30:00" },+ plannedEnd: { offset: 1, time: "09:30:00" }+ },+ {+ key: "integration-servo-fault",+ status: "Assigned",+ priority: "Critical",+ severity: "OEM Required",+ source: "Non-Conformance",+ oeeImpact: "Down",+ workCenter: "Integration Cell 1",+ nonConformance: "ncr:drive-fault",+ suspectedFailureMode: "Electrical Fault",+ content:+ "Cell's reference arm tripping an over-current fault on J3 during the drive test. Cell locked out; servo-amp OEM booked to swap the amplifier.",+ created: { offset: -4, time: "15:45:00" },+ plannedStart: { offset: 2, time: "08:00:00" },+ plannedEnd: { offset: 2, time: "15:00:00" },+ takesWorkCenterOffline: true,+ comments: [+ "Replacement amplifier confirmed in stock at the OEM — arrives Thursday.",+ "Final drive tests are routed to the spare cell until this one is back."+ ]+ },+ {+ key: "inspection-vision-cal",+ status: "In Progress",+ priority: "Low",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "No Impact",+ workCenter: "Inspection Bench",+ suspectedFailureMode: "Misalignment",+ content:+ "Vision gauge reading the end-effector bolt circle 0.02 mm off the master. Re-calibrating against the dot grid before the next first-article.",+ created: { offset: -1, time: "13:30:00" },+ plannedStart: { offset: -1, time: "13:45:00" },+ plannedEnd: { offset: -1, time: "15:30:00" },+ actualStart: { offset: -1, time: "13:55:00" }+ },+ {+ key: "gearbox-regrease",+ status: "Completed",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Gearbox Bench",+ schedule: "gearbox-press-regrease",+ actualFailureMode: "Lubrication Failure",+ content:+ "Monthly press re-grease. The ram guide was running dry and scoring — cleaned, re-greased and the backlash fixture re-verified.",+ created: { offset: -12, time: "06:00:00" },+ plannedStart: { offset: -11, time: "13:00:00" },+ plannedEnd: { offset: -11, time: "14:30:00" },+ actualStart: { offset: -11, time: "13:10:00" },+ actualEnd: { offset: -11, time: "15:05:00" },+ takesWorkCenterOffline: true,+ // Deliberately more than the kit's one pound.+ spareParts: [{ item: "CN-GREASE-EP", quantity: 2, shelf: "A1-L2" }],+ comments: ["Backlash on the master gearset after re-grease: 0.8 arcmin."]+ },+ {+ key: "cnc-coolant-skip",+ status: "Cancelled",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "CNC Mill Cell",+ schedule: "cnc-coolant-check",+ content:+ "Weekly coolant check. Cancelled — the sump was drained and recharged during the spindle rebuild the same day.",+ created: { offset: -7, time: "06:00:00" },+ plannedStart: { offset: -6, time: "12:00:00" },+ plannedEnd: { offset: -6, time: "12:30:00" }+ },+ {+ key: "smt-nozzle-today",+ status: "Assigned",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "SMT Line",+ schedule: "smt-nozzle-clean",+ content:+ "Daily nozzle and feeder clean: ultrasonic bath for the nozzles, blow out the feeder tracks, vacuum check at each head.",+ created: { offset: -1, time: "06:00:00" },+ plannedStart: { offset: 0, time: "14:00:00" },+ plannedEnd: { offset: 0, time: "14:25:00" }+ },+ {+ key: "harness-tester-down",+ status: "In Progress",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Down",+ workCenter: "Harness Bench",+ suspectedFailureMode: "Electrical Fault",+ content:+ "The cable continuity tester fails its self-test on the 37-pin fixture — every harness reads open on J12. Bench locked out until the fixture relay board is replaced.",+ created: { offset: -1, time: "15:30:00" },+ plannedStart: { offset: -1, time: "15:45:00" },+ plannedEnd: { offset: 1, time: "11:00:00" },+ actualStart: { offset: -1, time: "15:50:00" },+ takesWorkCenterOffline: true,+ comments: ["Relay board ordered from the tester OEM; ships overnight."]+ },+ {+ key: "integration-light-curtain",+ status: "Completed",+ priority: "Medium",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Integration Cell 1",+ suspectedFailureMode: "Misalignment",+ actualFailureMode: "Misalignment",+ content:+ "Light curtain on the cell door kept tripping with the door closed. Receiver bracket had been knocked out of line by a pallet; re-aligned and the muting test re-run.",+ created: { offset: -9, time: "14:10:00" },+ plannedStart: { offset: -9, time: "14:15:00" },+ plannedEnd: { offset: -9, time: "15:00:00" },+ actualStart: { offset: -9, time: "14:20:00" },+ actualEnd: { offset: -9, time: "14:55:00" }+ },+ {+ key: "gearbox-regrease-prior",+ status: "Completed",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Gearbox Bench",+ schedule: "gearbox-press-regrease",+ content:+ "Monthly re-grease of the gear-press guides and ball screw. Nothing out of the ordinary.",+ created: { offset: -43, time: "06:00:00" },+ plannedStart: { offset: -42, time: "12:00:00" },+ plannedEnd: { offset: -42, time: "15:00:00" },+ actualStart: { offset: -42, time: "12:05:00" },+ actualEnd: { offset: -42, time: "14:40:00" },+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-GREASE-EP", quantity: 1, shelf: "A1-L2" }]+ },+ {+ key: "cnc-spindle-chiller",+ status: "Completed",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Down",+ workCenter: "CNC Mill Cell",+ suspectedFailureMode: "Overheating",+ actualFailureMode: "Overheating",+ content:+ "Spindle chiller tripped on high refrigerant pressure mid-cycle — condenser coil packed with chips and mist. Coil cleaned, filter replaced, spindle warm-up re-run.",+ created: { offset: -48, time: "08:40:00" },+ plannedStart: { offset: -48, time: "09:00:00" },+ plannedEnd: { offset: -48, time: "15:00:00" },+ actualStart: { offset: -48, time: "09:10:00" },+ actualEnd: { offset: -47, time: "10:30:00" },+ takesWorkCenterOffline: true+ },+ {+ key: "demo-arm-brake",+ status: "Open",+ priority: "Medium",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Customer Demo Cell",+ suspectedFailureMode: "Excessive Wear",+ content:+ "The demo arm's J3 brake chatters when it re-engages after an e-stop recovery. Customer visit on Thursday — needs a look before then.",+ created: { offset: -2, time: "11:00:00" },+ plannedStart: { offset: 3, time: "09:00:00" },+ plannedEnd: { offset: 3, time: "11:00:00" }+ }+];++export const REPLACEMENT_PARTS: ReplacementPartSpec[] = [+ { workCenter: "Gearbox Bench", item: "CN-GREASE-EP", quantity: 2 },+ { workCenter: "Gearbox Bench", item: "BRG-CRB-100", quantity: 1 },+ { workCenter: "Integration Cell 1", item: "DRV-SRV-400", quantity: 1 }+];++export const TRAININGS: TrainingSpec[] = [+ {+ name: "Robot Cell Safety & Lockout/Tagout",+ description:+ "ISO 10218 / RIA R15.06 basics for anyone entering a robot cell.",+ status: "Active",+ frequency: "Once",+ type: "Mandatory",+ estimatedDuration: "40m",+ content: [+ "No one enters a cell while the arm is in automatic. Collaborative mode is not a license to stand in the work envelope.",+ "Lock out the cell's disconnect with your own lock and tag before reaching past the fence, and try-start to verify zero energy."+ ],+ questions: [+ {+ type: "MultipleChoice",+ question:+ "Which step comes right after applying your lock and tag to the cell disconnect?",+ options: [+ "Enter the cell",+ "Try-start to verify zero energy",+ "Call the supervisor",+ "Reset the light curtain"+ ],+ correct: "Try-start to verify zero energy"+ },+ {+ type: "TrueFalse",+ question:+ "A teach pendant in reduced-speed mode makes it safe to stand inside the arm's work envelope without an enabling device.",+ answer: false+ },+ {+ type: "MultipleAnswers",+ question:+ "Which of these are hazardous energy sources in a robot cell?",+ options: [+ "Servo power",+ "Compressed air to the gripper",+ "Gravity on a raised axis",+ "The cell's floor paint",+ "Stored charge in the drive capacitors"+ ],+ correct: [+ "Servo power",+ "Compressed air to the gripper",+ "Gravity on a raised axis",+ "Stored charge in the drive capacitors"+ ]+ },+ {+ type: "MatchingPairs",+ question: "Match each safeguard to what it does.",+ pairs: [+ { left: "Light curtain", right: "Stops the arm when a beam breaks" },+ { left: "Enabling device", right: "Allows motion only while held" },+ { left: "Gate interlock", right: "Drops servo power when opened" }+ ]+ },+ {+ type: "Numerical",+ question:+ "What is the maximum reduced-speed teach mode velocity at the tool center point, in mm/s?",+ answer: 250,+ tolerance: 0+ }+ ],+ assignment: { completedOffset: -15 }+ },+ {+ name: "ESD Handling for Drive Electronics",+ description:+ "Wrist straps, dissipative mats and shielded bags on the SMT line.",+ status: "Active",+ frequency: "Annual",+ type: "Mandatory",+ estimatedDuration: "25m",+ content: [+ "Every servo drive and encoder board is ESD-sensitive. Test your strap at the station before touching one."+ ],+ questions: [+ {+ type: "MultipleChoice",+ question: "Where are finished drive boards stored between operations?",+ options: [+ "Static-shielding bags",+ "Open plastic trays",+ "Cardboard boxes"+ ],+ correct: "Static-shielding bags"+ },+ {+ type: "TrueFalse",+ question: "Sleeves rolled up are enough to replace a wrist strap.",+ answer: false+ }+ ],+ assignment: {}+ },+ {+ name: "Harmonic Drive Assembly",+ description:+ "Operator qualification for building and grease-packing strain-wave gearboxes.",+ status: "Draft",+ frequency: "Once",+ type: "Optional",+ estimatedDuration: "75m",+ content: [+ "Draft — flexspline seating, wave-generator grease fill and lost-motion acceptance limits."+ ],+ questions: [+ {+ type: "Numerical",+ question:+ "What is the maximum lost motion accepted on a J1 gearbox, in arcmin?",+ answer: 1,+ tolerance: 0.2+ }+ ]+ }+];++export const TIMECARDS: TimecardSpec[] = [+ { dayOffset: -5, clockIn: "07:02:00", clockOut: "15:34:00" },+ {+ dayOffset: -4,+ clockIn: "06:57:00",+ clockOut: "17:20:00",+ note: "Stayed for the cell integration FAT with Lakeshore."+ },+ { dayOffset: -3, clockIn: "07:05:00", clockOut: "15:31:00" },+ { dayOffset: -2, clockIn: "06:59:00", clockOut: "15:28:00" },+ { dayOffset: -1, clockIn: "07:01:00", clockOut: "11:32:00" },+ { dayOffset: -1, clockIn: "12:02:00", clockOut: "15:36:00" }+];++// Clocked in before the first timer on the floor started this morning.+export const OPEN_TIMECARD: OpenTimecardSpec = { clockIn: "06:33:00" };++// None on today, so the MES schedule opens on every work center, not one station.+export const PEOPLE_ASSIGNMENTS: PeopleAssignmentSpec[] = [+ { dayOffset: -2, workCenter: "CNC Mill Cell", shift: "First Shift" },+ { dayOffset: -1, workCenter: "Gearbox Bench", shift: "First Shift" },+ {+ dayOffset: 1,+ workCenter: "Integration Cell 1",+ shift: "First Shift",+ note: "ROB-2000 arm-to-controller integration for Lakeshore."+ },+ { dayOffset: 2, workCenter: "Gearbox Bench", shift: "First Shift" },+ {+ dayOffset: 3,+ workCenter: "Integration Cell 1",+ shift: "First Shift",+ overtimeHours: 2,+ note: "Stay for the FAT dry run."+ },+ { dayOffset: 4, workCenter: "CNC Mill Cell", shift: "First Shift" }+];++export const PEOPLE_ABSENCES: PeopleAbsenceSpec[] = [+ {+ dayOffset: 8,+ note: "Robot safety (ISO 10218) recertification course."+ }+];++export const SUGGESTIONS: SuggestionSpec[] = [+ {+ suggestion:+ "Let the integration cell's maintenance downtime show on the production schedule so planners stop loading it.",+ emoji: "🤖",+ path: "/x/resources/maintenance",+ tags: ["Maintenance"]+ },+ {+ suggestion:+ "Show each job's serial numbers on the job list so we can find an arm without opening every job.",+ emoji: "💡",+ path: "/x/production/jobs"+ }+];++export const NOTES: NoteSpec[] = [+ {+ text: "Signed off on robot cell LOTO — can lock out Integration Cell 1 for the servo-amp swap."+ },+ {+ text: "Owns the harmonic drive assembly course until it leaves Draft."+ }+];++export const USER_ATTRIBUTE_CATEGORIES: UserAttributeCategorySpec[] = [+ {+ name: "Robot Cell Safety",+ emoji: "🤖",+ public: true,+ attributes: [+ {+ name: "R15.06 safeguarding training expires",+ dataType: "Date",+ valueOffset: 96+ },+ {+ name: "Teach-pendant access level",+ dataType: "List",+ listOptions: ["Operator", "Programmer", "Integrator"],+ value: "Programmer"+ },+ { name: "LOTO authorizer", dataType: "User" },+ {+ name: "Collaborative-mode sign-off",+ dataType: "Yes/No",+ value: true,+ canSelfManage: true+ }+ ]+ }+];++export const CUSTOM_FIELDS: CustomFieldSpec[] = [+ { table: "part", name: "CE declaration reference", dataType: "Text" },+ { table: "customer", name: "Applications engineer", dataType: "User" },+ { table: "job", name: "Customer witness test", dataType: "Yes/No" }+];++export const SERIAL_SEQUENCES: SerialSequenceSpec[] = [+ // Continues the supplier's numbering already on the shelf (…-0054).+ { item: "MOT-AC-750W", prefix: "MOT750-SN-", size: 4, next: 54 },+ { item: "ROB-2000", prefix: "ROB2000-SN-", size: 4, next: 1 }+];++export const PRINT_JOBS: PrintJobSpec[] = [+ {+ source: { kind: "Receipt", receipt: "receipt:bare-boards" },+ item: "PCB-BARE-4L",+ status: "completed",+ origin: "auto",+ at: { offset: -1, time: "15:18:00" },+ attempts: 1+ },+ {+ source: { kind: "Job", job: "done-base" },+ item: "ARM-BASE-001",+ status: "completed",+ origin: "manual",+ at: { offset: -2, time: "19:25:00" },+ attempts: 1+ },+ {+ source: { kind: "StorageUnit", shelf: "A1-L1" },+ status: "completed",+ origin: "manual",+ at: { offset: -6, time: "16:05:00" },+ attempts: 1+ },+ {+ source: { kind: "Job", job: "floor-drive" },+ item: "DRV-J2-MOD",+ status: "failed",+ origin: "auto",+ at: { offset: -1, time: "13:40:00" },+ attempts: 3,+ error: "Printer did not respond after 3 attempts (connection timed out)"+ },+ {+ source: { kind: "Job", job: "floor-drive" },+ item: "DRV-J2-MOD",+ status: "queued",+ origin: "reprint",+ at: { offset: 0, time: "06:54:00" },+ attempts: 0+ }+];++export const roboticsOps: OpsData = {+ userAttributeCategories: USER_ATTRIBUTE_CATEGORIES,+ customFields: CUSTOM_FIELDS,+ serialSequences: SERIAL_SEQUENCES,+ printJobs: PRINT_JOBS,+ maintenanceSchedules: MAINTENANCE_SCHEDULES,+ maintenanceDispatches: MAINTENANCE_DISPATCHES,+ replacementParts: REPLACEMENT_PARTS,+ trainings: TRAININGS,+ timecards: TIMECARDS,+ openTimecard: OPEN_TIMECARD,+ peopleAssignments: PEOPLE_ASSIGNMENTS,+ peopleAbsences: PEOPLE_ABSENCES,+ suggestions: SUGGESTIONS,+ notes: NOTES+};diff --git a/packages/database/src/datasets/data/robotics/planning.ts b/packages/database/src/datasets/data/robotics/planning.tsindex 01dd91b8c0..d82657e5b4 100644--- a/packages/database/src/datasets/data/robotics/planning.ts+++ b/packages/database/src/datasets/data/robotics/planning.ts@@ -1,6 +1,7 @@import type {DemandOrderSpec,DemandProjectionSpec,+ HqPlanningSpec,PlanningData} from "../../types.ts";@@ -62,9 +63,15 @@ export const DEMAND_ORDER: DemandOrderSpec = {]};+export const HQ_PLANNING: HqPlanningSpec = {+ reorderItemIds: ["CTRL-100", "DRV-SRV-400"],+ demandProjections: [{ readableId: "CTRL-100", quantities: [1, 1, 1, 2] }]+};+export const roboticsPlanning: PlanningData = {buyItemIds: BUY_ITEM_IDS,makeItemIds: MAKE_ITEM_IDS,demandProjections: DEMAND_PROJECTIONS,- demandOrder: DEMAND_ORDER+ demandOrder: DEMAND_ORDER,+ hq: HQ_PLANNING};diff --git a/packages/database/src/datasets/data/robotics/production.ts b/packages/database/src/datasets/data/robotics/production.tsindex b9acfd85d0..d6a18da397 100644--- a/packages/database/src/datasets/data/robotics/production.ts+++ b/packages/database/src/datasets/data/robotics/production.ts@@ -2,10 +2,10 @@ import type {GenealogyAssemblySpec,GenealogyInputSpec,JobSpec,+ PickingListSpec,ProductionData,ShiftEventSpec} from "../../types.ts";-import { roboticsAssembly } from "./assembly.ts";export const JOBS: JobSpec[] = [{@@ -17,8 +17,31 @@ export const JOBS: JobSpec[] = [salesOrder: "so:lakeshore",salesOrderLine: "soline:lakeshore:rob",customer: "Lakeshore Automotive",- dueDateOffset: -167,- releasedDateOffset: -297+ deadlineType: "Hard Deadline",+ dueDateOffset: 6,+ releasedDateOffset: -297,+ priority: 3,+ assignee: "self",+ operationOverrides: [+ { order: 1, status: "Done" },+ { order: 2, status: "In Progress", assignee: "self" },+ { order: 3, status: "Waiting" }+ ],+ quantities: [+ { order: 1, type: "Production", quantity: 1 },+ { order: 1, type: "Scrap", quantity: 2, scrapReason: "Damaged" },+ { order: 2, type: "Rework", quantity: 1 }+ ],+ operationNotes: [+ {+ order: 1,+ note: "Base-to-link dowels seated on the second press — torque-striped all J1 fasteners and logged the values in the Lakeshore acceptance packet."+ },+ {+ order: 2,+ note: "Burn-in hour 14 of 24. Repeatability holding at ±0.02 mm on the test cube, J2 drive temp steady at 41C."+ }+ ]},{key: "ready",@@ -28,8 +51,10 @@ export const JOBS: JobSpec[] = [salesOrder: "so:northwind",salesOrderLine: "soline:northwind:rob",customer: "Northwind Electronics",- dueDateOffset: -153,- releasedDateOffset: -251+ deadlineType: "ASAP",+ dueDateOffset: 14,+ releasedDateOffset: -4,+ priority: 10},{key: "planned",@@ -39,7 +64,9 @@ export const JOBS: JobSpec[] = [salesOrder: "so:planned",salesOrderLine: "soline:planned",customer: "Cascade Integration Group",- dueDateOffset: -90+ deadlineType: "Soft Deadline",+ dueDateOffset: 18,+ priority: 12},{key: "draft",@@ -49,7 +76,7 @@ export const JOBS: JobSpec[] = [salesOrder: "so:draft",salesOrderLine: "soline:draft",customer: "Alpine Research Institute",- dueDateOffset: -125+ deadlineType: "No Deadline"},{key: "paused",@@ -59,8 +86,9 @@ export const JOBS: JobSpec[] = [salesOrder: "so:paused",salesOrderLine: "soline:paused",customer: "Lakeshore Automotive",- dueDateOffset: -139,- releasedDateOffset: -266+ dueDateOffset: 9,+ releasedDateOffset: -266,+ priority: 6},{key: "completed",@@ -98,6 +126,204 @@ export const JOBS: JobSpec[] = [customer: "Alpine Research Institute",dueDateOffset: -314,releasedDateOffset: -337+ },++ // Released over the last few weeks so every work center has a queue and something running today.+ {+ key: "floor-ctrl-pcb",+ item: "PCB-CTRL-R1",+ status: "In Progress",+ quantity: 6,+ salesOrder: "so:floor-lakeshore",+ salesOrderLine: "soline:floor-lakeshore:ctrl-pcb",+ customer: "Lakeshore Automotive",+ dueDateOffset: 2,+ releasedDateOffset: -6,+ priority: 2,+ assignee: "self",+ operationOverrides: [+ { order: 1, status: "Done" },+ {+ order: 2,+ status: "In Progress",+ assignee: "self",+ running: { type: "Labor", startTimeOfDay: "07:30:00" }+ },+ // The first boards are already on the inspection bench (quality.inspections).+ { order: 3, status: "In Progress" }+ ]+ },+ {+ key: "floor-io-pcb",+ item: "PCB-IO-R1",+ status: "In Progress",+ quantity: 6,+ salesOrder: "so:floor-northwind",+ salesOrderLine: "soline:floor-northwind:io-pcb",+ customer: "Northwind Electronics",+ dueDateOffset: 5,+ releasedDateOffset: -2,+ priority: 4,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ {+ key: "floor-drive",+ item: "DRV-J2-MOD",+ status: "In Progress",+ quantity: 4,+ salesOrder: "so:floor-northwind",+ salesOrderLine: "soline:floor-northwind:drive",+ customer: "Northwind Electronics",+ deadlineType: "Soft Deadline",+ dueDateOffset: 12,+ releasedDateOffset: -9,+ priority: 8,+ assignee: "self",+ operationOverrides: [+ {+ order: 1,+ status: "In Progress",+ assignee: "self",+ running: { type: "Setup", startTimeOfDay: "06:45:00" }+ },+ { order: 2, status: "Waiting" }+ ]+ },+ {+ key: "floor-jaw",+ item: "GRP-JAW-80",+ status: "In Progress",+ quantity: 4,+ salesOrder: "so:floor-northwind",+ salesOrderLine: "soline:floor-northwind:jaw",+ customer: "Northwind Electronics",+ dueDateOffset: 7,+ releasedDateOffset: -5,+ priority: 5,+ operationOverrides: [+ {+ order: 1,+ status: "In Progress",+ running: { type: "Machine", startTimeOfDay: "08:15:00" }+ },+ { order: 2, status: "Waiting" }+ ]+ },+ {+ key: "floor-harness",+ item: "HRN-ARM-001",+ status: "Ready",+ quantity: 3,+ salesOrder: "so:floor-lakeshore",+ salesOrderLine: "soline:floor-lakeshore:harness",+ customer: "Lakeshore Automotive",+ deadlineType: "ASAP",+ dueDateOffset: 0,+ releasedDateOffset: -1,+ priority: 1,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ {+ key: "floor-wrist",+ item: "ARM-WRIST-001",+ status: "Ready",+ quantity: 2,+ salesOrder: "so:floor-northwind",+ salesOrderLine: "soline:floor-northwind:wrist",+ customer: "Northwind Electronics",+ dueDateOffset: 21,+ releasedDateOffset: -3,+ priority: 13+ },+ {+ key: "floor-ctrl",+ item: "CTRL-100",+ status: "Ready",+ quantity: 1,+ salesOrder: "so:floor-northwind",+ salesOrderLine: "soline:floor-northwind:ctrl",+ customer: "Northwind Electronics",+ deadlineType: "Soft Deadline",+ dueDateOffset: 16,+ releasedDateOffset: -4,+ priority: 11,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ // No deadline, so it lands in Priorities' Unscheduled column.+ {+ key: "floor-gripper",+ item: "GRP-2F-80",+ status: "Ready",+ quantity: 2,+ salesOrder: "so:floor-northwind",+ salesOrderLine: "soline:floor-northwind:gripper",+ customer: "Northwind Electronics",+ deadlineType: "No Deadline",+ releasedDateOffset: -1,+ priority: 14+ },+ {+ key: "stock-ctrl-pcb",+ item: "PCB-CTRL-R1",+ status: "In Progress",+ quantity: 10,+ dueDateOffset: 11,+ releasedDateOffset: -2,+ priority: 9+ },+ {+ key: "stock-harness",+ item: "HRN-ARM-001",+ status: "Ready",+ quantity: 6,+ deadlineType: "Soft Deadline",+ dueDateOffset: 9,+ releasedDateOffset: -3,+ priority: 7,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ // Feeds the completion-time and estimates-vs-actuals KPIs.+ {+ key: "done-io-pcb",+ item: "PCB-IO-R1",+ status: "Completed",+ quantity: 4,+ quantityComplete: 4,+ salesOrder: "so:floor-lakeshore",+ salesOrderLine: "soline:floor-lakeshore:io-pcb",+ customer: "Lakeshore Automotive",+ dueDateOffset: -8,+ releasedDateOffset: -16,+ completedDateOffset: -11,+ loggedTime: { startOffset: -14, efficiency: 0.92 }+ },+ {+ key: "done-jaw",+ item: "GRP-JAW-80",+ status: "Completed",+ quantity: 2,+ quantityComplete: 2,+ salesOrder: "so:floor-lakeshore",+ salesOrderLine: "soline:floor-lakeshore:jaw",+ customer: "Lakeshore Automotive",+ dueDateOffset: -20,+ releasedDateOffset: -28,+ completedDateOffset: -24,+ loggedTime: { startOffset: -27, efficiency: 1.18 }+ },+ {+ key: "done-base",+ item: "ARM-BASE-001",+ status: "Completed",+ quantity: 1,+ quantityComplete: 1,+ salesOrder: "so:floor-lakeshore",+ salesOrderLine: "soline:floor-lakeshore:base",+ customer: "Lakeshore Automotive",+ dueDateOffset: -2,+ releasedDateOffset: -12,+ completedDateOffset: -4,+ loggedTime: { startOffset: -9, efficiency: 1.07 }}];@@ -188,12 +414,75 @@ export const GENEALOGY_ASSEMBLY: GenealogyAssemblySpec = {}};+export const PICKING_LISTS: PickingListSpec[] = [+ {+ key: "rob-kit-1",+ status: "Completed",+ job: "in-progress",+ dateOffset: -20,+ lines: [+ {+ item: "FST-M8-SS",+ quantityRequired: 24,+ quantityPicked: 24,+ status: "Picked",+ fromShelf: "A1-L1"+ },+ {+ item: "MAT-CONN-M23",+ quantityRequired: 6,+ quantityPicked: 6,+ status: "Picked",+ fromShelf: "A1-L2"+ }+ ]+ },+ {+ key: "rob-kit-2",+ status: "In Progress",+ job: "in-progress",+ dateOffset: -2,+ lines: [+ {+ item: "BRG-CRB-100",+ quantityRequired: 4,+ quantityPicked: 0,+ status: "Pending",+ fromShelf: "A2-L3"+ },+ {+ item: "CN-GREASE-EP",+ quantityRequired: 1,+ quantityPicked: 0,+ status: "Short",+ fromShelf: "A1-L2"+ }+ ]+ }+];+export const roboticsProduction: ProductionData = {- assembly: roboticsAssembly,jobs: JOBS,shifts: SHIFTS,genealogyInputs: GENEALOGY_INPUTS,genealogyAssembly: GENEALOGY_ASSEMBLY,eventsJobKey: "in-progress",- genealogyJobKey: "in-progress"+ genealogyJobKey: "in-progress",+ // Must match the operation overridden to In Progress.+ openEvent: { operationOrder: 2 },+ batch: {+ members: [+ { job: "floor-io-pcb", order: 1 },+ { job: "stock-ctrl-pcb", order: 1 }+ ],+ running: { type: "Machine", startTimeOfDay: "07:05:00" }+ },+ rework: {+ quantity: 1,+ reason:+ "J4 wrist repeatability drifted past ±0.03 mm at burn-in hour 9 — return unit 2 to integration for wrist re-shim and encoder re-mate.",+ targetOperationOrder: 1,+ triggeredAtOperationOrder: 2+ },+ pickingLists: PICKING_LISTS};diff --git a/packages/database/src/datasets/data/robotics/purchasing.ts b/packages/database/src/datasets/data/robotics/purchasing.tsindex 0e2cc1ae98..f2b02f9976 100644--- a/packages/database/src/datasets/data/robotics/purchasing.ts+++ b/packages/database/src/datasets/data/robotics/purchasing.ts@@ -1,9 +1,12 @@import type {+ LifecycleRfqSpec,PurchaseOrderSpec,+ PurchaseReturnSpec,PurchasingData,RfqHeaderSpec,RfqLineSpec,- RfqQuoteSpec+ RfqQuoteSpec,+ StandaloneSupplierQuoteSpec} from "../../types.ts";// Every RFQ line and every supplier quote prices the same quantity breaks, so@@ -26,6 +29,7 @@ export const RFQ_LINES: RfqLineSpec[] = [export const RFQ_QUOTES: RfqQuoteSpec[] = [{key: "northgate",+ assignee: "self",supplier: "Northgate Electronics",supplierReference: "NGE-Q-4471",shippingCost: 250,@@ -110,6 +114,7 @@ export const RFQ_ORDER_QUANTITY = 25;// 2 lines, finalized (Requested), fanned out to 3 suppliers.export const RFQ_HEADER: RfqHeaderSpec = {ref: "prfq:controls",+ assignee: "self",status: "Requested",rfqDateOffset: -24,expirationOffset: 48,@@ -117,6 +122,40 @@ export const RFQ_HEADER: RfqHeaderSpec = {internalNotes: "Award on landed cost at 25 pcs unless lead time slips."};+export const LIFECYCLE_RFQS: LifecycleRfqSpec[] = [+ {+ ref: "prfq:drivetrain",+ status: "Draft",+ rfqDateOffset: -2,+ expirationOffset: 28,+ notes:+ "Harmonic gear sets and crossed-roller bearings for the next arm batch.",+ internalNotes: "Hold until the J2 gear-ratio decision lands.",+ quantities: [10, 25],+ lines: [+ { item: "GBX-HD-50", description: "50mm harmonic gear set, 80:1" },+ {+ item: "BRG-CRB-100",+ description: "100mm-bore crossed roller bearing, P5"+ }+ ],+ suppliers: ["Torqline Gearing", "Kestrel Motion"]+ },+ {+ ref: "prfq:ft-sensor",+ status: "Closed",+ rfqDateOffset: -58,+ expirationOffset: -28,+ notes: "Six-axis force/torque sensors for the collaborative wrist.",+ internalNotes: "Cancelled — cobot wrist program pushed to next year.",+ quantities: [5, 20],+ lines: [+ { item: "SNS-FT-6AX", description: "Six-axis F/T sensor, 200N range" }+ ],+ suppliers: ["Northgate Electronics", "Kestrel Motion"]+ }+];+export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [{source: "direct",@@ -170,6 +209,7 @@ export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [source: "direct",log: "purchase order 3 — Draft (Torqline)",ref: "po:torqline",+ assignee: "self",supplier: "Torqline Gearing",purchaseOrderType: "Purchase",status: "Draft",@@ -184,6 +224,411 @@ export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [orderDateOffset: -8,currencyCode: "USD",exchangeRate: 1+ },++ {+ source: "direct",+ log: "purchase order — Planned (Kestrel wrist motors)",+ supplier: "Kestrel Motion",+ purchaseOrderType: "Purchase",+ status: "Planned",+ orderDateOffset: -1,+ lines: [+ { item: "MOT-AC-200W", purchaseQuantity: 3, supplierUnitPrice: 315 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — To Review (Northgate control boards)",+ assignee: "self",+ supplier: "Northgate Electronics",+ purchaseOrderType: "Purchase",+ status: "To Review",+ orderDateOffset: -2,+ lines: [+ { item: "PCB-BARE-4L", purchaseQuantity: 25, supplierUnitPrice: 21 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — Needs Approval (Ironbark billet buy)",+ ref: "po:needs-approval",+ supplier: "Ironbark Metals",+ purchaseOrderType: "Purchase",+ status: "Needs Approval",+ orderDateOffset: -1,+ lines: [+ // Over the $5,000 approval tier.+ {+ item: "MAT-AL6061-BIL",+ purchaseQuantity: 1200,+ supplierUnitPrice: 4.35+ }+ ]+ },+ {+ source: "direct",+ log: "purchase order — Rejected (Torqline gear set quote too high)",+ supplier: "Torqline Gearing",+ purchaseOrderType: "Purchase",+ status: "Rejected",+ orderDateOffset: -13,+ lines: [{ item: "GBX-HD-50", purchaseQuantity: 2, supplierUnitPrice: 845 }]+ },++ {+ source: "direct",+ log: "purchase order — Completed, received in full and paid (Northgate)",+ ref: "po:paid",+ supplier: "Northgate Electronics",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -75,+ lines: [+ { item: "ENC-ABS-19", purchaseQuantity: 6, supplierUnitPrice: 238 },+ { item: "PCB-BARE-4L", purchaseQuantity: 20, supplierUnitPrice: 21.5 }+ ],+ receipt: {+ ref: "receipt:paid",+ status: "Posted",+ postedOffset: -68,+ lines: [+ {+ item: "ENC-ABS-19",+ orderQuantity: 6,+ outstandingQuantity: 0,+ receivedQuantity: 6,+ unitPrice: 238,+ requiresBatchTracking: true,+ toShelf: "ESD-Cage",+ // Received -68 with a 365-day calibration cert → expires at +297.+ lotNumber: "LOT-ENC-2611",+ lotExpiresOffset: 297+ },+ {+ item: "PCB-BARE-4L",+ orderQuantity: 20,+ outstandingQuantity: 0,+ receivedQuantity: 20,+ unitPrice: 21.5,+ toShelf: "ESD-Cage"+ }+ ]+ },+ invoice: {+ ref: "pinvoice:paid",+ key: "paid",+ status: "Paid",+ currencyCode: "USD",+ subtotal: 1858,+ totalAmount: 1858,+ dateIssuedOffset: -62,+ dueDateOffset: -32,+ lines: [+ { item: "ENC-ABS-19", quantity: 6, supplierUnitPrice: 238 },+ { item: "PCB-BARE-4L", quantity: 20, supplierUnitPrice: 21.5 }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Closed short after a partial receipt (Torqline gears)",+ ref: "po:closed-short",+ supplier: "Torqline Gearing",+ purchaseOrderType: "Purchase",+ status: "Closed",+ orderDateOffset: -88,+ lines: [+ { item: "GBX-HD-80", purchaseQuantity: 4, supplierUnitPrice: 1150 }+ ],+ receipt: {+ ref: "receipt:short",+ status: "Posted",+ postedOffset: -80,+ lines: [+ {+ item: "GBX-HD-80",+ orderQuantity: 4,+ outstandingQuantity: 2,+ receivedQuantity: 2,+ unitPrice: 1150,+ toShelf: "A2-L1"+ }+ ]+ },+ invoice: {+ ref: "pinvoice:debit-note",+ key: "debit-note",+ status: "Debit Note Issued",+ currencyCode: "USD",+ subtotal: 2300,+ totalAmount: 2300,+ dateIssuedOffset: -72,+ lines: [{ item: "GBX-HD-80", quantity: 2, supplierUnitPrice: 1150 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — To Receive with a voided receipt (Precision Fasteners)",+ supplier: "Precision Fasteners Co",+ purchaseOrderType: "Purchase",+ status: "To Receive",+ orderDateOffset: -21,+ lines: [+ { item: "FST-M5-SS", purchaseQuantity: 200, supplierUnitPrice: 0.55 }+ ],+ receipt: {+ ref: "receipt:voided",+ status: "Voided",+ lines: [+ {+ item: "FST-M5-SS",+ orderQuantity: 200,+ outstandingQuantity: 200,+ receivedQuantity: 0,+ unitPrice: 0.55+ }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice open (Northgate force sensor)",+ supplier: "Northgate Electronics",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -30,+ lines: [+ { item: "SNS-FT-6AX", purchaseQuantity: 1, supplierUnitPrice: 3400 }+ ],+ invoice: {+ ref: "pinvoice:open",+ key: "open",+ status: "Open",+ currencyCode: "USD",+ subtotal: 3400,+ totalAmount: 3400,+ dateIssuedOffset: -9,+ dueDateOffset: 21,+ lines: [{ item: "SNS-FT-6AX", quantity: 1, supplierUnitPrice: 3400 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice overdue (Ironbark steel sheet)",+ supplier: "Ironbark Metals",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -60,+ lines: [+ { item: "MAT-STEEL-SHT", purchaseQuantity: 100, supplierUnitPrice: 1.95 }+ ],+ invoice: {+ ref: "pinvoice:overdue",+ key: "overdue",+ status: "Overdue",+ currencyCode: "USD",+ subtotal: 195,+ totalAmount: 195,+ dateIssuedOffset: -45,+ dueDateOffset: -15,+ lines: [{ item: "MAT-STEEL-SHT", quantity: 100, supplierUnitPrice: 1.95 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice partially paid (Kestrel Gen2 drives)",+ supplier: "Kestrel Motion",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -55,+ lines: [+ { item: "DRV-SRV-400G2", purchaseQuantity: 10, supplierUnitPrice: 460 }+ ],+ invoice: {+ ref: "pinvoice:partial",+ key: "partial",+ status: "Partially Paid",+ currencyCode: "USD",+ subtotal: 4600,+ totalAmount: 4600,+ dateIssuedOffset: -40,+ dueDateOffset: -10,+ lines: [{ item: "DRV-SRV-400G2", quantity: 10, supplierUnitPrice: 460 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Closed, invoice voided over a billing error (Precision Fasteners)",+ supplier: "Precision Fasteners Co",+ purchaseOrderType: "Purchase",+ status: "Closed",+ orderDateOffset: -66,+ lines: [+ { item: "FST-M8-SS", purchaseQuantity: 300, supplierUnitPrice: 0.85 }+ ],+ invoice: {+ ref: "pinvoice:voided",+ key: "voided",+ status: "Voided",+ currencyCode: "USD",+ subtotal: 255,+ totalAmount: 255,+ dateIssuedOffset: -58,+ lines: [{ item: "FST-M8-SS", quantity: 300, supplierUnitPrice: 0.85 }]+ }+ },++ // Mirrors the OSP orders the create function raises from a job's outside operations.+ {+ source: "direct",+ log: "purchase order — Outside Processing, hard anodize at Kappa",+ assignee: "self",+ supplier: "Kappa Contract Machining",+ purchaseOrderType: "Outside Processing",+ status: "To Receive",+ orderDateOffset: -9,+ lines: [+ { item: "ARM-BASE-001", purchaseQuantity: 2, supplierUnitPrice: 180 }+ ]+ },++ {+ source: "direct",+ log: "purchase order — EUR order, unpaid (Schwarzwald gear sets)",+ ref: "po:eur",+ supplier: "Schwarzwald Antriebstechnik GmbH",+ purchaseOrderType: "Purchase",+ status: "To Invoice",+ orderDateOffset: -18,+ currencyCode: "EUR",+ exchangeRate: 0.92,+ lines: [{ item: "GBX-HD-50", purchaseQuantity: 3, supplierUnitPrice: 720 }]+ },+ {+ source: "direct",+ log: "purchase order — To Invoice, bare boards received yesterday, awaiting incoming inspection (Northgate)",+ ref: "po:bare-boards",+ supplier: "Northgate Electronics",+ purchaseOrderType: "Purchase",+ status: "To Invoice",+ orderDateOffset: -16,+ lines: [+ { item: "PCB-BARE-4L", purchaseQuantity: 20, supplierUnitPrice: 21.5 }+ ],+ receipt: {+ ref: "receipt:bare-boards",+ status: "Posted",+ postedOffset: -1,+ lines: [+ {+ item: "PCB-BARE-4L",+ orderQuantity: 20,+ outstandingQuantity: 0,+ receivedQuantity: 20,+ unitPrice: 21.5,+ toShelf: "ESD-Cage"+ }+ ]+ }+ }+];++export const STANDALONE_SUPPLIER_QUOTES: StandaloneSupplierQuoteSpec[] = [+ {+ key: "pfc-annual-hardware",+ assignee: "self",+ supplier: "Precision Fasteners Co",+ status: "Draft",+ supplierReference: "PFC-2026-1044",+ quotedOffset: -3,+ expirationOffset: 60,+ lines: [+ {+ item: "FST-M8-SS",+ supplierPartId: "PFC-M8X25-A4",+ prices: [+ { quantity: 1000, unitPrice: 0.78, leadTime: 10 },+ { quantity: 2500, unitPrice: 0.72, leadTime: 10 }+ ]+ }+ ]+ },+ {+ key: "ironbark-billet-2025",+ supplier: "Ironbark Metals",+ status: "Expired",+ supplierReference: "IBM-Q-8812",+ quotedOffset: -210,+ expirationOffset: -30,+ lines: [+ {+ item: "MAT-AL6061-BIL",+ supplierPartId: "IBM-6061-T6-RD",+ prices: [{ quantity: 500, unitPrice: 4.05, leadTime: 10 }]+ }+ ]+ },+ {+ key: "kestrel-motor-study",+ supplier: "Kestrel Motion",+ status: "Declined",+ supplierReference: "KM-2025-0912",+ quotedOffset: -40,+ expirationOffset: 20,+ lines: [+ {+ item: "MOT-AC-750W",+ supplierPartId: "KM-750W-3K-B",+ prices: [{ quantity: 8, unitPrice: 665, leadTime: 40 }]+ }+ ]+ }+];++// The completed return is dated after the posted cycle count so the count's+// snapshot stays the opening balance.+export const PURCHASE_RETURNS: PurchaseReturnSpec[] = [+ {+ key: "pcb-warpage",+ credit: {+ status: "Draft",+ dateOffset: -4,+ lines: [{ line: 1, quantity: 12 }]+ },+ status: "Completed",+ supplier: "Northgate Electronics",+ dateOffset: -6,+ lines: [+ {+ item: "PCB-BARE-4L",+ quantity: 12,+ unitPrice: 21.5,+ fromShelf: "ESD-Cage"+ }+ ]+ },+ {+ key: "bearing-preload",+ status: "To Ship",+ supplier: "Torqline Gearing",+ dateOffset: -2,+ lines: [{ item: "BRG-CRB-100", quantity: 2, unitPrice: 185 }]+ },+ {+ key: "drive-firmware",+ status: "Draft",+ supplier: "Kestrel Motion",+ dateOffset: 0,+ lines: [{ item: "DRV-SRV-400", quantity: 1, unitPrice: 420 }]+ },+ // Stays Draft while MRB decides; quality's ncr:gear-lost-motion links this line.+ {+ key: "gearbox-rtv",+ status: "Draft",+ supplier: "Torqline Gearing",+ dateOffset: -3,+ lines: [{ item: "GBX-HD-80", quantity: 1, unitPrice: 1150 }]}];@@ -194,5 +639,65 @@ export const roboticsPurchasing: PurchasingData = {rfqWinningQuote: RFQ_WINNING_QUOTE,rfqOrderQuantity: RFQ_ORDER_QUANTITY,rfqHeader: RFQ_HEADER,- purchaseOrders: PURCHASE_ORDERS+ lifecycleRfqs: LIFECYCLE_RFQS,+ purchaseOrders: PURCHASE_ORDERS,+ standaloneSupplierQuotes: STANDALONE_SUPPLIER_QUOTES,+ purchaseReturns: PURCHASE_RETURNS,+ approvalRules: [+ { documentType: "purchaseOrder", lowerBoundAmount: 5000 },+ {+ documentType: "purchaseOrder",+ lowerBoundAmount: 25000,+ escalationDays: 3+ },+ { documentType: "supplier", lowerBoundAmount: 0 }+ ],+ approvalRequests: [+ { purchaseOrder: "po:needs-approval", requestedOffset: -1 },+ { supplier: "Voltaic Drive Systems", requestedOffset: -4 }+ ],+ supplierBankAccounts: [+ {+ supplier: "Kestrel Motion",+ name: "Kestrel remittance",+ bankName: "Allegheny Commerce Bank (demo)",+ accountHolderName: "Kestrel Motion Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-1188-4402",+ bankCode: "DEMO-043000",+ isPrimary: true+ },+ {+ supplier: "Torqline Gearing",+ name: "Torqline operating",+ bankName: "Ohio Valley Savings (demo)",+ accountHolderName: "Torqline Gearing LLC",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-2299-5513",+ isPrimary: true+ },+ {+ supplier: "Northgate Electronics",+ name: "Northgate remittance",+ bankName: "Keystone Trust (demo)",+ accountHolderName: "Northgate Electronics Corp.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-3301-6624",+ isPrimary: true+ },+ {+ supplier: "Schwarzwald Antriebstechnik GmbH",+ name: "Schwarzwald EUR account",+ bankName: "Schwarzwald Handelsbank (demo)",+ accountHolderName: "Schwarzwald Antriebstechnik GmbH",+ countryCode: "DE",+ currencyCode: "EUR",+ accountNumber: "DEMO-DE00-0000-4412",+ swiftBic: "DEMODEXX",+ isPrimary: true+ }+ ]};diff --git a/packages/database/src/datasets/data/robotics/quality.ts b/packages/database/src/datasets/data/robotics/quality.tsindex 5393cf80cb..f692e6e7e1 100644--- a/packages/database/src/datasets/data/robotics/quality.ts+++ b/packages/database/src/datasets/data/robotics/quality.ts@@ -1,8 +1,58 @@-import type { NonConformanceSpec, QualityData } from "../../types.ts";+import type {+ GaugeSpec,+ InspectionFeatureSpec,+ InspectionSpec,+ NonConformanceSpec,+ NonConformanceWorkflowSpec,+ QualityData,+ QualityDocumentSpec,+ RiskSpec+} from "../../types.ts";++// The new-issue form copies source, required actions and MRB from these templates onto the issue.+export const WORKFLOWS: NonConformanceWorkflowSpec[] = [+ {+ key: "supplier-escape",+ name: "Supplier Escape — Drivetrain Components",+ description:+ "A purchased drivetrain part failed receiving inspection. Quarantine it, work the root cause with the supplier, and record their corrective action before MRB closes it out.",+ priority: "High",+ source: "External",+ requiredActions: [+ "Containment Action",+ "Root Cause Analysis",+ "Corrective Action"+ ],+ mrb: true+ },+ {+ key: "customer-return",+ name: "Customer Complaint — Field Return",+ description:+ "A customer reported a fault on a delivered arm or spare. Acknowledge within one business day, contain sister units, and verify the fix before closing.",+ priority: "Medium",+ source: "External",+ requiredActions: [+ "Customer Communication",+ "Containment Action",+ "Verification"+ ]+ },+ {+ key: "incoming-hold",+ name: "Incoming Lot Hold",+ description:+ "An incoming lot is missing paperwork or failed a screening check. Hold the whole lot until it is released or dispositioned.",+ priority: "Medium",+ source: "Internal",+ requiredActions: ["Containment Action"]+ }+];export const NON_CONFORMANCES: NonConformanceSpec[] = [{ref: "ncr:harness",+ assignee: "self",name: "Arm harness short detected during continuity test",source: "Internal",status: "In Progress",@@ -18,15 +68,454 @@ export const NON_CONFORMANCES: NonConformanceSpec[] = [},{ref: "ncr:torque",+ items: [{ item: "FST-M8-SS", quantity: 12 }],name: "J1 gearbox fastener torque below spec on base assembly",source: "Internal",status: "Registered",openDateOffset: -285,quantity: 12,priority: "Medium"+ },+ {+ ref: "ncr:gear-lost-motion",+ items: [+ { item: "GBX-HD-80", quantity: 1, disposition: "Return to Supplier" },+ { item: "DRV-J2-MOD", quantity: 2 }+ ],+ assignee: "self",+ workflow: "supplier-escape",+ purchaseReturnLine: { purchaseReturn: "gearbox-rtv", line: 1, quantity: 1 },+ name: "Harmonic gear set lost motion over limit on incoming bench test",+ description:+ "Receiving inspection on the Torqline short delivery measured 1.6 arc-min lost motion at ±4% rated torque on one GBX-HD-80 against a 1.0 arc-min limit. Gear set quarantined in QC hold; MRB to decide return-to-vendor vs. regrade for a J6 wrist application.",+ type: "Supplier Issue",+ source: "External",+ status: "In Progress",+ openDateOffset: -78,+ dueDateOffset: 14,+ quantity: 1,+ priority: "Critical",+ supplier: "Torqline Gearing",+ purchaseOrderLine: { po: "po:closed-short", item: "GBX-HD-80" },+ inspection: "insp:gear-set",+ actionTasks: [+ {+ action: "Containment Action",+ status: "Completed",+ dueDateOffset: -76,+ completedOffset: -77+ },+ {+ action: "Root Cause Analysis",+ status: "In Progress",+ dueDateOffset: 7,+ processes: ["Gearbox Assembly"]+ },+ { action: "Corrective Action", status: "Pending", dueDateOffset: 21 }+ ],+ mrb: {+ status: "In Progress",+ dueDateOffset: 10,+ reviewers: [+ { title: "Engineering", status: "Completed", completedOffset: -70 },+ { title: "Quality", status: "In Progress" }+ ]+ }+ },+ {+ ref: "ncr:drive-fault",+ items: [{ item: "DRV-SRV-400", quantity: 1, disposition: "Rework" }],+ workflow: "customer-return",+ salesReturnLine: { salesReturn: "servodrive", line: 1 },+ name: "Customer-reported servo drive spare faults on first power-up",+ description:+ "Cascade Integration Group reported one of two DRV-SRV-400 spares throwing an encoder-communication fault the first time it was enabled on their cell. Unit returned for evaluation; root cause traced to the drive shipping on a superseded firmware build that predates the 19-bit encoder protocol.",+ type: "Customer Complaint",+ source: "External",+ status: "Closed",+ openDateOffset: -14,+ dueDateOffset: 2,+ closeDateOffset: -3,+ quantity: 1,+ priority: "Low",+ customer: "Cascade Integration Group",+ salesOrderLine: "soline:cascade-drives:drv",+ actionTasks: [+ {+ action: "Customer Communication",+ status: "Completed",+ dueDateOffset: -13,+ completedOffset: -13+ },+ {+ action: "Containment Action",+ status: "Completed",+ dueDateOffset: -10,+ completedOffset: -11+ },+ {+ action: "Verification",+ status: "Completed",+ dueDateOffset: -4,+ completedOffset: -4+ }+ ]+ },+ {+ ref: "ncr:enc-lot",+ items: [{ item: "ENC-ABS-19", quantity: 2 }],+ // Feeds the supplier-quality KPI's issue this month.+ supplier: "Northgate Electronics",+ workflow: "incoming-hold",+ name: "Absolute encoder lot on hold — factory calibration certificate missing",+ description:+ "Lot LOT-ENC-2609 arrived without the vendor's factory calibration certificate, so its accuracy cannot be traced for the arm's positional-repeatability claim. Lot placed on hold pending the certificate or an in-house accuracy check.",+ type: "Documentation Error",+ source: "Internal",+ status: "Registered",+ openDateOffset: -6,+ dueDateOffset: 20,+ quantity: 2,+ priority: "Medium",+ trackedEntity: "LOT-ENC-2609",+ actionTasks: [+ { action: "Containment Action", status: "Pending", dueDateOffset: 2 }+ ]+ }+];++// Lot of 2 at AQL 1.0 / level II → code letter A, n = 2.+const BARE_BOARD_PLAN = {+ drawingNumber: "PCB-BARE-4L Fab Dwg Rev B",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Board thickness over copper",+ nominalValue: "1.60",+ tolerancePlus: "0.16",+ toleranceMinus: "0.16",+ unit: "mm"+ },+ {+ label: "2",+ description: "Plated through-hole diameter, M12 connector pattern",+ nominalValue: "1.10",+ tolerancePlus: "0.05",+ toleranceMinus: "0.05",+ unit: "mm"+ }+ ] satisfies InspectionFeatureSpec[]+};++export const INSPECTIONS: InspectionSpec[] = [+ {+ source: "Receipt",+ ref: "insp:gear-set",+ receipt: "receipt:short",+ item: "GBX-HD-80",+ drawingNumber: "TQ-HD80-100 Rev B",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Wave generator input bore diameter (Ø14 H7)",+ nominalValue: "14.000",+ tolerancePlus: "0.018",+ toleranceMinus: "0.000",+ unit: "mm"+ },+ {+ label: "2",+ description: "Lost motion at ±4% rated torque",+ nominalValue: "0.6",+ tolerancePlus: "0.4",+ toleranceMinus: "0.6",+ unit: "arcmin"+ }+ ],+ status: "Partial",+ dispositionOffset: -78,+ notes:+ "S/N HD80-2231 accepted. S/N HD80-2232 lost motion over limit — quarantined in QC hold and raised to MRB.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -79,+ measurements: [+ { feature: "1", value: 14.008 },+ { feature: "2", value: 0.7 }+ ]+ },+ {+ status: "Failed",+ inspectedOffset: -79,+ measurements: [+ { feature: "1", value: 14.011 },+ { feature: "2", value: 1.6 }+ ]+ }+ ]+ },+ // 20 boards at AQL 1.0 → n = 5.+ {+ source: "Receipt",+ ref: "insp:bare-boards",+ receipt: "receipt:paid",+ item: "PCB-BARE-4L",+ ...BARE_BOARD_PLAN,+ status: "Passed",+ dispositionOffset: -67,+ notes: "Five boards measured; thickness and connector holes nominal.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 1.62 },+ { feature: "2", value: 1.11 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 1.57 },+ { feature: "2", value: 1.09 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 1.6 },+ { feature: "2", value: 1.12 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 1.64 },+ { feature: "2", value: 1.1 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 1.59 },+ { feature: "2", value: 1.08 }+ ]+ }+ ]+ },+ {+ source: "Receipt",+ ref: "insp:bare-boards-queue",+ receipt: "receipt:bare-boards",+ item: "PCB-BARE-4L",+ ...BARE_BOARD_PLAN,+ status: "Pending",+ samples: []+ },+ {+ source: "Job Operation",+ ref: "insp:ctrl-fpt",+ job: "floor-ctrl-pcb",+ status: "In Progress",+ notes:+ "Board 1 of 6 on the bed-of-nails; the rest are still on the SMT line.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 24.1 },+ { feature: "2", value: 2.45 }+ ]+ }+ ]+ }+];++export const QUALITY_DOCUMENTS: QualityDocumentSpec[] = [+ {+ name: "Harmonic Gear Set Receiving Inspection",+ version: 1,+ status: "Archived",+ description:+ "Superseded receiving procedure for harmonic gear sets — visual and certificate review only.",+ steps: []+ },+ {+ name: "Harmonic Gear Set Receiving Inspection",+ version: 2,+ status: "Active",+ description:+ "Receiving procedure for harmonic gear sets: paperwork, lubrication and critical fits before stock-in.",+ steps: [+ {+ name: "Certificate of conformance and backlash report match PO and serial",+ type: "Checkbox",+ required: true+ },+ {+ name: "Flexspline grease condition on arrival",+ type: "List",+ required: true,+ listValues: ["Even film", "Dry spots", "Contaminated"]+ },+ {+ name: "Circular spline pilot diameter",+ description: "Measured with the bore gauge at three clock positions.",+ type: "Measurement",+ required: true,+ unitOfMeasureCode: "INCH",+ minValue: 3.148,+ maxValue: 3.15+ }+ ]+ },+ {+ name: "Collaborative Operation Risk Assessment (ISO/TS 15066)",+ version: 0,+ status: "Draft",+ description:+ "Draft power-and-force-limiting assessment for the ROB-2000 collaborative mode — contact zones, force thresholds and speed limits.",+ steps: []+ }+];++export const GAUGES: GaugeSpec[] = [+ {+ key: "gauge-blocks",+ gaugeType: "Gauge Block",+ description: "Grade 0 steel gauge block set, 87 pc — metrology lab master",+ modelNumber: "GBS-87-0",+ serialNumber: "RB-21-0381",+ role: "Master",+ status: "Active",+ calibrationIntervalInMonths: 12,+ acquiredOffset: -720,+ calibrations: [+ {+ dateOffset: -545,+ result: "Pass",+ temperature: 20,+ humidity: 45,+ measurementStandard: "ISO 3650, NIST-traceable interferometry"+ },+ {+ dateOffset: -180,+ result: "Pass",+ temperature: 20,+ humidity: 44,+ measurementStandard: "ISO 3650, NIST-traceable interferometry"+ }+ ]+ },+ {+ key: "dial-indicator",+ gaugeType: "Dial Indicator",+ description:+ "0.001 mm digital dial indicator — new unit for the gearbox bench lost-motion fixture",+ modelNumber: "DI-12.7D",+ serialNumber: "DI25-30917",+ role: "Standard",+ status: "Active",+ calibrationIntervalInMonths: 6,+ acquiredOffset: -12,+ calibrations: []+ },+ {+ key: "bore-gauge",+ gaugeType: "Bore Gauge",+ description: "35–60 mm dial bore gauge — retired after failed calibration",+ modelNumber: "BG-60",+ serialNumber: "BG18-11746",+ role: "Standard",+ status: "Inactive",+ calibrationIntervalInMonths: 6,+ acquiredOffset: -880,+ calibrations: [+ { dateOffset: -390, result: "Pass", temperature: 20, humidity: 47 },+ {+ dateOffset: -210,+ result: "Fail",+ requiresAction: true,+ requiresRepair: true,+ temperature: 20,+ humidity: 45,+ notes:+ "Measuring anvil worn — repeatability 6 µm against a 2 µm limit. Retired."+ }+ ]+ }+];++export const RISKS: RiskSpec[] = [+ {+ title: "Single-source harmonic gear supplier lost-motion escapes",+ description:+ "Torqline is the only qualified source for GBX-HD-80 and has now shipped a lost-motion escape on a lot already closed short.",+ type: "Risk",+ status: "Mitigating",+ severity: 5,+ likelihood: 3,+ source: "Supplier",+ supplier: "Torqline Gearing"+ },+ {+ title: "Line-uptime penalty clause on the Lakeshore body-shop cells",+ description:+ "Lakeshore's draft supply terms add a per-hour downtime penalty on delivered arms — legal and service are reviewing the exposure.",+ type: "Risk",+ status: "In Review",+ severity: 4,+ likelihood: 2,+ source: "Customer",+ customer: "Lakeshore Automotive"+ },+ {+ title: "Absolute encoder ASIC end-of-life",+ description:+ "The ENC-ABS-19 vendor announced end-of-life for the encoder's position ASIC; a last-time buy or a requalified replacement is needed.",+ type: "Risk",+ status: "Open",+ severity: 3,+ likelihood: 3,+ source: "Item",+ item: "ENC-ABS-19"+ },+ {+ title: "Burn-in rack availability for the ROB-2000 job",+ description:+ "The burn-in rack was double-booked with a controller qualification run for the job's 24-hour duty cycle; the slot has since been confirmed.",+ type: "Risk",+ status: "Closed",+ severity: 3,+ likelihood: 2,+ source: "Job",+ job: "job:in-progress"+ },+ {+ title: "Qualify a second harmonic gear source to cut lead time",+ description:+ "A second harmonic gear maker could halve the 60-day GBX lead time and end the single-source exposure — accepted into next year's plan.",+ type: "Opportunity",+ status: "Accepted",+ severity: 2,+ likelihood: 4,+ source: "General"}];export const roboticsQuality: QualityData = {- nonConformances: NON_CONFORMANCES+ workflows: WORKFLOWS,+ nonConformances: NON_CONFORMANCES,+ inspections: INSPECTIONS,+ qualityDocuments: QUALITY_DOCUMENTS,+ gauges: GAUGES,+ risks: RISKS};diff --git a/packages/database/src/datasets/data/robotics/sales.ts b/packages/database/src/datasets/data/robotics/sales.tsindex 54b199ae0b..10c6439df6 100644--- a/packages/database/src/datasets/data/robotics/sales.ts+++ b/packages/database/src/datasets/data/robotics/sales.ts@@ -6,6 +6,7 @@ import type {PriceBreak,SalesData,SalesOpportunitySpec,+ SalesReturnSpec,SalesStatusOrderSpec,StaggeredDeliverySpec} from "../../types.ts";@@ -64,6 +65,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [},quote: {ref: "quote:lakeshore",+ createdOffset: -330,status: "Ordered",externalNotes:"Quote for 3× Vertex 10 six-axis arms with two-finger grippers.",@@ -119,6 +121,8 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Cascade Integration Group",quote: {ref: "quote:cascade",+ createdOffset: -22,+ assignee: "self",status: "Sent",expirationOffset: CASCADE_QUOTE_EXPIRATION_OFFSET,lines: [@@ -149,6 +153,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Alpine Research Institute",rfq: {ref: "rfq:alpine",+ assignee: "self",status: "Ready for Quote",rfqDateOffset: -285,externalNotes:@@ -169,6 +174,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Northwind Electronics",quote: {ref: "quote:northwind",+ createdOffset: -270,status: "Ordered",lines: [{@@ -194,6 +200,182 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [}]}+ },++ {+ log: "opportunity 5 — RFQ draft (Alpine, second test-rig base)",+ ref: "opp:alpine-rig",+ customer: "Alpine Research Institute",+ rfq: {+ ref: "rfq:alpine-rig",+ assignee: "self",+ status: "Draft",+ rfqDateOffset: -3,+ externalNotes:+ "Inquiry being logged — second base assembly for a mobile manipulation rig.",+ lines: [+ {+ item: "ARM-BASE-001",+ customerPartId: "ALP-BASE-002",+ quantity: [1],+ order: 1+ }+ ]+ }+ },+ {+ log: "opportunity 6 — no-quoted RFQ, lost quote (Lakeshore washdown wrist)",+ ref: "opp:lakeshore-washdown",+ customer: "Lakeshore Automotive",+ rfq: {+ ref: "rfq:lakeshore-washdown",+ status: "Closed",+ rfqDateOffset: -95,+ expirationOffset: -50,+ noQuoteReason: "Out of Scope",+ externalNotes:+ "IP69K washdown-rated wrist variant — outside our sealing qualification.",+ lines: [+ {+ item: "ARM-WRIST-001",+ customerPartId: "LKS-WRIST-WD1",+ quantity: [2],+ order: 1+ }+ ]+ },+ quote: {+ ref: "quote:lakeshore-washdown",+ createdOffset: -80,+ status: "Lost",+ externalNotes: "Declined to bid the washdown-rated line.",+ lines: [+ {+ ref: "quoteline:lakeshore-washdown:wrist",+ item: "ARM-WRIST-001",+ status: "No Quote",+ sortOrder: 1,+ priceBreaks: []+ }+ ]+ }+ },+ {+ log: "opportunity 7 — quote draft (Northwind pick-and-place arm)",+ ref: "opp:northwind-pnp",+ customer: "Northwind Electronics",+ quote: {+ ref: "quote:northwind-pnp",+ createdOffset: -4,+ assignee: "self",+ status: "Draft",+ externalNotes:+ "Working draft — pick-and-place-optimized arm pricing in progress.",+ lines: [+ {+ ref: "quoteline:northwind-pnp:rob",+ configuration: {+ payload_kg: 35,+ controller_voltage: "480V 3-Phase",+ force_torque_sensor: false+ },+ item: "ROB-2000",+ status: "Not Started",+ sortOrder: 1,+ priceBreaks: [{ quantity: 1, unitPrice: 58500, leadTime: 125 }]+ }+ ]+ }+ },+ {+ log: "opportunity 8 — partial quote (Cascade cell retrofit)",+ ref: "opp:cascade-retrofit",+ customer: "Cascade Integration Group",+ quote: {+ ref: "quote:cascade-retrofit",+ createdOffset: -8,+ status: "Partial",+ expirationOffset: 45,+ externalNotes:+ "Controller line released to the customer; gripper line still in engineering review.",+ lines: [+ {+ ref: "quoteline:cascade-retrofit:ctrl",+ item: "CTRL-100",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 2, unitPrice: 11200, leadTime: 70 }]+ },+ {+ ref: "quoteline:cascade-retrofit:grp",+ item: "GRP-2F-80",+ status: "In Progress",+ sortOrder: 2,+ priceBreaks: [{ quantity: 2, unitPrice: 6700, leadTime: 85 }]+ }+ ]+ }+ },+ {+ log: "opportunity 9 — cancelled quote (Alpine teaching cell)",+ ref: "opp:alpine-teaching",+ customer: "Alpine Research Institute",+ quote: {+ ref: "quote:alpine-teaching",+ createdOffset: -150,+ status: "Cancelled",+ externalNotes: "Program defunded before pricing was issued.",+ lines: [+ {+ ref: "quoteline:alpine-teaching:ctrl",+ item: "CTRL-100",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 1, unitPrice: 11300, leadTime: 65 }]+ }+ ]+ }+ },+ {+ log: "opportunity 10 — expired quote (Northwind spare jaw set)",+ ref: "opp:northwind-jaws",+ customer: "Northwind Electronics",+ quote: {+ ref: "quote:northwind-jaws",+ createdOffset: -44,+ status: "Expired",+ expirationOffset: -14,+ externalNotes: "30-day pricing lapsed without a PO.",+ lines: [+ {+ ref: "quoteline:northwind-jaws:jaw",+ item: "GRP-JAW-80",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 1, unitPrice: 330, leadTime: 45 }]+ }+ ]+ }+ },+ {+ log: "sales order — Needs Approval (Lakeshore gearbox spares)",+ ref: "opp:lakeshore-gbx",+ customer: "Lakeshore Automotive",+ order: {+ ref: "so:lakeshore-gbx",+ assignee: "self",+ status: "Needs Approval",+ orderDateOffset: -2,+ lines: [+ {+ ref: "soline:lakeshore-gbx:gbx",+ item: "GBX-HD-80",+ saleQuantity: 2,+ unitPrice: 1725,+ status: "Ordered"+ }+ ]+ }}];@@ -267,6 +449,7 @@ export const RELEASED_ORDERS: SalesOpportunitySpec[] = [customer: "Cascade Integration Group",order: {ref: "so:toshipinvoice",+ assignee: "self",status: "To Ship and Invoice",orderDateOffset: -10,lines: STAGGERED_DELIVERIES.map((delivery) => ({@@ -281,11 +464,547 @@ export const RELEASED_ORDERS: SalesOpportunitySpec[] = [sortOrder: delivery.sortOrder}))}+ },++ // Shipped items are well-stocked untracked buy parts (spares sold from the+ // shelf), so the ledger rows never overdraw a bin.+ {+ log: "sales order — To Invoice (Cascade, posted spare-drive shipment)",+ ref: "opp:cascade-drives",+ customer: "Cascade Integration Group",+ order: {+ ref: "so:cascade-drives",+ status: "To Invoice",+ orderDateOffset: -30,+ lines: [+ {+ ref: "soline:cascade-drives:drv",+ item: "DRV-SRV-400",+ saleQuantity: 2,+ unitPrice: 630,+ status: "Completed"+ }+ ]+ },+ shipment: {+ ref: "shp:cascade-drives",+ status: "Posted",+ postedOffset: -18,+ lines: [+ {+ item: "DRV-SRV-400",+ orderQuantity: 2,+ outstandingQuantity: 0,+ shippedQuantity: 2,+ unitPrice: 630,+ fromShelf: "ESD-Cage"+ }+ ]+ }+ },+ {+ log: "sales order — To Ship and Invoice (Lakeshore, partial gear-set shipment)",+ ref: "opp:lakeshore-gearsets",+ customer: "Lakeshore Automotive",+ order: {+ ref: "so:lakeshore-gearsets",+ status: "To Ship and Invoice",+ orderDateOffset: -21,+ lines: [+ {+ ref: "soline:lakeshore-gearsets:gbx",+ item: "GBX-HD-50",+ saleQuantity: 4,+ unitPrice: 1170,+ status: "In Progress"+ }+ ]+ },+ shipment: {+ ref: "shp:lakeshore-gearsets",+ status: "Posted",+ postedOffset: -9,+ lines: [+ {+ item: "GBX-HD-50",+ orderQuantity: 4,+ outstandingQuantity: 2,+ shippedQuantity: 2,+ unitPrice: 1170,+ fromShelf: "A2-L1"+ }+ ]+ }+ },+ {+ log: "sales order — To Ship (Alpine, voided connector shipment)",+ ref: "opp:alpine-connectors",+ customer: "Alpine Research Institute",+ order: {+ ref: "so:alpine-connectors",+ status: "To Ship",+ orderDateOffset: -14,+ lines: [+ {+ ref: "soline:alpine-connectors:conn",+ item: "MAT-CONN-M23",+ saleQuantity: 8,+ unitPrice: 45,+ status: "Ordered"+ }+ ]+ },+ shipment: {+ ref: "shp:alpine-connectors",+ status: "Voided",+ lines: [+ {+ item: "MAT-CONN-M23",+ orderQuantity: 8,+ outstandingQuantity: 8,+ shippedQuantity: 0,+ unitPrice: 45+ }+ ]+ }+ },++ // accounting.ts settles "paid" and "partial" by these sinv keys.+ {+ log: "sales invoice — Submitted (Northwind bearing spares)",+ ref: "opp:northwind-bearings",+ customer: "Northwind Electronics",+ order: {+ ref: "so:northwind-bearings",+ status: "Invoiced",+ orderDateOffset: -35,+ lines: [+ {+ ref: "soline:northwind-bearings:brg",+ item: "BRG-CRB-100",+ saleQuantity: 20,+ unitPrice: 278,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:northwind-bearings",+ key: "submitted",+ status: "Submitted",+ subtotal: 5560,+ totalAmount: 5560,+ dateIssuedOffset: -20,+ dueDateOffset: 10,+ lines: [{ item: "BRG-CRB-100", quantity: 20, unitPrice: 278 }]+ }+ },+ {+ log: "sales invoice — Overdue (Cascade spare axis motor)",+ ref: "opp:cascade-motor",+ customer: "Cascade Integration Group",+ order: {+ ref: "so:cascade-motor",+ status: "Invoiced",+ orderDateOffset: -60,+ lines: [+ {+ ref: "soline:cascade-motor:mot",+ item: "MOT-AC-200W",+ saleQuantity: 1,+ unitPrice: 465,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:cascade-motor",+ key: "overdue",+ status: "Overdue",+ subtotal: 465,+ totalAmount: 465,+ dateIssuedOffset: -45,+ dueDateOffset: -15,+ lines: [{ item: "MOT-AC-200W", quantity: 1, unitPrice: 465 }]+ }+ },+ {+ log: "sales invoice — Paid (Lakeshore stainless fastener lot)",+ ref: "opp:lakeshore-fasteners",+ customer: "Lakeshore Automotive",+ order: {+ ref: "so:lakeshore-fasteners",+ status: "Closed",+ orderDateOffset: -90,+ lines: [+ {+ ref: "soline:lakeshore-fasteners:fst",+ item: "FST-M8-SS",+ saleQuantity: 500,+ unitPrice: 1.4,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:lakeshore-fasteners",+ key: "paid",+ status: "Paid",+ subtotal: 700,+ totalAmount: 700,+ dateIssuedOffset: -75,+ dueDateOffset: -45,+ lines: [{ item: "FST-M8-SS", quantity: 500, unitPrice: 1.4 }]+ }+ },+ {+ log: "sales invoice — Partially Paid (Alpine force/torque sensor)",+ ref: "opp:alpine-sensor",+ customer: "Alpine Research Institute",+ order: {+ ref: "so:alpine-sensor",+ status: "Invoiced",+ orderDateOffset: -50,+ lines: [+ {+ ref: "soline:alpine-sensor:sns",+ item: "SNS-FT-6AX",+ saleQuantity: 1,+ unitPrice: 5100,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:alpine-sensor",+ key: "partial",+ status: "Partially Paid",+ subtotal: 5100,+ totalAmount: 5100,+ dateIssuedOffset: -38,+ dueDateOffset: -8,+ lines: [{ item: "SNS-FT-6AX", quantity: 1, unitPrice: 5100 }]+ }+ },+ {+ log: "sales invoice — Voided (Northwind M5 fasteners, wrong bill-to)",+ ref: "opp:northwind-fasteners",+ customer: "Northwind Electronics",+ order: {+ ref: "so:northwind-fasteners",+ status: "To Invoice",+ orderDateOffset: -28,+ lines: [+ {+ ref: "soline:northwind-fasteners:fst",+ item: "FST-M5-SS",+ saleQuantity: 100,+ unitPrice: 0.9,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:northwind-fasteners",+ key: "voided",+ status: "Voided",+ subtotal: 90,+ totalAmount: 90,+ dateIssuedOffset: -25,+ lines: [{ item: "FST-M5-SS", quantity: 100, unitPrice: 0.9 }]+ }+ },+ {+ log: "sales invoice — Credit Note Issued (Cascade gripper jaw sets)",+ ref: "opp:cascade-jaws",+ customer: "Cascade Integration Group",+ order: {+ ref: "so:cascade-jaws",+ status: "Closed",+ orderDateOffset: -70,+ lines: [+ {+ ref: "soline:cascade-jaws:jaw",+ item: "GRP-JAW-80",+ saleQuantity: 2,+ unitPrice: 300,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:cascade-jaws",+ key: "credit",+ status: "Credit Note Issued",+ subtotal: 600,+ totalAmount: 600,+ dateIssuedOffset: -55,+ dueDateOffset: -25,+ lines: [{ item: "GRP-JAW-80", quantity: 2, unitPrice: 300 }]+ }+ },++ // Older overdue invoices, so receivables aging fills every bucket to 61–90.+ {+ log: "sales invoice — Overdue 31–60 days (Alpine servo motors)",+ ref: "opp:alpine-motors",+ customer: "Alpine Research Institute",+ order: {+ ref: "so:alpine-motors",+ status: "Invoiced",+ orderDateOffset: -90,+ lines: [+ {+ ref: "soline:alpine-motors:mot",+ item: "MOT-AC-200W",+ saleQuantity: 4,+ unitPrice: 465,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:alpine-motors",+ status: "Overdue",+ subtotal: 1860,+ totalAmount: 1860,+ dateIssuedOffset: -75,+ dueDateOffset: -45,+ lines: [{ item: "MOT-AC-200W", quantity: 4, unitPrice: 465 }]+ }+ },+ {+ log: "sales invoice — Overdue 61–90 days (Northwind crossed-roller bearings)",+ ref: "opp:northwind-crb",+ customer: "Northwind Electronics",+ order: {+ ref: "so:northwind-crb",+ status: "Invoiced",+ orderDateOffset: -120,+ lines: [+ {+ ref: "soline:northwind-crb:brg",+ item: "BRG-CRB-100",+ saleQuantity: 10,+ unitPrice: 278,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:northwind-crb",+ status: "Overdue",+ subtotal: 2780,+ totalAmount: 2780,+ dateIssuedOffset: -105,+ dueDateOffset: -75,+ lines: [{ item: "BRG-CRB-100", quantity: 10, unitPrice: 278 }]+ }+ },++ // Each line has a job of its own in production.ts (open or just completed).+ {+ log: "sales order — In Progress (Lakeshore controller and harness spares, floor load)",+ ref: "opp:floor-lakeshore",+ customer: "Lakeshore Automotive",+ order: {+ ref: "so:floor-lakeshore",+ status: "In Progress",+ orderDateOffset: -30,+ lines: [+ {+ ref: "soline:floor-lakeshore:ctrl-pcb",+ item: "PCB-CTRL-R1",+ saleQuantity: 6,+ unitPrice: 980,+ status: "In Progress",+ promisedDateOffset: 5+ },+ {+ ref: "soline:floor-lakeshore:io-pcb",+ item: "PCB-IO-R1",+ saleQuantity: 4,+ unitPrice: 620,+ status: "In Progress",+ promisedDateOffset: 3+ },+ {+ ref: "soline:floor-lakeshore:jaw",+ item: "GRP-JAW-80",+ saleQuantity: 2,+ unitPrice: 320,+ status: "In Progress",+ promisedDateOffset: 3+ },+ {+ ref: "soline:floor-lakeshore:base",+ item: "ARM-BASE-001",+ saleQuantity: 1,+ unitPrice: 6800,+ status: "In Progress",+ promisedDateOffset: 4+ },+ {+ ref: "soline:floor-lakeshore:harness",+ item: "HRN-ARM-001",+ saleQuantity: 3,+ unitPrice: 1400,+ status: "In Progress",+ promisedDateOffset: 2+ }+ ]+ }+ },+ {+ log: "sales order — In Progress (Northwind cell retrofit kit, floor load)",+ ref: "opp:floor-northwind",+ customer: "Northwind Electronics",+ order: {+ ref: "so:floor-northwind",+ assignee: "self",+ status: "In Progress",+ orderDateOffset: -15,+ lines: [+ {+ ref: "soline:floor-northwind:io-pcb",+ item: "PCB-IO-R1",+ saleQuantity: 6,+ unitPrice: 620,+ status: "In Progress",+ promisedDateOffset: 8+ },+ {+ ref: "soline:floor-northwind:drive",+ item: "DRV-J2-MOD",+ saleQuantity: 4,+ unitPrice: 3900,+ status: "In Progress",+ promisedDateOffset: 15+ },+ {+ ref: "soline:floor-northwind:jaw",+ item: "GRP-JAW-80",+ saleQuantity: 4,+ unitPrice: 320,+ status: "In Progress",+ promisedDateOffset: 10+ },+ {+ ref: "soline:floor-northwind:wrist",+ item: "ARM-WRIST-001",+ saleQuantity: 2,+ unitPrice: 9600,+ status: "In Progress",+ promisedDateOffset: 24+ },+ {+ ref: "soline:floor-northwind:ctrl",+ item: "CTRL-100",+ saleQuantity: 1,+ unitPrice: 11500,+ status: "In Progress",+ promisedDateOffset: 19+ },+ {+ ref: "soline:floor-northwind:gripper",+ item: "GRP-2F-80",+ saleQuantity: 2,+ unitPrice: 6900,+ status: "In Progress",+ promisedDateOffset: 30+ }+ ]+ }+ }+];++// Quantities come from the posted shipments above; the Completed RMA books+// stock back into the shelf it shipped from.+export const SALES_RETURNS: SalesReturnSpec[] = [+ {+ key: "servodrive",+ credit: {+ status: "Posted",+ dateOffset: -8,+ lines: [{ line: 1, quantity: 1 }]+ },+ status: "Completed",+ customer: "Cascade Integration Group",+ returnReason: "Defective",+ dateOffset: -12,+ salesOrder: "so:cascade-drives",+ lines: [+ { item: "DRV-SRV-400", quantity: 1, unitPrice: 630, toShelf: "ESD-Cage" }+ ]+ },+ {+ key: "gearset",+ status: "To Receive",+ customer: "Lakeshore Automotive",+ returnReason: "Damaged in Transit",+ dateOffset: -5,+ salesOrder: "so:lakeshore-gearsets",+ lines: [{ item: "GBX-HD-50", quantity: 1, unitPrice: 1170 }]+ },+ {+ key: "bearings",+ status: "Draft",+ customer: "Northwind Electronics",+ returnReason: "No Longer Needed",+ dateOffset: -1,+ salesOrder: "so:northwind-bearings",+ lines: [{ item: "BRG-CRB-100", quantity: 4, unitPrice: 278 }]}];export const roboticsSales: SalesData = {opportunities: OPPORTUNITIES,statusOrders: STATUS_ORDERS,- releasedOrders: RELEASED_ORDERS+ releasedOrders: RELEASED_ORDERS,+ salesReturns: SALES_RETURNS,+ customerPortals: ["Cascade Integration Group", "Lakeshore Automotive"],+ customerBankAccounts: [+ {+ customer: "Lakeshore Automotive",+ name: "Lakeshore remittance",+ bankName: "Great Lakes Commerce Bank (demo)",+ accountHolderName: "Lakeshore Automotive Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-4102-7781",+ bankCode: "DEMO-072000",+ isPrimary: true+ },+ {+ customer: "Cascade Integration Group",+ name: "Cascade operating account",+ bankName: "Cascade Valley Bank (demo)",+ accountHolderName: "Cascade Integration Group LLC",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-3390-1142",+ bankCode: "DEMO-125000",+ isPrimary: true+ },+ {+ customer: "Northwind Electronics",+ name: "Northwind payables",+ bankName: "Northwind Savings (demo)",+ accountHolderName: "Northwind Electronics Corp.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-8813-0496",+ isPrimary: true+ },+ {+ customer: "Alpine Research Institute",+ name: "Alpine grants account",+ bankName: "Alpine Scholars Bank (demo)",+ accountHolderName: "Alpine Research Institute",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-2257-6630",+ isPrimary: true+ }+ ]};diff --git a/packages/database/src/datasets/data/robotics/workflows.ts b/packages/database/src/datasets/data/robotics/workflows.tsindex d32e287d3e..4ca537b8ba 100644--- a/packages/database/src/datasets/data/robotics/workflows.ts+++ b/packages/database/src/datasets/data/robotics/workflows.ts@@ -1,5 +1,4 @@-import type { Edge, SeedWorkflow } from "../../tiers/workflow-definitions.ts";-import type { WorkflowData } from "../../types.ts";+import type { Edge, SeedWorkflow, WorkflowData } from "../../types.ts";// A factory, not a constant: every definition names ids that only exist once the seed has run.@@ -508,6 +507,38 @@ export function buildRoboticsWorkflows(refs: {];}+// The queued run was skipped at load while the workflow was briefly unpublished,+// so it has no steps.export const roboticsWorkflows: WorkflowData = {- build: buildRoboticsWorkflows+ build: buildRoboticsWorkflows,+ runs: [+ {+ workflow: "Assign new sales orders",+ status: "Succeeded",+ triggerRef: "so:alpine-connectors",+ at: { offset: -14, time: "13:41:27" },+ steps: [{ nodeId: "action_assign", status: "Succeeded" }]+ },+ {+ workflow: "Assign new sales orders",+ status: "Failed",+ triggerRef: "so:northwind-fasteners",+ at: { offset: -28, time: "09:12:05" },+ steps: [+ {+ nodeId: "action_assign",+ status: "Failed",+ error: "The assignee you chose is not in this company."+ }+ ]+ },+ {+ workflow: "Assign new sales orders",+ status: "Skipped",+ triggerRef: "so:lakeshore-gearsets",+ at: { offset: -21, time: "16:30:48" },+ statusReason: "This workflow was unpublished before the run started.",+ steps: []+ }+ ]};diff --git a/packages/database/src/datasets/data/satellite/accounting.ts b/packages/database/src/datasets/data/satellite/accounting.tsindex f355328aa8..6c887d3892 100644--- a/packages/database/src/datasets/data/satellite/accounting.ts+++ b/packages/database/src/datasets/data/satellite/accounting.ts@@ -1,7 +1,11 @@import type {AccountingData,FixedAssetSpec,- JournalEntrySpec+ JournalEntrySpec,+ MemoSpec,+ PaymentSpec,+ PeriodCloseTaskSpec,+ ProjectSpec} from "../../types.ts";export const FIXED_ASSETS: FixedAssetSpec[] = [@@ -76,6 +80,51 @@ export const FIXED_ASSETS: FixedAssetSpec[] = [acquisitionOffset: -2617,depreciationStartOffset: -2586,accumulatedDepreciation: 48000+ },+ {+ key: "tvac",+ className: "Machinery & Equipment",+ location: "Plant",+ name: "Legacy Thermal Vacuum Chamber",+ description:+ "1.2 m TVAC chamber retired after the 2 m chamber came online; sold to a university lab",+ serialNumber: "TVAC-12-04417",+ status: "Disposed",+ depreciationMethod: "Straight Line",+ usefulLifeMonths: 120,+ residualValuePercent: 5,+ acquisitionCost: 180000,+ acquisitionOffset: -2900,+ depreciationStartOffset: -2880,+ // 171,000 / 120 = 1,425 per month x the 93 months depreciated before sale.+ // NBV 47,475 against 52,000 proceeds books a 4,525 gain.+ accumulatedDepreciation: 132525,+ disposal: { dateOffset: -50, method: "Sale", saleProceeds: 52000 }+ },+ {+ key: "laser",+ className: "Machinery & Equipment",+ location: "Plant",+ name: "Fiber Laser Cutter",+ description:+ "6 kW fiber laser for bracket and panel blanks, depreciated by cutting hours",+ serialNumber: "FLC-6K-30982",+ status: "Active",+ depreciationMethod: "Units of Production",+ usefulLifeMonths: 96,+ residualValuePercent: 0,+ acquisitionCost: 96000,+ acquisitionOffset: -120,+ depreciationStartOffset: -100,+ // 96,000 / 40,000 hours = 2.40 per hour. The first logged month (310 h)+ // was booked on registration; the run's month (420 h) is the charge.+ assetLifetimeUsage: 40000,+ accumulatedDepreciation: 744,+ usageLogs: [+ { monthsBack: 2, unitsProduced: 310 },+ { monthsBack: 1, unitsProduced: 420 }+ ],+ depreciationCharge: 1008}];@@ -105,10 +154,319 @@ export const JOURNAL_ENTRIES: JournalEntrySpec[] = [journalLineReference: "JE-SEED-001"}]+ },+ {+ ref: "journal:payroll-accrual",+ journalEntryId: "JE-SEED-002",+ description: "Payroll accrual — integration & test crew, final week",+ status: "Posted",+ postingOffset: -12,+ lines: [+ {+ account: "6060",+ description: "Accrued I&T technician wages",+ amount: 48500,+ quantity: 1,+ journalLineReference: "JE-SEED-002-1",+ dimensions: [+ { dimension: "Project", value: "orbsec-block2" },+ { dimension: "Mission Phase", value: "Integration & Test" }+ ]+ },+ {+ account: "2150",+ description: "Accrued I&T technician wages",+ amount: 48500,+ quantity: 1,+ journalLineReference: "JE-SEED-002-2"+ }+ ]+ },+ {+ ref: "journal:amortization",+ journalEntryId: "JE-SEED-003",+ description: "Monthly amortization — orbit analysis software license",+ status: "Posted",+ postingOffset: -23,+ lines: [+ {+ account: "6310",+ description: "Orbit analysis license amortization",+ amount: 1250,+ quantity: 1,+ journalLineReference: "JE-SEED-003"+ },+ {+ // A credit on the contra-asset: negative on a debit-normal class.+ account: "1420",+ description: "Orbit analysis license amortization",+ amount: -1250,+ quantity: 1,+ journalLineReference: "JE-SEED-003"+ }+ ]+ },+ {+ ref: "journal:insurance-accrual",+ journalEntryId: "JE-SEED-004",+ description:+ "Accrued launch insurance premium — duplicate of broker invoice",+ status: "Reversed",+ postingOffset: -40,+ lines: [+ {+ account: "6100",+ description: "Launch insurance premium",+ amount: 9600,+ quantity: 1,+ journalLineReference: "JE-SEED-004"+ },+ {+ account: "2140",+ description: "Launch insurance premium",+ amount: 9600,+ quantity: 1,+ journalLineReference: "JE-SEED-004"+ }+ ],+ reversal: {+ ref: "journal:insurance-accrual-reversal",+ journalEntryId: "JE-SEED-005",+ postingOffset: -33+ }+ },+ {+ ref: "journal:opening-balance",+ journalEntryId: "JE-SEED-006",+ description: "Opening balances — cutover from the legacy ledger",+ status: "Posted",+ sourceType: "Opening Balance",+ postingOffset: -242,+ lines: [+ {+ account: "1010",+ description: "Operating cash",+ amount: 2400000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-1"+ },+ {+ account: "1210",+ description: "Raw materials on hand",+ amount: 380000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-2"+ },+ {+ account: "1220",+ description: "Finished goods on hand",+ amount: 520000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-3"+ },+ {+ account: "1350",+ description: "Machinery & equipment at cost",+ amount: 1850000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-4"+ },+ {+ account: "1330",+ description: "Accumulated depreciation to date",+ amount: -410000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-5"+ },+ {+ account: "2410",+ description: "Equipment term loan",+ amount: 1200000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-6"+ },+ {+ account: "3010",+ description: "Paid-in capital",+ amount: 2000000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-7"+ },+ {+ account: "3100",+ description: "Retained earnings brought forward",+ amount: 1540000,+ quantity: 1,+ journalLineReference: "JE-SEED-006-8"+ }+ ]+ }+];++// Credit/Debit Note Issued invoices settle by their memos as zero-cash credit+// applications, the way applyCreditsToInvoices records them.+export const PAYMENTS: PaymentSpec[] = [+ {+ key: "orbsec-ach",+ type: "Receipt",+ customer: "ORBSEC Defense",+ dateOffset: -47,+ amount: 2000,+ reference: "ACH 0417-2286",+ applies: [{ invoiceKey: "paid", amount: 2000 }]+ },+ {+ key: "apex-wire",+ type: "Receipt",+ customer: "Apex Space Research",+ dateOffset: -12,+ amount: 21000,+ reference: "WIRE 88213 — milestone 1 of 2",+ applies: [{ invoiceKey: "partial", amount: 21000 }]+ },+ {+ key: "novasat-credit",+ type: "Receipt",+ customer: "NovaSat Networks",+ dateOffset: -50,+ amount: 0,+ reference: "Credit application",+ applies: [],+ credits: [{ memoKey: "novasat-valves", invoiceKey: "credit", amount: 2850 }]+ },+ {+ key: "celestial-ach",+ type: "Disbursement",+ supplier: "CelestialElex",+ dateOffset: -33,+ amount: 5610,+ reference: "ACH 1120-5561",+ applies: [{ invoiceKey: "paid", amount: 5610 }]+ },+ {+ key: "celestial-check",+ type: "Disbursement",+ supplier: "CelestialElex",+ dateOffset: -14,+ amount: 1640,+ reference: "CHK 10442",+ applies: [{ invoiceKey: "partial", amount: 1640 }]+ },+ {+ key: "proptech-debit",+ type: "Disbursement",+ supplier: "PropTech Solutions",+ dateOffset: -66,+ amount: 0,+ reference: "Debit application",+ applies: [],+ credits: [+ { memoKey: "proptech-tanks", invoiceKey: "debit-note", amount: 6400 }+ ]+ },+ {+ key: "draft-receipt",+ type: "Receipt",+ status: "Draft",+ customer: "NovaSat Networks",+ dateOffset: -1,+ amount: 4800,+ reference: "WIRE advice 4471 — propellant tank",+ applies: []+ },+ {+ key: "draft-disbursement",+ type: "Disbursement",+ status: "Draft",+ supplier: "Orbital Composites",+ dateOffset: 0,+ amount: 640,+ reference: "ACH batch 0930 — laminate",+ applies: []+ }+];++export const MEMOS: MemoSpec[] = [+ {+ key: "novasat-valves",+ direction: "Credit",+ customer: "NovaSat Networks",+ invoiceKey: "credit",+ dateOffset: -52,+ amount: 2850,+ notes:+ "Full credit — solenoid valves exceeded leak rate at NovaSat acceptance test"+ },+ {+ key: "proptech-tanks",+ direction: "Debit",+ supplier: "PropTech Solutions",+ invoiceKey: "debit-note",+ dateOffset: -70,+ amount: 6400,+ notes: "Both received propellant tanks failed weld X-ray — billing debited"+ }+];++export const PROJECTS: ProjectSpec[] = [+ {+ key: "orbsec-block2",+ name: "ORBSEC Constellation Block 2",+ description: "Eight-satellite follow-on build for ORBSEC Defense",+ purchaseInvoiceLine: { invoiceKey: "paid", item: "BAT-LIION-48V" }+ },+ {+ key: "novasat-gen3",+ name: "NovaSat Gen-3 Bus Qualification",+ description: "Qualification campaign for the next-generation bus structure"+ }+];++export const CLOSE_TASKS: PeriodCloseTaskSpec[] = [+ { definition: "Post pending operational documents", status: "Done" },+ {+ definition: "Review negative on-hand inventory",+ status: "Skipped",+ skippedReason: "Cycle count reconciled every bin at month end"+ },+ {+ definition: "Review financial statements",+ status: "Open",+ notes: "Controller to review program margin on the ORBSEC contract"}];export const satelliteAccounting: AccountingData = {fixedAssets: FIXED_ASSETS,- journalEntries: JOURNAL_ENTRIES+ journalEntries: JOURNAL_ENTRIES,+ payments: PAYMENTS,+ memos: MEMOS,+ projects: PROJECTS,+ customDimension: {+ name: "Mission Phase",+ values: ["Design & Qualification", "Integration & Test"]+ },+ closeTasks: CLOSE_TASKS,+ // EUR per 1 USD (foreign units per base unit), the same direction as the EUR purchase order's 0.92 snapshot.+ exchangeRateOverrides: [{ currencyCode: "EUR", rate: 0.9215 }],+ billingAddresses: {+ receivable: {+ addressLine1: "4500 Space Commerce Drive",+ city: "Houston",+ state: "TX",+ postalCode: "77058",+ countryCode: "US",+ phone: "+1-281-555-1140",+ email: "[email protected]"+ },+ payable: {+ addressLine1: "4500 Space Commerce Drive",+ city: "Houston",+ state: "TX",+ postalCode: "77058",+ countryCode: "US",+ phone: "+1-281-555-1150",+ email: "[email protected]"+ }+ }};diff --git a/packages/database/src/datasets/data/satellite/assembly.ts b/packages/database/src/datasets/data/satellite/assembly.tsindex fb8b379c36..ee1024f0fb 100644--- a/packages/database/src/datasets/data/satellite/assembly.ts+++ b/packages/database/src/datasets/data/satellite/assembly.ts@@ -8,12 +8,15 @@ export const satelliteAssembly: AssemblySpec = {name: "Radial Engine — Build Sequence",item: "SAT-1000",componentCount: 266,+ // The Assembly operation of the SAT-1000 method.+ operation: 1,steps: [{title: "Set the crankcase in the stand",instruction:"Mount the crankcase in the rotating stand with the rear face up. Blow out every oil gallery and confirm each one passes air before anything closes over it — a blocked gallery is undetectable once the case is built.",- componentNodeIds: ["3bc7311d9d4c8ffc"]+ componentNodeIds: ["3bc7311d9d4c8ffc"],+ materials: [{ item: "BUS-STR-001", quantity: 1 }]},{title: "Install the master rod and piston assembly",@@ -25,7 +28,8 @@ export const satelliteAssembly: AssemblySpec = {title: "Close the crankcase cover",instruction:"Fit the cover with a new gasket and pull the nuts down in a criss-cross pattern in three passes. Re-check crank rotation after the final pass; if it stiffened, the case is pinching and the cover comes back off.",- componentNodeIds: ["95451b53f10c23c3"]+ componentNodeIds: ["95451b53f10c23c3"],+ tools: [{ item: "TL-TORQUE-J1", quantity: 1 }]},{title: "Fit the cam ring housing and its five followers",@@ -38,7 +42,8 @@ export const satelliteAssembly: AssemblySpec = {"c075111ec89c6304","2943e2036cf12fe5","8532047e4eda94e0"- ]+ ],+ materials: [{ item: "ADCS-001", quantity: 1 }]},{title: "Fit the five cylinder barrels",@@ -97,7 +102,9 @@ export const satelliteAssembly: AssemblySpec = {title: "Fit the front cover",instruction:"Close the front cover onto the nose case with a new gasket, pulling the fasteners down evenly. Turn the crank before and after: any change in drag means the cover is loading the cam drive and it comes back off.",- componentNodeIds: ["3d5308ee67a8d612"]+ componentNodeIds: ["3d5308ee67a8d612"],+ materials: [{ item: "CN-MLI-001", quantity: 1 }],+ tools: [{ item: "TL-TORQUE-J1", quantity: 1 }]},{title: "Fit the nose cone and turn the engine over",@@ -105,5 +112,22 @@ export const satelliteAssembly: AssemblySpec = {"Fit the nose cone last. Turn the engine through two full revolutions by hand feeling for the five compression peaks — five even peaks and no hard stop is the sign-off for this assembly.",componentNodeIds: ["7018fb918f1b1be6"]}+ ],+ componentMappings: [+ // model part "crankcase"+ {+ geometryHash: "15659b0b141103c3add155554c80d66c3ed0fcb1",+ item: "BUS-STR-001"+ },+ // model part "central spur gear"+ {+ geometryHash: "85a63cb31d05831b69fa9cef44cc604b498fdab5",+ item: "ADCS-001"+ },+ // model part "crankcase cover"+ {+ geometryHash: "9d3858a52412e910cefde30f0a9ed9ec20f9e63a",+ item: "CN-MLI-001"+ }]};diff --git a/packages/database/src/datasets/data/satellite/change-orders.ts b/packages/database/src/datasets/data/satellite/change-orders.tsindex 61e5ceae36..df1dbbd0a0 100644--- a/packages/database/src/datasets/data/satellite/change-orders.ts+++ b/packages/database/src/datasets/data/satellite/change-orders.ts@@ -63,6 +63,73 @@ export const CHANGE_ORDERS: ChangeOrderSpec[] = [sortOrder: 1}]+ },+ // Lifecycle-only notices: no affected items yet (every change type spins a+ // method draft), so they exercise the stage flow + action tasks alone.+ {+ ref: "co:start",+ name: "Relocate EPS connector bracket to clear harness bend radius",+ type: "Engineering",+ changeOrderType: "Design Improvement",+ status: "Start",+ priority: "Medium",+ openDateOffset: -9,+ dueDateOffset: 30,+ reasonForChange:+ "Integration found the EPS harness exceeds its minimum bend radius at the current bracket location.",+ affectedItems: [],+ actionTasks: [+ { action: "Engineering Review", status: "In Progress", dueDateOffset: 5 },+ { action: "Update Drawings / CAD", status: "Pending", dueDateOffset: 20 }+ ]+ },+ {+ ref: "co:eng-complete",+ name: "Add girth-weld UT to the propellant tank receiving plan",+ type: "Manufacturing",+ changeOrderType: "Quality / Reliability Improvement",+ status: "Engineering Complete",+ priority: "High",+ openDateOffset: -70,+ dueDateOffset: 14,+ reasonForChange:+ "The PropTech tank escape showed visual weld inspection alone cannot catch sub-minimum wall thickness.",+ nonConformance: "ncr:tank-wall",+ affectedItems: [],+ actionTasks: [+ {+ action: "Quality Review",+ status: "Completed",+ dueDateOffset: -45,+ completedOffset: -48+ },+ {+ action: "Notify Affected Parties",+ status: "In Progress",+ dueDateOffset: 7+ }+ ]+ },+ {+ ref: "co:cancelled",+ name: "Update star tracker ICD for the revised mounting pattern",+ type: "Documentation",+ changeOrderType: "Documentation Error / Correction",+ status: "Cancelled",+ priority: "Low",+ openDateOffset: -120,+ reasonForChange:+ "Vendor proposed a new ST-050 bolt pattern; they later withdrew it and kept the heritage interface.",+ affectedItems: [],+ actionTasks: [+ {+ action: "Cost Impact Review",+ status: "Completed",+ dueDateOffset: -110,+ completedOffset: -112+ },+ { action: "Update Drawings / CAD", status: "Skipped" }+ ]}];diff --git a/packages/database/src/datasets/data/satellite/foundation.ts b/packages/database/src/datasets/data/satellite/foundation.tsindex b53d84d38b..bb0dcbb019 100644--- a/packages/database/src/datasets/data/satellite/foundation.ts+++ b/packages/database/src/datasets/data/satellite/foundation.ts@@ -1,13 +1,19 @@import type {ContractorAgencySpec,+ EmployeeJobSpec,FoundationData,+ HolidaySpec,+ MaterialTaxonomySpec,+ PartnerSpec,PlantSpec,PrinterRouteSpec,ProcedureSpec,ProcedureStepSpec,ShelfSpec,ShiftSpec,- WarehouseSpec+ TagSpec,+ WarehouseSpec,+ WorkCenterSpec} from "../../types.ts";// ---------------------------------------------------------------------------@@ -116,6 +122,25 @@ export const WORK_CENTER_PROCESS_LINKS: Array<[string, string]> = [["Potting Station", "Clean Room Assembly"]];+export const WORK_CENTER_SHIFTS: Array<[string, string]> = [+ ["CNC Mill", "Day Shift"],+ ["TIG Welder Cell", "Day Shift"],+ ["Clean Room Bay A", "Day Shift"],+ ["Clean Room Bay A", "Swing Shift"],+ ["PCB Lab", "Day Shift"],+ ["TVAC Chamber 1", "Day Shift"],+ ["TVAC Chamber 1", "Swing Shift"],+ ["QC Bench", "Day Shift"],+ ["Potting Station", "Day Shift"]+];++export const EMPLOYEE_JOB: EmployeeJobSpec = {+ title: "Production Supervisor",+ department: "Manufacturing",+ shift: "Day Shift",+ startDateOffset: -1140+};+export const PLANT: PlantSpec = {name: "Manufacturing Plant",addressLine1: "4500 Space Commerce Drive",@@ -307,6 +332,37 @@ export const SUPPLIERS = [type: "Contract Manufacturer",phone: "+1-972-555-1000",website: "https://astromill.com"+ },+ // Status showcases + the EUR vendor. None of these may be referenced by+ // purchasing data — they exist so every supplier status renders somewhere.+ {+ name: "Legacy Harness Co",+ type: "Hardware",+ phone: "+1-720-555-1200",+ website: "https://legacyharness.com",+ status: "Inactive" as const+ },+ {+ name: "Ionix Thrusters",+ type: "Propulsion",+ phone: "+1-425-555-1300",+ website: "https://ionixthrusters.com",+ status: "Pending" as const+ },+ {+ name: "BargainSat Components",+ type: "Electronics",+ phone: "+1-702-555-1400",+ website: "https://bargainsat.com",+ status: "Rejected" as const+ },+ {+ name: "Rheinland Precision Bearings GmbH",+ type: "Hardware",+ phone: "+49-711-555-1500",+ website: "https://rheinland-bearings.de",+ status: "Active" as const,+ currencyCode: "EUR"}];@@ -352,6 +408,34 @@ export const SUPPLIER_CONTACTS = [lastName: "Brooks",email: "[email protected]",title: "Account Rep"+ },+ {+ supplier: "Legacy Harness Co",+ firstName: "Pat",+ lastName: "Whitfield",+ email: "[email protected]",+ title: "Sales Manager"+ },+ {+ supplier: "Ionix Thrusters",+ firstName: "Naomi",+ lastName: "Fedorova",+ email: "[email protected]",+ title: "Business Development"+ },+ {+ supplier: "BargainSat Components",+ firstName: "Gary",+ lastName: "Duncan",+ email: "[email protected]",+ title: "Account Executive"+ },+ {+ supplier: "Rheinland Precision Bearings GmbH",+ firstName: "Katrin",+ lastName: "Vogel",+ email: "[email protected]",+ title: "Export Sales"}];@@ -363,6 +447,28 @@ export const SUPPLIER_PROCESSES = [{ supplier: "AstroMill Machining", process: "Outside Processing" }];+export const PARTNERS: PartnerSpec[] = [+ {+ supplier: "AstroMill Machining",+ ability: "CNC Operation",+ hoursPerWeek: 40+ },+ { supplier: "AstroMill Machining", ability: "Welding", hoursPerWeek: 16 },+ {+ supplier: "Orbital Composites",+ ability: "Composite Layup",+ hoursPerWeek: 24+ }+];++export const HQ_WORK_CENTER: WorkCenterSpec = {+ name: "Flatsat Test Lab",+ dept: "Engineering",+ ability: "Inspection",+ laborRate: 80,+ machineRate: 25+};+export const CONTRACTORS = [{firstName: "Rafael",@@ -423,10 +529,15 @@ export const PROCEDURES: ProcedureSpec[] = [process: "Clean Room Assembly",description:"Assembly and torque procedure for the ESPA-class structural frame.",+ parameters: [+ { key: "Corner fastener torque", value: "9 N·m (M6 A286)" },+ { key: "Diagonal squareness limit", value: "0.5 mm" },+ { key: "Thread locker", value: "None — safety-wired per NASA-STD-5020" }+ ],versions: [{version: 1,- status: "Draft",+ status: "Archived",steps: [{name: "Verify panel kit against the pick list",@@ -444,7 +555,7 @@ export const PROCEDURES: ProcedureSpec[] = [}]},- { version: 2, status: "Draft", steps: STRUCTURAL_STEPS_V2 }+ { version: 2, status: "Active", steps: STRUCTURAL_STEPS_V2 }]},{@@ -455,7 +566,7 @@ export const PROCEDURES: ProcedureSpec[] = [versions: [{version: 1,- status: "Draft",+ status: "Active",steps: [{name: "Stage subsystems in the clean room",@@ -499,6 +610,11 @@ export const PROCEDURES: ProcedureSpec[] = [process: "Thermal Vacuum Test",description:"Thermal vacuum qualification cycle for an integrated satellite bus.",+ parameters: [+ { key: "Thermal cycles", value: "8" },+ { key: "Chamber pressure", value: "≤ 1×10⁻⁵ Torr" },+ { key: "Plateau dwell", value: "4 h hot / 4 h cold" }+ ],versions: [{version: 1,@@ -530,6 +646,26 @@ export const PROCEDURES: ProcedureSpec[] = [type: "Checkbox",instruction:"Command the bus through the functional script during the final hot dwell and confirm all telemetry is nominal."+ },+ {+ name: "Stamp chamber break time",+ type: "Timestamp",+ instruction:+ "Record the moment the chamber is vented back to ambient — the 24-hour outgassing bake clock starts here."+ },+ {+ name: "Attach thermal profile export",+ type: "File",+ instruction:+ "Export the full temperature/pressure profile from the chamber DAQ and attach it to the test record.",+ fileTypes: ["csv", "pdf"]+ },+ {+ name: "Post-test workmanship inspection",+ type: "Inspection",+ instruction:+ "Inspect harness lacing, thermocouple bond points and MLI closeouts for cycling damage. Photograph any finding.",+ required: false}]}@@ -573,11 +709,69 @@ export const NO_QUOTE_REASONS = ["Strategic Hold"];+// Offsets are positive (upcoming) and distinct — holiday has UNIQUE (date).+export const HOLIDAYS: HolidaySpec[] = [+ { name: "Company Founding Day", dateOffset: 40 },+ { name: "Launch Campaign Recognition Day", dateOffset: 100 },+ { name: "Year-End Shutdown", dateOffset: 160 }+];++export const TAGS: TagSpec[] = [+ { name: "Flight Critical", table: "operation" },+ { name: "ITAR Controlled", table: "procedure" },+ { name: "Clean Room Certified", table: "training" },+ { name: "Low Outgassing", table: "material" },+ { name: "Calibrated", table: "tool" }+];++// Names deliberately avoid the GLOBAL substances/forms migrations seed (Steel,+// Aluminum, Sheet, Plate, …) so the settings screens don't show duplicates.+export const MATERIAL_TAXONOMY: MaterialTaxonomySpec = {+ substances: [+ { name: "Carbon Fiber Composite", code: "CFRP" },+ // Backs the Kapton tape classification on MAT-KAPTON (items.ts).+ { name: "Polyimide Film", code: "PI" }+ ],+ forms: [+ { name: "Honeycomb Panel", code: "HCPANEL" },+ { name: "Film Roll", code: "FILMROLL" }+ ],+ types: [+ {+ name: "CFRP Honeycomb Panel",+ code: "CFRP-HC",+ substance: "Carbon Fiber Composite",+ form: "Honeycomb Panel"+ },+ {+ name: "Polyimide Tape Roll",+ code: "PI-ROLL",+ substance: "Polyimide Film",+ form: "Film Roll"+ }+ ],+ grades: [+ { name: "M55J", substance: "Carbon Fiber Composite" },+ { name: "T300", substance: "Carbon Fiber Composite" },+ { name: "Kapton HN", substance: "Polyimide Film" }+ ],+ finishes: [+ { name: "Low-Outgassing Coating", substance: "Carbon Fiber Composite" },+ { name: "Silicone Adhesive Backing", substance: "Polyimide Film" }+ ],+ dimensions: [+ { name: "1200 x 2400 x 25mm", form: "Honeycomb Panel", isMetric: true },+ { name: "600 x 600 x 10mm", form: "Honeycomb Panel", isMetric: true },+ { name: "25mm x 33m", form: "Film Roll", isMetric: true }+ ]+};+export const satelliteFoundation: FoundationData = {departments: DEPT_NAMES,abilities: ABILITIES,processes: PROCESSES,workCenters: WORK_CENTERS,+ hqWorkCenter: HQ_WORK_CENTER,customers: CUSTOMERS,customerContacts: CUSTOMER_CONTACTS,suppliers: SUPPLIERS,@@ -593,12 +787,18 @@ export const satelliteFoundation: FoundationData = {costCenters: COST_CENTERS,noQuoteReasons: NO_QUOTE_REASONS,contractors: CONTRACTORS,+ partners: PARTNERS,plant: PLANT,shifts: SHIFTS,+ workCenterShifts: WORK_CENTER_SHIFTS,+ employeeJob: EMPLOYEE_JOB,warehouses: WAREHOUSES,storageTypes: STORAGE_TYPES,shelves: SHELVES,printerRoute: PRINTER_ROUTE,+ holidays: HOLIDAYS,+ tags: TAGS,+ materialTaxonomy: MATERIAL_TAXONOMY,defaultShippingMethod: "UPS Ground",contractorAgency: CONTRACTOR_AGENCY,partyAddressCity: "Houston",diff --git a/packages/database/src/datasets/data/satellite/index.ts b/packages/database/src/datasets/data/satellite/index.tsindex 81d628eaa2..3f6413d234 100644--- a/packages/database/src/datasets/data/satellite/index.ts+++ b/packages/database/src/datasets/data/satellite/index.ts@@ -4,6 +4,7 @@ import { satelliteChangeOrders } from "./change-orders.ts";import { satelliteFoundation } from "./foundation.ts";import { satelliteInventory } from "./inventory.ts";import { satelliteItems } from "./items.ts";+import { satelliteOps } from "./ops.ts";import { satellitePlanning } from "./planning.ts";import { satelliteProduction } from "./production.ts";import { satellitePurchasing } from "./purchasing.ts";@@ -28,6 +29,7 @@ export const satellite: Dataset = {quality: satelliteQuality,changeOrders: satelliteChangeOrders,accounting: satelliteAccounting,+ ops: satelliteOps,workflows: satelliteWorkflows,planning: satellitePlanning};diff --git a/packages/database/src/datasets/data/satellite/inventory.ts b/packages/database/src/datasets/data/satellite/inventory.tsindex b88b983278..fd05055216 100644--- a/packages/database/src/datasets/data/satellite/inventory.ts+++ b/packages/database/src/datasets/data/satellite/inventory.ts@@ -3,7 +3,10 @@ import type {InventoryData,KanbanItemSpec,OpeningStockSpec,- TrackedStockSpec+ ShelfLifeSpec,+ StockTransferSpec,+ TrackedStockSpec,+ WarehouseTransferSpec} from "../../types.ts";// Opening inventory — realistic quantities for a smallsat shop.@@ -20,23 +23,24 @@ export const OPENING_STOCK: OpeningStockSpec[] = [{ item: "FST-M4-TI", qty: 500, shelf: "A1-L1" },{ item: "FST-M6-A286", qty: 200, shelf: "A1-L1" },{ item: "BRG-6201", qty: 24, shelf: "A1-L3" },- { item: "MAT-AL7075-PLT", qty: 60, shelf: "A2-L1" },+ { item: "MAT-AL7075-PLT", qty: 64, shelf: "A2-L1" },{ item: "MAT-CF-LAM", qty: 10, shelf: "CleanRoom" },{ item: "MAT-GAAS-CELL", qty: 256, shelf: "CleanRoom" },{ item: "MAT-KAPTON", qty: 50, shelf: "A1-L3" },{ item: "MAT-SYLGARD", qty: 5, shelf: "A2-L1" },{ item: "MAT-CONFCOAT", qty: 12, shelf: "A2-L1" },{ item: "CN-MLI-001", qty: 4, shelf: "CleanRoom" },- { item: "CN-GREASE-001", qty: 2, shelf: "A1-L3" }+ { item: "CN-GREASE-001", qty: 3, shelf: "A1-L3" }];-// Lots/serials that back the tracked slice of the opening stock above.+// Backs the tracked slice of the opening stock above.export const ON_HAND_TRACKED: TrackedStockSpec[] = [{item: "BAT-LIION-48V",entities: [{ readableId: "LOT-BAT-2607", quantity: 2 },- { readableId: "LOT-BAT-2608", quantity: 1 }+ { readableId: "LOT-BAT-2608", quantity: 1, expiresOffset: 30 },+ { readableId: "LOT-BAT-2609", quantity: 1, status: "On Hold" }]},{@@ -52,26 +56,189 @@ export const ON_HAND_TRACKED: TrackedStockSpec[] = [item: "MAT-AL7075-PLT",entities: [{ readableId: "LOT-AL7075-2608", quantity: 40 },- { readableId: "LOT-AL7075-2609", quantity: 20 }+ { readableId: "LOT-AL7075-2609", quantity: 20 },+ { readableId: "LOT-AL7075-2610", quantity: 2, status: "Rejected" },+ {+ readableId: "LOT-AL7075-2604",+ quantity: 4,+ status: "Scrapped",+ scrap: {+ shelf: "A2-L1",+ reason: "Damaged",+ dateOffset: -34,+ comment: "Plates bent past flatness tolerance in a forklift drop"+ }+ }]}];-// Kanbans (auto-replenishment cards) for high-usage buy parts.+// LOT-BAT-2608 above expires in 30 days so the expiry chips show amber.+export const SHELF_LIVES: ShelfLifeSpec[] = [+ { item: "BAT-LIION-48V", days: 365 }+];+export const KANBAN_ITEMS: KanbanItemSpec[] = [{ item: "FST-M4-TI", qty: 200, supplier: "SpaceGrade Fasteners" },{ item: "FST-M6-A286", qty: 100, supplier: "SpaceGrade Fasteners" },- { item: "PCB-BARE-REV3", qty: 10, supplier: "CelestialElex" }+ { item: "PCB-BARE-REV3", qty: 10, supplier: "CelestialElex" },+ { item: "BUS-STR-001", qty: 2, replenishmentSystem: "Make" },+ {+ item: "MAT-KAPTON",+ qty: 10,+ replenishmentSystem: "Transfer",+ fromShelf: "A1-L3",+ toShelf: "CleanRoom"+ }];-export const INVENTORY_COUNT: InventoryCountSpec = {- status: "Draft",- notes: "Quarterly physical count — Q3"-};+export const INVENTORY_COUNTS: InventoryCountSpec[] = [+ {+ // The first six opening-stock rows.+ key: "q3-draft",+ status: "Draft",+ notes: "Quarterly physical count — Q3",+ lines: [+ {+ item: "BAT-LIION-48V",+ shelf: "A1-L2",+ snapshotQuantity: 3,+ countedQuantity: 3+ },+ {+ item: "PCB-BARE-REV3",+ shelf: "A1-L1",+ snapshotQuantity: 20,+ countedQuantity: 20+ },+ {+ item: "RW-010",+ shelf: "A2-L2",+ snapshotQuantity: 4,+ countedQuantity: 4+ },+ {+ item: "ST-050",+ shelf: "A2-L3",+ snapshotQuantity: 2,+ countedQuantity: 2+ },+ {+ item: "TXRX-SBAND",+ shelf: "A2-L2",+ snapshotQuantity: 3,+ countedQuantity: 3+ },+ {+ item: "THR-HYDRA-1N",+ shelf: "A3-L1",+ snapshotQuantity: 4,+ countedQuantity: 4+ }+ ]+ },+ {+ key: "aug-cycle",+ status: "Posted",+ notes: "Cycle count — fastener & hardware bins",+ postedOffset: -20,+ lines: [+ {+ item: "FST-M4-TI",+ shelf: "A1-L1",+ snapshotQuantity: 500,+ countedQuantity: 498+ },+ {+ item: "FST-M6-A286",+ shelf: "A1-L1",+ snapshotQuantity: 200,+ countedQuantity: 200+ },+ {+ item: "BRG-6201",+ shelf: "A1-L3",+ snapshotQuantity: 24,+ countedQuantity: 26+ },+ {+ item: "MAT-KAPTON",+ shelf: "A1-L3",+ snapshotQuantity: 50,+ countedQuantity: 50+ },+ {+ item: "VLV-SOLENOID-LP",+ shelf: "A3-L2",+ snapshotQuantity: 8,+ countedQuantity: 8+ }+ ]+ }+];++// Only the Completed move changes stock, so it's dated after the posted count above.+export const STOCK_TRANSFERS: StockTransferSpec[] = [+ {+ key: "st-completed",+ status: "Completed",+ fromShelf: "A1-L1",+ toShelf: "A1-L2",+ dateOffset: -10,+ lines: [{ item: "FST-M4-TI", quantity: 50 }]+ },+ {+ key: "st-released",+ status: "Released",+ fromShelf: "A1-L1",+ toShelf: "CleanRoom",+ dateOffset: -1,+ lines: [{ item: "FST-M6-A286", quantity: 20 }]+ },+ {+ key: "st-draft",+ status: "Draft",+ fromShelf: "A3-L2",+ toShelf: "A3-L3",+ dateOffset: 0,+ lines: [{ item: "VLV-SOLENOID-LP", quantity: 2 }]+ }+];++// HQ has no bins, so completed receipts land shelfless.+export const WAREHOUSE_TRANSFERS: WarehouseTransferSpec[] = [+ {+ key: "wt-completed",+ status: "Completed",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: -12,+ lines: [{ item: "FST-M6-A286", quantity: 25, fromShelf: "A1-L1" }]+ },+ {+ key: "wt-toship",+ status: "To Ship",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: 0,+ lines: [{ item: "MAT-KAPTON", quantity: 5, fromShelf: "A1-L3" }]+ },+ {+ key: "wt-draft",+ status: "Draft",+ fromLocation: "Plant",+ toLocation: "HQ",+ dateOffset: 2,+ lines: [{ item: "BRG-6201", quantity: 4, fromShelf: "A1-L3" }]+ }+];export const satelliteInventory: InventoryData = {openingStock: OPENING_STOCK,onHandTracked: ON_HAND_TRACKED,kanbanItems: KANBAN_ITEMS,- inventoryCount: INVENTORY_COUNT+ inventoryCounts: INVENTORY_COUNTS,+ shelfLives: SHELF_LIVES,+ stockTransfers: STOCK_TRANSFERS,+ warehouseTransfers: WAREHOUSE_TRANSFERS};diff --git a/packages/database/src/datasets/data/satellite/items.ts b/packages/database/src/datasets/data/satellite/items.tsindex a44ac87688..7d9b1bf4a3 100644--- a/packages/database/src/datasets/data/satellite/items.ts+++ b/packages/database/src/datasets/data/satellite/items.ts@@ -1,9 +1,19 @@-import type { ItemSpec } from "../../helpers/items.ts";import type {+ BatchPropertySpec,+ ConfigurationSpec,+ CustomerPartSpec,+ EnforcementRuleSpec,+ InspectionPlanSpec,+ ItemSpec,ItemsData,MakeMethodSpec,+ PriceOverrideSpec,+ PricingRuleSpec,+ RevisionLadderSpec,+ SupersessionSpec,SupplierLinkSpec} from "../../types.ts";+import { satelliteAssembly } from "./assembly.ts";// ---------------------------------------------------------------------------// Satellite item catalog for Orbital Systems Inc.@@ -121,6 +131,16 @@ export const BUY_PARTS: ItemSpec[] = [standardCost: 18,unitSalePrice: 27,leadTime: 10+ },+ // Deliberately absent from every BOM: job creation and picking redirect to it via SUPERSESSIONS.+ {+ readableId: "VLV-SOLENOID-LP2",+ name: "Solenoid Valve Low-Pressure Gen2",+ type: "Part",+ replenishment: "Buy",+ standardCost: 1050,+ unitSalePrice: 1575,+ leadTime: 30}];@@ -140,7 +160,13 @@ export const MATERIALS: ItemSpec[] = [type: "Material",standardCost: 320,unitOfMeasureCode: "EA",- leadTime: 21+ leadTime: 21,+ // Partially classified on purpose.+ material: {+ substance: "Carbon Fiber Composite",+ grade: "M55J",+ finish: "Low-Outgassing Coating"+ }},{readableId: "MAT-GAAS-CELL",@@ -156,7 +182,15 @@ export const MATERIALS: ItemSpec[] = [type: "Material",standardCost: 45,unitOfMeasureCode: "YD",- leadTime: 7+ leadTime: 7,+ material: {+ substance: "Polyimide Film",+ form: "Film Roll",+ materialType: "Polyimide Tape Roll",+ grade: "Kapton HN",+ finish: "Silicone Adhesive Backing",+ dimension: "25mm x 33m"+ }},{readableId: "MAT-SYLGARD",@@ -228,7 +262,7 @@ export const MAKE_PARTS: ItemSpec[] = [replenishment: "Make",// Serial-tracked: each satellite gets its own genealogy in traceability.trackingType: "Serial",- standardCost: 0,+ standardCost: 990000,unitSalePrice: 1800000},{@@ -236,7 +270,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Structural Frame Assembly",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 24750,unitSalePrice: 45000},{@@ -244,7 +278,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Electrical Power Subsystem",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 66000,unitSalePrice: 120000},{@@ -252,7 +286,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Solar Array Wing",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 19250,unitSalePrice: 35000},{@@ -260,7 +294,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "EPS Control PCB Assembly",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 2310,unitSalePrice: 4200},{@@ -268,7 +302,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Attitude Determination & Control System",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 52250,unitSalePrice: 95000},{@@ -276,7 +310,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "ADCS Electronics Board",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 3190,unitSalePrice: 5800},{@@ -284,7 +318,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Communications Subsystem",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 15400,unitSalePrice: 28000},{@@ -292,7 +326,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Patch Antenna S-Band",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 990,unitSalePrice: 1800},{@@ -300,7 +334,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Propulsion Module",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 20900,unitSalePrice: 38000},{@@ -308,7 +342,7 @@ export const MAKE_PARTS: ItemSpec[] = [name: "Spacecraft Wiring Harness",type: "Part",replenishment: "Make",- standardCost: 0,+ standardCost: 6600,unitSalePrice: 12000}];@@ -333,13 +367,20 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "CNC Mill",description: "Machine structural panels",order: 1,- laborTime: 4+ setupTime: 0.75,+ laborTime: 4,+ machineTime: 3.5,+ parameters: [+ { key: "Fixture", value: "FX-BUS-PANEL-01" },+ { key: "Coolant", value: "Flood — water-soluble" }+ ]},{process: "Welding",workCenter: "TIG Welder Cell",description: "Weld bracket assemblies",order: 2,+ setupTime: 0.5,laborTime: 2},// Sent out to AstroMill for hard anodize between welding and assembly.@@ -361,7 +402,12 @@ export const METHODS: MakeMethodSpec[] = [order: 4,laborTime: 3,// Gives the MES operation screen an Instructions tab with real steps.- procedure: "procedure:Structural Frame Assembly"+ procedure: "procedure:Structural Frame Assembly",+ tools: [{ tool: "TL-TORQUE-J1", quantity: 1 }],+ parameters: [+ { key: "Torque Spec", value: "9 Nm, star pattern" },+ { key: "Cleanliness Class", value: "ISO 7" }+ ]}]},@@ -378,7 +424,9 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "Clean Room Bay A",description: "Layup solar array substrate",order: 1,- laborTime: 6+ setupTime: 0.5,+ laborTime: 6,+ machineTime: 4},{process: "Clean Room Assembly",@@ -423,7 +471,9 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "QC Bench",description: "Flying probe test",order: 3,- laborTime: 1+ laborTime: 1,+ operationType: "Inspection",+ inspectionPlan: "EPS-PCB-FPT"}]},@@ -439,7 +489,9 @@ export const METHODS: MakeMethodSpec[] = [workCenter: "PCB Lab",description: "SMT placement & reflow",order: 1,- laborTime: 1.5+ setupTime: 0.5,+ laborTime: 1.5,+ machineTime: 0.25},{process: "Potting & Conformal Coat",@@ -716,10 +768,246 @@ export const SUPPLIER_LINKS: SupplierLinkSpec[] = [leadTime: 45},{ supplier: "Deep Space RF", item: "RW-010", price: 14500, leadTime: 90 },- { supplier: "Deep Space RF", item: "ST-050", price: 28000, leadTime: 120 }+ { supplier: "Deep Space RF", item: "ST-050", price: 28000, leadTime: 120 },+ {+ supplier: "PropTech Solutions",+ item: "VLV-SOLENOID-LP2",+ price: 1050,+ leadTime: 30+ }+];++// PROP-001 still names VLV-SOLENOID-LP (8 on shelf A3-L2), so Consume First+// keeps pulling the old valve until the shelf is empty, then swaps to Gen2.+export const SUPERSESSIONS: SupersessionSpec[] = [+ {+ predecessor: "VLV-SOLENOID-LP",+ successor: "VLV-SOLENOID-LP2",+ mode: "Consume First",+ successorEffectivityOffset: -14+ }+];++export const CUSTOMER_PARTS: CustomerPartSpec[] = [+ {+ item: "SAT-1000",+ customer: "ORBSEC Defense",+ customerPartId: "ORB-BUS-4400",+ customerRevision: "C"+ },+ {+ item: "EPS-001",+ customer: "NovaSat Networks",+ customerPartId: "NS-PWR-201"+ }+];++export const PRICE_OVERRIDES: PriceOverrideSpec[] = [+ {+ item: "SAT-1000",+ customer: "NovaSat Networks",+ notes: "FY constellation block-buy pricing per MSA amendment 3.",+ breaks: [+ { quantity: 1, overridePrice: 1750000 },+ { quantity: 3, overridePrice: 1690000 }+ ]+ }+];++export const PRICING_RULES: PricingRuleSpec[] = [+ {+ name: "ORBSEC program discount",+ ruleType: "Discount",+ amountType: "Percentage",+ amount: 5,+ customer: "ORBSEC Defense",+ minQuantity: 2,+ priority: 10+ },+ {+ name: "Commercial operator spares markup",+ ruleType: "Markup",+ amountType: "Percentage",+ amount: 12,+ customerType: "Commercial",+ items: ["TXRX-SBAND", "THR-HYDRA-1N", "RW-010"],+ priority: 5+ },+ {+ name: "Flight fastener lot break",+ ruleType: "Discount",+ amountType: "Fixed",+ amount: 0.25,+ items: ["FST-M4-TI", "FST-M6-A286"],+ minQuantity: 250,+ priority: 1+ }+];++export const CONFIGURATION: ConfigurationSpec = {+ item: "SAT-1000",+ group: "Mission Configuration",+ parameters: [+ { key: "payload_mass_kg", label: "Payload Mass (kg)", dataType: "numeric" },+ {+ key: "orbit_regime",+ label: "Orbit Regime",+ dataType: "list",+ listOptions: ["LEO", "SSO", "GTO"]+ },+ {+ key: "propulsion_module",+ label: "Include Propulsion Module",+ dataType: "boolean"+ }+ ],+ rules: [+ {+ target: { component: "PROP-001" },+ field: "quantity",+ code: "return params.propulsion_module ? 1 : 0;"+ },+ {+ target: { operation: 2 },+ field: "laborTime",+ code: 'return params.orbit_regime === "GTO" ? 96 : 72;'+ }+ ]+};++export const REVISION_LADDER: RevisionLadderSpec[] = [+ {+ item: "ANT-PATCH-01",+ obsoleteRevision: "A",+ nextRevision: "B",+ nextStatus: "Prototype"+ }+];++// A sampling plan of its own makes the MES open an inspection lot, not a plain operation.+export const INSPECTION_PLANS: InspectionPlanSpec[] = [+ {+ key: "EPS-PCB-FPT",+ item: "PCB-EPS-R1",+ drawingNumber: "EPS-CTL-200 Rev D",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "3V3 bus regulation under 2 A load",+ nominalValue: "3.300",+ tolerancePlus: "0.050",+ toleranceMinus: "0.050",+ unit: "V"+ },+ {+ label: "2",+ description: "Battery charge FET gate threshold",+ nominalValue: "2.10",+ tolerancePlus: "0.25",+ toleranceMinus: "0.25",+ unit: "V"+ }+ ]+ }+];++export const ENFORCEMENT_RULES: EnforcementRuleSpec[] = [+ {+ family: "sales",+ name: "ITAR spacecraft — US ship-to only",+ description: "22 CFR 120: the bus and ADCS are defense articles.",+ message:+ "ITAR-controlled hardware can only ship to a US address. Route export requests through Trade Compliance.",+ severity: "error",+ surfaces: ["salesOrderLine", "salesInvoiceLine"],+ match: "all",+ conditions: [+ { field: "customer.location.countryCode", op: "in", value: ["US"] }+ ],+ items: ["SAT-1000", "ADCS-001"]+ },+ {+ family: "sales",+ name: "Research orders need program sign-off",+ message:+ "Flight subsystems quoted to a research institution need program office sign-off before pricing is released.",+ severity: "warn",+ surfaces: ["quoteLine", "salesOrderLine"],+ match: "all",+ conditions: [+ {+ field: "customer.customerTypeId",+ op: "notIn",+ value: { customerTypes: ["Research"] }+ }+ ],+ items: ["EPS-001", "COMMS-001"]+ },+ {+ family: "storage",+ targetType: "item",+ name: "Flight electronics stay at the plant",+ message:+ "Flight electronics are stored at the Houston plant only — pick a plant bin.",+ severity: "warn",+ surfaces: ["receipt", "stockTransfer"],+ match: "all",+ conditions: [+ {+ field: "storageUnit.locationId",+ op: "eq",+ value: { location: "Plant" }+ }+ ],+ items: ["TXRX-SBAND", "ST-050", "RW-010"]+ },+ {+ family: "storage",+ targetType: "item",+ name: "Propellant tanks on racks",+ message: "Titanium propellant tanks are racked, never binned.",+ severity: "warn",+ surfaces: ["place"],+ match: "all",+ conditions: [+ {+ field: "storageUnit.storageTypeId",+ op: "eq",+ value: { storageType: "Rack" }+ }+ ],+ items: ["TANK-TI-4L"]+ },+ {+ family: "storage",+ targetType: "workCenter",+ name: "Clean room bay in service",+ message:+ "This clean room bay is out of service — start the integration on another bay.",+ severity: "error",+ surfaces: ["operationStart"],+ match: "all",+ conditions: [{ field: "workCenter.active", op: "eq", value: true }],+ workCenters: ["Clean Room Bay A"]+ }+];++export const BATCH_PROPERTIES: BatchPropertySpec[] = [+ { item: "BAT-LIION-48V", label: "Cell lot code", dataType: "text" },+ { item: "BAT-LIION-48V", label: "Formation date", dataType: "date" },+ {+ item: "BAT-LIION-48V",+ label: "Capacity grade",+ dataType: "list",+ listOptions: ["A", "B"]+ },+ { item: "MAT-AL7075-PLT", label: "Heat number", dataType: "text" },+ { item: "MAT-AL7075-PLT", label: "Mill cert received", dataType: "boolean" }];export const satelliteItems: ItemsData = {+ assembly: satelliteAssembly,buyParts: BUY_PARTS,materials: MATERIALS,consumables: CONSUMABLES,@@ -727,5 +1015,14 @@ export const satelliteItems: ItemsData = {services: SERVICES,makeParts: MAKE_PARTS,methods: METHODS,- supplierLinks: SUPPLIER_LINKS+ supplierLinks: SUPPLIER_LINKS,+ supersessions: SUPERSESSIONS,+ customerParts: CUSTOMER_PARTS,+ priceOverrides: PRICE_OVERRIDES,+ pricingRules: PRICING_RULES,+ configuration: CONFIGURATION,+ revisionLadder: REVISION_LADDER,+ inspectionPlans: INSPECTION_PLANS,+ enforcementRules: ENFORCEMENT_RULES,+ batchProperties: BATCH_PROPERTIES};diff --git a/packages/database/src/datasets/data/satellite/ops.ts b/packages/database/src/datasets/data/satellite/ops.tsnew file mode 100644index 0000000000..b1ca200811--- /dev/null+++ b/packages/database/src/datasets/data/satellite/ops.ts@@ -0,0 +1,576 @@+import type {+ CustomFieldSpec,+ MaintenanceDispatchSpec,+ MaintenanceScheduleSpec,+ NoteSpec,+ OpenTimecardSpec,+ OpsData,+ PeopleAbsenceSpec,+ PeopleAssignmentSpec,+ PrintJobSpec,+ ReplacementPartSpec,+ SerialSequenceSpec,+ SuggestionSpec,+ TimecardSpec,+ TrainingSpec,+ UserAttributeCategorySpec+} from "../../types.ts";++export const MAINTENANCE_SCHEDULES: MaintenanceScheduleSpec[] = [+ {+ key: "cleanroom-particles",+ name: "Clean room particle count & wipe-down",+ description:+ "Handheld particle counter at the four ISO 7 sample points; wipe benches and glove ports with IPA.",+ workCenter: "Clean Room Bay A",+ frequency: "Daily",+ priority: "Medium",+ estimatedDuration: 30,+ // Today's count is already dispatched.+ nextDueOffset: 1+ },+ {+ key: "cnc-way-lube",+ name: "CNC spindle warm-up & way-lube check",+ description:+ "Run the 20-minute spindle warm-up program, top off way lube and log the air pressure.",+ workCenter: "CNC Mill",+ frequency: "Weekly",+ priority: "Medium",+ estimatedDuration: 45,+ nextDueOffset: 2+ },+ {+ key: "tvac-cryopump",+ name: "TVAC cryopump regeneration & door O-ring inspection",+ description:+ "Regenerate the cryopump, inspect and re-grease the door O-ring with Krytox, then leak-check to 1e-6 Torr.",+ workCenter: "TVAC Chamber 1",+ frequency: "Monthly",+ priority: "High",+ estimatedDuration: 240,+ nextDueOffset: 21,+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-GREASE-001", quantity: 1 }]+ },+ {+ key: "pcb-reflow-profile",+ name: "Reflow oven thermal profile verification",+ description:+ "Run the profiling board through the reflow oven and compare each zone against the IPC J-STD-001 space addendum profile.",+ workCenter: "PCB Lab",+ frequency: "Quarterly",+ priority: "Medium",+ estimatedDuration: 120,+ nextDueOffset: 38+ },+ {+ key: "tig-calibration",+ name: "Annual TIG welder calibration",+ description:+ "Third-party amperage and gas-flow calibration of the TIG power supply per AWS D17.1 requirements.",+ workCenter: "TIG Welder Cell",+ frequency: "Annual",+ priority: "High",+ estimatedDuration: 480,+ nextDueOffset: 145,+ takesWorkCenterOffline: true+ },+ {+ key: "flatsat-psu-cal",+ name: "Flatsat bench power supply calibration check",+ description:+ "Verify the flatsat's 28 V bench supplies and electronic load against the lab DMM; log drift and re-trim if over 0.5%.",+ workCenter: "Flatsat Test Lab",+ frequency: "Quarterly",+ priority: "Medium",+ estimatedDuration: 90,+ nextDueOffset: 27+ }+];++// Shapes the maintenance KPIs and boards read: a failure on a production day,+// back-dated completions, today's scheduled task, a machine down now, one at HQ.+export const MAINTENANCE_DISPATCHES: MaintenanceDispatchSpec[] = [+ {+ key: "potting-needle",+ status: "Open",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Potting Station",+ suspectedFailureMode: "Blockage",+ content:+ "Sylgard meter-mix dispense needle clogging mid-shot — two EPS boards came out with potting voids this morning.",+ created: { offset: -1, time: "08:40:00" },+ plannedStart: { offset: 1, time: "09:00:00" },+ plannedEnd: { offset: 1, time: "11:00:00" }+ },+ {+ key: "tvac-thermocouple",+ status: "Assigned",+ priority: "Critical",+ severity: "OEM Required",+ source: "Non-Conformance",+ oeeImpact: "Down",+ workCenter: "TVAC Chamber 1",+ nonConformance: "ncr:txrx-tvac",+ suspectedFailureMode: "Electrical Fault",+ content:+ "Shroud thermocouple TC-07 read 6 °C high during the transceiver thermal cycle. Chamber locked out; OEM field service booked to replace the feedthrough.",+ created: { offset: -4, time: "16:20:00" },+ plannedStart: { offset: 3, time: "08:00:00" },+ plannedEnd: { offset: 3, time: "16:00:00" },+ takesWorkCenterOffline: true,+ comments: [+ "Feedthrough part number confirmed with the OEM — ships Tuesday.",+ "Rerun of the transceiver cycle is on hold until the chamber is re-qualified."+ ]+ },+ {+ key: "qc-cmm-probe",+ status: "In Progress",+ priority: "Low",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "No Impact",+ workCenter: "QC Bench",+ suspectedFailureMode: "Misalignment",+ content:+ "CMM probe qualification failing on the reference sphere by 4 µm. Re-seating the stylus and re-qualifying before the next first-article.",+ created: { offset: -1, time: "13:50:00" },+ plannedStart: { offset: -1, time: "14:00:00" },+ plannedEnd: { offset: -1, time: "16:00:00" },+ actualStart: { offset: -1, time: "14:10:00" }+ },+ {+ key: "tvac-oring",+ status: "Completed",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "TVAC Chamber 1",+ schedule: "tvac-cryopump",+ actualFailureMode: "Leak",+ content:+ "Monthly cryopump regeneration. Door O-ring was weeping at the hinge side on the leak check — cleaned, re-greased and re-seated.",+ created: { offset: -10, time: "06:00:00" },+ plannedStart: { offset: -9, time: "12:00:00" },+ plannedEnd: { offset: -9, time: "16:00:00" },+ actualStart: { offset: -9, time: "12:15:00" },+ actualEnd: { offset: -9, time: "17:05:00" },+ takesWorkCenterOffline: true,+ // Two pounds instead of the kit's one, which is why the next satellite kit is short of Krytox.+ spareParts: [{ item: "CN-GREASE-001", quantity: 2, shelf: "A1-L3" }],+ comments: ["Leak rate after re-seat: 2e-7 Torr·L/s — within spec."]+ },+ {+ key: "cnc-lube-skip",+ status: "Cancelled",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "CNC Mill",+ schedule: "cnc-way-lube",+ content:+ "Weekly way-lube check. Cancelled — the lube was topped off during the fixture swap the same day.",+ created: { offset: -6, time: "06:00:00" },+ plannedStart: { offset: -5, time: "12:00:00" },+ plannedEnd: { offset: -5, time: "12:45:00" }+ },+ {+ key: "cleanroom-particles-today",+ status: "Assigned",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "Clean Room Bay A",+ schedule: "cleanroom-particles",+ content:+ "Daily particle count at the four ISO 7 sample points, then IPA wipe-down of benches and glove ports.",+ created: { offset: -1, time: "06:00:00" },+ plannedStart: { offset: 0, time: "14:00:00" },+ plannedEnd: { offset: 0, time: "14:30:00" }+ },+ {+ key: "tig-gas-solenoid",+ status: "In Progress",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Down",+ workCenter: "TIG Welder Cell",+ suspectedFailureMode: "Electrical Fault",+ content:+ "Shield-gas solenoid on the TIG power supply is sticking open — argon flow alarm on every arc start. Cell locked out while the valve is swapped and the purge re-verified.",+ created: { offset: -1, time: "15:40:00" },+ plannedStart: { offset: -1, time: "16:00:00" },+ plannedEnd: { offset: 1, time: "12:00:00" },+ actualStart: { offset: -1, time: "16:05:00" },+ takesWorkCenterOffline: true,+ comments: ["Replacement valve pulled from the cell's spares kit."]+ },+ {+ key: "cleanroom-ionizer",+ status: "Completed",+ priority: "Medium",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Clean Room Bay A",+ suspectedFailureMode: "Electrical Fault",+ actualFailureMode: "Electrical Fault",+ content:+ "Ionizer bar over the integration bench threw a balance alarm mid-shift. Emitter pins cleaned and the bar re-balanced to ±15 V.",+ created: { offset: -9, time: "14:20:00" },+ plannedStart: { offset: -9, time: "14:30:00" },+ plannedEnd: { offset: -9, time: "15:30:00" },+ actualStart: { offset: -9, time: "14:35:00" },+ actualEnd: { offset: -9, time: "15:20:00" }+ },+ {+ key: "tvac-cryopump-prior",+ status: "Completed",+ priority: "Medium",+ severity: "Preventive",+ source: "Scheduled",+ oeeImpact: "Planned",+ workCenter: "TVAC Chamber 1",+ schedule: "tvac-cryopump",+ content:+ "Monthly cryopump regeneration and door O-ring re-grease. Leak check passed first time.",+ created: { offset: -41, time: "06:00:00" },+ plannedStart: { offset: -40, time: "12:00:00" },+ plannedEnd: { offset: -40, time: "16:00:00" },+ actualStart: { offset: -40, time: "12:10:00" },+ actualEnd: { offset: -40, time: "15:50:00" },+ takesWorkCenterOffline: true,+ spareParts: [{ item: "CN-GREASE-001", quantity: 1, shelf: "A1-L3" }]+ },+ {+ key: "cnc-drawbar",+ status: "Completed",+ priority: "High",+ severity: "Support Required",+ source: "Reactive",+ oeeImpact: "Down",+ workCenter: "CNC Mill",+ suspectedFailureMode: "Excessive Wear",+ actualFailureMode: "Excessive Wear",+ content:+ "Spindle drawbar lost clamp force — tool pulled out during a roughing pass on a bus panel. Belleville stack replaced and clamp force re-measured.",+ created: { offset: -50, time: "09:15:00" },+ plannedStart: { offset: -50, time: "10:00:00" },+ plannedEnd: { offset: -50, time: "16:00:00" },+ actualStart: { offset: -50, time: "10:20:00" },+ actualEnd: { offset: -49, time: "11:30:00" },+ takesWorkCenterOffline: true+ },+ {+ key: "flatsat-breakout",+ status: "Open",+ priority: "Medium",+ severity: "Operator Performed",+ source: "Reactive",+ oeeImpact: "Impact",+ workCenter: "Flatsat Test Lab",+ suspectedFailureMode: "Electrical Fault",+ content:+ "Intermittent open on pin 14 of the flatsat harness breakout box — the EPS telemetry channel drops out when the cable is flexed.",+ created: { offset: -2, time: "10:30:00" },+ plannedStart: { offset: 2, time: "09:00:00" },+ plannedEnd: { offset: 2, time: "11:00:00" }+ }+];++export const REPLACEMENT_PARTS: ReplacementPartSpec[] = [+ { workCenter: "TVAC Chamber 1", item: "CN-GREASE-001", quantity: 1 },+ { workCenter: "TIG Welder Cell", item: "VLV-SOLENOID-LP2", quantity: 1 },+ { workCenter: "CNC Mill", item: "BRG-6201", quantity: 2 }+];++export const TRAININGS: TrainingSpec[] = [+ {+ name: "ESD Control for Flight Hardware",+ description:+ "ANSI/ESD S20.20 basics for anyone who handles flight electronics.",+ status: "Active",+ frequency: "Once",+ type: "Mandatory",+ estimatedDuration: "45m",+ content: [+ "Every flight board is ESD-sensitive. Inside the EPA you are grounded, the surface is dissipative, and insulators stay out.",+ "Check your wrist strap and heel straps at the tester every time you enter, and log the result."+ ],+ questions: [+ {+ type: "MultipleChoice",+ question:+ "What is the maximum wrist-strap system resistance the check-in tester accepts?",+ options: ["100 kΩ", "1 MΩ", "35 MΩ", "10 GΩ"],+ correct: "35 MΩ"+ },+ {+ type: "TrueFalse",+ question:+ "A grounded wrist strap is enough protection when the board sits on an ordinary, non-dissipative bench.",+ answer: false+ },+ {+ type: "MultipleAnswers",+ question:+ "Which of these belong inside the EPA? Select all that apply.",+ options: [+ "Static-shielding bags",+ "Ionizer",+ "Styrofoam cups",+ "Dissipative bench mat",+ "Standard bubble wrap"+ ],+ correct: ["Static-shielding bags", "Ionizer", "Dissipative bench mat"]+ },+ {+ type: "MatchingPairs",+ question: "Match each control to what it does.",+ pairs: [+ { left: "Wrist strap", right: "Grounds the operator" },+ { left: "Ionizer", right: "Neutralizes charge on insulators" },+ { left: "Static-shielding bag", right: "Protects parts in transit" }+ ]+ },+ {+ type: "Numerical",+ question:+ "How many inches must a process-essential insulator reading over 2,000 V/in be kept from an ESD-sensitive part?",+ answer: 12,+ tolerance: 0+ }+ ],+ assignment: { completedOffset: -12 }+ },+ {+ name: "Clean Room Gowning & Contamination Control",+ description:+ "ISO 7 gowning order, allowed materials and particle discipline.",+ status: "Active",+ frequency: "Annual",+ type: "Mandatory",+ estimatedDuration: "30m",+ content: [+ "Gown top-down: hood, coverall, then boots. Nothing from the gray area crosses the bench line."+ ],+ questions: [+ {+ type: "MultipleChoice",+ question: "In which order are clean room garments put on?",+ options: [+ "Hood, coverall, boots",+ "Boots, coverall, hood",+ "Coverall, hood, boots"+ ],+ correct: "Hood, coverall, boots"+ },+ {+ type: "TrueFalse",+ question: "Pencils and cosmetics are allowed inside the ISO 7 bay.",+ answer: false+ }+ ],+ assignment: {}+ },+ {+ name: "TVAC Chamber Operation",+ description:+ "Operator qualification for running flight-unit thermal vacuum cycles.",+ status: "Draft",+ frequency: "Once",+ type: "Optional",+ estimatedDuration: "90m",+ content: [+ "Draft — pump-down, bake-out and thermal ramp limits for the chamber."+ ],+ questions: [+ {+ type: "Numerical",+ question:+ "What is the maximum shroud ramp rate for flight units, in °C per minute?",+ answer: 2,+ tolerance: 0.5+ }+ ]+ }+];++export const TIMECARDS: TimecardSpec[] = [+ { dayOffset: -5, clockIn: "06:58:00", clockOut: "15:31:00" },+ { dayOffset: -4, clockIn: "07:04:00", clockOut: "15:36:00" },+ {+ dayOffset: -3,+ clockIn: "06:55:00",+ clockOut: "17:12:00",+ note: "Stayed late for the TVAC pump-down."+ },+ { dayOffset: -2, clockIn: "07:01:00", clockOut: "15:29:00" },+ { dayOffset: -1, clockIn: "07:02:00", clockOut: "11:30:00" },+ { dayOffset: -1, clockIn: "12:01:00", clockOut: "15:34:00" }+];++// Clocked in before the first timer on the floor started this morning.+export const OPEN_TIMECARD: OpenTimecardSpec = { clockIn: "06:31:00" };++// None on today, so the MES schedule opens on every work center, not one station.+export const PEOPLE_ASSIGNMENTS: PeopleAssignmentSpec[] = [+ { dayOffset: -2, workCenter: "CNC Mill", shift: "Day Shift" },+ { dayOffset: -1, workCenter: "TIG Welder Cell", shift: "Day Shift" },+ {+ dayOffset: 1,+ workCenter: "Clean Room Bay A",+ shift: "Day Shift",+ note: "Solar array substrate layup — cover for the bay lead."+ },+ { dayOffset: 2, workCenter: "CNC Mill", shift: "Day Shift" },+ {+ dayOffset: 3,+ workCenter: "TVAC Chamber 1",+ shift: "Day Shift",+ overtimeHours: 2,+ note: "Stay through the TVAC hot-soak handover."+ },+ { dayOffset: 4, workCenter: "TIG Welder Cell", shift: "Day Shift" }+];++export const PEOPLE_ABSENCES: PeopleAbsenceSpec[] = [+ {+ dayOffset: 9,+ note: "ITAR export-compliance refresher at the Houston office."+ }+];++export const SUGGESTIONS: SuggestionSpec[] = [+ {+ suggestion:+ "Show spare-part cost on the maintenance list so we can see what the TVAC chamber costs us each month.",+ emoji: "🔧",+ path: "/x/resources/maintenance",+ tags: ["Maintenance"]+ },+ {+ suggestion:+ "Let us scan a lot barcode straight into the quantities search instead of typing the lot number.",+ emoji: "💡",+ path: "/x/inventory/quantities"+ }+];++export const NOTES: NoteSpec[] = [+ {+ text: "Qualified as TVAC operator after the chamber re-qualification — can run flight-unit cycles unsupervised."+ },+ {+ text: "Covering the ESD program audit while the quality lead is at the customer's CDR."+ }+];++export const USER_ATTRIBUTE_CATEGORIES: UserAttributeCategorySpec[] = [+ {+ name: "Flight Hardware Qualifications",+ emoji: "🛰️",+ public: true,+ attributes: [+ {+ name: "J-STD-001 space addendum expires",+ dataType: "Date",+ valueOffset: 142+ },+ {+ name: "Clean room gown size",+ dataType: "List",+ listOptions: ["XS", "S", "M", "L", "XL", "XXL"],+ value: "L",+ canSelfManage: true+ },+ { name: "Qualification records owner", dataType: "User" },+ {+ name: "Cleared for flight-unit handling",+ dataType: "Yes/No",+ value: true+ }+ ]+ }+];++export const CUSTOM_FIELDS: CustomFieldSpec[] = [+ { table: "part", name: "Export classification (ECCN)", dataType: "Text" },+ { table: "customer", name: "Program manager", dataType: "User" },+ { table: "job", name: "Flight hardware", dataType: "Yes/No" }+];++export const SERIAL_SEQUENCES: SerialSequenceSpec[] = [+ // Continues the supplier's numbering already on the shelf (…-0054).+ { item: "RW-010", prefix: "RW010-SN-", size: 4, next: 54 },+ { item: "SAT-1000", prefix: "SAT1000-SN-", size: 4, next: 1 }+];++export const PRINT_JOBS: PrintJobSpec[] = [+ {+ source: { kind: "Receipt", receipt: "receipt:bare-boards" },+ item: "PCB-BARE-REV3",+ status: "completed",+ origin: "auto",+ at: { offset: -1, time: "15:12:00" },+ attempts: 1+ },+ {+ source: { kind: "Job", job: "done-bus" },+ item: "BUS-STR-001",+ status: "completed",+ origin: "manual",+ at: { offset: -2, time: "19:40:00" },+ attempts: 1+ },+ {+ source: { kind: "StorageUnit", shelf: "A1-L1" },+ status: "completed",+ origin: "manual",+ at: { offset: -6, time: "16:20:00" },+ attempts: 1+ },+ {+ source: { kind: "Job", job: "floor-bus" },+ item: "BUS-STR-001",+ status: "failed",+ origin: "auto",+ at: { offset: -1, time: "13:05:00" },+ attempts: 3,+ error: "Printer did not respond after 3 attempts (connection timed out)"+ },+ {+ source: { kind: "Job", job: "floor-bus" },+ item: "BUS-STR-001",+ status: "queued",+ origin: "reprint",+ at: { offset: 0, time: "06:52:00" },+ attempts: 0+ }+];++export const satelliteOps: OpsData = {+ userAttributeCategories: USER_ATTRIBUTE_CATEGORIES,+ customFields: CUSTOM_FIELDS,+ serialSequences: SERIAL_SEQUENCES,+ printJobs: PRINT_JOBS,+ maintenanceSchedules: MAINTENANCE_SCHEDULES,+ maintenanceDispatches: MAINTENANCE_DISPATCHES,+ replacementParts: REPLACEMENT_PARTS,+ trainings: TRAININGS,+ timecards: TIMECARDS,+ openTimecard: OPEN_TIMECARD,+ peopleAssignments: PEOPLE_ASSIGNMENTS,+ peopleAbsences: PEOPLE_ABSENCES,+ suggestions: SUGGESTIONS,+ notes: NOTES+};diff --git a/packages/database/src/datasets/data/satellite/planning.ts b/packages/database/src/datasets/data/satellite/planning.tsindex bd9545496c..e3b6d48bb9 100644--- a/packages/database/src/datasets/data/satellite/planning.ts+++ b/packages/database/src/datasets/data/satellite/planning.ts@@ -1,6 +1,7 @@import type {DemandOrderSpec,DemandProjectionSpec,+ HqPlanningSpec,PlanningData} from "../../types.ts";@@ -62,9 +63,15 @@ export const DEMAND_ORDER: DemandOrderSpec = {]};+export const HQ_PLANNING: HqPlanningSpec = {+ reorderItemIds: ["EPS-001", "BAT-LIION-48V"],+ demandProjections: [{ readableId: "EPS-001", quantities: [1, 1, 2, 2] }]+};+export const satellitePlanning: PlanningData = {buyItemIds: BUY_ITEM_IDS,makeItemIds: MAKE_ITEM_IDS,demandProjections: DEMAND_PROJECTIONS,- demandOrder: DEMAND_ORDER+ demandOrder: DEMAND_ORDER,+ hq: HQ_PLANNING};diff --git a/packages/database/src/datasets/data/satellite/production.ts b/packages/database/src/datasets/data/satellite/production.tsindex da82fd816c..5ec32d9594 100644--- a/packages/database/src/datasets/data/satellite/production.ts+++ b/packages/database/src/datasets/data/satellite/production.ts@@ -2,10 +2,10 @@ import type {GenealogyAssemblySpec,GenealogyInputSpec,JobSpec,+ PickingListSpec,ProductionData,ShiftEventSpec} from "../../types.ts";-import { satelliteAssembly } from "./assembly.ts";export const JOBS: JobSpec[] = [{@@ -17,8 +17,31 @@ export const JOBS: JobSpec[] = [salesOrder: "so:orbsec",salesOrderLine: "soline:orbsec:sat",customer: "ORBSEC Defense",- dueDateOffset: -167,- releasedDateOffset: -297+ deadlineType: "Hard Deadline",+ dueDateOffset: 6,+ releasedDateOffset: -297,+ priority: 3,+ assignee: "self",+ operationOverrides: [+ { order: 1, status: "Done" },+ { order: 2, status: "In Progress", assignee: "self" },+ { order: 3, status: "Waiting" }+ ],+ quantities: [+ { order: 1, type: "Production", quantity: 1 },+ { order: 1, type: "Scrap", quantity: 2, scrapReason: "Defective" },+ { order: 2, type: "Rework", quantity: 1 }+ ],+ operationNotes: [+ {+ order: 1,+ note: "Torque-striped all M6 bus fasteners after the second pass — witness marks photographed for the ORBSEC data package."+ },+ {+ order: 2,+ note: "TVAC cycle 3 of 8 running. Cold soak plateau holding at -25C, no anomalies on the battery heater loop."+ }+ ]},{key: "ready",@@ -28,8 +51,10 @@ export const JOBS: JobSpec[] = [salesOrder: "so:polar",salesOrderLine: "soline:polar:sat",customer: "PolarView Earth",- dueDateOffset: -153,- releasedDateOffset: -251+ deadlineType: "ASAP",+ dueDateOffset: 14,+ releasedDateOffset: -4,+ priority: 10},{key: "planned",@@ -39,7 +64,9 @@ export const JOBS: JobSpec[] = [salesOrder: "so:planned",salesOrderLine: "soline:planned",customer: "NovaSat Networks",- dueDateOffset: -90+ deadlineType: "Soft Deadline",+ dueDateOffset: 18,+ priority: 12},{key: "draft",@@ -49,7 +76,7 @@ export const JOBS: JobSpec[] = [salesOrder: "so:draft",salesOrderLine: "soline:draft",customer: "Apex Space Research",- dueDateOffset: -125+ deadlineType: "No Deadline"},{key: "paused",@@ -59,8 +86,9 @@ export const JOBS: JobSpec[] = [salesOrder: "so:paused",salesOrderLine: "soline:paused",customer: "ORBSEC Defense",- dueDateOffset: -139,- releasedDateOffset: -266+ dueDateOffset: 9,+ releasedDateOffset: -266,+ priority: 6},{key: "completed",@@ -98,6 +126,206 @@ export const JOBS: JobSpec[] = [customer: "Apex Space Research",dueDateOffset: -314,releasedDateOffset: -337+ },++ // Released over the last few weeks so every work center has a queue and something running today.+ {+ key: "floor-eps-pcb",+ item: "PCB-EPS-R1",+ status: "In Progress",+ quantity: 4,+ salesOrder: "so:floor-novasat",+ salesOrderLine: "soline:floor-novasat:eps-pcb",+ customer: "NovaSat Networks",+ dueDateOffset: 2,+ releasedDateOffset: -6,+ priority: 2,+ assignee: "self",+ operationOverrides: [+ { order: 1, status: "Done" },+ {+ order: 2,+ status: "In Progress",+ assignee: "self",+ running: { type: "Labor", startTimeOfDay: "07:30:00" }+ },+ // The first potted boards are already on the QC bench (quality.inspections).+ { order: 3, status: "In Progress" }+ ]+ },+ {+ key: "floor-adcs-pcb",+ item: "PCB-ADCS-R1",+ status: "In Progress",+ quantity: 3,+ salesOrder: "so:floor-polar",+ salesOrderLine: "soline:floor-polar:adcs-pcb",+ customer: "PolarView Earth",+ dueDateOffset: 5,+ releasedDateOffset: -2,+ priority: 4,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ {+ key: "floor-bus",+ item: "BUS-STR-001",+ status: "In Progress",+ quantity: 1,+ salesOrder: "so:floor-polar",+ salesOrderLine: "soline:floor-polar:bus",+ customer: "PolarView Earth",+ deadlineType: "Soft Deadline",+ dueDateOffset: 12,+ releasedDateOffset: -10,+ priority: 8,+ assignee: "self",+ operationOverrides: [+ {+ order: 1,+ status: "In Progress",+ assignee: "self",+ running: { type: "Machine", startTimeOfDay: "06:45:00" }+ },+ { order: 2, status: "Waiting" }+ ]+ },+ {+ key: "floor-saw",+ item: "SAW-001",+ status: "In Progress",+ quantity: 2,+ salesOrder: "so:floor-polar",+ salesOrderLine: "soline:floor-polar:saw",+ customer: "PolarView Earth",+ dueDateOffset: 7,+ releasedDateOffset: -5,+ priority: 5,+ operationOverrides: [+ { order: 1, status: "Done" },+ {+ order: 2,+ status: "In Progress",+ running: { type: "Setup", startTimeOfDay: "08:15:00" }+ },+ { order: 3, status: "Waiting" }+ ]+ },+ {+ key: "floor-antenna",+ item: "ANT-PATCH-01",+ status: "Ready",+ quantity: 4,+ salesOrder: "so:floor-novasat",+ salesOrderLine: "soline:floor-novasat:antenna",+ customer: "NovaSat Networks",+ deadlineType: "ASAP",+ dueDateOffset: 0,+ releasedDateOffset: -1,+ priority: 1,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ {+ key: "floor-prop",+ item: "PROP-001",+ status: "Ready",+ quantity: 1,+ salesOrder: "so:floor-polar",+ salesOrderLine: "soline:floor-polar:prop",+ customer: "PolarView Earth",+ dueDateOffset: 21,+ releasedDateOffset: -3,+ priority: 13+ },+ {+ key: "floor-comms",+ item: "COMMS-001",+ status: "Ready",+ quantity: 1,+ salesOrder: "so:floor-polar",+ salesOrderLine: "soline:floor-polar:comms",+ customer: "PolarView Earth",+ deadlineType: "Soft Deadline",+ dueDateOffset: 16,+ releasedDateOffset: -4,+ priority: 11,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },+ // No deadline, so it lands in Priorities' Unscheduled column.+ {+ key: "floor-harness",+ item: "HARNESS-001",+ status: "Ready",+ quantity: 2,+ salesOrder: "so:floor-polar",+ salesOrderLine: "soline:floor-polar:harness",+ customer: "PolarView Earth",+ deadlineType: "No Deadline",+ releasedDateOffset: -1,+ priority: 14+ },+ {+ key: "stock-eps-pcb",+ item: "PCB-EPS-R1",+ status: "In Progress",+ quantity: 6,+ dueDateOffset: 11,+ releasedDateOffset: -2,+ priority: 9+ },+ {+ key: "stock-harness",+ item: "HARNESS-001",+ status: "Ready",+ quantity: 4,+ deadlineType: "Soft Deadline",+ dueDateOffset: 9,+ releasedDateOffset: -3,+ priority: 7,+ operationOverrides: [{ order: 1, assignee: "self" }]+ },++ // Feeds the completion-time and estimates-vs-actuals KPIs.+ {+ key: "done-adcs-pcb",+ item: "PCB-ADCS-R1",+ status: "Completed",+ quantity: 2,+ quantityComplete: 2,+ salesOrder: "so:floor-novasat",+ salesOrderLine: "soline:floor-novasat:adcs-pcb",+ customer: "NovaSat Networks",+ dueDateOffset: -8,+ releasedDateOffset: -16,+ completedDateOffset: -11,+ loggedTime: { startOffset: -14, efficiency: 0.92 }+ },+ {+ key: "done-saw",+ item: "SAW-001",+ status: "Completed",+ quantity: 1,+ quantityComplete: 1,+ salesOrder: "so:floor-novasat",+ salesOrderLine: "soline:floor-novasat:saw",+ customer: "NovaSat Networks",+ dueDateOffset: -20,+ releasedDateOffset: -30,+ completedDateOffset: -24,+ loggedTime: { startOffset: -28, efficiency: 1.18 }+ },+ {+ key: "done-bus",+ item: "BUS-STR-001",+ status: "Completed",+ quantity: 1,+ quantityComplete: 1,+ salesOrder: "so:floor-novasat",+ salesOrderLine: "soline:floor-novasat:bus",+ customer: "NovaSat Networks",+ dueDateOffset: -2,+ releasedDateOffset: -12,+ completedDateOffset: -4,+ loggedTime: { startOffset: -9, efficiency: 1.07 }}];@@ -188,12 +416,75 @@ export const GENEALOGY_ASSEMBLY: GenealogyAssemblySpec = {}};+export const PICKING_LISTS: PickingListSpec[] = [+ {+ key: "sat-kit-1",+ status: "Completed",+ job: "in-progress",+ dateOffset: -20,+ lines: [+ {+ item: "FST-M4-TI",+ quantityRequired: 48,+ quantityPicked: 48,+ status: "Picked",+ fromShelf: "A1-L1"+ },+ {+ item: "FST-M6-A286",+ quantityRequired: 24,+ quantityPicked: 24,+ status: "Picked",+ fromShelf: "A1-L1"+ }+ ]+ },+ {+ key: "sat-kit-2",+ status: "In Progress",+ job: "in-progress",+ dateOffset: -2,+ lines: [+ {+ item: "BRG-6201",+ quantityRequired: 4,+ quantityPicked: 0,+ status: "Pending",+ fromShelf: "A1-L3"+ },+ {+ item: "CN-GREASE-001",+ quantityRequired: 1,+ quantityPicked: 0,+ status: "Short",+ fromShelf: "A1-L3"+ }+ ]+ }+];+export const satelliteProduction: ProductionData = {- assembly: satelliteAssembly,jobs: JOBS,shifts: SHIFTS,genealogyInputs: GENEALOGY_INPUTS,genealogyAssembly: GENEALOGY_ASSEMBLY,eventsJobKey: "in-progress",- genealogyJobKey: "in-progress"+ genealogyJobKey: "in-progress",+ // Must match the operation overridden to In Progress.+ openEvent: { operationOrder: 2 },+ batch: {+ members: [+ { job: "floor-adcs-pcb", order: 1 },+ { job: "stock-eps-pcb", order: 1 }+ ],+ running: { type: "Machine", startTimeOfDay: "07:10:00" }+ },+ rework: {+ quantity: 1,+ reason:+ "Battery heater harness continuity failed at cold soak — return unit 2 to systems integration for connector rework.",+ targetOperationOrder: 1,+ triggeredAtOperationOrder: 2+ },+ pickingLists: PICKING_LISTS};diff --git a/packages/database/src/datasets/data/satellite/purchasing.ts b/packages/database/src/datasets/data/satellite/purchasing.tsindex a32cf07f1f..6ad0a2d6d5 100644--- a/packages/database/src/datasets/data/satellite/purchasing.ts+++ b/packages/database/src/datasets/data/satellite/purchasing.ts@@ -1,9 +1,12 @@import type {+ LifecycleRfqSpec,PurchaseOrderSpec,+ PurchaseReturnSpec,PurchasingData,RfqHeaderSpec,RfqLineSpec,- RfqQuoteSpec+ RfqQuoteSpec,+ StandaloneSupplierQuoteSpec} from "../../types.ts";// Every RFQ line and every supplier quote prices the same quantity breaks, so@@ -20,6 +23,7 @@ export const RFQ_LINES: RfqLineSpec[] = [export const RFQ_QUOTES: RfqQuoteSpec[] = [{key: "celex",+ assignee: "self",supplier: "CelestialElex",supplierReference: "CEX-Q-4471",shippingCost: 250,@@ -104,6 +108,7 @@ export const RFQ_ORDER_QUANTITY = 25;// 2 lines, finalized (Requested), fanned out to 3 suppliers.export const RFQ_HEADER: RfqHeaderSpec = {ref: "prfq:avionics",+ assignee: "self",status: "Requested",rfqDateOffset: -24,expirationOffset: 48,@@ -111,6 +116,45 @@ export const RFQ_HEADER: RfqHeaderSpec = {internalNotes: "Award on landed cost at 25 pcs unless lead time slips."};+export const LIFECYCLE_RFQS: LifecycleRfqSpec[] = [+ {+ ref: "prfq:propulsion",+ status: "Draft",+ rfqDateOffset: -2,+ expirationOffset: 28,+ notes: "Feed-system valves and tanks for the Q1 propulsion module build.",+ internalNotes: "Add Ionix once their supplier approval clears.",+ quantities: [4, 8],+ lines: [+ {+ item: "VLV-SOLENOID-LP2",+ description: "Gen2 low-pressure solenoid valve — xenon feed"+ },+ {+ item: "TANK-TI-4L",+ description: "4L titanium propellant tank, burst-tested"+ }+ ],+ suppliers: ["PropTech Solutions", "Orbital Composites"]+ },+ {+ ref: "prfq:star-tracker",+ status: "Closed",+ rfqDateOffset: -58,+ expirationOffset: -28,+ notes: "Second-source star tracker for the constellation follow-on.",+ internalNotes: "Cancelled — program kept the flight-proven ST-050.",+ quantities: [2, 6],+ lines: [+ {+ item: "ST-050",+ description: "0.5 arcsec star tracker, flight heritage"+ }+ ],+ suppliers: ["Deep Space RF", "CelestialElex"]+ }+];+export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [{source: "direct",@@ -164,6 +208,7 @@ export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [source: "direct",log: "purchase order 3 — Draft (CelestialElex)",ref: "po:celex",+ assignee: "self",supplier: "CelestialElex",purchaseOrderType: "Purchase",status: "Draft",@@ -180,6 +225,400 @@ export const PURCHASE_ORDERS: PurchaseOrderSpec[] = [orderDateOffset: -8,currencyCode: "USD",exchangeRate: 1+ },++ {+ source: "direct",+ log: "purchase order — Planned (Deep Space RF reaction wheels)",+ supplier: "Deep Space RF",+ purchaseOrderType: "Purchase",+ status: "Planned",+ orderDateOffset: -1,+ lines: [{ item: "RW-010", purchaseQuantity: 2, supplierUnitPrice: 14350 }]+ },+ {+ source: "direct",+ log: "purchase order — To Review (CelestialElex EPS boards)",+ assignee: "self",+ supplier: "CelestialElex",+ purchaseOrderType: "Purchase",+ status: "To Review",+ orderDateOffset: -2,+ lines: [+ { item: "PCB-BARE-REV3", purchaseQuantity: 15, supplierUnitPrice: 84 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — Needs Approval (Orbital Composites laminate)",+ ref: "po:needs-approval",+ supplier: "Orbital Composites",+ purchaseOrderType: "Purchase",+ status: "Needs Approval",+ orderDateOffset: -1,+ // Over the $5,000 approval tier.+ lines: [+ { item: "MAT-CF-LAM", purchaseQuantity: 20, supplierUnitPrice: 315 }+ ]+ },+ {+ source: "direct",+ log: "purchase order — Rejected (PropTech thruster quote too high)",+ supplier: "PropTech Solutions",+ purchaseOrderType: "Purchase",+ status: "Rejected",+ orderDateOffset: -13,+ lines: [+ { item: "THR-HYDRA-1N", purchaseQuantity: 2, supplierUnitPrice: 7100 }+ ]+ },++ {+ source: "direct",+ log: "purchase order — Completed, received in full and paid (CelestialElex)",+ ref: "po:paid",+ supplier: "CelestialElex",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -75,+ lines: [+ { item: "BAT-LIION-48V", purchaseQuantity: 2, supplierUnitPrice: 2380 },+ { item: "PCB-BARE-REV3", purchaseQuantity: 10, supplierUnitPrice: 85 }+ ],+ receipt: {+ ref: "receipt:paid",+ status: "Posted",+ postedOffset: -68,+ lines: [+ {+ item: "BAT-LIION-48V",+ orderQuantity: 2,+ outstandingQuantity: 0,+ receivedQuantity: 2,+ unitPrice: 2380,+ requiresBatchTracking: true,+ toShelf: "A1-L2",+ // Received -68 with a 365-day pack shelf life → expires at +297.+ lotNumber: "LOT-BAT-2610",+ lotExpiresOffset: 297+ },+ {+ item: "PCB-BARE-REV3",+ orderQuantity: 10,+ outstandingQuantity: 0,+ receivedQuantity: 10,+ unitPrice: 85,+ toShelf: "A1-L1"+ }+ ]+ },+ invoice: {+ ref: "pinvoice:paid",+ key: "paid",+ status: "Paid",+ currencyCode: "USD",+ subtotal: 5610,+ totalAmount: 5610,+ dateIssuedOffset: -62,+ dueDateOffset: -32,+ lines: [+ { item: "BAT-LIION-48V", quantity: 2, supplierUnitPrice: 2380 },+ { item: "PCB-BARE-REV3", quantity: 10, supplierUnitPrice: 85 }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Closed short after a partial receipt (PropTech tanks)",+ ref: "po:closed-short",+ supplier: "PropTech Solutions",+ purchaseOrderType: "Purchase",+ status: "Closed",+ orderDateOffset: -88,+ lines: [+ { item: "TANK-TI-4L", purchaseQuantity: 4, supplierUnitPrice: 3200 }+ ],+ receipt: {+ ref: "receipt:short",+ status: "Posted",+ postedOffset: -80,+ lines: [+ {+ item: "TANK-TI-4L",+ orderQuantity: 4,+ outstandingQuantity: 2,+ receivedQuantity: 2,+ unitPrice: 3200,+ toShelf: "A3-L1"+ }+ ]+ },+ invoice: {+ ref: "pinvoice:debit-note",+ key: "debit-note",+ status: "Debit Note Issued",+ currencyCode: "USD",+ subtotal: 6400,+ totalAmount: 6400,+ dateIssuedOffset: -72,+ lines: [{ item: "TANK-TI-4L", quantity: 2, supplierUnitPrice: 3200 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — To Receive with a voided receipt (SpaceGrade)",+ supplier: "SpaceGrade Fasteners",+ purchaseOrderType: "Purchase",+ status: "To Receive",+ orderDateOffset: -21,+ lines: [+ { item: "FST-M4-TI", purchaseQuantity: 250, supplierUnitPrice: 2.5 }+ ],+ receipt: {+ ref: "receipt:voided",+ status: "Voided",+ lines: [+ {+ item: "FST-M4-TI",+ orderQuantity: 250,+ outstandingQuantity: 250,+ receivedQuantity: 0,+ unitPrice: 2.5+ }+ ]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice open (Deep Space RF star tracker)",+ supplier: "Deep Space RF",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -30,+ lines: [{ item: "ST-050", purchaseQuantity: 1, supplierUnitPrice: 28000 }],+ invoice: {+ ref: "pinvoice:open",+ key: "open",+ status: "Open",+ currencyCode: "USD",+ subtotal: 28000,+ totalAmount: 28000,+ dateIssuedOffset: -9,+ dueDateOffset: 21,+ lines: [{ item: "ST-050", quantity: 1, supplierUnitPrice: 28000 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice overdue (Orbital Composites)",+ supplier: "Orbital Composites",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -60,+ lines: [+ { item: "MAT-CF-LAM", purchaseQuantity: 2, supplierUnitPrice: 320 }+ ],+ invoice: {+ ref: "pinvoice:overdue",+ key: "overdue",+ status: "Overdue",+ currencyCode: "USD",+ subtotal: 640,+ totalAmount: 640,+ dateIssuedOffset: -45,+ dueDateOffset: -15,+ lines: [{ item: "MAT-CF-LAM", quantity: 2, supplierUnitPrice: 320 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Completed, invoice partially paid (CelestialElex)",+ supplier: "CelestialElex",+ purchaseOrderType: "Purchase",+ status: "Completed",+ orderDateOffset: -55,+ lines: [+ { item: "PCB-BARE-REV3", purchaseQuantity: 40, supplierUnitPrice: 82 }+ ],+ invoice: {+ ref: "pinvoice:partial",+ key: "partial",+ status: "Partially Paid",+ currencyCode: "USD",+ subtotal: 3280,+ totalAmount: 3280,+ dateIssuedOffset: -40,+ dueDateOffset: -10,+ lines: [{ item: "PCB-BARE-REV3", quantity: 40, supplierUnitPrice: 82 }]+ }+ },+ {+ source: "direct",+ log: "purchase order — Closed, invoice voided over a billing error (SpaceGrade)",+ supplier: "SpaceGrade Fasteners",+ purchaseOrderType: "Purchase",+ status: "Closed",+ orderDateOffset: -66,+ lines: [+ { item: "FST-M6-A286", purchaseQuantity: 100, supplierUnitPrice: 5.5 }+ ],+ invoice: {+ ref: "pinvoice:voided",+ key: "voided",+ status: "Voided",+ currencyCode: "USD",+ subtotal: 550,+ totalAmount: 550,+ dateIssuedOffset: -58,+ lines: [{ item: "FST-M6-A286", quantity: 100, supplierUnitPrice: 5.5 }]+ }+ },++ // Mirrors the OSP orders the create function raises from a job's outside operations.+ {+ source: "direct",+ log: "purchase order — Outside Processing, anodize at AstroMill",+ assignee: "self",+ supplier: "AstroMill Machining",+ purchaseOrderType: "Outside Processing",+ status: "To Receive",+ orderDateOffset: -9,+ lines: [+ { item: "BUS-STR-001", purchaseQuantity: 2, supplierUnitPrice: 240 }+ ]+ },++ {+ source: "direct",+ log: "purchase order — EUR order, unpaid (Rheinland bearings)",+ ref: "po:eur",+ supplier: "Rheinland Precision Bearings GmbH",+ purchaseOrderType: "Purchase",+ status: "To Invoice",+ orderDateOffset: -18,+ currencyCode: "EUR",+ exchangeRate: 0.92,+ lines: [{ item: "BRG-6201", purchaseQuantity: 60, supplierUnitPrice: 16.4 }]+ },+ {+ source: "direct",+ log: "purchase order — To Invoice, bare boards received yesterday, awaiting incoming inspection (CelestialElex)",+ ref: "po:bare-boards",+ supplier: "CelestialElex",+ purchaseOrderType: "Purchase",+ status: "To Invoice",+ orderDateOffset: -16,+ lines: [+ { item: "PCB-BARE-REV3", purchaseQuantity: 10, supplierUnitPrice: 85 }+ ],+ receipt: {+ ref: "receipt:bare-boards",+ status: "Posted",+ postedOffset: -1,+ lines: [+ {+ item: "PCB-BARE-REV3",+ orderQuantity: 10,+ outstandingQuantity: 0,+ receivedQuantity: 10,+ unitPrice: 85,+ toShelf: "A1-L1"+ }+ ]+ }+ }+];++export const STANDALONE_SUPPLIER_QUOTES: StandaloneSupplierQuoteSpec[] = [+ {+ key: "sgf-annual-fasteners",+ assignee: "self",+ supplier: "SpaceGrade Fasteners",+ status: "Draft",+ supplierReference: "SGF-2026-1044",+ quotedOffset: -3,+ expirationOffset: 60,+ lines: [+ {+ item: "FST-M4-TI",+ supplierPartId: "SGF-M4-TI-CL3",+ prices: [+ { quantity: 1000, unitPrice: 2.35, leadTime: 14 },+ { quantity: 2500, unitPrice: 2.2, leadTime: 14 }+ ]+ }+ ]+ },+ {+ key: "oc-laminate-2025",+ supplier: "Orbital Composites",+ status: "Expired",+ supplierReference: "OC-Q-8812",+ quotedOffset: -210,+ expirationOffset: -30,+ lines: [+ {+ item: "MAT-CF-LAM",+ supplierPartId: "OC-CFL-2X2",+ prices: [{ quantity: 6, unitPrice: 305, leadTime: 21 }]+ }+ ]+ },+ {+ key: "dsrf-tracker-study",+ supplier: "Deep Space RF",+ status: "Declined",+ supplierReference: "DSRF-2025-0912",+ quotedOffset: -40,+ expirationOffset: 20,+ lines: [+ {+ item: "ST-050",+ supplierPartId: "DSRF-ST050-B",+ prices: [{ quantity: 2, unitPrice: 29500, leadTime: 100 }]+ }+ ]+ }+];++// The completed return is dated after the posted cycle count so the count's+// snapshot stays the opening balance.+export const PURCHASE_RETURNS: PurchaseReturnSpec[] = [+ {+ key: "fastener-plating",+ credit: {+ status: "Draft",+ dateOffset: -4,+ lines: [{ line: 1, quantity: 40 }]+ },+ status: "Completed",+ supplier: "SpaceGrade Fasteners",+ dateOffset: -6,+ lines: [+ { item: "FST-M4-TI", quantity: 40, unitPrice: 2.5, fromShelf: "A1-L1" }+ ]+ },+ {+ key: "valve-supersession",+ status: "To Ship",+ supplier: "PropTech Solutions",+ dateOffset: -2,+ lines: [{ item: "VLV-SOLENOID-LP", quantity: 2, unitPrice: 950 }]+ },+ {+ key: "laminate-voids",+ status: "Draft",+ supplier: "Orbital Composites",+ dateOffset: 0,+ lines: [{ item: "MAT-CF-LAM", quantity: 1, unitPrice: 320 }]+ },+ // Stays Draft while MRB decides; quality's ncr:tank-wall links this line.+ {+ key: "tank-wall-rtv",+ status: "Draft",+ supplier: "PropTech Solutions",+ dateOffset: -3,+ lines: [{ item: "TANK-TI-4L", quantity: 1, unitPrice: 3200 }]}];@@ -190,5 +629,65 @@ export const satellitePurchasing: PurchasingData = {rfqWinningQuote: RFQ_WINNING_QUOTE,rfqOrderQuantity: RFQ_ORDER_QUANTITY,rfqHeader: RFQ_HEADER,- purchaseOrders: PURCHASE_ORDERS+ lifecycleRfqs: LIFECYCLE_RFQS,+ purchaseOrders: PURCHASE_ORDERS,+ standaloneSupplierQuotes: STANDALONE_SUPPLIER_QUOTES,+ purchaseReturns: PURCHASE_RETURNS,+ approvalRules: [+ { documentType: "purchaseOrder", lowerBoundAmount: 5000 },+ {+ documentType: "purchaseOrder",+ lowerBoundAmount: 25000,+ escalationDays: 3+ },+ { documentType: "supplier", lowerBoundAmount: 0 }+ ],+ approvalRequests: [+ { purchaseOrder: "po:needs-approval", requestedOffset: -1 },+ { supplier: "Ionix Thrusters", requestedOffset: -4 }+ ],+ supplierBankAccounts: [+ {+ supplier: "CelestialElex",+ name: "CelestialElex remittance",+ bankName: "Silicon Valley Commerce (demo)",+ accountHolderName: "CelestialElex Corp.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-3301-8820",+ bankCode: "DEMO-121140",+ isPrimary: true+ },+ {+ supplier: "PropTech Solutions",+ name: "PropTech operating",+ bankName: "South Bay Savings (demo)",+ accountHolderName: "PropTech Solutions LLC",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-6612-0457",+ isPrimary: true+ },+ {+ supplier: "Deep Space RF",+ name: "Deep Space RF remittance",+ bankName: "Front Range Bank (demo)",+ accountHolderName: "Deep Space RF Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-5178-2093",+ isPrimary: true+ },+ {+ supplier: "Rheinland Precision Bearings GmbH",+ name: "Rheinland EUR account",+ bankName: "Neckar Handelsbank (demo)",+ accountHolderName: "Rheinland Precision Bearings GmbH",+ countryCode: "DE",+ currencyCode: "EUR",+ accountNumber: "DEMO-DE00-0000-7711",+ swiftBic: "DEMODEXX",+ isPrimary: true+ }+ ]};diff --git a/packages/database/src/datasets/data/satellite/quality.ts b/packages/database/src/datasets/data/satellite/quality.tsindex bb8c9d388f..aab0b95119 100644--- a/packages/database/src/datasets/data/satellite/quality.ts+++ b/packages/database/src/datasets/data/satellite/quality.ts@@ -1,4 +1,53 @@-import type { NonConformanceSpec, QualityData } from "../../types.ts";+import type {+ GaugeSpec,+ InspectionFeatureSpec,+ InspectionSpec,+ NonConformanceSpec,+ NonConformanceWorkflowSpec,+ QualityData,+ QualityDocumentSpec,+ RiskSpec+} from "../../types.ts";++// The new-issue form copies source, required actions and MRB from these templates onto the issue.+export const WORKFLOWS: NonConformanceWorkflowSpec[] = [+ {+ key: "supplier-escape",+ name: "Supplier Escape — Flight Hardware",+ description:+ "A purchased flight part failed receiving inspection. Quarantine the lot, find the root cause with the supplier, and put their corrective action on record before MRB closes it out.",+ priority: "High",+ source: "External",+ requiredActions: [+ "Containment Action",+ "Root Cause Analysis",+ "Corrective Action"+ ],+ mrb: true+ },+ {+ key: "customer-return",+ name: "Customer Complaint — Returned Unit",+ description:+ "A customer reported a failure on delivered hardware. Acknowledge within one business day, contain any sister units, and verify the fix before closing.",+ priority: "Medium",+ source: "External",+ requiredActions: [+ "Customer Communication",+ "Containment Action",+ "Verification"+ ]+ },+ {+ key: "incoming-hold",+ name: "Incoming Lot Hold",+ description:+ "An incoming lot failed a screening test. Hold the whole lot in quarantine until teardown decides its disposition.",+ priority: "Medium",+ source: "Internal",+ requiredActions: ["Containment Action"]+ }+];export const NON_CONFORMANCES: NonConformanceSpec[] = [{@@ -12,7 +61,8 @@ export const NON_CONFORMANCES: NonConformanceSpec[] = [// 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.jobOperation: { job: "job:in-progress" },- items: [{ item: "SAT-1000", quantity: 1 }]+ items: [{ item: "SAT-1000", quantity: 1 }],+ assignee: "self"},{ref: "ncr:fastener",@@ -21,10 +71,435 @@ export const NON_CONFORMANCES: NonConformanceSpec[] = [status: "Registered",openDateOffset: -285,quantity: 12,- priority: "Medium"+ priority: "Medium",+ items: [{ item: "FST-M6-A286", quantity: 12 }]+ },+ {+ ref: "ncr:tank-wall",+ purchaseReturnLine: {+ purchaseReturn: "tank-wall-rtv",+ line: 1,+ quantity: 1+ },+ name: "Propellant tank wall below minimum thickness at girth weld",+ description:+ "Receiving inspection on the PropTech short delivery measured 1.12 mm wall at the girth weld of one TANK-TI-4L against a 1.15 mm minimum. Tank quarantined; MRB to decide return-to-vendor vs. use-as-is with stress analysis.",+ type: "Supplier Issue",+ source: "External",+ status: "In Progress",+ openDateOffset: -78,+ dueDateOffset: 14,+ quantity: 1,+ priority: "Critical",+ supplier: "PropTech Solutions",+ purchaseOrderLine: { po: "po:closed-short", item: "TANK-TI-4L" },+ inspection: "insp:tank",+ items: [+ { item: "TANK-TI-4L", quantity: 1, disposition: "Return to Supplier" },+ { item: "PROP-001", quantity: 1 }+ ],+ assignee: "self",+ workflow: "supplier-escape",+ actionTasks: [+ {+ action: "Containment Action",+ status: "Completed",+ dueDateOffset: -76,+ completedOffset: -77+ },+ {+ action: "Root Cause Analysis",+ status: "In Progress",+ dueDateOffset: 7,+ processes: ["Clean Room Assembly"]+ },+ { action: "Corrective Action", status: "Pending", dueDateOffset: 21 }+ ],+ mrb: {+ status: "In Progress",+ dueDateOffset: 10,+ reviewers: [+ { title: "Engineering", status: "Completed", completedOffset: -70 },+ { title: "Quality", status: "In Progress" }+ ]+ }+ },+ {+ ref: "ncr:txrx-tvac",+ salesReturnLine: { salesReturn: "transponder", line: 1 },+ name: "Customer-reported S-band transponder spare fails TVAC pre-screen",+ description:+ "NovaSat reported one of two TXRX-SBAND spares drifting 40 kHz off channel at the cold plateau of their TVAC pre-screen. Unit returned for evaluation; root cause traced to an unstaked TCXO shield lid.",+ type: "Customer Complaint",+ source: "External",+ status: "Closed",+ openDateOffset: -12,+ dueDateOffset: 2,+ closeDateOffset: -3,+ quantity: 1,+ priority: "Low",+ customer: "NovaSat Networks",+ salesOrderLine: "soline:novasat-spares:txrx",+ items: [{ item: "TXRX-SBAND", quantity: 1, disposition: "Rework" }],+ workflow: "customer-return",+ actionTasks: [+ {+ action: "Customer Communication",+ status: "Completed",+ dueDateOffset: -11,+ completedOffset: -11+ },+ {+ action: "Containment Action",+ status: "Completed",+ dueDateOffset: -9,+ completedOffset: -10+ },+ {+ action: "Verification",+ status: "Completed",+ dueDateOffset: -4,+ completedOffset: -4+ }+ ]+ },+ {+ ref: "ncr:bat-lot",+ name: "Li-ion battery lot quarantined — capacity drift on incoming cycle test",+ description:+ "Lot LOT-BAT-2609 lost 3.8% capacity over the first 20 incoming cycles, outside the 2% screening limit. Lot placed on hold pending cell-level teardown.",+ type: "Material Issue",+ source: "Internal",+ status: "Registered",+ openDateOffset: -6,+ dueDateOffset: 20,+ quantity: 1,+ priority: "Medium",+ trackedEntity: "LOT-BAT-2609",+ items: [{ item: "BAT-LIION-48V", quantity: 1 }],+ // Feeds the supplier-quality KPI's issue this month.+ supplier: "CelestialElex",+ workflow: "incoming-hold",+ actionTasks: [+ { action: "Containment Action", status: "Pending", dueDateOffset: 2 }+ ]+ }+];++// Lot of 2 at AQL 1.0 / level II → code letter A, n = 2.+const BARE_BOARD_PLAN = {+ drawingNumber: "PCB-BARE-REV3 Fab Dwg Rev C",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Board thickness over copper",+ nominalValue: "1.60",+ tolerancePlus: "0.16",+ toleranceMinus: "0.16",+ unit: "mm"+ },+ {+ label: "2",+ description: "Plated through-hole diameter, J1 connector pattern",+ nominalValue: "1.00",+ tolerancePlus: "0.05",+ toleranceMinus: "0.05",+ unit: "mm"+ }+ ] satisfies InspectionFeatureSpec[]+};++export const INSPECTIONS: InspectionSpec[] = [+ {+ source: "Receipt",+ ref: "insp:tank",+ receipt: "receipt:short",+ item: "TANK-TI-4L",+ drawingNumber: "PT-4L-100 Rev C",+ aql: 1.0,+ features: [+ {+ label: "1",+ description: "Inlet port thread pitch diameter (7/16-20 UNJF)",+ nominalValue: "0.4050",+ tolerancePlus: "0.0020",+ toleranceMinus: "0.0020",+ unit: "in"+ },+ {+ label: "2",+ description: "Wall thickness at girth weld (UT)",+ nominalValue: "1.20",+ tolerancePlus: "0.10",+ toleranceMinus: "0.05",+ unit: "mm"+ }+ ],+ status: "Partial",+ dispositionOffset: -78,+ notes:+ "S/N 0417 accepted. S/N 0418 wall under minimum at the girth weld — quarantined and raised to MRB.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -79,+ measurements: [+ { feature: "1", value: 0.4052 },+ { feature: "2", value: 1.22 }+ ]+ },+ {+ status: "Failed",+ inspectedOffset: -79,+ measurements: [+ { feature: "1", value: 0.4049 },+ { feature: "2", value: 1.12 }+ ]+ }+ ]+ },+ // 10 boards at AQL 1.0 → n = 3.+ {+ source: "Receipt",+ ref: "insp:bare-boards",+ receipt: "receipt:paid",+ item: "PCB-BARE-REV3",+ ...BARE_BOARD_PLAN,+ status: "Passed",+ dispositionOffset: -67,+ notes: "Three boards measured; thickness and via sizes nominal.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 1.62 },+ { feature: "2", value: 1.01 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 1.58 },+ { feature: "2", value: 0.99 }+ ]+ },+ {+ status: "Passed",+ inspectedOffset: -67,+ measurements: [+ { feature: "1", value: 1.61 },+ { feature: "2", value: 1.02 }+ ]+ }+ ]+ },+ {+ source: "Receipt",+ ref: "insp:bare-boards-queue",+ receipt: "receipt:bare-boards",+ item: "PCB-BARE-REV3",+ ...BARE_BOARD_PLAN,+ status: "Pending",+ samples: []+ },+ {+ source: "Job Operation",+ ref: "insp:eps-fpt",+ job: "floor-eps-pcb",+ status: "In Progress",+ notes: "Board 1 of 4 measured; boards 2–4 still curing.",+ samples: [+ {+ status: "Passed",+ inspectedOffset: -1,+ measurements: [+ { feature: "1", value: 3.31 },+ { feature: "2", value: 2.05 }+ ]+ }+ ]+ }+];++export const QUALITY_DOCUMENTS: QualityDocumentSpec[] = [+ {+ name: "Flight Hardware Receiving Inspection",+ version: 1,+ status: "Archived",+ description:+ "Superseded receiving procedure for flight hardware — visual and certificate review only.",+ steps: []+ },+ {+ name: "Flight Hardware Receiving Inspection",+ version: 2,+ status: "Active",+ description:+ "Receiving procedure for flight hardware: paperwork, cleanliness and critical dimensions before stock-in.",+ steps: [+ {+ name: "Certificate of conformance matches PO and drawing revision",+ type: "Checkbox",+ required: true+ },+ {+ name: "Precision-cleanliness level on arrival",+ type: "List",+ required: true,+ listValues: ["Level 100A", "Level 300A", "Out of specification"]+ },+ {+ name: "Port thread engagement length",+ description: "Measured with the plug gauge fully seated.",+ type: "Measurement",+ required: true,+ unitOfMeasureCode: "INCH",+ minValue: 0.4,+ maxValue: 0.5+ }+ ]+ },+ {+ name: "ESD Control Plan (ANSI/ESD S20.20)",+ version: 0,+ status: "Draft",+ description:+ "Draft ESD control plan for the avionics integration cell — grounding, wrist-strap checks and packaging.",+ steps: []+ }+];++export const GAUGES: GaugeSpec[] = [+ {+ key: "gauge-blocks",+ gaugeType: "Gauge Block",+ description: "Grade K steel gauge block set, 81 pc — metrology lab master",+ modelNumber: "GBS-81K",+ serialNumber: "MB-22-0144",+ role: "Master",+ status: "Active",+ calibrationIntervalInMonths: 12,+ acquiredOffset: -700,+ calibrations: [+ {+ dateOffset: -560,+ result: "Pass",+ temperature: 20,+ humidity: 45,+ measurementStandard: "ISO 3650, NIST-traceable interferometry"+ },+ {+ dateOffset: -200,+ result: "Pass",+ temperature: 20,+ humidity: 43,+ measurementStandard: "ISO 3650, NIST-traceable interferometry"+ }+ ]+ },+ {+ key: "caliper",+ gaugeType: "Caliper - Outside",+ description: "150 mm digital caliper — new unit for the integration cell",+ modelNumber: "DC-150",+ serialNumber: "C24-88213",+ role: "Standard",+ status: "Active",+ calibrationIntervalInMonths: 6,+ acquiredOffset: -10,+ calibrations: []+ },+ {+ key: "micrometer",+ gaugeType: "Micrometer - Outside",+ description:+ "0–25 mm outside micrometer — retired after failed calibration",+ modelNumber: "OM-25",+ serialNumber: "M19-40522",+ role: "Standard",+ status: "Inactive",+ calibrationIntervalInMonths: 6,+ acquiredOffset: -900,+ calibrations: [+ { dateOffset: -400, result: "Pass", temperature: 20, humidity: 46 },+ {+ dateOffset: -220,+ result: "Fail",+ requiresAction: true,+ requiresRepair: true,+ temperature: 20,+ humidity: 44,+ notes: "Anvil faces worn — flatness 1.8 µm, limit 0.6 µm. Retired."+ }+ ]+ }+];++export const RISKS: RiskSpec[] = [+ {+ title: "Single-source titanium tank supplier weld quality",+ description:+ "PropTech is the only qualified source for TANK-TI-4L and has now shipped two escapes in one lot.",+ type: "Risk",+ status: "Mitigating",+ severity: 5,+ likelihood: 3,+ source: "Supplier",+ supplier: "PropTech Solutions"+ },+ {+ title: "Export classification review on propulsion spares",+ description:+ "ORBSEC requested propulsion spares that may move to a stricter ITAR category — confirm before shipment.",+ type: "Risk",+ status: "In Review",+ severity: 4,+ likelihood: 2,+ source: "Customer",+ customer: "ORBSEC Defense"+ },+ {+ title: "Reaction wheel bearing obsolescence",+ description:+ "The RW-010 bearing vendor announced end-of-life for the current cage material.",+ type: "Risk",+ status: "Open",+ severity: 3,+ likelihood: 3,+ source: "Item",+ item: "RW-010"+ },+ {+ title: "TVAC chamber availability for SAT-1000 acceptance",+ description:+ "Shared TVAC chamber was double-booked for the acceptance window; slot confirmed with the test house.",+ type: "Risk",+ status: "Closed",+ severity: 3,+ likelihood: 2,+ source: "Job",+ job: "job:in-progress"+ },+ {+ title: "Qualify a second EPS board fab to cut lead time",+ description:+ "A second IPC-6012 Class 3 fab could halve the 21-day PCB lead time — accepted into next year's plan.",+ type: "Opportunity",+ status: "Accepted",+ severity: 2,+ likelihood: 4,+ source: "General"}];export const satelliteQuality: QualityData = {- nonConformances: NON_CONFORMANCES+ workflows: WORKFLOWS,+ nonConformances: NON_CONFORMANCES,+ inspections: INSPECTIONS,+ qualityDocuments: QUALITY_DOCUMENTS,+ gauges: GAUGES,+ risks: RISKS};diff --git a/packages/database/src/datasets/data/satellite/sales.ts b/packages/database/src/datasets/data/satellite/sales.tsindex 3a6eec7c97..3286282340 100644--- a/packages/database/src/datasets/data/satellite/sales.ts+++ b/packages/database/src/datasets/data/satellite/sales.ts@@ -6,6 +6,7 @@ import type {PriceBreak,SalesData,SalesOpportunitySpec,+ SalesReturnSpec,SalesStatusOrderSpec,StaggeredDeliverySpec} from "../../types.ts";@@ -64,6 +65,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [},quote: {ref: "quote:orbsec",+ createdOffset: -330,status: "Ordered",externalNotes: "Quote for 3× ESPA-class satellite buses.",lines: [@@ -118,6 +120,8 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "NovaSat Networks",quote: {ref: "quote:novasat",+ createdOffset: -20,+ assignee: "self",status: "Sent",expirationOffset: NOVASAT_QUOTE_EXPIRATION_OFFSET,lines: [@@ -148,6 +152,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "Apex Space Research",rfq: {ref: "rfq:apex",+ assignee: "self",status: "Ready for Quote",rfqDateOffset: -285,externalNotes:@@ -168,6 +173,7 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [customer: "PolarView Earth",quote: {ref: "quote:polar",+ createdOffset: -270,status: "Ordered",lines: [{@@ -193,6 +199,182 @@ export const OPPORTUNITIES: SalesOpportunitySpec[] = [}]}+ },++ {+ log: "opportunity 5 — RFQ draft (Apex, radiation test frame)",+ ref: "opp:apex-frame",+ customer: "Apex Space Research",+ rfq: {+ ref: "rfq:apex-frame",+ assignee: "self",+ status: "Draft",+ rfqDateOffset: -3,+ externalNotes:+ "Inquiry being logged — second structural frame for radiation test rig.",+ lines: [+ {+ item: "BUS-STR-001",+ customerPartId: "APX-STR-002",+ quantity: [1],+ order: 1+ }+ ]+ }+ },+ {+ log: "opportunity 6 — no-quoted RFQ, lost quote (ORBSEC crewed-rating)",+ ref: "opp:orbsec-crewed",+ customer: "ORBSEC Defense",+ rfq: {+ ref: "rfq:orbsec-crewed",+ status: "Closed",+ rfqDateOffset: -95,+ expirationOffset: -50,+ noQuoteReason: "Out of Scope",+ externalNotes:+ "Crewed-rated avionics variant — outside our qualification envelope.",+ lines: [+ {+ item: "ADCS-001",+ customerPartId: "ORBSEC-ADCS-CR1",+ quantity: [2],+ order: 1+ }+ ]+ },+ quote: {+ ref: "quote:orbsec-crewed",+ createdOffset: -80,+ status: "Lost",+ externalNotes: "Declined to bid the crewed-rating line.",+ lines: [+ {+ ref: "quoteline:orbsec-crewed:adcs",+ item: "ADCS-001",+ status: "No Quote",+ sortOrder: 1,+ priceBreaks: []+ }+ ]+ }+ },+ {+ log: "opportunity 7 — quote draft (PolarView imager bus)",+ ref: "opp:polar-imager",+ customer: "PolarView Earth",+ quote: {+ ref: "quote:polar-imager",+ createdOffset: -4,+ assignee: "self",+ status: "Draft",+ externalNotes:+ "Working draft — imager-optimized bus pricing in progress.",+ lines: [+ {+ ref: "quoteline:polar-imager:sat",+ configuration: {+ payload_mass_kg: 180,+ orbit_regime: "SSO",+ propulsion_module: true+ },+ item: "SAT-1000",+ status: "Not Started",+ sortOrder: 1,+ priceBreaks: [{ quantity: 1, unitPrice: 1850000, leadTime: 250 }]+ }+ ]+ }+ },+ {+ log: "opportunity 8 — partial quote (NovaSat gateway subsystems)",+ ref: "opp:novasat-gateway",+ customer: "NovaSat Networks",+ quote: {+ ref: "quote:novasat-gateway",+ createdOffset: -9,+ status: "Partial",+ expirationOffset: 45,+ externalNotes:+ "EPS line released to the customer; comms line still in engineering review.",+ lines: [+ {+ ref: "quoteline:novasat-gateway:eps",+ item: "EPS-001",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 2, unitPrice: 122000, leadTime: 140 }]+ },+ {+ ref: "quoteline:novasat-gateway:comms",+ item: "COMMS-001",+ status: "In Progress",+ sortOrder: 2,+ priceBreaks: [{ quantity: 2, unitPrice: 112000, leadTime: 160 }]+ }+ ]+ }+ },+ {+ log: "opportunity 9 — cancelled quote (Apex cubesat pathfinder)",+ ref: "opp:apex-pathfinder",+ customer: "Apex Space Research",+ quote: {+ ref: "quote:apex-pathfinder",+ createdOffset: -150,+ status: "Cancelled",+ externalNotes: "Program defunded before pricing was issued.",+ lines: [+ {+ ref: "quoteline:apex-pathfinder:eps",+ item: "EPS-001",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 1, unitPrice: 126000, leadTime: 130 }]+ }+ ]+ }+ },+ {+ log: "opportunity 10 — expired quote (PolarView spare wing)",+ ref: "opp:polar-wing",+ customer: "PolarView Earth",+ quote: {+ ref: "quote:polar-wing",+ createdOffset: -44,+ status: "Expired",+ expirationOffset: -14,+ externalNotes: "30-day pricing lapsed without a PO.",+ lines: [+ {+ ref: "quoteline:polar-wing:saw",+ item: "SAW-001",+ status: "Complete",+ sortOrder: 1,+ priceBreaks: [{ quantity: 1, unitPrice: 36500, leadTime: 90 }]+ }+ ]+ }+ },+ {+ log: "sales order — Needs Approval (ORBSEC propulsion spares)",+ ref: "opp:orbsec-prop",+ customer: "ORBSEC Defense",+ order: {+ ref: "so:orbsec-prop",+ assignee: "self",+ status: "Needs Approval",+ orderDateOffset: -2,+ lines: [+ {+ ref: "soline:orbsec-prop:tank",+ item: "TANK-TI-4L",+ saleQuantity: 2,+ unitPrice: 4800,+ status: "Ordered"+ }+ ]+ }}];@@ -266,6 +448,7 @@ export const RELEASED_ORDERS: SalesOpportunitySpec[] = [customer: "NovaSat Networks",order: {ref: "so:toshipinvoice",+ assignee: "self",status: "To Ship and Invoice",orderDateOffset: -10,lines: STAGGERED_DELIVERIES.map((delivery) => ({@@ -280,11 +463,547 @@ export const RELEASED_ORDERS: SalesOpportunitySpec[] = [sortOrder: delivery.sortOrder}))}+ },++ // Shipped items are well-stocked untracked buy parts (spares sold from the+ // shelf), so the ledger rows never overdraw a bin.+ {+ log: "sales order — To Invoice (NovaSat, posted spare-transponder shipment)",+ ref: "opp:novasat-spares",+ customer: "NovaSat Networks",+ order: {+ ref: "so:novasat-spares",+ status: "To Invoice",+ orderDateOffset: -30,+ lines: [+ {+ ref: "soline:novasat-spares:txrx",+ item: "TXRX-SBAND",+ saleQuantity: 2,+ unitPrice: 15900,+ status: "Completed"+ }+ ]+ },+ shipment: {+ ref: "shp:novasat-spares",+ status: "Posted",+ postedOffset: -18,+ lines: [+ {+ item: "TXRX-SBAND",+ orderQuantity: 2,+ outstandingQuantity: 0,+ shippedQuantity: 2,+ unitPrice: 15900,+ fromShelf: "A2-L2"+ }+ ]+ }+ },+ {+ log: "sales order — To Ship and Invoice (ORBSEC, partial thruster shipment)",+ ref: "opp:orbsec-thrusters",+ customer: "ORBSEC Defense",+ order: {+ ref: "so:orbsec-thrusters",+ status: "To Ship and Invoice",+ orderDateOffset: -21,+ lines: [+ {+ ref: "soline:orbsec-thrusters:thr",+ item: "THR-HYDRA-1N",+ saleQuantity: 4,+ unitPrice: 11400,+ status: "In Progress"+ }+ ]+ },+ shipment: {+ ref: "shp:orbsec-thrusters",+ status: "Posted",+ postedOffset: -9,+ lines: [+ {+ item: "THR-HYDRA-1N",+ orderQuantity: 4,+ outstandingQuantity: 2,+ shippedQuantity: 2,+ unitPrice: 11400,+ fromShelf: "A3-L1"+ }+ ]+ }+ },+ {+ log: "sales order — To Ship (Apex, voided valve shipment)",+ ref: "opp:apex-valves",+ customer: "Apex Space Research",+ order: {+ ref: "so:apex-valves",+ status: "To Ship",+ orderDateOffset: -14,+ lines: [+ {+ ref: "soline:apex-valves:vlv",+ item: "VLV-SOLENOID-LP",+ saleQuantity: 8,+ unitPrice: 1550,+ status: "Ordered"+ }+ ]+ },+ shipment: {+ ref: "shp:apex-valves",+ status: "Voided",+ lines: [+ {+ item: "VLV-SOLENOID-LP",+ orderQuantity: 8,+ outstandingQuantity: 8,+ shippedQuantity: 0,+ unitPrice: 1550+ }+ ]+ }+ },++ // accounting.ts settles "paid" and "partial" by these sinv keys.+ {+ log: "sales invoice — Submitted (PolarView bearing spares)",+ ref: "opp:polar-bearings",+ customer: "PolarView Earth",+ order: {+ ref: "so:polar-bearings",+ status: "Invoiced",+ orderDateOffset: -35,+ lines: [+ {+ ref: "soline:polar-bearings:brg",+ item: "BRG-6201",+ saleQuantity: 20,+ unitPrice: 27,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:polar-bearings",+ key: "submitted",+ status: "Submitted",+ subtotal: 540,+ totalAmount: 540,+ dateIssuedOffset: -20,+ dueDateOffset: 10,+ lines: [{ item: "BRG-6201", quantity: 20, unitPrice: 27 }]+ }+ },+ {+ log: "sales invoice — Overdue (NovaSat propellant tank)",+ ref: "opp:novasat-tank",+ customer: "NovaSat Networks",+ order: {+ ref: "so:novasat-tank",+ status: "Invoiced",+ orderDateOffset: -60,+ lines: [+ {+ ref: "soline:novasat-tank:tank",+ item: "TANK-TI-4L",+ saleQuantity: 1,+ unitPrice: 4800,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:novasat-tank",+ key: "overdue",+ status: "Overdue",+ subtotal: 4800,+ totalAmount: 4800,+ dateIssuedOffset: -45,+ dueDateOffset: -15,+ lines: [{ item: "TANK-TI-4L", quantity: 1, unitPrice: 4800 }]+ }+ },+ {+ log: "sales invoice — Paid (ORBSEC titanium fastener lot)",+ ref: "opp:orbsec-fasteners",+ customer: "ORBSEC Defense",+ order: {+ ref: "so:orbsec-fasteners",+ status: "Closed",+ orderDateOffset: -90,+ lines: [+ {+ ref: "soline:orbsec-fasteners:fst",+ item: "FST-M4-TI",+ saleQuantity: 500,+ unitPrice: 4,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:orbsec-fasteners",+ key: "paid",+ status: "Paid",+ subtotal: 2000,+ totalAmount: 2000,+ dateIssuedOffset: -75,+ dueDateOffset: -45,+ lines: [{ item: "FST-M4-TI", quantity: 500, unitPrice: 4 }]+ }+ },+ {+ log: "sales invoice — Partially Paid (Apex star tracker)",+ ref: "opp:apex-tracker",+ customer: "Apex Space Research",+ order: {+ ref: "so:apex-tracker",+ status: "Invoiced",+ orderDateOffset: -50,+ lines: [+ {+ ref: "soline:apex-tracker:st",+ item: "ST-050",+ saleQuantity: 1,+ unitPrice: 42000,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:apex-tracker",+ key: "partial",+ status: "Partially Paid",+ subtotal: 42000,+ totalAmount: 42000,+ dateIssuedOffset: -38,+ dueDateOffset: -8,+ lines: [{ item: "ST-050", quantity: 1, unitPrice: 42000 }]+ }+ },+ {+ log: "sales invoice — Voided (PolarView A286 fasteners, wrong bill-to)",+ ref: "opp:polar-fasteners",+ customer: "PolarView Earth",+ order: {+ ref: "so:polar-fasteners",+ status: "To Invoice",+ orderDateOffset: -28,+ lines: [+ {+ ref: "soline:polar-fasteners:fst",+ item: "FST-M6-A286",+ saleQuantity: 100,+ unitPrice: 8,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:polar-fasteners",+ key: "voided",+ status: "Voided",+ subtotal: 800,+ totalAmount: 800,+ dateIssuedOffset: -25,+ lines: [{ item: "FST-M6-A286", quantity: 100, unitPrice: 8 }]+ }+ },+ {+ log: "sales invoice — Credit Note Issued (NovaSat solenoid valves)",+ ref: "opp:novasat-valves",+ customer: "NovaSat Networks",+ order: {+ ref: "so:novasat-valves",+ status: "Closed",+ orderDateOffset: -70,+ lines: [+ {+ ref: "soline:novasat-valves:vlv",+ item: "VLV-SOLENOID-LP",+ saleQuantity: 2,+ unitPrice: 1425,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:novasat-valves",+ key: "credit",+ status: "Credit Note Issued",+ subtotal: 2850,+ totalAmount: 2850,+ dateIssuedOffset: -55,+ dueDateOffset: -25,+ lines: [{ item: "VLV-SOLENOID-LP", quantity: 2, unitPrice: 1425 }]+ }+ },++ // Older overdue invoices, so receivables aging fills every bucket to 61–90.+ {+ log: "sales invoice — Overdue 31–60 days (Apex solenoid valve spares)",+ ref: "opp:apex-valve-spares",+ customer: "Apex Space Research",+ order: {+ ref: "so:apex-valve-spares",+ status: "Invoiced",+ orderDateOffset: -90,+ lines: [+ {+ ref: "soline:apex-valve-spares:vlv",+ item: "VLV-SOLENOID-LP",+ saleQuantity: 4,+ unitPrice: 1425,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:apex-valve-spares",+ status: "Overdue",+ subtotal: 5700,+ totalAmount: 5700,+ dateIssuedOffset: -75,+ dueDateOffset: -45,+ lines: [{ item: "VLV-SOLENOID-LP", quantity: 4, unitPrice: 1425 }]+ }+ },+ {+ log: "sales invoice — Overdue 61–90 days (PolarView propellant tank)",+ ref: "opp:polar-tank",+ customer: "PolarView Earth",+ order: {+ ref: "so:polar-tank",+ status: "Invoiced",+ orderDateOffset: -120,+ lines: [+ {+ ref: "soline:polar-tank:tank",+ item: "TANK-TI-4L",+ saleQuantity: 1,+ unitPrice: 4800,+ status: "Completed"+ }+ ]+ },+ invoice: {+ ref: "inv:polar-tank",+ status: "Overdue",+ subtotal: 4800,+ totalAmount: 4800,+ dateIssuedOffset: -105,+ dueDateOffset: -75,+ lines: [{ item: "TANK-TI-4L", quantity: 1, unitPrice: 4800 }]+ }+ },++ // Each line has a job of its own in production.ts (open or just completed).+ {+ log: "sales order — In Progress (NovaSat subsystem spares, floor load)",+ ref: "opp:floor-novasat",+ customer: "NovaSat Networks",+ order: {+ ref: "so:floor-novasat",+ status: "In Progress",+ orderDateOffset: -32,+ lines: [+ {+ ref: "soline:floor-novasat:eps-pcb",+ item: "PCB-EPS-R1",+ saleQuantity: 4,+ unitPrice: 4200,+ status: "In Progress",+ promisedDateOffset: 5+ },+ {+ ref: "soline:floor-novasat:adcs-pcb",+ item: "PCB-ADCS-R1",+ saleQuantity: 2,+ unitPrice: 5800,+ status: "In Progress",+ promisedDateOffset: 3+ },+ {+ ref: "soline:floor-novasat:saw",+ item: "SAW-001",+ saleQuantity: 1,+ unitPrice: 35000,+ status: "In Progress",+ promisedDateOffset: 3+ },+ {+ ref: "soline:floor-novasat:bus",+ item: "BUS-STR-001",+ saleQuantity: 1,+ unitPrice: 45000,+ status: "In Progress",+ promisedDateOffset: 4+ },+ {+ ref: "soline:floor-novasat:antenna",+ item: "ANT-PATCH-01",+ saleQuantity: 4,+ unitPrice: 1800,+ status: "In Progress",+ promisedDateOffset: 2+ }+ ]+ }+ },+ {+ log: "sales order — In Progress (PolarView constellation refit, floor load)",+ ref: "opp:floor-polar",+ customer: "PolarView Earth",+ order: {+ ref: "so:floor-polar",+ assignee: "self",+ status: "In Progress",+ orderDateOffset: -14,+ lines: [+ {+ ref: "soline:floor-polar:adcs-pcb",+ item: "PCB-ADCS-R1",+ saleQuantity: 3,+ unitPrice: 5800,+ status: "In Progress",+ promisedDateOffset: 8+ },+ {+ ref: "soline:floor-polar:bus",+ item: "BUS-STR-001",+ saleQuantity: 1,+ unitPrice: 45000,+ status: "In Progress",+ promisedDateOffset: 15+ },+ {+ ref: "soline:floor-polar:saw",+ item: "SAW-001",+ saleQuantity: 2,+ unitPrice: 35000,+ status: "In Progress",+ promisedDateOffset: 10+ },+ {+ ref: "soline:floor-polar:prop",+ item: "PROP-001",+ saleQuantity: 1,+ unitPrice: 38000,+ status: "In Progress",+ promisedDateOffset: 24+ },+ {+ ref: "soline:floor-polar:comms",+ item: "COMMS-001",+ saleQuantity: 1,+ unitPrice: 28000,+ status: "In Progress",+ promisedDateOffset: 19+ },+ {+ ref: "soline:floor-polar:harness",+ item: "HARNESS-001",+ saleQuantity: 2,+ unitPrice: 12000,+ status: "In Progress",+ promisedDateOffset: 30+ }+ ]+ }+ }+];++// Quantities come from the posted shipments above; the Completed RMA books+// stock back into the shelf it shipped from.+export const SALES_RETURNS: SalesReturnSpec[] = [+ {+ key: "transponder",+ credit: {+ status: "Posted",+ dateOffset: -8,+ lines: [{ line: 1, quantity: 1 }]+ },+ status: "Completed",+ customer: "NovaSat Networks",+ returnReason: "Defective",+ dateOffset: -12,+ salesOrder: "so:novasat-spares",+ lines: [+ { item: "TXRX-SBAND", quantity: 1, unitPrice: 15900, toShelf: "A2-L2" }+ ]+ },+ {+ key: "thruster",+ status: "To Receive",+ customer: "ORBSEC Defense",+ returnReason: "Damaged in Transit",+ dateOffset: -5,+ salesOrder: "so:orbsec-thrusters",+ lines: [{ item: "THR-HYDRA-1N", quantity: 1, unitPrice: 11400 }]+ },+ {+ key: "bearings",+ status: "Draft",+ customer: "PolarView Earth",+ returnReason: "No Longer Needed",+ dateOffset: -1,+ salesOrder: "so:polar-bearings",+ lines: [{ item: "BRG-6201", quantity: 4, unitPrice: 27 }]}];export const satelliteSales: SalesData = {opportunities: OPPORTUNITIES,statusOrders: STATUS_ORDERS,- releasedOrders: RELEASED_ORDERS+ releasedOrders: RELEASED_ORDERS,+ salesReturns: SALES_RETURNS,+ customerPortals: ["NovaSat Networks", "ORBSEC Defense"],+ customerBankAccounts: [+ {+ customer: "ORBSEC Defense",+ name: "ORBSEC remittance",+ bankName: "Potomac Federal Trust (demo)",+ accountHolderName: "ORBSEC Defense Programs LLC",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-4410-2291",+ bankCode: "DEMO-054001",+ isPrimary: true+ },+ {+ customer: "NovaSat Networks",+ name: "NovaSat operating account",+ bankName: "Bay Commerce Bank (demo)",+ accountHolderName: "NovaSat Networks Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-7730-1184",+ bankCode: "DEMO-121000",+ isPrimary: true+ },+ {+ customer: "Apex Space Research",+ name: "Apex grants account",+ bankName: "Commonwealth Scholars Bank (demo)",+ accountHolderName: "Apex Space Research Foundation",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-2208-5563",+ isPrimary: true+ },+ {+ customer: "PolarView Earth",+ name: "PolarView payables",+ bankName: "Hill Country Bank (demo)",+ accountHolderName: "PolarView Earth Inc.",+ countryCode: "US",+ currencyCode: "USD",+ accountNumber: "DEMO-9051-3370",+ isPrimary: true+ }+ ]};diff --git a/packages/database/src/datasets/data/satellite/workflows.ts b/packages/database/src/datasets/data/satellite/workflows.tsindex 6d0faa4570..7d6beb6d73 100644--- a/packages/database/src/datasets/data/satellite/workflows.ts+++ b/packages/database/src/datasets/data/satellite/workflows.ts@@ -1,5 +1,4 @@-import type { Edge, SeedWorkflow } from "../../tiers/workflow-definitions.ts";-import type { WorkflowData } from "../../types.ts";+import type { Edge, SeedWorkflow, WorkflowData } from "../../types.ts";// A factory, not a constant: every definition names ids that only exist once the seed has run.@@ -508,4 +507,38 @@ export function buildSeedWorkflows(refs: {];}-export const satelliteWorkflows: WorkflowData = { build: buildSeedWorkflows };+// The queued run was skipped at load while the workflow was briefly unpublished,+// so it has no steps.+export const satelliteWorkflows: WorkflowData = {+ build: buildSeedWorkflows,+ runs: [+ {+ workflow: "Assign new sales orders",+ status: "Succeeded",+ triggerRef: "so:apex-valves",+ at: { offset: -14, time: "15:02:11" },+ steps: [{ nodeId: "action_assign", status: "Succeeded" }]+ },+ {+ workflow: "Assign new sales orders",+ status: "Failed",+ triggerRef: "so:polar-fasteners",+ at: { offset: -28, time: "10:47:33" },+ steps: [+ {+ nodeId: "action_assign",+ status: "Failed",+ error: "The assignee you chose is not in this company."+ }+ ]+ },+ {+ workflow: "Assign new sales orders",+ status: "Skipped",+ triggerRef: "so:orbsec-thrusters",+ at: { offset: -21, time: "09:15:04" },+ statusReason: "This workflow was unpublished before the run started.",+ steps: []+ }+ ]+};diff --git a/packages/database/src/datasets/dates.ts b/packages/database/src/datasets/dates.tsindex cc879bd695..fba0e3f775 100644--- a/packages/database/src/datasets/dates.ts+++ b/packages/database/src/datasets/dates.ts@@ -10,11 +10,10 @@import {type CalendarDate,endOfMonth,+ startOfMonth,startOfWeek} from "@internationalized/date";--/** Signed days relative to the dataset anchor. Negative = in the past. */-export type DayOffset = number;+import type { DayOffset } from "./types.ts";/** "YYYY-MM-DD" for a DATE column. */export function resolveDate(anchor: CalendarDate, offset: DayOffset): string {@@ -38,6 +37,28 @@ export function previousMonthEnd(anchor: CalendarDate): string {return endOfMonth(anchor.subtract({ months: 1 })).toString();}+// Seeded accounting periods: trailing months ending with the anchor's. Close is+// sequential, so the oldest are Closed, the next Locked, the rest Open.+export const SEEDED_PERIOD_MONTHS = 12;+export const CLOSED_PERIOD_MONTHS_BACK = [11, 10] as const;+export const LOCKED_PERIOD_MONTHS_BACK = 9;+/**+ * Offsets ≥ this land in month anchor−9 or later, never a Closed period (whose+ * journals the period-open trigger rejects). Nine shortest months = 273 days.+ */+export const NOT_CLOSED_MIN_OFFSET = -273;+/** Offsets ≥ this land in an Open period (month anchor−8 or later; 8 shortest months = 242 days). */+export const OPEN_PERIOD_MIN_OFFSET = -242;++/** `monthsBack` 0 = the anchor's own month. */+export function monthBack(+ anchor: CalendarDate,+ monthsBack: number+): { start: CalendarDate; end: CalendarDate } {+ const month = anchor.subtract({ months: monthsBack });+ return { start: startOfMonth(month), end: endOfMonth(month) };+}+/*** `count` consecutive Sunday-start weeks beginning with the anchor's own week.* Mirrors getOrCreatePeriods' startOfWeek(today, "en-US") so the seeded periodsdiff --git a/packages/database/src/datasets/helpers/bootstrap-lookup.ts b/packages/database/src/datasets/helpers/bootstrap-lookup.tsnew file mode 100644index 0000000000..a8d8bdb48d--- /dev/null+++ b/packages/database/src/datasets/helpers/bootstrap-lookup.ts@@ -0,0 +1,26 @@+import { maybeOne, quote } from "../sql.ts";+import type { Ctx } from "../types.ts";++/**+ * Cached in ctx.refs.misc — never module scope, which would leak across the+ * drift check's four companies.+ */+export async function bootstrapIdByName(+ ctx: Ctx,+ table: string,+ name: string+): Promise<string> {+ const key = `${table}:${name}`;+ const cached = ctx.refs.misc[key];+ if (cached) return cached;+ const row = await maybeOne<{ id: string }>(+ ctx.client,+ `SELECT id FROM ${quote(table)} WHERE "companyId" = $1 AND name = $2`,+ [ctx.companyId, name]+ );+ if (!row) {+ throw new Error(`Seed: no ${table} named "${name}"`);+ }+ ctx.refs.misc[key] = row.id;+ return row.id;+}diff --git a/packages/database/src/datasets/helpers/inspection.ts b/packages/database/src/datasets/helpers/inspection.tsnew file mode 100644index 0000000000..c432246479--- /dev/null+++ b/packages/database/src/datasets/helpers/inspection.ts@@ -0,0 +1,65 @@+// Pure inspection math shared by tier 07 and the validator, so the seeded+// sample statuses are exactly what the engine would have derived.++import {+ deriveSampleStatus as deriveVerdict,+ type InspectionVerdict,+ valuateMeasurement+} from "../../../supabase/functions/shared/inspection-verdict.ts";+import { resolveSamplingPlan, type SamplingResult } from "../../sampling.ts";+import type { InspectionFeatureSpec, InspectionSampleSpec } from "../types.ts";++export const SEED_SAMPLING_STANDARD = "ANSI_Z1_4" as const;++export function inspectionPlan(spec: { aql: number }) {+ return {+ type: "AQL" as const,+ aql: spec.aql,+ inspectionLevel: "II" as const,+ severity: "Normal" as const+ };+}++/**+ * The lot plan post-receipt / getOrCreateJobOperationInspection snapshot. Every+ * feature inherits the document default, so each feature's plan equals it.+ */+export function resolveInspectionPlan(+ spec: { aql: number },+ lotSize: number+): SamplingResult {+ return resolveSamplingPlan(+ inspectionPlan(spec),+ lotSize,+ SEED_SAMPLING_STANDARD+ );+}++/** Tier 07 writes every feature as a numeric Measurement. */+export function valuateReading(+ feature: InspectionFeatureSpec,+ value: number+): InspectionVerdict {+ return valuateMeasurement({ type: "Measurement", ...feature }, value);+}++/** upsertInspectionMeasurement's derivation over the sample's readings. */+export function deriveSampleStatus(+ features: InspectionFeatureSpec[],+ sample: InspectionSampleSpec+): InspectionVerdict {+ return deriveVerdict(+ features.map((f) => f.label),+ sample.measurements.flatMap((reading) => {+ const feature = features.find((f) => f.label === reading.feature);+ return feature+ ? [+ {+ inspectionFeatureId: feature.label,+ status: valuateReading(feature, reading.value)+ }+ ]+ : [];+ })+ );+}diff --git a/packages/database/src/datasets/helpers/items.ts b/packages/database/src/datasets/helpers/items.tsindex 9f25a57ada..a660859bae 100644--- a/packages/database/src/datasets/helpers/items.ts+++ b/packages/database/src/datasets/helpers/items.ts@@ -1,23 +1,13 @@import { assertSingle, insertId, insertMaybe, maybeOne } from "../sql.ts";-import type { Ctx, ItemRef, ItemType } from "../types.ts";--export type ItemSpec = {- readableId: string;- revision?: string;- name: string;- type: ItemType;- replenishment?: "Buy" | "Make" | "Buy and Make";- defaultMethodType?:- | "Pull from Inventory"- | "Purchase to Order"- | "Make to Order";- trackingType?: "Inventory" | "Non-Inventory" | "Serial" | "Batch";- unitOfMeasureCode?: string;- standardCost?: number;- unitSalePrice?: number;- leadTime?: number;- description?: string;-};+import type {+ Ctx,+ ItemRef,+ ItemSpec,+ ItemType,+ MethodType,+ OperationType+} from "../types.ts";+import { bootstrapIdByName } from "./bootstrap-lookup.ts";/*** Inserts an item and its positional extension row, then activates the@@ -71,7 +61,9 @@ export async function createItem(ctx: Ctx, spec: ItemSpec): Promise<ItemRef> {thumbnailPath: ctx.dataset.industryId? `_templates/${ctx.dataset.industryId}/${spec.readableId}.svg`: null,- active: true+ active: spec.active ?? true,+ // undefined is dropped by insertRow, keeping the column default.+ revisionStatus: spec.revisionStatus});// The item interceptor creates itemCost, itemReplenishment, itemUnitSalePrice,@@ -80,18 +72,45 @@ export async function createItem(ctx: Ctx, spec: ItemSpec): Promise<ItemRef> {// Positional extension row (part.id = readableId). All revisions share one row.const extensionTable = extensionTableFor(spec.type);+ const classification = spec.material;+ const lookup = (table: string, name: string | undefined) =>+ name ? bootstrapIdByName(ctx, table, name) : undefined;+ const taxonomy =+ spec.type === "Material" && classification+ ? {+ materialSubstanceId: await lookup(+ "materialSubstance",+ classification.substance+ ),+ materialFormId: await lookup("materialForm", classification.form),+ materialTypeId: await lookup(+ "materialType",+ classification.materialType+ ),+ gradeId: await lookup("materialGrade", classification.grade),+ finishId: await lookup("materialFinish", classification.finish),+ dimensionId: await lookup(+ "materialDimension",+ classification.dimension+ )+ }+ : {};await insertMaybe(ctx, extensionTable, {id: spec.readableId,approved: true,companyId,- createdBy: userId+ createdBy: userId,+ ...taxonomy});// Apply cost/price/lead-time by UPDATE (not insert).+ // unitCost too: FIFO valuation and calculateCOGS fall back to it for stock no+ // cost layer covers (opening stock, job output).if (spec.standardCost !== undefined) {await client.query(- `UPDATE "itemCost" SET "standardCost" = $1 WHERE "itemId" = $2`,- [spec.standardCost, itemId]+ `UPDATE "itemCost" SET "standardCost" = $1, "unitCost" = $1+ WHERE "itemId" = $2 AND "companyId" = $3`,+ [spec.standardCost, itemId, companyId]);}if (spec.unitSalePrice !== undefined) {@@ -107,9 +126,8 @@ export async function createItem(ctx: Ctx, spec: ItemSpec): Promise<ItemRef> {);}- // For Part / Tool / Service the interceptor created a Draft makeMethod. Leave- // it Draft — Active freezes the BOM and BOP, and a demo company should be able- // to edit them without first cutting a new version.+ // For Part / Tool / Service the interceptor created a Draft makeMethod; tier 02+ // releases the authored ones (Active) once their BOM and BOP are written.let makeMethodId: string | null = null;if (["Part", "Tool", "Service"].includes(spec.type)) {const mmRow = await maybeOne<{ id: string }>(@@ -185,17 +203,6 @@ export async function addBomLine(});}-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,@@ -215,6 +222,7 @@ export async function addBopOperation(operationLeadTime?: number;operationUnitCost?: number;procedureId?: string;+ inspectionDocumentId?: string;} = {}): Promise<string> {return insertId(ctx, "methodOperation", {@@ -231,6 +239,7 @@ export async function addBopOperation(operationSupplierProcessId: opts.operationSupplierProcessId ?? null,operationLeadTime: opts.operationLeadTime ?? 0,operationUnitCost: opts.operationUnitCost ?? 0,- procedureId: opts.procedureId ?? null+ procedureId: opts.procedureId ?? null,+ inspectionDocumentId: opts.inspectionDocumentId ?? null});}diff --git a/packages/database/src/datasets/helpers/job-method.ts b/packages/database/src/datasets/helpers/job-method.tsdeleted file mode 100644index e9c672aeee..0000000000--- a/packages/database/src/datasets/helpers/job-method.ts+++ /dev/null@@ -1,328 +0,0 @@-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;-}--// Prefers Active, but the seeded methods are Draft so a demo can edit them —-// fall back to the newest version rather than leaving the job without a method.-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- ORDER BY (status = 'Active') DESC, 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/datasets/helpers/memo.ts b/packages/database/src/datasets/helpers/memo.tsnew file mode 100644index 0000000000..95b417d6b8--- /dev/null+++ b/packages/database/src/datasets/helpers/memo.ts@@ -0,0 +1,78 @@+import { resolveDate, resolveTimestamp } from "../dates.ts";+import { insertId, nextSequence, one } from "../sql.ts";+import type { Ctx, DayOffset } from "../types.ts";++export type MemoInsert = {+ direction: "Credit" | "Debit";+ partyId: string;+ status: "Draft" | "Posted";+ dateOffset: DayOffset;+ amount: number;+ currencyCode: string;+ exchangeRate: number;+ reference: string;+ salesReturnOrderId?: string;+ purchaseReturnOrderId?: string;+ notes?: string;+};++/**+ * Draft is what Issue Credit writes; Posted adds post-memo's stamps. Tier 09's+ * postMemos journals every Posted one afterwards.+ */+export async function insertMemo(ctx: Ctx, memo: MemoInsert): Promise<string> {+ const isCredit = memo.direction === "Credit";+ const posted = memo.status === "Posted";+ const memoDate = resolveDate(ctx.anchor, memo.dateOffset);+ return insertId(ctx, "memo", {+ memoId: await nextSequence(ctx, isCredit ? "creditMemo" : "debitMemo"),+ direction: memo.direction,+ status: memo.status,+ customerId: isCredit ? memo.partyId : undefined,+ supplierId: isCredit ? undefined : memo.partyId,+ memoDate,+ currencyCode: memo.currencyCode,+ exchangeRate: memo.exchangeRate,+ amount: memo.amount,+ reference: memo.reference,+ salesReturnOrderId: memo.salesReturnOrderId,+ purchaseReturnOrderId: memo.purchaseReturnOrderId,+ notes: memo.notes,+ postingDate: posted ? memoDate : undefined,+ postedAt: posted+ ? resolveTimestamp(ctx.anchor, memo.dateOffset, "16:00:00")+ : undefined,+ postedBy: posted ? ctx.userId : undefined,+ reasonAccount: posted ? await reasonAccount(ctx, memo) : undefined+ });+}++/** post-memo's offset account: the return order's, else the party side's discount account. */+async function reasonAccount(ctx: Ctx, memo: MemoInsert): Promise<string> {+ const defaults = await one<{+ salesReturnsAccount: string | null;+ salesAccount: string | null;+ goodsReceivedNotInvoicedAccount: string | null;+ salesDiscountAccount: string | null;+ supplierPaymentDiscountAccount: string | null;+ }>(+ ctx.client,+ `SELECT "salesReturnsAccount", "salesAccount", "goodsReceivedNotInvoicedAccount",+ "salesDiscountAccount", "supplierPaymentDiscountAccount"+ FROM "accountDefault" WHERE "companyId" = $1`,+ [ctx.companyId]+ );+ const account = memo.salesReturnOrderId+ ? (defaults.salesReturnsAccount ?? defaults.salesAccount)+ : memo.purchaseReturnOrderId+ ? defaults.goodsReceivedNotInvoicedAccount+ : memo.direction === "Credit"+ ? defaults.salesDiscountAccount+ : defaults.supplierPaymentDiscountAccount;+ if (!account) {+ throw new Error(+ `Seed: accountDefault has no reason account for a Posted ${memo.direction} memo "${memo.reference}"`+ );+ }+ return account;+}diff --git a/packages/database/src/datasets/helpers/method-copy.ts b/packages/database/src/datasets/helpers/method-copy.tsnew file mode 100644index 0000000000..224b82569c--- /dev/null+++ b/packages/database/src/datasets/helpers/method-copy.ts@@ -0,0 +1,500 @@+import {+ insertId,+ maybeOne,+ need,+ one,+ type Row,+ rows,+ sharedColumns+} from "../sql.ts";+import type { Ctx } from "../types.ts";++/**+ * The seed's copy of the `get-method` edge function, which it cannot invoke from+ * inside its one SQL transaction. Narrower on purpose: no configuration rules,+ * supersession redirect, assembly-instruction step expansion or method steps.+ */++export type JobOperationStatus =+ | "Todo"+ | "Ready"+ | "Waiting"+ | "In Progress"+ | "Paused"+ | "Done"+ | "Canceled";++export type CopyMethodResult = {+ operations: number;+ materials: number;+ levels: number;+};++type Kind = "method" | "job" | "quote";++const TABLES: Record<+ Kind,+ { operation: string; material: string; tool: string; parameter: string }+> = {+ method: {+ operation: "methodOperation",+ material: "methodMaterial",+ tool: "methodOperationTool",+ parameter: "methodOperationParameter"+ },+ job: {+ operation: "jobOperation",+ material: "jobMaterial",+ tool: "jobOperationTool",+ parameter: "jobOperationParameter"+ },+ quote: {+ operation: "quoteOperation",+ material: "quoteMaterial",+ tool: "quoteOperationTool",+ parameter: "quoteOperationParameter"+ }+};++// get-method gives job/quote rows fresh customFields.+const NEVER_COPIED = [+ "id",+ "makeMethodId",+ "companyId",+ "createdAt",+ "createdBy",+ "updatedAt",+ "updatedBy",+ "productionQuantity"+];++type SourceOperation = Row & {+ id: string;+ procedureId: string | null;+ procedureFound: boolean;+ procedureContent: unknown;+ workInstruction: unknown;+ operationUnitCost: string | null;+ operationMinimumCost: string | null;+ supplierMinimumCost: string;+ supplierLeadTime: string;+ laborRate: string;+ machineRate: string;+ overheadRate: string;+};++type SourceMaterial = Row & {+ itemId: string;+ methodType: string;+ materialMakeMethodId: string | null;+ quantity: string;+ methodOperationId: string | null;+ itemName: string;+ itemTrackingType: string;+ standardCost: string | null;+ defaultStorageUnitId: string | null;+};++type Level = { makeMethodId: string; quantity: number };++type Target = {+ kind: Kind;+ locationId: string | null;+ operation: (op: SourceOperation, level: Level) => Row;+ material: (+ material: SourceMaterial,+ operationId: string | null,+ level: Level+ ) => Row;+ /** Absent for a method → method copy, which (like get-method's) copies one level. */+ adoptChild?: (+ materialId: string,+ quantityPerParent: number+ ) => Promise<string>;+};++export async function copyMethodToJob(+ ctx: Ctx,+ jobId: string,+ quantity: number,+ status: JobOperationStatus = "Todo"+): Promise<CopyMethodResult> {+ const root = await one<{ id: string; itemId: string }>(+ ctx.client,+ `SELECT id, "itemId" FROM "jobMakeMethod"+ WHERE "jobId" = $1 AND "parentMaterialId" IS NULL AND "companyId" = $2`,+ [jobId, ctx.companyId]+ );+ const target: Target = {+ kind: "job",+ locationId: null,+ operation: (op, level) => ({+ jobId,+ jobMakeMethodId: level.makeMethodId,+ operationMinimumCost: op.supplierMinimumCost,+ workInstruction: op.procedureId+ ? (op.procedureContent ?? {})+ : op.workInstruction,+ operationQuantity: level.quantity,+ targetQuantity: level.quantity,+ status+ }),+ material: (material, operationId, level) => ({+ jobId,+ jobMakeMethodId: level.makeMethodId,+ jobOperationId: operationId,+ ...materialCore(material),+ quantity: material.quantity,+ estimatedQuantity: Number(material.quantity) * level.quantity,+ requiresSerialTracking: material.itemTrackingType === "Serial",+ requiresBatchTracking: material.itemTrackingType === "Batch"+ }),+ adoptChild: async (materialId, quantityPerParent) =>+ adopted(+ await maybeOne<{ id: string }>(+ ctx.client,+ `UPDATE "jobMakeMethod" SET "quantityPerParent" = $4+ WHERE "jobId" = $1 AND "parentMaterialId" = $2 AND "companyId" = $3+ RETURNING id`,+ [jobId, materialId, ctx.companyId, quantityPerParent]+ ),+ `job material ${materialId}`+ )+ };+ return copyTree(ctx, target, root, quantity);+}++export async function copyMethodToQuoteLine(+ ctx: Ctx,+ quoteId: string,+ quoteLineId: string+): Promise<CopyMethodResult> {+ const root = await one<{ id: string; itemId: string }>(+ ctx.client,+ `SELECT id, "itemId" FROM "quoteMakeMethod"+ WHERE "quoteLineId" = $1 AND "parentMaterialId" IS NULL AND "companyId" = $2`,+ [quoteLineId, ctx.companyId]+ );+ const { locationId } = await one<{ locationId: string | null }>(+ ctx.client,+ `SELECT "locationId" FROM quote WHERE id = $1 AND "companyId" = $2`,+ [quoteId, ctx.companyId]+ );+ const target: Target = {+ kind: "quote",+ locationId,+ // get-method keeps the method's own minimum cost on a quote operation.+ operation: (op, level) => ({+ quoteId,+ quoteLineId,+ quoteMakeMethodId: level.makeMethodId,+ operationMinimumCost: op.operationMinimumCost ?? 0+ }),+ material: (material, operationId, level) => ({+ quoteId,+ quoteLineId,+ quoteMakeMethodId: level.makeMethodId,+ quoteOperationId: operationId,+ ...materialCore(material),+ quantity: material.quantity,+ storageUnitId: material.defaultStorageUnitId+ }),+ adoptChild: async (materialId) =>+ adopted(+ await maybeOne<{ id: string }>(+ ctx.client,+ `SELECT id FROM "quoteMakeMethod"+ WHERE "quoteLineId" = $1 AND "parentMaterialId" = $2 AND "companyId" = $3`,+ [quoteLineId, materialId, ctx.companyId]+ ),+ `quote material ${materialId}`+ )+ };+ return copyTree(ctx, target, root, 1);+}++/** Mirrors the app's `copyMakeMethod`. */+export async function copyMethodToMethod(+ ctx: Ctx,+ sourceMakeMethodId: string,+ targetMakeMethodId: string+): Promise<void> {+ const materialColumns = await sharedColumns(+ ctx.client,+ "methodMaterial",+ "methodMaterial",+ NEVER_COPIED+ );+ const target: Target = {+ kind: "method",+ locationId: null,+ operation: (_op, level) => ({ makeMethodId: level.makeMethodId }),+ material: (material, operationId, level) => ({+ ...pick(material, materialColumns),+ makeMethodId: level.makeMethodId,+ methodOperationId: operationId+ })+ };+ await copyLevel(+ ctx,+ target,+ sourceMakeMethodId,+ { makeMethodId: targetMakeMethodId, quantity: 1 },+ { operations: 0, materials: 0, levels: 0 },+ new Set([sourceMakeMethodId])+ );+}++async function copyTree(+ ctx: Ctx,+ target: Target,+ root: { id: string; itemId: string },+ quantity: number+): Promise<CopyMethodResult> {+ const makeMethodId = await methodOfItem(ctx, root.itemId);+ const result: CopyMethodResult = { operations: 0, materials: 0, levels: 0 };+ await copyLevel(+ ctx,+ target,+ makeMethodId,+ { makeMethodId: root.id, quantity },+ result,+ new Set([makeMethodId])+ );+ return result;+}++// Prefers Active; falls back to the newest version (a buy part's interceptor+// method stays Draft).+async function methodOfItem(ctx: Ctx, itemId: string): Promise<string> {+ const row = await maybeOne<{ id: string }>(+ ctx.client,+ `SELECT id FROM "makeMethod"+ WHERE "itemId" = $1 AND "companyId" = $2+ ORDER BY (status = 'Active') DESC, version DESC+ LIMIT 1`,+ [itemId, ctx.companyId]+ );+ if (!row) throw new Error(`Seed: item ${itemId} has no make method to copy`);+ return row.id;+}++function adopted(row: { id: string } | null, what: string): string {+ if (!row) {+ throw new Error(`Seed: ${what} has no interceptor child make method`);+ }+ return row.id;+}++function pick(row: Row, columns: string[]): Row {+ return Object.fromEntries(columns.map((column) => [column, row[column]]));+}++function materialCore(material: SourceMaterial): Row {+ return {+ itemId: material.itemId,+ itemType: material.itemType,+ methodType: material.methodType,+ kit: material.kit,+ order: material.order,+ description: material.itemName,+ unitOfMeasureCode: material.unitOfMeasureCode,+ unitCost: material.standardCost ?? 0+ };+}++// `visited` holds the make methods on the current path: the DB only blocks a+// method listing itself, and a longer cycle would recurse inside the open+// transaction forever.+async function copyLevel(+ ctx: Ctx,+ target: Target,+ makeMethodId: string,+ level: Level,+ result: CopyMethodResult,+ visited: Set<string>+): Promise<void> {+ result.levels += 1;+ const operationIds = await copyOperations(ctx, target, makeMethodId, level);+ result.operations += Object.keys(operationIds).length;++ const materials = await rows<SourceMaterial>(+ ctx.client,+ `SELECT mm.*, i.name AS "itemName", i."itemTrackingType",+ ic."standardCost", pm."defaultStorageUnitId"+ FROM "methodMaterial" mm+ JOIN item i ON i.id = mm."itemId" AND i."companyId" = mm."companyId"+ LEFT JOIN "itemCost" ic+ ON ic."itemId" = mm."itemId" AND ic."companyId" = mm."companyId"+ LEFT JOIN "pickMethod" pm+ ON pm."itemId" = mm."itemId" AND pm."locationId" = $3+ AND pm."companyId" = mm."companyId"+ WHERE mm."makeMethodId" = $1 AND mm."companyId" = $2+ ORDER BY mm."order"`,+ [makeMethodId, ctx.companyId, target.locationId]+ );++ for (const material of materials) {+ const operationId = material.methodOperationId+ ? need(operationIds, material.methodOperationId, "copied operation")+ : null;+ const materialId = await insertId(+ ctx,+ TABLES[target.kind].material,+ target.material(material, operationId, level)+ );+ result.materials += 1;++ if (!target.adoptChild || material.methodType !== "Make to Order") continue;++ const childMakeMethodId =+ material.materialMakeMethodId ??+ (await methodOfItem(ctx, material.itemId));+ if (visited.has(childMakeMethodId)) {+ throw new Error(+ `Seed: make method ${childMakeMethodId} is its own subassembly (BOM cycle)`+ );+ }+ const perParent = Number(material.quantity);+ const childLevel = {+ makeMethodId: await target.adoptChild(materialId, perParent),+ quantity: perParent * level.quantity+ };+ await copyLevel(+ ctx,+ target,+ childMakeMethodId,+ childLevel,+ result,+ new Set([...visited, childMakeMethodId])+ );+ }+}++async function copyOperations(+ ctx: Ctx,+ target: Target,+ makeMethodId: string,+ level: Level+): Promise<Record<string, string>> {+ const tables = TABLES[target.kind];+ const columns = await sharedColumns(+ ctx.client,+ "methodOperation",+ tables.operation,+ target.kind === "method" ? NEVER_COPIED : [...NEVER_COPIED, "customFields"]+ );+ const operations = await rows<SourceOperation>(+ ctx.client,+ `SELECT mo.*,+ p.id IS NOT NULL AS "procedureFound", p.content AS "procedureContent",+ COALESCE(sp."minimumCost", avg_sp."minimumCost", 0) AS "supplierMinimumCost",+ COALESCE(sp."leadTime", avg_sp."leadTime", 0) AS "supplierLeadTime",+ COALESCE(wc."laborRate", 0) AS "laborRate",+ COALESCE(wc."machineRate", 0) AS "machineRate",+ COALESCE(wc."overheadRate", 0) AS "overheadRate"+ FROM "methodOperation" mo+ LEFT JOIN procedure p+ ON p.id = mo."procedureId" AND p."companyId" = mo."companyId"+ LEFT JOIN "supplierProcess" sp+ ON sp.id = mo."operationSupplierProcessId" AND sp."companyId" = mo."companyId"+ LEFT JOIN LATERAL (+ SELECT avg(s."minimumCost") AS "minimumCost", avg(s."leadTime") AS "leadTime"+ FROM "supplierProcess" s+ WHERE s."processId" = mo."processId" AND s."companyId" = mo."companyId"+ ) avg_sp ON true+ LEFT JOIN "workCenter" wc+ ON wc.id = mo."workCenterId" AND wc."companyId" = mo."companyId"+ WHERE mo."makeMethodId" = $1 AND mo."companyId" = $2+ ORDER BY mo."order"`,+ [makeMethodId, ctx.companyId]+ );++ const operationIds: Record<string, string> = {};+ for (const op of operations) {+ if (op.procedureId && !op.procedureFound) {+ throw new Error(+ `Seed: operation ${op.id} names procedure ${op.procedureId}, which is not this company's`+ );+ }+ const runtime =+ target.kind === "method"+ ? {}+ : {+ laborRate: op.laborRate,+ machineRate: op.machineRate,+ overheadRate: op.overheadRate,+ operationUnitCost: op.operationUnitCost ?? 0,+ operationLeadTime: op.supplierLeadTime+ };+ const operationId = await insertId(ctx, tables.operation, {+ ...pick(op, columns),+ ...runtime,+ ...target.operation(op, level)+ });+ operationIds[op.id] = operationId;+ await copyOperationChildren(ctx, target.kind, op, operationId);+ }+ return operationIds;+}++async function copyOperationChildren(+ ctx: Ctx,+ kind: Kind,+ op: SourceOperation,+ operationId: string+): Promise<void> {+ const tables = TABLES[kind];+ const params = [op.id, operationId, ctx.companyId, ctx.userId];+ await ctx.client.query(+ `INSERT INTO "${tables.tool}"+ ("operationId", "toolId", "quantity", "companyId", "createdBy")+ SELECT $2, t."toolId", t."quantity", $3, $4+ FROM "methodOperationTool" t+ WHERE t."operationId" = $1 AND t."companyId" = $3`,+ params+ );++ if (!op.procedureId) {+ await ctx.client.query(+ `INSERT INTO "${tables.parameter}"+ ("operationId", "key", "value", "companyId", "createdBy")+ SELECT $2, p."key", p."value", $3, $4+ FROM "methodOperationParameter" p+ WHERE p."operationId" = $1 AND p."companyId" = $3`,+ params+ );+ return;+ }+ if (kind !== "job") return;++ // insertProcedureDataForJobOperation: the procedure is snapshotted onto the+ // job operation, so a later revision cannot rewrite what the floor was told.+ const procedureParams = [+ op.procedureId,+ operationId,+ ctx.companyId,+ ctx.userId+ ];+ 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 AND ps."companyId" = $3+ ORDER BY ps."sortOrder"`,+ procedureParams+ );+ await ctx.client.query(+ `INSERT INTO "jobOperationParameter"+ ("operationId", "key", "value", "companyId", "createdBy")+ SELECT $2, pp."key", pp."value", $3, $4+ FROM "procedureParameter" pp+ WHERE pp."procedureId" = $1 AND pp."companyId" = $3`,+ procedureParams+ );+}diff --git a/packages/database/src/datasets/helpers/post-documents.ts b/packages/database/src/datasets/helpers/post-documents.tsnew file mode 100644index 0000000000..29ef89750d--- /dev/null+++ b/packages/database/src/datasets/helpers/post-documents.ts@@ -0,0 +1,709 @@+import {+ assertBalanced,+ EPSILON,+ round+} from "../../../supabase/functions/shared/precision.ts";+import { insertId, insertRow, nextJournalEntryId, rows } from "../sql.ts";+import type { AccountClass, Ctx } from "../types.ts";+import {+ consumeFifo,+ type DefaultPostingRole,+ memoJournal,+ POSTING_ROLE_CLASS,+ type PostingJournal,+ paymentJournal,+ postingImbalance,+ purchaseInvoiceJournal,+ receiptJournal,+ salesInvoiceJournal,+ scrapJournal,+ shipmentJournal,+ voidJournal+} from "./posting-journals.ts";++/**+ * Writes the GL (and cost layers) the posting functions leave behind for the+ * documents tiers 04/05/09 seeded as posted.+ */++export type AccountingPeriodRange = {+ id: string;+ startDate: string;+ endDate: string;+};++export type PostingContext = {+ defaults: Record<DefaultPostingRole, string>;+ classById: Map<string, AccountClass>;+ periods: AccountingPeriodRange[];+};++export async function loadPostingContext(+ ctx: Ctx,+ periods: AccountingPeriodRange[]+): Promise<PostingContext> {+ const roles = Object.keys(POSTING_ROLE_CLASS) as DefaultPostingRole[];+ const [row] = await rows<Record<string, string | null>>(+ ctx.client,+ `SELECT ${roles.map((r) => `"${r}"`).join(", ")}+ FROM "accountDefault" WHERE "companyId" = $1`,+ [ctx.companyId]+ );+ if (!row) throw new Error("Seed: this company has no accountDefault row");+ // account is companyGroup-scoped; only active posting accounts may be booked.+ const accounts = await rows<{ id: string; class: AccountClass }>(+ ctx.client,+ `SELECT id, class FROM account+ WHERE "companyGroupId" = $1 AND "isGroup" = false AND active = true`,+ [ctx.companyGroupId]+ );+ const classById = new Map(accounts.map((a) => [a.id, a.class]));+ const defaults = {} as Record<DefaultPostingRole, string>;+ for (const role of roles) {+ const id = row[role];+ if (!id || classById.get(id) !== POSTING_ROLE_CLASS[role]) {+ throw new Error(+ `Seed: accountDefault.${role} must be an active ${POSTING_ROLE_CLASS[role]} posting account`+ );+ }+ defaults[role] = id;+ }+ return { defaults, classById, periods };+}++export function periodFor(posting: PostingContext, date: string): string {+ const period = posting.periods.find(+ (p) => p.startDate <= date && date <= p.endDate+ );+ if (!period) {+ throw new Error(`Seed: no seeded accounting period contains ${date}`);+ }+ return period.id;+}++export async function insertPostingJournal(+ ctx: Ctx,+ posting: PostingContext,+ args: {+ journal: PostingJournal;+ documentId: string;+ postingDate: string;+ reasonAccountId?: string;+ /** A void keeps its original's journalLineReferences. */+ referencePrefix?: string;+ }+): Promise<{ id: string; journalEntryId: string }> {+ const { journal } = args;+ assertBalanced(+ postingImbalance(journal),+ 0,+ EPSILON,+ `${journal.description} journal`+ );+ const journalEntryId = await nextJournalEntryId(ctx);+ const id = await insertId(ctx, "journal", {+ journalEntryId,+ accountingPeriodId: periodFor(posting, args.postingDate),+ description: journal.description,+ postingDate: args.postingDate,+ sourceType: journal.sourceType,+ status: "Posted",+ postedAt: `${args.postingDate}T17:00:00Z`,+ postedBy: ctx.userId+ });+ for (const line of journal.lines) {+ let accountId: string;+ if (line.role === "reasonAccount") {+ if (!args.reasonAccountId) {+ throw new Error(`Seed: ${journal.description} has no reason account`);+ }+ accountId = args.reasonAccountId;+ } else {+ accountId = posting.defaults[line.role];+ }+ await insertRow(ctx, "journalLine", {+ journalId: id,+ accountId,+ description: line.description,+ amount: line.amount,+ quantity: line.quantity,+ documentType: line.documentType,+ documentId: args.documentId,+ documentLineReference: line.documentLineReference ?? undefined,+ journalLineReference: `${args.referencePrefix ?? journalEntryId}-${line.group + 1}`,+ accrual: line.accrual+ });+ }+ return { id, journalEntryId };+}++/** post-sales-invoice for every non-Draft invoice; a Voided one also gets its void journal. */+export async function postSalesInvoices(+ ctx: Ctx,+ posting: PostingContext+): Promise<void> {+ const invoices = await rows<{+ id: string;+ invoiceId: string;+ status: string;+ postingDate: string | null;+ }>(+ ctx.client,+ `SELECT id, "invoiceId", status, "postingDate"::text AS "postingDate"+ FROM "salesInvoice" WHERE "companyId" = $1 AND status <> 'Draft'+ ORDER BY "postingDate", "invoiceId"`,+ [ctx.companyId]+ );+ if (invoices.length === 0) return;+ const lines = await rows<{+ invoiceId: string;+ quantity: string;+ unitPrice: string;+ salesOrderLineId: string | null;+ invoiceLineType: string;+ }>(+ ctx.client,+ `SELECT "invoiceId", quantity, "unitPrice", "salesOrderLineId", "invoiceLineType"+ FROM "salesInvoiceLine"+ WHERE "companyId" = $1 AND "invoiceId" = ANY($2::text[])+ ORDER BY "createdAt", id`,+ [ctx.companyId, invoices.map((i) => i.id)]+ );+ for (const invoice of invoices) {+ if (!invoice.postingDate) {+ throw new Error(+ `Seed: sales invoice ${invoice.invoiceId} has no postingDate`+ );+ }+ const own = lines.filter((l) => l.invoiceId === invoice.id);+ const journal = salesInvoiceJournal({+ invoiceReadableId: invoice.invoiceId,+ documentId: invoice.id,+ lines: own.map((l) => {+ if (l.invoiceLineType !== "Part" || !l.salesOrderLineId) {+ throw new Error(+ `Seed: sales invoice ${invoice.invoiceId} has a line the seeded posting shape does not cover`+ );+ }+ return {+ quantity: Number(l.quantity),+ unitPrice: Number(l.unitPrice),+ salesOrderLineId: l.salesOrderLineId+ };+ })+ });+ ctx.log(`journal — ${journal.description}`);+ const posted = await insertPostingJournal(ctx, posting, {+ journal,+ documentId: invoice.id,+ postingDate: invoice.postingDate+ });+ if (invoice.status === "Voided") {+ await insertPostingJournal(ctx, posting, {+ journal: voidJournal(journal, invoice.invoiceId),+ documentId: invoice.id,+ postingDate: invoice.postingDate,+ referencePrefix: posted.journalEntryId+ });+ }+ }+}++type PostedReceiptLine = {+ receiptId: string;+ receiptReadableId: string;+ postingDate: string;+ supplierId: string | null;+ externalDocumentId: string | null;+ purchaseOrderLineId: string;+ itemId: string;+ receivedQuantity: number;+ unitPrice: number;+ itemTrackingType: string | null;+ replenishmentSystem: string | null;+};++async function postedReceiptLines(ctx: Ctx): Promise<PostedReceiptLine[]> {+ const found = await rows<{+ receiptId: string;+ receiptReadableId: string;+ postingDate: string | null;+ supplierId: string | null;+ externalDocumentId: string | null;+ purchaseOrderLineId: string | null;+ itemId: string | null;+ receivedQuantity: string;+ unitPrice: string | null;+ itemTrackingType: string | null;+ replenishmentSystem: string | null;+ }>(+ ctx.client,+ `SELECT r.id AS "receiptId", r."receiptId" AS "receiptReadableId",+ r."postingDate"::text AS "postingDate", r."supplierId", r."externalDocumentId",+ rl."lineId" AS "purchaseOrderLineId", rl."itemId", rl."receivedQuantity",+ rl."unitPrice", i."itemTrackingType", i."replenishmentSystem"+ FROM receipt r+ JOIN "receiptLine" rl ON rl."receiptId" = r.id AND rl."companyId" = r."companyId"+ JOIN item i ON i.id = rl."itemId" AND i."companyId" = r."companyId"+ WHERE r."companyId" = $1 AND r.status = 'Posted'+ AND r."sourceDocument" = 'Purchase Order' AND rl."receivedQuantity" > 0+ ORDER BY r."postingDate", r."receiptId", rl."createdAt", rl.id`,+ [ctx.companyId]+ );+ return found.map((r) => {+ if (!r.postingDate || !r.purchaseOrderLineId || !r.itemId) {+ throw new Error(+ `Seed: posted receipt ${r.receiptReadableId} is incomplete`+ );+ }+ return {+ receiptId: r.receiptId,+ receiptReadableId: r.receiptReadableId,+ postingDate: r.postingDate,+ supplierId: r.supplierId,+ externalDocumentId: r.externalDocumentId,+ purchaseOrderLineId: r.purchaseOrderLineId,+ itemId: r.itemId,+ receivedQuantity: Number(r.receivedQuantity),+ unitPrice: Number(r.unitPrice),+ itemTrackingType: r.itemTrackingType,+ replenishmentSystem: r.replenishmentSystem+ };+ });+}++/** post-purchase-invoice for every non-Draft invoice. */+export async function postPurchaseInvoices(+ ctx: Ctx,+ posting: PostingContext+): Promise<void> {+ const invoices = await rows<{+ id: string;+ invoiceId: string;+ status: string;+ postingDate: string | null;+ exchangeRate: string | null;+ }>(+ ctx.client,+ `SELECT id, "invoiceId", status, "postingDate"::text AS "postingDate", "exchangeRate"+ FROM "purchaseInvoice" WHERE "companyId" = $1 AND status <> 'Draft'+ ORDER BY "postingDate", "invoiceId"`,+ [ctx.companyId]+ );+ if (invoices.length === 0) return;+ const lines = await rows<{+ invoiceId: string;+ quantity: string;+ supplierUnitPrice: string;+ purchaseOrderLineId: string | null;+ }>(+ ctx.client,+ `SELECT "invoiceId", quantity, "supplierUnitPrice", "purchaseOrderLineId"+ FROM "purchaseInvoiceLine"+ WHERE "companyId" = $1 AND "invoiceId" = ANY($2::text[])+ ORDER BY "createdAt", id`,+ [ctx.companyId, invoices.map((i) => i.id)]+ );+ const receipts = await postedReceiptLines(ctx);+ for (const invoice of invoices) {+ const postingDate = invoice.postingDate;+ if (!postingDate) {+ throw new Error(+ `Seed: purchase invoice ${invoice.invoiceId} has no postingDate`+ );+ }+ if (Number(invoice.exchangeRate ?? 1) !== 1) {+ throw new Error(+ `Seed: purchase invoice ${invoice.invoiceId} is not base currency — seeded GL is USD only`+ );+ }+ const journal = purchaseInvoiceJournal({+ invoiceReadableId: invoice.invoiceId,+ lines: lines+ .filter((l) => l.invoiceId === invoice.id)+ .map((l) => {+ const poLineId = l.purchaseOrderLineId;+ if (!poLineId) {+ throw new Error(+ `Seed: purchase invoice ${invoice.invoiceId} has a line with no purchase order line`+ );+ }+ const received = receipts.filter(+ (r) =>+ r.purchaseOrderLineId === poLineId && r.postingDate <= postingDate+ );+ return {+ quantity: Number(l.quantity),+ unitCost: Number(l.supplierUnitPrice),+ purchaseOrderLineId: poLineId,+ receivedQuantity: received.reduce(+ (sum, r) => sum + r.receivedQuantity,+ 0+ ),+ receiptUnitCost: received[0]?.unitPrice ?? null+ };+ })+ });+ ctx.log(`journal — ${journal.description}`);+ const posted = await insertPostingJournal(ctx, posting, {+ journal,+ documentId: invoice.id,+ postingDate+ });+ if (invoice.status === "Voided") {+ await insertPostingJournal(ctx, posting, {+ journal: voidJournal(journal, invoice.invoiceId),+ documentId: invoice.id,+ postingDate,+ referencePrefix: posted.journalEntryId+ });+ }+ }+}++/**+ * post-receipt and post-shipment in date order: receipts open FIFO layers that+ * shipments then draw on (calculateCOGS).+ */+export async function postInventoryDocuments(+ ctx: Ctx,+ posting: PostingContext+): Promise<void> {+ const receipts = await postedReceiptLines(ctx);+ const shipments = await rows<{+ shipmentId: string;+ shipmentReadableId: string;+ postingDate: string;+ shipmentLineId: string;+ itemId: string;+ shippedQuantity: string;+ itemTrackingType: string | null;+ replenishmentSystem: string | null;+ unitCost: string | null;+ }>(+ ctx.client,+ `SELECT s.id AS "shipmentId", s."shipmentId" AS "shipmentReadableId",+ s."postingDate"::text AS "postingDate", sl.id AS "shipmentLineId",+ sl."itemId", sl."shippedQuantity", i."itemTrackingType",+ i."replenishmentSystem", ic."unitCost"+ FROM shipment s+ JOIN "shipmentLine" sl ON sl."shipmentId" = s.id AND sl."companyId" = s."companyId"+ JOIN item i ON i.id = sl."itemId" AND i."companyId" = s."companyId"+ JOIN "itemCost" ic ON ic."itemId" = i.id AND ic."companyId" = s."companyId"+ WHERE s."companyId" = $1 AND s.status = 'Posted'+ AND s."sourceDocument" = 'Sales Order' AND sl."shippedQuantity" > 0+ ORDER BY s."postingDate", s."shipmentId", sl."createdAt", sl.id`,+ [ctx.companyId]+ );+ // Scrap write-offs (tier 03) draw layers like any other decrease.+ const scraps = await rows<{+ itemLedgerId: string;+ postingDate: string;+ itemId: string;+ quantity: string;+ comment: string | null;+ itemTrackingType: string | null;+ replenishmentSystem: string | null;+ unitCost: string | null;+ }>(+ ctx.client,+ `SELECT il.id AS "itemLedgerId", il."postingDate"::text AS "postingDate",+ il."itemId", -il.quantity AS quantity, il.comment,+ i."itemTrackingType", i."replenishmentSystem", ic."unitCost"+ FROM "itemLedger" il+ JOIN item i ON i.id = il."itemId" AND i."companyId" = il."companyId"+ JOIN "itemCost" ic ON ic."itemId" = i.id AND ic."companyId" = il."companyId"+ WHERE il."companyId" = $1 AND il."documentType" = 'Scrap'+ AND il."entryType" = 'Negative Adjmt.'+ ORDER BY il."postingDate", il.id`,+ [ctx.companyId]+ );++ type Layer = {+ line: PostedReceiptLine;+ quantity: number;+ cost: number;+ remaining: number;+ };+ const layersByItem = new Map<string, Layer[]>();+ const layers: Layer[] = [];+ const events = [+ ...receipts.map((line) => ({+ kind: "receipt" as const,+ date: line.postingDate,+ line+ })),+ ...shipments.map((row) => ({+ kind: "shipment" as const,+ date: row.postingDate,+ row+ })),+ ...scraps.map((scrap) => ({+ kind: "scrap" as const,+ date: scrap.postingDate,+ scrap+ }))+ ].sort((a, b) =>+ a.date === b.date+ ? (a.kind === "receipt" ? 0 : 1) - (b.kind === "receipt" ? 0 : 1)+ : a.date < b.date+ ? -1+ : 1+ );+ const shipmentCosts = new Map<string, number>();+ const scrapCosts = new Map<string, number>();+ for (const event of events) {+ if (event.kind === "scrap") {+ const { scrap } = event;+ if (scrap.itemTrackingType === "Non-Inventory") continue;+ scrapCosts.set(+ scrap.itemLedgerId,+ consumeFifo(+ layersByItem.get(scrap.itemId) ?? [],+ Number(scrap.quantity),+ Number(scrap.unitCost ?? 0)+ )+ );+ continue;+ }+ if (event.kind === "receipt") {+ const { line } = event;+ if (line.itemTrackingType === "Non-Inventory") continue;+ const layer = {+ line,+ quantity: line.receivedQuantity,+ cost: line.receivedQuantity * line.unitPrice,+ remaining: line.receivedQuantity+ };+ layers.push(layer);+ layersByItem.set(line.itemId, [+ ...(layersByItem.get(line.itemId) ?? []),+ layer+ ]);+ continue;+ }+ const { row } = event;+ if (row.itemTrackingType === "Non-Inventory") continue;+ shipmentCosts.set(+ row.shipmentLineId,+ consumeFifo(+ layersByItem.get(row.itemId) ?? [],+ Number(row.shippedQuantity),+ Number(row.unitCost ?? 0)+ )+ );+ }++ for (const layer of layers) {+ await insertRow(ctx, "costLedger", {+ itemLedgerType: "Purchase",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Purchase Receipt",+ documentId: layer.line.receiptId,+ externalDocumentId: layer.line.externalDocumentId ?? undefined,+ itemId: layer.line.itemId,+ quantity: round(layer.quantity),+ nominalCost: round(layer.cost),+ cost: round(layer.cost),+ remainingQuantity: round(layer.remaining),+ supplierId: layer.line.supplierId ?? undefined,+ postingDate: layer.line.postingDate+ });+ }+ const receiptIds = [...new Set(receipts.map((r) => r.receiptId))];+ for (const receiptId of receiptIds) {+ const own = receipts.filter((r) => r.receiptId === receiptId);+ const first = own[0]!;+ const journal = receiptJournal({+ receiptReadableId: first.receiptReadableId,+ lines: own.map((r) => ({+ quantity: r.receivedQuantity,+ cost: r.receivedQuantity * r.unitPrice,+ purchaseOrderLineId: r.purchaseOrderLineId,+ replenishmentSystem: r.replenishmentSystem,+ itemTrackingType: r.itemTrackingType+ }))+ });+ ctx.log(`journal — ${journal.description}`);+ await insertPostingJournal(ctx, posting, {+ journal,+ documentId: receiptId,+ postingDate: first.postingDate+ });+ }++ // One Sale row per item, not per line, as post-shipment writes.+ const shipmentIds = [...new Set(shipments.map((s) => s.shipmentId))];+ for (const shipmentId of shipmentIds) {+ const own = shipments.filter(+ (s) =>+ s.shipmentId === shipmentId && s.itemTrackingType !== "Non-Inventory"+ );+ if (own.length === 0) continue;+ const postingDate = own[0]!.postingDate;+ const byItem = new Map<string, { quantity: number; cost: number }>();+ for (const s of own) {+ const item = s.itemId;+ const prior = byItem.get(item) ?? { quantity: 0, cost: 0 };+ byItem.set(item, {+ quantity: prior.quantity + Number(s.shippedQuantity),+ cost: prior.cost + (shipmentCosts.get(s.shipmentLineId) ?? 0)+ });+ }+ for (const [itemId, total] of byItem) {+ await insertRow(ctx, "costLedger", {+ itemLedgerType: "Sale",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Sales Shipment",+ documentId: shipmentId,+ itemId,+ quantity: round(-total.quantity),+ cost: round(-total.cost),+ remainingQuantity: 0,+ postingDate+ });+ }+ const journal = shipmentJournal({+ shipmentReadableId: own[0]!.shipmentReadableId,+ lines: own.map((s) => ({+ quantity: Number(s.shippedQuantity),+ cost: shipmentCosts.get(s.shipmentLineId) ?? 0,+ shipmentLineId: s.shipmentLineId,+ replenishmentSystem: s.replenishmentSystem,+ itemTrackingType: s.itemTrackingType+ }))+ });+ ctx.log(`journal — ${journal.description}`);+ await insertPostingJournal(ctx, posting, {+ journal,+ documentId: shipmentId,+ postingDate+ });+ }++ for (const scrap of scraps) {+ const cost = scrapCosts.get(scrap.itemLedgerId);+ // A zero-value movement posts nothing, as bookAdjustment.+ if (!cost) continue;+ const quantity = Number(scrap.quantity);+ await insertRow(ctx, "costLedger", {+ itemLedgerType: "Negative Adjmt.",+ costLedgerType: "Direct Cost",+ adjustment: false,+ documentType: "Scrap",+ documentId: scrap.itemLedgerId,+ itemId: scrap.itemId,+ quantity: round(-quantity),+ cost: round(-cost),+ remainingQuantity: 0,+ postingDate: scrap.postingDate+ });+ const journal = scrapJournal({+ description: scrap.comment?.trim()+ ? `Scrap — ${scrap.comment.trim()}`+ : "Scrap",+ quantity,+ cost,+ replenishmentSystem: scrap.replenishmentSystem,+ itemTrackingType: scrap.itemTrackingType+ });+ ctx.log(`journal — ${journal.description}`);+ await insertPostingJournal(ctx, posting, {+ journal,+ documentId: scrap.itemLedgerId,+ postingDate: scrap.postingDate+ });+ }+}++/** post-memo for every Posted memo still without a journal (tier 09's and the return credits). */+export async function postMemos(+ ctx: Ctx,+ posting: PostingContext+): Promise<void> {+ const memos = await rows<{+ id: string;+ memoId: string;+ direction: "Credit" | "Debit";+ customerId: string | null;+ amount: string;+ exchangeRate: string;+ postingDate: string | null;+ reasonAccount: string | null;+ }>(+ ctx.client,+ `SELECT id, "memoId", direction, "customerId", amount, "exchangeRate",+ "postingDate"::text AS "postingDate", "reasonAccount"+ FROM memo+ WHERE "companyId" = $1 AND status = 'Posted' AND "journalId" IS NULL+ ORDER BY "postingDate", "memoId"`,+ [ctx.companyId]+ );+ for (const memo of memos) {+ const reasonClass = memo.reasonAccount+ ? posting.classById.get(memo.reasonAccount)+ : undefined;+ if (!memo.postingDate || !memo.reasonAccount || !reasonClass) {+ throw new Error(+ `Seed: posted memo ${memo.memoId} needs a posting date and an active reason account`+ );+ }+ if (Number(memo.exchangeRate) !== 1) {+ throw new Error(`Seed: memo ${memo.memoId} is not base currency`);+ }+ const journal = memoJournal({+ memoReadableId: memo.memoId,+ documentId: memo.id,+ direction: memo.direction,+ isAR: memo.customerId !== null,+ amount: Number(memo.amount),+ reasonAccountClass: reasonClass+ });+ ctx.log(`journal — ${journal.description}`);+ const { id } = await insertPostingJournal(ctx, posting, {+ journal,+ documentId: memo.id,+ postingDate: memo.postingDate,+ reasonAccountId: memo.reasonAccount+ });+ await ctx.client.query(+ `UPDATE memo SET "journalId" = $1, "updatedBy" = $2+ WHERE id = $3 AND "companyId" = $4`,+ [id, ctx.userId, memo.id, ctx.companyId]+ );+ }+}++/** post-payment's journal for one Posted payment. */+export async function postPayment(+ ctx: Ctx,+ posting: PostingContext,+ args: {+ paymentId: string;+ paymentReadableId: string;+ type: "Receipt" | "Disbursement";+ amount: number;+ postingDate: string;+ applies: { targetId: string; amount: number }[];+ }+): Promise<void> {+ const journal = paymentJournal({+ paymentReadableId: args.paymentReadableId,+ documentId: args.paymentId,+ type: args.type,+ amount: args.amount,+ applies: args.applies+ });+ const { id } = await insertPostingJournal(ctx, posting, {+ journal,+ documentId: args.paymentId,+ postingDate: args.postingDate+ });+ await ctx.client.query(+ `UPDATE payment SET "journalId" = $1, "updatedBy" = $2+ WHERE id = $3 AND "companyId" = $4`,+ [id, ctx.userId, args.paymentId, ctx.companyId]+ );+}diff --git a/packages/database/src/datasets/helpers/posting-journals.ts b/packages/database/src/datasets/helpers/posting-journals.tsnew file mode 100644index 0000000000..ebf105ab99--- /dev/null+++ b/packages/database/src/datasets/helpers/posting-journals.ts@@ -0,0 +1,543 @@+import {+ accountTypeFromClass,+ credit,+ debit,+ journalReference+} from "../../../supabase/functions/lib/utils.ts";+import { buildMemoJournal } from "../../../supabase/functions/post-memo/build-memo-journal.ts";+import { buildPaymentJournal } from "../../../supabase/functions/post-payment/build-payment-journal.ts";+import {+ EPSILON,+ round+} from "../../../supabase/functions/shared/precision.ts";+import {+ buildSalesPostingLines,+ type SalesPostingAccount+} from "../../../supabase/functions/shared/sales-posting-amounts.ts";+import type { AccountClass } from "../types.ts";++/**+ * The posting functions' journals, built from plain facts so tier 09 and the+ * validator derive the SAME lines. Base currency only: every seeded posted+ * document is USD at rate 1.+ */++export type PostingRole =+ | "receivablesAccount"+ | "payablesAccount"+ | "salesAccount"+ | "bankCashAccount"+ | "goodsReceivedNotInvoicedAccount"+ | "rawMaterialsAccount"+ | "finishedGoodsAccount"+ | "indirectCostAccount"+ | "costOfGoodsSoldAccount"+ | "scrapAccount"+ | "reasonAccount";++export type DefaultPostingRole = Exclude<PostingRole, "reasonAccount">;++/** The posting functions refuse a default of any other class. */+export const POSTING_ROLE_CLASS: Record<DefaultPostingRole, AccountClass> = {+ receivablesAccount: "Asset",+ payablesAccount: "Liability",+ salesAccount: "Revenue",+ bankCashAccount: "Asset",+ goodsReceivedNotInvoicedAccount: "Liability",+ rawMaterialsAccount: "Asset",+ finishedGoodsAccount: "Asset",+ indirectCostAccount: "Expense",+ costOfGoodsSoldAccount: "Expense",+ scrapAccount: "Expense"+};++export type PostingSourceType =+ | "Sales Invoice"+ | "Purchase Invoice"+ | "Payment"+ | "Credit Memo"+ | "Debit Memo"+ | "Purchase Receipt"+ | "Sales Shipment"+ | "Inventory Adjustment";++export type PostingLine = {+ role: PostingRole;+ accountClass: AccountClass;+ description: string;+ /** Signed by the account's natural balance (lib/utils.ts debit/credit). */+ amount: number;+ quantity: number;+ documentType:+ | "Invoice"+ | "Payment"+ | "Memo"+ | "Receipt"+ | "Sales Shipment"+ | "Scrap";+ documentLineReference?: string | null;+ accrual?: boolean;+ group: number;+};++export type PostingJournal = {+ sourceType: PostingSourceType;+ description: string;+ lines: PostingLine[];+};++/** A positive amount debits an Asset/Expense account and credits the others. */+export function signedNet(+ lines: readonly { accountClass: AccountClass; amount: number }[]+): number {+ return round(+ lines.reduce(+ (net, line) =>+ net + debit(accountTypeFromClass(line.accountClass), line.amount),+ 0+ )+ );+}++export function postingImbalance(journal: PostingJournal): number {+ return signedNet(journal.lines);+}++export function isBalanced(journal: PostingJournal): boolean {+ return Math.abs(postingImbalance(journal)) <= EPSILON;+}++function roleLine(+ role: DefaultPostingRole,+ line: Omit<PostingLine, "role" | "accountClass">+): PostingLine {+ return { role, accountClass: POSTING_ROLE_CLASS[role], ...line };+}++/** resolveInventoryAccount (get-posting-group.ts) plus post-receipt's Non-Inventory branch. */+export function inventoryRoleFor(item: {+ replenishmentSystem: string | null;+ itemTrackingType: string | null;+}): {+ role: DefaultPostingRole;+ description: string;+} {+ if (item.itemTrackingType === "Non-Inventory") {+ return {+ role: "indirectCostAccount",+ description: "Indirect Cost Account"+ };+ }+ return item.replenishmentSystem === "Make" ||+ item.replenishmentSystem === "Buy and Make"+ ? { role: "finishedGoodsAccount", description: "Finished Goods Account" }+ : { role: "rawMaterialsAccount", description: "Raw Materials Account" };+}++const pseudoAccount = (role: DefaultPostingRole): SalesPostingAccount => ({+ id: role,+ class: POSTING_ROLE_CLASS[role],+ active: true,+ isGroup: false,+ companyGroupId: "group"+});++/** post-sales-invoice, sales-order lines: the charge rows only (COGS rides on the shipment). */+export function salesInvoiceJournal(args: {+ invoiceReadableId: string;+ documentId: string;+ lines: { quantity: number; unitPrice: number; salesOrderLineId: string }[];+}): PostingJournal {+ const lines: PostingLine[] = [];+ args.lines.forEach((line, group) => {+ const built = buildSalesPostingLines({+ line: {+ quantity: line.quantity,+ unitPrice: line.unitPrice,+ invoiceLineType: "Part"+ },+ context: {+ companyId: "",+ companyGroupId: "group",+ documentId: args.documentId,+ documentLineReference: journalReference.to.salesInvoice(+ line.salesOrderLineId+ ),+ journalLineReference: ""+ },+ accounts: {+ receivables: pseudoAccount("receivablesAccount"),+ sales: pseudoAccount("salesAccount")+ },+ metadata: {+ customerTypeId: null,+ itemPostingGroupId: null,+ itemId: null,+ locationId: null,+ costCenterId: null,+ fixedAssetClassId: null+ }+ });+ for (const builtLine of built.lines) {+ const role = builtLine.accountId as DefaultPostingRole;+ lines.push(+ roleLine(role, {+ description: builtLine.description,+ amount: builtLine.amount,+ quantity: builtLine.quantity,+ documentType: "Invoice",+ documentLineReference: builtLine.documentLineReference,+ group+ })+ );+ }+ });+ return {+ sourceType: "Sales Invoice",+ description: `Sales Invoice ${args.invoiceReadableId}`,+ lines+ };+}++/**+ * post-purchase-invoice, PO lines. Seeded invoices bill at the receipt price, so+ * there is no price variance to split.+ */+export function purchaseInvoiceJournal(args: {+ invoiceReadableId: string;+ lines: {+ quantity: number;+ unitCost: number;+ purchaseOrderLineId: string;+ receivedQuantity: number;+ receiptUnitCost: number | null;+ }[];+}): PostingJournal {+ const lines: PostingLine[] = [];+ let group = 0;+ for (const line of args.lines) {+ const reference = journalReference.to.purchaseInvoice(+ line.purchaseOrderLineId+ );+ const reversed = Math.max(+ 0,+ Math.min(line.quantity, line.receivedQuantity)+ );+ if (reversed > 0) {+ const receiptCost = reversed * (line.receiptUnitCost ?? line.unitCost);+ if (Math.abs(receiptCost - reversed * line.unitCost) > 0.005) {+ throw new Error(+ `Seed: purchase invoice ${args.invoiceReadableId} bills a received line away from its receipt price`+ );+ }+ lines.push(+ roleLine("goodsReceivedNotInvoicedAccount", {+ description: "GR/IR Clearing",+ amount: round(debit("liability", receiptCost)),+ quantity: round(reversed),+ documentType: "Invoice",+ documentLineReference: reference,+ group+ }),+ roleLine("payablesAccount", {+ description: "Accounts Payable",+ amount: round(credit("liability", receiptCost)),+ quantity: round(reversed),+ documentType: "Invoice",+ documentLineReference: reference,+ group+ })+ );+ group++;+ }+ const accrued = line.quantity - reversed;+ if (accrued > 0) {+ const accrualCost = accrued * line.unitCost;+ lines.push(+ roleLine("goodsReceivedNotInvoicedAccount", {+ description: "GR/IR Clearing",+ accrual: true,+ amount: round(debit("liability", accrualCost)),+ quantity: round(accrued),+ documentType: "Invoice",+ documentLineReference: reference,+ group+ }),+ roleLine("payablesAccount", {+ description: "Accounts Payable",+ accrual: true,+ amount: round(credit("liability", accrualCost)),+ quantity: round(accrued),+ documentType: "Invoice",+ documentLineReference: reference,+ group+ })+ );+ group++;+ }+ }+ return {+ sourceType: "Purchase Invoice",+ description: `Purchase Invoice ${args.invoiceReadableId}`,+ lines+ };+}++/** The void branch of post-{sales,purchase}-invoice: every line negated, same references. */+export function voidJournal(+ journal: PostingJournal,+ invoiceReadableId: string+): PostingJournal {+ return {+ sourceType: journal.sourceType,+ description: `VOID ${journal.sourceType} ${invoiceReadableId}`,+ lines: journal.lines.map((line) => ({+ ...line,+ description: `VOID: ${line.description}`,+ amount: -line.amount,+ quantity: -line.quantity+ }))+ };+}++/** post-payment's buildPaymentJournal: cash against the control account, one reference. */+export function paymentJournal(args: {+ paymentReadableId: string;+ documentId: string;+ type: "Receipt" | "Disbursement";+ amount: number;+ applies: { targetId: string; amount: number }[];+}): PostingJournal {+ const isAR = args.type === "Receipt";+ const control: DefaultPostingRole = isAR+ ? "receivablesAccount"+ : "payablesAccount";+ const applied = args.applies.reduce((sum, a) => sum + a.amount, 0);+ const built = buildPaymentJournal({+ paymentId: args.documentId,+ companyId: "",+ isAR,+ cashIn: isAR,+ totalAmount: args.amount,+ exchangeRate: 1,+ bankAccount: "bankCashAccount",+ journalLineReference: "",+ applications: args.applies.map((apply) => ({+ targetSalesInvoiceId: isAR ? apply.targetId : null,+ targetPurchaseInvoiceId: isAR ? null : apply.targetId,+ sourceAmount: apply.amount,+ sourcePaymentId: null,+ fxGainLossAmount: 0,+ appliedAmount: apply.amount,+ discountAmount: 0,+ writeOffAmount: 0,+ targetExchangeRate: 1,+ sourceExchangeRate: 1+ })),+ newOnAccountBase: round(args.amount - applied),+ accounts: {+ controlAccountId: control,+ discountAccountId: null,+ writeOffAccountId: null,+ fxGainAccountId: null,+ fxLossAccountId: null+ }+ });+ return {+ sourceType: "Payment",+ description: `Payment ${args.paymentReadableId}`,+ lines: built.lines.map((line) =>+ roleLine(line.accountId as DefaultPostingRole, {+ description: line.description,+ amount: line.amount,+ quantity: line.quantity,+ documentType: "Payment",+ documentLineReference: line.documentLineReference,+ group: 0+ })+ )+ };+}++/** post-memo's buildMemoJournal, two-line shape (no return-shipment carried cost). */+export function memoJournal(args: {+ memoReadableId: string;+ documentId: string;+ direction: "Credit" | "Debit";+ isAR: boolean;+ amount: number;+ reasonAccountClass: AccountClass;+}): PostingJournal {+ const control: DefaultPostingRole = args.isAR+ ? "receivablesAccount"+ : "payablesAccount";+ const built = buildMemoJournal({+ memoId: args.documentId,+ companyId: "",+ isAR: args.isAR,+ direction: args.direction,+ amount: args.amount,+ exchangeRate: 1,+ journalLineReference: "",+ controlAccountId: control,+ reasonAccountId: "reasonAccount",+ reasonAccountClass: args.reasonAccountClass+ });+ return {+ sourceType: args.direction === "Credit" ? "Credit Memo" : "Debit Memo",+ description: `${args.direction} Memo ${args.memoReadableId}`,+ lines: built.lines.map((line) =>+ line.accountId === "reasonAccount"+ ? {+ role: "reasonAccount",+ accountClass: args.reasonAccountClass,+ description: line.description,+ amount: line.amount,+ quantity: line.quantity,+ documentType: "Memo",+ group: 0+ }+ : roleLine(control, {+ description: line.description,+ amount: line.amount,+ quantity: line.quantity,+ documentType: "Memo",+ group: 0+ })+ )+ };+}++/** post-receipt, purchase-order branch: DR inventory (or indirect cost) / CR GR/IR at receipt cost. */+export function receiptJournal(args: {+ receiptReadableId: string;+ lines: {+ quantity: number;+ cost: number;+ purchaseOrderLineId: string;+ replenishmentSystem: string | null;+ itemTrackingType: string | null;+ }[];+}): PostingJournal {+ const lines: PostingLine[] = [];+ args.lines.forEach((line, group) => {+ const inventory = inventoryRoleFor(line);+ const reference = journalReference.to.receipt(line.purchaseOrderLineId);+ lines.push(+ roleLine(inventory.role, {+ description: inventory.description,+ amount: round(debit("asset", line.cost)),+ quantity: round(line.quantity),+ documentType: "Receipt",+ documentLineReference: reference,+ group+ }),+ roleLine("goodsReceivedNotInvoicedAccount", {+ description: "Goods Received Not Invoiced",+ amount: round(credit("liability", line.cost)),+ quantity: round(line.quantity),+ documentType: "Receipt",+ documentLineReference: reference,+ group+ })+ );+ });+ return {+ sourceType: "Purchase Receipt",+ description: `Purchase Receipt ${args.receiptReadableId}`,+ lines+ };+}++/** post-shipment, sales-order branch: DR COGS / CR inventory at the consumed cost. */+export function shipmentJournal(args: {+ shipmentReadableId: string;+ lines: {+ quantity: number;+ cost: number;+ shipmentLineId: string;+ replenishmentSystem: string | null;+ itemTrackingType: string | null;+ }[];+}): PostingJournal {+ const lines: PostingLine[] = [];+ args.lines.forEach((line, group) => {+ const inventory = inventoryRoleFor(line);+ const reference = journalReference.to.shipment(line.shipmentLineId);+ lines.push(+ roleLine("costOfGoodsSoldAccount", {+ description: "Cost of Goods Sold",+ amount: round(debit("expense", line.cost)),+ quantity: round(line.quantity),+ documentType: "Sales Shipment",+ documentLineReference: reference,+ group+ }),+ roleLine(inventory.role, {+ description: inventory.description,+ amount: round(credit("asset", line.cost)),+ quantity: round(line.quantity),+ documentType: "Sales Shipment",+ documentLineReference: reference,+ group+ })+ );+ });+ return {+ sourceType: "Sales Shipment",+ description: `Sales Shipment ${args.shipmentReadableId}`,+ lines+ };+}++/** post-inventory-adjustment's Scrap (bookAdjustment): CR inventory / DR the scrap account at the relieved cost. */+export function scrapJournal(args: {+ description: string;+ quantity: number;+ cost: number;+ replenishmentSystem: string | null;+ itemTrackingType: string | null;+}): PostingJournal {+ const inventory = inventoryRoleFor(args);+ return {+ sourceType: "Inventory Adjustment",+ description: args.description,+ lines: [+ roleLine(inventory.role, {+ description: inventory.description,+ amount: round(credit("asset", args.cost)),+ quantity: round(args.quantity),+ documentType: "Scrap",+ group: 0+ }),+ roleLine("scrapAccount", {+ description: "Scrap Account",+ amount: round(debit("expense", args.cost)),+ quantity: round(args.quantity),+ documentType: "Scrap",+ group: 0+ })+ ]+ };+}++/** calculateCOGS for a FIFO item. Mutates `remaining`. */+export function consumeFifo(+ layers: { quantity: number; cost: number; remaining: number }[],+ quantity: number,+ fallbackUnitCost: number+): number {+ let toConsume = quantity;+ let total = 0;+ for (const layer of layers) {+ if (toConsume <= 0) break;+ if (layer.remaining <= 0) continue;+ const unitCost = layer.quantity > 0 ? layer.cost / layer.quantity : 0;+ const take = Math.min(toConsume, layer.remaining);+ total += take * unitCost;+ layer.remaining -= take;+ toConsume -= take;+ }+ if (toConsume > 0) total += toConsume * fallbackUnitCost;+ return total;+}diff --git a/packages/database/src/datasets/helpers/return-credit.ts b/packages/database/src/datasets/helpers/return-credit.tsnew file mode 100644index 0000000000..71312a4e99--- /dev/null+++ b/packages/database/src/datasets/helpers/return-credit.ts@@ -0,0 +1,93 @@+import { round } from "../../../supabase/functions/shared/precision.ts";+import { insertRow, maybeOne, one, quote, rows } from "../sql.ts";+import type { Ctx, ReturnCreditSpec } from "../types.ts";+import { insertMemo } from "./memo.ts";++/**+ * Mirrors "Issue Credit" (createSalesReturnOrderCredit / createPurchaseReturnOrderCredit).+ * Tier 09 journals a Posted one with the other Posted memos.+ */+export async function seedReturnCredit(+ ctx: Ctx,+ args: {+ spec: ReturnCreditSpec;+ kind: "sales" | "purchase";+ partyId: string;+ returnOrderId: string;+ }+): Promise<string> {+ const { spec, kind } = args;+ const isSales = kind === "sales";+ const table = isSales ? "salesReturnOrder" : "purchaseReturnOrder";++ const order = await one<{+ readableId: string;+ currencyCode: string;+ exchangeRate: number;+ }>(+ ctx.client,+ `SELECT ${quote(`${table}Id`)} AS "readableId", "currencyCode", "exchangeRate"+ FROM ${quote(table)} WHERE id = $1 AND "companyId" = $2`,+ [args.returnOrderId, ctx.companyId]+ );+ const returnLines = await rows<{+ id: string;+ unitPrice: number;+ restockFeePercent: number;+ }>(+ ctx.client,+ `SELECT id, "unitPrice", "restockFeePercent" FROM ${quote(`${table}Line`)}+ WHERE ${quote(`${table}Id`)} = $1 AND "companyId" = $2 ORDER BY "lineNumber"`,+ [args.returnOrderId, ctx.companyId]+ );+ const currency = await maybeOne<{ decimalPlaces: number | null }>(+ ctx.client,+ `SELECT "decimalPlaces" FROM currency WHERE code = $1 AND "companyGroupId" = $2`,+ [order.currencyCode, ctx.companyGroupId]+ );++ const credited = spec.lines.map((line) => {+ const returnLine = returnLines[line.line - 1];+ if (!returnLine) {+ throw new Error(+ `Seed: return credit names line ${line.line}, which the return does not have`+ );+ }+ const unitPrice = Number(returnLine.unitPrice);+ const gross = line.quantity * unitPrice;+ return {+ id: returnLine.id,+ quantity: line.quantity,+ unitPrice,+ restockFee: gross * Number(returnLine.restockFeePercent)+ };+ });+ const total = credited.reduce(+ (sum, line) => sum + line.quantity * line.unitPrice - line.restockFee,+ 0+ );++ const memoId = await insertMemo(ctx, {+ direction: isSales ? "Credit" : "Debit",+ partyId: args.partyId,+ status: spec.status,+ dateOffset: spec.dateOffset,+ amount: round(total, Number(currency?.decimalPlaces ?? 2)),+ currencyCode: order.currencyCode,+ exchangeRate: Number(order.exchangeRate),+ reference: order.readableId,+ salesReturnOrderId: isSales ? args.returnOrderId : undefined,+ purchaseReturnOrderId: isSales ? undefined : args.returnOrderId+ });++ for (const line of credited) {+ await insertRow(ctx, `${table}CreditLine`, {+ memoId,+ [`${table}LineId`]: line.id,+ quantity: line.quantity,+ unitPrice: line.unitPrice,+ restockFee: line.restockFee+ });+ }+ return memoId;+}diff --git a/packages/database/src/datasets/rule-fields.ts b/packages/database/src/datasets/rule-fields.tsnew file mode 100644index 0000000000..75148c3986--- /dev/null+++ b/packages/database/src/datasets/rule-fields.ts@@ -0,0 +1,73 @@+import type { RuleOperator } from "./types.ts";+import type { RuleShape } from "./validate.ts";++export type RuleValueKind =+ | "enum"+ | "number"+ | "boolean"+ | "country"+ | "storageType"+ | "customerTypes"+ | "location";++// A copy of the rule builder's field registry slice the seed can author: this package+// cannot import @carbon/utils, whose field-registry.test.ts pins it to the registry.+export const RULE_FIELDS: Record<+ string,+ {+ ops: readonly RuleOperator[];+ shapes: RuleShape[];+ value: RuleValueKind;+ }+> = {+ "item.type": {+ ops: ["eq", "neq", "in", "notIn"],+ shapes: ["sales", "storage:item"],+ value: "enum"+ },+ "item.replenishmentSystem": {+ ops: ["eq", "neq", "in", "notIn"],+ shapes: ["sales", "storage:item"],+ value: "enum"+ },+ "item.itemTrackingType": {+ ops: ["eq", "neq", "in", "notIn"],+ shapes: ["sales", "storage:item"],+ value: "enum"+ },+ "storageUnit.storageTypeId": {+ ops: ["eq", "neq", "isSet", "isNotSet"],+ shapes: ["storage:item"],+ value: "storageType"+ },+ "storageUnit.locationId": {+ ops: ["eq", "neq", "isSet", "isNotSet"],+ shapes: ["storage:item"],+ value: "location"+ },+ "workCenter.locationId": {+ ops: ["eq", "neq", "isSet", "isNotSet"],+ shapes: ["storage:workCenter"],+ value: "location"+ },+ "workCenter.active": {+ ops: ["eq", "neq"],+ shapes: ["storage:workCenter"],+ value: "boolean"+ },+ "transaction.quantity": {+ ops: ["eq", "neq", "gt", "lt"],+ shapes: ["sales", "storage:item", "storage:workCenter"],+ value: "number"+ },+ "customer.customerTypeId": {+ ops: ["in", "notIn", "isSet", "isNotSet"],+ shapes: ["sales"],+ value: "customerTypes"+ },+ "customer.location.countryCode": {+ ops: ["eq", "neq", "in", "notIn", "isSet", "isNotSet"],+ shapes: ["sales"],+ value: "country"+ }+};diff --git a/packages/database/src/datasets/sql.ts b/packages/database/src/datasets/sql.tsindex da42f557d9..d577fafb59 100644--- a/packages/database/src/datasets/sql.ts+++ b/packages/database/src/datasets/sql.ts@@ -240,14 +240,20 @@ export async function ensureSequences(}}+// Journals survive the wipe, so their counter must not rewind: a rewound one+// hands the app (and the seed) an id a preserved journal already holds.+const PRESERVED_SEQUENCES = ["journalEntry"];+// Re-running the seed must produce the same readable ids as the first run.export async function resetSequences(client: PoolClient,companyId: string): Promise<void> {- await client.query(`UPDATE sequence SET next = 0 WHERE "companyId" = $1`, [- companyId- ]);+ await client.query(+ `UPDATE sequence SET next = 0+ WHERE "companyId" = $1 AND "table" <> ALL($2::text[])`,+ [companyId, PRESERVED_SEQUENCES]+ );}// SECURITY DEFINER, skips its permission check when session_user != 'authenticator'.@@ -261,6 +267,19 @@ export async function nextSequence(ctx: Ctx, table: string): Promise<string> {return value;}+/** Earlier seeds rewound this counter while journals survived, so skip past any collision. */+export async function nextJournalEntryId(ctx: Ctx): Promise<string> {+ for (let attempt = 0; attempt < 10_000; attempt++) {+ const candidate = await nextSequence(ctx, "journalEntry");+ const taken = await ctx.client.query(+ `SELECT 1 FROM journal WHERE "journalEntryId" = $1 AND "companyId" = $2`,+ [candidate, ctx.companyId]+ );+ if (taken.rowCount === 0) return candidate;+ }+ throw new Error("Seed: no free journalEntry id after 10000 attempts");+}+const SUMMARY_TABLES = ["location","process",diff --git a/packages/database/src/datasets/tiers/01-foundation.ts b/packages/database/src/datasets/tiers/01-foundation.tsindex 9a7f3503d4..5ab42b7dfa 100644--- a/packages/database/src/datasets/tiers/01-foundation.ts+++ b/packages/database/src/datasets/tiers/01-foundation.ts@@ -1,6 +1,30 @@-import { insertId, insertRow, need, one, RICH, rows } from "../sql.ts";+import { resolveDate } from "../dates.ts";+import { bootstrapIdByName } from "../helpers/bootstrap-lookup.ts";+import {+ insertId,+ insertMaybe,+ insertRow,+ maybeOne,+ need,+ one,+ RICH+} from "../sql.ts";import type { Ctx } from "../types.ts";+// Bootstrap seeds the full ISO currency set, so a miss is a typo'd code, not a gap.+async function assertCurrencyExists(ctx: Ctx, code: string): Promise<void> {+ const row = await maybeOne(+ ctx.client,+ `SELECT code FROM currency WHERE "companyGroupId" = $1 AND code = $2`,+ [ctx.companyGroupId, code]+ );+ if (!row) {+ throw new Error(+ `Seed: currency "${code}" does not exist for this company group`+ );+ }+}+export async function runTier1(ctx: Ctx): Promise<void> {const data = ctx.dataset.foundation;const { client, companyId, locationId } = ctx;@@ -12,24 +36,6 @@ export async function runTier1(ctx: Ctx): Promise<void> {ctx.refs.departments[name] = id;}- // ── Shifts ────────────────────────────────────────────────────────────────- ctx.log("shifts");- for (const shift of data.shifts) {- ctx.refs.shifts[shift.name] = await insertId(ctx, "shift", {- name: shift.name,- startTime: shift.startTime,- endTime: shift.endTime,- locationId,- monday: shift.monday ?? false,- tuesday: shift.tuesday ?? false,- wednesday: shift.wednesday ?? false,- thursday: shift.thursday ?? false,- friday: shift.friday ?? false,- saturday: shift.saturday ?? false,- sunday: shift.sunday ?? false- });- }-// ── Processes ─────────────────────────────────────────────────────────────// Processes come before abilities: an ability is a process's qualification// (it carries no name of its own), so each ability must link to a process.@@ -88,14 +94,61 @@ export async function runTier1(ctx: Ctx): Promise<void> {ctx.refs.locations.Plant = plantId;ctx.refs.locations.HQ = locationId;+ // At the plant: the work-center shift picker, the scheduler and Resource+ // Planning all read the shifts of the work centers' own location.+ ctx.log("shifts");+ for (const shift of data.shifts) {+ ctx.refs.shifts[shift.name] = await insertId(ctx, "shift", {+ name: shift.name,+ startTime: shift.startTime,+ endTime: shift.endTime,+ locationId: plantId,+ monday: shift.monday ?? false,+ tuesday: shift.tuesday ?? false,+ wednesday: shift.wednesday ?? false,+ thursday: shift.thursday ?? false,+ friday: shift.friday ?? false,+ saturday: shift.saturday ?? false,+ sunday: shift.sunday ?? false+ });+ }+// 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.+ // the ERP's location-scoped pages read the signed-in user's default location+ // (`userDefaults` is a view over employeeJob). Leave that at HQ and the shop+ // floor renders empty. Other employees move with the applying user.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.)+ // Upsert, not UPDATE: a company created outside bootstrap has no row for the+ // applying user, and the MES would then fall back to an arbitrary location.+ const job = data.employeeJob;+ ctx.log("employee job");+ await insertRow(+ ctx,+ "employeeJob",+ {+ id: ctx.userId,+ locationId: plantId,+ title: job.title,+ departmentId: need(ctx.refs.departments, job.department, "department"),+ shiftId: need(ctx.refs.shifts, job.shift, "shift"),+ startDate: resolveDate(ctx.anchor, job.startDateOffset),+ managerId: null,+ updatedBy: ctx.userId+ },+ {+ onConflict: `("id", "companyId") DO UPDATE SET+ "locationId" = EXCLUDED."locationId",+ "title" = EXCLUDED."title",+ "departmentId" = EXCLUDED."departmentId",+ "shiftId" = EXCLUDED."shiftId",+ "startDate" = EXCLUDED."startDate",+ "managerId" = NULL,+ "updatedBy" = EXCLUDED."updatedBy"`+ }+ );// ── Warehouses ────────────────────────────────────────────────────────────ctx.log("warehouses");@@ -113,7 +166,9 @@ export async function runTier1(ctx: Ctx): Promise<void> {ctx.log("storage types + units");const storageTypeIdByName = new Map<string, string>();for (const name of data.storageTypes) {- storageTypeIdByName.set(name, await insertId(ctx, "storageType", { name }));+ const storageTypeId = await insertId(ctx, "storageType", { name });+ storageTypeIdByName.set(name, storageTypeId);+ ctx.refs.misc[`storagetype:${name}`] = storageTypeId;}// Array order is the contract: a parent shelf must be inserted before its@@ -158,6 +213,17 @@ export async function runTier1(ctx: Ctx): Promise<void> {});ctx.refs.workCenters[wc.name] = id;}+ // The ERP's maintenance lists open on the first location by name (HQ), so+ // one work center there carries a schedule and a dispatch.+ const hq = data.hqWorkCenter;+ ctx.refs.workCenters[hq.name] = await insertId(ctx, "workCenter", {+ name: hq.name,+ departmentId: need(ctx.refs.departments, hq.dept, "department"),+ requiredAbilityId: need(ctx.refs.abilities, hq.ability, "ability"),+ locationId,+ laborRate: hq.laborRate,+ machineRate: hq.machineRate+ });// Link work centers to processesfor (const [wc, proc] of data.workCenterProcessLinks) {@@ -167,12 +233,19 @@ export async function runTier1(ctx: Ctx): Promise<void> {});}+ for (const [wc, shift] of data.workCenterShifts) {+ await insertRow(ctx, "workCenterShift", {+ workCenterId: need(ctx.refs.workCenters, wc, "work center"),+ shiftId: need(ctx.refs.shifts, shift, "shift")+ });+ }+// Storage units for work centers (for floor-level inventory)for (const wc of data.workCenters) {const suId = await insertId(ctx, "storageUnit", {name: `${wc.name} Floor`,locationId: plantId,- workCenterId: ctx.refs.workCenters[wc.name],+ workCenterId: need(ctx.refs.workCenters, wc.name, "work center"),isWorkCenterDefault: true});ctx.refs.shelves[`wc:${wc.name}`] = suId;@@ -216,7 +289,6 @@ export async function runTier1(ctx: Ctx): Promise<void> {});}- // ── Payment term id ───────────────────────────────────────────────────────const netThirty = await one<{ id: string }>(client,`SELECT id FROM "paymentTerm" WHERE "companyId" = $1 AND name ILIKE '%net%30%' LIMIT 1`,@@ -224,22 +296,21 @@ export async function runTier1(ctx: Ctx): Promise<void> {);ctx.refs.misc.paymentTermId = netThirty.id;- // ── Customer status ids ───────────────────────────────────────────────────- const statuses = await rows<{ id: string; name: string }>(- client,- `SELECT id, name FROM "customerStatus" WHERE "companyId" = $1`,- [companyId]- );- for (const s of statuses) ctx.refs.misc[`cstatus:${s.name}`] = s.id;+ const paymentTermFor = (spec: { paymentTerm?: string }): Promise<string> =>+ spec.paymentTerm+ ? bootstrapIdByName(ctx, "paymentTerm", spec.paymentTerm)+ : Promise.resolve(netThirty.id);++ const currencyCodes = new Set<string>();+ for (const party of [...data.customers, ...data.suppliers]) {+ if (party.currencyCode) currencyCodes.add(party.currencyCode);+ }+ for (const code of currencyCodes) await assertCurrencyExists(ctx, code);// ── Customers ─────────────────────────────────────────────────────────────ctx.log("customers");for (const c of data.customers) {- const statusId = need(- ctx.refs.misc,- `cstatus:${c.status}`,- "customer status"- );+ const statusId = await bootstrapIdByName(ctx, "customerStatus", c.status);const typeId = need(ctx.refs.misc, `ctype:${c.type}`, "customer type");const custId = await insertId(ctx, "customer", {name: c.name,@@ -247,14 +318,14 @@ export async function runTier1(ctx: Ctx): Promise<void> {customerStatusId: statusId,phone: c.phone,website: c.website,- currencyCode: "USD"+ currencyCode: c.currencyCode ?? "USD"});ctx.refs.customers[c.name] = custId;// Interceptor created customerPayment/Shipping/Tax — just update payment termawait client.query(`UPDATE "customerPayment" SET "paymentTermId" = $1 WHERE "customerId" = $2`,- [netThirty.id, custId]+ [await paymentTermFor(c), custId]);await client.query(`UPDATE "customerShipping" SET "shippingMethodId" = $1 WHERE "customerId" = $2`,@@ -304,13 +375,14 @@ export async function runTier1(ctx: Ctx): Promise<void> {supplierTypeId: typeId,phone: s.phone,website: s.website,- currencyCode: "USD"+ currencyCode: s.currencyCode ?? "USD",+ supplierStatus: s.status ?? "Active"});ctx.refs.suppliers[s.name] = supId;await client.query(`UPDATE "supplierPayment" SET "paymentTermId" = $1 WHERE "supplierId" = $2`,- [netThirty.id, supId]+ [await paymentTermFor(s), supId]);await client.query(`UPDATE "supplierShipping" SET "shippingMethodId" = $1 WHERE "supplierId" = $2`,@@ -352,6 +424,16 @@ export async function runTier1(ctx: Ctx): Promise<void> {ctx.refs.contacts[`sc:${sc.supplier}`] = scId;}+ ctx.log("partners");+ for (const partner of data.partners) {+ await insertRow(ctx, "partner", {+ id: need(ctx.refs.misc, `sloc:${partner.supplier}`, "supplier location"),+ abilityId: need(ctx.refs.abilities, partner.ability, "ability"),+ hoursPerWeek: partner.hoursPerWeek,+ active: true+ });+ }+// ── Supplier processes (contract manufacturer) ────────────────────────────ctx.log("supplier processes");for (const sp of data.supplierProcesses) {@@ -375,7 +457,8 @@ export async function runTier1(ctx: Ctx): Promise<void> {name: agency.name,supplierTypeId: need(ctx.refs.misc, `stype:${agency.type}`),phone: agency.phone,- currencyCode: "USD"+ currencyCode: "USD",+ supplierStatus: "Active"});ctx.refs.suppliers[agency.name] = staffAgencyId;@@ -416,8 +499,7 @@ export async function runTier1(ctx: Ctx): Promise<void> {// ── Procedures (shop-floor work instructions) ─────────────────────────────// Two versions of the same name: the version menu groups on `name`, so the- // second version is what gives a procedure a readable history. Every version- // seeds as Draft so a demo company can edit its steps without a new version.+ // second version is what gives a procedure a readable history.ctx.log("procedures");for (const spec of data.procedures) {const processId = need(ctx.refs.processes, spec.process, "process");@@ -433,6 +515,13 @@ export async function runTier1(ctx: Ctx): Promise<void> {if (version.version === latestVersion) {ctx.refs.misc[`procedure:${spec.name}`] = procedureId;}+ for (const parameter of spec.parameters ?? []) {+ await insertRow(ctx, "procedureParameter", {+ procedureId,+ key: parameter.key,+ value: parameter.value+ });+ }for (const [index, step] of version.steps.entries()) {await insertId(ctx, "procedureStep", {procedureId,@@ -443,6 +532,8 @@ export async function runTier1(ctx: Ctx): Promise<void> {unitOfMeasureCode: step.unitOfMeasureCode ?? null,minValue: step.minValue ?? null,maxValue: step.maxValue ?? null,+ listValues: step.listValues ?? null,+ fileTypes: step.fileTypes ?? null,description: RICH(step.instruction)});}@@ -458,6 +549,101 @@ export async function runTier1(ctx: Ctx): Promise<void> {// ── No-quote reasons ──────────────────────────────────────────────────────ctx.log("no-quote reasons");for (const name of data.noQuoteReasons) {- await insertId(ctx, "noQuoteReason", { name });+ ctx.refs.misc[`nqr:${name}`] = await insertId(ctx, "noQuoteReason", {+ name+ });+ }++ // insertMaybe: holiday is UNIQUE (date, companyId).+ ctx.log("holidays");+ for (const holiday of data.holidays) {+ // holiday.year is GENERATED ALWAYS from date — never insert it.+ await insertMaybe(ctx, "holiday", {+ name: holiday.name,+ date: resolveDate(ctx.anchor, holiday.dateOffset)+ });+ }++ // tag's PK is (name, table, companyId) — insertMaybe keeps re-seeds clean.+ ctx.log("tags");+ for (const tag of data.tags) {+ await insertMaybe(ctx, "tag", { name: tag.name, table: tag.table });+ }++ // Company-scoped rows only (unique keys treat global rows as distinct), so+ // insertMaybe + a lookup by name is idempotent. Parents land before children+ // (FKs); helpers/items.ts resolves an item's classification the same way.+ ctx.log("material taxonomy");+ const taxonomy = data.materialTaxonomy;++ for (const substance of taxonomy.substances) {+ await insertMaybe(ctx, "materialSubstance", {+ name: substance.name,+ code: substance.code+ });+ }+ for (const form of taxonomy.forms) {+ await insertMaybe(ctx, "materialForm", {+ name: form.name,+ code: form.code+ });+ }+ for (const type of taxonomy.types) {+ await insertMaybe(ctx, "materialType", {+ name: type.name,+ code: type.code,+ materialSubstanceId: await bootstrapIdByName(+ ctx,+ "materialSubstance",+ type.substance+ ),+ materialFormId: await bootstrapIdByName(ctx, "materialForm", type.form)+ });}+ for (const grade of taxonomy.grades) {+ await insertMaybe(ctx, "materialGrade", {+ name: grade.name,+ materialSubstanceId: await bootstrapIdByName(+ ctx,+ "materialSubstance",+ grade.substance+ )+ });+ }+ for (const finish of taxonomy.finishes) {+ await insertMaybe(ctx, "materialFinish", {+ name: finish.name,+ materialSubstanceId: await bootstrapIdByName(+ ctx,+ "materialSubstance",+ finish.substance+ )+ });+ }+ for (const dimension of taxonomy.dimensions) {+ await insertMaybe(ctx, "materialDimension", {+ name: dimension.name,+ materialFormId: await bootstrapIdByName(+ ctx,+ "materialForm",+ dimension.form+ ),+ isMetric: dimension.isMetric ?? true+ });+ }++ // The seeded user gets two abilities and their job's shift so the People+ // screens have a real member. insertMaybe: both are UNIQUE (employeeId, <resource>Id).+ ctx.log("employee links");+ for (const abilityName of data.abilities.slice(0, 2)) {+ await insertMaybe(ctx, "employeeAbility", {+ employeeId: ctx.userId,+ abilityId: need(ctx.refs.abilities, abilityName, "ability"),+ lastTrainingDate: resolveDate(ctx.anchor, -30)+ });+ }+ await insertMaybe(ctx, "employeeShift", {+ employeeId: ctx.userId,+ shiftId: need(ctx.refs.shifts, data.employeeJob.shift, "shift")+ });}diff --git a/packages/database/src/datasets/tiers/02-items.ts b/packages/database/src/datasets/tiers/02-items.tsindex e0aa6455b1..06485b8bbc 100644--- a/packages/database/src/datasets/tiers/02-items.ts+++ b/packages/database/src/datasets/tiers/02-items.ts@@ -1,6 +1,145 @@+import { resolveDate, resolveTimestamp } from "../dates.ts";+import { inspectionPlan } from "../helpers/inspection.ts";import { addBomLine, addBopOperation, createItem } from "../helpers/items.ts";-import { insertId, insertRow, need } from "../sql.ts";-import type { Ctx, ItemRef } from "../types.ts";+import { insertId, insertRow, need, one, rows } from "../sql.ts";+import type {+ AssemblySpec,+ Ctx,+ EnforcementRuleSpec,+ InspectionPlanSpec,+ ItemRef,+ RuleConditionValue+} from "../types.ts";++// A file-less plan document + its features, the shape post-receipt leaves.+async function seedInspectionPlan(+ ctx: Ctx,+ spec: InspectionPlanSpec+): Promise<string> {+ const rule = inspectionPlan(spec);+ const documentId = await insertId(ctx, "inspectionDocument", {+ partId: need(ctx.refs.items, spec.item).id,+ drawingNumber: spec.drawingNumber,+ samplingPlanType: rule.type,+ samplingAql: rule.aql,+ samplingInspectionLevel: rule.inspectionLevel,+ samplingSeverity: rule.severity+ });+ for (const feature of spec.features) {+ await insertRow(ctx, "inspectionFeature", {+ inspectionDocumentId: documentId,+ pageNumber: 1,+ label: feature.label,+ description: feature.description,+ nominalValue: feature.nominalValue,+ tolerancePlus: feature.tolerancePlus,+ toleranceMinus: feature.toleranceMinus,+ unit: feature.unit,+ type: "Measurement"+ });+ }+ return documentId;+}++// `_templates/` paths resolve via getDatasetAssetUrl, not the storage proxy: the+// modelUpload row points at a bundled file, so nothing is uploaded and the assembler never runs.+async function seedAssembly(ctx: Ctx, spec: AssemblySpec): Promise<void> {+ const { industryId } = ctx.dataset;+ if (!industryId) return;++ const base = `_templates/${industryId}/models/${spec.model}`;+ const modelUploadId = await insertId(ctx, "modelUpload", {+ name: `${spec.name}.glb`,+ // Already converted, so the source and the render artifact are the same file.+ modelPath: `${base}.glb`,+ glbPath: `${base}.glb`,+ graphPath: `${base}.graph.json`,+ componentCount: spec.componentCount,+ processingStatus: "Success",+ processedAt: resolveTimestamp(ctx.anchor, 0, "09:00")+ });++ const item = spec.item ? need(ctx.refs.items, spec.item) : undefined;+ const itemId = item?.id;+ // Published is what the floor runs; editing it means cutting a new version.+ const instructionId = await insertId(ctx, "assemblyInstruction", {+ name: spec.name,+ modelUploadId,+ itemId: itemId ?? null,+ status: "Published",+ version: 1,+ publishedAt: resolveTimestamp(ctx.anchor, -1, "16:00:00")+ });++ let sortOrder = 1;+ for (const step of spec.steps) {+ const stepId = await insertId(ctx, "assemblyInstructionStep", {+ assemblyInstructionId: instructionId,+ title: step.title,+ instructionText: step.instruction ?? step.title,+ componentNodeIds: step.componentNodeIds,+ sortOrder: sortOrder+++ });+ for (const [index, material] of (step.materials ?? []).entries()) {+ await insertRow(ctx, "assemblyInstructionStepMaterial", {+ stepId,+ itemId: need(ctx.refs.items, material.item).id,+ quantity: material.quantity,+ sortOrder: index + 1+ });+ }+ for (const [index, tool] of (step.tools ?? []).entries()) {+ await insertRow(ctx, "assemblyInstructionStepTool", {+ stepId,+ itemId: need(ctx.refs.items, tool.item).id,+ quantity: tool.quantity,+ sortOrder: index + 1+ });+ }+ }++ for (const mapping of spec.componentMappings) {+ await insertRow(ctx, "assemblyComponentMapping", {+ modelUploadId,+ geometryHash: mapping.geometryHash,+ itemId: need(ctx.refs.items, mapping.item).id,+ confidence: "high"+ });+ }++ if (itemId) {+ await ctx.client.query(+ `UPDATE "item" SET "modelUploadId" = $1 WHERE "id" = $2 AND "companyId" = $3`,+ [modelUploadId, itemId, ctx.companyId]+ );+ }++ // The method's Assembly operation plays this instruction in the MES. Linked+ // before release, so quote lines (tier 04) and jobs (tier 06) copy it.+ if (!item?.makeMethodId) {+ throw new Error(+ `Seed: assembly "${spec.name}" needs an item with a make method to link operation ${spec.operation} to`+ );+ }+ const operations = await rows<{ id: string }>(+ ctx.client,+ `SELECT id FROM "methodOperation"+ WHERE "makeMethodId" = $1 AND "companyId" = $2+ ORDER BY "order"`,+ [item.makeMethodId, ctx.companyId]+ );+ const operation = operations[spec.operation - 1];+ if (!operation) {+ throw new Error(+ `Seed: assembly "${spec.name}" names operation ${spec.operation}, but ${spec.item} has only ${operations.length}`+ );+ }+ await ctx.client.query(+ `UPDATE "methodOperation" SET "assemblyInstructionId" = $1+ WHERE id = $2 AND "companyId" = $3`,+ [instructionId, operation.id, ctx.companyId]+ );+}export async function runTier2(ctx: Ctx): Promise<void> {const data = ctx.dataset.items;@@ -59,6 +198,12 @@ export async function runTier2(ctx: Ctx): Promise<void> {return ref;}+ const inspectionPlanIds: Record<string, string> = {};+ for (const plan of data.inspectionPlans) {+ ctx.log(`inspection plan ${plan.drawingNumber}`);+ inspectionPlanIds[plan.key] = await seedInspectionPlan(ctx, plan);+ }+for (const method of data.methods) {const mm = needMM(i, method.readableId);for (const line of method.bom) {@@ -75,7 +220,7 @@ export async function runTier2(ctx: Ctx): Promise<void> {);}for (const op of method.bop) {- await addBopOperation(+ const operationId = await addBopOperation(ctx,mm,need(pr, op.process),@@ -97,12 +242,46 @@ export async function runTier2(ctx: Ctx): Promise<void> {operationUnitCost: op.operationUnitCost,procedureId: op.procedure? need(ctx.refs.misc, op.procedure)+ : undefined,+ inspectionDocumentId: op.inspectionPlan+ ? need(inspectionPlanIds, op.inspectionPlan, "inspection plan"): undefined});+ for (const tool of op.tools ?? []) {+ await insertRow(ctx, "methodOperationTool", {+ operationId,+ toolId: needItem(tool.tool).id,+ quantity: tool.quantity+ });+ }+ for (const parameter of op.parameters ?? []) {+ await insertRow(ctx, "methodOperationParameter", {+ operationId,+ key: parameter.key,+ value: parameter.value+ });+ }}}+ if (data.assembly) {+ ctx.log(`assembly ${data.assembly.name}`);+ await seedAssembly(ctx, data.assembly);+ }++ // Authored methods are released: Active is what job creation copies and what+ // the change notices (tier 08) cut their Draft versions from.+ await ctx.client.query(+ `UPDATE "makeMethod" SET status = 'Active', "updatedBy" = $3+ WHERE id = ANY($1) AND "companyId" = $2`,+ [+ data.methods.map((method) => needMM(i, method.readableId)),+ ctx.companyId,+ ctx.userId+ ]+ );+// ── Supplier parts (which supplier can supply what) ────────────────────────ctx.log("supplier parts");for (const sl of data.supplierLinks) {@@ -123,6 +302,254 @@ export async function runTier2(ctx: Ctx): Promise<void> {sourceType: "Manual Entry"});}++ // The active revision is the released one, so it goes to Production (locking+ // its BOM/BOP in the app). The rungs share its readableId and stay out of+ // ctx.refs.items so later tiers keep resolving the active revision.+ ctx.log("revision ladder");+ const allItemSpecs = [+ ...data.buyParts,+ ...data.materials,+ ...data.consumables,+ ...data.tools,+ ...data.services,+ ...data.makeParts+ ];+ for (const ladder of data.revisionLadder) {+ const baseSpec = allItemSpecs.find(+ (spec) => spec.readableId === ladder.item+ );+ if (!baseSpec) {+ throw new Error(+ `Seed: revisionLadder item "${ladder.item}" is not a seeded item spec`+ );+ }+ await ctx.client.query(+ `UPDATE item SET "revisionStatus" = 'Production'+ WHERE id = $1 AND "companyId" = $2`,+ [needItem(ladder.item).id, ctx.companyId]+ );+ await createItem(ctx, {+ ...baseSpec,+ revision: ladder.obsoleteRevision,+ active: false,+ revisionStatus: "Obsolete",+ description: `Rev ${ladder.obsoleteRevision} — superseded; kept for historical jobs`+ });+ await createItem(ctx, {+ ...baseSpec,+ revision: ladder.nextRevision,+ active: false,+ revisionStatus: ladder.nextStatus,+ description: `Rev ${ladder.nextRevision} — in work, not yet released`+ });+ }++ // PK is itemId ALONE — the row lives on the predecessor.+ ctx.log("supersessions");+ for (const spec of data.supersessions) {+ await insertRow(ctx, "itemSupersession", {+ itemId: needItem(spec.predecessor).id,+ successorItemId: needItem(spec.successor).id,+ supersessionMode: spec.mode,+ // undefined keys are dropped, keeping the column default (1).+ conversionFactor: spec.conversionFactor,+ successorEffectivityDate:+ spec.successorEffectivityOffset !== undefined+ ? resolveDate(ctx.anchor, spec.successorEffectivityOffset)+ : undefined,+ discontinuationDate:+ spec.discontinuationOffset !== undefined+ ? resolveDate(ctx.anchor, spec.discontinuationOffset)+ : undefined+ });+ }++ ctx.log("customer part numbers");+ for (const spec of data.customerParts) {+ await insertRow(ctx, "customerPartToItem", {+ itemId: needItem(spec.item).id,+ customerId: need(ctx.refs.customers, spec.customer, "customer"),+ customerPartId: spec.customerPartId,+ customerPartRevision: spec.customerRevision ?? null+ });+ }++ ctx.log("customer price overrides");+ for (const spec of data.priceOverrides) {+ const overrideId = await insertId(ctx, "customerItemPriceOverride", {+ itemId: needItem(spec.item).id,+ customerId: need(ctx.refs.customers, spec.customer, "customer"),+ notes: spec.notes ?? null+ });+ for (const priceBreak of spec.breaks) {+ await insertRow(ctx, "customerItemPriceOverrideBreak", {+ customerItemPriceOverrideId: overrideId,+ quantity: priceBreak.quantity,+ overridePrice: priceBreak.overridePrice+ });+ }+ }++ ctx.log("pricing rules");+ for (const spec of data.pricingRules) {+ await insertRow(ctx, "pricingRule", {+ name: spec.name,+ ruleType: spec.ruleType,+ amountType: spec.amountType,+ amount: spec.amount,+ priority: spec.priority,+ customerIds: spec.customer+ ? [need(ctx.refs.customers, spec.customer, "customer")]+ : undefined,+ customerTypeIds: spec.customerType+ ? [need(ctx.refs.misc, `ctype:${spec.customerType}`, "customer type")]+ : undefined,+ itemIds: spec.items?.map((item) => needItem(item).id),+ minQuantity: spec.minQuantity+ });+ }++ // requiresConfiguration is what shows the Configure button and the rules+ // panel; a rule's field is `${field}:${methodRowId}`, as the BoM/BoP+ // editors key it.+ ctx.log("configuration parameters + rules");+ const cfg = data.configuration;+ const cfgItem = needItem(cfg.item);+ const flagged = await ctx.client.query(+ `UPDATE "itemReplenishment" SET "requiresConfiguration" = true, "updatedBy" = $3+ WHERE "itemId" = $1 AND "companyId" = $2`,+ [cfgItem.id, ctx.companyId, ctx.userId]+ );+ if (flagged.rowCount !== 1) {+ throw new Error(`Seed: "${cfg.item}" has no itemReplenishment row`);+ }+ const groupId = await insertId(ctx, "configurationParameterGroup", {+ itemId: cfgItem.id,+ name: cfg.group,+ sortOrder: 1+ });+ for (const [index, parameter] of cfg.parameters.entries()) {+ await insertRow(ctx, "configurationParameter", {+ itemId: cfgItem.id,+ configurationParameterGroupId: groupId,+ key: parameter.key,+ label: parameter.label,+ dataType: parameter.dataType,+ listOptions: parameter.listOptions ?? null,+ sortOrder: index + 1+ });+ }+ const cfgMethodId = needMM(i, cfg.item);+ for (const rule of cfg.rules) {+ const row =+ "component" in rule.target+ ? await one<{ id: string }>(+ ctx.client,+ `SELECT id FROM "methodMaterial"+ WHERE "makeMethodId" = $1 AND "itemId" = $2 AND "companyId" = $3`,+ [cfgMethodId, needItem(rule.target.component).id, ctx.companyId]+ )+ : await one<{ id: string }>(+ ctx.client,+ `SELECT id FROM "methodOperation"+ WHERE "makeMethodId" = $1 AND "companyId" = $2+ ORDER BY "order" OFFSET $3 LIMIT 1`,+ [cfgMethodId, ctx.companyId, rule.target.operation - 1]+ );+ await insertRow(ctx, "configurationRule", {+ itemId: cfgItem.id,+ field: `${rule.field}:${row.id}`,+ code: rule.code,+ updatedBy: ctx.userId+ });+ }++ ctx.log("enforcement rules");+ for (const spec of data.enforcementRules) {+ await seedEnforcementRule(ctx, spec);+ }++ ctx.log("batch properties");+ const nextSortOrder = new Map<string, number>();+ for (const property of data.batchProperties) {+ const sortOrder = (nextSortOrder.get(property.item) ?? 0) + 1;+ nextSortOrder.set(property.item, sortOrder);+ await insertRow(ctx, "batchProperty", {+ itemId: needItem(property.item).id,+ label: property.label,+ dataType: property.dataType,+ listOptions: property.listOptions ?? null,+ sortOrder+ });+ }+}++function resolveRuleValue(+ ctx: Ctx,+ value: RuleConditionValue | undefined+): unknown {+ if (value === undefined || value === null || typeof value !== "object") {+ return value;+ }+ if (Array.isArray(value)) return value;+ if ("storageType" in value) {+ return need(+ ctx.refs.misc,+ `storagetype:${value.storageType}`,+ "storage type"+ );+ }+ if ("customerTypes" in value) {+ return value.customerTypes.map((name) =>+ need(ctx.refs.misc, `ctype:${name}`, "customer type")+ );+ }+ return need(ctx.refs.locations, value.location, "location");+}++// The row upsertEnforcementRule writes, plus the assignment rows the item /+// work-center rules panels list.+async function seedEnforcementRule(+ ctx: Ctx,+ spec: EnforcementRuleSpec+): Promise<void> {+ const targetType = spec.family === "sales" ? "item" : spec.targetType;+ const ruleId = await insertId(ctx, "enforcementRule", {+ family: spec.family,+ name: spec.name,+ description: spec.description,+ message: spec.message,+ severity: spec.severity,+ conditionAst: JSON.stringify({+ kind: spec.match,+ conditions: spec.conditions.map((condition) => ({+ field: condition.field,+ op: condition.op,+ ...(condition.value === undefined+ ? {}+ : { value: resolveRuleValue(ctx, condition.value) })+ }))+ }),+ surfaces: spec.surfaces,+ targetType,+ active: true+ });+ if ("workCenters" in spec) {+ for (const workCenter of spec.workCenters) {+ await insertRow(ctx, "enforcementRuleWorkCenterAssignment", {+ ruleId,+ workCenterId: need(ctx.refs.workCenters, workCenter, "work center")+ });+ }+ return;+ }+ for (const item of spec.items) {+ await insertRow(ctx, "enforcementRuleItemAssignment", {+ ruleId,+ itemId: need(ctx.refs.items, item, "item").id+ });+ }}function needMM(items: Record<string, ItemRef>, readableId: string): string {diff --git a/packages/database/src/datasets/tiers/03-inventory.ts b/packages/database/src/datasets/tiers/03-inventory.tsindex 26ea0e6170..c31cc85246 100644--- a/packages/database/src/datasets/tiers/03-inventory.ts+++ b/packages/database/src/datasets/tiers/03-inventory.ts@@ -1,5 +1,54 @@+import { resolveDate, resolveTimestamp } from "../dates.ts";+import { bootstrapIdByName } from "../helpers/bootstrap-lookup.ts";import { insertId, insertRow, need, nextSequence } from "../sql.ts";-import type { Ctx } from "../types.ts";+import type { Ctx, TrackedStockSpec } from "../types.ts";++// Mirrors post-inventory-adjustment's full-entity Scrap (the entity keeps its+// quantity). Tier 09 posts its cost row and scrap-account journal.+async function scrapLot(+ ctx: Ctx,+ entity: TrackedStockSpec["entities"][number],+ itemRef: { id: string; readableId: string }+): Promise<void> {+ const scrap = entity.scrap;+ if (!scrap) {+ throw new Error(+ `Seed: Scrapped lot "${entity.readableId}" has no scrap spec`+ );+ }+ const entityId = need(ctx.refs.misc, `te:${entity.readableId}`);+ const reasonId = await bootstrapIdByName(ctx, "scrapReason", scrap.reason);+ const activityId = await insertId(ctx, "trackedActivity", {+ type: "Scrap",+ sourceDocument: "Item",+ sourceDocumentId: itemRef.id,+ sourceDocumentReadableId: itemRef.readableId,+ attributes: JSON.stringify({+ "Scrap Reason": reasonId,+ Employee: ctx.userId,+ Notes: scrap.comment+ }),+ updatedBy: ctx.userId+ });+ await insertRow(ctx, "trackedActivityInput", {+ trackedActivityId: activityId,+ trackedEntityId: entityId,+ quantity: entity.quantity,+ updatedBy: ctx.userId+ });+ await insertRow(ctx, "itemLedger", {+ entryType: "Negative Adjmt.",+ documentType: "Scrap",+ scrapReasonId: reasonId,+ postingDate: resolveDate(ctx.anchor, scrap.dateOffset),+ itemId: itemRef.id,+ locationId: ctx.refs.locations.Plant ?? ctx.locationId,+ storageUnitId: need(ctx.refs.shelves, scrap.shelf),+ trackedEntityId: entityId,+ quantity: -entity.quantity,+ comment: scrap.comment+ });+}export async function runTier3(ctx: Ctx): Promise<void> {const { companyId, userId, locationId } = ctx;@@ -25,65 +74,296 @@ export async function runTier3(ctx: Ctx): Promise<void> {});}+ ctx.log("pick methods");+ const defaultShelf = new Map<string, string>();+ for (const entry of data.openingStock) {+ if (!defaultShelf.has(entry.item))+ defaultShelf.set(entry.item, entry.shelf);+ }+ for (const [item, shelf] of defaultShelf) {+ await insertRow(ctx, "pickMethod", {+ itemId: need(ctx.refs.items, item).id,+ locationId: plantId,+ defaultStorageUnitId: need(ctx.refs.shelves, shelf)+ });+ }+// ── 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");+ // even though the item shows stock. A Scrapped lot also gets the scrap+ // posting (scrapLot).+ ctx.log("lots and serials");for (const stock of data.onHandTracked) {const itemRef = need(ctx.refs.items, stock.item);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- });+ // Registered so quality can hang an NCR on a specific lot (tier 07).+ ctx.refs.misc[`te:${entity.readableId}`] = await insertId(+ ctx,+ "trackedEntity",+ {+ quantity: entity.quantity,+ status: entity.status ?? "Available",+ sourceDocument: "Item",+ sourceDocumentId: itemRef.id,+ sourceDocumentReadableId: itemRef.readableId,+ readableId: entity.readableId,+ itemId: itemRef.id,+ attributes: JSON.stringify({}),+ expirationDate:+ entity.expiresOffset !== undefined+ ? resolveDate(ctx.anchor, entity.expiresOffset)+ : undefined,+ updatedBy: userId+ }+ );+ if (entity.status === "Scrapped") await scrapLot(ctx, entity, itemRef);}}- // ── Kanbans (auto-replenishment cards) for high-usage buy parts ───────────+ ctx.log("item shelf lives");+ for (const shelfLife of data.shelfLives) {+ const itemRef = need(ctx.refs.items, shelfLife.item);+ await insertRow(ctx, "itemShelfLife", {+ itemId: itemRef.id,+ mode: "Fixed Duration",+ days: shelfLife.days+ });+ }+ctx.log("kanban cards");for (const kb of data.kanbanItems) {const itemRef = need(ctx.refs.items, kb.item);- const supplierId = need(ctx.refs.suppliers, kb.supplier);+ const system = kb.replenishmentSystem ?? "Buy";+ // Transfer cards need two distinct bins (kanbanValidator; validate.ts mirrors it).+ if (system === "Buy" && kb.supplier === undefined) {+ throw new Error(`Seed: Buy kanban for "${kb.item}" has no supplier`);+ }+ if (system === "Transfer" && (!kb.fromShelf || !kb.toShelf)) {+ throw new Error(+ `Seed: Transfer kanban for "${kb.item}" needs fromShelf and toShelf`+ );+ }await insertId(ctx, "kanban", {itemId: itemRef.id,- replenishmentSystem: "Buy",+ replenishmentSystem: system,quantity: kb.qty,locationId: plantId,- supplierId,+ supplierId:+ system === "Buy" && kb.supplier !== undefined+ ? need(ctx.refs.suppliers, kb.supplier)+ : undefined,+ fromStorageUnitId:+ system === "Transfer" && kb.fromShelf+ ? need(ctx.refs.shelves, kb.fromShelf)+ : undefined,+ storageUnitId:+ system === "Transfer" && kb.toShelf+ ? need(ctx.refs.shelves, kb.toShelf)+ : undefined,autoRelease: true});}- // ── Inventory count (Draft state — Posted counts need the edge function) ──- ctx.log("inventory count (draft)");- const countId = await nextSequence(ctx, "inventoryCount");- const icId = await insertId(ctx, "inventoryCount", {- inventoryCountId: countId,- locationId: plantId,- status: data.inventoryCount.status,- notes: data.inventoryCount.notes- });+ // Draft = the app's pre-snapshot state (bare lines). Posted mirrors+ // post-inventory-count: frozen quantities plus one adjustment ledger row per+ // variance, linked back through postedItemLedgerId.+ for (const count of data.inventoryCounts) {+ ctx.log(`inventory count (${count.status.toLowerCase()})`);+ const readableId = await nextSequence(ctx, "inventoryCount");+ const posted = count.status === "Posted";+ if (posted && count.postedOffset === undefined) {+ throw new Error(+ `Seed: inventory count "${count.key}" is Posted but has no postedOffset`+ );+ }+ const postedAt = posted+ ? resolveTimestamp(ctx.anchor, count.postedOffset ?? 0, "16:00:00")+ : undefined;+ const icId = await insertId(ctx, "inventoryCount", {+ inventoryCountId: readableId,+ locationId: plantId,+ status: count.status,+ notes: count.notes,+ snapshotAt: postedAt,+ postedAt,+ postedBy: posted ? userId : undefined+ });- // Add a few count lines for the items we put in stock- const sampleLines = data.openingStock.slice(0, 6);- for (const entry of sampleLines) {- const itemRef = need(ctx.refs.items, entry.item);- const shelfId = need(ctx.refs.shelves, entry.shelf);- await insertId(ctx, "inventoryCountLine", {- inventoryCountId: icId,- itemId: itemRef.id,+ for (const line of count.lines) {+ const itemRef = need(ctx.refs.items, line.item);+ const shelfId = need(ctx.refs.shelves, line.shelf);+ if (!posted) {+ await insertId(ctx, "inventoryCountLine", {+ inventoryCountId: icId,+ itemId: itemRef.id,+ locationId: plantId,+ storageUnitId: shelfId+ });+ continue;+ }++ const delta = line.countedQuantity - line.snapshotQuantity;+ let postedItemLedgerId: string | undefined;+ if (delta !== 0) {+ postedItemLedgerId = await insertId(ctx, "itemLedger", {+ entryType: delta > 0 ? "Positive Adjmt." : "Negative Adjmt.",+ documentType: "Inventory Count",+ documentId: icId,+ itemId: itemRef.id,+ locationId: plantId,+ storageUnitId: shelfId,+ quantity: delta,+ postingDate: resolveDate(ctx.anchor, count.postedOffset ?? 0),+ comment: `Inventory Count ${readableId}`,+ companyId,+ createdBy: userId+ });+ }+ await insertId(ctx, "inventoryCountLine", {+ inventoryCountId: icId,+ itemId: itemRef.id,+ locationId: plantId,+ storageUnitId: shelfId,+ systemQuantity: line.snapshotQuantity,+ countedQuantity: line.countedQuantity,+ countedAt: postedAt,+ countedBy: userId,+ postedItemLedgerId+ });+ }++ ctx.refs.documents[`ic:${count.key}`] = icId;+ }++ // Completed mirrors post-stock-transfer's "inventory" case: a Direct Transfer+ // ledger pair per line. Draft/Released move nothing yet.+ ctx.log("stock transfers");+ for (const transfer of data.stockTransfers) {+ const readableId = await nextSequence(ctx, "stockTransfer");+ const fromShelfId = need(ctx.refs.shelves, transfer.fromShelf);+ const toShelfId = need(ctx.refs.shelves, transfer.toShelf);+ const completed = transfer.status === "Completed";+ const createdAt = resolveTimestamp(+ ctx.anchor,+ transfer.dateOffset,+ "09:00:00"+ );+ const stId = await insertId(ctx, "stockTransfer", {+ stockTransferId: readableId,locationId: plantId,- storageUnitId: shelfId+ status: transfer.status,+ createdAt,+ completedAt: completed+ ? resolveTimestamp(ctx.anchor, transfer.dateOffset, "15:30:00")+ : undefined});++ for (const line of transfer.lines) {+ const itemRef = need(ctx.refs.items, line.item);+ await insertId(ctx, "stockTransferLine", {+ stockTransferId: stId,+ itemId: itemRef.id,+ quantity: line.quantity,+ pickedQuantity: completed ? line.quantity : 0,+ fromStorageUnitId: fromShelfId,+ toStorageUnitId: toShelfId+ });+ if (completed) {+ const postingDate = resolveDate(ctx.anchor, transfer.dateOffset);+ await insertRow(ctx, "itemLedger", {+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stId,+ itemId: itemRef.id,+ locationId: plantId,+ storageUnitId: fromShelfId,+ quantity: -line.quantity,+ postingDate,+ companyId,+ createdBy: userId+ });+ await insertRow(ctx, "itemLedger", {+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: stId,+ itemId: itemRef.id,+ locationId: plantId,+ storageUnitId: toShelfId,+ quantity: line.quantity,+ postingDate,+ companyId,+ createdBy: userId+ });+ }+ }++ ctx.refs.documents[`st:${transfer.key}`] = stId;}- ctx.refs.documents.inventoryCount = icId;+ // Completed mirrors post-shipment + post-receipt: a Transfer Shipment row out+ // of the from-shelf and a shelfless Transfer Receipt (HQ has no bins; the app+ // does the same), documentId = the READABLE transferId.+ ctx.log("warehouse transfers");+ for (const transfer of data.warehouseTransfers) {+ const readableId = await nextSequence(ctx, "warehouseTransfer");+ const fromLocationId = need(ctx.refs.locations, transfer.fromLocation);+ const toLocationId = need(ctx.refs.locations, transfer.toLocation);+ const completed = transfer.status === "Completed";+ const wtId = await insertId(ctx, "warehouseTransfer", {+ transferId: readableId,+ fromLocationId,+ toLocationId,+ status: transfer.status,+ transferDate: resolveDate(ctx.anchor, transfer.dateOffset),+ expectedReceiptDate: resolveDate(ctx.anchor, transfer.dateOffset + 5)+ });++ for (const line of transfer.lines) {+ const itemRef = need(ctx.refs.items, line.item);+ const fromShelfId =+ line.fromShelf !== undefined+ ? need(ctx.refs.shelves, line.fromShelf)+ : undefined;+ await insertId(ctx, "warehouseTransferLine", {+ transferId: wtId,+ itemId: itemRef.id,+ quantity: line.quantity,+ fromLocationId,+ toLocationId,+ fromStorageUnitId: fromShelfId,+ unitOfMeasureCode: itemRef.unitOfMeasureCode,+ shippedQuantity: completed ? line.quantity : 0,+ receivedQuantity: completed ? line.quantity : 0+ });+ if (completed) {+ const postingDate = resolveDate(ctx.anchor, transfer.dateOffset);+ await insertRow(ctx, "itemLedger", {+ entryType: "Transfer",+ documentType: "Transfer Shipment",+ documentId: readableId,+ itemId: itemRef.id,+ locationId: fromLocationId,+ storageUnitId: fromShelfId,+ quantity: -line.quantity,+ postingDate,+ companyId,+ createdBy: userId+ });+ await insertRow(ctx, "itemLedger", {+ entryType: "Transfer",+ documentType: "Transfer Receipt",+ documentId: readableId,+ itemId: itemRef.id,+ locationId: toLocationId,+ quantity: line.quantity,+ postingDate,+ companyId,+ createdBy: userId+ });+ }+ }++ ctx.refs.documents[`wt:${transfer.key}`] = wtId;+ }}diff --git a/packages/database/src/datasets/tiers/04-sales.ts b/packages/database/src/datasets/tiers/04-sales.tsindex be1705af22..f4013105dd 100644--- a/packages/database/src/datasets/tiers/04-sales.ts+++ b/packages/database/src/datasets/tiers/04-sales.ts@@ -1,4 +1,7 @@-import { resolveDate } from "../dates.ts";+import { resolveDate, resolveTimestamp } from "../dates.ts";+import { bootstrapIdByName } from "../helpers/bootstrap-lookup.ts";+import { copyMethodToQuoteLine } from "../helpers/method-copy.ts";+import { seedReturnCredit } from "../helpers/return-credit.ts";import { insertId, insertRow, need, nextSequence, RICH } from "../sql.ts";import type { Ctx, PriceBreak, SalesOpportunitySpec } from "../types.ts";@@ -58,7 +61,11 @@ export async function runTier4(ctx: Ctx): Promise<void> {async function insertOpportunity(spec: SalesOpportunitySpec): Promise<void> {ctx.log(spec.log);const customerId = need(ctx.refs.customers, spec.customer);- const customerLocationId = ctx.refs.misc[`cloc:${spec.customer}`] ?? null;+ const customerLocationId = need(+ ctx.refs.misc,+ `cloc:${spec.customer}`,+ "customer location"+ );const opportunityId = await insertId(ctx, "opportunity", { customerId });ctx.refs.documents[spec.ref] = opportunityId;@@ -72,7 +79,23 @@ export async function runTier4(ctx: Ctx): Promise<void> {customerLocationId,locationId: plantId,opportunityId,+ // The no-quote reason lives on the RFQ, as updateSalesRFQStatus writes it.+ noQuoteReasonId:+ spec.rfq.noQuoteReason === undefined+ ? undefined+ : need(+ ctx.refs.misc,+ `nqr:${spec.rfq.noQuoteReason}`,+ "no-quote reason"+ ),rfqDate: resolveDate(ctx.anchor, spec.rfq.rfqDateOffset),+ // The KPI chart counts RFQs by createdAt; a seed-time stamp is one spike.+ createdAt: resolveTimestamp(+ ctx.anchor,+ spec.rfq.rfqDateOffset,+ "09:00:00"+ ),+ assignee: spec.rfq.assignee === "self" ? ctx.userId : undefined,expirationDate:spec.rfq.expirationOffset === undefined? undefined@@ -104,6 +127,15 @@ export async function runTier4(ctx: Ctx): Promise<void> {locationId: plantId,currencyCode: "USD",opportunityId,+ createdAt:+ spec.quote.createdOffset === undefined+ ? undefined+ : resolveTimestamp(+ ctx.anchor,+ spec.quote.createdOffset,+ "09:30:00"+ ),+ assignee: spec.quote.assignee === "self" ? ctx.userId : undefined,expirationDate:spec.quote.expirationOffset === undefined? undefined@@ -138,9 +170,14 @@ export async function runTier4(ctx: Ctx): Promise<void> {// array, so a break that isn't in quoteLine.quantity is invisible.quantity: line.priceBreaks.map((brk) => brk.quantity),status: line.status,- sortOrder: line.sortOrder+ sortOrder: line.sortOrder,+ configuration:+ line.configuration === undefined+ ? undefined+ : JSON.stringify(line.configuration)});await insertPriceBreaks(ctx, quoteId, quoteLineId, line.priceBreaks);+ await copyMethodToQuoteLine(ctx, quoteId, quoteLineId);ctx.refs.documents[line.ref] = quoteLineId;}@@ -184,7 +221,8 @@ export async function runTier4(ctx: Ctx): Promise<void> {locationId: plantId,currencyCode: "USD",opportunityId,- orderDate: resolveDate(ctx.anchor, spec.order.orderDateOffset)+ orderDate: resolveDate(ctx.anchor, spec.order.orderDateOffset),+ assignee: spec.order.assignee === "self" ? ctx.userId : undefined});await insertRow(ctx, "salesOrderPayment", {id: orderId,@@ -231,12 +269,22 @@ export async function runTier4(ctx: Ctx): Promise<void> {ctx.refs.documents[spec.order.ref] = orderId;}- // Shipment (Draft — Posted shipments need the edge function)+ // Draft/Voided are header+lines only; Posted mirrors post-shipment's+ // untracked branch: one Sales Shipment ledger row per line out of its fromShelf.let shipmentId: string | null = null;if (spec.shipment) {if (!orderId || !orderReadableId) {throw new Error(`Seed: shipment on "${spec.ref}" has no sales order`);}+ const posted = spec.shipment.status === "Posted";+ if (posted && spec.shipment.postedOffset === undefined) {+ throw new Error(+ `Seed: shipment "${spec.shipment.ref}" is Posted but has no postedOffset`+ );+ }+ const postingDate = posted+ ? resolveDate(ctx.anchor, spec.shipment.postedOffset ?? 0)+ : undefined;const shipmentReadableId = await nextSequence(ctx, "shipment");shipmentId = await insertId(ctx, "shipment", {shipmentId: shipmentReadableId,@@ -247,10 +295,21 @@ export async function runTier4(ctx: Ctx): Promise<void> {sourceDocumentReadableId: orderReadableId,shippingMethodId,customerId,- opportunityId+ opportunityId,+ postingDate,+ postedBy: posted ? userId : undefined});for (const line of spec.shipment.lines) {const item = need(ctx.refs.items, line.item);+ const shelfId =+ line.fromShelf === undefined+ ? undefined+ : need(ctx.refs.shelves, line.fromShelf);+ if (posted && line.shippedQuantity > 0 && shelfId === undefined) {+ throw new Error(+ `Seed: posted shipment "${spec.shipment.ref}" line "${line.item}" has no fromShelf`+ );+ }await insertId(ctx, "shipmentLine", {shipmentId,lineId: need(orderLineIdByItem, line.item),@@ -259,15 +318,31 @@ export async function runTier4(ctx: Ctx): Promise<void> {outstandingQuantity: line.outstandingQuantity,shippedQuantity: line.shippedQuantity,locationId: plantId,+ storageUnitId: shelfId,unitOfMeasure: "EA",unitPrice: line.unitPrice});+ if (posted && line.shippedQuantity > 0) {+ await insertRow(ctx, "itemLedger", {+ entryType: "Negative Adjmt.",+ documentType: "Sales Shipment",+ documentId: shipmentId,+ itemId: item.id,+ locationId: plantId,+ storageUnitId: shelfId,+ quantity: -line.shippedQuantity,+ postingDate,+ companyId,+ createdBy: userId+ });+ }}ctx.refs.documents[spec.shipment.ref] = shipmentId;}if (spec.invoice) {const invoiceReadableId = await nextSequence(ctx, "salesInvoice");+ const dateIssued = resolveDate(ctx.anchor, spec.invoice.dateIssuedOffset);const invoiceId = await insertId(ctx, "salesInvoice", {invoiceId: invoiceReadableId,status: spec.invoice.status,@@ -280,8 +355,18 @@ export async function runTier4(ctx: Ctx): Promise<void> {totalAmount: spec.invoice.totalAmount,invoiceCustomerId: customerId,shipmentId: shipmentId ?? undefined,- dateIssued: resolveDate(ctx.anchor, spec.invoice.dateIssuedOffset)+ dateIssued,+ // post-sales-invoice stamps it; the AR aging and open-balance RPCs filter on it.+ postingDate: spec.invoice.status === "Draft" ? undefined : dateIssued,+ dateDue:+ spec.invoice.dueDateOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, spec.invoice.dueDateOffset)});+ // Payments settle Paid / Partially Paid invoices by this key.+ if (spec.invoice.key !== undefined) {+ ctx.refs.misc[`sinv:${spec.invoice.key}`] = invoiceId;+ }// salesInvoiceShipment — id = invoice.id (INNER JOINed by the salesInvoices view)await insertRow(ctx, "salesInvoiceShipment", {id: invoiceId,@@ -317,7 +402,11 @@ export async function runTier4(ctx: Ctx): Promise<void> {for (const spec of data.statusOrders) {ctx.log(`sales order — ${spec.status} (job ${spec.key})`);const customerId = need(ctx.refs.customers, spec.customer);- const customerLocationId = ctx.refs.misc[`cloc:${spec.customer}`] ?? null;+ const customerLocationId = need(+ ctx.refs.misc,+ `cloc:${spec.customer}`,+ "customer location"+ );const item = need(ctx.refs.items, spec.item);const oppId = await insertId(ctx, "opportunity", { customerId });const readableId = await nextSequence(ctx, "salesOrder");@@ -365,4 +454,189 @@ export async function runTier4(ctx: Ctx): Promise<void> {for (const spec of data.releasedOrders) {await insertOpportunity(spec);}++ // Completed mirrors post-receipt's Sales Return Order branch: a Posted receipt+ // plus a Sales Return Receipt ledger row per line. A `credit` adds Issue+ // Credit's memo (helpers/return-credit.ts); tier 09 journals it if Posted.+ if (data.salesReturns.length > 0) {+ ctx.log("sales returns");+ for (const spec of data.salesReturns) {+ ctx.log(` rma ${spec.key} — ${spec.status}`);+ const customerId = need(ctx.refs.customers, spec.customer);+ const customerLocationId = need(+ ctx.refs.misc,+ `cloc:${spec.customer}`,+ "customer location"+ );+ const returnReasonId = await bootstrapIdByName(+ ctx,+ "returnReason",+ spec.returnReason+ );+ const completed = spec.status === "Completed";+ const orderDate = resolveDate(ctx.anchor, spec.dateOffset);+ const rmaReadableId = await nextSequence(ctx, "salesReturnOrder");+ const rmaId = await insertId(ctx, "salesReturnOrder", {+ salesReturnOrderId: rmaReadableId,+ status: spec.status,+ customerId,+ customerLocationId,+ locationId: plantId,+ currencyCode: "USD",+ orderDate,+ salesOrderId:+ spec.salesOrder === undefined+ ? undefined+ : need(ctx.refs.documents, spec.salesOrder, "sales order ref")+ });++ const lineIds: string[] = [];+ for (const [index, line] of spec.lines.entries()) {+ const item = need(ctx.refs.items, line.item);+ const lineId = await insertId(ctx, "salesReturnOrderLine", {+ salesReturnOrderId: rmaId,+ itemId: item.id,+ lineNumber: index + 1,+ quantity: line.quantity,+ quantityReceived: completed ? line.quantity : 0,+ returnReasonId,+ unitOfMeasureCode: "EA",+ unitPrice: line.unitPrice+ });+ lineIds.push(lineId);+ ctx.refs.documents[`rmaline:${spec.key}:${index + 1}`] = lineId;+ }++ if (completed) {+ const receiptReadableId = await nextSequence(ctx, "receipt");+ const receiptId = await insertId(ctx, "receipt", {+ receiptId: receiptReadableId,+ status: "Posted",+ locationId: plantId,+ sourceDocument: "Sales Return Order",+ sourceDocumentId: rmaId,+ sourceDocumentReadableId: rmaReadableId,+ postingDate: orderDate,+ postedBy: userId+ });+ for (const [index, line] of spec.lines.entries()) {+ const item = need(ctx.refs.items, line.item);+ if (line.toShelf === undefined) {+ throw new Error(+ `Seed: completed return "${spec.key}" line "${line.item}" has no toShelf`+ );+ }+ const shelfId = need(ctx.refs.shelves, line.toShelf);+ await insertId(ctx, "receiptLine", {+ receiptId,+ lineId: lineIds[index],+ itemId: item.id,+ orderQuantity: line.quantity,+ outstandingQuantity: 0,+ receivedQuantity: line.quantity,+ locationId: plantId,+ storageUnitId: shelfId,+ unitOfMeasure: "EA",+ unitPrice: line.unitPrice+ });+ await insertRow(ctx, "itemLedger", {+ entryType: "Positive Adjmt.",+ documentType: "Sales Return Receipt",+ documentId: receiptId,+ itemId: item.id,+ locationId: plantId,+ storageUnitId: shelfId,+ quantity: line.quantity,+ postingDate: orderDate,+ companyId,+ createdBy: userId+ });+ }+ ctx.refs.documents[`rma-receipt:${spec.key}`] = receiptId;+ }++ if (spec.credit) {+ ctx.log(` rma ${spec.key} — credit memo (${spec.credit.status})`);+ await seedReturnCredit(ctx, {+ spec: spec.credit,+ kind: "sales",+ partyId: customerId,+ returnOrderId: rmaId+ });+ }++ ctx.refs.documents[`rma:${spec.key}`] = rmaId;+ }+ }++ // The portal form's insert: documentId = customerId. No fixed id —+ // externalLink's PK is global.+ ctx.log("customer portals");+ for (const customer of data.customerPortals) {+ const customerId = need(ctx.refs.customers, customer, "customer");+ await insertId(ctx, "externalLink", {+ documentType: "Customer",+ documentId: customerId,+ customerId+ });+ }++ for (const spec of data.customerBankAccounts) {+ await insertRow(ctx, "customerBankAccount", {+ customerId: need(ctx.refs.customers, spec.customer, "customer"),+ name: spec.name,+ accountHolderName: spec.accountHolderName,+ bankName: spec.bankName,+ countryCode: spec.countryCode,+ currencyCode: spec.currencyCode,+ accountNumber: spec.accountNumber,+ bankCode: spec.bankCode,+ swiftBic: spec.swiftBic,+ isPrimary: spec.isPrimary,+ active: true+ });+ }++ // Timestamps are staggered so the timeline reads as a real approval trail.+ const inProgress = [...data.opportunities, ...data.releasedOrders].find(+ (spec) => spec.order?.status === "In Progress"+ );+ if (inProgress?.order) {+ ctx.log(`status history — ${inProgress.order.ref}`);+ const salesOrderId = need(ctx.refs.documents, inProgress.order.ref);+ const base = inProgress.order.orderDateOffset;+ const trail: Array<[string, number, string]> = [+ ["Draft", base, "09:12:00"],+ ["Confirmed", base + 1, "15:41:00"],+ ["In Progress", base + 6, "10:05:00"]+ ];+ for (const [status, offset, timeOfDay] of trail) {+ await insertRow(ctx, "salesOrderStatusHistory", {+ salesOrderId,+ status,+ createdAt: resolveTimestamp(ctx.anchor, offset, timeOfDay)+ });+ }+ }++ // The job favorite is tier 06's — job refs do not exist yet.+ const sentQuote = data.opportunities.find(+ (spec) => spec.quote?.status === "Sent"+ );+ if (!sentQuote?.quote) {+ throw new Error(`Seed: no Sent quote to favorite`);+ }+ await insertRow(ctx, "quoteFavorite", {+ quoteId: need(ctx.refs.documents, sentQuote.quote.ref),+ userId+ });++ const firstReleased = data.releasedOrders[0];+ if (!firstReleased?.order) {+ throw new Error(`Seed: no released order to favorite`);+ }+ await insertRow(ctx, "salesOrderFavorite", {+ salesOrderId: need(ctx.refs.documents, firstReleased.order.ref),+ userId+ });}diff --git a/packages/database/src/datasets/tiers/05-purchasing.ts b/packages/database/src/datasets/tiers/05-purchasing.tsindex 695586087b..1b943b7ad9 100644--- a/packages/database/src/datasets/tiers/05-purchasing.ts+++ b/packages/database/src/datasets/tiers/05-purchasing.ts@@ -1,5 +1,6 @@import { resolveDate, resolveTimestamp } from "../dates.ts";-import { insertId, insertRow, need, nextSequence, RICH } from "../sql.ts";+import { seedReturnCredit } from "../helpers/return-credit.ts";+import { insertId, insertRow, need, nextSequence, one, RICH } from "../sql.ts";import type { Ctx } from "../types.ts";// Supplier quotes come back shortly before the RFQ closes and stay open well@@ -10,7 +11,7 @@ const SUPPLIER_QUOTE_EXPIRATION_TIME_OF_DAY = "23:59:59";export async function runTier5(ctx: Ctx): Promise<void> {const data = ctx.dataset.purchasing;- const { companyId, locationId } = ctx;+ const { companyId, userId, locationId } = ctx;const plantId = ctx.refs.locations.Plant ?? locationId;const shippingMethodId = need(ctx.refs.shippingMethods,@@ -18,6 +19,11 @@ export async function runTier5(ctx: Ctx): Promise<void> {);const paymentTermId = ctx.refs.misc.paymentTermId;+ // The status-history trail hangs off the first direct PO whose receipt+ // posted — the one order per dataset with a full approval-to-dock story.+ let historyPoId: string | null = null;+ let historyPoBase: number | null = null;+// ── Purchase orders written directly, each with its own receipt/invoice ────for (const spec of data.purchaseOrders) {if (spec.source !== "direct") continue;@@ -34,7 +40,15 @@ export async function runTier5(ctx: Ctx): Promise<void> {status: spec.status,supplierId,supplierInteractionId: interactionId,- orderDate: resolveDate(ctx.anchor, spec.orderDateOffset)+ // exchangeRateUpdatedAt = the order date, as insertPurchaseOrder stamps it.+ currencyCode: spec.currencyCode,+ exchangeRate: spec.exchangeRate,+ exchangeRateUpdatedAt:+ spec.exchangeRate === undefined+ ? undefined+ : resolveTimestamp(ctx.anchor, spec.orderDateOffset, "08:00:00"),+ orderDate: resolveDate(ctx.anchor, spec.orderDateOffset),+ assignee: spec.assignee === "self" ? userId : undefined});await insertRow(ctx, "purchaseOrderDelivery", {id: poId,@@ -59,14 +73,33 @@ export async function runTier5(ctx: Ctx): Promise<void> {description: item.name,purchaseQuantity: line.purchaseQuantity,supplierUnitPrice: line.supplierUnitPrice,+ exchangeRate: spec.exchangeRate,inventoryUnitOfMeasureCode: "EA",purchaseUnitOfMeasureCode: "EA",locationId: plantId});}- if (spec.ref) ctx.refs.documents[spec.ref] = poId;+ if (spec.ref) {+ ctx.refs.documents[spec.ref] = poId;+ // PO lines by (order, item), so an NCR can name its line (tier 07).+ for (const [item, lineId] of Object.entries(lineIdByItem)) {+ ctx.refs.documents[`poline:${spec.ref}:${item}`] = lineId;+ }+ }+ // Draft/Voided are header+lines only; Posted mirrors post-receipt's+ // PO branch: one Purchase Receipt ledger row per line into its toShelf. A+ // batch-tracked line mints its lot as update_receipt_line_batch_tracking does.if (spec.receipt) {+ const posted = spec.receipt.status === "Posted";+ if (posted && spec.receipt.postedOffset === undefined) {+ throw new Error(+ `Seed: receipt "${spec.receipt.ref}" is Posted but has no postedOffset`+ );+ }+ const postingDate = posted+ ? resolveDate(ctx.anchor, spec.receipt.postedOffset ?? 0)+ : undefined;const receiptReadableId = await nextSequence(ctx, "receipt");const receiptId = await insertId(ctx, "receipt", {receiptId: receiptReadableId,@@ -75,11 +108,22 @@ export async function runTier5(ctx: Ctx): Promise<void> {sourceDocument: "Purchase Order",sourceDocumentId: poId,sourceDocumentReadableId: poReadableId,- supplierId+ supplierId,+ postingDate,+ postedBy: posted ? userId : undefined});for (const line of spec.receipt.lines) {const item = need(ctx.refs.items, line.item);- await insertId(ctx, "receiptLine", {+ const shelfId =+ line.toShelf === undefined+ ? undefined+ : need(ctx.refs.shelves, line.toShelf);+ if (posted && line.receivedQuantity > 0 && shelfId === undefined) {+ throw new Error(+ `Seed: posted receipt "${spec.receipt.ref}" line "${line.item}" has no toShelf`+ );+ }+ const receiptLineId = await insertId(ctx, "receiptLine", {receiptId,lineId: need(lineIdByItem, line.item),itemId: item.id,@@ -87,16 +131,69 @@ export async function runTier5(ctx: Ctx): Promise<void> {outstandingQuantity: line.outstandingQuantity,receivedQuantity: line.receivedQuantity,locationId: plantId,+ storageUnitId: shelfId,unitOfMeasure: "EA",unitPrice: line.unitPrice,requiresBatchTracking: line.requiresBatchTracking});+ // Receipt lines by (receipt, item) — quality inspects one (tier 07).+ ctx.refs.documents[`rline:${spec.receipt.ref}:${line.item}`] =+ receiptLineId;+ if (posted && line.receivedQuantity > 0) {+ let trackedEntityId: string | undefined;+ if (line.requiresBatchTracking) {+ if (line.lotNumber === undefined) {+ throw new Error(+ `Seed: posted batch line "${line.item}" on receipt "${spec.receipt.ref}" has no lotNumber`+ );+ }+ trackedEntityId = await insertId(ctx, "trackedEntity", {+ quantity: line.receivedQuantity,+ status: "Available",+ sourceDocument: "Item",+ sourceDocumentId: item.id,+ sourceDocumentReadableId: item.readableId,+ readableId: line.lotNumber,+ itemId: item.id,+ attributes: JSON.stringify({+ "Receipt Line": receiptLineId,+ Receipt: receiptId,+ Supplier: supplierId+ }),+ expirationDate:+ line.lotExpiresOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, line.lotExpiresOffset),+ updatedBy: userId+ });+ ctx.refs.misc[`te:${line.lotNumber}`] = trackedEntityId;+ }+ await insertRow(ctx, "itemLedger", {+ entryType: "Positive Adjmt.",+ documentType: "Purchase Receipt",+ documentId: receiptId,+ itemId: item.id,+ locationId: plantId,+ storageUnitId: shelfId,+ quantity: line.receivedQuantity,+ trackedEntityId,+ postingDate,+ companyId,+ createdBy: userId+ });+ }}ctx.refs.documents[spec.receipt.ref] = receiptId;++ if (posted && historyPoId === null) {+ historyPoId = poId;+ historyPoBase = spec.orderDateOffset;+ }}if (spec.invoice) {const invoiceReadableId = await nextSequence(ctx, "purchaseInvoice");+ const dateIssued = resolveDate(ctx.anchor, spec.invoice.dateIssuedOffset);const invoiceId = await insertId(ctx, "purchaseInvoice", {invoiceId: invoiceReadableId,status: spec.invoice.status,@@ -106,8 +203,18 @@ export async function runTier5(ctx: Ctx): Promise<void> {paymentTermId,subtotal: spec.invoice.subtotal,totalAmount: spec.invoice.totalAmount,- dateIssued: resolveDate(ctx.anchor, spec.invoice.dateIssuedOffset)+ dateIssued,+ // post-purchase-invoice stamps it; the AP aging and open-balance RPCs filter on it.+ postingDate: spec.invoice.status === "Draft" ? undefined : dateIssued,+ dateDue:+ spec.invoice.dueDateOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, spec.invoice.dueDateOffset)});+ // Payments settle Paid / Partially Paid invoices by this key.+ if (spec.invoice.key !== undefined) {+ ctx.refs.misc[`pinv:${spec.invoice.key}`] = invoiceId;+ }await insertRow(ctx, "purchaseInvoiceDelivery", {id: invoiceId,locationId: plantId,@@ -120,6 +227,7 @@ export async function runTier5(ctx: Ctx): Promise<void> {invoiceId,invoiceLineType: "Part",purchaseOrderId: poId,+ purchaseOrderLineId: need(lineIdByItem, line.item),itemId: item.id,description: item.name,quantity: line.quantity,@@ -139,8 +247,15 @@ export async function runTier5(ctx: Ctx): Promise<void> {rfqId: rfqReadableId,status: data.rfqHeader.status,employeeId: ctx.userId,+ assignee: data.rfqHeader.assignee === "self" ? userId : undefined,locationId: plantId,rfqDate: resolveDate(ctx.anchor, data.rfqHeader.rfqDateOffset),+ // The KPI chart and list sort on createdAt; a seed-time stamp is one spike.+ createdAt: resolveTimestamp(+ ctx.anchor,+ data.rfqHeader.rfqDateOffset,+ "09:00:00"+ ),expirationDate: resolveDate(ctx.anchor, data.rfqHeader.expirationOffset),notes: RICH(data.rfqHeader.notes),internalNotes: RICH(data.rfqHeader.internalNotes)@@ -165,7 +280,8 @@ export async function runTier5(ctx: Ctx): Promise<void> {// ── One Active supplier quote per RFQ supplier, linked back to the RFQ ────let winningInteractionId = "";for (const spec of data.rfqQuotes) {- ctx.log(`supplier quote — ${spec.supplier} (Active)`);+ const quoteStatus = spec.status ?? "Active";+ ctx.log(`supplier quote — ${spec.supplier} (${quoteStatus})`);const supplierId = need(ctx.refs.suppliers, spec.supplier);await insertId(ctx, "purchasingRfqSupplier", {@@ -180,13 +296,19 @@ export async function runTier5(ctx: Ctx): Promise<void> {const quoteId = await insertId(ctx, "supplierQuote", {supplierQuoteId: quoteReadableId,supplierQuoteType: "Purchase",- status: "Active",+ status: quoteStatus,supplierId,supplierContactId: need(ctx.refs.contacts, `sc:${spec.supplier}`),supplierLocationId: need(ctx.refs.misc, `sloc:${spec.supplier}`),supplierReference: spec.supplierReference,supplierInteractionId: interactionId,+ assignee: spec.assignee === "self" ? userId : undefined,quotedDate: resolveDate(ctx.anchor, SUPPLIER_QUOTE_QUOTED_OFFSET),+ createdAt: resolveTimestamp(+ ctx.anchor,+ SUPPLIER_QUOTE_QUOTED_OFFSET,+ "10:00:00"+ ),expirationDate: resolveDate(ctx.anchor, SUPPLIER_QUOTE_EXPIRATION_OFFSET),currencyCode: "USD",exchangeRate: 1,@@ -259,6 +381,63 @@ export async function runTier5(ctx: Ctx): Promise<void> {if (spec.key === data.rfqWinningQuote) winningInteractionId = interactionId;}+ // Same shape as a quote created from the supplier screen. No externalLink —+ // only finalize mints one, and none of these were finalized.+ for (const spec of data.standaloneSupplierQuotes) {+ ctx.log(`supplier quote — ${spec.supplier} (${spec.status}, standalone)`);+ const supplierId = need(ctx.refs.suppliers, spec.supplier);+ const interactionId = await insertId(ctx, "supplierInteraction", {+ supplierId+ });+ const quoteReadableId = await nextSequence(ctx, "supplierQuote");+ const quoteId = await insertId(ctx, "supplierQuote", {+ supplierQuoteId: quoteReadableId,+ supplierQuoteType: "Purchase",+ status: spec.status,+ supplierId,+ supplierContactId: need(ctx.refs.contacts, `sc:${spec.supplier}`),+ supplierLocationId: need(ctx.refs.misc, `sloc:${spec.supplier}`),+ supplierReference: spec.supplierReference,+ supplierInteractionId: interactionId,+ assignee: spec.assignee === "self" ? userId : undefined,+ quotedDate: resolveDate(ctx.anchor, spec.quotedOffset),+ createdAt: resolveTimestamp(ctx.anchor, spec.quotedOffset, "10:00:00"),+ expirationDate: resolveDate(ctx.anchor, spec.expirationOffset),+ currencyCode: "USD",+ exchangeRate: 1+ });++ 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: line.prices.map((price) => price.quantity),+ purchaseUnitOfMeasureCode: "EA",+ inventoryUnitOfMeasureCode: "EA",+ conversionFactor: 1,+ sortOrder: quoteLineSort+++ });+ for (const price of line.prices) {+ await insertRow(ctx, "supplierQuoteLinePrice", {+ supplierQuoteId: quoteId,+ supplierQuoteLineId: quoteLineId,+ quantity: price.quantity,+ supplierUnitPrice: price.unitPrice,+ leadTime: price.leadTime,+ exchangeRate: 1,+ supplierShippingCost: 0,+ supplierTaxAmount: 0+ });+ }+ }+ ctx.refs.documents[`sq:${spec.key}`] = quoteId;+ }+// ── Purchase orders converted from the winning quote ──────────────────────// 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@@ -332,4 +511,238 @@ export async function runTier5(ctx: Ctx): Promise<void> {});ctx.refs.documents[`po:sq-${data.rfqWinningQuote}`] = poId;}++ // Lines + suppliers only; neither was ever sent. Cancel clears the assignee.+ for (const spec of data.lifecycleRfqs) {+ ctx.log(`purchasing RFQ — ${spec.status}`);+ const lifecycleRfq = await insertId(ctx, "purchasingRfq", {+ rfqId: await nextSequence(ctx, "purchasingRfq"),+ status: spec.status,+ employeeId: ctx.userId,+ assignee: spec.status === "Draft" ? ctx.userId : null,+ locationId: plantId,+ rfqDate: resolveDate(ctx.anchor, spec.rfqDateOffset),+ createdAt: resolveTimestamp(ctx.anchor, spec.rfqDateOffset, "09:00:00"),+ expirationDate: resolveDate(ctx.anchor, spec.expirationOffset),+ notes: RICH(spec.notes),+ internalNotes: RICH(spec.internalNotes)+ });+ ctx.refs.documents[spec.ref] = lifecycleRfq;+ let order = 1;+ for (const line of spec.lines) {+ await insertId(ctx, "purchasingRfqLine", {+ purchasingRfqId: lifecycleRfq,+ itemId: need(ctx.refs.items, line.item).id,+ description: line.description,+ quantity: spec.quantities,+ purchaseUnitOfMeasureCode: "EA",+ inventoryUnitOfMeasureCode: "EA",+ conversionFactor: 1,+ order: order+++ });+ }+ for (const supplier of spec.suppliers) {+ await insertId(ctx, "purchasingRfqSupplier", {+ purchasingRfqId: lifecycleRfq,+ supplierId: need(ctx.refs.suppliers, supplier)+ });+ }+ }++ // Completed mirrors post-shipment's Purchase Return Order branch: a Posted+ // shipment plus one ledger row per line out of its fromShelf.+ if (data.purchaseReturns.length > 0) {+ ctx.log("purchase returns");+ for (const spec of data.purchaseReturns) {+ ctx.log(` return ${spec.key} — ${spec.status}`);+ const supplierId = need(ctx.refs.suppliers, spec.supplier);+ const completed = spec.status === "Completed";+ const orderDate = resolveDate(ctx.anchor, spec.dateOffset);+ const returnReadableId = await nextSequence(ctx, "purchaseReturnOrder");+ const returnId = await insertId(ctx, "purchaseReturnOrder", {+ purchaseReturnOrderId: returnReadableId,+ status: spec.status,+ supplierId,+ locationId: plantId,+ currencyCode: "USD",+ orderDate+ });++ const lineIds: string[] = [];+ for (const [index, line] of spec.lines.entries()) {+ const item = need(ctx.refs.items, line.item);+ const lineId = await insertId(ctx, "purchaseReturnOrderLine", {+ purchaseReturnOrderId: returnId,+ itemId: item.id,+ lineNumber: index + 1,+ quantity: line.quantity,+ quantityShipped: completed ? line.quantity : 0,+ unitOfMeasureCode: "EA",+ unitPrice: line.unitPrice+ });+ lineIds.push(lineId);+ ctx.refs.documents[`pretline:${spec.key}:${index + 1}`] = lineId;+ }++ if (completed) {+ const shipmentReadableId = await nextSequence(ctx, "shipment");+ const shipmentId = await insertId(ctx, "shipment", {+ shipmentId: shipmentReadableId,+ status: "Posted",+ locationId: plantId,+ sourceDocument: "Purchase Return Order",+ sourceDocumentId: returnId,+ sourceDocumentReadableId: returnReadableId,+ shippingMethodId,+ supplierId,+ postingDate: orderDate,+ postedBy: userId+ });+ for (const [index, line] of spec.lines.entries()) {+ const item = need(ctx.refs.items, line.item);+ if (line.fromShelf === undefined) {+ throw new Error(+ `Seed: completed return "${spec.key}" line "${line.item}" has no fromShelf`+ );+ }+ const shelfId = need(ctx.refs.shelves, line.fromShelf);+ await insertId(ctx, "shipmentLine", {+ shipmentId,+ lineId: lineIds[index],+ itemId: item.id,+ orderQuantity: line.quantity,+ outstandingQuantity: 0,+ shippedQuantity: line.quantity,+ locationId: plantId,+ storageUnitId: shelfId,+ unitOfMeasure: "EA",+ unitPrice: line.unitPrice+ });+ await insertRow(ctx, "itemLedger", {+ entryType: "Negative Adjmt.",+ documentType: "Purchase Return Shipment",+ documentId: shipmentId,+ itemId: item.id,+ locationId: plantId,+ storageUnitId: shelfId,+ quantity: -line.quantity,+ postingDate: orderDate,+ companyId,+ createdBy: userId+ });+ }+ ctx.refs.documents[`pret-shipment:${spec.key}`] = shipmentId;+ }++ if (spec.credit) {+ ctx.log(` return ${spec.key} — debit memo (${spec.credit.status})`);+ await seedReturnCredit(ctx, {+ spec: spec.credit,+ kind: "purchase",+ partyId: supplierId,+ returnOrderId: returnId+ });+ }++ ctx.refs.documents[`pret:${spec.key}`] = returnId;+ }+ }++ await seedApprovals(ctx);++ for (const spec of data.supplierBankAccounts) {+ await insertRow(ctx, "supplierBankAccount", {+ supplierId: need(ctx.refs.suppliers, spec.supplier, "supplier"),+ name: spec.name,+ accountHolderName: spec.accountHolderName,+ bankName: spec.bankName,+ countryCode: spec.countryCode,+ currencyCode: spec.currencyCode,+ accountNumber: spec.accountNumber,+ bankCode: spec.bankCode,+ swiftBic: spec.swiftBic,+ isPrimary: spec.isPrimary,+ active: true+ });+ }++ // Timestamps are staggered so the timeline reads as a real trail.+ if (historyPoId !== null && historyPoBase !== null) {+ ctx.log("purchase order status history");+ const trail: Array<[string, number, string]> = [+ ["Draft", historyPoBase, "08:52:00"],+ ["To Review", historyPoBase + 1, "14:18:00"],+ ["To Receive", historyPoBase + 3, "09:37:00"]+ ];+ for (const [status, offset, timeOfDay] of trail) {+ await insertRow(ctx, "purchaseOrderStatusHistory", {+ purchaseOrderId: historyPoId,+ status,+ createdAt: resolveTimestamp(ctx.anchor, offset, timeOfDay)+ });+ }+ }+}++// Pending requests in the shape PO finalize and supplier "Request approval" leave;+// "Needs my approval", the PO banner and the supplier Approval tab read them.+async function seedApprovals(ctx: Ctx): Promise<void> {+ const data = ctx.dataset.purchasing;+ ctx.log("approval rules + requests");+ const admin = await one<{ id: string }>(+ ctx.client,+ `SELECT g.id FROM "group" g+ JOIN "employeeType" et ON et.id = g.id AND et."companyId" = g."companyId"+ WHERE g."companyId" = $1 AND g."isEmployeeTypeGroup" AND et."systemType" = 'Admin'+ ORDER BY et."createdAt" LIMIT 1`,+ [ctx.companyId]+ );+ for (const rule of data.approvalRules) {+ await insertRow(ctx, "approvalRule", {+ documentType: rule.documentType,+ enabled: true,+ approverGroupIds: [admin.id],+ defaultApproverId: ctx.userId,+ lowerBoundAmount: rule.lowerBoundAmount,+ escalationDays: rule.escalationDays+ });+ }++ for (const request of data.approvalRequests) {+ const requestedAt = resolveTimestamp(+ ctx.anchor,+ request.requestedOffset,+ "15:00:00"+ );+ if ("purchaseOrder" in request) {+ const purchaseOrderId = need(+ ctx.refs.documents,+ request.purchaseOrder,+ "purchase order"+ );+ const order = await one<{ orderTotal: string }>(+ ctx.client,+ `SELECT "orderTotal" FROM "purchaseOrders" WHERE id = $1 AND "companyId" = $2`,+ [purchaseOrderId, ctx.companyId]+ );+ await insertRow(ctx, "approvalRequest", {+ documentType: "purchaseOrder",+ documentId: purchaseOrderId,+ status: "Pending",+ amount: order.orderTotal,+ requestedBy: ctx.userId,+ requestedAt,+ createdAt: requestedAt+ });+ } else {+ await insertRow(ctx, "approvalRequest", {+ documentType: "supplier",+ documentId: need(ctx.refs.suppliers, request.supplier, "supplier"),+ status: "Pending",+ requestedBy: ctx.userId,+ requestedAt,+ createdAt: requestedAt+ });+ }+ }}diff --git a/packages/database/src/datasets/tiers/06-production.ts b/packages/database/src/datasets/tiers/06-production.tsindex ce5d538121..b451785137 100644--- a/packages/database/src/datasets/tiers/06-production.ts+++ b/packages/database/src/datasets/tiers/06-production.ts@@ -1,61 +1,62 @@+import { Time, toCalendarDateTime } from "@internationalized/date";import { resolveDate, resolveTimestamp } from "../dates.ts";+import { bootstrapIdByName } from "../helpers/bootstrap-lookup.ts";import {copyMethodToJob,type JobOperationStatus-} from "../helpers/job-method.ts";-import { insertId, insertRow, need, nextSequence, rows } from "../sql.ts";-import type { AssemblySpec, Ctx, ProductionData } from "../types.ts";--/**- * Seeds an animated assembly instruction against a CAD model that ships with the- * app. The `_templates/` paths are resolved by getDatasetAssetUrl rather than the- * storage proxy, so there are no objects to upload and nothing to clean up — the- * modelUpload row is a pointer at a bundled file, and the assembler never runs.- */-async function seedAssembly(ctx: Ctx, spec: AssemblySpec): Promise<void> {- const { industryId } = ctx.dataset;- if (!industryId) return;-- const base = `_templates/${industryId}/models/${spec.model}`;- const modelUploadId = await insertId(ctx, "modelUpload", {- name: `${spec.name}.glb`,- // Already converted, so the source and the render artifact are the same file.- modelPath: `${base}.glb`,- glbPath: `${base}.glb`,- graphPath: `${base}.graph.json`,- componentCount: spec.componentCount,- processingStatus: "Success",- processedAt: resolveTimestamp(ctx.anchor, 0, "09:00")- });+} from "../helpers/method-copy.ts";+import {+ insertId,+ insertRow,+ maybeOne,+ need,+ nextSequence,+ rows+} from "../sql.ts";+import type {+ Ctx,+ DayOffset,+ JobSpec,+ PickingListSpec,+ ProductionData+} from "../types.ts";- const itemId = spec.item ? ctx.refs.items[spec.item]?.id : undefined;- const instructionId = await insertId(ctx, "assemblyInstruction", {- name: spec.name,- modelUploadId,- itemId: itemId ?? null,- // Draft, not Published: Published makes the 3D assembly editor read-only.- status: "Draft",- version: 1,- publishedAt: null- });+type RootOperation = {+ id: string;+ workCenterId: string | null;+ processId: string;+ order: number;+};- let sortOrder = 1;- for (const step of spec.steps) {- await insertRow(ctx, "assemblyInstructionStep", {- assemblyInstructionId: instructionId,- title: step.title,- instructionText: step.instruction ?? step.title,- componentNodeIds: step.componentNodeIds,- sortOrder: sortOrder++- });- }+// Specs address root ops by 1-based position, not raw order (10/20/30 = 1/2/3).+async function rootOperations(+ ctx: Ctx,+ jobId: string+): Promise<RootOperation[]> {+ return rows<RootOperation>(+ ctx.client,+ `SELECT jo.id, jo."workCenterId", jo."processId", 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"`,+ [jobId, ctx.companyId]+ );+}- if (itemId) {- await ctx.client.query(- `UPDATE "item" SET "modelUploadId" = $1 WHERE "id" = $2`,- [modelUploadId, itemId]+function rootOperationAt(+ operations: RootOperation[],+ position: number,+ what: string+): RootOperation {+ const operation = operations[position - 1];+ if (!operation) {+ throw new Error(+ `Seed: ${what} names root operation position ${position}, but the job has only ${operations.length}`);}+ return operation;}// A job's operations open in the state its own status implies — a Draft job's@@ -82,11 +83,6 @@ export async function runTier6(ctx: Ctx): Promise<void> {const { locationId } = ctx;const plantId = ctx.refs.locations.Plant ?? locationId;- if (data.assembly) {- ctx.log(`assembly ${data.assembly.name}`);- await seedAssembly(ctx, data.assembly);- }-for (const spec of data.jobs) {ctx.log(`job ${spec.item} — ${spec.status}`);const item = need(ctx.refs.items, spec.item);@@ -100,11 +96,16 @@ export async function runTier6(ctx: Ctx): Promise<void> {quantity: spec.quantity,quantityComplete: spec.quantityComplete ?? 0,scrapQuantity: 0,- customerId: need(ctx.refs.customers, spec.customer),- salesOrderId: need(ctx.refs.documents, spec.salesOrder),- salesOrderLineId: need(ctx.refs.documents, spec.salesOrderLine),- deadlineType: "Hard Deadline",- dueDate: resolveDate(ctx.anchor, spec.dueDateOffset),+ customerId: optionalRef(ctx.refs.customers, spec.customer),+ salesOrderId: optionalRef(ctx.refs.documents, spec.salesOrder),+ salesOrderLineId: optionalRef(ctx.refs.documents, spec.salesOrderLine),+ priority: spec.priority,+ assignee: spec.assignee === "self" ? ctx.userId : null,+ deadlineType: spec.deadlineType ?? "Hard Deadline",+ dueDate:+ spec.dueDateOffset === undefined+ ? null+ : resolveDate(ctx.anchor, spec.dueDateOffset),releasedDate:spec.releasedDateOffset === undefined? null@@ -129,6 +130,9 @@ export async function runTier6(ctx: Ctx): Promise<void> {` method: ${copied.operations} operations, ${copied.materials} materials, ${copied.levels} levels`);+ await applyOperationDepth(ctx, id, spec);+ if (spec.loggedTime) await seedLoggedTime(ctx, id, spec);+// 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.@@ -142,8 +146,102 @@ export async function runTier6(ctx: Ctx): Promise<void> {);}+ // Job refs only exist from here on, so this favorite isn't tier 04's.+ // jobFavorite has no companyId/createdBy, so audit injection no-ops.+ await insertRow(ctx, "jobFavorite", {+ jobId: need(ctx.refs.documents, `job:${data.eventsJobKey}`),+ userId: ctx.userId+ });+await seedProductionEvents(ctx, data);+ await seedOpenEvent(ctx, data);+ await seedStepRecords(ctx);+ await seedBatch(ctx, data);+ await seedRework(ctx, data);await seedGenealogy(ctx, data);+ await seedPickingLists(ctx, data);+}++async function applyOperationDepth(+ ctx: Ctx,+ jobId: string,+ spec: JobSpec+): Promise<void> {+ if (!spec.operationOverrides && !spec.quantities && !spec.operationNotes) {+ return;+ }+ const operations = await rootOperations(ctx, jobId);++ for (const override of spec.operationOverrides ?? []) {+ const operation = rootOperationAt(+ operations,+ override.order,+ `job "${spec.key}" operationOverrides`+ );+ if (override.status) {+ await ctx.client.query(+ `UPDATE "jobOperation" SET status = $1 WHERE id = $2 AND "companyId" = $3`,+ [override.status, operation.id, ctx.companyId]+ );+ }+ if (override.assignee === "self") {+ await ctx.client.query(+ `UPDATE "jobOperation" SET assignee = $1 WHERE id = $2 AND "companyId" = $3`,+ [ctx.userId, operation.id, ctx.companyId]+ );+ }+ if (override.running) {+ if (override.status !== "In Progress" || !operation.workCenterId) {+ throw new Error(+ `Seed: job "${spec.key}" operation ${override.order} is running, so it must be "In Progress" at a work center`+ );+ }+ // MES's Active list, the work-center display and the board's running dot read this.+ await insertRow(ctx, "productionEvent", {+ jobOperationId: operation.id,+ type: override.running.type,+ startTime: resolveTimestamp(+ ctx.anchor,+ 0,+ override.running.startTimeOfDay+ ),+ endTime: null,+ employeeId: ctx.userId,+ workCenterId: operation.workCenterId,+ postedToGL: false+ });+ }+ }++ for (const quantity of spec.quantities ?? []) {+ const operation = rootOperationAt(+ operations,+ quantity.order,+ `job "${spec.key}" quantities`+ );+ await insertId(ctx, "productionQuantity", {+ jobOperationId: operation.id,+ type: quantity.type,+ quantity: quantity.quantity,+ scrapReasonId:+ quantity.scrapReason === undefined+ ? null+ : await bootstrapIdByName(ctx, "scrapReason", quantity.scrapReason)+ });+ }++ for (const note of spec.operationNotes ?? []) {+ const operation = rootOperationAt(+ operations,+ note.order,+ `job "${spec.key}" operationNotes`+ );+ // jobOperationNote.note is plain text (the MES operation chat), not TipTap.+ await insertRow(ctx, "jobOperationNote", {+ jobOperationId: operation.id,+ note: note.note+ });+ }}/**@@ -156,22 +254,9 @@ async function seedProductionEvents(data: ProductionData): Promise<void> {const jobId = need(ctx.refs.documents, `job:${data.eventsJobKey}`);+ const eventsJobSpec = data.jobs.find((job) => job.key === data.eventsJobKey);- 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]- );+ const operations = (await rootOperations(ctx, jobId)).slice(0, 2);if (operations.length === 0) return;if (data.shifts.length === 0) return;@@ -201,11 +286,402 @@ async function seedProductionEvents(});}- await insertId(ctx, "productionQuantity", {- jobOperationId: operation.id,- type: "Production",- quantity: 1+ // A job that authors its own productionQuantity rows (JobSpec.quantities)+ // replaces this legacy Production-1 default entirely.+ if (!eventsJobSpec?.quantities) {+ await insertId(ctx, "productionQuantity", {+ jobOperationId: operation.id,+ type: "Production",+ quantity: 1+ });+ }+ }+}++// Without an open event (no endTime) MES's active-operation UI renders nothing.+async function seedOpenEvent(ctx: Ctx, data: ProductionData): Promise<void> {+ const jobId = need(ctx.refs.documents, `job:${data.eventsJobKey}`);+ const operations = await rootOperations(ctx, jobId);+ const operation = rootOperationAt(+ operations,+ data.openEvent.operationOrder,+ "production.openEvent"+ );++ ctx.log("open production event");+ await insertRow(ctx, "productionEvent", {+ jobOperationId: operation.id,+ type: "Setup",+ startTime: resolveTimestamp(ctx.anchor, 0, "08:00:00"),+ endTime: null,+ employeeId: ctx.userId,+ workCenterId: operation.workCenterId,+ postedToGL: false+ });+}++// Mirrors batch-operations' "create" with release.+async function seedBatch(ctx: Ctx, data: ProductionData): Promise<void> {+ const members: RootOperation[] = [];+ for (const member of data.batch.members) {+ const jobId = need(ctx.refs.documents, `job:${member.job}`);+ members.push(+ rootOperationAt(+ await rootOperations(ctx, jobId),+ member.order,+ `production.batch member "${member.job}"`+ )+ );+ }+ const processId = members[0]?.processId;+ if (!processId || members.some((op) => op.processId !== processId)) {+ throw new Error(`Seed: production.batch members must share one process`);+ }+ const workCenters = new Set(members.map((op) => op.workCenterId));++ ctx.log(`job operation batch — ${members.length} members`);+ await ctx.client.query(+ `UPDATE process SET batchable = true WHERE id = $1 AND "companyId" = $2`,+ [processId, ctx.companyId]+ );+ const batchId = await insertId(ctx, "jobOperationBatch", {+ readableId: await nextSequence(ctx, "jobOperationBatch"),+ processId,+ workCenterId: workCenters.size === 1 ? [...workCenters][0] : null,+ locationId: ctx.refs.locations.Plant ?? ctx.locationId,+ status: "Active",+ mergeOutput: false+ });+ await ctx.client.query(+ `UPDATE "jobOperation" SET "jobOperationBatchId" = $1, status = 'In Progress'+ WHERE id = ANY($2) AND "companyId" = $3`,+ [batchId, members.map((op) => op.id), ctx.companyId]+ );+ // The batch timer: one event tagged with the batch, on the operation the+ // operator opened (batch-operations slices it per member at completion).+ const lead = members[0]!;+ if (!lead.workCenterId) {+ throw new Error(`Seed: production.batch's first member has no work center`);+ }+ await insertRow(ctx, "productionEvent", {+ jobOperationId: lead.id,+ jobOperationBatchId: batchId,+ type: data.batch.running.type,+ startTime: resolveTimestamp(+ ctx.anchor,+ 0,+ data.batch.running.startTimeOfDay+ ),+ endTime: null,+ employeeId: ctx.userId,+ workCenterId: lead.workCenterId,+ postedToGL: false+ });+}++function optionalRef(+ map: Record<string, string>,+ key: string | undefined+): string | null {+ return key === undefined ? null : need(map, key);+}++// makeDurations (ERP utils/duration.ts): milliseconds one time/unit pair adds.+const MS_PER_PIECE: Record<string, number> = {+ "Hours/Piece": 3_600_000,+ "Hours/100 Pieces": 36_000,+ "Hours/1000 Pieces": 3_600,+ "Minutes/Piece": 60_000,+ "Minutes/100 Pieces": 600,+ "Minutes/1000 Pieces": 60,+ "Seconds/Piece": 1_000+};+function estimateMs(time: number, unit: string, quantity: number): number {+ switch (unit) {+ case "Total Hours":+ return time * 3_600_000;+ case "Total Minutes":+ return time * 60_000;+ case "Pieces/Hour":+ return time > 0 ? (quantity / time) * 3_600_000 : 0;+ case "Pieces/Minute":+ return time > 0 ? (quantity / time) * 60_000 : 0;+ default:+ return time * quantity * (MS_PER_PIECE[unit] ?? 0);+ }+}++async function seedLoggedTime(+ ctx: Ctx,+ jobId: string,+ spec: JobSpec+): Promise<void> {+ const logged = spec.loggedTime;+ if (!logged) return;+ if (spec.completedDateOffset === undefined) {+ throw new Error(+ `Seed: job "${spec.key}" logs time but has no completedDate`+ );+ }+ const operations = await rows<{+ id: string;+ workCenterId: string;+ setupTime: string;+ setupUnit: string;+ laborTime: string;+ laborUnit: string;+ machineTime: string;+ machineUnit: string;+ operationQuantity: string | null;+ }>(+ ctx.client,+ `SELECT jo.id, jo."workCenterId", jo."setupTime", jo."setupUnit"::text,+ jo."laborTime", jo."laborUnit"::text, jo."machineTime",+ jo."machineUnit"::text, jo."operationQuantity"+ FROM "jobOperation" jo+ JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"+ WHERE jo."jobId" = $1 AND jo."companyId" = $2 AND jo."workCenterId" IS NOT NULL+ ORDER BY (jmm."parentMaterialId" IS NULL), jmm.id, jo."order"`,+ [jobId, ctx.companyId]+ );++ ctx.log(` logged time on ${operations.length} operations`);+ const at = (offset: DayOffset) =>+ toCalendarDateTime(ctx.anchor.add({ days: offset }), new Time(7));+ const stamp = (moment: ReturnType<typeof at>) => `${moment.toString()}Z`;+ let cursor = at(logged.startOffset);+ for (const op of operations) {+ const quantity = Number(op.operationQuantity ?? 0);+ const seconds = (time: string, unit: string) =>+ Math.round(+ (estimateMs(Number(time), unit, quantity) * logged.efficiency) / 1000+ );+ const setup = seconds(op.setupTime, op.setupUnit);+ const labor = seconds(op.laborTime, op.laborUnit);+ const machine = seconds(op.machineTime, op.machineUnit);+ const runStart = cursor.add({ seconds: setup });+ const events: Array<[string, typeof cursor, number]> = [+ ["Setup", cursor, setup],+ ["Labor", runStart, labor],+ ["Machine", runStart, machine]+ ];+ for (const [type, start, duration] of events) {+ if (duration <= 0) continue;+ await insertRow(ctx, "productionEvent", {+ jobOperationId: op.id,+ type,+ startTime: stamp(start),+ endTime: stamp(start.add({ seconds: duration })),+ employeeId: ctx.userId,+ workCenterId: op.workCenterId,+ postedToGL: false+ });+ }+ cursor = runStart.add({ seconds: Math.max(labor, machine) });+ if (quantity > 0) {+ await insertId(ctx, "productionQuantity", {+ jobOperationId: op.id,+ type: "Production",+ quantity,+ createdAt: stamp(cursor)+ });+ }+ }++ // completedDate is midnight of its day; the work has to be done by then.+ if (cursor.compare(at(spec.completedDateOffset).set({ hour: 0 })) > 0) {+ throw new Error(+ `Seed: job "${spec.key}" logged time runs to ${stamp(cursor)}, past its completedDate — start it earlier`+ );+ }+}++// File steps need an upload, so they stay empty.+async function seedStepRecords(ctx: Ctx): Promise<void> {+ const steps = await rows<{+ id: string;+ type: string;+ minValue: string | null;+ maxValue: string | null;+ listValues: string[] | null;+ recordedAt: string | null;+ }>(+ ctx.client,+ `SELECT s.id, s.type::text, s."minValue", s."maxValue", s."listValues",+ to_char(COALESCE(+ (SELECT max(pe."endTime") FROM "productionEvent" pe+ WHERE pe."jobOperationId" = jo.id AND pe."companyId" = $1),+ j."completedDate", j."releasedDate"+ ) AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS "recordedAt"+ FROM "jobOperationStep" s+ JOIN "jobOperation" jo ON jo.id = s."operationId" AND jo."companyId" = $1+ JOIN job j ON j.id = jo."jobId" AND j."companyId" = $1+ WHERE s."companyId" = $1 AND jo.status = 'Done' AND s.type <> 'File'+ ORDER BY jo.id, s."sortOrder"`,+ [ctx.companyId]+ );+ if (steps.length === 0) return;++ ctx.log(`step records — ${steps.length}`);+ for (const step of steps) {+ const record: Record<string, unknown> = {+ jobOperationStepId: step.id,+ index: 0+ };+ switch (step.type) {+ case "Measurement": {+ const min = step.minValue === null ? null : Number(step.minValue);+ const max = step.maxValue === null ? null : Number(step.maxValue);+ record.numericValue =+ min !== null && max !== null ? (min + max) / 2 : (min ?? max ?? 1);+ break;+ }+ case "Value":+ record.value = "OK";+ break;+ case "List":+ record.value = step.listValues?.[0] ?? "OK";+ break;+ case "Person":+ record.userValue = ctx.userId;+ break;+ case "Timestamp":+ record.value =+ step.recordedAt ?? resolveTimestamp(ctx.anchor, -1, "15:00:00");+ break;+ default:+ record.booleanValue = true;+ }+ await insertRow(ctx, "jobOperationStepRecord", record);+ }+}++/** Mirrors trigger-rework; left open (no completedAt) since the job is still In Progress. */+async function seedRework(ctx: Ctx, data: ProductionData): Promise<void> {+ const jobId = need(ctx.refs.documents, `job:${data.eventsJobKey}`);+ const operations = await rootOperations(ctx, jobId);+ const target = rootOperationAt(+ operations,+ data.rework.targetOperationOrder,+ "production.rework target"+ );+ const triggeredAt = rootOperationAt(+ operations,+ data.rework.triggeredAtOperationOrder,+ "production.rework triggeredAt"+ );++ ctx.log("rework");+ await insertRow(ctx, "rework", {+ jobId,+ quantity: data.rework.quantity,+ reason: data.rework.reason,+ requestedById: ctx.userId,+ targetJobOperationId: target.id,+ triggeredAtJobOperationId: triggeredAt.id+ });+}++/**+ * Header status is inserted directly: update_picking_list_status fires only on+ * line UPDATE. Picked lines on a Completed list write post-picking's ledger pair.+ */+async function seedPickingLists(ctx: Ctx, data: ProductionData): Promise<void> {+ for (const spec of data.pickingLists) {+ await seedPickingList(ctx, spec);+ }+}++async function seedPickingList(ctx: Ctx, spec: PickingListSpec): Promise<void> {+ ctx.log(`picking list ${spec.key} — ${spec.status}`);+ const plantId = ctx.refs.locations.Plant ?? ctx.locationId;+ const jobId = need(ctx.refs.documents, `job:${spec.job}`);+ const operations = await rootOperations(ctx, jobId);+ const staffedOperation = operations.find((op) => op.workCenterId !== null);+ if (!staffedOperation) {+ throw new Error(+ `Seed: picking list "${spec.key}": job "${spec.job}" has no root operation with a work center to stage material at`+ );+ }+ const lineside = await maybeOne<{ id: string }>(+ ctx.client,+ `SELECT id FROM "storageUnit"+ WHERE "workCenterId" = $1 AND "isWorkCenterDefault" = true AND "companyId" = $2+ LIMIT 1`,+ [staffedOperation.workCenterId, ctx.companyId]+ );+ if (!lineside) {+ throw new Error(+ `Seed: picking list "${spec.key}": no floor storage unit for the job's work center`+ );+ }++ const pickingListId = await insertId(ctx, "pickingList", {+ pickingListId: await nextSequence(ctx, "pickingList"),+ locationId: plantId,+ status: spec.status,+ dueDate: resolveDate(ctx.anchor, spec.dateOffset),+ assignee: ctx.userId+ });++ for (const line of spec.lines) {+ const item = need(ctx.refs.items, line.item);+ const fromShelfId = need(ctx.refs.shelves, line.fromShelf, "shelf");+ const material = await maybeOne<{+ id: string;+ jobOperationId: string | null;+ }>(+ ctx.client,+ `SELECT id, "jobOperationId" FROM "jobMaterial"+ WHERE "jobId" = $1 AND "itemId" = $2 AND "companyId" = $3+ ORDER BY "order", id+ LIMIT 1`,+ [jobId, item.id, ctx.companyId]+ );+ if (!material) {+ throw new Error(+ `Seed: picking list "${spec.key}": item "${line.item}" is not a jobMaterial of job "${spec.job}"`+ );+ }++ await insertRow(ctx, "pickingListLine", {+ pickingListId,+ jobId,+ jobMaterialId: material.id,+ jobOperationId: material.jobOperationId,+ itemId: item.id,+ quantityToPick: line.quantityRequired,+ quantityPicked: line.quantityPicked,+ status: line.status,+ storageUnitId: fromShelfId,+ toStorageUnitId: lineside.id});++ // Only a Picked line has moved stock; the paired Transfer rows mirror+ // post-picking's writes exactly (same entryType/documentType/documentId).+ if (line.status === "Picked" && line.quantityPicked > 0) {+ const postingDate = resolveDate(ctx.anchor, spec.dateOffset);+ await insertRow(ctx, "itemLedger", {+ postingDate,+ itemId: item.id,+ quantity: -line.quantityPicked,+ locationId: plantId,+ storageUnitId: fromShelfId,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId+ });+ await insertRow(ctx, "itemLedger", {+ postingDate,+ itemId: item.id,+ quantity: line.quantityPicked,+ locationId: plantId,+ storageUnitId: lineside.id,+ entryType: "Transfer",+ documentType: "Direct Transfer",+ documentId: pickingListId+ });+ }}}diff --git a/packages/database/src/datasets/tiers/07-quality.ts b/packages/database/src/datasets/tiers/07-quality.tsindex 32d3a42f86..f94b8f4533 100644--- a/packages/database/src/datasets/tiers/07-quality.ts+++ b/packages/database/src/datasets/tiers/07-quality.ts@@ -1,19 +1,61 @@-import { resolveDate } from "../dates.ts";+import { resolveDate, resolveTimestamp } from "../dates.ts";+import { bootstrapIdByName } from "../helpers/bootstrap-lookup.ts";+import {+ deriveSampleStatus,+ inspectionPlan,+ resolveInspectionPlan,+ SEED_SAMPLING_STANDARD,+ valuateReading+} from "../helpers/inspection.ts";import {insertId,insertRow,maybeOne,need,nextSequence,- one+ one,+ RICH,+ rows} from "../sql.ts";-import type { Ctx } from "../types.ts";+import type {+ Ctx,+ InspectionFeatureSpec,+ InspectionSpec,+ JobOperationInspectionSpec,+ ReceiptInspectionSpec,+ RiskSpec+} from "../types.ts";export async function runTier7(ctx: Ctx): Promise<void> {const { client, companyId, locationId } = ctx;const data = ctx.dataset.quality;const plantId = ctx.refs.locations.Plant ?? locationId;+ // Inspection lots go first so an NCR below can link one.+ await seedInspections(ctx);++ // Issue workflows are the templates the NCRs below were raised from.+ const workflowIds: Record<string, string> = {};+ for (const workflow of data.workflows) {+ ctx.log(`issue workflow "${workflow.name}"`);+ const requiredActionIds: string[] = [];+ for (const action of workflow.requiredActions) {+ requiredActionIds.push(+ await bootstrapIdByName(ctx, "nonConformanceRequiredAction", action)+ );+ }+ workflowIds[workflow.key] = await insertId(ctx, "nonConformanceWorkflow", {+ name: workflow.name,+ description: workflow.description,+ content: RICH(workflow.description),+ priority: workflow.priority,+ source: workflow.source,+ requiredActionIds,+ approvalRequirements: workflow.mrb ? ["MRB"] : [],+ active: true+ });+ }+// Grab the first nonConformanceType available for this companyconst nct = await one<{ id: string }>(client,@@ -25,20 +67,121 @@ export async function runTier7(ctx: Ctx): Promise<void> {for (const [index, spec] of data.nonConformances.entries()) {ctx.log(`NCR ${index + 1} — ${spec.status}`);const nonConformanceId = await nextSequence(ctx, "nonConformance");+ // Required actions and MRB ride on the NCR as the create form writes them;+ // the task rows below mirror the `create` edge function's derivation.+ const requiredActionIds: string[] = [];+ for (const task of spec.actionTasks ?? []) {+ requiredActionIds.push(+ await bootstrapIdByName(+ ctx,+ "nonConformanceRequiredAction",+ task.action+ )+ );+ }const ncr = await insertId(ctx, "nonConformance", {nonConformanceId,name: spec.name,source: spec.source,status: spec.status,locationId: plantId,- nonConformanceTypeId: nct.id,+ nonConformanceTypeId:+ spec.type === undefined+ ? nct.id+ : await bootstrapIdByName(ctx, "nonConformanceType", spec.type),openDate: resolveDate(ctx.anchor, spec.openDateOffset),quantity: spec.quantity,priority: spec.priority,+ description: spec.description,+ content:+ spec.description === undefined ? undefined : RICH(spec.description),+ dueDate:+ spec.dueDateOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, spec.dueDateOffset),+ closeDate:+ spec.closeDateOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, spec.closeDateOffset),+ requiredActionIds:+ requiredActionIds.length === 0 ? undefined : requiredActionIds,+ approvalRequirements: spec.mrb ? ["MRB"] : undefined,+ nonConformanceWorkflowId:+ spec.workflow === undefined+ ? undefined+ : need(workflowIds, spec.workflow, "issue workflow"),+ assignee: spec.assignee === "self" ? ctx.userId : undefined,companyId});ctx.refs.documents[spec.ref] = ncr;ncrIds.push(ncr);++ for (const line of spec.items) {+ const item = need(ctx.refs.items, line.item, "item");+ await insertRow(ctx, "nonConformanceItem", {+ nonConformanceId: ncr,+ itemId: item.id,+ quantity: line.quantity,+ disposition: line.disposition ?? "Pending"+ });+ }++ for (const [taskIndex, task] of (spec.actionTasks ?? []).entries()) {+ const actionTaskId = await insertId(ctx, "nonConformanceActionTask", {+ nonConformanceId: ncr,+ actionTypeId: requiredActionIds[taskIndex],+ sortOrder: taskIndex + 1,+ status: task.status,+ assignee: task.status === "In Progress" ? ctx.userId : undefined,+ dueDate:+ task.dueDateOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, task.dueDateOffset),+ completedDate:+ task.completedOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, task.completedOffset)+ });+ for (const process of task.processes ?? []) {+ await insertRow(ctx, "nonConformanceActionProcess", {+ actionTaskId,+ processId: need(ctx.refs.processes, process, "process")+ });+ }+ }++ if (spec.mrb) {+ await insertRow(ctx, "nonConformanceApprovalTask", {+ nonConformanceId: ncr,+ approvalType: "MRB",+ status: spec.mrb.status,+ assignee: spec.mrb.status === "In Progress" ? ctx.userId : undefined,+ dueDate:+ spec.mrb.dueDateOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, spec.mrb.dueDateOffset),+ completedDate:+ spec.mrb.completedOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, spec.mrb.completedOffset)+ });+ for (const reviewer of spec.mrb.reviewers) {+ await insertRow(ctx, "nonConformanceReviewer", {+ nonConformanceId: ncr,+ title: reviewer.title,+ status: reviewer.status,+ assignee: reviewer.status === "In Progress" ? ctx.userId : undefined,+ completedDate:+ reviewer.completedOffset === undefined+ ? undefined+ : resolveTimestamp(+ ctx.anchor,+ reviewer.completedOffset,+ "16:00:00"+ )+ });+ }+ }}// ── Associations ──────────────────────────────────────────────────────────@@ -59,7 +202,11 @@ export async function runTier7(ctx: Ctx): Promise<void> {LIMIT 1`,[jobId, companyId]);- if (!operation) continue;+ if (!operation) {+ throw new Error(+ `Seed: NCR "${spec.ref}" names job "${spec.jobOperation.job}", which has no root operation to associate`+ );+ }ctx.log(`NCR ${index + 1} — job operation association`);await insertRow(ctx, "nonConformanceJobOperation", {@@ -68,14 +215,568 @@ export async function runTier7(ctx: Ctx): Promise<void> {jobId,jobReadableId: operation.jobReadableId});+ }- for (const line of spec.items ?? []) {- const item = need(ctx.refs.items, line.item, "item");- await insertRow(ctx, "nonConformanceItem", {- nonConformanceId: ncrIds[index],- itemId: item.id,- quantity: line.quantity+ // Associations, in the shapes insertIssue and the association modal write.+ for (const [index, spec] of data.nonConformances.entries()) {+ const nonConformanceId = ncrIds[index];+ if (spec.supplier !== undefined) {+ await insertRow(ctx, "nonConformanceSupplier", {+ nonConformanceId,+ supplierId: need(ctx.refs.suppliers, spec.supplier, "supplier")+ });+ }+ if (spec.purchaseOrderLine !== undefined) {+ const { po, item } = spec.purchaseOrderLine;+ const purchaseOrderId = need(ctx.refs.documents, po, "purchase order");+ const order = await one<{ purchaseOrderId: string }>(+ client,+ `SELECT "purchaseOrderId" FROM "purchaseOrder" WHERE id = $1`,+ [purchaseOrderId]+ );+ await insertRow(ctx, "nonConformancePurchaseOrderLine", {+ nonConformanceId,+ purchaseOrderLineId: need(+ ctx.refs.documents,+ `poline:${po}:${item}`,+ "purchase order line"+ ),+ purchaseOrderId,+ purchaseOrderReadableId: order.purchaseOrderId});}+ if (spec.customer !== undefined) {+ await insertRow(ctx, "nonConformanceCustomer", {+ nonConformanceId,+ customerId: need(ctx.refs.customers, spec.customer, "customer")+ });+ }+ if (spec.salesOrderLine !== undefined) {+ const salesOrderLineId = need(+ ctx.refs.documents,+ spec.salesOrderLine,+ "sales order line"+ );+ const order = await one<{ id: string; salesOrderId: string }>(+ client,+ `SELECT so.id, so."salesOrderId"+ FROM "salesOrderLine" sol JOIN "salesOrder" so ON so.id = sol."salesOrderId"+ WHERE sol.id = $1`,+ [salesOrderLineId]+ );+ await insertRow(ctx, "nonConformanceSalesOrderLine", {+ nonConformanceId,+ salesOrderLineId,+ salesOrderId: order.id,+ salesOrderReadableId: order.salesOrderId+ });+ }+ if (spec.trackedEntity !== undefined) {+ await insertRow(ctx, "nonConformanceTrackedEntity", {+ nonConformanceId,+ trackedEntityId: need(+ ctx.refs.misc,+ `te:${spec.trackedEntity}`,+ "tracked entity"+ )+ });+ }+ if (spec.salesReturnLine !== undefined) {+ const { salesReturn, line } = spec.salesReturnLine;+ const salesReturnOrderId = need(+ ctx.refs.documents,+ `rma:${salesReturn}`,+ "sales return"+ );+ const order = await one<{ salesReturnOrderId: string }>(+ client,+ `SELECT "salesReturnOrderId" FROM "salesReturnOrder" WHERE id = $1 AND "companyId" = $2`,+ [salesReturnOrderId, ctx.companyId]+ );+ await insertRow(ctx, "nonConformanceSalesReturnOrderLine", {+ nonConformanceId,+ salesReturnOrderLineId: need(+ ctx.refs.documents,+ `rmaline:${salesReturn}:${line}`,+ "sales return line"+ ),+ salesReturnOrderId,+ salesReturnOrderReadableId: order.salesReturnOrderId+ });+ }+ if (spec.purchaseReturnLine !== undefined) {+ const { purchaseReturn, line, quantity } = spec.purchaseReturnLine;+ const purchaseReturnOrderId = need(+ ctx.refs.documents,+ `pret:${purchaseReturn}`,+ "purchase return"+ );+ const order = await one<{ purchaseReturnOrderId: string }>(+ client,+ `SELECT "purchaseReturnOrderId" FROM "purchaseReturnOrder" WHERE id = $1 AND "companyId" = $2`,+ [purchaseReturnOrderId, ctx.companyId]+ );+ await insertRow(ctx, "nonConformancePurchaseReturnOrderLine", {+ nonConformanceId,+ purchaseReturnOrderLineId: need(+ ctx.refs.documents,+ `pretline:${purchaseReturn}:${line}`,+ "purchase return line"+ ),+ purchaseReturnOrderId,+ purchaseReturnOrderReadableId: order.purchaseReturnOrderId,+ quantity+ });+ }+ if (spec.inspection !== undefined) {+ await insertRow(ctx, "nonConformanceInspection", {+ nonConformanceId,+ inspectionId: need(ctx.refs.documents, spec.inspection, "inspection")+ });+ }+ }++ await seedQualityDocuments(ctx);+ await seedGauges(ctx);+ await seedRisks(ctx);+}++async function seedInspections(ctx: Ctx): Promise<void> {+ // One Receipt-usage plan per item (the assignment's PK is (itemId, usage)),+ // shared by every lot of that item.+ const receiptPlans: Record<string, LotPlan> = {};+ for (const spec of ctx.dataset.quality.inspections) {+ const lot =+ spec.source === "Receipt"+ ? await receiptLot(ctx, spec, receiptPlans)+ : await jobOperationLot(ctx, spec);+ await insertLot(ctx, spec, lot);+ }+}++type LotPlan = {+ documentId: string;+ featureIds: Record<string, string>;+ features: InspectionFeatureSpec[];+ aql: number;+};++type LotSource = {+ plan: LotPlan;+ lotSize: number;+ columns: Record<string, unknown>;+ itemId: string;+ supplierId?: string;+};++async function insertPlanDocument(+ ctx: Ctx,+ itemId: string,+ spec: ReceiptInspectionSpec+): Promise<LotPlan> {+ const rule = inspectionPlan(spec);+ const documentId = await insertId(ctx, "inspectionDocument", {+ partId: itemId,+ drawingNumber: spec.drawingNumber,+ samplingPlanType: rule.type,+ samplingAql: rule.aql,+ samplingInspectionLevel: rule.inspectionLevel,+ samplingSeverity: rule.severity+ });+ const featureIds: Record<string, string> = {};+ for (const feature of spec.features) {+ featureIds[feature.label] = await insertId(ctx, "inspectionFeature", {+ inspectionDocumentId: documentId,+ pageNumber: 1,+ label: feature.label,+ description: feature.description,+ nominalValue: feature.nominalValue,+ tolerancePlus: feature.tolerancePlus,+ toleranceMinus: feature.toleranceMinus,+ unit: feature.unit,+ type: "Measurement"+ });+ }+ await insertRow(ctx, "itemInspectionDocumentAssignment", {+ itemId,+ usage: "Receipt",+ inspectionDocumentId: documentId+ });+ return {+ documentId,+ featureIds,+ features: spec.features,+ aql: spec.aql+ };+}++// Mirrors post-receipt's inspection branch (file-less plan document).+async function receiptLot(+ ctx: Ctx,+ spec: ReceiptInspectionSpec,+ plans: Record<string, LotPlan>+): Promise<LotSource> {+ const item = need(ctx.refs.items, spec.item);+ const receiptLineId = need(+ ctx.refs.documents,+ `rline:${spec.receipt}:${spec.item}`,+ "receipt line"+ );+ const line = await one<{+ receiptId: string;+ receiptReadableId: string;+ supplierId: string | null;+ receivedQuantity: string;+ }>(+ ctx.client,+ `SELECT r.id AS "receiptId", r."receiptId" AS "receiptReadableId",+ r."supplierId", rl."receivedQuantity"+ FROM "receiptLine" rl JOIN receipt r ON r.id = rl."receiptId"+ WHERE rl.id = $1 AND rl."companyId" = $2`,+ [receiptLineId, ctx.companyId]+ );+ plans[spec.item] ??= await insertPlanDocument(ctx, item.id, spec);+ return {+ plan: need(plans, spec.item, "receipt inspection plan"),+ lotSize: Number(line.receivedQuantity),+ itemId: item.id,+ supplierId: line.supplierId ?? undefined,+ columns: {+ sourceDocument: "Receipt",+ sourceDocumentId: line.receiptId,+ sourceDocumentLineId: receiptLineId,+ sourceDocumentReadableId: line.receiptReadableId,+ itemId: item.id,+ itemReadableId: item.readableId,+ supplierId: line.supplierId ?? undefined+ }+ };+}++// Mirrors getOrCreateJobOperationInspection: the lot of the job's root+// Inspection operation, under the operation's own plan document.+async function jobOperationLot(+ ctx: Ctx,+ spec: JobOperationInspectionSpec+): Promise<LotSource> {+ const jobId = need(ctx.refs.documents, `job:${spec.job}`, "job");+ const operation = await one<{+ id: string;+ jobReadableId: string;+ operationQuantity: string | null;+ inspectionDocumentId: string | null;+ itemId: string;+ itemReadableId: string;+ }>(+ ctx.client,+ `SELECT jo.id, j."jobId" AS "jobReadableId", jo."operationQuantity",+ jo."inspectionDocumentId", jmm."itemId",+ i."readableIdWithRevision" AS "itemReadableId"+ FROM "jobOperation" jo+ JOIN job j ON j.id = jo."jobId"+ JOIN "jobMakeMethod" jmm ON jmm.id = jo."jobMakeMethodId"+ JOIN item i ON i.id = jmm."itemId"+ WHERE jo."jobId" = $1 AND jo."companyId" = $2+ AND jmm."parentMaterialId" IS NULL AND jo."operationType" = 'Inspection'+ ORDER BY jo."order"+ LIMIT 1`,+ [jobId, ctx.companyId]+ );+ const documentId = operation.inspectionDocumentId;+ if (!documentId) {+ throw new Error(+ `Seed: inspection "${spec.ref}": the Inspection operation of job "${spec.job}" has no plan document`+ );+ }+ const job = need(+ Object.fromEntries(ctx.dataset.production.jobs.map((j) => [j.key, j])),+ spec.job,+ "job spec"+ );+ const planKey = ctx.dataset.items.methods+ .find((method) => method.readableId === job.item)+ ?.bop.find((op) => op.inspectionPlan !== undefined)?.inspectionPlan;+ const planSpec = ctx.dataset.items.inspectionPlans.find(+ (plan) => plan.key === planKey+ );+ if (!planSpec) {+ throw new Error(+ `Seed: inspection "${spec.ref}": "${job.item}" has no inspection plan`+ );+ }+ const features = await rows<{ id: string; label: string }>(+ ctx.client,+ `SELECT id, label FROM "inspectionFeature"+ WHERE "inspectionDocumentId" = $1 AND "companyId" = $2`,+ [documentId, ctx.companyId]+ );+ return {+ plan: {+ documentId,+ featureIds: Object.fromEntries(features.map((f) => [f.label, f.id])),+ features: planSpec.features,+ aql: planSpec.aql+ },+ lotSize: Math.max(1, Math.floor(Number(operation.operationQuantity ?? 1))),+ itemId: operation.itemId,+ columns: {+ sourceDocument: "Job Operation",+ sourceDocumentId: jobId,+ sourceDocumentLineId: operation.id,+ sourceDocumentReadableId: operation.jobReadableId,+ itemId: operation.itemId,+ itemReadableId: operation.itemReadableId+ }+ };+}++async function insertLot(+ ctx: Ctx,+ spec: InspectionSpec,+ source: LotSource+): Promise<void> {+ const { plan: lotPlan, lotSize } = source;+ const rule = inspectionPlan(lotPlan);+ const plan = resolveInspectionPlan(lotPlan, lotSize);+ if (spec.samples.length > plan.sampleSize) {+ throw new Error(+ `Seed: inspection "${spec.ref}" authors ${spec.samples.length} samples for a plan of n=${plan.sampleSize}`+ );+ }+ const dispositioned = spec.status === "Passed" || spec.status === "Partial";+ ctx.log(+ `inspection ${spec.ref} — ${spec.source} lot of ${lotSize}, n=${plan.sampleSize} (${spec.status})`+ );++ const inspectionId = await insertId(ctx, "inspection", {+ inspectionId: await nextSequence(ctx, "inspection"),+ ...source.columns,+ lotSize,+ samplingStandard: SEED_SAMPLING_STANDARD,+ samplingPlanType: rule.type,+ sampleSize: plan.sampleSize,+ acceptanceNumber: plan.acceptance,+ rejectionNumber: plan.rejection,+ aql: rule.aql,+ inspectionLevel: rule.inspectionLevel,+ severity: rule.severity,+ codeLetter: plan.codeLetter ?? undefined,+ inspectionDocumentId: lotPlan.documentId,+ status: spec.status,+ notes: spec.notes,+ dispositionedBy: dispositioned ? ctx.userId : undefined,+ dispositionedAt:+ dispositioned && spec.dispositionOffset !== undefined+ ? resolveTimestamp(ctx.anchor, spec.dispositionOffset, "15:00:00")+ : undefined+ });+ ctx.refs.documents[spec.ref] = inspectionId;++ for (const featureId of Object.values(lotPlan.featureIds)) {+ await insertRow(ctx, "inspectionSamplingPlan", {+ inspectionId,+ inspectionFeatureId: featureId,+ sampleSize: plan.sampleSize,+ acceptanceNumber: plan.acceptance,+ rejectionNumber: plan.rejection,+ codeLetter: plan.codeLetter ?? undefined+ });+ }++ let defects = 0;+ for (const [index, sample] of spec.samples.entries()) {+ const inspectedAt = resolveTimestamp(+ ctx.anchor,+ sample.inspectedOffset,+ `10:${String(10 + index * 5).padStart(2, "0")}:00`+ );+ const status = deriveSampleStatus(lotPlan.features, sample);+ if (status === "Failed") defects += 1;+ const sampleId = await insertId(ctx, "inspectionSample", {+ inspectionId,+ status,+ inspectedBy: status === "Pending" ? undefined : ctx.userId,+ inspectedAt: status === "Pending" ? undefined : inspectedAt+ });+ for (const reading of sample.measurements) {+ const feature = lotPlan.features.find((f) => f.label === reading.feature);+ if (!feature) {+ throw new Error(+ `Seed: inspection sample reads unknown feature "${reading.feature}"`+ );+ }+ await insertRow(ctx, "inspectionMeasurement", {+ inspectionId,+ inspectionSampleId: sampleId,+ inspectionFeatureId: need(lotPlan.featureIds, feature.label, "feature"),+ value: reading.value,+ status: valuateReading(feature, reading.value),+ inspectedBy: ctx.userId,+ inspectedAt+ });+ }+ }++ if (!dispositioned) return;+ await insertRow(ctx, "inspectionHistory", {+ inspectionId,+ itemId: source.itemId,+ supplierId: source.supplierId,+ samplingStandard: SEED_SAMPLING_STANDARD,+ severity: rule.severity,+ inspectionLevel: rule.inspectionLevel,+ aql: rule.aql,+ lotSize,+ sampleSize: plan.sampleSize,+ defectsFound: defects,+ outcome: spec.status === "Passed" ? "Accepted" : "Partial"+ });+}++// Quality documents are plain rows; the archive-on-activate interceptor only+// fires on UPDATE, so inserting an Archived v1 beside an Active v2 is stable.+async function seedQualityDocuments(ctx: Ctx): Promise<void> {+ for (const doc of ctx.dataset.quality.qualityDocuments) {+ ctx.log(`quality document "${doc.name}" v${doc.version} — ${doc.status}`);+ const documentId = await insertId(ctx, "qualityDocument", {+ name: doc.name,+ description: doc.description,+ version: doc.version,+ status: doc.status,+ content: RICH(doc.description)+ });+ for (const [index, step] of doc.steps.entries()) {+ await insertRow(ctx, "qualityDocumentStep", {+ qualityDocumentId: documentId,+ name: step.name,+ description: step.description,+ type: step.type,+ required: step.required,+ sortOrder: index + 1,+ unitOfMeasureCode: step.unitOfMeasureCode,+ minValue: step.minValue,+ maxValue: step.maxValue,+ listValues: step.listValues+ });+ }+ }+}++// Replays records oldest-first as upsertGaugeCalibrationRecord does. An+// out-of-calibration gauge also gets lastCalibrationStatus set, as the nightly+// cleanup leaves it after notifying, so the demo fires no stale alert.+async function seedGauges(ctx: Ctx): Promise<void> {+ const plantId = ctx.refs.locations.Plant ?? ctx.locationId;+ for (const gauge of ctx.dataset.quality.gauges) {+ let calibrationStatus = "Pending";+ let lastCalibrationStatus = "Pending";+ for (const record of gauge.calibrations) {+ calibrationStatus =+ record.result === "Pass" ? "In-Calibration" : "Out-of-Calibration";+ if (record.result === "Pass") lastCalibrationStatus = "In-Calibration";+ }+ if (calibrationStatus === "Out-of-Calibration") {+ lastCalibrationStatus = "Out-of-Calibration";+ }+ const latest = gauge.calibrations.at(-1);+ ctx.log(`gauge ${gauge.key} — ${gauge.status}, ${calibrationStatus}`);++ const gaugeId = await insertId(ctx, "gauge", {+ gaugeId: await nextSequence(ctx, "gauge"),+ gaugeTypeId: await bootstrapIdByName(ctx, "gaugeType", gauge.gaugeType),+ description: gauge.description,+ modelNumber: gauge.modelNumber,+ serialNumber: gauge.serialNumber,+ supplierId:+ gauge.supplier === undefined+ ? undefined+ : need(ctx.refs.suppliers, gauge.supplier, "supplier"),+ dateAcquired: resolveDate(ctx.anchor, gauge.acquiredOffset),+ gaugeRole: gauge.role,+ gaugeStatus: gauge.status,+ gaugeCalibrationStatus: calibrationStatus,+ lastCalibrationStatus,+ calibrationIntervalInMonths: gauge.calibrationIntervalInMonths,+ lastCalibrationDate:+ latest === undefined+ ? undefined+ : resolveDate(ctx.anchor, latest.dateOffset),+ nextCalibrationDate:+ latest === undefined+ ? undefined+ : ctx.anchor+ .add({ days: latest.dateOffset })+ .add({ months: gauge.calibrationIntervalInMonths })+ .toString(),+ locationId: plantId,+ storageUnitId:+ gauge.shelf === undefined+ ? undefined+ : need(ctx.refs.shelves, gauge.shelf, "shelf")+ });++ for (const record of gauge.calibrations) {+ await insertRow(ctx, "gaugeCalibrationRecord", {+ gaugeId,+ dateCalibrated: resolveDate(ctx.anchor, record.dateOffset),+ inspectionStatus: record.result,+ requiresAction: record.requiresAction ?? false,+ requiresAdjustment: record.requiresAdjustment ?? false,+ requiresRepair: record.requiresRepair ?? false,+ temperature: record.temperature,+ humidity: record.humidity,+ measurementStandard: record.measurementStandard,+ notes: record.notes === undefined ? undefined : RICH(record.notes),+ approvedBy: ctx.userId+ });+ }+ }+}++// sourceId / itemId exactly as each entity's RiskRegisterCard writes them.+async function riskLinks(+ ctx: Ctx,+ risk: RiskSpec+): Promise<{ sourceId?: string; itemId?: string }> {+ switch (risk.source) {+ case "General":+ return {};+ case "Customer":+ return { sourceId: need(ctx.refs.customers, risk.customer, "customer") };+ case "Supplier":+ return { sourceId: need(ctx.refs.suppliers, risk.supplier, "supplier") };+ case "Work Center":+ return {+ sourceId: need(ctx.refs.workCenters, risk.workCenter, "work center")+ };+ case "Item": {+ const itemId = need(ctx.refs.items, risk.item, "item").id;+ return { sourceId: itemId, itemId };+ }+ case "Job": {+ const jobId = need(ctx.refs.documents, risk.job, "job");+ const job = await one<{ itemId: string }>(+ ctx.client,+ `SELECT "itemId" FROM job WHERE id = $1`,+ [jobId]+ );+ return { sourceId: jobId, itemId: job.itemId };+ }+ }+}++async function seedRisks(ctx: Ctx): Promise<void> {+ for (const risk of ctx.dataset.quality.risks) {+ ctx.log(`risk "${risk.title}" — ${risk.type}, ${risk.status}`);+ await insertRow(ctx, "riskRegister", {+ title: risk.title,+ description: risk.description,+ type: risk.type,+ status: risk.status,+ source: risk.source,+ severity: risk.severity,+ likelihood: risk.likelihood,+ ...(await riskLinks(ctx, risk))+ });}}diff --git a/packages/database/src/datasets/tiers/08-change-orders.ts b/packages/database/src/datasets/tiers/08-change-orders.tsindex 7960355bb7..1e5c9901a0 100644--- a/packages/database/src/datasets/tiers/08-change-orders.ts+++ b/packages/database/src/datasets/tiers/08-change-orders.ts@@ -1,34 +1,10 @@import { resolveDate } from "../dates.ts";+import { bootstrapIdByName } from "../helpers/bootstrap-lookup.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 { copyMethodToMethod } from "../helpers/method-copy.ts";+import { insertId, insertRow, need, nextSequence, one, RICH } 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(@@ -45,69 +21,6 @@ async function baseMakeMethod();}-/**- * 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 data = ctx.dataset.changeOrders;@@ -119,9 +32,55 @@ export async function runTier8(ctx: Ctx): Promise<void> {name: spec.name,type: spec.type,status: spec.status,- openDate: resolveDate(ctx.anchor, spec.openDateOffset)+ openDate: resolveDate(ctx.anchor, spec.openDateOffset),+ changeOrderTypeId:+ spec.changeOrderType === undefined+ ? undefined+ : await bootstrapIdByName(+ ctx,+ "changeOrderType",+ spec.changeOrderType+ ),+ priority: spec.priority,+ dueDate:+ spec.dueDateOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, spec.dueDateOffset),+ reasonForChange:+ spec.reasonForChange === undefined+ ? undefined+ : RICH(spec.reasonForChange),+ nonConformanceId:+ spec.nonConformance === undefined+ ? undefined+ : need(ctx.refs.documents, spec.nonConformance, "NCR")});+ // Action tasks as setChangeNoticeActionTasks instantiates them from the+ // required-action templates: template id + name, 1-based sortOrder.+ for (const [taskIndex, task] of (spec.actionTasks ?? []).entries()) {+ await insertRow(ctx, "changeOrderActionTask", {+ changeOrderId: changeOrder,+ actionTypeId: await bootstrapIdByName(+ ctx,+ "changeOrderRequiredAction",+ task.action+ ),+ name: task.action,+ status: task.status,+ sortOrder: taskIndex + 1,+ assignee: task.status === "In Progress" ? ctx.userId : undefined,+ dueDate:+ task.dueDateOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, task.dueDateOffset),+ completedDate:+ task.completedOffset === undefined+ ? undefined+ : resolveDate(ctx.anchor, task.completedOffset)+ });+ }+for (const affected of spec.affectedItems) {const item = need(ctx.refs.items, affected.item);const base = await baseMakeMethod(ctx, item);@@ -142,7 +101,7 @@ export async function runTier8(ctx: Ctx): Promise<void> {status: "Draft",changeOrderId: changeOrder});- await cloneMethodRows(ctx, base.id, draft);+ await copyMethodToMethod(ctx, base.id, draft);ctx.log(` ${item.readableId} draft method v${draftVersion}`);draftMakeMethodId = draft;baseMakeMethodId = base.id;@@ -164,7 +123,8 @@ export async function runTier8(ctx: Ctx): Promise<void> {name: item.name,type: "Part",replenishment: "Make",- standardCost: 0,+ // A new revision starts at its predecessor's cost.+ standardCost: item.unitCost,unitSalePrice: revisionSpec.unitSalePrice,description: revisionSpec.description});@@ -184,7 +144,7 @@ export async function runTier8(ctx: Ctx): Promise<void> {WHERE id = $1`,[draft, changeOrder, ctx.userId]);- await cloneMethodRows(ctx, base.id, draft);+ await copyMethodToMethod(ctx, base.id, draft);ctx.log(` ${revisionItem.readableId}.${revisionItem.revision} draft method`);diff --git a/packages/database/src/datasets/tiers/09-accounting.ts b/packages/database/src/datasets/tiers/09-accounting.tsindex fe388bdb98..ffcbd11ae0 100644--- a/packages/database/src/datasets/tiers/09-accounting.ts+++ b/packages/database/src/datasets/tiers/09-accounting.ts@@ -1,6 +1,59 @@-import { previousMonthEnd, resolveDate } from "../dates.ts";-import { insertId, insertRow, maybeOne, nextSequence, rows } from "../sql.ts";-import type { Ctx } from "../types.ts";+import { round } from "../../../supabase/functions/shared/precision.ts";+import {+ CLOSED_PERIOD_MONTHS_BACK,+ LOCKED_PERIOD_MONTHS_BACK,+ monthBack,+ previousMonthEnd,+ resolveDate,+ resolveTimestamp,+ SEEDED_PERIOD_MONTHS+} from "../dates.ts";+import { insertMemo } from "../helpers/memo.ts";+import {+ type AccountingPeriodRange,+ loadPostingContext,+ type PostingContext,+ periodFor,+ postInventoryDocuments,+ postMemos,+ postPayment,+ postPurchaseInvoices,+ postSalesInvoices+} from "../helpers/post-documents.ts";+import {+ insertId,+ insertMaybe,+ insertRow,+ maybeOne,+ need,+ nextSequence,+ one,+ rows+} from "../sql.ts";+import type {+ AccountClass,+ BillingAddressSpec,+ Ctx,+ JournalEntrySpec,+ JournalLineSpec+} from "../types.ts";++// Mirrors get-accounting-period.ts so seeded periods get the same (fiscalYear,+// periodNumber) key the app computes.+const MONTH_NUMBER: Record<string, number> = {+ January: 1,+ February: 2,+ March: 3,+ April: 4,+ May: 5,+ June: 6,+ July: 7,+ August: 8,+ September: 9,+ October: 10,+ November: 11,+ December: 12+};export async function runTier9(ctx: Ctx): Promise<void> {const { client, companyId, companyGroupId } = ctx;@@ -18,44 +71,308 @@ export async function runTier9(ctx: Ctx): Promise<void> {`SELECT id FROM account WHERE class = 'Revenue' AND "companyGroupId" = $1 ORDER BY number LIMIT 1`,[companyGroupId]);-if (!acctAR || !acctSales) {- ctx.log("no GL accounts found — skipping journal entry");- } else {- const accountIdByClass = { Asset: acctAR.id, Revenue: acctSales.id };- for (const entry of data.journalEntries) {- // journal is preserved across wipes — skip if already seeded- const existing = await maybeOne<{ id: string }>(+ throw new Error(+ "Seed: no GL accounts found for this company group — bootstrap must seed the chart of accounts before datasets apply"+ );+ }+ const accountIdByClass = new Map<AccountClass, string>([+ ["Asset", acctAR.id],+ ["Revenue", acctSales.id]+ ]);+ const accountIdByNumber: Record<string, string> = Object.fromEntries(+ (+ await rows<{ id: string; number: string }>(+ client,+ `SELECT id, number FROM account+ WHERE "companyGroupId" = $1 AND number IS NOT NULL AND "isGroup" = false`,+ [companyGroupId]+ )+ ).map((a) => [a.number, a.id])+ );+ const resolveAccount = async (line: JournalLineSpec): Promise<string> => {+ if (line.account !== undefined) {+ return need(accountIdByNumber, line.account, "GL account");+ }+ const cached = accountIdByClass.get(line.accountClass);+ if (cached) return cached;+ const row = await one<{ id: string }>(+ client,+ `SELECT id FROM account WHERE class = $1 AND "companyGroupId" = $2 ORDER BY number LIMIT 1`,+ [line.accountClass, companyGroupId]+ );+ accountIdByClass.set(line.accountClass, row.id);+ return row.id;+ };++ const defaults = await one<{ bankCashAccount: string | null }>(+ client,+ `SELECT "bankCashAccount" FROM "accountDefault" WHERE "companyId" = $1`,+ [companyId]+ );++ // Before the journals, so the journal_check_period_open trigger vets every+ // seeded posting date against the seeded close state.+ const periods = await seedAccountingPeriods(ctx);+ const posting = await loadPostingContext(ctx, periods);++ for (const spec of data.projects) {+ ctx.log(`project ${spec.name}`);+ const projectId = await insertId(ctx, "project", {+ name: spec.name,+ description: spec.description+ });+ ctx.refs.misc[`project:${spec.key}`] = projectId;+ if (spec.purchaseInvoiceLine) {+ const invoiceId = need(+ ctx.refs.misc,+ `pinv:${spec.purchaseInvoiceLine.invoiceKey}`,+ "purchase invoice"+ );+ const item = need(ctx.refs.items, spec.purchaseInvoiceLine.item, "item");+ const res = await client.query(+ `UPDATE "purchaseInvoiceLine" SET "projectId" = $1, "updatedBy" = $2+ WHERE "invoiceId" = $3 AND "itemId" = $4 AND "companyId" = $5`,+ [projectId, ctx.userId, invoiceId, item.id, companyId]+ );+ if (res.rowCount !== 1) {+ throw new Error(+ `Seed: project "${spec.key}" expected one purchase invoice line for "${spec.purchaseInvoiceLine.item}", found ${res.rowCount}`+ );+ }+ }+ }++ // dimension/dimensionValue are companyGroup-scoped (no companyId), so the+ // dataset wipe never clears them — look up before inserting.+ const projectDimension = await maybeOne<{ id: string }>(+ client,+ `SELECT id FROM dimension+ WHERE "companyGroupId" = $1 AND "entityType" = 'Project' AND active = true+ ORDER BY id LIMIT 1`,+ [companyGroupId]+ );+ const custom = data.customDimension;+ let customDimensionId = (+ await maybeOne<{ id: string }>(+ client,+ `SELECT id FROM dimension WHERE "companyGroupId" = $1 AND name = $2 AND active = true`,+ [companyGroupId, custom.name]+ )+ )?.id;+ if (!customDimensionId) {+ ctx.log(`dimension ${custom.name} — Custom`);+ customDimensionId = await insertId(ctx, "dimension", {+ name: custom.name,+ entityType: "Custom",+ companyGroupId+ });+ }+ const dimensionValueIds: Record<string, string> = {};+ for (const value of custom.values) {+ const existing = await maybeOne<{ id: string }>(+ client,+ `SELECT id FROM "dimensionValue" WHERE "dimensionId" = $1 AND name = $2`,+ [customDimensionId, value]+ );+ dimensionValueIds[value] =+ existing?.id ??+ (await insertId(ctx, "dimensionValue", {+ dimensionId: customDimensionId,+ name: value,+ companyGroupId+ }));+ }+ const resolveDimension = (tag: {+ dimension: string;+ value: string;+ }): { dimensionId: string; valueId: string } => {+ if (tag.dimension === "Project") {+ if (!projectDimension) {+ throw new Error(+ "Seed: no active Project dimension for this company group — bootstrap seeds it"+ );+ }+ return {+ dimensionId: projectDimension.id,+ valueId: need(ctx.refs.misc, `project:${tag.value}`, "project")+ };+ }+ if (tag.dimension !== custom.name) {+ throw new Error(`Seed: unknown dimension "${tag.dimension}"`);+ }+ return {+ dimensionId: customDimensionId,+ valueId: need(dimensionValueIds, tag.value, "dimension value")+ };+ };++ for (const entry of data.journalEntries) {+ const journalId = await seedJournal(ctx, posting, entry, resolveAccount);+ for (const line of entry.lines) {+ if (!line.dimensions?.length) continue;+ const lineRow = await one<{ id: string }>(client,- `SELECT id FROM journal WHERE "journalEntryId" = $1 AND "companyId" = $2`,- [entry.journalEntryId, companyId]+ `SELECT id FROM "journalLine"+ WHERE "journalId" = $1 AND "journalLineReference" = $2 AND "companyId" = $3`,+ [journalId, line.journalLineReference, companyId]);- if (existing) {- ctx.log("journal entry — already exists, skipping");- ctx.refs.documents[entry.ref] = existing.id;- } else {- ctx.log("journal entry — revenue recognition");- const je = await insertId(ctx, "journal", {- journalEntryId: entry.journalEntryId,- description: entry.description,- status: entry.status,- postingDate: resolveDate(ctx.anchor, entry.postingOffset)+ for (const tag of line.dimensions) {+ await insertMaybe(ctx, "journalLineDimension", {+ journalLineId: lineRow.id,+ ...resolveDimension(tag)});- for (const line of entry.lines) {- await insertId(ctx, "journalLine", {- journalId: je,- accountId: accountIdByClass[line.accountClass],- description: line.description,- amount: line.amount,- quantity: line.quantity,- journalLineReference: line.journalLineReference- });- }- ctx.refs.documents[entry.ref] = je;}}}+ await postInventoryDocuments(ctx, posting);+ await postSalesInvoices(ctx, posting);+ await postPurchaseInvoices(ctx, posting);++ for (const spec of data.memos) {+ const isCredit = spec.direction === "Credit";+ const invoice = await one<{+ id: string;+ invoiceId: string;+ currencyCode: string;+ }>(+ client,+ `SELECT id, "invoiceId", "currencyCode" FROM ${isCredit ? '"salesInvoice"' : '"purchaseInvoice"'}+ WHERE id = $1 AND "companyId" = $2`,+ [+ need(+ ctx.refs.misc,+ `${isCredit ? "sinv" : "pinv"}:${spec.invoiceKey}`,+ "invoice"+ ),+ companyId+ ]+ );+ ctx.log(`${spec.direction.toLowerCase()} memo ${spec.key} — Posted`);+ const memoId = await insertMemo(ctx, {+ direction: spec.direction,+ partyId: isCredit+ ? need(ctx.refs.customers, spec.customer ?? "", "customer")+ : need(ctx.refs.suppliers, spec.supplier ?? "", "supplier"),+ status: "Posted",+ dateOffset: spec.dateOffset,+ amount: spec.amount,+ currencyCode: invoice.currencyCode,+ exchangeRate: 1,+ reference: invoice.invoiceId,+ notes: spec.notes+ });+ ctx.refs.documents[`memo:${spec.key}`] = memoId;+ }+ // Also journals the Posted return credits tier 04 wrote.+ await postMemos(ctx, posting);++ if (data.payments.length > 0 && !defaults.bankCashAccount) {+ throw new Error("Seed: accountDefault.bankCashAccount is not set");+ }+ for (const spec of data.payments) {+ const isReceipt = spec.type === "Receipt";+ const paymentDate = resolveDate(ctx.anchor, spec.dateOffset);+ const posted = spec.status !== "Draft";+ ctx.log(`payment ${spec.key} — ${spec.type} ${spec.status ?? "Posted"}`);+ const paymentReadableId = await nextSequence(ctx, "payment");+ const paymentId = await insertId(ctx, "payment", {+ paymentId: paymentReadableId,+ paymentType: spec.type,+ customerId: isReceipt+ ? need(ctx.refs.customers, spec.customer ?? "", "customer")+ : undefined,+ supplierId: isReceipt+ ? undefined+ : need(ctx.refs.suppliers, spec.supplier ?? "", "supplier"),+ currencyCode: "USD",+ exchangeRate: 1,+ bankAccount: defaults.bankCashAccount,+ paymentDate,+ postingDate: posted ? paymentDate : undefined,+ totalAmount: spec.amount,+ reference: spec.reference,+ status: posted ? "Posted" : "Draft",+ postedAt: posted+ ? resolveTimestamp(ctx.anchor, spec.dateOffset, "15:00:00")+ : undefined,+ postedBy: posted ? ctx.userId : undefined+ });+ ctx.refs.documents[`payment:${spec.key}`] = paymentId;+ if (!posted) {+ if (spec.applies.length > 0 || spec.credits?.length) {+ throw new Error(+ `Seed: Draft payment "${spec.key}" must be unapplied (the apply table is the point)`+ );+ }+ continue;+ }++ const invoiceIdFor = (invoiceKey: string) =>+ need(+ ctx.refs.misc,+ `${isReceipt ? "sinv" : "pinv"}:${invoiceKey}`,+ "invoice"+ );+ const target = (invoiceKey: string) => {+ const id = invoiceIdFor(invoiceKey);+ return isReceipt+ ? { targetSalesInvoiceId: id }+ : { targetPurchaseInvoiceId: id };+ };+ // Base currency at rate 1: appliedAmount (base) = sourceAmount (principal).+ for (const apply of spec.applies) {+ await insertRow(ctx, "invoiceSettlement", {+ paymentId,+ ...target(apply.invoiceKey),+ appliedAmount: apply.amount,+ sourceAmount: apply.amount,+ sourceExchangeRate: 1,+ targetExchangeRate: 1,+ discountAmount: 0,+ writeOffAmount: 0,+ fxGainLossAmount: 0,+ appliedDate: paymentDate+ });+ }+ // Matching-snapshot memo applications are GL-neutral (applyCreditsToInvoices).+ for (const credit of spec.credits ?? []) {+ await insertRow(ctx, "invoiceSettlement", {+ memoId: need(ctx.refs.documents, `memo:${credit.memoKey}`, "memo"),+ appliedViaPaymentId: paymentId,+ ...target(credit.invoiceKey),+ appliedAmount: credit.amount,+ sourceAmount: credit.amount,+ sourceExchangeRate: 1,+ targetExchangeRate: 1,+ discountAmount: 0,+ writeOffAmount: 0,+ fxGainLossAmount: 0,+ appliedDate: paymentDate+ });+ }+ await postPayment(ctx, posting, {+ paymentId,+ paymentReadableId,+ type: spec.type,+ amount: spec.amount,+ postingDate: paymentDate,+ applies: spec.applies.map((apply) => ({+ targetId: invoiceIdFor(apply.invoiceKey),+ amount: apply.amount+ }))+ });+ }++ for (const spec of data.exchangeRateOverrides) {+ ctx.log(`exchange rate override ${spec.currencyCode}`);+ await insertMaybe(ctx, "exchangeRateOverride", {+ currencyCode: spec.currencyCode,+ rate: spec.rate+ });+ }+// ── Fixed assets ─────────────────────────────────────────────────────────// fixedAssetClass is in PRESERVED_TABLES — bootstrap seeds the three classes,// so look them up by name rather than inserting.@@ -73,15 +390,20 @@ export async function runTier9(ctx: Ctx): Promise<void> {const fixedAssetClassId =faClassByName.get(spec.className) ?? fallbackClassId;if (!fixedAssetClassId) {- ctx.log(`fixed asset ${spec.name} — no fixedAssetClass, skipping`);- continue;+ throw new Error(+ `Seed: missing fixedAssetClass "${spec.className}" for fixed asset "${spec.name}" (and no fallback class exists)`+ );}ctx.log(`fixed asset ${spec.name} — ${spec.status}`);const fixedAssetId = await nextSequence(ctx, "fixedAsset");+ const disposalDate =+ spec.disposal === undefined+ ? undefined+ : resolveDate(ctx.anchor, spec.disposal.dateOffset);const fa = await insertId(ctx, "fixedAsset", {fixedAssetId,fixedAssetClassId,- locationId: ctx.refs.locations[spec.location] ?? ctx.locationId,+ locationId: need(ctx.refs.locations, spec.location, "location"),name: spec.name,description: spec.description,serialNumber: spec.serialNumber,@@ -98,14 +420,55 @@ export async function runTier9(ctx: Ctx): Promise<void> {spec.depreciationStartOffset === null? null: resolveDate(ctx.anchor, spec.depreciationStartOffset),- accumulatedDepreciation: spec.accumulatedDepreciation+ accumulatedDepreciation: spec.accumulatedDepreciation,+ // Undefined keys are dropped by insertId, so plain assets insert as before.+ assetLifetimeUsage: spec.assetLifetimeUsage,+ disposalDate,+ disposalMethod: spec.disposal?.method,+ saleProceeds: spec.disposal?.saleProceeds});ctx.refs.documents[`fixedAsset:${spec.key}`] = fa;if (spec.depreciationCharge) {runLines.push({ fixedAssetId: fa, amount: spec.depreciationCharge });}+ for (const log of spec.usageLogs ?? []) {+ const { start, end } = monthBack(ctx.anchor, log.monthsBack);+ await insertRow(ctx, "fixedAssetUsageLog", {+ fixedAssetId: fa,+ periodStart: start.toString(),+ periodEnd: end.toString(),+ unitsProduced: log.unitsProduced+ });+ }+ if (spec.disposal && disposalDate) {+ // The app's disposal math: NBV = cost − accumulated depreciation, and the+ // gain/(loss) is proceeds − NBV (post-sales-invoice).+ const netBookValueAtDisposal = round(+ spec.acquisitionCost - spec.accumulatedDepreciation+ );+ await insertRow(ctx, "fixedAssetDisposal", {+ fixedAssetId: fa,+ disposalDate,+ disposalMethod: spec.disposal.method,+ saleProceeds: spec.disposal.saleProceeds,+ netBookValueAtDisposal,+ gainLoss: round(spec.disposal.saleProceeds - netBookValueAtDisposal)+ });+ }}+ ctx.log("AR / AP billing addresses");+ await upsertBillingAddress(+ ctx,+ "companyAccountsReceivableBillingAddress",+ data.billingAddresses.receivable+ );+ await upsertBillingAddress(+ ctx,+ "companyAccountsPayableBillingAddress",+ data.billingAddresses.payable+ );+// ── 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@@ -130,3 +493,291 @@ export async function runTier9(ctx: Ctx): Promise<void> {ctx.refs.documents["depreciationRun:draft"] = run;}}++async function seedJournal(+ ctx: Ctx,+ posting: PostingContext,+ entry: JournalEntrySpec,+ resolveAccount: (line: JournalLineSpec) => Promise<string>+): Promise<string> {+ const { client, companyId } = ctx;+ const findJournal = (journalEntryId: string) =>+ maybeOne<{ id: string }>(+ client,+ `SELECT id FROM journal WHERE "journalEntryId" = $1 AND "companyId" = $2`,+ [journalEntryId, companyId]+ );++ // journal is preserved across wipes — skip if already seeded. A company holds+ // one Posted Opening Balance (unique index), so an earlier one is adopted too.+ const existing =+ (await findJournal(entry.journalEntryId)) ??+ (entry.sourceType === "Opening Balance"+ ? await maybeOne<{ id: string }>(+ client,+ `SELECT id FROM journal+ WHERE "companyId" = $1 AND "sourceType" = 'Opening Balance' AND status = 'Posted'`,+ [companyId]+ )+ : null);+ if (existing) {+ ctx.log("journal entry — already exists, skipping");+ ctx.refs.documents[entry.ref] = existing.id;+ if (entry.reversal) {+ const reversal = await findJournal(entry.reversal.journalEntryId);+ if (reversal) ctx.refs.documents[entry.reversal.ref] = reversal.id;+ }+ return existing.id;+ }++ ctx.log(`journal entry ${entry.journalEntryId} — ${entry.status}`);+ // A Reversed entry was Posted first; reverseJournalEntry flips it below.+ const posted = entry.status !== "Draft";+ const postedStamp = (offset: number) => ({+ sourceType: entry.sourceType ?? "Manual",+ postedAt: resolveTimestamp(ctx.anchor, offset, "17:00:00"),+ postedBy: ctx.userId+ });+ const postingDate = resolveDate(ctx.anchor, entry.postingOffset);+ const je = await insertId(ctx, "journal", {+ journalEntryId: entry.journalEntryId,+ description: entry.description,+ status: posted ? "Posted" : entry.status,+ postingDate,+ accountingPeriodId: periodFor(posting, postingDate),+ ...(posted ? postedStamp(entry.postingOffset) : {})+ });+ for (const line of entry.lines) {+ await insertId(ctx, "journalLine", {+ journalId: je,+ accountId: await resolveAccount(line),+ description: line.description,+ amount: line.amount,+ quantity: line.quantity,+ journalLineReference: line.journalLineReference+ });+ }+ ctx.refs.documents[entry.ref] = je;++ if (entry.status === "Reversed") {+ const spec = entry.reversal;+ if (!spec) {+ throw new Error(+ `Seed: journal "${entry.ref}" is Reversed but names no reversal entry`+ );+ }+ ctx.log(`journal entry ${spec.journalEntryId} — reversal, Posted`);+ const reversalDate = resolveDate(ctx.anchor, spec.postingOffset);+ const reversal = await insertId(ctx, "journal", {+ journalEntryId: spec.journalEntryId,+ description: `Reversal of ${entry.journalEntryId}`,+ status: "Posted",+ postingDate: reversalDate,+ accountingPeriodId: periodFor(posting, reversalDate),+ reversalOfId: je,+ ...postedStamp(spec.postingOffset)+ });+ for (const line of entry.lines) {+ await insertId(ctx, "journalLine", {+ journalId: reversal,+ accountId: await resolveAccount(line),+ description: line.description,+ amount: -line.amount,+ quantity: line.quantity,+ journalLineReference: spec.journalEntryId+ });+ }+ // Posted → Reversed is the one UPDATE journal_posted_immutable permits.+ await client.query(+ `UPDATE journal SET status = 'Reversed', "reversedById" = $1, "updatedBy" = $2+ WHERE id = $3 AND "companyId" = $4`,+ [reversal, ctx.userId, je, companyId]+ );+ ctx.refs.documents[spec.ref] = reversal;+ }+ return je;+}++// Close is sequential: oldest months Closed, then one Locked, the rest Open.+async function seedAccountingPeriods(+ ctx: Ctx+): Promise<AccountingPeriodRange[]> {+ const { client, companyId } = ctx;+ const fiscal = await maybeOne<{ startMonth: string | null }>(+ client,+ `SELECT "startMonth" FROM "fiscalYearSettings" WHERE "companyId" = $1`,+ [companyId]+ );+ const startMonth = fiscal?.startMonth+ ? (MONTH_NUMBER[fiscal.startMonth] ?? 1)+ : 1;++ // One Active period per company, like resolveAccountingPeriod's "current" mode.+ await client.query(+ `UPDATE "accountingPeriod" SET status = 'Inactive' WHERE "companyId" = $1 AND status = 'Active'`,+ [companyId]+ );++ const closed = new Set<number>(CLOSED_PERIOD_MONTHS_BACK);+ const seeded: AccountingPeriodRange[] = [];+ let lockedPeriodId: string | null = null;+ let lockedPeriodEnd: string | null = null;+ ctx.log(`accounting periods — ${SEEDED_PERIOD_MONTHS} months`);+ for (let back = SEEDED_PERIOD_MONTHS - 1; back >= 0; back--) {+ const { start, end } = monthBack(ctx.anchor, back);+ const fiscalYear =+ startMonth === 1 || start.month < startMonth+ ? start.year+ : start.year + 1;+ const periodNumber = ((start.month - startMonth + 12) % 12) + 1;+ const isClosed = closed.has(back);+ const isLocked = back === LOCKED_PERIOD_MONTHS_BACK;+ // Closed periods went through Locked first.+ const lockedAt =+ isClosed || isLocked+ ? `${end.add({ days: 4 }).toString()}T17:00:00Z`+ : null;+ const closedAt = isClosed+ ? `${end.add({ days: 9 }).toString()}T17:00:00Z`+ : null;+ const period = {+ startDate: start.toString(),+ endDate: end.toString(),+ fiscalYear,+ periodNumber,+ status: back === 0 ? "Active" : "Inactive",+ closeStatus: isClosed ? "Closed" : isLocked ? "Locked" : "Open",+ lockedAt,+ lockedBy: lockedAt ? ctx.userId : null,+ closedAt,+ closedBy: closedAt ? ctx.userId : null+ };+ // accountingPeriod survives the wipe (posted journals reference it), and+ // the app finds a period by date range — so adopt the month's existing+ // row, which job-costing functions may have minted without fiscal numbers,+ // rather than add an overlapping one.+ const existing = await maybeOne<{ id: string }>(+ client,+ `SELECT id FROM "accountingPeriod"+ WHERE "companyId" = $1+ AND (("fiscalYear" = $2 AND "periodNumber" = $3) OR "startDate" = $4)+ ORDER BY ("fiscalYear" = $2 AND "periodNumber" = $3) DESC NULLS LAST, id+ LIMIT 1`,+ [companyId, fiscalYear, periodNumber, period.startDate]+ );+ let periodId: string;+ if (existing) {+ periodId = existing.id;+ await client.query(+ `UPDATE "accountingPeriod" SET+ "startDate" = $3, "endDate" = $4, "fiscalYear" = $5,+ "periodNumber" = $6, status = $7, "closeStatus" = $8,+ "lockedAt" = $9, "lockedBy" = $10, "closedAt" = $11,+ "closedBy" = $12, "updatedBy" = $13+ WHERE id = $1 AND "companyId" = $2`,+ [+ periodId,+ companyId,+ period.startDate,+ period.endDate,+ period.fiscalYear,+ period.periodNumber,+ period.status,+ period.closeStatus,+ period.lockedAt,+ period.lockedBy,+ period.closedAt,+ period.closedBy,+ ctx.userId+ ]+ );+ } else {+ periodId = await insertId(ctx, "accountingPeriod", period);+ }+ seeded.push({+ id: periodId,+ startDate: period.startDate,+ endDate: period.endDate+ });+ if (isLocked) {+ lockedPeriodId = periodId;+ lockedPeriodEnd = end.toString();+ }+ }++ // Snapshot the bootstrap definitions the way getPeriodCloseChecklist+ // instantiates them; the rest of the checklist materializes on first view.+ const tasks = ctx.dataset.accounting.closeTasks;+ if (tasks.length === 0) return seeded;+ if (!lockedPeriodId || !lockedPeriodEnd) {+ throw new Error("Seed: close tasks need a Locked period");+ }+ const definitions = await rows<{+ id: string;+ name: string;+ taskType: string;+ autoCheckKey: string | null;+ sortOrder: number;+ required: boolean;+ severity: string | null;+ }>(+ client,+ `SELECT id, name, "taskType", "autoCheckKey", "sortOrder", required, severity+ FROM "periodCloseTaskDefinition" WHERE "companyId" = $1`,+ [companyId]+ );+ const byName = Object.fromEntries(definitions.map((d) => [d.name, d]));+ const completedAt = `${lockedPeriodEnd}T16:00:00Z`;+ for (const task of tasks) {+ const def = need(byName, task.definition, "period close task definition");+ ctx.log(`period close task ${def.name} — ${task.status}`);+ const done = task.status === "Done";+ await insertRow(ctx, "periodCloseTask", {+ accountingPeriodId: lockedPeriodId,+ definitionId: def.id,+ name: def.name,+ taskType: def.taskType,+ autoCheckKey: def.autoCheckKey,+ sortOrder: def.sortOrder,+ required: def.required,+ severity: def.severity,+ status: task.status,+ assigneeId: ctx.userId,+ completedAt: done ? completedAt : undefined,+ // NULL for system-auto completions (the table's own convention).+ completedBy: done && def.taskType !== "Auto" ? ctx.userId : undefined,+ skippedReason: task.skippedReason,+ notes: task.notes+ });+ }+ return seeded;+}++async function upsertBillingAddress(+ ctx: Ctx,+ table:+ | "companyAccountsReceivableBillingAddress"+ | "companyAccountsPayableBillingAddress",+ address: BillingAddressSpec+): Promise<void> {+ const values = [+ address.addressLine1,+ address.city,+ address.state,+ address.postalCode,+ address.countryCode,+ address.phone,+ address.email+ ];+ await ctx.client.query(+ `INSERT INTO "${table}"+ (id, "addressLine1", city, state, "postalCode", "countryCode", phone, email, "updatedBy")+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ ON CONFLICT (id) DO UPDATE SET+ "addressLine1" = EXCLUDED."addressLine1", city = EXCLUDED.city,+ state = EXCLUDED.state, "postalCode" = EXCLUDED."postalCode",+ "countryCode" = EXCLUDED."countryCode", phone = EXCLUDED.phone,+ email = EXCLUDED.email, "updatedBy" = EXCLUDED."updatedBy"`,+ [ctx.companyId, ...values, ctx.userId]+ );+}diff --git a/packages/database/src/datasets/tiers/10-ops.ts b/packages/database/src/datasets/tiers/10-ops.tsindex f2fa9def36..747be79c51 100644--- a/packages/database/src/datasets/tiers/10-ops.ts+++ b/packages/database/src/datasets/tiers/10-ops.ts@@ -1,7 +1,627 @@-import type { Ctx } from "../types.ts";+import { resolveDate, resolveTimestamp } from "../dates.ts";+import { bootstrapIdByName } from "../helpers/bootstrap-lookup.ts";+import {+ insertId,+ insertRow,+ maybeOne,+ need,+ nextSequence,+ one,+ RICH+} from "../sql.ts";+import type {+ AttributeDataTypeLabel,+ Ctx,+ CustomFieldSpec,+ InstantSpec,+ MaintenanceDispatchSpec,+ MaintenanceScheduleSpec,+ PrintJobSpec,+ TrainingQuestionSpec,+ TrainingSpec,+ UserAttributeCategorySpec+} from "../types.ts";++// Every ops row is written in the shape the app's own create/transition paths+// leave it.-// Placeholder tier — nothing structural needed here yet.-// Future: maintenance, table views, custom fields, approvals.export async function runTier10(ctx: Ctx): Promise<void> {- ctx.log("ops/misc — nothing to seed yet");+ const data = ctx.dataset.ops;++ ctx.log(`maintenance schedules — ${data.maintenanceSchedules.length}`);+ for (const spec of data.maintenanceSchedules) {+ await seedSchedule(ctx, spec);+ }++ ctx.log(`maintenance dispatches — ${data.maintenanceDispatches.length}`);+ for (const spec of data.maintenanceDispatches) {+ await seedDispatch(ctx, spec);+ }++ ctx.log(`work-center replacement parts — ${data.replacementParts.length}`);+ for (const spec of data.replacementParts) {+ const item = need(ctx.refs.items, spec.item, "item");+ await insertRow(ctx, "workCenterReplacementPart", {+ workCenterId: need(ctx.refs.workCenters, spec.workCenter, "work center"),+ itemId: item.id,+ quantity: spec.quantity,+ unitOfMeasureCode: item.unitOfMeasureCode+ });+ }++ ctx.log(`trainings — ${data.trainings.length}`);+ for (const spec of data.trainings) {+ await seedTraining(ctx, spec);+ }++ ctx.log(`timecards — ${data.timecards.length}`);+ for (const card of data.timecards) {+ await insertRow(ctx, "timeCardEntry", {+ employeeId: ctx.userId,+ clockIn: resolveTimestamp(ctx.anchor, card.dayOffset, card.clockIn),+ clockOut: resolveTimestamp(ctx.anchor, card.dayOffset, card.clockOut),+ note: card.note+ });+ }++ // companySettings has no companyId, so the wipe keeps it; without the flag+ // both apps hide the time clock and redirect away from the timecard pages.+ ctx.log("time clock — enabled, clocked in today");+ await insertRow(+ ctx,+ "companySettings",+ { id: ctx.companyId, timeCardEnabled: true },+ { onConflict: '("id") DO UPDATE SET "timeCardEnabled" = true' }+ );+ // The MES reads the open entry with maybeSingle, so there is exactly one.+ await insertRow(ctx, "timeCardEntry", {+ employeeId: ctx.userId,+ clockIn: resolveTimestamp(ctx.anchor, 0, data.openTimecard.clockIn),+ clockOut: null,+ note: data.openTimecard.note+ });++ ctx.log(+ `people assignments — ${data.peopleAssignments.length}, absences — ${data.peopleAbsences.length}`+ );+ const plantId = need(ctx.refs.locations, "Plant", "location");+ for (const spec of data.peopleAssignments) {+ await insertRow(ctx, "peopleAssignment", {+ locationId: plantId,+ workCenterId: need(ctx.refs.workCenters, spec.workCenter, "work center"),+ employeeId: ctx.userId,+ date: resolveDate(ctx.anchor, spec.dayOffset),+ shiftId: need(ctx.refs.shifts, spec.shift, "shift"),+ overtimeHours: spec.overtimeHours ?? 0,+ note: spec.note+ });+ }+ for (const spec of data.peopleAbsences) {+ await insertRow(ctx, "peopleAbsence", {+ employeeId: ctx.userId,+ date: resolveDate(ctx.anchor, spec.dayOffset),+ shiftId: spec.shift ? need(ctx.refs.shifts, spec.shift, "shift") : null,+ note: spec.note+ });+ }++ // suggestion has no createdBy; userId is the submitting user (null = anonymous).+ for (const spec of data.suggestions) {+ await insertRow(ctx, "suggestion", {+ suggestion: spec.suggestion,+ emoji: spec.emoji,+ path: spec.path,+ tags: spec.tags ?? [],+ userId: ctx.userId+ });+ }++ // insertNote writes the rich-text form's HTML into `note` and leaves+ // noteRichText at its '{}' default.+ for (const spec of data.notes) {+ await insertRow(ctx, "note", {+ documentId: ctx.userId,+ note: `<p>${escapeHtml(spec.text)}</p>`+ });+ }++ ctx.log(+ `user attributes — ${data.userAttributeCategories.length} categories, custom fields — ${data.customFields.length}`+ );+ for (const spec of data.userAttributeCategories) {+ await seedAttributeCategory(ctx, spec);+ }+ await seedCustomFields(ctx, data.customFields);++ ctx.log(`item serial sequences — ${data.serialSequences.length}`);+ for (const spec of data.serialSequences) {+ await insertRow(ctx, "itemSerialSequence", {+ itemId: need(ctx.refs.items, spec.item, "item").id,+ prefix: spec.prefix,+ suffix: spec.suffix ?? null,+ size: spec.size,+ next: spec.next,+ step: 1+ });+ }++ ctx.log(`print jobs — ${data.printJobs.length}`);+ for (const spec of data.printJobs) {+ await seedPrintJob(ctx, spec);+ }+}++// A global lookup (no companyId) — the label is its natural key.+async function attributeDataTypeId(+ ctx: Ctx,+ label: AttributeDataTypeLabel+): Promise<number> {+ const key = `attributeDataType:${label}`;+ const cached = ctx.refs.misc[key];+ if (cached) return Number(cached);+ const row = await maybeOne<{ id: number }>(+ ctx.client,+ `SELECT id FROM "attributeDataType" WHERE label = $1`,+ [label]+ );+ if (!row) throw new Error(`Seed: no attributeDataType labelled "${label}"`);+ ctx.refs.misc[key] = String(row.id);+ return row.id;+}++// The wipe keeps userAttributeCategory (and userAttribute / userAttributeValue+// have no companyId), so a re-apply adopts the category and attributes by name+// and upserts the value instead of stacking duplicates.+async function seedAttributeCategory(+ ctx: Ctx,+ spec: UserAttributeCategorySpec+): Promise<void> {+ const existing = await maybeOne<{ id: string }>(+ ctx.client,+ `SELECT id FROM "userAttributeCategory"+ WHERE "companyId" = $1 AND name = $2 ORDER BY "createdAt" LIMIT 1`,+ [ctx.companyId, spec.name]+ );+ let categoryId: string;+ if (existing) {+ categoryId = existing.id;+ await ctx.client.query(+ `UPDATE "userAttributeCategory"+ SET emoji = $3, public = $4, active = true, "updatedBy" = $5+ WHERE id = $1 AND "companyId" = $2`,+ [categoryId, ctx.companyId, spec.emoji, spec.public, ctx.userId]+ );+ } else {+ categoryId = await insertId(ctx, "userAttributeCategory", {+ name: spec.name,+ emoji: spec.emoji,+ public: spec.public+ });+ }++ for (const [index, attribute] of spec.attributes.entries()) {+ const columns = {+ sortOrder: index + 1,+ attributeDataTypeId: await attributeDataTypeId(ctx, attribute.dataType),+ listOptions: attribute.dataType === "List" ? attribute.listOptions : null,+ canSelfManage: attribute.canSelfManage ?? false+ };+ const found = await maybeOne<{ id: string }>(+ ctx.client,+ `SELECT ua.id FROM "userAttribute" ua+ JOIN "userAttributeCategory" c ON c.id = ua."userAttributeCategoryId"+ WHERE c."companyId" = $1 AND ua."userAttributeCategoryId" = $2 AND ua.name = $3+ ORDER BY ua."createdAt" LIMIT 1`,+ [ctx.companyId, categoryId, attribute.name]+ );+ let attributeId: string;+ if (found) {+ attributeId = found.id;+ await ctx.client.query(+ `UPDATE "userAttribute"+ SET "sortOrder" = $2, "attributeDataTypeId" = $3, "listOptions" = $4,+ "canSelfManage" = $5, active = true, "updatedBy" = $6+ WHERE id = $1`,+ [+ attributeId,+ columns.sortOrder,+ columns.attributeDataTypeId,+ columns.listOptions,+ columns.canSelfManage,+ ctx.userId+ ]+ );+ } else {+ attributeId = await insertId(ctx, "userAttribute", {+ name: attribute.name,+ userAttributeCategoryId: categoryId,+ ...columns+ });+ }++ // Every value column is written, so a re-apply that changes an+ // attribute's type still satisfies the single-value CHECK.+ const value = {+ valueBoolean: attribute.dataType === "Yes/No" ? attribute.value : null,+ valueDate:+ attribute.dataType === "Date"+ ? resolveDate(ctx.anchor, attribute.valueOffset)+ : null,+ valueNumeric: attribute.dataType === "Numeric" ? attribute.value : null,+ valueText:+ attribute.dataType === "List" || attribute.dataType === "Text"+ ? attribute.value+ : null,+ valueUser: attribute.dataType === "User" ? ctx.userId : null,+ valueFile: null+ };+ await insertRow(+ ctx,+ "userAttributeValue",+ { userAttributeId: attributeId, userId: ctx.userId, ...value },+ {+ onConflict: `("userAttributeId", "userId") DO UPDATE SET+ "valueBoolean" = EXCLUDED."valueBoolean", "valueDate" = EXCLUDED."valueDate",+ "valueNumeric" = EXCLUDED."valueNumeric", "valueText" = EXCLUDED."valueText",+ "valueUser" = EXCLUDED."valueUser", "valueFile" = EXCLUDED."valueFile",+ "updatedBy" = EXCLUDED."createdBy"`+ }+ );+ }+}++// customField survives the wipe; UNIQUE (table, name, companyId) is the adopt key.+async function seedCustomFields(+ ctx: Ctx,+ specs: CustomFieldSpec[]+): Promise<void> {+ const perTable = new Map<string, number>();+ for (const spec of specs) {+ const sortOrder = (perTable.get(spec.table) ?? 0) + 1;+ perTable.set(spec.table, sortOrder);+ await insertRow(+ ctx,+ "customField",+ {+ table: spec.table,+ name: spec.name,+ dataTypeId: await attributeDataTypeId(ctx, spec.dataType),+ listOptions: spec.listOptions ?? null,+ sortOrder+ },+ {+ onConflict: `("table", name, "companyId") DO UPDATE SET+ "dataTypeId" = EXCLUDED."dataTypeId", "listOptions" = EXCLUDED."listOptions",+ "sortOrder" = EXCLUDED."sortOrder", active = true, "updatedBy" = EXCLUDED."createdBy"`+ }+ );+ }+}++async function seedPrintJob(ctx: Ctx, spec: PrintJobSpec): Promise<void> {+ const route = ctx.dataset.foundation.printerRoute;+ if (!route) {+ throw new Error("Seed: print jobs need foundation.printerRoute");+ }+ if (route.format !== "zpl") {+ throw new Error(+ `Seed: print jobs render ZPL; the route is "${route.format}"`+ );+ }++ let sourceDocumentId: string;+ let readableId: string;+ const { source } = spec;+ if (source.kind === "Receipt") {+ sourceDocumentId = need(ctx.refs.documents, source.receipt, "receipt");+ readableId = (+ await one<{ readableId: string }>(+ ctx.client,+ `SELECT "receiptId" AS "readableId" FROM receipt WHERE id = $1 AND "companyId" = $2`,+ [sourceDocumentId, ctx.companyId]+ )+ ).readableId;+ } else if (source.kind === "Job") {+ sourceDocumentId = need(ctx.refs.documents, `job:${source.job}`, "job");+ readableId = (+ await one<{ readableId: string }>(+ ctx.client,+ `SELECT "jobId" AS "readableId" FROM job WHERE id = $1 AND "companyId" = $2`,+ [sourceDocumentId, ctx.companyId]+ )+ ).readableId;+ } else {+ sourceDocumentId = need(ctx.refs.shelves, source.shelf, "shelf");+ readableId = source.shelf;+ }++ const label = spec.item ? [readableId, spec.item] : [readableId];+ // What the built-in renderer hands the printer: text lines plus a Code 128 of the id.+ const content = [+ "^XA^CI28",+ ...label.map(+ (text, index) =>+ `^FO40,${40 + index * 50}^A0N,${index === 0 ? 40 : 30},${index === 0 ? 40 : 30}^FD${text}^FS`+ ),+ `^FO40,${50 + label.length * 50}^BCN,80,Y,N,N^FD${readableId}^FS`,+ "^XZ"+ ].join("\n");++ const createdAt = at(ctx, spec.at);+ await insertRow(ctx, "printJob", {+ status: spec.status,+ contentType: route.format,+ content,+ printerUrl: route.printerUrl,+ sourceDocument: source.kind,+ sourceDocumentId,+ sourceDocumentReadableId: readableId,+ description: label.join(" — "),+ origin: spec.origin,+ error: spec.error ?? null,+ attempts: spec.attempts,+ createdAt,+ updatedAt: spec.status === "queued" ? null : createdAt,+ completedAt: spec.status === "completed" ? createdAt : null+ });+}++function at(ctx: Ctx, instant: InstantSpec): string {+ return resolveTimestamp(ctx.anchor, instant.offset, instant.time);+}++function escapeHtml(text: string): string {+ return text+ .replace(/&/g, "&")+ .replace(/</g, "<")+ .replace(/>/g, ">");+}++// Schedules and dispatches take their work center's location (the plant, or+// HQ for its one work center), as the create forms default it.+async function workCenterLocation(+ ctx: Ctx,+ workCenterId: string+): Promise<string> {+ const row = await one<{ locationId: string }>(+ ctx.client,+ `SELECT "locationId" FROM "workCenter" WHERE id = $1 AND "companyId" = $2`,+ [workCenterId, ctx.companyId]+ );+ return row.locationId;+}++async function seedSchedule(+ ctx: Ctx,+ spec: MaintenanceScheduleSpec+): Promise<void> {+ const weekends = spec.weekends ?? true;+ const workCenterId = need(+ ctx.refs.workCenters,+ spec.workCenter,+ "work center"+ );+ const scheduleId = await insertId(ctx, "maintenanceSchedule", {+ name: spec.name,+ description: spec.description,+ workCenterId,+ locationId: await workCenterLocation(ctx, workCenterId),+ frequency: spec.frequency,+ priority: spec.priority,+ estimatedDuration: spec.estimatedDuration,+ takesWorkCenterOffline: spec.takesWorkCenterOffline ?? false,+ nextDueAt: resolveTimestamp(ctx.anchor, spec.nextDueOffset, "00:00:00"),+ saturday: weekends,+ sunday: weekends,+ active: true+ });+ ctx.refs.misc[`maintenanceSchedule:${spec.key}`] = scheduleId;++ for (const part of spec.spareParts ?? []) {+ const item = need(ctx.refs.items, part.item, "item");+ await insertRow(ctx, "maintenanceScheduleItem", {+ maintenanceScheduleId: scheduleId,+ itemId: item.id,+ quantity: part.quantity,+ unitOfMeasureCode: item.unitOfMeasureCode+ });+ }+}++const ASSIGNED_STATUSES = new Set(["Assigned", "In Progress", "Completed"]);++async function seedDispatch(+ ctx: Ctx,+ spec: MaintenanceDispatchSpec+): Promise<void> {+ const workCenterId = need(+ ctx.refs.workCenters,+ spec.workCenter,+ "work center"+ );+ const locationId = await workCenterLocation(ctx, workCenterId);+ const scheduleId = spec.schedule+ ? need(ctx.refs.misc, `maintenanceSchedule:${spec.schedule}`)+ : undefined;+ const completedAt =+ spec.status === "Completed" && spec.actualEnd+ ? at(ctx, spec.actualEnd)+ : undefined;++ // Inserted in its final state: sync_on_maintenance_dispatch_complete only+ // fires on UPDATE, and duration is GENERATED from the actual start/end.+ const dispatchId = await insertId(ctx, "maintenanceDispatch", {+ maintenanceDispatchId: await nextSequence(ctx, "maintenanceDispatch"),+ status: spec.status,+ priority: spec.priority,+ severity: spec.severity,+ source: spec.source,+ oeeImpact: spec.oeeImpact,+ workCenterId,+ locationId,+ maintenanceScheduleId: scheduleId,+ nonConformanceId: spec.nonConformance+ ? need(ctx.refs.documents, spec.nonConformance, "NCR")+ : undefined,+ suspectedFailureModeId: spec.suspectedFailureMode+ ? await bootstrapIdByName(+ ctx,+ "maintenanceFailureMode",+ spec.suspectedFailureMode+ )+ : undefined,+ actualFailureModeId: spec.actualFailureMode+ ? await bootstrapIdByName(+ ctx,+ "maintenanceFailureMode",+ spec.actualFailureMode+ )+ : undefined,+ plannedStartTime: at(ctx, spec.plannedStart),+ plannedEndTime: at(ctx, spec.plannedEnd),+ actualStartTime: spec.actualStart ? at(ctx, spec.actualStart) : undefined,+ actualEndTime: completedAt,+ completedAt,+ assignee: ASSIGNED_STATUSES.has(spec.status) ? ctx.userId : undefined,+ takesWorkCenterOffline: spec.takesWorkCenterOffline ?? false,+ content: RICH(spec.content),+ createdAt: at(ctx, spec.created),+ updatedBy: ctx.userId+ });+ ctx.refs.misc[`maintenanceDispatch:${spec.key}`] = dispatchId;++ // The generate-maintenance job links a scheduled dispatch to its work center.+ if (spec.source === "Scheduled") {+ await insertRow(ctx, "maintenanceDispatchWorkCenter", {+ maintenanceDispatchId: dispatchId,+ workCenterId+ });+ }++ // The MES Start action opens a labor event; Complete closes it at completedAt.+ if (spec.actualStart) {+ await insertRow(ctx, "maintenanceDispatchEvent", {+ maintenanceDispatchId: dispatchId,+ employeeId: ctx.userId,+ workCenterId,+ startTime: at(ctx, spec.actualStart),+ endTime: completedAt+ });+ }++ for (const comment of spec.comments ?? []) {+ await insertRow(ctx, "maintenanceDispatchComment", {+ maintenanceDispatchId: dispatchId,+ comment+ });+ }++ // Mirrors the `issue` edge function's untracked path: a dispatch item+ // (totalCost is GENERATED) plus a negative Consumption ledger row.+ for (const part of spec.spareParts ?? []) {+ const item = need(ctx.refs.items, part.item, "item");+ if (item.unitCost <= 0) {+ throw new Error(+ `Seed: dispatch "${spec.key}" spare part "${part.item}" has no standard cost`+ );+ }+ const dispatchItemId = await insertId(ctx, "maintenanceDispatchItem", {+ maintenanceDispatchId: dispatchId,+ itemId: item.id,+ quantity: part.quantity,+ unitOfMeasureCode: item.unitOfMeasureCode,+ unitCost: item.unitCost+ });+ await insertRow(ctx, "itemLedger", {+ postingDate: resolveDate(+ ctx.anchor,+ (spec.actualEnd ?? spec.plannedStart).offset+ ),+ entryType: "Consumption",+ documentType: "Maintenance Consumption",+ documentId: dispatchId,+ documentLineId: dispatchItemId,+ itemId: item.id,+ quantity: -part.quantity,+ locationId,+ storageUnitId: need(ctx.refs.shelves, part.shelf, "shelf")+ });+ }+}++/** The columns the question editor leaves per type (resources.models.ts + $id.questions.new). */+function questionColumns(q: TrainingQuestionSpec): Record<string, unknown> {+ const base = {+ options: null as string[] | null,+ correctAnswers: null as string[] | null,+ correctBoolean: false,+ matchingPairs: JSON.stringify([]),+ correctNumber: null as number | null,+ tolerance: null as number | null+ };+ switch (q.type) {+ case "MultipleChoice":+ return { ...base, options: q.options, correctAnswers: [q.correct] };+ case "MultipleAnswers":+ return { ...base, options: q.options, correctAnswers: q.correct };+ case "TrueFalse":+ return { ...base, correctBoolean: q.answer };+ case "MatchingPairs":+ return { ...base, matchingPairs: JSON.stringify(q.pairs) };+ case "Numerical":+ return {+ ...base,+ correctNumber: q.answer,+ tolerance: q.tolerance ?? null+ };+ }+}++async function seedTraining(ctx: Ctx, spec: TrainingSpec): Promise<void> {+ const trainingId = await insertId(ctx, "training", {+ name: spec.name,+ description: spec.description,+ status: spec.status,+ frequency: spec.frequency,+ type: spec.type,+ estimatedDuration: spec.estimatedDuration,+ content: JSON.stringify({+ type: "doc",+ content: spec.content.map((text) => ({+ type: "paragraph",+ content: [{ type: "text", text }]+ }))+ })+ });++ for (const [index, q] of spec.questions.entries()) {+ await insertRow(ctx, "trainingQuestion", {+ trainingId,+ question: q.question,+ type: q.type,+ sortOrder: index + 1,+ ...questionColumns(q)+ });+ }++ if (!spec.assignment) return;+ // A user id is its own identity group, which users_for_groups expands.+ const assignmentId = await insertId(ctx, "trainingAssignment", {+ trainingId,+ groupIds: [ctx.userId]+ });+ const { completedOffset } = spec.assignment;+ if (completedOffset === undefined) return;+ if (spec.frequency !== "Once") {+ throw new Error(+ `Seed: training "${spec.name}": a completion needs a "Once" training (recurring ones key on the current period)`+ );+ }+ // "Once" completions carry a NULL period — the status RPC's join key for them.+ await insertRow(ctx, "trainingCompletion", {+ trainingAssignmentId: assignmentId,+ employeeId: ctx.userId,+ completedAt: resolveTimestamp(ctx.anchor, completedOffset, "15:30:00"),+ completedBy: ctx.userId+ });}diff --git a/packages/database/src/datasets/tiers/11-workflows.ts b/packages/database/src/datasets/tiers/11-workflows.tsindex 915f9aa26b..74acb34831 100644--- a/packages/database/src/datasets/tiers/11-workflows.ts+++ b/packages/database/src/datasets/tiers/11-workflows.ts@@ -1,10 +1,7 @@-import { insertId, insertRow, one } from "../sql.ts";-import type { Ctx } from "../types.ts";-import {- EVENT_SOURCES,- FORMAT_VERSION,- type Node-} from "./workflow-definitions.ts";+import { resolveDate } from "../dates.ts";+import { insertId, insertRow, need, one } from "../sql.ts";+import type { Ctx, Node, WorkflowRunSpec } from "../types.ts";+import { EVENT_SOURCES, FORMAT_VERSION } from "./workflow-definitions.ts";// Wired exactly as the publish and activate routes do it, so a later change in the app// really fires them. Definitions must pass `validateDefinition` in @carbon/workflows —@@ -68,6 +65,7 @@ export async function runTier11(ctx: Ctx): Promise<void> {const data = ctx.dataset.workflows;const { userId } = ctx;const allEventIds: string[] = [];+ const publishedByName = new Map<string, PublishedWorkflow>();// The issue-creating workflow names a type, which is NOT NULL on the table.const issueType = await one<{ id: string }>(@@ -107,6 +105,11 @@ export async function runTier11(ctx: Ctx): Promise<void> {`UPDATE "workflow" SET "publishedVersionId" = $1 WHERE "id" = $2 AND "companyId" = $3`,[versionId, workflowId, ctx.companyId]);+ publishedByName.set(workflow.name, {+ workflowId,+ versionId,+ nodes: workflow.nodes+ });for (const row of triggerRowsFor(workflow.nodes)) {await insertRow(ctx, "workflowTriggerEvent", {@@ -121,4 +124,193 @@ export async function runTier11(ctx: Ctx): Promise<void> {const tables = await reconcileSubscriptions(ctx, allEventIds);ctx.log(`workflow subscriptions — ${tables.join(", ")}`);++ ctx.log(`workflow runs — ${data.runs.length}`);+ for (const [index, spec] of data.runs.entries()) {+ const workflow = publishedByName.get(spec.workflow);+ if (!workflow) {+ throw new Error(+ `Seed: workflow run "${spec.workflow}": not a published seed workflow`+ );+ }+ await seedRun(ctx, workflow, spec, `seed:${index + 1}`);+ }+}++type PublishedWorkflow = {+ workflowId: string;+ versionId: string;+ nodes: Node[];+};++type EntityValue = {+ kind: "entity";+ of: string;+ id: string;+ row?: Record<string, unknown>;+};++/**+ * Millisecond offsets are fixed so durationMs agrees with the timestamps. A+ * Skipped run settles at `load`: never claimed, no step rows.+ */+async function seedRun(+ ctx: Ctx,+ workflow: PublishedWorkflow,+ spec: WorkflowRunSpec,+ sourceEventId: string+): Promise<void> {+ const trigger = workflow.nodes.find((node) => node.type === "trigger");+ const eventId = ((trigger?.data.events as string[] | undefined) ?? [])[0];+ if (!trigger || !eventId) {+ throw new Error(`Seed: workflow "${spec.workflow}" has no trigger event`);+ }+ const source = EVENT_SOURCES[eventId];+ if (!source) {+ throw new Error(+ `Seed: workflow run "${spec.workflow}": event "${eventId}" has no source table to name the triggering record`+ );+ }+ const recordId = need(ctx.refs.documents, spec.triggerRef, "document");+ const second = `${resolveDate(ctx.anchor, spec.at.offset)}T${spec.at.time}`;+ const ms = (n: number) => `${second}.${String(n).padStart(3, "0")}Z`;++ const record: EntityValue = {+ kind: "entity",+ of: source.table,+ id: recordId,+ row: await triggerRow(ctx, source.table, recordId)+ };++ const claimedAt = 250;+ const lastStepEnd = 270 + spec.steps.length * 360;+ const settledAt = spec.status === "Skipped" ? 180 : lastStepEnd + 60;+ const runId = await insertId(ctx, "workflowRun", {+ workflowId: workflow.workflowId,+ workflowVersionId: workflow.versionId,+ eventId,+ sourceEventId,+ triggerTable: source.table,+ triggerRecordId: recordId,+ ownerId: ctx.userId,+ status: spec.status,+ statusReason: spec.statusReason,+ isTest: false,+ startedAt: spec.status === "Skipped" ? undefined : ms(claimedAt),+ completedAt: ms(settledAt),+ durationMs: settledAt - (spec.status === "Skipped" ? 0 : claimedAt),+ createdAt: ms(0)+ });+ if (spec.status === "Skipped") return;++ await insertRow(ctx, "workflowStepRun", {+ runId,+ sequence: 0,+ nodeId: trigger.id,+ nodeType: "trigger",+ status: "Succeeded",+ output: JSON.stringify({ record }),+ startedAt: ms(260),+ completedAt: ms(270),+ durationMs: 10+ });++ for (const [index, step] of spec.steps.entries()) {+ const node = workflow.nodes.find((n) => n.id === step.nodeId);+ if (!node || node.type === "trigger") {+ throw new Error(+ `Seed: workflow run "${spec.workflow}": "${step.nodeId}" is not an action node of the definition`+ );+ }+ const start = 270 + index * 360;+ const inputs = (node.data.inputs ?? {}) as Record<string, unknown>;+ const settled = actionOutcome(node, record);+ await insertRow(ctx, "workflowStepRun", {+ runId,+ sequence: index + 1,+ nodeId: node.id,+ nodeType: node.type,+ status: step.status,+ statusReason: step.status === "Succeeded" ? settled.summary : undefined,+ input: JSON.stringify({+ inputs,+ resolved: resolveInputs(inputs, trigger.id, record)+ }),+ output:+ step.status === "Succeeded"+ ? JSON.stringify(settled.output)+ : undefined,+ error: step.error,+ startedAt: ms(start + 10),+ completedAt: ms(start + 360),+ durationMs: 350+ });+ }+}++/** Mirrors the loader's entity row for the triggering record. */+async function triggerRow(+ ctx: Ctx,+ table: string,+ id: string+): Promise<Record<string, unknown>> {+ if (table !== "salesOrder") {+ throw new Error(`Seed: no trigger row shape for "${table}" runs`);+ }+ return one<Record<string, unknown>>(+ ctx.client,+ `SELECT id, "salesOrderId", "customerId", status,+ "orderDate"::text AS "orderDate", "currencyCode"+ FROM "salesOrder" WHERE id = $1 AND "companyId" = $2`,+ [id, ctx.companyId]+ );+}++function resolveInputs(+ inputs: Record<string, unknown>,+ triggerId: string,+ record: EntityValue+): Record<string, EntityValue> {+ const resolved: Record<string, EntityValue> = {};+ for (const [name, raw] of Object.entries(inputs)) {+ const value = raw as {+ kind?: string;+ nodeId?: string;+ output?: string;+ type?: { kind?: string; of?: string };+ value?: unknown;+ };+ if (value.kind === "ref" && value.nodeId === triggerId) {+ resolved[name] = record;+ } else if (+ value.kind === "literal" &&+ value.type?.kind === "entity" &&+ typeof value.type.of === "string" &&+ typeof value.value === "string"+ ) {+ resolved[name] = { kind: "entity", of: value.type.of, id: value.value };+ } else {+ throw new Error(`Seed: cannot resolve workflow input "${name}"`);+ }+ }+ return resolved;+}++/** Mirrors what actions/update.ts settles with. */+function actionOutcome(+ node: Node,+ record: EntityValue+): { output: unknown; summary: string } {+ const action = node.data.action as string | undefined;+ if (!action?.endsWith(".update")) {+ throw new Error(`Seed: no seeded outcome for action "${action}"`);+ }+ const target = action.slice(0, -".update".length);+ const fields = Object.keys(+ (node.data.inputs ?? {}) as Record<string, unknown>+ ).filter((name) => name !== target).length;+ return {+ output: { record: { kind: "entity", of: target, id: record.id } },+ summary: `Updated ${fields} field(s).`+ };}diff --git a/packages/database/src/datasets/tiers/12-planning.ts b/packages/database/src/datasets/tiers/12-planning.tsindex 19ffec76c4..fbf1485e01 100644--- a/packages/database/src/datasets/tiers/12-planning.ts+++ b/packages/database/src/datasets/tiers/12-planning.ts@@ -37,11 +37,7 @@ export async function runTier12(ctx: Ctx): Promise<void> {// ── 1. itemPlanning: Buy items → Fixed Reorder Quantity ─────────────────────ctx.log("itemPlanning — Buy items reorder policy");for (const readableId of data.buyItemIds) {- const item = refs.items[readableId];- if (!item) {- ctx.log(` skip ${readableId} — not in refs`);- continue;- }+ const item = need(refs.items, readableId, "planning buy item");await client.query(`UPDATE "itemPlanning"SET "reorderingPolicy" = 'Fixed Reorder Quantity',@@ -57,11 +53,7 @@ export async function runTier12(ctx: Ctx): Promise<void> {// ── 2. itemPlanning: Make items → Fixed Reorder Quantity ─────────────────────ctx.log("itemPlanning — Make items reorder policy");for (const readableId of data.makeItemIds) {- const item = refs.items[readableId];- if (!item) {- ctx.log(` skip ${readableId} — not in refs`);- continue;- }+ const item = need(refs.items, readableId, "planning make item");await client.query(`UPDATE "itemPlanning"SET "reorderingPolicy" = 'Fixed Reorder Quantity',@@ -80,8 +72,12 @@ export async function runTier12(ctx: Ctx): Promise<void> {// promisedDate must fall inside the 48-week planning horizon.ctx.log("SO — open order for buy-item demand");const order = data.demandOrder;- const customerId = refs.customers[order.customer]!;- const customerLocationId = refs.misc[`cloc:${order.customer}`] ?? null;+ const customerId = need(refs.customers, order.customer, "customer");+ const customerLocationId = need(+ refs.misc,+ `cloc:${order.customer}`,+ "customer location"+ );const promisedDate = resolveDate(ctx.anchor, order.promisedDateOffset);@@ -115,7 +111,7 @@ export async function runTier12(ctx: Ctx): Promise<void> {companyId});for (const line of order.lines) {- const item = refs.items[line.item]!;+ const item = need(refs.items, line.item, "demand order item");await insertId(ctx, "salesOrderLine", {salesOrderId: so,salesOrderLineType: line.salesOrderLineType,@@ -175,11 +171,7 @@ export async function runTier12(ctx: Ctx): Promise<void> {ctx.log("demandProjection — weekly forecast for make parts");for (const spec of data.demandProjections) {- const item = refs.items[spec.readableId];- if (!item) {- ctx.log(` skip ${spec.readableId} — not in refs`);- continue;- }+ const item = need(refs.items, spec.readableId, "demand projection item");for (let week = 0; week < spec.quantities.length; week++) {const periodId = periodIds[week];if (!periodId) break;@@ -195,6 +187,44 @@ export async function runTier12(ctx: Ctx): Promise<void> {}}+ // ── 5. HQ: one reorder policy per planning screen + a projection ────────────+ // Every other planning row is at the plant; without these the planning+ // screens render empty whenever the location picker is on HQ.+ ctx.log("itemPlanning + demandProjection — HQ");+ const hqId = need(refs.locations, "HQ", "location");+ for (const readableId of data.hq.reorderItemIds) {+ const item = need(refs.items, readableId, "HQ planning item");+ const updated = await client.query(+ `UPDATE "itemPlanning"+ SET "reorderingPolicy" = 'Fixed Reorder Quantity',+ "reorderPoint" = 2,+ "reorderQuantity" = 4,+ "updatedBy" = $1,+ "updatedAt" = NOW()+ WHERE "itemId" = $2 AND "companyId" = $3 AND "locationId" = $4`,+ [userId, item.id, companyId, hqId]+ );+ if (updated.rowCount !== 1) {+ throw new Error(+ `Seed: item "${readableId}" has no itemPlanning row at HQ to set a reorder policy on`+ );+ }+ }+ for (const spec of data.hq.demandProjections) {+ const item = need(refs.items, spec.readableId, "HQ demand projection item");+ for (let week = 0; week < spec.quantities.length; week++) {+ const periodId = periodIds[week];+ if (!periodId) break;+ await insertMaybe(ctx, "demandProjection", {+ itemId: item.id,+ locationId: hqId,+ 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/datasets/tiers/workflow-definitions.ts b/packages/database/src/datasets/tiers/workflow-definitions.tsindex f8a3a11fa1..86fb861202 100644--- a/packages/database/src/datasets/tiers/workflow-definitions.ts+++ b/packages/database/src/datasets/tiers/workflow-definitions.ts@@ -1,4 +1,4 @@-// The shape every dataset's starter workflows are written in. Split out from the tier that+// Every dataset's starter workflows (shape: `types/workflows.ts`). Split out from the tier that// writes them so `@carbon/workflows` can import it and assert every definition still passes// `validateDefinition` — the cycle blocks that check from running on this side.@@ -21,7 +21,8 @@ export const SEED_WORKFLOW_BUILDERS = {export const FORMAT_VERSION = 4;/** Mirrors each event's `match` block in the workflow catalog, spelled out here for the- * same package-cycle reason. `null` is a business moment: it has no table to subscribe to. */+ * same package-cycle reason; `seed-workflows.test.ts` in `@carbon/ee` pins the two together.+ * `null` is a business moment: it has no table to subscribe to. */export const EVENT_SOURCES: Record<string,{ table: string; operation: string } | null@@ -42,29 +43,3 @@ export const EVENT_SOURCES: Record<},"production.jobReleased": null};--export type Node = {- id: string;- name: string;- type: string;- position: { x: number; y: number };- expanded?: boolean;- data: Record<string, unknown>;-};--export type Edge = {- id: string;- source: string;- sourceHandle: string;- target: string;- targetHandle: string;-};--export type SeedWorkflow = {- name: string;- description: string;- /** Only the simplest one ships published; the rest are there to read and publish deliberately. */- published: boolean;- nodes: Node[];- edges: Edge[];-};diff --git a/packages/database/src/datasets/types.ts b/packages/database/src/datasets/types.tsindex d57b27006a..f1907b7ce8 100644--- a/packages/database/src/datasets/types.ts+++ b/packages/database/src/datasets/types.ts@@ -1,33 +1,41 @@import type { CalendarDate } from "@internationalized/date";import type { PoolClient } from "pg";-import type { DayOffset } from "./dates.ts";-import type { ItemSpec, MethodType, OperationType } from "./helpers/items.ts";import { maybeOne, one } from "./sql.ts";-import type { SeedWorkflow } from "./tiers/workflow-definitions.ts";-// Must stay in step with DATASETS in index.ts — a key with no dataset is unusable.-export type DatasetKey = "satellite" | "robotics" | "precision" | "motor";--export type { ItemSpec };+/** Signed days relative to the dataset anchor. Negative = in the past. */+export type DayOffset = number;-// ----------------------------------------------------------------------------// Slice shapes — the contract every dataset's data files implement.-// ---------------------------------------------------------------------------+/** `time` is a UTC "HH:MM:SS". */+export type InstantSpec = { offset: DayOffset; time: string };export type ProcedureStepSpec = {name: string;- type: "Task" | "Checkbox" | "Measurement" | "Value" | "List" | "Person";+ /** Timestamp / File / Inspection collect their payload in MES at runtime, so the row needs no upload. */+ type:+ | "Task"+ | "Checkbox"+ | "Measurement"+ | "Value"+ | "List"+ | "Person"+ | "Timestamp"+ | "File"+ | "Inspection";instruction: string;required?: boolean;unitOfMeasureCode?: string;minValue?: number;maxValue?: number;+ listValues?: string[];+ fileTypes?: string[];};export type ProcedureSpec = {name: string;process: string;description: string;+ /** Written on every version — a new version copies them. */+ parameters?: { key: string; value: string }[];versions: Array<{version: number;status: "Draft" | "Active" | "Archived";@@ -57,6 +65,10 @@ export type CustomerSpec = {status: string;phone: string;website: string;+ /** Must be a currency bootstrap seeds. Defaults to "USD". */+ currencyCode?: string;+ /** Defaults to Net 30. */+ paymentTerm?: string;};export type SupplierSpec = {@@ -64,6 +76,12 @@ export type SupplierSpec = {type: string;phone: string;website: string;+ /** Omitted = Active, written explicitly (the column has no default). */+ status?: "Active" | "Inactive" | "Pending" | "Rejected";+ /** Must be a currency bootstrap seeds. Defaults to "USD". */+ currencyCode?: string;+ /** Defaults to Net 30. */+ paymentTerm?: string;};export type ContactSpec = {@@ -82,6 +100,13 @@ export type SupplierProcessSpec = {process: string;};+export type PartnerSpec = {+ /** A supplier with a supplierContact — its supplierLocation is the partner id. */+ supplier: string;+ ability: string;+ hoursPerWeek: number;+};+export type ContractorSpec = {firstName: string;lastName: string;@@ -103,6 +128,14 @@ export type ShiftSpec = {sunday?: boolean;};+export type EmployeeJobSpec = {+ title: string;+ department: string;+ /** Also written as the user's employeeShift. */+ shift: string;+ startDateOffset: DayOffset;+};+export type PlantSpec = {name: string;addressLine1: string;@@ -146,11 +179,34 @@ export type ContractorAgencySpec = {phone: string;};+export type HolidaySpec = {+ name: string;+ /** Positive and distinct — holiday is UNIQUE (date, companyId). */+ dateOffset: DayOffset;+};++export type TagSpec = {+ name: string;+ table: string;+};++/** Children name parents in THIS spec, never global rows, so validation needs no database. */+export type MaterialTaxonomySpec = {+ substances: { name: string; code: string }[];+ forms: { name: string; code: string }[];+ types: { name: string; code: string; substance: string; form: string }[];+ grades: { name: string; substance: string }[];+ finishes: { name: string; substance: string }[];+ dimensions: { name: string; form: string; isMetric?: boolean }[];+};+export type FoundationData = {departments: string[];abilities: string[];processes: ProcessSpec[];workCenters: WorkCenterSpec[];+ /** Maintenance only (no shift, process or operations) — the ERP's maintenance lists open at HQ. */+ hqWorkCenter: WorkCenterSpec;customers: CustomerSpec[];customerContacts: CustomerContactSpec[];suppliers: SupplierSpec[];@@ -166,13 +222,21 @@ export type FoundationData = {costCenters: string[];noQuoteReasons: string[];contractors: ContractorSpec[];+ partners: PartnerSpec[];plant: PlantSpec;+ /** Created at the plant, where every work center lives. */shifts: ShiftSpec[];+ /** [work center, shift] — every work center needs at least one. */+ workCenterShifts: Array<[string, string]>;+ employeeJob: EmployeeJobSpec;warehouses: WarehouseSpec[];storageTypes: string[];/** Insertion order matters — a parent shelf must precede its children. */shelves: ShelfSpec[];printerRoute: PrinterRouteSpec | null;+ holidays: HolidaySpec[];+ tags: TagSpec[];+ materialTaxonomy: MaterialTaxonomySpec;/** Must be one of shippingMethods; applied to every customer and supplier. */defaultShippingMethod: string;contractorAgency: ContractorAgencySpec | null;@@ -183,6 +247,57 @@ export type FoundationData = {partyAddressCountryCode: string;};+export type ItemType =+ | "Part"+ | "Material"+ | "Tool"+ | "Consumable"+ | "Service"+ | "Fixture";++/** Names resolve against the dataset's own taxonomy, never the global bootstrap rows. */+export type MaterialClassificationSpec = {+ substance?: string;+ form?: string;+ materialType?: string;+ grade?: string;+ finish?: string;+ dimension?: string;+};++export type ItemSpec = {+ readableId: string;+ revision?: string;+ name: string;+ type: ItemType;+ replenishment?: "Buy" | "Make" | "Buy and Make";+ defaultMethodType?:+ | "Pull from Inventory"+ | "Purchase to Order"+ | "Make to Order";+ trackingType?: "Inventory" | "Non-Inventory" | "Serial" | "Batch";+ unitOfMeasureCode?: string;+ standardCost?: number;+ unitSalePrice?: number;+ leadTime?: number;+ description?: string;+ /** Revision ladders seed inactive rungs. */+ active?: boolean;+ revisionStatus?: "Design" | "Prototype" | "Production" | "Obsolete";+ material?: MaterialClassificationSpec;+};++export type MethodType =+ | "Make to Order"+ | "Pull from Inventory"+ | "Purchase to Order";++export type OperationType =+ | "Process"+ | "Assembly"+ | "Inspection"+ | "Outside Processing";+export type SupplierLinkSpec = {supplier: string;item: string;@@ -217,6 +332,10 @@ export type BopOperationSpec = {operationUnitCost?: number;/** key into ctx.refs.misc, e.g. "procedure:TVAC Qualification Test" */procedure?: string;+ tools?: { tool: string; quantity: number }[];+ parameters?: { key: string; value: string }[];+ /** Required on (and only on) an "Inspection" operation. */+ inspectionPlan?: string;};export type MakeMethodSpec = {@@ -226,6 +345,154 @@ export type MakeMethodSpec = {bop: BopOperationSpec[];};+/**+ * The predecessor needs opening stock so "Consume First" is demoable; the successor+ * must stay out of every BOM — job creation and picking redirect to it live.+ */+export type SupersessionSpec = {+ predecessor: string;+ successor: string;+ mode: "Consume First" | "Prefer New" | "Stock Only" | "No Stock";+ /** 1 old = N new. Default 1. */+ conversionFactor?: number;+ successorEffectivityOffset?: DayOffset;+ discontinuationOffset?: DayOffset;+};++export type CustomerPartSpec = {+ item: string;+ customer: string;+ customerPartId: string;+ customerRevision?: string;+};++export type PriceOverrideSpec = {+ item: string;+ customer: string;+ breaks: { quantity: number; overridePrice: number }[];+ notes?: string;+};++/** No customer, customer type or item = every sale. */+export type PricingRuleSpec = {+ name: string;+ ruleType: "Discount" | "Markup";+ amountType: "Percentage" | "Fixed";+ /** Percent (0–100] for Percentage; a per-unit amount for Fixed. */+ amount: number;+ customer?: string;+ customerType?: string;+ items?: string[];+ minQuantity?: number;+ priority?: number;+};++export type ConfigurationParameterSpec = {+ key: string;+ label: string;+ dataType: "numeric" | "list" | "boolean";+ /** Required when dataType is "list". */+ listOptions?: string[];+};++/** The app keys a rule `${field}:${methodRowId}`, so the tier resolves the row. */+export type ConfigurationRuleSpec = {+ /** `operation` is a 1-based BOP position. */+ target: { component: string } | { operation: number };+ field: "quantity" | "methodType" | "laborTime" | "setupTime" | "machineTime";+ /** Body of `configure(params)`; reads only this configuration's parameter keys. */+ code: string;+};++export type ConfigurationSpec = {+ item: string;+ group: string;+ parameters: ConfigurationParameterSpec[];+ rules: ConfigurationRuleSpec[];+};++export type RuleOperator =+ | "eq"+ | "neq"+ | "in"+ | "notIn"+ | "isSet"+ | "isNotSet"+ | "gt"+ | "lt";++/** The object forms resolve to ids when the tier runs. */+export type RuleConditionValue =+ | string+ | number+ | boolean+ | string[]+ | { storageType: string }+ | { customerTypes: string[] }+ | { location: "Plant" | "HQ" };++/** Conditions state what must hold: the rule fires when they do NOT (and when a field is unset). */+export type EnforcementRuleSpec = {+ name: string;+ description?: string;+ message: string;+ severity: "error" | "warn";+ match: "all" | "any" | "none";+ conditions: { field: string; op: RuleOperator; value?: RuleConditionValue }[];+} & (+ | {+ family: "sales";+ surfaces: ("quoteLine" | "salesOrderLine" | "salesInvoiceLine")[];+ items: string[];+ }+ | {+ family: "storage";+ targetType: "item";+ surfaces: (+ | "receipt"+ | "shipment"+ | "stockTransfer"+ | "warehouseTransfer"+ | "inventoryAdjustment"+ | "place"+ | "pick"+ )[];+ items: string[];+ }+ | {+ family: "storage";+ targetType: "workCenter";+ surfaces: (+ | "operationStart"+ | "operationFinish"+ | "materialIssue"+ | "materialReceive"+ )[];+ workCenters: string[];+ }+);++/** The new revisions are not registered in ctx.refs.items — later tiers keep the active one. */+export type RevisionLadderSpec = {+ item: string;+ /** Must differ from the active revision. */+ obsoleteRevision: string;+ nextRevision: string;+ nextStatus: "Design" | "Prototype";+};++/**+ * The BOP picker lists only plans whose partId is the item, so the receipt plans+ * of quality.inspections cannot serve an operation.+ */+export type InspectionPlanSpec = {+ key: string;+ item: string;+ drawingNumber: string;+ aql: number;+ features: InspectionFeatureSpec[];+};+export type ItemsData = {buyParts: ItemSpec[];materials: ItemSpec[];@@ -235,6 +502,31 @@ export type ItemsData = {makeParts: ItemSpec[];methods: MakeMethodSpec[];supplierLinks: SupplierLinkSpec[];+ /** Exactly one Consume First pair between two BUY parts per dataset. */+ supersessions: SupersessionSpec[];+ customerParts: CustomerPartSpec[];+ priceOverrides: PriceOverrideSpec[];+ pricingRules: PricingRuleSpec[];+ configuration: ConfigurationSpec;+ revisionLadder: RevisionLadderSpec[];+ inspectionPlans: InspectionPlanSpec[];+ enforcementRules: EnforcementRuleSpec[];+ batchProperties: BatchPropertySpec[];+ /**+ * Animated 3D work instructions built on a bundled CAD assembly, linked to+ * its item's Assembly operation before the method is released. Optional: a+ * dataset with no industryId has nowhere to resolve the model from.+ */+ assembly?: AssemblySpec;+};++/** sortOrder follows the item's authoring order. */+export type BatchPropertySpec = {+ item: string;+ label: string;+ dataType: "text" | "numeric" | "boolean" | "list" | "date";+ /** Required exactly when dataType is "list". */+ listOptions?: string[];};export type OpeningStockSpec = {@@ -245,25 +537,109 @@ export type OpeningStockSpec = {export type TrackedStockSpec = {item: string;- entities: Array<{ readableId: string; quantity: number }>;+ entities: Array<{+ readableId: string;+ quantity: number;+ /** Omitted = "Available". */+ status?: "Available" | "On Hold" | "Rejected" | "Scrapped";+ /**+ * Required iff "Scrapped": books a full-entity scrap (Scrap activity plus a+ * Negative Adjmt. ledger row out of `shelf`); the entity keeps its quantity.+ */+ scrap?: {+ /** Must hold the lot's opening stock. */+ shelf: string;+ reason: string;+ dateOffset: DayOffset;+ comment: string;+ };+ /** Batch items with a shelfLives spec only (validator-enforced). */+ expiresOffset?: DayOffset;+ }>;+};++/** The item must be Batch-tracked (expiry is per lot). */+export type ShelfLifeSpec = {+ item: string;+ days: number;};export type KanbanItemSpec = {item: string;qty: number;- supplier: string;+ /** Omitted = "Buy". */+ replenishmentSystem?: "Buy" | "Make" | "Transfer";+ /** Required when Buy. */+ supplier?: string;+ /** Transfer kanbans only, with toShelf. */+ fromShelf?: string;+ toShelf?: string;+};++export type InventoryCountLineSpec = {+ item: string;+ shelf: string;+ /**+ * inventoryCountLine.systemQuantity. On a Posted count it must equal the+ * (item, shelf) openingStock — the snapshot IS the opening balance.+ */+ snapshotQuantity: number;+ countedQuantity: number;};export type InventoryCountSpec = {- status: string;+ /** Registered in ctx.refs.documents as `ic:<key>`. */+ key: string;+ status: "Draft" | "Posted";notes: string;+ /**+ * Required when Posted; dates the header and variance ledger rows. Must precede+ * every completed transfer so the snapshot still equals opening stock.+ */+ postedOffset?: DayOffset;+ /**+ * Draft writes bare item/shelf lines (the app snapshots later); Posted writes+ * full lines plus one adjustment ledger row per variance, as post-inventory-count.+ */+ lines: InventoryCountLineSpec[];+};++/** Untracked items only — tracked moves need per-entity splits the seed does not model. */+export type StockTransferSpec = {+ /** Registered in ctx.refs.documents as `st:<key>`. */+ key: string;+ status: "Draft" | "Released" | "Completed";+ fromShelf: string;+ toShelf: string;+ dateOffset: DayOffset;+ lines: { item: string; quantity: number }[];+};++/** Completed writes a shelfless Transfer Receipt — HQ has no bins, and the app does the same. */+export type WarehouseTransferSpec = {+ /** Registered in ctx.refs.documents as `wt:<key>`. */+ key: string;+ status: "Draft" | "To Ship" | "Completed";+ fromLocation: "Plant" | "HQ";+ toLocation: "Plant" | "HQ";+ dateOffset: DayOffset;+ lines: {+ item: string;+ quantity: number;+ /** Required when Completed. */+ fromShelf?: string;+ }[];};export type InventoryData = {openingStock: OpeningStockSpec[];onHandTracked: TrackedStockSpec[];kanbanItems: KanbanItemSpec[];- inventoryCount: InventoryCountSpec;+ inventoryCounts: InventoryCountSpec[];+ /** One Fixed Duration shelf life per dataset, paired with an expiring lot. */+ shelfLives: ShelfLifeSpec[];+ stockTransfers: StockTransferSpec[];+ warehouseTransfers: WarehouseTransferSpec[];};// The stored columns on quoteLinePrice — every net* and converted* column is@@ -291,6 +667,9 @@ export type SalesRfqSpec = {rfqDateOffset: DayOffset;expirationOffset?: DayOffset;externalNotes: string;+ /** The column lives on the RFQ. Pair with "Closed". */+ noQuoteReason?: string;+ assignee?: "self";lines: SalesRfqLineSpec[];};@@ -302,6 +681,7 @@ export type SalesQuoteLineSpec = {sortOrder: number;/** Also supplies quoteLine.quantity — the two have to stay in step. */priceBreaks: readonly PriceBreak[];+ configuration?: Record<string, string | number | boolean>;};export type SalesQuoteExternalLinkSpec = {@@ -314,8 +694,11 @@ export type SalesQuoteSpec = {/** ctx.refs.documents key this quote is stored under. */ref: string;status: string;+ /** quote.createdAt (09:30 UTC); the KPI chart buckets quotes by it. */+ createdOffset?: DayOffset;expirationOffset?: DayOffset;externalNotes?: string;+ assignee?: "self";lines: SalesQuoteLineSpec[];externalLink?: SalesQuoteExternalLinkSpec;};@@ -338,6 +721,7 @@ export type SalesOrderSpec = {ref: string;status: string;orderDateOffset: DayOffset;+ assignee?: "self";lines: SalesOrderLineSpec[];};@@ -345,6 +729,11 @@ export type ShipmentSpec = {/** ctx.refs.documents key this shipment is stored under. */ref: string;status: string;+ /**+ * Required when Posted; dates the header and ledger. Posted mirrors post-shipment:+ * one Sales Shipment ledger row per line from its fromShelf. Voided writes none.+ */+ postedOffset?: DayOffset;lines: {/** ctx.refs.items key — also selects which order line the shipment covers. */item: string;@@ -352,16 +741,21 @@ export type ShipmentSpec = {outstandingQuantity: number;shippedQuantity: number;unitPrice: number;+ /** Required (untracked, stocked item) on a Posted line with shippedQuantity > 0. */+ fromShelf?: string;}[];};export type SalesInvoiceSpec = {/** ctx.refs.documents key this invoice is stored under. */ref: string;+ /** Registered in ctx.refs.misc as `sinv:<key>` so payments can settle it. */+ key?: string;status: string;subtotal: number;totalAmount: number;dateIssuedOffset: DayOffset;+ dueDateOffset?: DayOffset;lines: {/** ctx.refs.items key — also selects which order line the invoice covers. */item: string;@@ -399,11 +793,67 @@ export type StaggeredDeliverySpec = {sortOrder: number;};+export type SalesReturnLineSpec = {+ item: string;+ quantity: number;+ unitPrice: number;+ /** Required when Completed — the receipt books stock back onto it. */+ toShelf?: string;+};++/**+ * Mirrors "Issue Credit": amount = Σ qty × unit price (no restock fee). Completed+ * returns only — the app caps credit at what was received / shipped.+ */+export type ReturnCreditSpec = {+ /** Draft is what Issue Credit leaves; Posted adds post-memo's stamps. */+ status: "Draft" | "Posted";+ /** On/after the return's dateOffset. */+ dateOffset: DayOffset;+ /** `line` is the 1-based return line number. */+ lines: { line: number; quantity: number }[];+};++/**+ * RMA. Completed mirrors post-receipt's Sales Return Order branch (Posted receipt+ * plus one ledger row per line). Line ids are registered as `rmaline:<key>:<n>`.+ */+export type SalesReturnSpec = {+ /** Registered in ctx.refs.documents as `rma:<key>`. */+ key: string;+ status: "Draft" | "To Receive" | "Completed";+ customer: string;+ /** Applied to every line (the column is per-line). */+ returnReason: string;+ /** Order date; also the receipt date when Completed. */+ dateOffset: DayOffset;+ salesOrder?: string;+ lines: SalesReturnLineSpec[];+ credit?: ReturnCreditSpec;+};++export type BankAccountSpec = {+ name: string;+ bankName: string;+ accountHolderName: string;+ countryCode: string;+ currencyCode: string;+ /** Must start with "DEMO-" — never a real account number. */+ accountNumber: string;+ bankCode?: string;+ swiftBic?: string;+ isPrimary: boolean;+};+export type SalesData = {opportunities: SalesOpportunitySpec[];statusOrders: SalesStatusOrderSpec[];// Written AFTER the status orders — salesOrder readable ids depend on it.releasedOrders: SalesOpportunitySpec[];+ salesReturns: SalesReturnSpec[];+ /** Customers with a portal (externalLink documentType Customer), as the portal form writes it. */+ customerPortals: string[];+ customerBankAccounts: (BankAccountSpec & { customer: string })[];};export type RfqLineSpec = {@@ -416,6 +866,9 @@ export type RfqQuoteSpec = {supplier: string;supplierReference: string;shippingCost: number;+ /** Omitted = "Active", which keeps the RFQ trio open for Compare Quotes. */+ status?: "Draft" | "Active" | "Expired" | "Declined";+ assignee?: "self";lines: {item: string;supplierPartId: string;@@ -424,6 +877,23 @@ export type RfqQuoteSpec = {}[];};+/** The supplier needs a supplierContact — the quote takes the contact and location refs foundation seeds from it. */+export type StandaloneSupplierQuoteSpec = {+ /** Registered in ctx.refs.documents as `sq:<key>` (shared with RfqQuoteSpec keys). */+ key: string;+ supplier: string;+ status: "Draft" | "Active" | "Expired" | "Declined";+ supplierReference: string;+ quotedOffset: DayOffset;+ assignee?: "self";+ expirationOffset: DayOffset;+ lines: {+ item: string;+ supplierPartId: string;+ prices: { quantity: number; unitPrice: number; leadTime: number }[];+ }[];+};+export type RfqHeaderSpec = {/** ctx.refs.documents key this RFQ is stored under. */ref: string;@@ -432,6 +902,21 @@ export type RfqHeaderSpec = {expirationOffset: DayOffset;notes: string;internalNotes: string;+ assignee?: "self";+};++/** Closed mirrors the app's Cancel RFQ action taken before quotes were requested. */+export type LifecycleRfqSpec = {+ /** ctx.refs.documents key this RFQ is stored under. */+ ref: string;+ status: "Draft" | "Closed";+ rfqDateOffset: DayOffset;+ expirationOffset: DayOffset;+ notes: string;+ internalNotes: string;+ quantities: number[];+ lines: RfqLineSpec[];+ suppliers: string[];};export type PurchaseOrderLineSpec = {@@ -445,6 +930,11 @@ export type ReceiptSpec = {/** ctx.refs.documents key this receipt is stored under. */ref: string;status: string;+ /**+ * Required when Posted; dates the header and ledger. Posted mirrors post-receipt:+ * one Purchase Receipt ledger row per line into its toShelf. Voided writes none.+ */+ postedOffset?: DayOffset;lines: {/** ctx.refs.items key — also selects which PO line the receipt line covers. */item: string;@@ -453,17 +943,28 @@ export type ReceiptSpec = {receivedQuantity: number;unitPrice: number;requiresBatchTracking?: boolean;+ /** Required on a Posted line with receivedQuantity > 0. */+ toShelf?: string;+ /**+ * Lot minted for a Posted batch-tracked line, as update_receipt_line_batch_tracking+ * does. Must not collide with any onHandTracked or genealogy readableId.+ */+ lotNumber?: string;+ lotExpiresOffset?: DayOffset;}[];};export type PurchaseInvoiceSpec = {/** ctx.refs.documents key this invoice is stored under. */ref: string;+ /** Registered in ctx.refs.misc as `pinv:<key>` so payments can settle it. */+ key?: string;status: string;currencyCode: string;subtotal: number;totalAmount: number;dateIssuedOffset: DayOffset;+ dueDateOffset?: DayOffset;lines: {item: string;quantity: number;@@ -483,6 +984,11 @@ export type PurchaseOrderSpec =purchaseOrderType: string;status: string;orderDateOffset: DayOffset;+ /** Omitted = base. EUR is pinned to exactly one direct, childless, unpaid PO. */+ currencyCode?: string;+ /** Foreign units per base unit; required when currencyCode is set. */+ exchangeRate?: number;+ assignee?: "self";lines: PurchaseOrderLineSpec[];receipt?: ReceiptSpec;invoice?: PurchaseInvoiceSpec;@@ -497,6 +1003,46 @@ export type PurchaseOrderSpec =exchangeRate: number;};+/**+ * Return to vendor. Completed mirrors post-shipment's Purchase Return Order+ * branch (Posted shipment plus one ledger row per line out of its fromShelf).+ * Line ids are registered as `pretline:<key>:<n>`.+ */+export type PurchaseReturnSpec = {+ /** Registered in ctx.refs.documents as `pret:<key>`. */+ key: string;+ status: "Draft" | "To Ship" | "Completed";+ supplier: string;+ /** Order date; also the shipment date when Completed. */+ dateOffset: DayOffset;+ lines: {+ item: string;+ quantity: number;+ unitPrice: number;+ /** Required when Completed. */+ fromShelf?: string;+ }[];+ /** A Debit memo — the app's supplier-credit direction. */+ credit?: ReturnCreditSpec;+};++/** Approvers are the company's Admin employee-type group plus the applying user as default approver. */+export type ApprovalRuleSpec = {+ documentType: "purchaseOrder" | "supplier";+ /** A supplier rule is amount-less, so 0. */+ lowerBoundAmount: number;+ escalationDays?: number;+};++/**+ * A Pending `approvalRequest`, as PO finalize / supplier "Request approval"+ * write it. A PO request's amount is the order total (purchaseOrders view).+ */+export type ApprovalRequestSpec = { requestedOffset: DayOffset } & (+ | { purchaseOrder: string /** a direct PO's ref, status "Needs Approval" */ }+ | { supplier: string /** status "Pending" */ }+);+export type PurchasingData = {rfqQuantityBreaks: number[];rfqLines: RfqLineSpec[];@@ -504,26 +1050,87 @@ export type PurchasingData = {rfqWinningQuote: string;rfqOrderQuantity: number;rfqHeader: RfqHeaderSpec;+ lifecycleRfqs: LifecycleRfqSpec[];purchaseOrders: PurchaseOrderSpec[];+ standaloneSupplierQuotes: StandaloneSupplierQuoteSpec[];+ purchaseReturns: PurchaseReturnSpec[];+ approvalRules: ApprovalRuleSpec[];+ approvalRequests: ApprovalRequestSpec[];+ supplierBankAccounts: (BankAccountSpec & { supplier: string })[];};// Every non-deprecated jobStatus, each one hanging off a real salesOrderLine, so// the sales order → job link is exercised at every stage of the lifecycle.// "Overdue" / "Due Today" are deliberately absent: they are deprecated stored// statuses that the UI derives from dueDate instead.+export type JobDeadlineType =+ | "No Deadline"+ | "ASAP"+ | "Soft Deadline"+ | "Hard Deadline";++/**+ * Applied after copyMethodToJob. `order` is the 1-based POSITION among root+ * operations sorted by "order" — not the raw value (methods number 10/20/30).+ */+export type JobOperationOverrideSpec = {+ order: number;+ status?:+ | "Todo"+ | "Ready"+ | "Waiting"+ | "In Progress"+ | "Paused"+ | "Done"+ | "Canceled";+ assignee?: "self";+ /** An open productionEvent (no endTime) started today; status must be "In Progress". */+ running?: { type: "Setup" | "Labor" | "Machine"; startTimeOfDay: string };+};++/** Authoring any of these on a job replaces the tier's default Production-1 rows. */+export type ProductionQuantitySpec = {+ order: number;+ type: "Production" | "Scrap" | "Rework";+ quantity: number;+ /** Required on Scrap rows. */+ scrapReason?: string;+};++/** Plain text, not TipTap. */+export type OperationNoteSpec = {+ order: number;+ note: string;+};+export type JobSpec = {key: string;item: string;status: string;quantity: number;quantityComplete?: number;- // Ref keys written by tier 4.- salesOrder: string;- salesOrderLine: string;- customer: string;- dueDateOffset: DayOffset;+ // Ref keys written by tier 4. All three or none — none is a make-to-stock job.+ salesOrder?: string;+ salesOrderLine?: string;+ customer?: string;+ /** Distinct across the dataset; required on released jobs. */+ priority?: number;+ assignee?: "self";+ /** Omitted = "Hard Deadline". */+ deadlineType?: JobDeadlineType;+ /** Required unless "No Deadline", where it must be absent. */+ dueDateOffset?: DayOffset;releasedDateOffset?: DayOffset;completedDateOffset?: DayOffset;+ operationOverrides?: JobOperationOverrideSpec[];+ quantities?: ProductionQuantitySpec[];+ operationNotes?: OperationNoteSpec[];+ /**+ * Completed jobs only: Setup/Labor/Machine events on every staffed operation,+ * each sized from the operation's own estimate × `efficiency`, run back to back+ * from `startOffset` 07:00 — the estimates-vs-actuals KPI compares the two.+ */+ loggedTime?: { startOffset: DayOffset; efficiency: number };};export type ShiftEventSpec = {@@ -584,6 +1191,13 @@ export type AssemblyStepSpec = {* graph — a step naming an absent node renders but animates nothing.*/componentNodeIds: string[];+ materials?: { item: string; quantity: number }[];+ tools?: { item: string; quantity: number }[];+};++export type AssemblyComponentMappingSpec = {+ geometryHash: string;+ item: string;};export type AssemblySpec = {@@ -598,16 +1212,44 @@ export type AssemblySpec = {item?: string;/** Component total from the bundled graph, mirrored onto modelUpload. */componentCount: number;+ /** 1-based BOP position of the item's "Assembly" operation. */+ operation: number;steps: AssemblyStepSpec[];+ componentMappings: AssemblyComponentMappingSpec[];+};++/** Orders are 1-based root-operation positions (see JobOperationOverrideSpec). */+export type ReworkSpec = {+ quantity: number;+ reason: string;+ targetOperationOrder: number;+ triggeredAtOperationOrder: number;+};++export type PickingListLineSpec = {+ /** Must be a component somewhere on the picked job's BOM tree. */+ item: string;+ quantityRequired: number;+ quantityPicked: number;+ status: "Pending" | "Picked" | "Short";+ fromShelf: string;+};++/**+ * Completed lists write paired Direct Transfer ledger rows fromShelf → the floor+ * storage unit of the job's first root operation's work center.+ */+export type PickingListSpec = {+ key: string;+ status: "In Progress" | "Completed";+ job: string;+ /** Due date of the list, and posting date of the Completed ledger pairs. */+ dateOffset: DayOffset;+ lines: PickingListLineSpec[];};export type ProductionData = {jobs: JobSpec[];- /**- * Animated 3D work instructions built on a bundled CAD assembly. Optional:- * a dataset with no industryId has nowhere to resolve the model from.- */- assembly?: AssemblySpec;/** Production-event blocks, indexed by operation position — not shift rows. */shifts: ShiftEventSpec[][];genealogyInputs: GenealogyInputSpec[];@@ -616,6 +1258,57 @@ export type ProductionData = {eventsJobKey: string;/** JobSpec.key the as-built genealogy hangs off. */genealogyJobKey: string;+ /** Open Setup event (null endTime) on the events job; use the op overridden to "In Progress". */+ openEvent: { operationOrder: number };+ /**+ * An Active batch; members are unstarted root operations of different+ * released jobs on one process. `running` is its batch timer today, on the+ * first member: the tier moves every member to "In Progress", so each member+ * job is "In Progress" with its earlier root operations Done.+ */+ batch: {+ members: { job: string; order: number }[];+ running: { type: "Setup" | "Labor" | "Machine"; startTimeOfDay: string };+ };+ rework: ReworkSpec;+ pickingLists: PickingListSpec[];+};++export type NonConformanceTaskStatus =+ | "Pending"+ | "In Progress"+ | "Completed"+ | "Skipped";++/** Mirrors the `create` edge function's nonConformanceTasks case; In Progress goes to the applying user. */+export type NonConformanceActionTaskSpec = {+ action: string;+ status: NonConformanceTaskStatus;+ dueDateOffset?: DayOffset;+ /** Required when Completed. */+ completedOffset?: DayOffset;+ processes?: string[];+};++/** The active picker subset of the `disposition` enum (quality.models.ts). */+export type NonConformanceDisposition =+ | "Pending"+ | "Return to Supplier"+ | "Rework"+ | "Scrap"+ | "Use As Is";++/** An issue workflow (template): the new-issue form copies its fields onto the NCR. */+export type NonConformanceWorkflowSpec = {+ key: string;+ name: string;+ /** Also the TipTap `content` body. */+ description: string;+ priority: "Low" | "Medium" | "High" | "Critical";+ source: "Internal" | "External";+ requiredActions: string[];+ /** approvalRequirements = ["MRB"]. */+ mrb?: boolean;};export type NonConformanceSpec = {@@ -627,14 +1320,216 @@ export type NonConformanceSpec = {openDateOffset: DayOffset;quantity: number;priority: string;+ /** Omitted = the first row the DB returns. */+ type?: string;+ /** Also written as the TipTap `content` body. */+ description?: string;+ dueDateOffset?: DayOffset;+ /** Required when "Closed", forbidden otherwise. */+ closeDateOffset?: DayOffset;/** `job` is a ctx.refs.documents key; the operation itself is resolved by query. */jobOperation?: { job: string };- /** `item` is a ctx.refs.items key. */- items?: { item: string; quantity: number }[];+ items: {+ item: string;+ quantity: number;+ /** Omitted = Pending. A Closed issue has every row dispositioned. */+ disposition?: NonConformanceDisposition;+ }[];+ /** Open issues only (close clears it). */+ assignee?: "self";+ /** The issue carries that workflow's source, actions and approvals. */+ workflow?: string;+ /** An externalLink is minted by the sync interceptor. */+ supplier?: string;+ /** The PO's supplier must be `supplier`. */+ purchaseOrderLine?: { po: string; item: string };+ customer?: string;+ /** A `soline:` ref; its order's customer must be `customer`. */+ salesOrderLine?: string;+ trackedEntity?: string;+ inspection?: string;+ /** The RMA's customer must be `customer`. */+ salesReturnLine?: { salesReturn: string; line: number };+ /** Covers the issue's quantity; its supplier must be `supplier`. */+ purchaseReturnLine?: {+ purchaseReturn: string;+ line: number;+ quantity: number;+ };+ /** In `requiredActionIds` order. */+ actionTasks?: NonConformanceActionTaskSpec[];+ /** One approval task plus Engineering and Quality reviewers, as the edge function seeds. */+ mrb?: {+ status: NonConformanceTaskStatus;+ dueDateOffset?: DayOffset;+ completedOffset?: DayOffset;+ reviewers: {+ title: "Engineering" | "Quality";+ status: NonConformanceTaskStatus;+ /** Required when Completed. */+ completedOffset?: DayOffset;+ }[];+ };};+export type InspectionFeatureSpec = {+ label: string;+ description: string;+ nominalValue: string;+ tolerancePlus: string;+ toleranceMinus: string;+ unit: string;+};++/** Status must equal the engine's derivation. */+export type InspectionSampleSpec = {+ status: "Passed" | "Failed";+ inspectedOffset: DayOffset;+ measurements: { feature: string; value: number }[];+};++type InspectionLotSpec = {+ ref: string;+ /** "Partial" = some samples passed, some failed. */+ status: "Pending" | "In Progress" | "Passed" | "Partial";+ /** Required iff dispositioned; on/after every sample's inspectedOffset. */+ dispositionOffset?: DayOffset;+ notes?: string;+ /**+ * A dispositioned lot has exactly the resolved sample size; Pending has none;+ * In Progress has at least one and fewer than the sample size.+ */+ samples: InspectionSampleSpec[];+};++/**+ * A lot post-receipt creates for a line whose item has a Receipt-usage plan+ * (file-less document, AQL ANSI Z1.4 level II Normal). Lots of one item share+ * its single plan, so they carry identical drawing / aql / features.+ */+export type ReceiptInspectionSpec = InspectionLotSpec & {+ source: "Receipt";+ receipt: string;+ item: string;+ drawingNumber: string;+ /** Resolved sample size must be ≤ 5 so every sample is authored. */+ aql: number;+ features: InspectionFeatureSpec[];+};++/**+ * The lot getOrCreateJobOperationInspection creates when the MES opens a job's+ * Inspection operation: plan = the operation's items.inspectionPlans document,+ * lot size = the operation quantity.+ */+export type JobOperationInspectionSpec = InspectionLotSpec & {+ source: "Job Operation";+ job: string;+};++export type InspectionSpec = ReceiptInspectionSpec | JobOperationInspectionSpec;++export type QualityDocumentStepType =+ | "Value"+ | "Measurement"+ | "Checkbox"+ | "Timestamp"+ | "Person"+ | "List"+ | "Task";++export type QualityDocumentSpec = {+ name: string;+ /** (name, version) is unique — same-name rows are versions of one document. */+ version: number;+ status: "Draft" | "Active" | "Archived";+ description: string;+ steps: {+ name: string;+ description?: string;+ type: QualityDocumentStepType;+ required?: boolean;+ /** Required for (and only for) Measurement steps. */+ unitOfMeasureCode?: string;+ minValue?: number;+ maxValue?: number;+ listValues?: string[];+ }[];+};++/**+ * Calibration status is derived as upsertGaugeCalibrationRecord does: none ⇒+ * Pending; latest Pass ⇒ In-Calibration; latest Fail ⇒ Out-of-Calibration.+ */+export type GaugeSpec = {+ key: string;+ gaugeType: string;+ description: string;+ modelNumber?: string;+ serialNumber?: string;+ supplier?: string;+ role: "Master" | "Standard";+ status: "Active" | "Inactive";+ calibrationIntervalInMonths: number;+ acquiredOffset: DayOffset;+ shelf?: string;+ /** Oldest first; every dateOffset on/after acquiredOffset and ≤ 0. */+ calibrations: {+ dateOffset: DayOffset;+ result: "Pass" | "Fail";+ requiresAction?: boolean;+ requiresAdjustment?: boolean;+ requiresRepair?: boolean;+ temperature?: number;+ humidity?: number;+ measurementStandard?: string;+ notes?: string;+ }[];+};++export type RiskStatus =+ | "Open"+ | "In Review"+ | "Mitigating"+ | "Closed"+ | "Accepted";++/**+ * `source` picks the entity card; Item/Job risks also carry itemId (a Job's is its+ * item), as each RiskRegisterCard writes them.+ */+export type RiskSpec = {+ title: string;+ description: string;+ type: "Risk" | "Opportunity";+ status: RiskStatus;+ /** 1–5 */+ severity: number;+ /** 1–5 */+ likelihood: number;+} & (+ | { source: "General" }+ | { source: "Customer"; customer: string }+ | { source: "Supplier"; supplier: string }+ | { source: "Item"; item: string }+ | { source: "Job" /** `job:<key>` ref. */; job: string }+ | {+ source: "Work Center";+ workCenter: string;+ }+);+export type QualityData = {+ /** Inserted before the NCRs that link them. */+ workflows: NonConformanceWorkflowSpec[];nonConformances: NonConformanceSpec[];+ /** Inserted before NCRs so one can link a lot. */+ inspections: InspectionSpec[];+ qualityDocuments: QualityDocumentSpec[];+ /** Together they cover all three calibration statuses. */+ gauges: GaugeSpec[];+ /** ≥ 5 — every risk status, one Opportunity, sources spread. */+ risks: RiskSpec[];};// The change type drives what the tier does to the item's methods, so it is a@@ -674,6 +1569,21 @@ export type AffectedItemSpec = {revision?: RevisionSpec;};+export type ChangeOrderTaskStatus =+ | "Pending"+ | "In Progress"+ | "Completed"+ | "Skipped";++/** Instantiated as setChangeNoticeActionTasks does; In Progress goes to the applying user. */+export type ChangeOrderActionTaskSpec = {+ action: string;+ status: ChangeOrderTaskStatus;+ dueDateOffset?: DayOffset;+ /** Required when Completed. */+ completedOffset?: DayOffset;+};+export type ChangeOrderSpec = {/** ctx.refs.documents key this change order is stored under. */ref: string;@@ -681,7 +1591,15 @@ export type ChangeOrderSpec = {type: string;status: string;openDateOffset: DayOffset;+ /** Empty on lifecycle-only notices — every change type spins a method draft. */affectedItems: AffectedItemSpec[];+ changeOrderType?: string;+ priority?: "Low" | "Medium" | "High" | "Critical";+ dueDateOffset?: DayOffset;+ /** Plain text → TipTap body. */+ reasonForChange?: string;+ nonConformance?: string;+ actionTasks?: ChangeOrderActionTaskSpec[];};export type ChangeOrderData = {@@ -699,8 +1617,11 @@ export type FixedAssetSpec = {name: string;description: string;serialNumber: string;- status: "Draft" | "Active" | "Fully Depreciated";- depreciationMethod: "Straight Line" | "Declining Balance";+ status: "Draft" | "Active" | "Fully Depreciated" | "Disposed";+ depreciationMethod:+ | "Straight Line"+ | "Declining Balance"+ | "Units of Production";usefulLifeMonths: number;// Whole percent — the app reads residual as cost * (percent / 100).residualValuePercent: number;@@ -713,36 +1634,460 @@ export type FixedAssetSpec = {// (cost - residual) / usefulLifeMonths * months since depreciationStartDate.// Both dates move with the anchor, so the elapsed month count is stable.// Omit to leave the asset out of the seeded run.+ // Units of Production instead uses the run month's usage log:+ // (cost - residual) / assetLifetimeUsage * unitsProduced.depreciationCharge?: number;+ /** Required for "Units of Production". */+ assetLifetimeUsage?: number;+ /** One per month; monthsBack 1 is the seeded run's period, the only log it reads. */+ usageLogs?: { monthsBack: number; unitsProduced: number }[];+ /** Required iff "Disposed"; the tier derives NBV and gainLoss as post-sales-invoice does. */+ disposal?: { dateOffset: DayOffset; method: "Sale"; saleProceeds: number };+};++export type AccountClass =+ | "Asset"+ | "Liability"+ | "Equity"+ | "Revenue"+ | "Expense";++/** A class resolves to the group's first posting account of that class. */+export type JournalLineAccount =+ | { accountClass: AccountClass; account?: never }+ | { account: string; accountClass?: never };++export type JournalLineDimensionSpec = {+ /**+ * "Project" = the bootstrap Project dimension (`value` is a projects key);+ * otherwise accounting.customDimension.name, `value` one of its values.+ */+ dimension: string;+ value: string;};-// The tier resolves one GL account per class, so a line names its class rather-// than an account id.-export type JournalLineSpec = {- accountClass: "Asset" | "Revenue";+// amount is the class-signed natural balance the journalEntries view decodes:+// positive on a debit-normal class (Asset/Expense) is a debit, positive on a+// credit-normal class (Liability/Equity/Revenue) is a credit.+export type JournalLineSpec = JournalLineAccount & {description: string;amount: number;quantity: number;journalLineReference: string;+ /** The line must carry a unique journalLineReference. */+ dimensions?: JournalLineDimensionSpec[];};export type JournalEntrySpec = {ref: string;journalEntryId: string;description: string;- status: "Draft" | "Posted";+ status: "Draft" | "Posted" | "Reversed";+ /** Omitted = "Manual". A company holds one Posted "Opening Balance" entry (unique index). */+ sourceType?: "Opening Balance";postingOffset: DayOffset;lines: JournalLineSpec[];+ /** Required iff "Reversed": the tier writes a negated Posted reversal, as reverseJournalEntry does. */+ reversal?: { ref: string; journalEntryId: string; postingOffset: DayOffset };+};++/**+ * Posted = post-payment's shape with its journal (payment.journalId); all USD at+ * rate 1. Draft = entered, unapplied and unposted — the payment's apply table.+ */+export type PaymentSpec = {+ /** Registered in ctx.refs.documents as `payment:<key>`. */+ key: string;+ type: "Receipt" | "Disbursement";+ /** Omitted = "Posted". A Draft carries no applies and no credits. */+ status?: "Draft";+ /** Required for a Receipt. */+ customer?: string;+ /** Required for a Disbursement. */+ supplier?: string;+ dateOffset: DayOffset;+ /** Cash total; 0 = a pure credit application. */+ amount: number;+ reference: string;+ /** Cash applications; Σ amount must equal `amount`. invoiceKey → `sinv:`/`pinv:` by type. */+ applies: { invoiceKey: string; amount: number }[];+ /** applyCreditsToInvoices shape. */+ credits?: { memoKey: string; invoiceKey: string; amount: number }[];+};++/**+ * Posted credit/debit memo. The memo table has no invoice column, so the tie is+ * `reference` = the invoice's readable id plus a PaymentSpec.credits application.+ */+export type MemoSpec = {+ /** Registered in ctx.refs.documents as `memo:<key>`. */+ key: string;+ direction: "Credit" | "Debit";+ customer?: string;+ supplier?: string;+ /** Credit → a `sinv:` key; Debit → a `pinv:` key. */+ invoiceKey: string;+ dateOffset: DayOffset;+ amount: number;+ notes: string;+};++export type ProjectSpec = {+ /** Registered in ctx.refs.misc as `project:<key>`. */+ key: string;+ name: string;+ description: string;+ /** job has no projectId, so project coding lives on purchaseInvoiceLine. */+ purchaseInvoiceLine?: { invoiceKey: string; item: string };+};++export type CustomDimensionSpec = {+ name: string;+ values: string[];+};++/** Snapshotted from the bootstrap periodCloseTaskDefinition named `definition`. */+export type PeriodCloseTaskSpec = {+ definition: string;+ status: "Open" | "Done" | "Skipped";+ /** Required iff Skipped (the app's close checklist demands a reason). */+ skippedReason?: string;+ notes?: string;+};++/**+ * Company-scoped rate pin, foreign units per base unit. Never write the global+ * "exchangeRate" table from a tenant template.+ */+export type ExchangeRateOverrideSpec = {+ currencyCode: string;+ rate: number;+};++export type BillingAddressSpec = {+ addressLine1: string;+ city: string;+ state: string;+ postalCode: string;+ countryCode: string;+ phone: string;+ /** A reserved `.example` domain — never a real mailbox. */+ email: string;};export type AccountingData = {fixedAssets: FixedAssetSpec[];journalEntries: JournalEntrySpec[];+ payments: PaymentSpec[];+ memos: MemoSpec[];+ projects: ProjectSpec[];+ customDimension: CustomDimensionSpec;+ closeTasks: PeriodCloseTaskSpec[];+ exchangeRateOverrides: ExchangeRateOverrideSpec[];+ billingAddresses: {+ receivable: BillingAddressSpec;+ payable: BillingAddressSpec;+ };+};++export type MaintenanceFrequency =+ | "Daily"+ | "Weekly"+ | "Monthly"+ | "Quarterly"+ | "Annual";+export type MaintenancePriority = "Low" | "Medium" | "High" | "Critical";++/** Shaped as scheduled-maintenance.new writes it (location = the work center's). */+export type MaintenanceScheduleSpec = {+ /** Registered in ctx.refs.misc as `maintenanceSchedule:<key>`. */+ key: string;+ name: string;+ description: string;+ workCenter: string;+ frequency: MaintenanceFrequency;+ priority: MaintenancePriority;+ /** Minutes; > 0 when it takes the work center offline. */+ estimatedDuration: number;+ /** Stored at midnight UTC; must not be in the past. */+ nextDueOffset: DayOffset;+ takesWorkCenterOffline?: boolean;+ /** Daily only: false leaves Saturday/Sunday off. Default true. */+ weekends?: boolean;+ /** Kit the generator copies onto each dispatch it creates. */+ spareParts?: { item: string; quantity: number }[];+};++export type MaintenanceDispatchStatus =+ | "Open"+ | "Assigned"+ | "In Progress"+ | "Completed"+ | "Cancelled";+export type MaintenanceSeverity =+ | "Preventive"+ | "Operator Performed"+ | "Support Required"+ | "OEM Required";+export type MaintenanceSource = "Scheduled" | "Reactive" | "Non-Conformance";+export type OeeImpact = "Down" | "Planned" | "Impact" | "No Impact";++/** The tier assigns ctx.userId for Assigned / In Progress / Completed, no one otherwise. */+export type MaintenanceDispatchSpec = {+ /** Registered in ctx.refs.misc as `maintenanceDispatch:<key>`. */+ key: string;+ status: MaintenanceDispatchStatus;+ priority: MaintenancePriority;+ severity: MaintenanceSeverity;+ source: MaintenanceSource;+ oeeImpact: OeeImpact;+ workCenter: string;+ /** Required iff source is "Scheduled": an ops.maintenanceSchedules key on the same work center. */+ schedule?: string;+ /** Required iff source is "Non-Conformance". */+ nonConformance?: string;+ suspectedFailureMode?: string;+ /** Completed only. */+ actualFailureMode?: string;+ /** Plain text → TipTap body. */+ content: string;+ created: InstantSpec;+ plannedStart: InstantSpec;+ plannedEnd: InstantSpec;+ /** Required iff In Progress or Completed (the Start action stamps it). */+ actualStart?: InstantSpec;+ /** Required iff Completed (also completedAt, as the MES Complete action writes both). */+ actualEnd?: InstantSpec;+ takesWorkCenterOffline?: boolean;+ /**+ * Completed only, untracked items: issued via add-and-issue with a ledger draw+ * from `shelf`, at the item's standard cost (the spare-part cost KPI).+ */+ spareParts?: { item: string; quantity: number; shelf: string }[];+ comments?: string[];+};++type TrainingQuestionBase = { question: string };++/** Mirrors what the training question editor saves per type. */+export type TrainingQuestionSpec = TrainingQuestionBase &+ (+ | { type: "MultipleChoice"; options: string[]; correct: string }+ | { type: "MultipleAnswers"; options: string[]; correct: string[] }+ | { type: "TrueFalse"; answer: boolean }+ | { type: "MatchingPairs"; pairs: { left: string; right: string }[] }+ | { type: "Numerical"; answer: number; tolerance?: number }+ );++/** `assignment` targets ctx.userId's group (a user id is its own group id). */+export type TrainingSpec = {+ name: string;+ description: string;+ status: "Draft" | "Active" | "Archived";+ frequency: "Once" | "Quarterly" | "Annual";+ type: "Mandatory" | "Optional";+ estimatedDuration: string;+ /** Paragraphs → TipTap body. */+ content: string[];+ questions: TrainingQuestionSpec[];+ /**+ * Active trainings only. completedOffset only on "Once": a recurring one's+ * completion must match the current period, which an offset can't guarantee.+ */+ assignment?: { completedOffset?: DayOffset };+};++/** Clock-in and clock-out on the same day. */+export type TimecardSpec = {+ dayOffset: DayOffset;+ /** UTC "HH:MM:SS". */+ clockIn: string;+ /** UTC "HH:MM:SS", after clockIn. */+ clockOut: string;+ note?: string;+};++export type OpenTimecardSpec = {+ /** UTC "HH:MM:SS" today; no later than the earliest running production event. */+ clockIn: string;+ note?: string;+};++/** Never today: a today row pre-filters the MES schedule to that one work center. */+export type PeopleAssignmentSpec = {+ dayOffset: DayOffset;+ workCenter: string;+ shift: string;+ overtimeHours?: number;+ note?: string;+};++export type PeopleAbsenceSpec = {+ dayOffset: DayOffset;+ /** Omitted = the whole day. */+ shift?: string;+ note: string;+};++/** `path` = the page it was sent from. */+export type SuggestionSpec = {+ suggestion: string;+ emoji: string;+ path: string;+ tags?: string[];+};++/** Hangs on ctx.userId — only /x/person/:personId/notes reads the table. */+export type NoteSpec = { text: string };++export type ReplacementPartSpec = {+ workCenter: string;+ item: string;+ /** Whole units (the column is an integer). */+ quantity: number;+};++/** Tiers resolve the attributeDataType id by this label. */+export type AttributeDataTypeLabel =+ | "Yes/No"+ | "Date"+ | "List"+ | "Numeric"+ | "Text"+ | "User"+ | "Customer"+ | "Supplier"+ | "File";++/** The applying user is the only person the seed may name, so a User attribute points at them. */+export type UserAttributeSpec = {+ name: string;+ canSelfManage?: boolean;+} & (+ | { dataType: "Date"; valueOffset: DayOffset }+ | { dataType: "List"; listOptions: string[]; value: string }+ | { dataType: "User" }+ | { dataType: "Text"; value: string }+ | { dataType: "Numeric"; value: number }+ | { dataType: "Yes/No"; value: boolean }+);++/** Adopted by name on a re-apply (the wipe keeps it). */+export type UserAttributeCategorySpec = {+ name: string;+ emoji: string;+ public: boolean;+ attributes: UserAttributeSpec[];+};++/** Adopted by (table, name) on a re-apply (the wipe keeps it). */+export type CustomFieldSpec = {+ table: string;+ name: string;+ dataType: Exclude<AttributeDataTypeLabel, "File">;+ /** Required iff dataType is "List". */+ listOptions?: string[];+};++export type SerialSequenceSpec = {+ item: string;+ prefix: string;+ suffix?: string;+ /** Zero-padded counter width. */+ size: number;+ /**+ * The last counter issued (the next serial is next + 1): at least every+ * seeded serial of the item that fits prefix + counter + suffix.+ */+ next: number;+};++/** As the print-job task leaves it. */+export type PrintJobSpec = {+ source:+ | { kind: "Receipt"; receipt: string }+ | { kind: "Job"; job: string }+ | { kind: "StorageUnit"; shelf: string };+ /** Omitted for a storage-unit label. */+ item?: string;+ status: "completed" | "failed" | "queued";+ origin: "auto" | "manual" | "reprint";+ /** createdAt; the cleanup job deletes completed jobs after 30 days. */+ at: InstantSpec;+ attempts: number;+ /** Required iff failed. */+ error?: string;+};++export type OpsData = {+ userAttributeCategories: UserAttributeCategorySpec[];+ customFields: CustomFieldSpec[];+ serialSequences: SerialSequenceSpec[];+ printJobs: PrintJobSpec[];+ maintenanceSchedules: MaintenanceScheduleSpec[];+ maintenanceDispatches: MaintenanceDispatchSpec[];+ replacementParts: ReplacementPartSpec[];+ trainings: TrainingSpec[];+ timecards: TimecardSpec[];+ openTimecard: OpenTimecardSpec;+ peopleAssignments: PeopleAssignmentSpec[];+ peopleAbsences: PeopleAbsenceSpec[];+ suggestions: SuggestionSpec[];+ notes: NoteSpec[];+};++export type Node = {+ id: string;+ name: string;+ type: string;+ position: { x: number; y: number };+ expanded?: boolean;+ data: Record<string, unknown>;+};++export type Edge = {+ id: string;+ source: string;+ sourceHandle: string;+ target: string;+ targetHandle: string;+};++export type SeedWorkflow = {+ name: string;+ description: string;+ /** Only the simplest one ships published; the rest are there to read and publish deliberately. */+ published: boolean;+ nodes: Node[];+ edges: Edge[];+};++/**+ * A finished run in the engine's shape: a Succeeded trigger step (sequence 0),+ * then `steps`. Skipped runs stop at `load` — no steps, startedAt null.+ */+export type WorkflowRunSpec = {+ /** Name of a `published: true` workflow from `build`. */+ workflow: string;+ status: "Succeeded" | "Failed" | "Skipped";+ triggerRef: string;+ /** createdAt; on or after the triggering record's date. */+ at: InstantSpec;+ /** Required iff Skipped: the engine's statusReason. */+ statusReason?: string;+ /** Non-trigger steps, in walk order. Empty iff Skipped. */+ steps: {+ nodeId: string;+ status: "Succeeded" | "Failed";+ /** Required iff Failed — the executor's error string (detail stays null). */+ error?: string;+ }[];};// A factory, not a constant: the definitions name ids that only exist once the seed has run.export type WorkflowData = {build: (refs: { ownerId: string; issueTypeId: string }) => SeedWorkflow[];+ runs: WorkflowRunSpec[];};export type DemandProjectionSpec = {@@ -774,13 +2119,25 @@ export type DemandOrderSpec = {lines: DemandOrderLineSpec[];};+/** Planning at the bootstrap (HQ) location, so its planning screens are not empty. */+export type HqPlanningSpec = {+ /** Fixed Reorder Quantity at HQ; at least one make part and one buy part. */+ reorderItemIds: string[];+ /** Make parts only — the projections screen lists Make items. */+ demandProjections: DemandProjectionSpec[];+};+export type PlanningData = {buyItemIds: string[];makeItemIds: string[];demandProjections: DemandProjectionSpec[];demandOrder: DemandOrderSpec;+ hq: HqPlanningSpec;};+// Must stay in step with DATASETS in index.ts — a key with no dataset is unusable.+export type DatasetKey = "satellite" | "robotics" | "precision" | "motor";+// One industry story's worth of data. The tiers hold the insertion logic; a// Dataset holds everything that differs between stories.export type Dataset = {@@ -797,6 +2154,7 @@ export type Dataset = {quality: QualityData;changeOrders: ChangeOrderData;accounting: AccountingData;+ ops: OpsData;workflows: WorkflowData;planning: PlanningData;};@@ -835,14 +2193,6 @@ export type ItemRef = {unitOfMeasureCode: string;};-export type ItemType =- | "Part"- | "Material"- | "Tool"- | "Consumable"- | "Service"- | "Fixture";-export type Ctx = {client: PoolClient;companyId: string;diff --git a/packages/database/src/datasets/validate.ts b/packages/database/src/datasets/validate.tsnew file mode 100644index 0000000000..8a796fd457--- /dev/null+++ b/packages/database/src/datasets/validate.ts@@ -0,0 +1,6711 @@+// Pure, DB-free validation of a Dataset's internal consistency (reads the bundled+// assembly graph.json sidecars from disk); `pnpm db:check:datasets` covers the live+// schema. RULES order is the order violations are listed in.++import { existsSync, readFileSync } from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";+import {+ accounts,+ changeOrderRequiredActions,+ changeOrderTypes,+ currencies,+ dimensions,+ failureModes,+ gaugeTypes,+ nonConformanceRequiredActions,+ nonConformanceTypes,+ paymentTerms,+ periodCloseTaskDefinitions,+ returnReasons,+ scrapReasons,+ unitOfMeasures+} from "../../supabase/functions/lib/seed.data.ts";+import { EPSILON, round } from "../../supabase/functions/shared/precision.ts";+import { Constants } from "../types.ts";+import { NOT_CLOSED_MIN_OFFSET, OPEN_PERIOD_MIN_OFFSET } from "./dates.ts";+import {+ deriveSampleStatus,+ resolveInspectionPlan+} from "./helpers/inspection.ts";+import {+ isBalanced,+ memoJournal,+ type PostingJournal,+ paymentJournal,+ postingImbalance,+ purchaseInvoiceJournal,+ receiptJournal,+ salesInvoiceJournal,+ scrapJournal,+ shipmentJournal,+ signedNet,+ voidJournal+} from "./helpers/posting-journals.ts";+import { RULE_FIELDS, type RuleValueKind } from "./rule-fields.ts";+import type {+ AccountClass,+ BankAccountSpec,+ BopOperationSpec,+ Dataset,+ EnforcementRuleSpec,+ InspectionFeatureSpec,+ InspectionPlanSpec,+ InstantSpec,+ ItemSpec,+ ItemsData,+ JobSpec,+ JournalEntrySpec,+ JournalLineSpec,+ MakeMethodSpec,+ ReturnCreditSpec,+ RuleConditionValue,+ RuleOperator,+ SalesOpportunitySpec+} from "./types.ts";++export const OPEN_JOB_STATUSES = new Set([+ "Planned",+ "Ready",+ "In Progress",+ "Paused"+]);+export const RELEASED_OPEN_JOB_STATUSES = new Set([+ "Ready",+ "In Progress",+ "Paused"+]);+export const OPEN_NCR_STATUSES = new Set(["Registered", "In Progress"]);+export const OPEN_NCR_TASK_STATUSES = new Set(["Pending", "In Progress"]);++export const HORIZON_DAYS = 48 * 7; // tier 12 seeds a 48-week planning horizon++/** tier 06 opens production.openEvent at this UTC time today. */+export const OPEN_EVENT_TIME = "08:00:00";++export const TIME_OF_DAY = /^([01]\d|2[0-3]):[0-5]\d:[0-5]\d$/;++export function secondsOfDay(time: string): number | null {+ if (!TIME_OF_DAY.test(time)) return null;+ const [h, m, sec] = time.split(":").map(Number);+ return h! * 3600 + m! * 60 + sec!;+}++export function checkInstant(+ fail: (message: string) => void,+ where: string,+ instant: InstantSpec+): void {+ if (secondsOfDay(instant.time) === null) {+ fail(`${where}: time "${instant.time}" is not a UTC "HH:MM:SS"`);+ }+}++export const COUNTRY_CODE = /^[A-Z]{2}$/;++export const PAYMENT_TERM_NAMES = new Set<string>(+ paymentTerms.map((pt) => pt.name)+);+export const RETURN_REASON_NAMES = new Set<string>(returnReasons);+export const SCRAP_REASON_NAMES = new Set<string>(scrapReasons);+export const NCR_TYPE_NAMES = new Set<string>(+ nonConformanceTypes.map((t) => t.name)+);+export const NCR_ACTION_NAMES = new Set<string>(+ nonConformanceRequiredActions.map((a) => a.name)+);+export const GAUGE_TYPE_NAMES = new Set<string>(gaugeTypes);+export const CO_TYPE_NAMES = new Set<string>(+ changeOrderTypes.map((t) => t.name)+);+export const CO_ACTION_NAMES = new Set<string>(+ changeOrderRequiredActions.map((a) => a.name)+);+export const UOM_CODES = new Set<string>(unitOfMeasures.map((u) => u.code));+export const FAILURE_MODE_NAMES = new Set<string>(failureModes);++export const ACCOUNT_CLASS_BY_NUMBER = new Map<string, AccountClass>(+ accounts.flatMap((a) =>+ !a.isGroup && a.number && a.class+ ? [[a.number, a.class as AccountClass] as const]+ : []+ )+);+export const BOOTSTRAP_DIMENSION_NAMES = new Set<string>(+ dimensions.map((d) => d.name)+);+export const CLOSE_TASK_DEFINITION_NAMES = new Set<string>(+ periodCloseTaskDefinitions.map((d) => d.name)+);++/** USD is every seeded company's base currency. */+export const USD_DECIMALS = currencies.find(+ (c) => c.code === "USD"+)!.decimalPlaces;++// Value sets every dataset must exhibit, so an edit can't silently drop a state+// the docs screenshot. Enum-backed sets are the DB enum minus `except`, so a new+// enum value fails every dataset until one exhibits it or it is excluded here.++type Enums = typeof Constants.public.Enums;++function enumValues<K extends keyof Enums>(+ name: K,+ except: Partial<Record<Enums[K][number], string>> = {}+): readonly Enums[K][number][] {+ return Constants.public.Enums[name].filter((value) => !(value in except));+}++const matrix =+ (scope: string, what: string, tail = "the full required set") =>+ (value: string) =>+ `${scope}: no ${what} "${value}" — every dataset must exhibit ${tail}`;++type Coverage = {+ values: readonly string[];+ missing: (value: string) => string;+};++const NOT_AUTHORABLE = "the dataset types cannot author it";+const OPTIONAL = "authorable, not required";++export const COVERAGE = {+ salesRfq: {+ values: enumValues("salesRfqStatus"),+ missing: matrix("sales status matrix", "salesRfq with status")+ },+ quote: {+ values: enumValues("quoteStatus"),+ missing: matrix("sales status matrix", "quote with status")+ },+ quoteLine: {+ values: enumValues("quoteLineStatus"),+ missing: matrix("sales status matrix", "quoteLine with status")+ },+ salesOrder: {+ values: enumValues("salesOrderStatus"),+ missing: matrix("sales status matrix", "salesOrder with status")+ },+ shipment: {+ values: enumValues("shipmentStatus", {+ Pending: "transient; the seed posts directly"+ }),+ missing: matrix("sales status matrix", "shipment with status")+ },+ salesInvoice: {+ values: enumValues("salesInvoiceStatus", {+ Pending: "transient; the seed posts directly",+ Return: "the return-invoice flow only"+ }),+ missing: matrix("sales status matrix", "salesInvoice with status")+ },+ salesReturn: {+ values: enumValues("salesReturnOrderStatus", { Cancelled: OPTIONAL }),+ missing: matrix("sales status matrix", "salesReturn with status")+ },+ arAgingBucket: {+ // get_ar_aging's default buckets, by days past due as of today.+ values: ["Current", "1-30", "31-60", "61-90"],+ missing: (bucket) =>+ `sales invoices: no open invoice in the "${bucket}" receivables aging bucket`+ },++ purchaseOrder: {+ values: enumValues("purchaseOrderStatus"),+ missing: matrix("purchasing status matrix", "purchaseOrder with status")+ },+ receipt: {+ values: enumValues("receiptStatus", {+ Pending: "transient; the seed posts directly"+ }),+ missing: matrix("purchasing status matrix", "receipt with status")+ },+ purchaseInvoice: {+ values: enumValues("purchaseInvoiceStatus", {+ Pending: "transient; the seed posts directly",+ Return: "the return-invoice flow only"+ }),+ missing: matrix("purchasing status matrix", "purchaseInvoice with status")+ },+ purchaseReturn: {+ values: enumValues("purchaseReturnOrderStatus", { Cancelled: OPTIONAL }),+ missing: matrix(+ "purchasing status matrix",+ "purchaseReturnOrder with status"+ )+ },+ supplierQuote: {+ values: enumValues("supplierQuoteStatus", { Cancelled: OPTIONAL }),+ missing: matrix("purchasing status matrix", "supplierQuote with status")+ },+ purchasingRfq: {+ values: enumValues("purchasingRfqStatus"),+ missing: matrix("purchasing status matrix", "purchasingRfq with status")+ },+ approvalRequestType: {+ values: enumValues("approvalDocumentType", {+ qualityDocument: "the seed requests approval for orders and suppliers"+ }),+ missing: (type) => `purchasing.approvalRequests: no ${type} request`+ },++ procedureStatus: {+ values: enumValues("procedureStatus"),+ missing: matrix(+ "foundation status matrix",+ "procedure version with status",+ "all three"+ )+ },+ trackedEntityStatus: {+ values: enumValues("trackedEntityStatus", {+ Available: "opening lots exhibit it",+ Reserved: "job reservations exhibit it",+ Consumed: "genealogy exhibits it"+ }),+ missing: matrix(+ "inventory status matrix",+ "tracked entity with status",+ "it"+ )+ },+ jobDeadlineType: {+ values: enumValues("deadlineType"),+ missing: matrix(+ "production status matrix",+ "job with deadlineType",+ "all four"+ )+ },+ jobOperationOverride: {+ values: enumValues("jobOperationStatus", {+ Todo: "operationStatusFor derives it",+ Ready: "operationStatusFor derives it",+ Done: "operationStatusFor derives it",+ Canceled: "operationStatusFor derives it",+ Paused: "operationStatusFor derives it"+ }),+ missing: matrix(+ "production status matrix",+ "operationOverride with status",+ "the mixed-floor states"+ )+ },+ productionQuantityType: {+ values: enumValues("productionQuantityType"),+ missing: matrix(+ "production status matrix",+ "productionQuantity spec of type",+ "all three"+ )+ },+ pickingListStatus: {+ values: enumValues("pickingListStatus", {+ Draft: NOT_AUTHORABLE,+ Cancelled: NOT_AUTHORABLE,+ Partial: NOT_AUTHORABLE+ }),+ missing: matrix(+ "production status matrix",+ "picking list with status",+ "both"+ )+ },++ ncrStatus: {+ values: enumValues("nonConformanceStatus"),+ missing: matrix("quality matrix", "nonConformance status")+ },+ ncrPriority: {+ values: enumValues("nonConformancePriority"),+ missing: matrix("quality matrix", "nonConformance priority")+ },+ ncrSource: {+ values: enumValues("nonConformanceSource"),+ missing: matrix("quality matrix", "nonConformance source")+ },+ ncrTaskStatus: {+ values: enumValues("nonConformanceTaskStatus", {+ Skipped: "nothing in the issue flow requires skipping a task"+ }),+ missing: matrix("quality matrix", "nonConformanceActionTask status")+ },+ qualityDocumentStatus: {+ values: enumValues("qualityDocumentStatus"),+ missing: matrix("quality matrix", "qualityDocument status")+ },+ gaugeStatus: {+ values: enumValues("gaugeStatus"),+ missing: matrix("quality matrix", "gauge status")+ },+ gaugeCalibrationStatus: {+ values: enumValues("gaugeCalibrationStatus"),+ missing: matrix("quality matrix", "gauge calibration status")+ },+ riskStatus: {+ values: enumValues("riskStatus"),+ missing: matrix("quality matrix", "riskRegister status")+ },+ riskSource: {+ values: enumValues("riskSource", {+ "Quote Line": NOT_AUTHORABLE,+ "Work Center": OPTIONAL+ }),+ missing: matrix("quality matrix", "riskRegister source")+ },+ riskType: {+ values: enumValues("riskRegisterType"),+ missing: matrix("quality matrix", "riskRegister type")+ },+ inspectionStatus: {+ values: enumValues("inspectionStatusType", {+ "In Progress": OPTIONAL,+ Failed: NOT_AUTHORABLE+ }),+ missing: matrix("quality status matrix", "inspection lot with status")+ },+ inspectionSource: {+ values: enumValues("inspectionSourceDocument"),+ missing: matrix("quality status matrix", "inspection lot with source")+ },++ changeOrderStatus: {+ values: enumValues("changeOrderStatus"),+ missing: matrix("change order matrix", "changeOrder status")+ },+ changeOrderTaskStatus: {+ values: enumValues("changeOrderTaskStatus"),+ missing: matrix("change order matrix", "changeOrderActionTask status")+ },++ journalStatus: {+ values: enumValues("journalEntryStatus"),+ missing: (status) => `accounting.journalEntries: no "${status}" entry`+ },+ memoDirection: {+ values: enumValues("memoDirection"),+ missing: (direction) => `accounting.memos: no "${direction}" memo`+ },+ paymentType: {+ values: enumValues("paymentType"),+ missing: (type) => `accounting.payments: no "${type}" payment`+ },+ /** Draft payments render the payment's apply table. */+ draftPaymentType: {+ values: enumValues("paymentType"),+ missing: (type) => `accounting.payments: no Draft "${type}" payment`+ },+ periodCloseTaskStatus: {+ values: ["Open", "Done", "Skipped"],+ missing: (status) => `accounting.closeTasks: no "${status}" task`+ },+ fixedAssetStatus: {+ values: enumValues("fixedAssetStatus"),+ missing: (status) => `accounting.fixedAssets: no "${status}" asset`+ },++ dispatchStatus: {+ values: enumValues("maintenanceDispatchStatus"),+ missing: matrix("ops matrix", "maintenance dispatch with status")+ },+ dispatchSeverity: {+ values: enumValues("maintenanceSeverity"),+ missing: matrix("ops matrix", "maintenance dispatch with severity")+ },+ dispatchSource: {+ values: enumValues("maintenanceSource"),+ missing: matrix("ops matrix", "maintenance dispatch with source")+ },+ dispatchOeeImpact: {+ values: enumValues("oeeImpact"),+ missing: matrix("ops matrix", "maintenance dispatch with oeeImpact")+ },+ trainingStatus: {+ values: enumValues("trainingStatus", { Archived: OPTIONAL }),+ missing: matrix("ops matrix", "training with status")+ },+ workflowRunStatus: {+ values: ["Succeeded", "Failed", "Skipped"],+ missing: matrix("workflow run matrix", "run with status")+ },++ userAttributeType: {+ values: ["Date", "List", "User"],+ missing: (type) => `ops.userAttributeCategories: no ${type} attribute`+ },+ /** `<table>|<dataType>` */+ customField: {+ values: ["part|Text", "customer|User", "job|Yes/No"],+ missing: (key) => {+ const [table, dataType] = key.split("|");+ return `ops.customFields: no ${dataType} field on "${table}"`;+ }+ },+ printJobStatus: {+ values: ["completed", "failed", "queued"],+ missing: (status) => `ops.printJobs: no ${status} job`+ },+ printJobOrigin: {+ values: ["auto", "manual", "reprint"],+ missing: (origin) => `ops.printJobs: no ${origin} job`+ },++ enforcementRuleShape: {+ values: ["sales", "storage:item", "storage:workCenter"] as const,+ missing: (shape) =>+ `items.enforcementRules: no ${shape} rule — every rules screen must list one`+ },+ salesRuleSeverity: {+ values: ["error", "warn"],+ missing: (severity) =>+ `items.enforcementRules: no sales rule with severity "${severity}"`+ }+} satisfies Record<string, Coverage>;++export type CoverageKey = keyof typeof COVERAGE;++export function checkCoverage(+ fail: (message: string) => void,+ exhibited: Partial<Record<CoverageKey, ReadonlySet<string>>>+): void {+ for (const [key, seen] of Object.entries(exhibited)) {+ const { values, missing } = COVERAGE[key as CoverageKey];+ for (const value of values) if (!seen?.has(value)) fail(missing(value));+ }+}++export type RuleShape = (typeof COVERAGE.enforcementRuleShape.values)[number];++export const TRAINING_QUESTION_TYPES = enumValues("trainingQuestionType");++export function lineClass(line: JournalLineSpec): AccountClass | undefined {+ return line.accountClass ?? ACCOUNT_CLASS_BY_NUMBER.get(line.account ?? "");+}++/** The journalEntries view signs amounts by account class, as posting does. */+export function journalImbalance(entry: JournalEntrySpec): number {+ return signedNet(+ entry.lines.flatMap((line) => {+ const accountClass = lineClass(line);+ // An unknown account is reported separately.+ return accountClass ? [{ accountClass, amount: line.amount }] : [];+ })+ );+}++// Read with node:fs: assets.ts needs a bundler, so the validator cannot import it.++type GraphNode = {+ nodeId?: string;+ geometryHash?: string | null;+ isAssembly?: boolean;+ children?: GraphNode[];+};++function collectNodeIds(node: GraphNode, into: Set<string>): void {+ if (node.nodeId) into.add(node.nodeId);+ for (const child of node.children ?? []) collectNodeIds(child, into);+}++/** Leaf geometry hashes — what assemblyComponentMapping keys a component by. */+function collectGeometryHashes(node: GraphNode, into: Set<string>): void {+ if (node.geometryHash && !node.isAssembly) into.add(node.geometryHash);+ for (const child of node.children ?? []) collectGeometryHashes(child, into);+}++export function loadAssemblyGraph(+ industryId: string,+ model: string+): {+ nodeIds: Set<string>;+ geometryHashes: Set<string>;+ componentCount: number;+} | null {+ const datasetsDir = path.dirname(fileURLToPath(import.meta.url));+ const graphPath = path.join(+ datasetsDir,+ "assets",+ industryId,+ "models",+ `${model}.graph.json`+ );+ if (!existsSync(graphPath)) return null;+ const graph = JSON.parse(readFileSync(graphPath, "utf8")) as {+ componentCount: number;+ root: GraphNode;+ };+ const nodeIds = new Set<string>();+ collectNodeIds(graph.root, nodeIds);+ const geometryHashes = new Set<string>();+ collectGeometryHashes(graph.root, geometryHashes);+ return { nodeIds, geometryHashes, componentCount: graph.componentCount };+}++export type BomWalks = {+ methodByItem: Map<string, MakeMethodSpec>;+ /** What a job's jobMaterial rows, and so a picking line, may name. */+ componentsOf(rootItem: string): Set<string>;+ rootOpCountOf(item: string): number;+ /** Root operations in the order the tier resolves 1-based positions against. */+ rootOpsOf(item: string): BopOperationSpec[];+ /** Ops copyMethodToJob adds beyond the root: each Make-to-Order subassembly's, recursively. */+ subassemblyOpsOf(item: string): BopOperationSpec[];+};++export function bomWalks(+ items: ItemsData,+ makePartIds: ReadonlySet<string>+): BomWalks {+ const methodByItem = new Map(+ items.methods.map((method) => [method.readableId, method])+ );+ const componentsOf = (rootItem: string): Set<string> => {+ const components = new Set<string>();+ const visited = new Set<string>();+ const stack = [rootItem];+ while (stack.length > 0) {+ const current = stack.pop()!;+ if (visited.has(current)) continue;+ visited.add(current);+ const method = methodByItem.get(current);+ if (!method) continue;+ for (const line of method.bom) {+ components.add(line.component);+ stack.push(line.component);+ }+ }+ return components;+ };+ const subassemblyOpsOf = (+ item: string,+ path: ReadonlySet<string> = new Set([item])+ ): BopOperationSpec[] => {+ const out: BopOperationSpec[] = [];+ for (const line of methodByItem.get(item)?.bom ?? []) {+ const madeHere =+ (line.methodType ??+ (makePartIds.has(line.component) ? "Make to Order" : "")) ===+ "Make to Order";+ if (!madeHere || path.has(line.component)) continue;+ out.push(...(methodByItem.get(line.component)?.bop ?? []));+ out.push(+ ...subassemblyOpsOf(line.component, new Set([...path, line.component]))+ );+ }+ return out;+ };+ return {+ methodByItem,+ componentsOf,+ rootOpCountOf: (item) => methodByItem.get(item)?.bop.length ?? 0,+ rootOpsOf: (item) =>+ [...(methodByItem.get(item)?.bop ?? [])].sort(+ (a, b) => a.order - b.order+ ),+ subassemblyOpsOf: (item) => subassemblyOpsOf(item)+ };+}++// Document refs in tier registration order, as tier N's ctx.refs.documents holds them.++export type DocumentRefs = {+ duplicates: Array<{ where: string; ref: string }>;+ has(ref: string, seen: number): boolean;+ /**+ * Registrations visible when each reader's tier runs: an RMA, job or NCR sees+ * refs up to its own; risks the whole quality slice; workflow all through accounting.+ */+ seenBy: {+ salesReturns: number[];+ jobs: number[];+ nonConformances: number[];+ risks: number;+ workflowRuns: number;+ };+};++export function documentRefs(dataset: Dataset): DocumentRefs {+ const firstSeen = new Map<string, number>();+ const duplicates: DocumentRefs["duplicates"] = [];+ let count = 0;+ const register = (where: string, ref: string) => {+ if (firstSeen.has(ref)) duplicates.push({ where, ref });+ else firstSeen.set(ref, count);+ count += 1;+ };+ const seenBy: DocumentRefs["seenBy"] = {+ salesReturns: [],+ jobs: [],+ nonConformances: [],+ risks: 0,+ workflowRuns: 0+ };++ const opportunity = (where: string, spec: SalesOpportunitySpec) => {+ register(where, spec.ref);+ if (spec.rfq) register(where, spec.rfq.ref);+ if (spec.quote) {+ register(where, spec.quote.ref);+ for (const line of spec.quote.lines) register(where, line.ref);+ if (spec.quote.externalLink) {+ register(where, spec.quote.externalLink.ref);+ }+ }+ if (spec.order) {+ register(where, spec.order.ref);+ for (const line of spec.order.lines) register(where, line.ref);+ }+ if (spec.shipment) register(where, spec.shipment.ref);+ if (spec.invoice) {+ register(where, spec.invoice.ref);+ if (spec.invoice.key !== undefined) {+ register(where, `sinv:${spec.invoice.key}`);+ }+ }+ };+ const sales = dataset.sales;+ for (const [index, spec] of sales.opportunities.entries()) {+ opportunity(`sales.opportunities[${index}]`, spec);+ }+ for (const spec of sales.statusOrders) {+ const where = `sales.statusOrders "${spec.key}"`;+ register(where, `so:${spec.key}`);+ register(where, `soline:${spec.key}`);+ register(where, `opp:${spec.key}`);+ }+ for (const [index, spec] of sales.releasedOrders.entries()) {+ opportunity(`sales.releasedOrders[${index}]`, spec);+ }+ for (const rma of sales.salesReturns) {+ register(`sales.salesReturns "${rma.key}"`, `rma:${rma.key}`);+ seenBy.salesReturns.push(count);+ }++ const p = dataset.purchasing;+ for (const quote of p.rfqQuotes) {+ register(`purchasing.rfqQuotes "${quote.key}"`, `sq:${quote.key}`);+ }+ register("purchasing.rfqHeader", p.rfqHeader.ref);+ register("purchasing", `po:sq-${p.rfqWinningQuote}`);+ for (const rfq of p.lifecycleRfqs) {+ register(`purchasing.lifecycleRfqs "${rfq.ref}"`, rfq.ref);+ }+ for (const quote of p.standaloneSupplierQuotes) {+ register(+ `purchasing.standaloneSupplierQuotes "${quote.key}"`,+ `sq:${quote.key}`+ );+ }+ for (const [index, po] of p.purchaseOrders.entries()) {+ if (po.source !== "direct") continue;+ const where = `purchasing.purchaseOrders[${index}]`;+ if (po.ref !== undefined) register(where, po.ref);+ if (po.receipt) register(where, po.receipt.ref);+ if (po.invoice) {+ register(where, po.invoice.ref);+ if (po.invoice.key !== undefined) {+ register(where, `pinv:${po.invoice.key}`);+ }+ }+ }+ for (const ret of p.purchaseReturns) {+ register(`purchasing.purchaseReturns "${ret.key}"`, `pret:${ret.key}`);+ }++ for (const job of dataset.production.jobs) {+ register(`production.jobs "${job.key}"`, `job:${job.key}`);+ seenBy.jobs.push(count);+ }+ register(+ "production.genealogyAssembly",+ dataset.production.genealogyAssembly.ref+ );++ for (const insp of dataset.quality.inspections) {+ register(`quality.inspections "${insp.ref}"`, insp.ref);+ }+ for (const ncr of dataset.quality.nonConformances) {+ register(`quality.nonConformances "${ncr.ref}"`, ncr.ref);+ seenBy.nonConformances.push(count);+ }+ seenBy.risks = count;++ for (const co of dataset.changeOrders.changeOrders) {+ register(`changeOrders "${co.ref}"`, co.ref);+ }++ const a = dataset.accounting;+ for (const entry of a.journalEntries) {+ register("accounting.journalEntries", entry.ref);+ if (entry.reversal) {+ register("accounting.journalEntries", entry.reversal.ref);+ }+ }+ for (const memo of a.memos) {+ register(`accounting.memos "${memo.key}"`, `memo:${memo.key}`);+ }+ for (const payment of a.payments) {+ register(`accounting.payments "${payment.key}"`, `payment:${payment.key}`);+ }+ for (const asset of a.fixedAssets) {+ register("accounting.fixedAssets", `fixedAsset:${asset.key}`);+ }+ seenBy.workflowRuns = count;++ register("planning.demandOrder", dataset.planning.demandOrder.ref);++ return {+ duplicates,+ has: (ref, seen) => (firstSeen.get(ref) ?? Number.POSITIVE_INFINITY) < seen,+ seenBy+ };+}++export type FloorState = {+ openByWorkCenter: Map<string, number>;+ running: Set<string>;+ /** Work centers with an operation In Progress, timer or not. */+ active: Set<string>;+ assignedOpen: number;+ openInspection: boolean;+ /** The batch's first member runs the batch timer on an operation with no work center. */+ batchLeadWithoutWorkCenter: boolean;+};++export function floorState(+ dataset: Dataset,+ jobByKey: ReadonlyMap<string, JobSpec>,+ bom: BomWalks+): FloorState {+ const production = dataset.production;+ const { rootOpsOf, subassemblyOpsOf } = bom;+ const released = production.jobs.filter((job) =>+ RELEASED_OPEN_JOB_STATUSES.has(job.status)+ );+ // Open operations per work center, as the MES board filters them: released+ // job, operation not Done / Canceled. Overrides reach root operations only.+ const openByWorkCenter = new Map<string, number>();+ const running = new Set<string>();+ const active = new Set<string>();+ let assignedOpen = 0;+ let openInspection = false;+ const bump = (workCenter: string | undefined) => {+ if (workCenter === undefined) return;+ openByWorkCenter.set(+ workCenter,+ (openByWorkCenter.get(workCenter) ?? 0) + 1+ );+ };+ for (const job of released) {+ const initial = job.status === "Paused" ? "Paused" : "Ready";+ const roots = rootOpsOf(job.item);+ const overrides = new Map(+ (job.operationOverrides ?? []).map((o) => [o.order, o])+ );+ const ops: Array<{+ op: BopOperationSpec;+ status: string;+ root: boolean;+ order: number;+ }> = [+ ...roots.map((op, index) => ({+ op,+ status: overrides.get(index + 1)?.status ?? initial,+ root: true,+ order: index + 1+ })),+ ...subassemblyOpsOf(job.item).map((op) => ({+ op,+ status: initial,+ root: false,+ order: 0+ }))+ ];+ for (const { op, status, root, order } of ops) {+ if (status === "Done" || status === "Canceled") continue;+ bump(op.workCenter);+ if (op.operationType === "Inspection") openInspection = true;+ if (!root) continue;+ const override = overrides.get(order);+ if (override?.assignee === "self") assignedOpen += 1;+ if (override?.running && op.workCenter) running.add(op.workCenter);+ if (status === "In Progress" && op.workCenter) active.add(op.workCenter);+ }+ }+ const eventsJob = jobByKey.get(production.eventsJobKey);+ if (eventsJob) {+ const workCenter = rootOpsOf(eventsJob.item)[+ production.openEvent.operationOrder - 1+ ]?.workCenter;+ if (workCenter) {+ running.add(workCenter);+ active.add(workCenter);+ }+ }+ let batchLeadWithoutWorkCenter = false;+ const batchLead = production.batch.members[0];+ const batchLeadJob = batchLead && jobByKey.get(batchLead.job);+ if (batchLead && batchLeadJob) {+ const workCenter = rootOpsOf(batchLeadJob.item)[batchLead.order - 1]+ ?.workCenter;+ if (workCenter) {+ running.add(workCenter);+ active.add(workCenter);+ } else {+ batchLeadWithoutWorkCenter = true;+ }+ }+ return {+ openByWorkCenter,+ running,+ active,+ assignedOpen,+ openInspection,+ batchLeadWithoutWorkCenter+ };+}++// Net on-hand per (item, shelf). A movement its slice's rule rejects is left out,+// as the tier would never write it.++export const onHandKey = (item: string, shelf: string) => `${item} @ ${shelf}`;++export function onHandLedger(+ dataset: Dataset,+ shelves: ReadonlySet<string>,+ isTracked: (item: string) => boolean,+ jobByKey: ReadonlyMap<string, JobSpec>+): Map<string, number> {+ const onHand = new Map<string, number>();+ const add = (item: string, shelf: string, delta: number) => {+ const key = onHandKey(item, shelf);+ onHand.set(key, (onHand.get(key) ?? 0) + delta);+ };+ const inventory = dataset.inventory;++ for (const stock of inventory.openingStock) {+ add(stock.item, stock.shelf, stock.qty);+ }+ for (const tracked of inventory.onHandTracked) {+ for (const entity of tracked.entities) {+ if (entity.scrap) add(tracked.item, entity.scrap.shelf, -entity.quantity);+ }+ }+ for (const count of inventory.inventoryCounts) {+ if (count.status !== "Posted") continue;+ for (const line of count.lines) {+ const delta = line.countedQuantity - line.snapshotQuantity;+ if (delta !== 0) add(line.item, line.shelf, delta);+ }+ }+ for (const transfer of inventory.stockTransfers) {+ if (transfer.status !== "Completed") continue;+ for (const line of transfer.lines) {+ add(line.item, transfer.fromShelf, -line.quantity);+ add(line.item, transfer.toShelf, line.quantity);+ }+ }+ for (const transfer of inventory.warehouseTransfers) {+ if (transfer.status !== "Completed") continue;+ for (const line of transfer.lines) {+ if (line.fromShelf !== undefined) {+ add(line.item, line.fromShelf, -line.quantity);+ }+ }+ }++ const shipped = (spec: SalesOpportunitySpec) => {+ if (spec.shipment?.status !== "Posted") return;+ for (const line of spec.shipment.lines) {+ if (+ line.shippedQuantity > 0 &&+ line.fromShelf !== undefined &&+ !isTracked(line.item) &&+ shelves.has(line.fromShelf)+ ) {+ add(line.item, line.fromShelf, -line.shippedQuantity);+ }+ }+ };+ for (const spec of dataset.sales.opportunities) shipped(spec);+ for (const spec of dataset.sales.releasedOrders) shipped(spec);+ for (const rma of dataset.sales.salesReturns) {+ if (rma.status !== "Completed") continue;+ for (const line of rma.lines) {+ if (line.toShelf !== undefined && shelves.has(line.toShelf)) {+ add(line.item, line.toShelf, line.quantity);+ }+ }+ }++ for (const po of dataset.purchasing.purchaseOrders) {+ if (po.source !== "direct" || po.receipt?.status !== "Posted") continue;+ for (const line of po.receipt.lines) {+ if (+ line.receivedQuantity > 0 &&+ line.toShelf !== undefined &&+ shelves.has(line.toShelf)+ ) {+ add(line.item, line.toShelf, line.receivedQuantity);+ }+ }+ }+ for (const ret of dataset.purchasing.purchaseReturns) {+ if (ret.status !== "Completed") continue;+ for (const line of ret.lines) {+ if (line.fromShelf !== undefined && shelves.has(line.fromShelf)) {+ add(line.item, line.fromShelf, -line.quantity);+ }+ }+ }++ for (const list of dataset.production.pickingLists) {+ if (!jobByKey.has(list.job) || list.status !== "Completed") continue;+ for (const line of list.lines) {+ if (shelves.has(line.fromShelf)) {+ add(line.item, line.fromShelf, -line.quantityPicked);+ }+ }+ }+ for (const dispatch of dataset.ops.maintenanceDispatches) {+ if (dispatch.status !== "Completed") continue;+ for (const part of dispatch.spareParts ?? []) {+ if (shelves.has(part.shelf)) add(part.item, part.shelf, -part.quantity);+ }+ }+ return onHand;+}++export type LotRegistry = {+ onHandIds: Set<string>;+ receiptLotIds: Set<string>;+ mintedReceiptLines: Set<string>;+};++export const receiptLineKey = (poIndex: number, lineIndex: number) =>+ `${poIndex}:${lineIndex}`;++export function lotRegistry(+ dataset: Dataset,+ trackingByItem: ReadonlyMap<string, string>+): LotRegistry {+ const onHandIds = new Set<string>();+ for (const tracked of dataset.inventory.onHandTracked) {+ for (const entity of tracked.entities) onHandIds.add(entity.readableId);+ }+ const receiptLotIds = new Set<string>();+ const mintedReceiptLines = new Set<string>();+ for (const [poIndex, po] of dataset.purchasing.purchaseOrders.entries()) {+ if (po.source !== "direct" || po.receipt?.status !== "Posted") continue;+ for (const [lineIndex, line] of po.receipt.lines.entries()) {+ if (+ !(line.receivedQuantity > 0) ||+ trackingByItem.get(line.item) !== "Batch" ||+ !line.requiresBatchTracking ||+ line.lotNumber === undefined ||+ onHandIds.has(line.lotNumber) ||+ receiptLotIds.has(line.lotNumber)+ ) {+ continue;+ }+ receiptLotIds.add(line.lotNumber);+ mintedReceiptLines.add(receiptLineKey(poIndex, lineIndex));+ }+ }+ return { onHandIds, receiptLotIds, mintedReceiptLines };+}++export const REF_LABELS = {+ item: "item",+ customer: "customer",+ supplier: "supplier",+ process: "process",+ ability: "ability",+ department: "department",+ workCenter: "work center",+ maintainedWorkCenter: "work center",+ warehouse: "warehouse",+ shelf: "shelf",+ shift: "shift",+ storageType: "storageType",+ customerType: "customer type",+ supplierType: "supplier type",+ substance: "material substance",+ form: "material form",+ materialType: "material type",+ grade: "material grade",+ finish: "material finish",+ dimension: "material dimension"+} as const;+export type RefKind = keyof typeof REF_LABELS;++export type DatasetIndex = {+ refs: Record<RefKind, Set<string>>;+ itemBuckets: ReadonlyArray<readonly [string, readonly ItemSpec[]]>;+ makePartIds: Set<string>;+ toolIds: Set<string>;+ trackingByItem: Map<string, string>;+ standardCost: Map<string, number>;+ isTracked(item: string): boolean;+ customersWithContacts: Set<string>;+ suppliersWithContacts: Set<string>;+ /** Pending / Rejected / Inactive suppliers exist for the supplier list only. */+ activeSuppliers: Set<string>;+ bom: BomWalks;+ jobByKey: Map<string, JobSpec>;+ orderDateByRef: Map<string, number>;+ documentRefs: DocumentRefs;+ onHand: Map<string, number>;+ lots: LotRegistry;+ ncrRefs: Set<string>;+ floor: FloorState;+};++export function buildIndex(dataset: Dataset): DatasetIndex {+ const f = dataset.foundation;+ const items = dataset.items;+ const itemBuckets = [+ ["items.buyParts", items.buyParts],+ ["items.materials", items.materials],+ ["items.consumables", items.consumables],+ ["items.tools", items.tools],+ ["items.services", items.services],+ ["items.makeParts", items.makeParts]+ ] as const;+ const allItems = itemBuckets.flatMap(([, specs]) => specs);++ const suppliers = new Set(f.suppliers.map((s) => s.name));+ if (f.contractorAgency) suppliers.add(f.contractorAgency.name);+ const processes = new Set(f.processes.map((p) => p.name));+ for (const ability of f.abilities) processes.add(ability); // tier 01 mints a process per ability+ const workCenters = new Set(f.workCenters.map((w) => w.name));+ const taxonomy = f.materialTaxonomy;+ const refs: Record<RefKind, Set<string>> = {+ item: new Set(allItems.map((spec) => spec.readableId)),+ customer: new Set(f.customers.map((c) => c.name)),+ supplier: suppliers,+ process: processes,+ ability: new Set(f.abilities),+ department: new Set(f.departments),+ workCenter: workCenters,+ maintainedWorkCenter: new Set([...workCenters, f.hqWorkCenter.name]),+ warehouse: new Set(f.warehouses.map((w) => w.key)),+ shelf: new Set(f.shelves.map((s) => s.name)),+ shift: new Set(f.shifts.map((shift) => shift.name)),+ storageType: new Set(f.storageTypes),+ customerType: new Set(f.customerTypes),+ supplierType: new Set(f.supplierTypes),+ substance: new Set(taxonomy.substances.map((s) => s.name)),+ form: new Set(taxonomy.forms.map((s) => s.name)),+ materialType: new Set(taxonomy.types.map((t) => t.name)),+ grade: new Set(taxonomy.grades.map((g) => g.name)),+ finish: new Set(taxonomy.finishes.map((fi) => fi.name)),+ dimension: new Set(taxonomy.dimensions.map((d) => d.name))+ };++ const trackingByItem = new Map<string, string>();+ const standardCost = new Map<string, number>();+ for (const spec of allItems) {+ trackingByItem.set(spec.readableId, spec.trackingType ?? "Inventory");+ standardCost.set(spec.readableId, spec.standardCost ?? 0);+ }+ const isTracked = (item: string) => {+ const tracking = trackingByItem.get(item);+ return tracking === "Serial" || tracking === "Batch";+ };++ const activeSuppliers = new Set(+ f.suppliers+ .filter((s) => (s.status ?? "Active") === "Active")+ .map((s) => s.name)+ );+ if (f.contractorAgency) activeSuppliers.add(f.contractorAgency.name);++ const makePartIds = new Set(items.makeParts.map((spec) => spec.readableId));+ const bom = bomWalks(items, makePartIds);+ const jobByKey = new Map(+ dataset.production.jobs.map((job) => [job.key, job])+ );++ const orderDateByRef = new Map<string, number>();+ for (const spec of [+ ...dataset.sales.opportunities,+ ...dataset.sales.releasedOrders+ ]) {+ if (spec.order) {+ orderDateByRef.set(spec.order.ref, spec.order.orderDateOffset);+ }+ }+ for (const spec of dataset.sales.statusOrders) {+ orderDateByRef.set(`so:${spec.key}`, spec.orderDateOffset);+ }++ return {+ refs,+ itemBuckets,+ makePartIds,+ toolIds: new Set(items.tools.map((spec) => spec.readableId)),+ trackingByItem,+ standardCost,+ isTracked,+ customersWithContacts: new Set(f.customerContacts.map((cc) => cc.customer)),+ suppliersWithContacts: new Set(f.supplierContacts.map((sc) => sc.supplier)),+ activeSuppliers,+ bom,+ jobByKey,+ orderDateByRef,+ documentRefs: documentRefs(dataset),+ onHand: onHandLedger(dataset, refs.shelf, isTracked, jobByKey),+ lots: lotRegistry(dataset, trackingByItem),+ ncrRefs: new Set(dataset.quality.nonConformances.map((ncr) => ncr.ref)),+ floor: floorState(dataset, jobByKey, bom)+ };+}++export type ValidationCtx = {+ readonly dataset: Dataset;+ readonly ix: DatasetIndex;+ readonly violations: string[];+ fail(message: string): void;+ need(kind: RefKind, where: string, id: string): void;+ /** Also requires a contact: tier 01 seeds the customer's location from it. */+ needCustomer(where: string, name: string): void;+};++export type Rule = (ctx: ValidationCtx) => void;++export function createContext(dataset: Dataset): ValidationCtx {+ const ix = buildIndex(dataset);+ const violations: string[] = [];+ const fail = (message: string) => {+ violations.push(message);+ };+ return {+ dataset,+ ix,+ violations,+ fail,+ need(kind, where, id) {+ if (!ix.refs[kind].has(id)) {+ fail(`${where}: unknown ${REF_LABELS[kind]} "${id}"`);+ }+ },+ needCustomer(where, name) {+ if (!ix.refs.customer.has(name)) {+ fail(`${where}: unknown customer "${name}"`);+ } else if (!ix.customersWithContacts.has(name)) {+ fail(+ `${where}: customer "${name}" has no customerContact, so no customer location is seeded for it`+ );+ }+ }+ };+}++/** A document ref names one seeded row: tiers key ctx.refs.documents by it. */+export function uniqueDocumentRefs(ctx: ValidationCtx): void {+ for (const { where, ref } of ctx.ix.documentRefs.duplicates) {+ ctx.fail(`${where}: duplicate document ref "${ref}"`);+ }+}++const MIN_PROCEDURES_WITH_PARAMETERS = 2;+const MIN_PARTNERS = 2;++export function foundation(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const f = dataset.foundation;++ const nonEmpty: Array<[string, ReadonlyArray<unknown>]> = [+ ["foundation.departments", f.departments],+ ["foundation.abilities", f.abilities],+ ["foundation.processes", f.processes],+ ["foundation.workCenters", f.workCenters],+ ["foundation.customers", f.customers],+ ["foundation.customerContacts", f.customerContacts],+ ["foundation.suppliers", f.suppliers],+ ["foundation.supplierContacts", f.supplierContacts],+ ["foundation.procedures", f.procedures],+ ["foundation.shippingMethods", f.shippingMethods],+ ["foundation.warehouses", f.warehouses],+ ["foundation.shelves", f.shelves],+ ["foundation.shifts", f.shifts],+ ["foundation.holidays", f.holidays],+ ["foundation.tags", f.tags],+ ["foundation.materialTaxonomy.substances", f.materialTaxonomy.substances],+ ["foundation.materialTaxonomy.forms", f.materialTaxonomy.forms],+ ["foundation.materialTaxonomy.types", f.materialTaxonomy.types],+ ["foundation.materialTaxonomy.grades", f.materialTaxonomy.grades],+ ["foundation.materialTaxonomy.finishes", f.materialTaxonomy.finishes],+ ["foundation.materialTaxonomy.dimensions", f.materialTaxonomy.dimensions],+ ["items.buyParts", dataset.items.buyParts],+ ["items.materials", dataset.items.materials],+ ["items.consumables", dataset.items.consumables],+ ["items.tools", dataset.items.tools],+ ["items.services", dataset.items.services],+ ["items.makeParts", dataset.items.makeParts],+ ["items.methods", dataset.items.methods],+ ["items.supplierLinks", dataset.items.supplierLinks],+ ["items.batchProperties", dataset.items.batchProperties],+ ["items.supersessions", dataset.items.supersessions],+ ["items.customerParts", dataset.items.customerParts],+ ["items.priceOverrides", dataset.items.priceOverrides],+ ["items.pricingRules", dataset.items.pricingRules],+ ["items.revisionLadder", dataset.items.revisionLadder],+ ["inventory.openingStock", dataset.inventory.openingStock],+ ["inventory.onHandTracked", dataset.inventory.onHandTracked],+ ["inventory.kanbanItems", dataset.inventory.kanbanItems],+ ["inventory.inventoryCounts", dataset.inventory.inventoryCounts],+ ["inventory.shelfLives", dataset.inventory.shelfLives],+ ["inventory.stockTransfers", dataset.inventory.stockTransfers],+ ["inventory.warehouseTransfers", dataset.inventory.warehouseTransfers],+ ["sales.opportunities", dataset.sales.opportunities],+ ["sales.statusOrders", dataset.sales.statusOrders],+ ["sales.releasedOrders", dataset.sales.releasedOrders],+ ["sales.salesReturns", dataset.sales.salesReturns],+ ["purchasing.rfqLines", dataset.purchasing.rfqLines],+ ["purchasing.rfqQuotes", dataset.purchasing.rfqQuotes],+ ["purchasing.lifecycleRfqs", dataset.purchasing.lifecycleRfqs],+ ["purchasing.purchaseOrders", dataset.purchasing.purchaseOrders],+ ["production.jobs", dataset.production.jobs],+ ["production.genealogyInputs", dataset.production.genealogyInputs],+ ["production.pickingLists", dataset.production.pickingLists],+ ["quality.workflows", dataset.quality.workflows],+ ["quality.nonConformances", dataset.quality.nonConformances],+ ["quality.inspections", dataset.quality.inspections],+ ["quality.qualityDocuments", dataset.quality.qualityDocuments],+ ["quality.gauges", dataset.quality.gauges],+ ["quality.risks", dataset.quality.risks],+ ["changeOrders.changeOrders", dataset.changeOrders.changeOrders],+ ["accounting.fixedAssets", dataset.accounting.fixedAssets],+ ["accounting.journalEntries", dataset.accounting.journalEntries],+ ["ops.maintenanceSchedules", dataset.ops.maintenanceSchedules],+ ["ops.maintenanceDispatches", dataset.ops.maintenanceDispatches],+ ["ops.replacementParts", dataset.ops.replacementParts],+ ["ops.trainings", dataset.ops.trainings],+ ["ops.timecards", dataset.ops.timecards],+ ["ops.suggestions", dataset.ops.suggestions],+ ["ops.notes", dataset.ops.notes],+ ["workflows.runs", dataset.workflows.runs],+ ["planning.buyItemIds", dataset.planning.buyItemIds],+ ["planning.makeItemIds", dataset.planning.makeItemIds],+ ["planning.demandProjections", dataset.planning.demandProjections]+ ];+ for (const [where, arr] of nonEmpty) {+ if (arr.length === 0) fail(`${where}: must not be empty`);+ }++ if (!f.shippingMethods.includes(f.defaultShippingMethod)) {+ fail(+ `foundation.defaultShippingMethod "${f.defaultShippingMethod}" is not in shippingMethods`+ );+ }+ for (const wc of f.workCenters) {+ need("department", `foundation.workCenters "${wc.name}"`, wc.dept);+ need("ability", `foundation.workCenters "${wc.name}"`, wc.ability);+ }+ {+ const hq = f.hqWorkCenter;+ const where = `foundation.hqWorkCenter "${hq.name}"`;+ if (ix.refs.workCenter.has(hq.name)) {+ fail(`${where}: shares its name with a plant work center`);+ }+ need("department", where, hq.dept);+ need("ability", where, hq.ability);+ }+ // A partner row IS a supplier location, which tier 01 mints per supplier contact.+ const suppliersWithLocations = ix.suppliersWithContacts;+ const partnerKeys = new Set<string>();+ for (const partner of f.partners) {+ const where = `foundation.partners "${partner.supplier}" / "${partner.ability}"`;+ const key = `${partner.supplier}|${partner.ability}`;+ if (partnerKeys.has(key)) fail(`${where}: duplicate partner ability`);+ partnerKeys.add(key);+ if (!suppliersWithLocations.has(partner.supplier)) {+ fail(+ `${where}: supplier has no supplierContact, so no supplier location is seeded for it`+ );+ }+ need("ability", where, partner.ability);+ if (+ !Number.isInteger(partner.hoursPerWeek) ||+ partner.hoursPerWeek <= 0 ||+ partner.hoursPerWeek > 168+ ) {+ fail(`${where}: hoursPerWeek ${partner.hoursPerWeek} must be 1–168`);+ }+ }+ if (f.partners.length < MIN_PARTNERS) {+ fail(+ `foundation.partners: ${f.partners.length} partners, need ≥ ${MIN_PARTNERS} (Resources › Partners)`+ );+ }+ for (const [wcName, processName] of f.workCenterProcessLinks) {+ need("workCenter", "foundation.workCenterProcessLinks", wcName);+ need("process", "foundation.workCenterProcessLinks", processName);+ }+ for (const c of f.customers) {+ need("customerType", `foundation.customers "${c.name}"`, c.type);+ }+ for (const s of f.suppliers) {+ need("supplierType", `foundation.suppliers "${s.name}"`, s.type);+ }++ for (const party of [...f.customers, ...f.suppliers]) {+ if (party.currencyCode && !/^[A-Z]{3}$/.test(party.currencyCode)) {+ fail(+ `foundation parties "${party.name}": currencyCode "${party.currencyCode}" is not a 3-letter ISO code`+ );+ }+ if (party.paymentTerm && !PAYMENT_TERM_NAMES.has(party.paymentTerm)) {+ fail(+ `foundation parties "${party.name}": paymentTerm "${party.paymentTerm}" is not a bootstrap payment term`+ );+ }+ }+ // Convention: every dataset showcases at least one EUR supplier so the FX+ // and multi-currency purchasing screens have a party to render.+ if (!f.suppliers.some((s) => s.currencyCode === "EUR")) {+ fail(`foundation.suppliers: no supplier with currencyCode "EUR"`);+ }++ const holidayOffsets = new Set<number>();+ for (const holiday of f.holidays) {+ if (!Number.isFinite(holiday.dateOffset)) {+ fail(+ `foundation.holidays "${holiday.name}": dateOffset is not a finite number`+ );+ } else if (holidayOffsets.has(holiday.dateOffset)) {+ // holiday has UNIQUE (date, companyId), so a repeated offset would be+ // silently dropped by insertMaybe.+ fail(+ `foundation.holidays "${holiday.name}": duplicate dateOffset ${holiday.dateOffset}`+ );+ }+ holidayOffsets.add(holiday.dateOffset);+ }++ for (const tag of f.tags) {+ if (!tag.name.trim()) fail(`foundation.tags: empty tag name`);+ if (!tag.table.trim()) {+ fail(`foundation.tags "${tag.name}": empty table scope`);+ }+ }++ const taxonomy = f.materialTaxonomy;+ for (const type of taxonomy.types) {+ need(+ "substance",+ `foundation.materialTaxonomy.types "${type.name}"`,+ type.substance+ );+ need("form", `foundation.materialTaxonomy.types "${type.name}"`, type.form);+ }+ for (const grade of taxonomy.grades) {+ need(+ "substance",+ `foundation.materialTaxonomy.grades "${grade.name}"`,+ grade.substance+ );+ }+ for (const finish of taxonomy.finishes) {+ need(+ "substance",+ `foundation.materialTaxonomy.finishes "${finish.name}"`,+ finish.substance+ );+ }+ for (const dimension of taxonomy.dimensions) {+ need(+ "form",+ `foundation.materialTaxonomy.dimensions "${dimension.name}"`,+ dimension.form+ );+ }+ for (const cc of f.customerContacts) {+ need("customer", "foundation.customerContacts", cc.customer);+ }+ for (const sc of f.supplierContacts) {+ need("supplier", "foundation.supplierContacts", sc.supplier);+ }+ for (const sp of f.supplierProcesses) {+ need("supplier", "foundation.supplierProcesses", sp.supplier);+ need("process", "foundation.supplierProcesses", sp.process);+ }+ for (const contractor of f.contractors) {+ need(+ "ability",+ `foundation.contractors "${contractor.lastName}"`,+ contractor.ability+ );+ }+ const staffedWorkCenters = new Set<string>();+ const seenWorkCenterShifts = new Set<string>();+ for (const [wcName, shiftName] of f.workCenterShifts) {+ const key = `${wcName}|${shiftName}`;+ if (seenWorkCenterShifts.has(key)) {+ fail(+ `foundation.workCenterShifts: duplicate link "${wcName}" / "${shiftName}"`+ );+ }+ seenWorkCenterShifts.add(key);+ need("workCenter", "foundation.workCenterShifts", wcName);+ need("shift", "foundation.workCenterShifts", shiftName);+ staffedWorkCenters.add(wcName);+ }+ for (const wc of f.workCenters) {+ if (!staffedWorkCenters.has(wc.name)) {+ fail(+ `foundation.workCenterShifts: work center "${wc.name}" has no shift, so its shift picker and the scheduler's calendar are empty`+ );+ }+ }+ const job = f.employeeJob;+ if (!job.title.trim()) fail("foundation.employeeJob: empty title");+ need("department", "foundation.employeeJob", job.department);+ need("shift", "foundation.employeeJob", job.shift);+ if (!(job.startDateOffset < 0)) {+ fail(+ `foundation.employeeJob: startDateOffset ${job.startDateOffset} must be in the past`+ );+ }++ if (f.contractorAgency) {+ need(+ "supplierType",+ "foundation.contractorAgency",+ f.contractorAgency.type+ );+ }+ const seenShelves = new Set<string>();+ for (const shelf of f.shelves) {+ need("warehouse", `foundation.shelves "${shelf.name}"`, shelf.warehouse);+ need(+ "storageType",+ `foundation.shelves "${shelf.name}"`,+ shelf.storageType+ );+ if (shelf.parent !== undefined && !seenShelves.has(shelf.parent)) {+ fail(+ `foundation.shelves "${shelf.name}": parent "${shelf.parent}" is not defined before it (insertion order matters)`+ );+ }+ seenShelves.add(shelf.name);+ }+ const seenProcedureStatuses = new Set<string>();+ for (const proc of f.procedures) {+ need("process", `foundation.procedures "${proc.name}"`, proc.process);+ for (const version of proc.versions) {+ seenProcedureStatuses.add(version.status);+ }+ const parameterKeys = new Set<string>();+ for (const parameter of proc.parameters ?? []) {+ if (!parameter.key.trim() || !parameter.value.trim()) {+ fail(+ `foundation.procedures "${proc.name}": empty parameter key or value`+ );+ }+ if (parameterKeys.has(parameter.key)) {+ fail(+ `foundation.procedures "${proc.name}": duplicate parameter "${parameter.key}"`+ );+ }+ parameterKeys.add(parameter.key);+ }+ // One released version per procedure — Archived is what a release replaced.+ if (proc.versions.filter((v) => v.status === "Active").length > 1) {+ fail(+ `foundation.procedures "${proc.name}": more than one Active version`+ );+ }+ }+ const withParameters = f.procedures.filter(+ (proc) => (proc.parameters ?? []).length > 0+ ).length;+ if (withParameters < MIN_PROCEDURES_WITH_PARAMETERS) {+ fail(+ `foundation.procedures: ${withParameters} procedures carry parameters, need ≥ ${MIN_PROCEDURES_WITH_PARAMETERS} (procedure Parameters tab)`+ );+ }+ checkCoverage(fail, { procedureStatus: seenProcedureStatuses });+}++export function itemIdentity(ctx: ValidationCtx): void {+ const itemIds = new Set<string>();+ for (const [bucket, specs] of ctx.ix.itemBuckets) {+ for (const spec of specs) {+ if (itemIds.has(spec.readableId)) {+ ctx.fail(`${bucket}: duplicate item readableId "${spec.readableId}"`);+ }+ itemIds.add(spec.readableId);+ }+ }+}++export function items(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need, needCustomer } = ctx;+ const f = dataset.foundation;+ const { makePartIds, toolIds, itemBuckets } = ix;+ const procedures = new Set(f.procedures.map((p) => p.name));+ const supplierProcessKeys = new Set(+ f.supplierProcesses.map((sp) => `sp:${sp.supplier}:${sp.process}`)+ );++ for (const method of dataset.items.methods) {+ const where = `items.methods "${method.readableId}"`;+ if (!makePartIds.has(method.readableId)) {+ fail(`${where}: not a makePart readableId`);+ }+ for (const line of method.bom) {+ need("item", `${where} bom`, line.component);+ }+ for (const op of method.bop) {+ need("process", `${where} bop order ${op.order}`, op.process);+ if (op.workCenter !== undefined)+ need("workCenter", `${where} bop order ${op.order}`, op.workCenter);+ if (+ op.supplierProcess !== undefined &&+ !supplierProcessKeys.has(op.supplierProcess)+ ) {+ fail(+ `${where} bop order ${op.order}: unknown supplier process key "${op.supplierProcess}" (expected "sp:<supplier>:<process>" from foundation.supplierProcesses)`+ );+ }+ if (op.procedure !== undefined) {+ const name = op.procedure.replace(/^procedure:/, "");+ if (!op.procedure.startsWith("procedure:") || !procedures.has(name)) {+ fail(+ `${where} bop order ${op.order}: unknown procedure key "${op.procedure}" (expected "procedure:<name>" from foundation.procedures)`+ );+ }+ }+ }+ }+ for (const link of dataset.items.supplierLinks) {+ need("supplier", "items.supplierLinks", link.supplier);+ need("item", "items.supplierLinks", link.item);+ }++ if (dataset.items.inspectionPlans.length === 0) {+ fail(+ `items.inspectionPlans: empty — the MES inspection view needs an Inspection operation with a plan`+ );+ }+ const inspectionPlanByKey = new Map<string, InspectionPlanSpec>();+ for (const plan of dataset.items.inspectionPlans) {+ const where = `items.inspectionPlans "${plan.key}"`;+ if (inspectionPlanByKey.has(plan.key)) fail(`${where}: duplicate key`);+ inspectionPlanByKey.set(plan.key, plan);+ if (!makePartIds.has(plan.item)) {+ fail(`${where}: "${plan.item}" is not a make part`);+ }+ if (!(plan.aql > 0)) fail(`${where}: aql must be positive`);+ if (plan.features.length === 0) fail(`${where}: no features`);+ }+ const referencedPlans = new Set<string>();+ for (const method of dataset.items.methods) {+ for (const op of method.bop) {+ const where = `items.methods "${method.readableId}" bop order ${op.order}`;+ const isInspection = op.operationType === "Inspection";+ if (isInspection !== (op.inspectionPlan !== undefined)) {+ fail(+ `${where}: an "Inspection" operation and an inspectionPlan go together — the MES inspection view needs both`+ );+ }+ if (op.inspectionPlan === undefined) continue;+ referencedPlans.add(op.inspectionPlan);+ const plan = inspectionPlanByKey.get(op.inspectionPlan);+ if (!plan) {+ fail(`${where}: unknown inspectionPlan "${op.inspectionPlan}"`);+ } else if (plan.item !== method.readableId) {+ fail(+ `${where}: plan "${plan.key}" inspects "${plan.item}" — the BOP picker lists only the item's own plans`+ );+ }+ if (op.workCenter === undefined) {+ fail(`${where}: an Inspection operation needs a work center`);+ }+ }+ }+ for (const key of inspectionPlanByKey.keys()) {+ if (!referencedPlans.has(key)) {+ fail(`items.inspectionPlans "${key}": no BOP operation uses it`);+ }+ }++ const stockedItems = new Set(+ dataset.inventory.openingStock+ .filter((stock) => stock.qty > 0)+ .map((stock) => stock.item)+ );++ for (const method of dataset.items.methods) {+ for (const op of method.bop) {+ for (const tool of op.tools ?? []) {+ if (!toolIds.has(tool.tool)) {+ fail(+ `items.methods "${method.readableId}" bop order ${op.order}: tool "${tool.tool}" is not an items.tools readableId`+ );+ }+ }+ }+ }++ for (const [bucket, specs] of itemBuckets) {+ for (const spec of specs) {+ const classification = spec.material;+ if (!classification) continue;+ const where = `${bucket} "${spec.readableId}" material`;+ if (spec.type !== "Material") {+ fail(`${where}: taxonomy classification on a non-Material item`);+ }+ if (classification.substance !== undefined) {+ need("substance", where, classification.substance);+ }+ if (classification.form !== undefined)+ need("form", where, classification.form);+ if (classification.materialType !== undefined)+ need("materialType", where, classification.materialType);+ if (classification.grade !== undefined)+ need("grade", where, classification.grade);+ if (classification.finish !== undefined)+ need("finish", where, classification.finish);+ if (classification.dimension !== undefined)+ need("dimension", where, classification.dimension);+ }+ }++ for (const [index, spec] of dataset.items.supersessions.entries()) {+ const where = `items.supersessions[${index}]`;+ need("item", where, spec.predecessor);+ need("item", where, spec.successor);+ if (spec.predecessor === spec.successor) {+ fail(`${where}: predecessor and successor are the same item`);+ }+ if (+ ix.refs.item.has(spec.predecessor) &&+ !stockedItems.has(spec.predecessor)+ ) {+ fail(+ `${where}: predecessor "${spec.predecessor}" has no opening stock, so "Consume First" has nothing to consume`+ );+ }+ for (const method of dataset.items.methods) {+ if (method.bom.some((line) => line.component === spec.successor)) {+ fail(+ `${where}: successor "${spec.successor}" is on the BOM of "${method.readableId}" — the successor must only be reached through the live redirect`+ );+ }+ }+ }++ for (const [index, spec] of dataset.items.customerParts.entries()) {+ const where = `items.customerParts[${index}]`;+ need("item", where, spec.item);+ needCustomer(where, spec.customer);+ }++ for (const [index, spec] of dataset.items.priceOverrides.entries()) {+ const where = `items.priceOverrides[${index}]`;+ need("item", where, spec.item);+ needCustomer(where, spec.customer);+ if (spec.breaks.length === 0) fail(`${where}: no price breaks`);+ }++ const pricingRuleNames = new Set<string>();+ for (const spec of dataset.items.pricingRules) {+ const where = `items.pricingRules "${spec.name}"`;+ if (pricingRuleNames.has(spec.name)) fail(`${where}: duplicate name`);+ pricingRuleNames.add(spec.name);+ if (spec.customer !== undefined) needCustomer(where, spec.customer);+ if (spec.customerType !== undefined)+ need("customerType", where, spec.customerType);+ for (const item of spec.items ?? []) need("item", where, item);+ if (spec.items?.length === 0) fail(`${where}: empty items list`);+ if (spec.amount <= 0) fail(`${where}: amount must be positive`);+ if (spec.amountType === "Percentage" && spec.amount > 100) {+ fail(`${where}: ${spec.amount}% is not a percentage in (0, 100]`);+ }+ if (spec.minQuantity !== undefined && spec.minQuantity <= 0) {+ fail(`${where}: minQuantity must be positive`);+ }+ }+ // The Pricing Rules list shows both rule types and a quantity break.+ for (const ruleType of ["Discount", "Markup"] as const) {+ if (!dataset.items.pricingRules.some((r) => r.ruleType === ruleType)) {+ fail(`items.pricingRules: no ${ruleType} rule`);+ }+ }+ if (!dataset.items.pricingRules.some((r) => r.minQuantity !== undefined)) {+ fail("items.pricingRules: no quantity-break rule (minQuantity)");+ }+ if (dataset.items.pricingRules.length < 3) {+ fail(+ `items.pricingRules: ${dataset.items.pricingRules.length} rules, need ≥ 3`+ );+ }++ // Convention: every dataset showcases one configurable make part.+ if (!dataset.items.configuration) {+ fail(`items.configuration: missing — every dataset showcases one`);+ } else {+ const cfg = dataset.items.configuration;+ const where = `items.configuration "${cfg.item}"`;+ if (!makePartIds.has(cfg.item)) {+ fail(`${where}: not a makePart readableId`);+ }+ for (const parameter of cfg.parameters) {+ if (+ parameter.dataType === "list" &&+ (parameter.listOptions === undefined ||+ parameter.listOptions.length === 0)+ ) {+ fail(`${where}: list parameter "${parameter.key}" has no listOptions`);+ }+ }+ }++ const revisionByItem = new Map(+ itemBuckets.flatMap(([, specs]) =>+ specs.map((spec) => [spec.readableId, spec.revision ?? "0"] as const)+ )+ );+ for (const [index, spec] of dataset.items.revisionLadder.entries()) {+ const where = `items.revisionLadder[${index}]`;+ need("item", where, spec.item);+ const activeRevision = revisionByItem.get(spec.item);+ const rungs = [spec.obsoleteRevision, spec.nextRevision];+ if (new Set(rungs).size !== rungs.length) {+ fail(`${where}: obsolete and next revisions must be distinct`);+ }+ for (const rung of rungs) {+ if (rung === activeRevision) {+ fail(+ `${where}: revision "${rung}" collides with the active revision of "${spec.item}"`+ );+ }+ }+ }+ // Tier 02 promotes each ladder's active revision to Production and every+ // other item keeps the Design default, so Prototype is the one status only+ // a ladder rung can supply.+ if (+ !dataset.items.revisionLadder.some(+ (spec) => spec.nextStatus === "Prototype"+ )+ ) {+ fail(+ `items.revisionLadder: no rung with nextStatus "Prototype" — every itemRevisionStatus must be on screen`+ );+ }+}++export function batchProperties(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const trackingByItem = ix.trackingByItem;+ const batchPropertyLabels = new Set<string>();+ for (const property of dataset.items.batchProperties) {+ const where = `items.batchProperties "${property.item}" "${property.label}"`;+ need("item", where, property.item);+ if (trackingByItem.get(property.item) !== "Batch") {+ fail(`${where}: batch property on a non-Batch-tracked item`);+ }+ const key = `${property.item}\u0000${property.label}`;+ if (batchPropertyLabels.has(key)) fail(`${where}: label listed twice`);+ batchPropertyLabels.add(key);+ const isList = property.dataType === "list";+ if (isList !== (property.listOptions !== undefined)) {+ fail(`${where}: listOptions are required exactly for a "list" property`);+ }+ if (isList && (property.listOptions ?? []).length < 2) {+ fail(`${where}: a list property needs ≥ 2 options`);+ }+ }+ for (const [item, tracking] of trackingByItem) {+ if (+ tracking === "Batch" &&+ !dataset.items.batchProperties.some((p) => p.item === item)+ ) {+ fail(+ `items.batchProperties: Batch-tracked "${item}" has no batch property (item › Purchasing tab)`+ );+ }+ }+}++export function openingStock(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { trackingByItem } = ix;+ for (const stock of dataset.inventory.openingStock) {+ need("item", "inventory.openingStock", stock.item);+ need("shelf", `inventory.openingStock "${stock.item}"`, stock.shelf);+ }++ for (const shelfLife of dataset.inventory.shelfLives) {+ const where = `inventory.shelfLives "${shelfLife.item}"`;+ need("item", where, shelfLife.item);+ if (trackingByItem.get(shelfLife.item) !== "Batch") {+ fail(`${where}: shelf life on a non-Batch-tracked item`);+ }+ if (shelfLife.days <= 0) fail(`${where}: days must be positive`);+ }+}++export function trackedStockAndMovements(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { makePartIds, isTracked } = ix;+ const shelfLifeItems = new Set(+ dataset.inventory.shelfLives.map((sl) => sl.item)+ );+ const trackedEntityQty = new Map<string, number>();+ const trackedStatuses = new Set<string>();+ for (const tracked of dataset.inventory.onHandTracked) {+ need("item", "inventory.onHandTracked", tracked.item);+ for (const entity of tracked.entities) {+ if (trackedEntityQty.has(entity.readableId)) {+ fail(+ `inventory.onHandTracked: duplicate tracked entity readableId "${entity.readableId}"`+ );+ }+ trackedEntityQty.set(entity.readableId, entity.quantity);+ trackedStatuses.add(entity.status ?? "Available");+ if (+ entity.status !== undefined &&+ !["Available", "On Hold", "Rejected", "Scrapped"].includes(+ entity.status+ )+ ) {+ fail(+ `inventory.onHandTracked "${entity.readableId}": unsupported status "${entity.status}"`+ );+ }+ // A Scrapped lot carries the scrap posting (tier 03 scrapLot): its+ // quantity leaves the shelf, so it draws on the net on-hand balance.+ if ((entity.status === "Scrapped") !== (entity.scrap !== undefined)) {+ fail(+ `inventory.onHandTracked "${entity.readableId}": a scrap spec is required on, and only on, a Scrapped lot`+ );+ }+ if (entity.scrap) {+ const where = `inventory.onHandTracked "${entity.readableId}" scrap`;+ need("shelf", where, entity.scrap.shelf);+ if (!SCRAP_REASON_NAMES.has(entity.scrap.reason)) {+ fail(+ `${where}: reason "${entity.scrap.reason}" is not a bootstrap scrap reason`+ );+ }+ if (entity.scrap.dateOffset >= 0) {+ fail(`${where}: dateOffset must be in the past`);+ }+ }+ if (+ entity.expiresOffset !== undefined &&+ !shelfLifeItems.has(tracked.item)+ ) {+ fail(+ `inventory.onHandTracked "${entity.readableId}": expiresOffset on "${tracked.item}", which has no inventory.shelfLives spec`+ );+ }+ }+ }++ checkCoverage(fail, { trackedEntityStatus: trackedStatuses });++ for (const kanban of dataset.inventory.kanbanItems) {+ const where = `inventory.kanbanItems "${kanban.item}"`;+ need("item", where, kanban.item);+ const system = kanban.replenishmentSystem ?? "Buy";+ if (system === "Buy") {+ if (kanban.supplier === undefined) {+ fail(`${where}: Buy kanban has no supplier`);+ } else {+ need("supplier", where, kanban.supplier);+ }+ }+ if (system === "Make" && !makePartIds.has(kanban.item)) {+ fail(`${where}: Make kanban on an item that is not a makePart`);+ }+ if (system === "Transfer") {+ if (!kanban.fromShelf || !kanban.toShelf) {+ fail(`${where}: Transfer kanban needs fromShelf and toShelf`);+ } else {+ need("shelf", where, kanban.fromShelf);+ need("shelf", where, kanban.toShelf);+ if (kanban.fromShelf === kanban.toShelf) {+ fail(`${where}: Transfer kanban's shelves must differ`);+ }+ }+ }+ }++ const inventoryKeys = new Set<string>();+ const uniqueKey = (where: string, key: string) => {+ if (inventoryKeys.has(key)) fail(`${where}: duplicate key "${key}"`);+ inventoryKeys.add(key);+ };+ const openingQty = new Map<string, number>();+ for (const stock of dataset.inventory.openingStock) {+ openingQty.set(onHandKey(stock.item, stock.shelf), stock.qty);+ }+ for (const count of dataset.inventory.inventoryCounts) {+ const where = `inventory.inventoryCounts "${count.key}"`;+ uniqueKey(where, count.key);+ if (count.status === "Posted" && count.postedOffset === undefined) {+ fail(`${where}: Posted count has no postedOffset`);+ }+ let variances = 0;+ for (const line of count.lines) {+ need("item", where, line.item);+ need("shelf", where, line.shelf);+ if (count.status !== "Posted") continue;+ // A posted count's snapshot IS the opening balance — the seed has no+ // other movement dated before it (completed transfers are authored+ // later on the timeline), so any other snapshot is variance dishonesty.+ const opening = openingQty.get(onHandKey(line.item, line.shelf)) ?? 0;+ if (line.snapshotQuantity !== opening) {+ fail(+ `${where} line "${line.item}": snapshotQuantity ${line.snapshotQuantity} != opening stock ${opening} at "${line.shelf}"`+ );+ }+ const delta = line.countedQuantity - line.snapshotQuantity;+ if (delta !== 0) {+ variances += 1;+ }+ }+ if (count.status === "Posted" && variances === 0) {+ fail(`${where}: Posted count has no non-zero variance line`);+ }+ }++ for (const transfer of dataset.inventory.stockTransfers) {+ const where = `inventory.stockTransfers "${transfer.key}"`;+ uniqueKey(where, transfer.key);+ for (const shelf of [transfer.fromShelf, transfer.toShelf]) {+ need("shelf", where, shelf);+ }+ if (transfer.fromShelf === transfer.toShelf) {+ fail(`${where}: fromShelf and toShelf must differ`);+ }+ for (const line of transfer.lines) {+ need("item", where, line.item);+ if (line.quantity <= 0) {+ fail(`${where} line "${line.item}": quantity must be positive`);+ }+ if (isTracked(line.item)) {+ fail(+ `${where} line "${line.item}": tracked items need per-entity moves the seed does not model`+ );+ }+ }+ }++ for (const transfer of dataset.inventory.warehouseTransfers) {+ const where = `inventory.warehouseTransfers "${transfer.key}"`;+ uniqueKey(where, transfer.key);+ if (transfer.fromLocation === transfer.toLocation) {+ fail(`${where}: fromLocation and toLocation must differ`);+ }+ if (transfer.status === "Completed" && transfer.fromLocation !== "Plant") {+ fail(+ `${where}: Completed transfer must ship from Plant — the datasets stock no other location`+ );+ }+ for (const line of transfer.lines) {+ need("item", where, line.item);+ if (line.quantity <= 0) {+ fail(`${where} line "${line.item}": quantity must be positive`);+ }+ if (isTracked(line.item)) {+ fail(+ `${where} line "${line.item}": tracked items need per-entity moves the seed does not model`+ );+ }+ if (line.fromShelf !== undefined) need("shelf", where, line.fromShelf);+ if (transfer.status === "Completed" && line.fromShelf === undefined) {+ fail(+ `${where} line "${line.item}": Completed transfer line needs a fromShelf`+ );+ }+ }+ }+}++export function netOnHand(ctx: ValidationCtx): void {+ for (const [key, net] of ctx.ix.onHand) {+ if (net < 0) {+ ctx.fail(+ `inventory: net on-hand for ${key} is ${net} — count variances, completed transfers, posted shipments, completed purchase returns, completed picking lists and completed maintenance dispatches drain more than the opening stock and posted receipts provide`+ );+ }+ }+}++export function sales(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need, needCustomer } = ctx;+ const f = dataset.foundation;+ const { isTracked } = ix;++ const seenStatuses = {+ salesRfq: new Set<string>(),+ quote: new Set<string>(),+ quoteLine: new Set<string>(),+ salesOrder: new Set<string>(),+ shipment: new Set<string>(),+ salesInvoice: new Set<string>(),+ salesReturn: new Set<string>()+ };+ const noQuoteReasons = new Set(f.noQuoteReasons);++ const checkOpportunity = (+ where: string,+ spec: SalesOpportunitySpec+ ): void => {+ needCustomer(where, spec.customer);+ if (spec.rfq) {+ seenStatuses.salesRfq.add(spec.rfq.status);+ if (+ spec.rfq.noQuoteReason !== undefined &&+ !noQuoteReasons.has(spec.rfq.noQuoteReason)+ ) {+ fail(+ `${where} rfq: noQuoteReason "${spec.rfq.noQuoteReason}" is not in foundation.noQuoteReasons`+ );+ }+ for (const line of spec.rfq.lines)+ need("item", `${where} rfq`, line.item);+ }+ if (spec.quote) {+ seenStatuses.quote.add(spec.quote.status);+ for (const line of spec.quote.lines) {+ need("item", `${where} quote`, line.item);+ seenStatuses.quoteLine.add(line.status);+ // A "No Quote" line was declined — it never got priced, so it is the+ // one line status allowed to carry no breaks.+ if (line.priceBreaks.length === 0 && line.status !== "No Quote") {+ fail(`${where} quote line "${line.ref}": no price breaks`);+ }+ }+ }+ if (spec.order) {+ seenStatuses.salesOrder.add(spec.order.status);+ for (const line of spec.order.lines) {+ need("item", `${where} order`, line.item);+ if (+ line.promisedDateOffset !== undefined &&+ (line.promisedDateOffset < 0 ||+ line.promisedDateOffset >= HORIZON_DAYS)+ ) {+ fail(+ `${where} order line "${line.ref}": promisedDateOffset ${line.promisedDateOffset} outside the ${HORIZON_DAYS}-day planning horizon`+ );+ }+ }+ }+ if (spec.shipment) {+ if (!spec.order) fail(`${where}: shipment without an order`);+ seenStatuses.shipment.add(spec.shipment.status);+ const posted = spec.shipment.status === "Posted";+ if (posted && spec.shipment.postedOffset === undefined) {+ fail(`${where} shipment: Posted shipment has no postedOffset`);+ }+ if (+ posted &&+ spec.order &&+ spec.shipment.postedOffset !== undefined &&+ spec.shipment.postedOffset < spec.order.orderDateOffset+ ) {+ fail(+ `${where} shipment: postedOffset ${spec.shipment.postedOffset} is before the order's orderDateOffset ${spec.order.orderDateOffset}`+ );+ }+ const orderItems = new Set(spec.order?.lines.map((l) => l.item) ?? []);+ for (const line of spec.shipment.lines) {+ need("item", `${where} shipment`, line.item);+ if (spec.order && !orderItems.has(line.item)) {+ fail(+ `${where} shipment: item "${line.item}" is not a line on the opportunity's order`+ );+ }+ if (line.shippedQuantity > line.orderQuantity) {+ fail(+ `${where} shipment: shippedQuantity ${line.shippedQuantity} exceeds orderQuantity ${line.orderQuantity} for "${line.item}"`+ );+ }+ if (line.fromShelf !== undefined)+ need("shelf", `${where} shipment`, line.fromShelf);+ if (posted && line.shippedQuantity > 0) {+ if (line.fromShelf === undefined) {+ fail(+ `${where} shipment: Posted line "${line.item}" needs a fromShelf`+ );+ } else if (isTracked(line.item)) {+ fail(+ `${where} shipment: tracked item "${line.item}" needs per-entity shipping the seed does not model`+ );+ }+ }+ }+ }+ if (spec.invoice) {+ if (!spec.order) fail(`${where}: invoice without an order`);+ seenStatuses.salesInvoice.add(spec.invoice.status);+ if (+ spec.order &&+ spec.invoice.dateIssuedOffset < spec.order.orderDateOffset+ ) {+ fail(+ `${where} invoice "${spec.invoice.ref}": dateIssuedOffset ${spec.invoice.dateIssuedOffset} is before the order's orderDateOffset ${spec.order.orderDateOffset}`+ );+ }+ const orderItems = new Set(spec.order?.lines.map((l) => l.item) ?? []);+ for (const line of spec.invoice.lines) {+ need("item", `${where} invoice`, line.item);+ if (spec.order && !orderItems.has(line.item)) {+ fail(+ `${where} invoice: item "${line.item}" is not a line on the opportunity's order`+ );+ }+ }+ const lineTotal = spec.invoice.lines.reduce(+ (sum, line) => sum + line.quantity * line.unitPrice,+ 0+ );+ if (Math.abs(lineTotal - spec.invoice.subtotal) > 0.01) {+ fail(+ `${where} invoice "${spec.invoice.ref}": subtotal ${spec.invoice.subtotal} does not equal its lines' total ${lineTotal}`+ );+ }+ }+ };++ for (const [index, spec] of dataset.sales.opportunities.entries()) {+ checkOpportunity(`sales.opportunities[${index}]`, spec);+ }+ for (const spec of dataset.sales.statusOrders) {+ const where = `sales.statusOrders "${spec.key}"`;+ needCustomer(where, spec.customer);+ need("item", where, spec.item);+ seenStatuses.salesOrder.add(spec.status);+ }+ for (const [index, spec] of dataset.sales.releasedOrders.entries()) {+ checkOpportunity(`sales.releasedOrders[${index}]`, spec);+ }++ const { documentRefs } = ix;+ for (const [rmaIndex, rma] of dataset.sales.salesReturns.entries()) {+ const where = `sales.salesReturns "${rma.key}"`;+ needCustomer(where, rma.customer);+ seenStatuses.salesReturn.add(rma.status);+ if (!RETURN_REASON_NAMES.has(rma.returnReason)) {+ fail(+ `${where}: returnReason "${rma.returnReason}" is not a bootstrap return reason`+ );+ }+ if (+ rma.salesOrder !== undefined &&+ !documentRefs.has(+ rma.salesOrder,+ documentRefs.seenBy.salesReturns[rmaIndex]!+ )+ ) {+ fail(`${where}: unknown sales order ref "${rma.salesOrder}"`);+ }+ if (rma.lines.length === 0) fail(`${where}: no lines`);+ for (const line of rma.lines) {+ need("item", where, line.item);+ if (line.quantity <= 0) {+ fail(`${where} line "${line.item}": quantity must be positive`);+ }+ if (isTracked(line.item)) {+ fail(+ `${where} line "${line.item}": tracked items need per-entity returns the seed does not model`+ );+ }+ if (line.toShelf !== undefined) need("shelf", where, line.toShelf);+ if (rma.status === "Completed") {+ if (line.toShelf === undefined) {+ fail(+ `${where} line "${line.item}": Completed return line needs a toShelf`+ );+ }+ }+ }+ }++ checkCoverage(fail, seenStatuses);+}++/** Sales/purchasing dashboards' "Assigned to me" needs a few of each. */+const MIN_ASSIGNED_OPEN_DOCUMENTS = 2;+const MIN_CUSTOMER_PORTALS = 2;+/** The KPI charts' default window; quotes created in it keep them from being one spike. */+const KPI_WINDOW_DAYS = 30;++// The dashboards' own "open" status lists (sales+/_index.tsx, purchasing+/_index.tsx).+const OPEN_QUOTE_STATUSES = new Set(["Draft", "Sent", "Partial"]);+const OPEN_SALES_RFQ_STATUSES = new Set(["Draft", "Ready for Quote"]);+const OPEN_SALES_ORDER_STATUSES = new Set([+ "Draft",+ "Needs Approval",+ "Confirmed",+ "In Progress",+ "To Ship and Invoice",+ "To Ship",+ "To Invoice"+]);+const OPEN_PURCHASE_ORDER_STATUSES = new Set([+ "Planned",+ "Draft",+ "To Review",+ "Needs Approval",+ "To Receive",+ "To Receive and Invoice",+ "To Invoice"+]);+const OPEN_PURCHASING_RFQ_STATUSES = new Set(["Draft", "Requested"]);+const OPEN_SUPPLIER_QUOTE_STATUSES = new Set(["Draft", "Active"]);+const CURRENCY_CODE = /^[A-Z]{3}$/;++function checkBankAccount(+ where: string,+ spec: BankAccountSpec,+ fail: (message: string) => void+): void {+ // Visibly fake: a real-looking number in a demo is a credential-shaped leak.+ if (!spec.accountNumber.startsWith("DEMO-")) {+ fail(`${where}: accountNumber must start with "DEMO-"`);+ }+ if (spec.bankCode !== undefined && !spec.bankCode.startsWith("DEMO-")) {+ fail(`${where}: bankCode must start with "DEMO-"`);+ }+ if (spec.swiftBic !== undefined && !spec.swiftBic.startsWith("DEMO")) {+ fail(`${where}: swiftBic must start with "DEMO"`);+ }+ if (!COUNTRY_CODE.test(spec.countryCode)) {+ fail(`${where}: countryCode "${spec.countryCode}" is not ISO alpha-2`);+ }+ if (!CURRENCY_CODE.test(spec.currencyCode)) {+ fail(`${where}: currencyCode "${spec.currencyCode}" is not ISO 4217`);+ }+}++export function commercial(ctx: ValidationCtx): void {+ const { dataset, fail, need, needCustomer } = ctx;+ const f = dataset.foundation;+ const cfg = dataset.items.configuration;+ const cfgWhere = `items.configuration "${cfg.item}"`;+ const method = dataset.items.methods.find((m) => m.readableId === cfg.item);+ const parameterByKey = new Map(cfg.parameters.map((p) => [p.key, p]));+ if (cfg.rules.length === 0) {+ fail(`${cfgWhere}: no rules — the configurator would change nothing`);+ }+ if (!method) fail(`${cfgWhere}: the configurable item has no method`);+ const ruleTargets = new Set<string>();+ for (const rule of cfg.rules) {+ const target =+ "component" in rule.target+ ? `component ${rule.target.component}`+ : `operation ${rule.target.operation}`;+ const where = `${cfgWhere} rule ${rule.field}:${target}`;+ if (ruleTargets.has(`${rule.field}:${target}`)) {+ fail(`${where}: duplicate rule`);+ }+ ruleTargets.add(`${rule.field}:${target}`);+ if ("component" in rule.target) {+ const component = rule.target.component;+ if (method && !method.bom.some((line) => line.component === component)) {+ fail(`${where}: "${component}" is not on the item's BOM`);+ }+ if (rule.field !== "quantity" && rule.field !== "methodType") {+ fail(`${where}: a BOM line takes quantity or methodType rules`);+ }+ } else {+ const position = rule.target.operation;+ if (method && (position < 1 || position > method.bop.length)) {+ fail(`${where}: the BOP has ${method.bop.length} operations`);+ }+ if (rule.field === "quantity" || rule.field === "methodType") {+ fail(`${where}: an operation takes time rules`);+ }+ }+ if (!/\breturn\b/.test(rule.code)) {+ fail(`${where}: code never returns a value`);+ }+ for (const match of rule.code.matchAll(/params\.(\w+)/g)) {+ if (!parameterByKey.has(match[1] ?? "")) {+ fail(`${where}: code reads unknown parameter "${match[1]}"`);+ }+ }+ }++ // Tier 04 copies the method as authored — the seed cannot run rule code the+ // way get-method does — so a configured line must pick parameter values+ // whose rule results equal the method's own numbers, or the quote's BoM/BoP+ // would disagree with its configuration.+ const checkConfiguredDefaults = (+ where: string,+ configuration: Record<string, string | number | boolean>+ ) => {+ if (!method) return;+ for (const rule of cfg.rules) {+ let expected: number | undefined;+ if ("component" in rule.target) {+ const component = rule.target.component;+ const bomLine = method.bom.find((l) => l.component === component);+ expected = rule.field === "quantity" ? bomLine?.quantity : undefined;+ } else {+ const op = method.bop[rule.target.operation - 1];+ expected =+ rule.field === "laborTime"+ ? (op?.laborTime ?? 0)+ : rule.field === "setupTime"+ ? (op?.setupTime ?? 0)+ : rule.field === "machineTime"+ ? (op?.machineTime ?? 0)+ : undefined;+ }+ if (expected === undefined) continue;+ let actual: unknown;+ try {+ // Authored rule bodies from this repository, evaluated like the+ // configurator's own preview does.+ actual = new Function("params", rule.code)(configuration);+ } catch (error) {+ fail(`${where}: rule ${rule.field} throws: ${String(error)}`);+ continue;+ }+ if (actual !== expected) {+ fail(+ `${where}: rule ${rule.field} yields ${String(actual)} but the copied method has ${expected} — pick values that keep the method's defaults`+ );+ }+ }+ };++ let configuredLines = 0;+ let recentQuotes = 0;+ const assigned = {+ quote: 0,+ salesRfq: 0,+ salesOrder: 0,+ purchaseOrder: 0,+ purchasingRfq: 0,+ supplierQuote: 0+ };+ const checkAssignee = (+ where: string,+ assignee: "self" | undefined,+ status: string,+ open: Set<string>,+ kind: keyof typeof assigned+ ) => {+ if (assignee === undefined) return;+ if (!open.has(status)) {+ fail(+ `${where}: assignee on a ${status} document — only open work is assigned`+ );+ } else {+ assigned[kind] += 1;+ }+ };+ for (const spec of [+ ...dataset.sales.opportunities,+ ...dataset.sales.releasedOrders+ ]) {+ const where = `sales "${spec.ref}"`;+ if (spec.rfq) {+ checkAssignee(+ `${where} rfq`,+ spec.rfq.assignee,+ spec.rfq.status,+ OPEN_SALES_RFQ_STATUSES,+ "salesRfq"+ );+ }+ if (spec.order) {+ checkAssignee(+ `${where} order`,+ spec.order.assignee,+ spec.order.status,+ OPEN_SALES_ORDER_STATUSES,+ "salesOrder"+ );+ }+ const quote = spec.quote;+ if (!quote) continue;+ const quoteWhere = `${where} quote "${quote.ref}"`;+ checkAssignee(+ quoteWhere,+ quote.assignee,+ quote.status,+ OPEN_QUOTE_STATUSES,+ "quote"+ );+ if (quote.createdOffset === undefined) {+ fail(+ `${quoteWhere}: no createdOffset — every quote would share the seed's timestamp`+ );+ } else {+ const created = quote.createdOffset;+ if (created > 0) fail(`${quoteWhere}: createdOffset is in the future`);+ if (created >= -KPI_WINDOW_DAYS) recentQuotes += 1;+ if (spec.rfq && created < spec.rfq.rfqDateOffset) {+ fail(`${quoteWhere}: created before its RFQ`);+ }+ if (spec.order && created > spec.order.orderDateOffset) {+ fail(`${quoteWhere}: created after its order`);+ }+ if (+ quote.expirationOffset !== undefined &&+ quote.expirationOffset <= created+ ) {+ fail(`${quoteWhere}: expires before it was created`);+ }+ }+ for (const line of quote.lines) {+ if (!line.configuration) continue;+ configuredLines += 1;+ const lineWhere = `${quoteWhere} line "${line.ref}"`;+ checkConfiguredDefaults(lineWhere, line.configuration);+ if (line.item !== cfg.item) {+ fail(+ `${lineWhere}: configured, but "${line.item}" is not configurable`+ );+ }+ for (const key of Object.keys(line.configuration)) {+ if (!parameterByKey.has(key)) {+ fail(`${lineWhere}: unknown configuration parameter "${key}"`);+ }+ }+ for (const parameter of cfg.parameters) {+ const value = line.configuration[parameter.key];+ const ok =+ parameter.dataType === "numeric"+ ? typeof value === "number"+ : parameter.dataType === "boolean"+ ? typeof value === "boolean"+ : typeof value === "string" &&+ (parameter.listOptions ?? []).includes(value);+ if (!ok) {+ fail(+ `${lineWhere}: "${parameter.key}" is not a valid ${parameter.dataType} value`+ );+ }+ }+ }+ }+ if (configuredLines === 0) {+ fail(+ "sales: no configured quote line — the configurator never shows a result"+ );+ }+ if (recentQuotes < 2) {+ fail(+ `sales: ${recentQuotes} quote(s) created in the last ${KPI_WINDOW_DAYS} days, need ≥ 2 for the KPI chart`+ );+ }++ const p = dataset.purchasing;+ checkAssignee(+ `purchasing.rfqHeader "${p.rfqHeader.ref}"`,+ p.rfqHeader.assignee,+ p.rfqHeader.status,+ OPEN_PURCHASING_RFQ_STATUSES,+ "purchasingRfq"+ );+ // Tier 05 assigns every Draft lifecycle RFQ to the applying user.+ assigned.purchasingRfq += p.lifecycleRfqs.filter(+ (rfq) => rfq.status === "Draft"+ ).length;+ for (const quote of p.rfqQuotes) {+ checkAssignee(+ `purchasing.rfqQuotes "${quote.key}"`,+ quote.assignee,+ quote.status ?? "Active",+ OPEN_SUPPLIER_QUOTE_STATUSES,+ "supplierQuote"+ );+ }+ for (const quote of p.standaloneSupplierQuotes) {+ checkAssignee(+ `purchasing.standaloneSupplierQuotes "${quote.key}"`,+ quote.assignee,+ quote.status,+ OPEN_SUPPLIER_QUOTE_STATUSES,+ "supplierQuote"+ );+ }+ for (const [index, po] of p.purchaseOrders.entries()) {+ if (po.source !== "direct") continue;+ checkAssignee(+ `purchasing.purchaseOrders[${index}]`,+ po.assignee,+ po.status,+ OPEN_PURCHASE_ORDER_STATUSES,+ "purchaseOrder"+ );+ }+ for (const [kind, count] of Object.entries(assigned)) {+ if (count < MIN_ASSIGNED_OPEN_DOCUMENTS) {+ fail(+ `assignees: ${count} open ${kind}(s) assigned to the applying user, need ≥ ${MIN_ASSIGNED_OPEN_DOCUMENTS}`+ );+ }+ }++ const portals = dataset.sales.customerPortals;+ if (portals.length < MIN_CUSTOMER_PORTALS) {+ fail(+ `sales.customerPortals: ${portals.length}, need ≥ ${MIN_CUSTOMER_PORTALS}`+ );+ }+ if (new Set(portals).size !== portals.length) {+ // externalLink is unique on (documentId, documentType).+ fail("sales.customerPortals: a customer can have only one portal");+ }+ for (const customer of portals) {+ needCustomer("sales.customerPortals", customer);+ }+ const primaryParties = new Set<string>();+ for (const spec of dataset.sales.customerBankAccounts) {+ const where = `sales.customerBankAccounts "${spec.name}"`;+ needCustomer(where, spec.customer);+ checkBankAccount(where, spec, fail);+ if (spec.isPrimary) {+ if (primaryParties.has(`c:${spec.customer}`)) {+ fail(`${where}: "${spec.customer}" already has a primary account`);+ }+ primaryParties.add(`c:${spec.customer}`);+ }+ }+ for (const spec of p.supplierBankAccounts) {+ const where = `purchasing.supplierBankAccounts "${spec.name}"`;+ need("supplier", where, spec.supplier);+ checkBankAccount(where, spec, fail);+ if (spec.isPrimary) {+ if (primaryParties.has(`s:${spec.supplier}`)) {+ fail(`${where}: "${spec.supplier}" already has a primary account`);+ }+ primaryParties.add(`s:${spec.supplier}`);+ }+ }+ if (dataset.sales.customerBankAccounts.length === 0) {+ fail("sales.customerBankAccounts: must not be empty");+ }+ if (p.supplierBankAccounts.length === 0) {+ fail("purchasing.supplierBankAccounts: must not be empty");+ }++ const poFloors = p.approvalRules+ .filter((rule) => rule.documentType === "purchaseOrder")+ .map((rule) => rule.lowerBoundAmount);+ const supplierRules = p.approvalRules.filter(+ (rule) => rule.documentType === "supplier"+ );+ if (poFloors.length < 2) {+ fail(+ "purchasing.approvalRules: need ≥ 2 purchaseOrder tiers — the rules screen shows a ladder"+ );+ }+ if (new Set(poFloors).size !== poFloors.length) {+ fail("purchasing.approvalRules: two purchaseOrder tiers share a floor");+ }+ // Supplier requests carry no amount, so only a 0-floor rule ever matches them.+ if (!supplierRules.some((rule) => rule.lowerBoundAmount === 0)) {+ fail("purchasing.approvalRules: no supplier rule with lowerBoundAmount 0");+ }+ for (const rule of p.approvalRules) {+ if (rule.lowerBoundAmount < 0) {+ fail(`purchasing.approvalRules: negative floor ${rule.lowerBoundAmount}`);+ }+ if (rule.documentType === "supplier" && rule.lowerBoundAmount !== 0) {+ fail(+ "purchasing.approvalRules: a supplier rule is amount-less (floor 0)"+ );+ }+ }+ const lowestPoFloor = poFloors.length > 0 ? Math.min(...poFloors) : 0;+ const needsApproval = new Map<+ string,+ { total: number; orderDateOffset: number; foreign: boolean }+ >();+ for (const po of p.purchaseOrders) {+ if (po.source !== "direct" || po.status !== "Needs Approval") continue;+ if (po.ref === undefined) {+ fail(+ `purchasing: Needs Approval order "${po.log}" has no ref for its approval request`+ );+ continue;+ }+ needsApproval.set(po.ref, {+ total: po.lines.reduce(+ (sum, line) => sum + line.purchaseQuantity * line.supplierUnitPrice,+ 0+ ),+ orderDateOffset: po.orderDateOffset,+ foreign: po.currencyCode !== undefined+ });+ }+ const pendingSuppliers = new Set(+ f.suppliers.filter((s) => s.status === "Pending").map((s) => s.name)+ );+ const requested = new Set<string>();+ const requestTypes = new Set<string>();+ for (const request of p.approvalRequests) {+ if (request.requestedOffset > 0) {+ fail("purchasing.approvalRequests: requestedOffset is in the future");+ }+ if ("purchaseOrder" in request) {+ requestTypes.add("purchaseOrder");+ const where = `purchasing.approvalRequests "${request.purchaseOrder}"`;+ const po = needsApproval.get(request.purchaseOrder);+ if (!po) {+ fail(`${where}: not a Needs Approval purchase order`);+ continue;+ }+ if (requested.has(request.purchaseOrder)) {+ fail(`${where}: a document has one Pending request`);+ }+ requested.add(request.purchaseOrder);+ if (request.requestedOffset < po.orderDateOffset) {+ fail(`${where}: requested before the order was placed`);+ }+ if (po.foreign) {+ fail(`${where}: the request amount is in base currency — keep it USD`);+ }+ if (po.total < lowestPoFloor) {+ fail(+ `${where}: order total ${po.total} is below the lowest approval tier ${lowestPoFloor}, so finalize would not have asked for approval`+ );+ }+ } else {+ requestTypes.add("supplier");+ const where = `purchasing.approvalRequests "${request.supplier}"`;+ if (!pendingSuppliers.has(request.supplier)) {+ fail(`${where}: not a Pending supplier`);+ }+ if (requested.has(request.supplier)) {+ fail(`${where}: a document has one Pending request`);+ }+ requested.add(request.supplier);+ }+ }+ for (const ref of needsApproval.keys()) {+ if (!requested.has(ref)) {+ fail(`purchasing: Needs Approval order "${ref}" has no approval request`);+ }+ }+ for (const name of pendingSuppliers) {+ if (!requested.has(name)) {+ fail(`purchasing: Pending supplier "${name}" has no approval request`);+ }+ }+ checkCoverage(fail, { approvalRequestType: requestTypes });+}++export function returnOrders(ctx: ValidationCtx): void {+ const { dataset, fail } = ctx;+ const p = dataset.purchasing;+ const checkCredit = (+ where: string,+ ret: {+ status: string;+ dateOffset: number;+ lines: { quantity: number }[];+ credit?: ReturnCreditSpec;+ }+ ): boolean => {+ const credit = ret.credit;+ if (!credit) return false;+ // Issue Credit caps each line at what was received / shipped.+ if (ret.status !== "Completed") {+ fail(`${where}: credit on a ${ret.status} return — nothing received yet`);+ }+ if (credit.dateOffset < ret.dateOffset || credit.dateOffset > 0) {+ fail(+ `${where}: credit dateOffset ${credit.dateOffset} outside [${ret.dateOffset}, 0]`+ );+ }+ if (+ credit.status === "Posted" &&+ credit.dateOffset < OPEN_PERIOD_MIN_OFFSET+ ) {+ fail(`${where}: a Posted credit must fall in an open period`);+ }+ if (credit.lines.length === 0) fail(`${where}: credit has no lines`);+ const seen = new Set<number>();+ for (const line of credit.lines) {+ const returnLine = ret.lines[line.line - 1];+ if (!returnLine) {+ fail(`${where}: credit names line ${line.line}, which does not exist`);+ continue;+ }+ if (seen.has(line.line))+ fail(`${where}: line ${line.line} credited twice`);+ seen.add(line.line);+ if (line.quantity <= 0 || line.quantity > returnLine.quantity) {+ fail(+ `${where}: line ${line.line} credits ${line.quantity} of ${returnLine.quantity}`+ );+ }+ }+ return true;+ };+ let salesCredits = 0;+ for (const rma of dataset.sales.salesReturns) {+ if (checkCredit(`sales.salesReturns "${rma.key}"`, rma)) salesCredits += 1;+ }+ let purchaseCredits = 0;+ for (const ret of p.purchaseReturns) {+ if (checkCredit(`purchasing.purchaseReturns "${ret.key}"`, ret)) {+ purchaseCredits += 1;+ }+ }+ if (salesCredits === 0) {+ fail("sales.salesReturns: no credited RMA — its Credits tab is empty");+ }+ if (purchaseCredits === 0) {+ fail(+ "purchasing.purchaseReturns: no credited return — its Credits tab is empty"+ );+ }++ const rmaByKey = new Map(dataset.sales.salesReturns.map((r) => [r.key, r]));+ const returnByKey = new Map(p.purchaseReturns.map((r) => [r.key, r]));+ let salesIssues = 0;+ let purchaseIssues = 0;+ for (const ncr of dataset.quality.nonConformances) {+ const where = `quality.nonConformances "${ncr.ref}"`;+ if (ncr.salesReturnLine) {+ salesIssues += 1;+ const { salesReturn, line } = ncr.salesReturnLine;+ const rma = rmaByKey.get(salesReturn);+ if (!rma) {+ fail(`${where}: unknown sales return "${salesReturn}"`);+ } else {+ if (!rma.lines[line - 1]) {+ fail(`${where}: sales return "${salesReturn}" has no line ${line}`);+ }+ if (ncr.customer !== rma.customer) {+ fail(+ `${where}: sales return "${salesReturn}" belongs to "${rma.customer}", not the NCR's customer`+ );+ }+ }+ }+ if (ncr.purchaseReturnLine) {+ purchaseIssues += 1;+ const { purchaseReturn, line, quantity } = ncr.purchaseReturnLine;+ const ret = returnByKey.get(purchaseReturn);+ if (!ret) {+ fail(`${where}: unknown purchase return "${purchaseReturn}"`);+ continue;+ }+ const returnLine = ret.lines[line - 1];+ if (!returnLine) {+ fail(+ `${where}: purchase return "${purchaseReturn}" has no line ${line}`+ );+ continue;+ }+ if (ncr.supplier !== ret.supplier) {+ fail(+ `${where}: purchase return "${purchaseReturn}" goes to "${ret.supplier}", not the NCR's supplier`+ );+ }+ if (quantity <= 0 || quantity > returnLine.quantity) {+ fail(+ `${where}: covers ${quantity} of the return line's ${returnLine.quantity}`+ );+ }+ const ncrItems = new Set([+ ...(ncr.items ?? []).map((i) => i.item),+ ...(ncr.purchaseOrderLine ? [ncr.purchaseOrderLine.item] : [])+ ]);+ if (ncrItems.size > 0 && !ncrItems.has(returnLine.item)) {+ fail(+ `${where}: return line item "${returnLine.item}" is not an item of the issue`+ );+ }+ // closeIssue refuses while a linked return is still open.+ if (ncr.status === "Closed" && ret.status !== "Completed") {+ fail(`${where}: Closed, but its linked return is still ${ret.status}`);+ }+ if (ret.dateOffset < ncr.openDateOffset) {+ fail(`${where}: linked return predates the issue`);+ }+ }+ }+ if (salesIssues === 0) {+ fail("quality: no NCR linked to an RMA line — the RMA Issues tab is empty");+ }+ if (purchaseIssues === 0) {+ fail(+ "quality: no NCR linked to a supplier-return line — its Issues tab is empty"+ );+ }+}++export function purchasing(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const f = dataset.foundation;+ const { trackingByItem, isTracked } = ix;+ const suppliers = ix.refs.supplier;++ const p = dataset.purchasing;+ const breakCount = p.rfqQuantityBreaks.length;+ const rfqItems = new Set(p.rfqLines.map((line) => line.item));+ for (const line of p.rfqLines) need("item", "purchasing.rfqLines", line.item);++ const seenPurchasing = {+ purchaseOrder: new Set<string>(),+ receipt: new Set<string>(),+ purchaseInvoice: new Set<string>(),+ purchaseReturn: new Set<string>(),+ supplierQuote: new Set<string>(),+ purchasingRfq: new Set<string>([p.rfqHeader.status])+ };+ const { activeSuppliers, suppliersWithContacts } = ix;+ const needActiveSupplier = (where: string, name: string) => {+ need("supplier", where, name);+ if (suppliers.has(name) && !activeSuppliers.has(name)) {+ fail(`${where}: supplier "${name}" is not Active`);+ }+ };+ const supplierProcessSuppliers = new Set(+ f.supplierProcesses.map((sp) => sp.supplier)+ );+ const eurSuppliers = new Set(+ f.suppliers.filter((s) => s.currencyCode === "EUR").map((s) => s.name)+ );++ const quoteKeys = new Set<string>();+ for (const quote of p.rfqQuotes) {+ const where = `purchasing.rfqQuotes "${quote.key}"`;+ quoteKeys.add(quote.key);+ needActiveSupplier(where, quote.supplier);+ if (+ suppliers.has(quote.supplier) &&+ !suppliersWithContacts.has(quote.supplier)+ ) {+ fail(+ `${where}: supplier "${quote.supplier}" has no supplierContact, which the quote row requires`+ );+ }+ seenPurchasing.supplierQuote.add(quote.status ?? "Active");+ for (const line of quote.lines) {+ need("item", where, line.item);+ if (!rfqItems.has(line.item)) {+ fail(`${where}: item "${line.item}" is not an rfqLine item`);+ }+ if (line.breaks.length !== breakCount) {+ fail(+ `${where} item "${line.item}": ${line.breaks.length} price breaks but rfqQuantityBreaks has ${breakCount}`+ );+ }+ }+ }+ if (!quoteKeys.has(p.rfqWinningQuote)) {+ fail(+ `purchasing.rfqWinningQuote "${p.rfqWinningQuote}" is not an rfqQuotes key`+ );+ }+ if (!p.rfqQuantityBreaks.includes(p.rfqOrderQuantity)) {+ fail(+ `purchasing.rfqOrderQuantity ${p.rfqOrderQuantity} is not one of rfqQuantityBreaks [${p.rfqQuantityBreaks.join(", ")}]`+ );+ }+ const winningQuote = p.rfqQuotes.find((q) => q.key === p.rfqWinningQuote);+ if (winningQuote && (winningQuote.status ?? "Active") !== "Active") {+ fail(+ `purchasing.rfqWinningQuote "${p.rfqWinningQuote}": the winning quote must stay Active`+ );+ }++ for (const rfq of p.lifecycleRfqs) {+ const where = `purchasing.lifecycleRfqs "${rfq.ref}"`;+ seenPurchasing.purchasingRfq.add(rfq.status);+ if (rfq.lines.length === 0) fail(`${where}: has no lines`);+ for (const line of rfq.lines) need("item", where, line.item);+ if (new Set(rfq.lines.map((line) => line.item)).size !== rfq.lines.length) {+ fail(`${where}: an item appears on two lines`);+ }+ if (+ rfq.quantities.length === 0 ||+ rfq.quantities.some(+ (qty, index) =>+ qty <= 0 || (index > 0 && qty <= rfq.quantities[index - 1]!)+ )+ ) {+ fail(`${where}: quantities must be positive and strictly ascending`);+ }+ if (rfq.suppliers.length === 0) fail(`${where}: has no suppliers`);+ if (new Set(rfq.suppliers).size !== rfq.suppliers.length) {+ fail(`${where}: a supplier is listed twice`);+ }+ for (const supplier of rfq.suppliers) needActiveSupplier(where, supplier);+ if (rfq.rfqDateOffset > 0) fail(`${where}: rfqDateOffset is in the future`);+ if (rfq.expirationOffset <= rfq.rfqDateOffset) {+ fail(`${where}: expires on or before its RFQ date`);+ }+ }++ for (const quote of p.standaloneSupplierQuotes) {+ const where = `purchasing.standaloneSupplierQuotes "${quote.key}"`;+ needActiveSupplier(where, quote.supplier);+ if (+ suppliers.has(quote.supplier) &&+ !suppliersWithContacts.has(quote.supplier)+ ) {+ fail(+ `${where}: supplier "${quote.supplier}" has no supplierContact, which the quote row requires`+ );+ }+ seenPurchasing.supplierQuote.add(quote.status);+ if (quote.status === "Expired" && quote.expirationOffset >= 0) {+ fail(+ `${where}: Expired quote's expirationOffset ${quote.expirationOffset} is not in the past`+ );+ }+ if (quote.lines.length === 0) fail(`${where}: no lines`);+ for (const line of quote.lines) {+ need("item", where, line.item);+ if (line.prices.length === 0) {+ fail(`${where} line "${line.item}": no prices`);+ }+ }+ }++ let eurPoCount = 0;+ let ospPoCount = 0;+ for (const [index, po] of p.purchaseOrders.entries()) {+ const where = `purchasing.purchaseOrders[${index}]`;+ seenPurchasing.purchaseOrder.add(po.status);+ if (po.source !== "direct") continue;++ needActiveSupplier(where, po.supplier);+ const poItems = new Set(po.lines.map((line) => line.item));+ for (const line of po.lines) need("item", where, line.item);++ if (po.purchaseOrderType === "Outside Processing") {+ ospPoCount += 1;+ if (!supplierProcessSuppliers.has(po.supplier)) {+ fail(+ `${where}: Outside Processing order on "${po.supplier}", which has no foundation.supplierProcesses entry`+ );+ }+ }++ // FX discipline: EUR belongs to exactly one childless, unpaid order on+ // the EUR supplier; everything else stays in base currency.+ if (po.currencyCode !== undefined && po.currencyCode !== "USD") {+ if (po.currencyCode !== "EUR") {+ fail(`${where}: unsupported currencyCode "${po.currencyCode}"`);+ } else {+ eurPoCount += 1;+ if (!eurSuppliers.has(po.supplier)) {+ fail(+ `${where}: EUR order on "${po.supplier}", which is not the EUR supplier`+ );+ }+ if (po.exchangeRate === undefined) {+ fail(`${where}: EUR order has no exchangeRate`);+ }+ if (po.receipt || po.invoice) {+ fail(+ `${where}: the EUR order must stay childless — receipts and invoices are settled in base currency by design`+ );+ }+ if (po.status !== "To Invoice" && po.status !== "Draft") {+ fail(+ `${where}: the EUR order must be unpaid ("To Invoice" or "Draft"), got "${po.status}"`+ );+ }+ }+ }++ if (po.receipt) {+ seenPurchasing.receipt.add(po.receipt.status);+ const posted = po.receipt.status === "Posted";+ if (posted && po.receipt.postedOffset === undefined) {+ fail(`${where} receipt: Posted receipt has no postedOffset`);+ }+ if (+ posted &&+ po.receipt.postedOffset !== undefined &&+ po.receipt.postedOffset < po.orderDateOffset+ ) {+ fail(+ `${where} receipt: postedOffset ${po.receipt.postedOffset} is before the order's orderDateOffset ${po.orderDateOffset}`+ );+ }+ for (const [lineIndex, line] of po.receipt.lines.entries()) {+ need("item", `${where} receipt`, line.item);+ if (!poItems.has(line.item)) {+ fail(`${where} receipt: item "${line.item}" is not a PO line`);+ }+ if (line.receivedQuantity > line.orderQuantity) {+ fail(+ `${where} receipt: receivedQuantity ${line.receivedQuantity} exceeds orderQuantity ${line.orderQuantity} for "${line.item}"`+ );+ }+ if (line.toShelf !== undefined)+ need("shelf", `${where} receipt`, line.toShelf);+ const tracking = trackingByItem.get(line.item);+ if (line.lotNumber !== undefined && tracking !== "Batch") {+ fail(+ `${where} receipt: lotNumber on "${line.item}", which is not Batch-tracked`+ );+ }+ if (posted && line.receivedQuantity > 0) {+ if (line.toShelf === undefined) {+ fail(+ `${where} receipt: Posted line "${line.item}" needs a toShelf`+ );+ }+ if (tracking === "Serial") {+ fail(+ `${where} receipt: serial item "${line.item}" needs per-unit receiving the seed does not model`+ );+ } else if (tracking === "Batch") {+ if (!line.requiresBatchTracking || line.lotNumber === undefined) {+ fail(+ `${where} receipt: Posted batch line "${line.item}" needs requiresBatchTracking and a lotNumber`+ );+ } else if (+ !ix.lots.mintedReceiptLines.has(receiptLineKey(index, lineIndex))+ ) {+ fail(+ `${where} receipt: lotNumber "${line.lotNumber}" collides with another tracked entity readableId`+ );+ }+ }+ }+ }+ }++ if (po.invoice) {+ seenPurchasing.purchaseInvoice.add(po.invoice.status);+ if (po.invoice.dateIssuedOffset < po.orderDateOffset) {+ fail(+ `${where} invoice "${po.invoice.ref}": dateIssuedOffset ${po.invoice.dateIssuedOffset} is before the order's orderDateOffset ${po.orderDateOffset}`+ );+ }+ if (+ po.receipt?.postedOffset !== undefined &&+ po.invoice.dateIssuedOffset < po.receipt.postedOffset+ ) {+ fail(+ `${where} invoice "${po.invoice.ref}": dateIssuedOffset ${po.invoice.dateIssuedOffset} is before the receipt's postedOffset ${po.receipt.postedOffset}`+ );+ }+ for (const line of po.invoice.lines) {+ need("item", `${where} invoice`, line.item);+ if (!poItems.has(line.item)) {+ fail(`${where} invoice: item "${line.item}" is not a PO line`);+ }+ }+ const lineTotal = po.invoice.lines.reduce(+ (sum, line) => sum + line.quantity * line.supplierUnitPrice,+ 0+ );+ if (Math.abs(lineTotal - po.invoice.subtotal) > 0.01) {+ fail(+ `${where} invoice "${po.invoice.ref}": subtotal ${po.invoice.subtotal} does not equal its lines' total ${lineTotal}`+ );+ }+ }+ }+ if (ospPoCount === 0) {+ fail(+ `purchasing.purchaseOrders: no "Outside Processing" order — every dataset showcases one`+ );+ }+ if (eurPoCount !== 1) {+ fail(+ `purchasing.purchaseOrders: expected exactly 1 EUR order (the FX showcase), found ${eurPoCount}`+ );+ }++ for (const ret of p.purchaseReturns) {+ const where = `purchasing.purchaseReturns "${ret.key}"`;+ needActiveSupplier(where, ret.supplier);+ seenPurchasing.purchaseReturn.add(ret.status);+ if (ret.lines.length === 0) fail(`${where}: no lines`);+ for (const line of ret.lines) {+ need("item", where, line.item);+ if (line.quantity <= 0) {+ fail(`${where} line "${line.item}": quantity must be positive`);+ }+ if (isTracked(line.item)) {+ fail(+ `${where} line "${line.item}": tracked items need per-entity returns the seed does not model`+ );+ }+ if (line.fromShelf !== undefined) need("shelf", where, line.fromShelf);+ if (ret.status === "Completed") {+ if (line.fromShelf === undefined) {+ fail(+ `${where} line "${line.item}": Completed return line needs a fromShelf`+ );+ }+ }+ }+ }++ checkCoverage(fail, seenPurchasing);+}++/** Open jobs are due inside this window, so Priorities' week and month show them. */+const OPEN_JOB_DUE_WINDOW = { min: -3, max: 21 } as const;+const RELEASED_JOB_STATUSES = new Set([+ "Ready",+ "In Progress",+ "Paused",+ "Completed",+ "Closed",+ "Cancelled"+]);++export function jobs(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need, needCustomer } = ctx;+ const { orderDateByRef } = ix;+ const { rootOpCountOf, rootOpsOf } = ix.bom;+ const checkJobTimeline = (where: string, job: JobSpec) => {+ const released = job.releasedDateOffset;+ const completed = job.completedDateOffset;+ if (RELEASED_JOB_STATUSES.has(job.status) && released === undefined) {+ fail(`${where}: a ${job.status} job has no releasedDateOffset`);+ }+ if (!RELEASED_JOB_STATUSES.has(job.status) && released !== undefined) {+ fail(`${where}: a ${job.status} job has not been released`);+ }+ const finished = job.status === "Completed" || job.status === "Closed";+ if (finished !== (completed !== undefined)) {+ fail(+ `${where}: completedDateOffset belongs on (and only on) Completed / Closed jobs`+ );+ }+ if (released !== undefined && released > 0) {+ fail(`${where}: releasedDateOffset ${released} is in the future`);+ }+ if (completed !== undefined && completed > 0) {+ fail(`${where}: completedDateOffset ${completed} is in the future`);+ }+ if (+ released !== undefined &&+ completed !== undefined &&+ completed < released+ ) {+ fail(+ `${where}: completedDateOffset ${completed} is before releasedDateOffset ${released}`+ );+ }+ const ordered =+ job.salesOrder === undefined+ ? undefined+ : orderDateByRef.get(job.salesOrder);+ if (released !== undefined && ordered !== undefined && released < ordered) {+ fail(+ `${where}: releasedDateOffset ${released} is before its sales order's orderDateOffset ${ordered}`+ );+ }+ if (+ OPEN_JOB_STATUSES.has(job.status) &&+ job.dueDateOffset !== undefined &&+ (job.dueDateOffset < OPEN_JOB_DUE_WINDOW.min ||+ job.dueDateOffset > OPEN_JOB_DUE_WINDOW.max)+ ) {+ fail(+ `${where}: open job due at ${job.dueDateOffset}, outside ${OPEN_JOB_DUE_WINDOW.min}…+${OPEN_JOB_DUE_WINDOW.max}`+ );+ }+ if (+ job.priority !== undefined &&+ !(Number.isInteger(job.priority) && job.priority > 0)+ ) {+ fail(`${where}: priority ${job.priority} is not a positive integer`);+ }+ if (+ RELEASED_OPEN_JOB_STATUSES.has(job.status) &&+ job.priority === undefined+ ) {+ fail(`${where}: a released job needs a priority`);+ }+ const logged = job.loggedTime;+ if (logged) {+ if (job.status !== "Completed" || completed === undefined) {+ fail(`${where}: loggedTime belongs on Completed jobs`);+ } else if (+ (released !== undefined && logged.startOffset < released) ||+ logged.startOffset >= completed+ ) {+ fail(+ `${where}: loggedTime starts at ${logged.startOffset}, outside release ${released} … the day before completion ${completed}`+ );+ }+ if (!(logged.efficiency >= 0.5 && logged.efficiency <= 2)) {+ fail(+ `${where}: loggedTime efficiency ${logged.efficiency} outside 0.5…2`+ );+ }+ }+ };++ const jobKeys = new Set<string>();+ const seenDeadlineTypes = new Set<string>();+ const seenOperationStatuses = new Set<string>();+ const seenQuantityTypes = new Set<string>();+ const { documentRefs } = ix;+ for (const [jobIndex, job] of dataset.production.jobs.entries()) {+ const seen = documentRefs.seenBy.jobs[jobIndex]!;+ const where = `production.jobs "${job.key}"`;+ if (jobKeys.has(job.key)) fail(`${where}: duplicate job key`);+ jobKeys.add(job.key);+ need("item", where, job.item);+ const orderRefs = [job.salesOrder, job.salesOrderLine, job.customer];+ const orderRefCount = orderRefs.filter((r) => r !== undefined).length;+ if (orderRefCount !== 0 && orderRefCount !== 3) {+ fail(+ `${where}: salesOrder, salesOrderLine and customer go together — all three (made to order) or none (made to stock)`+ );+ }+ if (job.customer !== undefined) needCustomer(where, job.customer);+ if (+ job.salesOrder !== undefined &&+ !documentRefs.has(job.salesOrder, seen)+ ) {+ fail(`${where}: unknown sales order ref "${job.salesOrder}"`);+ }+ if (+ job.salesOrderLine !== undefined &&+ !documentRefs.has(job.salesOrderLine, seen)+ ) {+ fail(`${where}: unknown sales order line ref "${job.salesOrderLine}"`);+ }+ checkJobTimeline(where, job);+ if (+ job.quantityComplete !== undefined &&+ job.quantityComplete > job.quantity+ ) {+ fail(+ `${where}: quantityComplete ${job.quantityComplete} exceeds quantity ${job.quantity}`+ );+ }++ const deadlineType = job.deadlineType ?? "Hard Deadline";+ seenDeadlineTypes.add(deadlineType);+ if (deadlineType === "No Deadline" && job.dueDateOffset !== undefined) {+ fail(`${where}: a "No Deadline" job must not carry a dueDateOffset`);+ }+ if (deadlineType !== "No Deadline" && job.dueDateOffset === undefined) {+ fail(`${where}: "${deadlineType}" job has no dueDateOffset`);+ }++ const opCount = rootOpCountOf(job.item);+ const checkOrder = (label: string, order: number) => {+ if (!Number.isInteger(order) || order < 1) {+ fail(`${where} ${label}: order ${order} is not a positive integer`);+ } else if (order > opCount) {+ fail(+ `${where} ${label}: order ${order} exceeds the ${opCount} root operations of "${job.item}"`+ );+ }+ };++ const overrideOrders = new Set<number>();+ for (const override of job.operationOverrides ?? []) {+ checkOrder("operationOverrides", override.order);+ if (overrideOrders.has(override.order)) {+ fail(`${where} operationOverrides: duplicate order ${override.order}`);+ }+ overrideOrders.add(override.order);+ if (override.status) seenOperationStatuses.add(override.status);+ if (!override.status && !override.assignee && !override.running) {+ fail(+ `${where} operationOverrides order ${override.order}: sets nothing`+ );+ }+ if (override.running) {+ if (override.status !== "In Progress") {+ fail(+ `${where} operationOverrides order ${override.order}: a running operation must be "In Progress"`+ );+ }+ if (!TIME_OF_DAY.test(override.running.startTimeOfDay)) {+ fail(+ `${where} operationOverrides order ${override.order}: startTimeOfDay "${override.running.startTimeOfDay}" is not HH:MM:SS`+ );+ }+ const workCenter = rootOpsOf(job.item)[override.order - 1]?.workCenter;+ if (workCenter === undefined) {+ fail(+ `${where} operationOverrides order ${override.order}: a running operation needs a work center`+ );+ }+ }+ }++ for (const quantity of job.quantities ?? []) {+ checkOrder("quantities", quantity.order);+ seenQuantityTypes.add(quantity.type);+ if (quantity.quantity <= 0) {+ fail(`${where} quantities: quantity must be positive`);+ }+ if (quantity.type === "Scrap") {+ if (quantity.scrapReason === undefined) {+ fail(`${where} quantities: Scrap row has no scrapReason`);+ } else if (!SCRAP_REASON_NAMES.has(quantity.scrapReason)) {+ fail(+ `${where} quantities: scrapReason "${quantity.scrapReason}" is not a bootstrap scrap reason`+ );+ }+ } else if (quantity.scrapReason !== undefined) {+ fail(+ `${where} quantities: scrapReason on a ${quantity.type} row — only Scrap rows carry one`+ );+ }+ }++ for (const note of job.operationNotes ?? []) {+ checkOrder("operationNotes", note.order);+ if (!note.note.trim()) fail(`${where} operationNotes: empty note`);+ }+ }+ checkCoverage(fail, {+ jobDeadlineType: seenDeadlineTypes,+ jobOperationOverride: seenOperationStatuses,+ productionQuantityType: seenQuantityTypes+ });+ if (!jobKeys.has(dataset.production.eventsJobKey)) {+ fail(+ `production.eventsJobKey "${dataset.production.eventsJobKey}" is not a job key`+ );+ }+ if (!jobKeys.has(dataset.production.genealogyJobKey)) {+ fail(+ `production.genealogyJobKey "${dataset.production.genealogyJobKey}" is not a job key`+ );+ }+}++export function eventsJobAndPicking(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { jobByKey, isTracked } = ix;+ const { componentsOf, rootOpCountOf } = ix.bom;+ const eventsJob = jobByKey.get(dataset.production.eventsJobKey);+ if (eventsJob) {+ const eventsOpCount = rootOpCountOf(eventsJob.item);+ const checkEventsOrder = (label: string, order: number) => {+ if (!Number.isInteger(order) || order < 1 || order > eventsOpCount) {+ fail(+ `production.${label}: operation order ${order} is not within the ${eventsOpCount} root operations of "${eventsJob.item}"`+ );+ }+ };+ checkEventsOrder("openEvent", dataset.production.openEvent.operationOrder);+ const openEventOverride = (eventsJob.operationOverrides ?? []).find(+ (override) =>+ override.order === dataset.production.openEvent.operationOrder+ );+ if (openEventOverride?.status !== "In Progress") {+ fail(+ `production.openEvent: operation ${dataset.production.openEvent.operationOrder} is not overridden to "In Progress" on job "${eventsJob.key}"`+ );+ }+ const rework = dataset.production.rework;+ checkEventsOrder("rework target", rework.targetOperationOrder);+ checkEventsOrder("rework triggeredAt", rework.triggeredAtOperationOrder);+ if (rework.targetOperationOrder > rework.triggeredAtOperationOrder) {+ fail(+ `production.rework: target operation ${rework.targetOperationOrder} is downstream of the triggering operation ${rework.triggeredAtOperationOrder} — rework sends units BACK`+ );+ }+ if (rework.quantity <= 0) {+ fail(`production.rework: quantity must be positive`);+ }+ if (!rework.reason.trim()) fail(`production.rework: empty reason`);+ }++ const seenPickingStatuses = new Set<string>();+ const pickingKeys = new Set<string>();+ for (const list of dataset.production.pickingLists) {+ const where = `production.pickingLists "${list.key}"`;+ if (pickingKeys.has(list.key)) fail(`${where}: duplicate key`);+ pickingKeys.add(list.key);+ seenPickingStatuses.add(list.status);+ const job = jobByKey.get(list.job);+ if (!job) {+ fail(`${where}: unknown job key "${list.job}"`);+ continue;+ }+ // Material is staged for a job the floor has — picking before release is+ // a timeline lie.+ if (job.releasedDateOffset === undefined) {+ fail(`${where}: job "${list.job}" was never released`);+ } else if (list.dateOffset < job.releasedDateOffset) {+ fail(+ `${where}: dateOffset ${list.dateOffset} is before the job's releasedDateOffset ${job.releasedDateOffset}`+ );+ }+ if (list.lines.length === 0) fail(`${where}: no lines`);+ const jobComponents = componentsOf(job.item);+ for (const line of list.lines) {+ need("item", where, line.item);+ if (!jobComponents.has(line.item)) {+ fail(+ `${where} line "${line.item}": not a component of "${job.item}"'s BOM tree, so the job has no jobMaterial row to pick against`+ );+ }+ need("shelf", `${where} line "${line.item}"`, line.fromShelf);+ if (isTracked(line.item)) {+ fail(+ `${where} line "${line.item}": tracked items need per-entity picks the seed does not model`+ );+ }+ if (line.quantityRequired <= 0) {+ fail(`${where} line "${line.item}": quantityRequired must be positive`);+ }+ if (list.status === "Completed") {+ if (line.status !== "Picked") {+ fail(+ `${where} line "${line.item}": a Completed list's lines must all be Picked`+ );+ }+ if (line.quantityPicked !== line.quantityRequired) {+ fail(+ `${where} line "${line.item}": Picked line must have quantityPicked ${line.quantityRequired}, got ${line.quantityPicked}`+ );+ }+ } else {+ if (line.status === "Picked") {+ fail(+ `${where} line "${line.item}": an In Progress list holds only Pending or Short lines`+ );+ }+ if (line.quantityPicked !== 0) {+ fail(+ `${where} line "${line.item}": an unpicked line must have quantityPicked 0 — partial picks would need ledger rows the seed does not model here`+ );+ }+ }+ }+ }+ checkCoverage(fail, { pickingListStatus: seenPickingStatuses });+}++export function genealogy(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { lots } = ix;+ // Genealogy inputs are historical lots/serials that tier 06 CREATES as+ // consumed entities — they must not collide with an on-hand entity's+ // readableId, or the UI shows two entities under one id.+ const genealogyIds = new Set<string>();+ for (const input of dataset.production.genealogyInputs) {+ const where = `production.genealogyInputs "${input.readableId}"`;+ need("item", where, input.item);+ if (lots.onHandIds.has(input.readableId)) {+ fail(+ `${where}: readableId collides with an inventory.onHandTracked entity`+ );+ }+ if (lots.receiptLotIds.has(input.readableId)) {+ fail(`${where}: readableId collides with a purchasing receipt lotNumber`);+ }+ if (genealogyIds.has(input.readableId)) {+ fail(`${where}: duplicate genealogy input readableId`);+ }+ genealogyIds.add(input.readableId);+ }+ need(+ "item",+ "production.genealogyAssembly",+ dataset.production.genealogyAssembly.item+ );+ const assemblySerialId =+ dataset.production.genealogyAssembly.serial.readableId;+ if (+ lots.onHandIds.has(assemblySerialId) ||+ lots.receiptLotIds.has(assemblySerialId) ||+ genealogyIds.has(assemblySerialId)+ ) {+ fail(+ `production.genealogyAssembly: serial readableId "${assemblySerialId}" collides with another tracked entity readableId`+ );+ }+}++export const MIN_JOBS = 18;+const MIN_OPEN_OPERATIONS_PER_WORK_CENTER = 2;+const MIN_RUNNING_WORK_CENTERS = 4;+const MIN_ASSIGNED_OPEN_OPERATIONS = 6;+const MIN_MAKE_TO_STOCK_JOBS = 2;+const MIN_RECENTLY_COMPLETED_JOBS = 3;+const MIN_OPERATIONS_WITH_TOOLS = 3;+const MIN_OPERATIONS_WITH_PARAMETERS = 3;+/** Completed jobs the completion-time KPI's default month window picks up. */+const RECENT_COMPLETION_WINDOW = { min: -25, max: -3 } as const;+const UNSTARTED_OPERATION_STATUSES = new Set(["Todo", "Ready", "Waiting"]);++export function floor(ctx: ValidationCtx): void {+ const { dataset, ix, fail } = ctx;+ const { jobByKey } = ix;+ const { rootOpsOf, subassemblyOpsOf } = ix.bom;+ const production = dataset.production;+ const jobs = production.jobs;+ if (jobs.length < MIN_JOBS) {+ fail(`production.jobs: ${jobs.length} jobs, need ≥ ${MIN_JOBS}`);+ }++ const priorities = new Map<number, string>();+ for (const job of jobs) {+ if (job.priority === undefined) continue;+ const other = priorities.get(job.priority);+ if (other) {+ fail(+ `production.jobs "${job.key}": priority ${job.priority} is also "${other}"'s — priorities are distinct`+ );+ }+ priorities.set(job.priority, job.key);+ }++ const open = jobs.filter((job) => OPEN_JOB_STATUSES.has(job.status));+ const released = jobs.filter((job) =>+ RELEASED_OPEN_JOB_STATUSES.has(job.status)+ );+ if (+ !open.some(+ (job) =>+ job.dueDateOffset !== undefined &&+ job.dueDateOffset >= 0 &&+ job.dueDateOffset <= 7+ )+ ) {+ fail(`production.jobs: no open job due within 0…+7 (Priorities' week)`);+ }+ if (!released.some((job) => job.dueDateOffset === undefined)) {+ fail(+ `production.jobs: no released job without a due date (Priorities › Unscheduled)`+ );+ }+ const madeToStock = open.filter((job) => job.salesOrder === undefined);+ if (madeToStock.length < MIN_MAKE_TO_STOCK_JOBS) {+ fail(+ `production.jobs: ${madeToStock.length} open make-to-stock jobs, need ≥ ${MIN_MAKE_TO_STOCK_JOBS} (openProductionOrders)`+ );+ }+ const recentlyCompleted = jobs.filter(+ (job) =>+ job.status === "Completed" &&+ job.loggedTime !== undefined &&+ job.completedDateOffset !== undefined &&+ job.completedDateOffset >= RECENT_COMPLETION_WINDOW.min &&+ job.completedDateOffset <= RECENT_COMPLETION_WINDOW.max+ );+ if (recentlyCompleted.length < MIN_RECENTLY_COMPLETED_JOBS) {+ fail(+ `production.jobs: ${recentlyCompleted.length} Completed jobs with loggedTime finished ${RECENT_COMPLETION_WINDOW.min}…${RECENT_COMPLETION_WINDOW.max}, need ≥ ${MIN_RECENTLY_COMPLETED_JOBS}`+ );+ }+ // Logged time is sized from estimates, so Setup / Machine events exist only+ // where the completed jobs' operations carry those estimates.+ const loggedOps = recentlyCompleted+ .flatMap((job) => [...rootOpsOf(job.item), ...subassemblyOpsOf(job.item)])+ .filter((op) => op.workCenter !== undefined);+ if (+ !loggedOps.some((op) => (op.setupTime ?? 0) > 0) ||+ !loggedOps.some((op) => (op.machineTime ?? 0) > 0)+ ) {+ fail(+ `production.jobs: the recently completed jobs need a staffed operation with setupTime and one with machineTime, or no Setup / Machine events are logged`+ );+ }+ if (!jobs.some((job) => job.assignee === "self")) {+ fail(`production.jobs: no job assigned to the applying user`);+ }++ const {+ openByWorkCenter,+ running,+ assignedOpen,+ openInspection,+ batchLeadWithoutWorkCenter+ } = ix.floor;+ if (batchLeadWithoutWorkCenter) {+ fail(+ `production.batch: the first member runs the batch timer, so it needs a work center`+ );+ }+ for (const workCenter of dataset.foundation.workCenters) {+ const count = openByWorkCenter.get(workCenter.name) ?? 0;+ if (count < MIN_OPEN_OPERATIONS_PER_WORK_CENTER) {+ fail(+ `production floor: work center "${workCenter.name}" has ${count} open operations, need ≥ ${MIN_OPEN_OPERATIONS_PER_WORK_CENTER} (MES board column)`+ );+ }+ }+ if (running.size < MIN_RUNNING_WORK_CENTERS) {+ fail(+ `production floor: running operations on ${running.size} work centers, need ≥ ${MIN_RUNNING_WORK_CENTERS} (work-center displays)`+ );+ }+ if (assignedOpen < MIN_ASSIGNED_OPEN_OPERATIONS) {+ fail(+ `production floor: ${assignedOpen} open operations assigned to the applying user, need ≥ ${MIN_ASSIGNED_OPEN_OPERATIONS} (MES Assigned)`+ );+ }+ if (!openInspection) {+ fail(+ `production floor: no open Inspection operation on a released job — the MES inspection view is unreachable`+ );+ }++ // Tools ride every job copy of an operation; parameters come from its+ // procedure when it has one, else from the method (get-method's rule).+ const procedureParameterCount = new Map(+ dataset.foundation.procedures.map((proc) => [+ `procedure:${proc.name}`,+ (proc.parameters ?? []).length+ ])+ );+ let withTools = 0;+ let withParameters = 0;+ for (const job of jobs) {+ for (const op of [...rootOpsOf(job.item), ...subassemblyOpsOf(job.item)]) {+ if ((op.tools ?? []).length > 0) withTools += 1;+ const parameters = op.procedure+ ? (procedureParameterCount.get(op.procedure) ?? 0)+ : (op.parameters ?? []).length;+ if (parameters > 0) withParameters += 1;+ }+ }+ if (withTools < MIN_OPERATIONS_WITH_TOOLS) {+ fail(+ `production.jobs: ${withTools} job operations carry tools, need ≥ ${MIN_OPERATIONS_WITH_TOOLS}`+ );+ }+ if (withParameters < MIN_OPERATIONS_WITH_PARAMETERS) {+ fail(+ `production.jobs: ${withParameters} job operations carry parameters, need ≥ ${MIN_OPERATIONS_WITH_PARAMETERS}`+ );+ }++ // The batch, as batch-operations' create would accept it.+ const members = production.batch.members;+ if (members.length < 2) {+ fail(`production.batch: ${members.length} members, need ≥ 2`);+ }+ const memberJobs = new Set<string>();+ const memberProcesses = new Set<string>();+ for (const member of members) {+ const where = `production.batch member "${member.job}"`;+ if (memberJobs.has(member.job)) {+ fail(`${where}: members come from different jobs`);+ }+ memberJobs.add(member.job);+ const job = jobByKey.get(member.job);+ if (!job) {+ fail(`${where}: unknown job key`);+ continue;+ }+ if (!RELEASED_OPEN_JOB_STATUSES.has(job.status)) {+ fail(`${where}: job is ${job.status}, not released`);+ }+ if (member.job === production.eventsJobKey) {+ fail(`${where}: the events job's operations carry production events`);+ }+ const op = rootOpsOf(job.item)[member.order - 1];+ if (!op) {+ fail(`${where}: no root operation at position ${member.order}`);+ continue;+ }+ memberProcesses.add(op.process);+ const override = (job.operationOverrides ?? []).find(+ (o) => o.order === member.order+ );+ if (+ (override?.status &&+ !UNSTARTED_OPERATION_STATUSES.has(override.status)) ||+ override?.running+ ) {+ fail(`${where}: operation ${member.order} has already started`);+ }+ // The running batch timer puts every member on the floor.+ if (job.status !== "In Progress") {+ fail(`${where}: the batch is running, so its job is "In Progress"`);+ }+ for (let order = 1; order < member.order; order += 1) {+ const earlier = (job.operationOverrides ?? []).find(+ (o) => o.order === order+ );+ if (earlier?.status !== "Done") {+ fail(+ `${where}: operation ${order} runs before the batched operation ${member.order}, so it must be Done`+ );+ }+ }+ }+ if (!TIME_OF_DAY.test(production.batch.running.startTimeOfDay)) {+ fail(+ `production.batch.running: startTimeOfDay "${production.batch.running.startTimeOfDay}" is not HH:MM:SS`+ );+ }+ if (memberProcesses.size > 1) {+ fail(+ `production.batch: members span processes ${[...memberProcesses].join(", ")} — a batch runs one`+ );+ }++ // The 3D instruction plays on the item's Assembly operation.+ const assembly = dataset.items.assembly;+ if (assembly) {+ if (!assembly.item) {+ fail(+ `items.assembly: an instruction linked to an operation needs an item`+ );+ } else {+ const op = rootOpsOf(assembly.item)[assembly.operation - 1];+ if (op?.operationType !== "Assembly") {+ fail(+ `items.assembly: operation ${assembly.operation} of "${assembly.item}" is not an "Assembly" operation`+ );+ }+ const playable = jobs.some((job) => {+ if (+ job.item !== assembly.item ||+ !RELEASED_OPEN_JOB_STATUSES.has(job.status)+ ) {+ return false;+ }+ const status = (job.operationOverrides ?? []).find(+ (o) => o.order === assembly.operation+ )?.status;+ return status !== "Done" && status !== "Canceled";+ });+ if (!playable) {+ fail(+ `items.assembly: no released "${assembly.item}" job with its Assembly operation still open (MES 3D playback)`+ );+ }+ }+ }++ // get_action_tasks_by_item_and_process: the MES operation screen lists an+ // open issue's task only on an open operation of a linked process that+ // builds one of the issue's items.+ const openRootOps = released.flatMap((job) =>+ rootOpsOf(job.item)+ .map((op, index) => ({ job, op, order: index + 1 }))+ .filter(({ order }) => {+ const status = (job.operationOverrides ?? []).find(+ (o) => o.order === order+ )?.status;+ return status !== "Done" && status !== "Canceled";+ })+ );+ const taskReachesFloor = dataset.quality.nonConformances.some(+ (ncr) =>+ OPEN_NCR_STATUSES.has(ncr.status) &&+ (ncr.actionTasks ?? []).some(+ (task) =>+ OPEN_NCR_TASK_STATUSES.has(task.status) &&+ (task.processes ?? []).some((process) =>+ openRootOps.some(+ ({ job, op }) =>+ op.process === process &&+ ncr.items.some((line) => line.item === job.item)+ )+ )+ )+ );+ if (!taskReachesFloor) {+ fail(+ "quality.nonConformances: no open action task whose process runs on an open operation building one of the issue's items (MES operation › issue actions)"+ );+ }+}++const MIN_ASSEMBLY_STEP_MATERIALS = 2;+const MIN_ASSEMBLY_COMPONENT_MAPPINGS = 2;++export function assembly(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { toolIds } = ix;+ const { componentsOf } = ix.bom;+ const assembly = dataset.items.assembly;+ if (assembly && dataset.industryId) {+ const graph = loadAssemblyGraph(dataset.industryId, assembly.model);+ if (!graph) {+ fail(+ `items.assembly: no bundled graph at assets/${dataset.industryId}/models/${assembly.model}.graph.json`+ );+ } else {+ if (assembly.componentCount !== graph.componentCount) {+ fail(+ `items.assembly "${assembly.model}": componentCount ${assembly.componentCount} != graph's ${graph.componentCount}`+ );+ }+ if (assembly.item !== undefined)+ need("item", "items.assembly", assembly.item);+ for (const step of assembly.steps) {+ for (const nodeId of step.componentNodeIds) {+ if (!graph.nodeIds.has(nodeId)) {+ fail(+ `items.assembly step "${step.title}": node id "${nodeId}" is not in the bundled graph`+ );+ }+ }+ }+ const bom =+ assembly.item === undefined+ ? new Set<string>()+ : componentsOf(assembly.item);+ let stepMaterials = 0;+ let stepTools = 0;+ for (const step of assembly.steps) {+ const where = `items.assembly step "${step.title}"`;+ const seen = new Set<string>();+ for (const material of step.materials ?? []) {+ stepMaterials += 1;+ if (!bom.has(material.item)) {+ fail(+ `${where}: material "${material.item}" is not on "${assembly.item}"'s BOM`+ );+ }+ if (seen.has(material.item)) {+ fail(`${where}: material "${material.item}" listed twice`);+ }+ seen.add(material.item);+ if (material.quantity <= 0) {+ fail(+ `${where}: material "${material.item}" quantity must be positive`+ );+ }+ }+ const seenTools = new Set<string>();+ for (const tool of step.tools ?? []) {+ stepTools += 1;+ if (!toolIds.has(tool.item)) {+ fail(`${where}: tool "${tool.item}" is not a Tool item`);+ }+ if (seenTools.has(tool.item)) {+ fail(`${where}: tool "${tool.item}" listed twice`);+ }+ seenTools.add(tool.item);+ if (!Number.isInteger(tool.quantity) || tool.quantity <= 0) {+ fail(+ `${where}: tool "${tool.item}" quantity must be a positive integer`+ );+ }+ }+ }+ if (stepMaterials < MIN_ASSEMBLY_STEP_MATERIALS) {+ fail(+ `items.assembly: ${stepMaterials} step materials, need ≥ ${MIN_ASSEMBLY_STEP_MATERIALS}`+ );+ }+ if (stepTools < 1) {+ fail("items.assembly: no step names a tool");+ }+ const mappedHashes = new Set<string>();+ for (const mapping of assembly.componentMappings) {+ const where = `items.assembly componentMappings "${mapping.geometryHash}"`;+ if (!graph.geometryHashes.has(mapping.geometryHash)) {+ fail(`${where}: not a leaf geometryHash of the bundled graph`);+ }+ if (mappedHashes.has(mapping.geometryHash)) {+ fail(`${where}: mapped twice`);+ }+ mappedHashes.add(mapping.geometryHash);+ if (!bom.has(mapping.item)) {+ fail(+ `${where}: "${mapping.item}" is not on "${assembly.item}"'s BOM`+ );+ }+ }+ if (mappedHashes.size < MIN_ASSEMBLY_COMPONENT_MAPPINGS) {+ fail(+ `items.assembly: ${mappedHashes.size} component mappings, need ≥ ${MIN_ASSEMBLY_COMPONENT_MAPPINGS}`+ );+ }+ }+ }+}++export function inspections(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { jobByKey, isTracked } = ix;+ const { rootOpsOf } = ix.bom;+ const q = dataset.quality;+ const p = dataset.purchasing;+ // Inspection lots — each mirrors the path that creates it (post-receipt, or+ // the MES opening a job's Inspection operation), and every authored sample+ // is exactly what the engine would have derived from its readings.+ const seenInspection = {+ status: new Set<string>(),+ source: new Set<string>()+ };+ const receiptPlanByItem = new Map<string, string>();+ const receiptLines = new Set<string>();+ const inspectedJobs = new Set<string>();+ for (const insp of q.inspections) {+ const where = `quality.inspections "${insp.ref}"`;+ seenInspection.status.add(insp.status);+ seenInspection.source.add(insp.source);++ let features: InspectionFeatureSpec[] = [];+ let lotSize: number | undefined;+ let aql: number | undefined;+ let earliest = Number.NEGATIVE_INFINITY;+ if (insp.source === "Receipt") {+ need("item", where, insp.item);+ features = insp.features;+ aql = insp.aql;+ const lineKey = `${insp.receipt}|${insp.item}`;+ if (receiptLines.has(lineKey)) {+ fail(`${where}: a second lot on the same receipt line`);+ }+ receiptLines.add(lineKey);+ const plan = JSON.stringify([+ insp.drawingNumber,+ insp.aql,+ insp.features+ ]);+ const other = receiptPlanByItem.get(insp.item);+ if (other !== undefined && other !== plan) {+ fail(+ `${where}: "${insp.item}" has one Receipt-usage plan — every lot of it carries the same drawing, aql and features`+ );+ }+ receiptPlanByItem.set(insp.item, plan);+ const receipt = p.purchaseOrders+ .map((po) => (po.source === "direct" ? po.receipt : undefined))+ .find((r) => r?.ref === insp.receipt);+ const line = receipt?.lines.find((l) => l.item === insp.item);+ if (!receipt) {+ fail(`${where}: unknown purchasing receipt ref "${insp.receipt}"`);+ } else if (receipt.status !== "Posted") {+ fail(+ `${where}: receipt "${insp.receipt}" is ${receipt.status}, not Posted`+ );+ } else if (!line || line.receivedQuantity <= 0) {+ fail(`${where}: receipt "${insp.receipt}" received no "${insp.item}"`);+ } else {+ if (line.requiresBatchTracking || isTracked(insp.item)) {+ fail(+ `${where}: "${insp.item}" is tracked — the seeded lot has no per-entity samples`+ );+ }+ lotSize = line.receivedQuantity;+ earliest = receipt.postedOffset ?? 0;+ }+ const labels = new Set<string>();+ for (const feature of insp.features) {+ if (labels.has(feature.label)) {+ fail(`${where}: duplicate feature label "${feature.label}"`);+ }+ labels.add(feature.label);+ }+ if (insp.features.length < 2) {+ fail(`${where}: needs at least 2 features`);+ }+ } else {+ if (inspectedJobs.has(insp.job)) {+ fail(+ `${where}: a second lot on job "${insp.job}"'s Inspection operation`+ );+ }+ inspectedJobs.add(insp.job);+ const job = jobByKey.get(insp.job);+ if (!job) {+ fail(`${where}: unknown job key "${insp.job}"`);+ } else {+ if (!RELEASED_OPEN_JOB_STATUSES.has(job.status)) {+ fail(+ `${where}: job "${insp.job}" is ${job.status}, not released and open`+ );+ }+ const roots = rootOpsOf(job.item);+ const index = roots.findIndex(+ (op) => op.operationType === "Inspection"+ );+ const op = roots[index];+ const plan = dataset.items.inspectionPlans.find(+ (candidate) => candidate.key === op?.inspectionPlan+ );+ if (!op || !plan) {+ fail(+ `${where}: "${job.item}" has no root Inspection operation with an inspection plan`+ );+ } else {+ features = plan.features;+ aql = plan.aql;+ lotSize = job.quantity;+ earliest = job.releasedDateOffset ?? 0;+ const override = (job.operationOverrides ?? []).find(+ (o) => o.order === index + 1+ );+ const opStatus =+ override?.status ?? (job.status === "Paused" ? "Paused" : "Ready");+ if (opStatus === "Done" || opStatus === "Canceled") {+ fail(`${where}: the Inspection operation is ${opStatus}`);+ }+ if (insp.status === "In Progress" && opStatus !== "In Progress") {+ fail(+ `${where}: samples are being recorded, so the Inspection operation must be In Progress, not ${opStatus}`+ );+ }+ }+ }+ if (insp.status === "Passed" || insp.status === "Partial") {+ fail(+ `${where}: a dispositioned job-operation lot posts production quantities the seed does not author`+ );+ }+ }++ const dispositioned = insp.status === "Passed" || insp.status === "Partial";+ if (dispositioned !== (insp.dispositionOffset !== undefined)) {+ fail(+ `${where}: dispositionOffset is required exactly when dispositioned`+ );+ }+ if (insp.dispositionOffset !== undefined && insp.dispositionOffset > 0) {+ fail(`${where}: dispositionOffset is in the future`);+ }+ if (lotSize !== undefined && aql !== undefined) {+ const plan = resolveInspectionPlan({ aql }, lotSize);+ if (plan.sampleSize > 5) {+ fail(+ `${where}: lot of ${lotSize} resolves to n=${plan.sampleSize} — pick a lot whose sample size is ≤ 5`+ );+ }+ const n = insp.samples.length;+ if (dispositioned && n !== plan.sampleSize) {+ fail(+ `${where}: ${n} samples authored but the plan resolves to n=${plan.sampleSize}`+ );+ }+ if (insp.status === "Pending" && n !== 0) {+ fail(`${where}: a Pending lot has no recorded samples`);+ }+ if (insp.status === "In Progress" && (n === 0 || n >= plan.sampleSize)) {+ fail(+ `${where}: an In Progress lot has 1…${plan.sampleSize - 1} recorded samples, not ${n}`+ );+ }+ }+ const latest = insp.dispositionOffset ?? -1;+ for (const [index, sample] of insp.samples.entries()) {+ if (+ sample.inspectedOffset < earliest ||+ sample.inspectedOffset > latest+ ) {+ fail(+ `${where} sample ${index + 1}: inspectedOffset ${sample.inspectedOffset} outside [${earliest}, ${latest}]`+ );+ }+ const labels = new Set(features.map((f) => f.label));+ const read = new Set<string>();+ for (const reading of sample.measurements) {+ if (!labels.has(reading.feature)) {+ fail(+ `${where} sample ${index + 1}: unknown feature "${reading.feature}"`+ );+ }+ if (read.has(reading.feature)) {+ fail(+ `${where} sample ${index + 1}: feature "${reading.feature}" read twice`+ );+ }+ read.add(reading.feature);+ }+ const derived = deriveSampleStatus(features, sample);+ if (derived !== sample.status) {+ fail(+ `${where} sample ${index + 1}: status "${sample.status}" but its readings derive "${derived}"`+ );+ }+ }+ const passed = insp.samples.filter((s) => s.status === "Passed").length;+ const failed = insp.samples.filter((s) => s.status === "Failed").length;+ if (insp.status === "Partial" && (passed === 0 || failed === 0)) {+ fail(`${where}: Partial needs at least one Passed and one Failed sample`);+ }+ if (insp.status === "Passed" && failed > 0) {+ fail(`${where}: Passed lot has a Failed sample`);+ }+ }+ checkCoverage(fail, {+ inspectionStatus: seenInspection.status,+ inspectionSource: seenInspection.source+ });+}++const MIN_NCR_WORKFLOWS = 3;+const MIN_WORKFLOW_LINKED_NCRS = 2;+/** The quality dashboard's supplier KPI reads issues opened in the last month. */+const SUPPLIER_QUALITY_WINDOW_DAYS = 28;+/** Dispositions the closeIssue path accepts without posting inventory value. */+const CLOSED_NCR_DISPOSITIONS = new Set(["Use As Is", "Rework"]);++export function checkCompletion(+ fail: (message: string) => void,+ where: string,+ status: string,+ openDateOffset: number,+ completedOffset: number | undefined+): void {+ if (status === "Completed" && completedOffset === undefined) {+ fail(`${where}: Completed but has no completedOffset`);+ }+ if (status !== "Completed" && completedOffset !== undefined) {+ fail(`${where}: completedOffset on a task that is "${status}"`);+ }+ if (+ completedOffset !== undefined &&+ (completedOffset < openDateOffset || completedOffset > 0)+ ) {+ fail(+ `${where}: completedOffset ${completedOffset} outside [${openDateOffset}, 0]`+ );+ }+}++export function quality(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const p = dataset.purchasing;+ const q = dataset.quality;+ const seenQuality = {+ ncrStatus: new Set<string>(),+ ncrPriority: new Set<string>(),+ ncrSource: new Set<string>(),+ ncrTaskStatus: new Set<string>(),+ documentStatus: new Set<string>(),+ gaugeStatus: new Set<string>(),+ gaugeCalibration: new Set<string>(),+ riskStatus: new Set<string>(),+ riskSource: new Set<string>(),+ riskType: new Set<string>()+ };++ const directPoByRef = new Map<+ string,+ { supplier: string; items: Set<string> }+ >();+ for (const po of p.purchaseOrders) {+ if (po.source !== "direct" || po.ref === undefined) continue;+ directPoByRef.set(po.ref, {+ supplier: po.supplier,+ items: new Set(po.lines.map((line) => line.item))+ });+ }+ const salesOrderLineCustomer = new Map<string, string>();+ for (const spec of [+ ...dataset.sales.opportunities,+ ...dataset.sales.releasedOrders+ ]) {+ for (const line of spec.order?.lines ?? []) {+ salesOrderLineCustomer.set(line.ref, spec.customer);+ }+ }+ for (const spec of dataset.sales.statusOrders) {+ salesOrderLineCustomer.set(`soline:${spec.key}`, spec.customer);+ }+ const inspectionRefs = new Set(q.inspections.map((insp) => insp.ref));++ const workflowByKey = new Map<string, (typeof q.workflows)[number]>();+ const workflowNames = new Set<string>();+ for (const workflow of q.workflows) {+ const where = `quality.workflows "${workflow.key}"`;+ if (workflowByKey.has(workflow.key)) fail(`${where}: duplicate key`);+ workflowByKey.set(workflow.key, workflow);+ if (workflowNames.has(workflow.name)) fail(`${where}: duplicate name`);+ workflowNames.add(workflow.name);+ if (!workflow.description.trim()) fail(`${where}: empty description`);+ if (workflow.requiredActions.length === 0) {+ fail(`${where}: no required actions`);+ }+ const actions = new Set<string>();+ for (const action of workflow.requiredActions) {+ if (!NCR_ACTION_NAMES.has(action)) {+ fail(+ `${where}: "${action}" is not a bootstrap nonConformanceRequiredAction`+ );+ }+ if (actions.has(action)) fail(`${where}: duplicate action "${action}"`);+ actions.add(action);+ }+ }+ if (q.workflows.length < MIN_NCR_WORKFLOWS) {+ fail(+ `quality.workflows: ${q.workflows.length} workflows, need ≥ ${MIN_NCR_WORKFLOWS} (Issue Workflows)`+ );+ }++ const processesInUse = new Set(+ dataset.items.methods.flatMap((method) =>+ method.bop.map((op) => op.process)+ )+ );+ const { documentRefs } = ix;+ for (const [ncrIndex, ncr] of q.nonConformances.entries()) {+ const where = `quality.nonConformances "${ncr.ref}"`;+ seenQuality.ncrStatus.add(ncr.status);+ seenQuality.ncrPriority.add(ncr.priority);+ seenQuality.ncrSource.add(ncr.source);+ if (+ ncr.jobOperation &&+ !documentRefs.has(+ ncr.jobOperation.job,+ documentRefs.seenBy.nonConformances[ncrIndex]!+ )+ ) {+ fail(`${where}: unknown job ref "${ncr.jobOperation.job}"`);+ }+ if (ncr.items.length === 0) {+ fail(+ `${where}: no items — the issue's Items card and Actions list are empty`+ );+ }+ const ncrItems = new Set<string>();+ for (const line of ncr.items) {+ need("item", where, line.item);+ if (ncrItems.has(line.item))+ fail(`${where}: item "${line.item}" listed twice`);+ ncrItems.add(line.item);+ if (line.quantity <= 0) {+ fail(`${where} item "${line.item}": quantity must be positive`);+ }+ const disposition = line.disposition ?? "Pending";+ if (+ ncr.status === "Closed" &&+ !CLOSED_NCR_DISPOSITIONS.has(disposition)+ ) {+ fail(+ `${where} item "${line.item}": a Closed issue's rows are dispositioned Use As Is or Rework (other dispositions post inventory value the seed does not author), not "${disposition}"`+ );+ }+ }+ if (ncr.assignee !== undefined && !OPEN_NCR_STATUSES.has(ncr.status)) {+ fail(+ `${where}: an assignee on a ${ncr.status} issue (closing clears it)`+ );+ }+ if (ncr.workflow !== undefined) {+ const workflow = workflowByKey.get(ncr.workflow);+ if (!workflow) {+ fail(`${where}: unknown workflow "${ncr.workflow}"`);+ } else {+ const actions = (ncr.actionTasks ?? []).map((t) => t.action);+ if (+ workflow.source !== ncr.source ||+ JSON.stringify(workflow.requiredActions) !==+ JSON.stringify(actions) ||+ Boolean(workflow.mrb) !== Boolean(ncr.mrb)+ ) {+ fail(+ `${where}: raised from workflow "${ncr.workflow}" but its source, required actions or MRB differ from the workflow's`+ );+ }+ }+ }++ if (ncr.type !== undefined && !NCR_TYPE_NAMES.has(ncr.type)) {+ fail(+ `${where}: type "${ncr.type}" is not a bootstrap nonConformanceType`+ );+ }+ if (ncr.openDateOffset > 0)+ fail(`${where}: openDateOffset is in the future`);+ if (ncr.status === "Closed") {+ if (ncr.closeDateOffset === undefined) {+ fail(`${where}: Closed but has no closeDateOffset`);+ } else if (+ ncr.closeDateOffset < ncr.openDateOffset ||+ ncr.closeDateOffset > 0+ ) {+ fail(+ `${where}: closeDateOffset ${ncr.closeDateOffset} outside [${ncr.openDateOffset}, 0]`+ );+ }+ } else if (ncr.closeDateOffset !== undefined) {+ fail(`${where}: closeDateOffset on a ${ncr.status} NCR`);+ }++ if (ncr.supplier !== undefined) need("supplier", where, ncr.supplier);+ if (ncr.purchaseOrderLine !== undefined) {+ const { po, item } = ncr.purchaseOrderLine;+ const order = directPoByRef.get(po);+ if (!order) {+ fail(`${where}: unknown direct purchase order ref "${po}"`);+ } else {+ if (!order.items.has(item)) {+ fail(`${where}: purchase order "${po}" has no line for "${item}"`);+ }+ if (order.supplier !== ncr.supplier) {+ fail(+ `${where}: purchase order "${po}" is on "${order.supplier}", not the NCR's supplier "${ncr.supplier ?? "(none)"}"`+ );+ }+ }+ }+ if (ncr.customer !== undefined) need("customer", where, ncr.customer);+ if (ncr.salesOrderLine !== undefined) {+ const owner = salesOrderLineCustomer.get(ncr.salesOrderLine);+ if (owner === undefined) {+ fail(`${where}: unknown sales order line ref "${ncr.salesOrderLine}"`);+ } else if (owner !== ncr.customer) {+ fail(+ `${where}: sales order line "${ncr.salesOrderLine}" belongs to "${owner}", not the NCR's customer "${ncr.customer ?? "(none)"}"`+ );+ }+ }+ if (+ ncr.trackedEntity !== undefined &&+ !ix.lots.onHandIds.has(ncr.trackedEntity) &&+ !ix.lots.receiptLotIds.has(ncr.trackedEntity)+ ) {+ fail(+ `${where}: tracked entity "${ncr.trackedEntity}" is not an on-hand lot/serial or a receipt lotNumber`+ );+ }+ if (ncr.inspection !== undefined && !inspectionRefs.has(ncr.inspection)) {+ fail(`${where}: unknown inspection ref "${ncr.inspection}"`);+ }++ const actions = new Set<string>();+ for (const task of ncr.actionTasks ?? []) {+ const taskWhere = `${where} action "${task.action}"`;+ if (!NCR_ACTION_NAMES.has(task.action)) {+ fail(`${taskWhere}: not a bootstrap nonConformanceRequiredAction`);+ }+ if (actions.has(task.action))+ fail(`${taskWhere}: duplicate required action`);+ actions.add(task.action);+ seenQuality.ncrTaskStatus.add(task.status);+ for (const process of task.processes ?? []) {+ if (!processesInUse.has(process)) {+ fail(+ `${taskWhere}: process "${process}" is not used by any operation`+ );+ }+ }+ if (+ (task.processes ?? []).length > 0 &&+ !OPEN_NCR_TASK_STATUSES.has(task.status)+ ) {+ fail(`${taskWhere}: processes are linked while a task is open`);+ }+ checkCompletion(+ fail,+ taskWhere,+ task.status,+ ncr.openDateOffset,+ task.completedOffset+ );+ }+ const allTasks = [+ ...(ncr.actionTasks ?? []).map((t) => t.status),+ ...(ncr.mrb+ ? [ncr.mrb.status, ...ncr.mrb.reviewers.map((r) => r.status)]+ : [])+ ];+ // Tasks start Pending and working one moves the issue to In Progress; a+ // Closed issue has nothing left open.+ if (ncr.status === "Registered" && allTasks.some((s) => s !== "Pending")) {+ fail(`${where}: a Registered NCR can only have Pending tasks`);+ }+ if (+ ncr.status === "Closed" &&+ allTasks.some((s) => s !== "Completed" && s !== "Skipped")+ ) {+ fail(`${where}: a Closed NCR has open tasks`);+ }+ if (ncr.mrb) {+ checkCompletion(+ fail,+ `${where} MRB approval`,+ ncr.mrb.status,+ ncr.openDateOffset,+ ncr.mrb.completedOffset+ );+ const titles = new Set<string>();+ for (const reviewer of ncr.mrb.reviewers) {+ if (titles.has(reviewer.title)) {+ fail(`${where}: duplicate MRB reviewer "${reviewer.title}"`);+ }+ titles.add(reviewer.title);+ checkCompletion(+ fail,+ `${where} reviewer "${reviewer.title}"`,+ reviewer.status,+ ncr.openDateOffset,+ reviewer.completedOffset+ );+ }+ }+ }++ const linkedNcrs = q.nonConformances.filter((n) => n.workflow !== undefined);+ if (linkedNcrs.length < MIN_WORKFLOW_LINKED_NCRS) {+ fail(+ `quality.nonConformances: ${linkedNcrs.length} issues raised from a workflow, need ≥ ${MIN_WORKFLOW_LINKED_NCRS}`+ );+ }+ if (+ !q.nonConformances.some(+ (n) => n.assignee === "self" && OPEN_NCR_STATUSES.has(n.status)+ )+ ) {+ fail(+ "quality.nonConformances: no open issue assigned to the applying user (dashboard › Assigned to me)"+ );+ }+ if (+ !q.nonConformances.some(+ (n) =>+ n.supplier !== undefined &&+ n.openDateOffset >= -SUPPLIER_QUALITY_WINDOW_DAYS+ )+ ) {+ fail(+ `quality.nonConformances: no supplier issue opened in the last ${SUPPLIER_QUALITY_WINDOW_DAYS} days (dashboard › Supplier quality)`+ );+ }+ if (+ !q.nonConformances.some((n) =>+ (n.actionTasks ?? []).some((t) => (t.processes ?? []).length > 0)+ )+ ) {+ fail(+ "quality.nonConformances: no open action task linked to a process (nonConformanceActionProcess)"+ );+ }++ const documentVersions = new Set<string>();+ for (const doc of q.qualityDocuments) {+ const where = `quality.qualityDocuments "${doc.name}" v${doc.version}`;+ seenQuality.documentStatus.add(doc.status);+ const key = `${doc.name}@${doc.version}`;+ if (documentVersions.has(key)) fail(`${where}: duplicate (name, version)`);+ documentVersions.add(key);+ if (doc.version < 0) fail(`${where}: version must be ≥ 0`);+ if (doc.status === "Active" && doc.steps.length < 2) {+ fail(`${where}: the Active document needs at least 2 steps`);+ }+ for (const step of doc.steps) {+ const stepWhere = `${where} step "${step.name}"`;+ if (step.type === "Measurement") {+ if (step.unitOfMeasureCode === undefined) {+ fail(`${stepWhere}: Measurement step needs a unitOfMeasureCode`);+ } else if (!UOM_CODES.has(step.unitOfMeasureCode)) {+ fail(+ `${stepWhere}: unitOfMeasureCode "${step.unitOfMeasureCode}" is not a bootstrap unit of measure`+ );+ }+ } else if (step.unitOfMeasureCode !== undefined) {+ fail(`${stepWhere}: only Measurement steps take a unitOfMeasureCode`);+ }+ if (step.type === "List" && (step.listValues ?? []).length === 0) {+ fail(`${stepWhere}: List step needs listValues`);+ }+ if (+ step.minValue !== undefined &&+ step.maxValue !== undefined &&+ step.minValue > step.maxValue+ ) {+ fail(`${stepWhere}: minValue > maxValue`);+ }+ }+ }++ const gaugeKeys = new Set<string>();+ let activeMaster = false;+ for (const gauge of q.gauges) {+ const where = `quality.gauges "${gauge.key}"`;+ if (gaugeKeys.has(gauge.key)) fail(`${where}: duplicate gauge key`);+ gaugeKeys.add(gauge.key);+ if (!GAUGE_TYPE_NAMES.has(gauge.gaugeType)) {+ fail(+ `${where}: gaugeType "${gauge.gaugeType}" is not a bootstrap gauge type`+ );+ }+ if (gauge.supplier !== undefined) need("supplier", where, gauge.supplier);+ if (gauge.shelf !== undefined) need("shelf", where, gauge.shelf);+ if (gauge.calibrationIntervalInMonths <= 0) {+ fail(`${where}: calibrationIntervalInMonths must be positive`);+ }+ if (gauge.acquiredOffset > 0)+ fail(`${where}: acquiredOffset is in the future`);+ let previous = gauge.acquiredOffset;+ for (const record of gauge.calibrations) {+ if (record.dateOffset < previous || record.dateOffset > 0) {+ fail(+ `${where}: calibration on ${record.dateOffset} is out of order (after acquisition, oldest first, not in the future)`+ );+ }+ previous = record.dateOffset;+ }+ const latest = gauge.calibrations.at(-1);+ const calibration =+ latest === undefined+ ? "Pending"+ : latest.result === "Pass"+ ? "In-Calibration"+ : "Out-of-Calibration";+ // The gauges view flips an overdue gauge to Out-of-Calibration; an+ // In-Calibration gauge must still be inside its interval (28-day months,+ // conservatively).+ if (+ calibration === "In-Calibration" &&+ latest !== undefined &&+ latest.dateOffset + 28 * gauge.calibrationIntervalInMonths <= 0+ ) {+ fail(`${where}: last Pass calibration is already past its interval`);+ }+ seenQuality.gaugeStatus.add(gauge.status);+ seenQuality.gaugeCalibration.add(calibration);+ if (gauge.role === "Master" && gauge.status === "Active")+ activeMaster = true;+ }+ if (!activeMaster) fail("quality.gauges: needs an Active Master gauge");++ for (const risk of q.risks) {+ const where = `quality.risks "${risk.title}"`;+ seenQuality.riskStatus.add(risk.status);+ seenQuality.riskSource.add(risk.source);+ seenQuality.riskType.add(risk.type);+ for (const [field, value] of [+ ["severity", risk.severity],+ ["likelihood", risk.likelihood]+ ] as const) {+ if (!Number.isInteger(value) || value < 1 || value > 5) {+ fail(`${where}: ${field} ${value} must be an integer 1–5`);+ }+ }+ switch (risk.source) {+ case "Customer":+ need("customer", where, risk.customer);+ break;+ case "Supplier":+ need("supplier", where, risk.supplier);+ break;+ case "Item":+ need("item", where, risk.item);+ break;+ case "Job":+ if (+ !risk.job.startsWith("job:") ||+ !documentRefs.has(risk.job, documentRefs.seenBy.risks)+ ) {+ fail(`${where}: unknown job ref "${risk.job}"`);+ }+ break;+ case "Work Center":+ need("workCenter", where, risk.workCenter);+ break;+ case "General":+ break;+ }+ }++ checkCoverage(fail, {+ ncrStatus: seenQuality.ncrStatus,+ ncrPriority: seenQuality.ncrPriority,+ ncrSource: seenQuality.ncrSource,+ ncrTaskStatus: seenQuality.ncrTaskStatus,+ qualityDocumentStatus: seenQuality.documentStatus,+ gaugeStatus: seenQuality.gaugeStatus,+ gaugeCalibrationStatus: seenQuality.gaugeCalibration,+ riskStatus: seenQuality.riskStatus,+ riskSource: seenQuality.riskSource,+ riskType: seenQuality.riskType+ });+}++export function changeOrders(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const seenChangeOrderStatus = new Set<string>();+ const seenChangeOrderTaskStatus = new Set<string>();+ for (const co of dataset.changeOrders.changeOrders) {+ const where = `changeOrders "${co.ref}"`;+ seenChangeOrderStatus.add(co.status);+ for (const affected of co.affectedItems) {+ need("item", where, affected.item);+ if (affected.changeType === "Revision" && !affected.revision) {+ fail(`${where}: Revision on "${affected.item}" has no revision spec`);+ }+ for (const edit of affected.revision?.bomEdits ?? []) {+ need("item", `${where} bomEdits`, edit.component);+ }+ }+ if (+ co.changeOrderType !== undefined &&+ !CO_TYPE_NAMES.has(co.changeOrderType)+ ) {+ fail(+ `${where}: changeOrderType "${co.changeOrderType}" is not a bootstrap changeOrderType`+ );+ }+ if (co.nonConformance !== undefined && !ix.ncrRefs.has(co.nonConformance)) {+ fail(`${where}: unknown NCR ref "${co.nonConformance}"`);+ }+ if (+ co.dueDateOffset !== undefined &&+ co.dueDateOffset < co.openDateOffset+ ) {+ fail(`${where}: dueDateOffset before openDateOffset`);+ }+ const actions = new Set<string>();+ for (const task of co.actionTasks ?? []) {+ const taskWhere = `${where} action "${task.action}"`;+ if (!CO_ACTION_NAMES.has(task.action)) {+ fail(`${taskWhere}: not a bootstrap changeOrderRequiredAction`);+ }+ if (actions.has(task.action))+ fail(`${taskWhere}: duplicate required action`);+ actions.add(task.action);+ seenChangeOrderTaskStatus.add(task.status);+ checkCompletion(+ fail,+ taskWhere,+ task.status,+ co.openDateOffset,+ task.completedOffset+ );+ }+ }+ checkCoverage(fail, {+ changeOrderStatus: seenChangeOrderStatus,+ changeOrderTaskStatus: seenChangeOrderTaskStatus+ });+}++type InvoiceFacts = {+ party: string;+ /** Σ line quantity × price — what the salesInvoices/purchaseInvoices views total. */+ total: number;+ issued: number;+ status: string;+ currencyCode: string;+};++export function accounting(ctx: ValidationCtx): void {+ const { dataset, ix, fail } = ctx;+ const customers = ix.refs.customer;+ const suppliers = ix.refs.supplier;+ const a = dataset.accounting;++ const salesInvoices = new Map<string, InvoiceFacts>();+ for (const opp of [+ ...dataset.sales.opportunities,+ ...dataset.sales.releasedOrders+ ]) {+ const inv = opp.invoice;+ if (inv?.key === undefined) continue;+ salesInvoices.set(inv.key, {+ party: opp.customer,+ total: inv.lines.reduce((s, l) => s + l.quantity * l.unitPrice, 0),+ issued: inv.dateIssuedOffset,+ status: inv.status,+ currencyCode: "USD"+ });+ }+ const purchaseInvoices = new Map<string, InvoiceFacts>();+ for (const po of dataset.purchasing.purchaseOrders) {+ if (po.source !== "direct" || po.invoice?.key === undefined) continue;+ purchaseInvoices.set(po.invoice.key, {+ party: po.supplier,+ total: po.invoice.lines.reduce(+ (s, l) => s + l.quantity * l.supplierUnitPrice,+ 0+ ),+ issued: po.invoice.dateIssuedOffset,+ status: po.invoice.status,+ currencyCode: po.invoice.currencyCode+ });+ }+ const invoiceIn = (sales: boolean) =>+ sales ? salesInvoices : purchaseInvoices;+ const invoiceLabel = (sales: boolean, key: string) =>+ `${sales ? "sinv" : "pinv"}:${key}`;+ const settled = new Map<string, number>();+ const partialDates = new Map<string, number[]>();+ const settle = (label: string, amount: number, dateOffset: number) => {+ settled.set(label, (settled.get(label) ?? 0) + amount);+ partialDates.set(label, [...(partialDates.get(label) ?? []), dateOffset]);+ };++ const projectKeys = new Set<string>();+ const projectNames = new Set<string>();+ for (const project of a.projects) {+ const where = `accounting.projects "${project.key}"`;+ if (projectKeys.has(project.key)) fail(`${where}: duplicate key`);+ if (projectNames.has(project.name))+ fail(`${where}: duplicate name "${project.name}" (unique per company)`);+ projectKeys.add(project.key);+ projectNames.add(project.name);+ const link = project.purchaseInvoiceLine;+ if (link) {+ const po = dataset.purchasing.purchaseOrders.find(+ (p) => p.source === "direct" && p.invoice?.key === link.invoiceKey+ );+ if (!po || po.source !== "direct" || !po.invoice) {+ fail(`${where}: unknown purchase invoice key "${link.invoiceKey}"`);+ } else if (+ po.invoice.lines.filter((l) => l.item === link.item).length !== 1+ ) {+ fail(+ `${where}: purchase invoice "${link.invoiceKey}" has no single line for "${link.item}"`+ );+ }+ }+ }+ if (a.projects.length < 2) fail("accounting.projects: expected at least 2");+ if (!a.projects.some((p) => p.purchaseInvoiceLine)) {+ fail("accounting.projects: no project codes a purchase invoice line");+ }++ const custom = a.customDimension;+ if (BOOTSTRAP_DIMENSION_NAMES.has(custom.name)) {+ fail(+ `accounting.customDimension: "${custom.name}" collides with a bootstrap dimension`+ );+ }+ if (new Set(custom.values).size !== custom.values.length) {+ fail("accounting.customDimension: duplicate value");+ }+ if (custom.values.length < 2) {+ fail("accounting.customDimension: expected at least 2 values");+ }++ const journalEntryIds = new Set<string>();+ const seenJournalStatus = new Set<string>();+ let postedDimensionTags = 0;+ const needEntryId = (where: string, id: string) => {+ if (journalEntryIds.has(id))+ fail(`${where}: duplicate journalEntryId "${id}"`);+ journalEntryIds.add(id);+ };+ for (const entry of a.journalEntries) {+ const where = `accounting.journalEntries "${entry.ref}"`;+ needEntryId(where, entry.journalEntryId);+ seenJournalStatus.add(entry.status);+ const net = journalImbalance(entry);+ // Stricter than the app's manual-journal 0.001 (accounting.service.ts):+ // authored amounts are exact, so any residual is an authoring error.+ if (Math.abs(net) > EPSILON) {+ fail(`${where}: entry does not balance (net ${net})`);+ }+ if (entry.lines.length < 2) fail(`${where}: needs at least two lines`);+ // The period-open trigger rejects ANY journal dated in a Closed period;+ // posted work belongs in an Open one.+ const minOffset =+ entry.status === "Draft" ? NOT_CLOSED_MIN_OFFSET : OPEN_PERIOD_MIN_OFFSET;+ if (entry.postingOffset > 0 || entry.postingOffset < minOffset) {+ fail(+ `${where}: postingOffset ${entry.postingOffset} outside [${minOffset}, 0] (seeded period close state)`+ );+ }+ const references = entry.lines.map((l) => l.journalLineReference);+ for (const line of entry.lines) {+ if ((line.accountClass === undefined) === (line.account === undefined)) {+ fail(+ `${where}: a line must name exactly one of accountClass / account`+ );+ } else if (lineClass(line) === undefined) {+ fail(`${where}: unknown GL account "${line.account}"`);+ }+ if (!line.dimensions?.length) continue;+ if (+ references.filter((r) => r === line.journalLineReference).length !== 1+ ) {+ fail(+ `${where}: a dimension-tagged line needs a unique journalLineReference ("${line.journalLineReference}")`+ );+ }+ const dims = new Set<string>();+ for (const tag of line.dimensions) {+ if (dims.has(tag.dimension))+ fail(+ `${where}: dimension "${tag.dimension}" tagged twice on one line`+ );+ dims.add(tag.dimension);+ if (tag.dimension === "Project") {+ if (!projectKeys.has(tag.value))+ fail(`${where}: unknown project "${tag.value}"`);+ } else if (tag.dimension !== custom.name) {+ fail(`${where}: unknown dimension "${tag.dimension}"`);+ } else if (!custom.values.includes(tag.value)) {+ fail(`${where}: "${tag.value}" is not a ${custom.name} value`);+ }+ if (entry.status === "Posted") postedDimensionTags++;+ }+ }+ if ((entry.status === "Reversed") !== (entry.reversal !== undefined)) {+ fail(+ `${where}: a reversal entry is required exactly when status is Reversed`+ );+ }+ if (entry.reversal) {+ needEntryId(where, entry.reversal.journalEntryId);+ if (+ entry.reversal.postingOffset < entry.postingOffset ||+ entry.reversal.postingOffset > 0+ ) {+ fail(+ `${where}: reversal postingOffset ${entry.reversal.postingOffset} must fall between the original's and today`+ );+ }+ }+ }+ checkCoverage(fail, { journalStatus: seenJournalStatus });+ if (postedDimensionTags === 0) {+ fail("accounting.journalEntries: no Posted line carries a dimension tag");+ }++ const memos = new Map<+ string,+ { party: string; direction: string; amount: number; dateOffset: number }+ >();+ const seenDirections = new Set<string>();+ for (const memo of a.memos) {+ const where = `accounting.memos "${memo.key}"`;+ seenDirections.add(memo.direction);+ const sales = memo.direction === "Credit";+ const party = sales ? memo.customer : memo.supplier;+ if (!party || (sales ? memo.supplier : memo.customer) !== undefined) {+ fail(+ `${where}: a ${memo.direction} memo names exactly one ${sales ? "customer" : "supplier"}`+ );+ continue;+ }+ if (!(sales ? customers : suppliers).has(party))+ fail(`${where}: unknown ${sales ? "customer" : "supplier"} "${party}"`);+ const invoice = invoiceIn(sales).get(memo.invoiceKey);+ if (!invoice) {+ fail(+ `${where}: unknown invoice key "${invoiceLabel(sales, memo.invoiceKey)}"`+ );+ continue;+ }+ if (invoice.party !== party)+ fail(+ `${where}: party "${party}" does not match the invoice's "${invoice.party}"`+ );+ if (invoice.currencyCode !== "USD")+ fail(`${where}: memos settle base-currency (USD) invoices only`);+ if (+ memo.amount <= 0 ||+ round(memo.amount, USD_DECIMALS) > round(invoice.total, USD_DECIMALS)+ )+ fail(+ `${where}: amount ${memo.amount} outside (0, invoice total ${invoice.total}]`+ );+ if (+ memo.dateOffset < invoice.issued ||+ memo.dateOffset > 0 ||+ memo.dateOffset < OPEN_PERIOD_MIN_OFFSET+ ) {+ fail(+ `${where}: dateOffset ${memo.dateOffset} must fall between the invoice's issue date and today`+ );+ }+ memos.set(memo.key, {+ party,+ direction: memo.direction,+ amount: memo.amount,+ dateOffset: memo.dateOffset+ });+ }+ checkCoverage(fail, { memoDirection: seenDirections });++ const seenTypes = new Set<string>();+ const memoConsumed = new Map<string, number>();+ for (const payment of a.payments) {+ const where = `accounting.payments "${payment.key}"`;+ if (payment.status === "Draft") {+ // Checked with the open invoices in rules/postings.ts.+ continue;+ }+ seenTypes.add(payment.type);+ const sales = payment.type === "Receipt";+ const party = sales ? payment.customer : payment.supplier;+ if (!party || (sales ? payment.supplier : payment.customer) !== undefined) {+ fail(+ `${where}: a ${payment.type} names exactly one ${sales ? "customer" : "supplier"}`+ );+ continue;+ }+ if (!(sales ? customers : suppliers).has(party))+ fail(`${where}: unknown ${sales ? "customer" : "supplier"} "${party}"`);+ if (payment.amount < 0) fail(`${where}: negative amount`);+ const applied = payment.applies.reduce((s, x) => s + x.amount, 0);+ if (round(applied, USD_DECIMALS) !== round(payment.amount, USD_DECIMALS)) {+ fail(+ `${where}: applications total ${applied} but the payment is ${payment.amount}`+ );+ }+ if (payment.amount === 0 && !payment.credits?.length) {+ fail(`${where}: a zero-cash payment must carry credit applications`);+ }+ if (payment.dateOffset > 0 || payment.dateOffset < OPEN_PERIOD_MIN_OFFSET) {+ fail(+ `${where}: dateOffset ${payment.dateOffset} outside [${OPEN_PERIOD_MIN_OFFSET}, 0]`+ );+ }+ const checkTarget = (invoiceKey: string, amount: number) => {+ const invoice = invoiceIn(sales).get(invoiceKey);+ const label = invoiceLabel(sales, invoiceKey);+ if (!invoice) {+ fail(`${where}: unknown invoice key "${label}"`);+ return;+ }+ if (invoice.party !== party)+ fail(+ `${where}: party "${party}" does not match ${label}'s "${invoice.party}"`+ );+ if (invoice.currencyCode !== "USD")+ fail(+ `${where}: ${label} is not base currency — seeded settlements are USD only`+ );+ if (amount <= 0) fail(`${where}: non-positive application to ${label}`);+ if (payment.dateOffset < invoice.issued) {+ fail(+ `${where}: dateOffset ${payment.dateOffset} precedes ${label}'s issue date ${invoice.issued}`+ );+ }+ settle(label, amount, payment.dateOffset);+ };+ for (const apply of payment.applies)+ checkTarget(apply.invoiceKey, apply.amount);+ for (const credit of payment.credits ?? []) {+ const memo = memos.get(credit.memoKey);+ if (!memo) {+ fail(`${where}: unknown memo "${credit.memoKey}"`);+ continue;+ }+ if (+ memo.direction !== (sales ? "Credit" : "Debit") ||+ memo.party !== party+ ) {+ fail(+ `${where}: memo "${credit.memoKey}" must be a ${sales ? "Credit" : "Debit"} memo of "${party}"`+ );+ }+ if (payment.dateOffset < memo.dateOffset) {+ fail(`${where}: applies memo "${credit.memoKey}" before it was posted`);+ }+ memoConsumed.set(+ credit.memoKey,+ (memoConsumed.get(credit.memoKey) ?? 0) + credit.amount+ );+ checkTarget(credit.invoiceKey, credit.amount);+ }+ }+ checkCoverage(fail, { paymentType: seenTypes });+ for (const [key, consumed] of memoConsumed) {+ const memo = memos.get(key);+ if (+ memo &&+ round(consumed, USD_DECIMALS) > round(memo.amount, USD_DECIMALS)+ ) {+ fail(+ `accounting.memos "${key}": applied ${consumed} exceeds its amount ${memo.amount}`+ );+ }+ }+ // The invoice views derive status from settlements, so the authored status+ // and the settled total must agree.+ for (const sales of [true, false]) {+ for (const [key, invoice] of invoiceIn(sales)) {+ const label = invoiceLabel(sales, key);+ const paid = round(settled.get(label) ?? 0, USD_DECIMALS);+ const total = round(invoice.total, USD_DECIMALS);+ if (paid > total) {+ fail(+ `accounting: ${label} is over-settled (${paid} of ${invoice.total})`+ );+ }+ const fullyCredited =+ invoice.status === "Credit Note Issued" ||+ invoice.status === "Debit Note Issued";+ if ((invoice.status === "Paid" || fullyCredited) && paid !== total) {+ fail(+ `accounting: ${label} is ${invoice.status} but settled ${paid} of ${invoice.total}`+ );+ } else if (invoice.status === "Partially Paid") {+ if (paid <= 0 || paid >= total) {+ fail(+ `accounting: ${label} is Partially Paid but settled ${paid} of ${invoice.total}`+ );+ }+ if ((partialDates.get(label) ?? []).some((d) => d >= 0)) {+ fail(`accounting: ${label}'s partial payment must predate today`);+ }+ } else if (invoice.status !== "Paid" && !fullyCredited && paid !== 0) {+ fail(+ `accounting: ${label} is ${invoice.status} yet carries settlements (the view would re-derive its status)`+ );+ }+ }+ }++ const seenTaskStatus = new Set<string>();+ const taskDefinitions = new Set<string>();+ for (const task of a.closeTasks) {+ const where = `accounting.closeTasks "${task.definition}"`;+ if (!CLOSE_TASK_DEFINITION_NAMES.has(task.definition))+ fail(`${where}: not a bootstrap periodCloseTaskDefinition`);+ if (taskDefinitions.has(task.definition))+ fail(`${where}: duplicate (unique per period + definition)`);+ taskDefinitions.add(task.definition);+ seenTaskStatus.add(task.status);+ if ((task.status === "Skipped") !== Boolean(task.skippedReason)) {+ fail(`${where}: skippedReason is required exactly when Skipped`);+ }+ }+ checkCoverage(fail, { periodCloseTaskStatus: seenTaskStatus });++ const eurPo = dataset.purchasing.purchaseOrders.find(+ (p) => p.source === "direct" && p.currencyCode === "EUR"+ );+ const overrideCodes = new Set<string>();+ for (const override of a.exchangeRateOverrides) {+ const where = `accounting.exchangeRateOverrides "${override.currencyCode}"`;+ if (overrideCodes.has(override.currencyCode))+ fail(`${where}: duplicate (unique per company + currency)`);+ overrideCodes.add(override.currencyCode);+ if (override.currencyCode === "USD")+ fail(`${where}: the base currency needs no rate`);+ if (!(override.rate > 0)) fail(`${where}: rate must be positive`);+ const poRate =+ eurPo?.source === "direct" && override.currencyCode === "EUR"+ ? eurPo.exchangeRate+ : undefined;+ // Same direction as the document snapshot (foreign units per base unit):+ // an inverted rate would be ~1/rate, far outside this band.+ if (poRate !== undefined && Math.abs(override.rate / poRate - 1) > 0.05) {+ fail(+ `${where}: rate ${override.rate} disagrees with the EUR order's ${poRate}`+ );+ }+ // Rates are units of the foreign currency per 1 USD, and a euro is worth+ // more than a dollar — so a EUR rate at or above 1 is the inverted+ // (USD-per-EUR) quote, which halves-and-doubles every converted amount.+ if (+ override.currencyCode === "EUR" &&+ !(override.rate > 0.5 && override.rate < 1)+ ) {+ fail(+ `${where}: rate ${override.rate} is not EUR per 1 USD (expected ~0.9 — is it inverted?)`+ );+ }+ }+ if (+ eurPo?.source === "direct" &&+ eurPo.exchangeRate !== undefined &&+ !(eurPo.exchangeRate > 0.5 && eurPo.exchangeRate < 1)+ ) {+ fail(+ `purchasing EUR order: exchangeRate ${eurPo.exchangeRate} is not EUR per 1 USD (expected ~0.9 — is it inverted?)`+ );+ }+ if (!overrideCodes.has("EUR")) {+ fail("accounting.exchangeRateOverrides: no EUR rate for the FX showcase");+ }++ const seenAssetStatus = new Set<string>();+ for (const asset of a.fixedAssets) {+ const where = `accounting.fixedAssets "${asset.key}"`;+ seenAssetStatus.add(asset.status);+ const base = asset.acquisitionCost * (1 - asset.residualValuePercent / 100);+ if (asset.accumulatedDepreciation > base + 0.005) {+ fail(+ `${where}: accumulatedDepreciation exceeds the depreciable base ${base}`+ );+ }+ if (asset.depreciationCharge !== undefined && asset.status !== "Active") {+ fail(`${where}: only Active assets are in the depreciation run`);+ }+ if ((asset.status === "Disposed") !== (asset.disposal !== undefined)) {+ fail(`${where}: a disposal is required exactly when status is Disposed`);+ }+ if (asset.disposal) {+ const d = asset.disposal;+ if (+ asset.acquisitionOffset === null ||+ d.dateOffset < asset.acquisitionOffset ||+ d.dateOffset > 0 ||+ d.dateOffset < OPEN_PERIOD_MIN_OFFSET+ ) {+ fail(+ `${where}: disposal dateOffset ${d.dateOffset} must fall between acquisition and today`+ );+ }+ if (d.saleProceeds < 0) fail(`${where}: negative sale proceeds`);+ }+ const uop = asset.depreciationMethod === "Units of Production";+ if (uop !== (asset.assetLifetimeUsage !== undefined)) {+ fail(+ `${where}: assetLifetimeUsage is required exactly for Units of Production`+ );+ }+ if (asset.usageLogs && !uop) {+ fail(`${where}: usage logs belong to Units of Production assets`);+ }+ const months = new Set<number>();+ for (const log of asset.usageLogs ?? []) {+ if (log.monthsBack < 1 || months.has(log.monthsBack)) {+ fail(+ `${where}: usage log monthsBack ${log.monthsBack} must be ≥ 1 and unique`+ );+ }+ months.add(log.monthsBack);+ // Month anchor−m starts no earlier than −(30 + 31m).+ if (+ asset.depreciationStartOffset === null ||+ asset.depreciationStartOffset > -(30 + 31 * log.monthsBack)+ ) {+ fail(+ `${where}: usage log ${log.monthsBack} month(s) back predates depreciation start`+ );+ }+ if (log.unitsProduced <= 0) fail(`${where}: non-positive unitsProduced`);+ }+ if (uop && asset.assetLifetimeUsage) {+ // buildDepreciationLines: min(round(base / lifetime × units), remaining),+ // from the log whose periodEnd is the run's (monthsBack 1).+ const runLog = asset.usageLogs?.find((l) => l.monthsBack === 1);+ const expected = runLog+ ? Math.min(+ round(+ (base / asset.assetLifetimeUsage) * runLog.unitsProduced,+ USD_DECIMALS+ ),+ round(base - asset.accumulatedDepreciation, USD_DECIMALS)+ )+ : 0;+ const charge = round(asset.depreciationCharge ?? 0, USD_DECIMALS);+ if (charge !== expected) {+ fail(+ `${where}: depreciationCharge ${asset.depreciationCharge ?? 0} but the app computes ${expected}`+ );+ }+ }+ }+ checkCoverage(fail, { fixedAssetStatus: seenAssetStatus });+}++// Re-derives tier 09's GL with its own builders (helpers/posting-journals.ts).++// defaultReportRange: the current month plus the five before it — never shorter than this.+const SCRAP_REPORT_MIN_OFFSET = -150;++// Invoice statuses whose balance the open-balance RPCs still carry (Paid,+// Voided and fully credited ones net to zero; Draft is not posted).+const OPEN_INVOICE_STATUSES = new Set([+ "Submitted",+ "Open",+ "Overdue",+ "Partially Paid"+]);++function agingBucket(dueDateOffset: number | undefined): string {+ if (dueDateOffset === undefined || dueDateOffset >= 0) return "Current";+ const pastDue = -dueDateOffset;+ if (pastDue <= 30) return "1-30";+ if (pastDue <= 60) return "31-60";+ if (pastDue <= 90) return "61-90";+ return "90+";+}++export function postings(ctx: ValidationCtx): void {+ const { dataset, fail } = ctx;+ const a = dataset.accounting;+ const items = new Map(+ [+ ...dataset.items.buyParts,+ ...dataset.items.materials,+ ...dataset.items.consumables,+ ...dataset.items.tools,+ ...dataset.items.services,+ ...dataset.items.makeParts+ ].map((item) => [item.readableId, item])+ );+ const itemFacts = (readableId: string) => {+ const item = items.get(readableId);+ return {+ replenishmentSystem: item?.replenishment ?? "Buy",+ itemTrackingType: item?.trackingType ?? "Inventory",+ standardCost: item?.standardCost ?? 0+ };+ };+ const check = (where: string, build: () => PostingJournal) => {+ let journal: PostingJournal;+ try {+ journal = build();+ } catch (error) {+ fail(`${where}: ${(error as Error).message}`);+ return;+ }+ if (!isBalanced(journal)) {+ fail(+ `${where}: generated journal does not balance (net ${postingImbalance(journal)})`+ );+ }+ };+ const openPeriod = (where: string, offset: number) => {+ if (offset > 0 || offset < OPEN_PERIOD_MIN_OFFSET) {+ fail(+ `${where}: posting offset ${offset} outside [${OPEN_PERIOD_MIN_OFFSET}, 0] — its journal needs an Open period`+ );+ }+ };++ // Stocked items carry a unit cost (valuation, COGS fallback).+ for (const [readableId, item] of items) {+ if ((item.trackingType ?? "Inventory") === "Non-Inventory") continue;+ if (!((item.standardCost ?? 0) > 0)) {+ fail(+ `items "${readableId}": a stocked item needs standardCost > 0 (itemCost.unitCost)`+ );+ }+ }++ const openByCustomer = new Set<string>();+ const seenBuckets = new Set<string>();+ for (const opp of [+ ...dataset.sales.opportunities,+ ...dataset.sales.releasedOrders+ ]) {+ const invoice = opp.invoice;+ if (invoice && invoice.status !== "Draft") {+ const where = `sales invoice "${invoice.ref}"`;+ openPeriod(where, invoice.dateIssuedOffset);+ const journal = () =>+ salesInvoiceJournal({+ invoiceReadableId: invoice.ref,+ documentId: invoice.ref,+ lines: invoice.lines.map((line) => ({+ quantity: line.quantity,+ unitPrice: line.unitPrice,+ salesOrderLineId: line.item+ }))+ });+ check(where, journal);+ if (invoice.status === "Voided") {+ check(`${where} void`, () => voidJournal(journal(), invoice.ref));+ }+ if (OPEN_INVOICE_STATUSES.has(invoice.status)) {+ openByCustomer.add(opp.customer);+ seenBuckets.add(agingBucket(invoice.dueDateOffset));+ }+ }+ const shipment = opp.shipment;+ if (shipment?.status === "Posted" && shipment.postedOffset !== undefined) {+ const where = `shipment "${shipment.ref}"`;+ openPeriod(where, shipment.postedOffset);+ check(where, () =>+ shipmentJournal({+ shipmentReadableId: shipment.ref,+ lines: shipment.lines+ .filter(+ (line) =>+ line.shippedQuantity > 0 &&+ itemFacts(line.item).itemTrackingType !== "Non-Inventory"+ )+ .map((line) => {+ const facts = itemFacts(line.item);+ return {+ quantity: line.shippedQuantity,+ cost: line.shippedQuantity * facts.standardCost,+ shipmentLineId: line.item,+ replenishmentSystem: facts.replenishmentSystem,+ itemTrackingType: facts.itemTrackingType+ };+ })+ })+ );+ }+ }+ checkCoverage(fail, { arAgingBucket: seenBuckets });++ const scrapOffsets = dataset.inventory.onHandTracked.flatMap((tracked) =>+ tracked.entities.flatMap((entity) =>+ entity.scrap ? [entity.scrap.dateOffset] : []+ )+ );+ if (!scrapOffsets.some((offset) => offset >= SCRAP_REPORT_MIN_OFFSET)) {+ fail(+ `inventory.onHandTracked: no scrapped lot in the last ${-SCRAP_REPORT_MIN_OFFSET} days (Reports › Scrap opens on the trailing six months)`+ );+ }+ for (const tracked of dataset.inventory.onHandTracked) {+ for (const entity of tracked.entities) {+ if (!entity.scrap) continue;+ const where = `scrap of "${entity.readableId}"`;+ openPeriod(where, entity.scrap.dateOffset);+ const facts = itemFacts(tracked.item);+ check(where, () =>+ scrapJournal({+ description: `Scrap — ${entity.scrap!.comment}`,+ quantity: entity.quantity,+ cost: entity.quantity * facts.standardCost,+ replenishmentSystem: facts.replenishmentSystem,+ itemTrackingType: facts.itemTrackingType+ })+ );+ }+ }++ const openBySupplier = new Set<string>();+ for (const po of dataset.purchasing.purchaseOrders) {+ if (po.source !== "direct") continue;+ const receipt = po.receipt;+ const postedReceipt =+ receipt?.status === "Posted" && receipt.postedOffset !== undefined+ ? { ...receipt, postedOffset: receipt.postedOffset }+ : null;+ if (postedReceipt) {+ const where = `receipt "${postedReceipt.ref}"`;+ openPeriod(where, postedReceipt.postedOffset);+ check(where, () =>+ receiptJournal({+ receiptReadableId: postedReceipt.ref,+ lines: postedReceipt.lines+ .filter((line) => line.receivedQuantity > 0)+ .map((line) => ({+ quantity: line.receivedQuantity,+ cost: line.receivedQuantity * line.unitPrice,+ purchaseOrderLineId: line.item,+ ...itemFacts(line.item)+ }))+ })+ );+ }+ const invoice = po.invoice;+ if (!invoice || invoice.status === "Draft") continue;+ const where = `purchase invoice "${invoice.ref}"`;+ openPeriod(where, invoice.dateIssuedOffset);+ if (invoice.currencyCode !== "USD") {+ fail(+ `${where}: a posted purchase invoice must be base currency (USD) — its journal is base-only`+ );+ }+ const journal = () =>+ purchaseInvoiceJournal({+ invoiceReadableId: invoice.ref,+ lines: invoice.lines.map((line) => {+ const received =+ postedReceipt &&+ postedReceipt.postedOffset <= invoice.dateIssuedOffset+ ? postedReceipt.lines.find((r) => r.item === line.item)+ : undefined;+ return {+ quantity: line.quantity,+ unitCost: line.supplierUnitPrice,+ purchaseOrderLineId: line.item,+ receivedQuantity: received?.receivedQuantity ?? 0,+ receiptUnitCost: received?.unitPrice ?? null+ };+ })+ });+ check(where, journal);+ if (invoice.status === "Voided") {+ check(`${where} void`, () => voidJournal(journal(), invoice.ref));+ }+ if (OPEN_INVOICE_STATUSES.has(invoice.status))+ openBySupplier.add(po.supplier);+ }++ for (const memo of a.memos) {+ check(`accounting.memos "${memo.key}"`, () =>+ memoJournal({+ memoReadableId: memo.key,+ documentId: memo.key,+ direction: memo.direction,+ isAR: memo.direction === "Credit",+ amount: memo.amount,+ // salesDiscountAccount / supplierPaymentDiscountAccount+ reasonAccountClass: memo.direction === "Credit" ? "Revenue" : "Expense"+ })+ );+ }+ for (const rma of dataset.sales.salesReturns) {+ const credit = rma.credit;+ if (credit?.status !== "Posted") continue;+ const where = `sales.salesReturns "${rma.key}" credit`;+ openPeriod(where, credit.dateOffset);+ const amount = credit.lines.reduce(+ (sum, line) =>+ sum + line.quantity * (rma.lines[line.line - 1]?.unitPrice ?? 0),+ 0+ );+ check(where, () =>+ memoJournal({+ memoReadableId: rma.key,+ documentId: rma.key,+ direction: "Credit",+ isAR: true,+ amount,+ // salesReturnsAccount+ reasonAccountClass: "Revenue"+ })+ );+ }++ const seenDraftTypes = new Set<string>();+ for (const payment of a.payments) {+ const where = `accounting.payments "${payment.key}"`;+ const sales = payment.type === "Receipt";+ if (payment.status === "Draft") {+ seenDraftTypes.add(payment.type);+ const party = sales ? payment.customer : payment.supplier;+ if (payment.applies.length > 0 || payment.credits?.length) {+ fail(`${where}: a Draft payment is unapplied (no applies, no credits)`);+ }+ if (!(payment.amount > 0))+ fail(`${where}: a Draft payment needs an amount`);+ if (+ payment.dateOffset > 0 ||+ payment.dateOffset < OPEN_PERIOD_MIN_OFFSET+ ) {+ fail(+ `${where}: dateOffset ${payment.dateOffset} outside [${OPEN_PERIOD_MIN_OFFSET}, 0]`+ );+ }+ if (!party || !(sales ? openByCustomer : openBySupplier).has(party)) {+ fail(+ `${where}: "${party}" has no open posted ${sales ? "sales" : "purchase"} invoice for the apply table to list`+ );+ }+ continue;+ }+ check(where, () =>+ paymentJournal({+ paymentReadableId: payment.key,+ documentId: payment.key,+ type: payment.type,+ amount: payment.amount,+ applies: payment.applies.map((apply) => ({+ targetId: apply.invoiceKey,+ amount: apply.amount+ }))+ })+ );+ }+ checkCoverage(fail, { draftPaymentType: seenDraftTypes });++ // A unique index allows exactly one Posted opening balance.+ const openingBalances = a.journalEntries.filter(+ (entry) => entry.sourceType === "Opening Balance"+ );+ if (openingBalances.length !== 1) {+ fail(+ `accounting.journalEntries: expected exactly one "Opening Balance" entry, found ${openingBalances.length}`+ );+ }+ for (const entry of openingBalances) {+ if (entry.status !== "Posted") {+ fail(+ `accounting.journalEntries "${entry.ref}": an Opening Balance entry is Posted`+ );+ }+ }++ for (const [side, address] of Object.entries(a.billingAddresses)) {+ const where = `accounting.billingAddresses.${side}`;+ if (!address.addressLine1 || !address.city || !address.postalCode) {+ fail(`${where}: street, city and postal code are required`);+ }+ if (!/^[A-Z]{2}$/.test(address.countryCode)) {+ fail(+ `${where}: countryCode "${address.countryCode}" is not ISO-3166 alpha-2`+ );+ }+ if (!address.email.endsWith(".example")) {+ fail(+ `${where}: email "${address.email}" must use a reserved .example domain`+ );+ }+ }+}++const MIN_TIMECARDS = 5;++export function workforce(ctx: ValidationCtx): void {+ const { dataset, fail } = ctx;+ const ops = dataset.ops;+ const trainingNames = new Set<string>();+ const trainingStatuses = new Set<string>();+ let fullyCovered = false;+ let completedAssignments = 0;+ let pendingAssignments = 0;+ for (const training of ops.trainings) {+ const where = `ops.trainings "${training.name}"`;+ if (trainingNames.has(training.name)) fail(`${where}: duplicate name`);+ trainingNames.add(training.name);+ trainingStatuses.add(training.status);+ if (training.questions.length === 0) fail(`${where}: no questions`);++ const types = new Set<string>();+ training.questions.forEach((q, index) => {+ const qWhere = `${where} question ${index + 1}`;+ types.add(q.type);+ switch (q.type) {+ case "MultipleChoice":+ if (!q.options.includes(q.correct)) {+ fail(`${qWhere}: correct answer "${q.correct}" is not an option`);+ }+ break;+ case "MultipleAnswers":+ if (q.correct.length === 0) fail(`${qWhere}: no correct answers`);+ for (const answer of q.correct) {+ if (!q.options.includes(answer)) {+ fail(`${qWhere}: correct answer "${answer}" is not an option`);+ }+ }+ break;+ case "MatchingPairs":+ if (q.pairs.length < 2) fail(`${qWhere}: needs at least 2 pairs`);+ break;+ case "Numerical":+ if (q.tolerance !== undefined && q.tolerance < 0) {+ fail(`${qWhere}: tolerance must not be negative`);+ }+ break;+ case "TrueFalse":+ break;+ }+ if (+ (q.type === "MultipleChoice" || q.type === "MultipleAnswers") &&+ new Set(q.options).size !== q.options.length+ ) {+ fail(`${qWhere}: duplicate options`);+ }+ });+ if (+ training.status === "Active" &&+ TRAINING_QUESTION_TYPES.every((t) => types.has(t))+ ) {+ fullyCovered = true;+ }++ if (training.assignment) {+ if (training.status !== "Active") {+ fail(+ `${where}: only Active trainings are assigned (the status RPC ignores the rest)`+ );+ }+ const { completedOffset } = training.assignment;+ if (completedOffset === undefined) {+ pendingAssignments++;+ } else {+ completedAssignments++;+ if (training.frequency !== "Once") {+ fail(+ `${where}: a completion needs a "Once" training — a recurring one only counts in the current period`+ );+ }+ if (completedOffset >= 0) {+ fail(`${where}: completedOffset must be in the past`);+ }+ }+ }+ }+ checkCoverage(fail, { trainingStatus: trainingStatuses });+ if (!fullyCovered) {+ fail(+ `ops matrix: no Active training covers every trainingQuestionType (${TRAINING_QUESTION_TYPES.join(", ")})`+ );+ }+ if (completedAssignments === 0 || pendingAssignments === 0) {+ fail(+ "ops matrix: training assignments must include at least one Completed and one Pending"+ );+ }++ if (ops.timecards.length < MIN_TIMECARDS) {+ fail(+ `ops.timecards: ${ops.timecards.length} entries — every dataset needs at least ${MIN_TIMECARDS}`+ );+ }+ const spans: { where: string; start: number; end: number }[] = [];+ ops.timecards.forEach((card, index) => {+ const where = `ops.timecards[${index}]`;+ if (card.dayOffset > -1 || card.dayOffset < -7) {+ fail(+ `${where}: dayOffset ${card.dayOffset} is outside the past week (-7…-1)`+ );+ }+ const clockIn = secondsOfDay(card.clockIn);+ const clockOut = secondsOfDay(card.clockOut);+ if (clockIn === null || clockOut === null) {+ fail(`${where}: clockIn/clockOut must be UTC "HH:MM:SS"`);+ return;+ }+ if (clockOut <= clockIn) fail(`${where}: clockOut must be after clockIn`);+ const day = card.dayOffset * 86_400;+ spans.push({ where, start: day + clockIn, end: day + clockOut });+ });+ spans.sort((a, b) => a.start - b.start);+ for (let i = 1; i < spans.length; i++) {+ if (spans[i]!.start < spans[i - 1]!.end) {+ fail(`${spans[i]!.where}: overlaps ${spans[i - 1]!.where}`);+ }+ }++ if (ops.suggestions.length < 2) {+ fail("ops.suggestions: every dataset needs at least 2");+ }+ ops.suggestions.forEach((suggestion, index) => {+ const where = `ops.suggestions[${index}]`;+ if (suggestion.suggestion.trim() === "") fail(`${where}: empty text`);+ if (!suggestion.path.startsWith("/x/")) {+ fail(`${where}: path "${suggestion.path}" is not an ERP page (/x/…)`);+ }+ });+ if (ops.notes.length < 2) fail("ops.notes: every dataset needs at least 2");+ ops.notes.forEach((note, index) => {+ if (note.text.trim() === "") fail(`ops.notes[${index}]: empty text`);+ });+}++export function workflowRuns(ctx: ValidationCtx): void {+ const { dataset, ix, fail } = ctx;+ // The definitions are a factory over ids the seed mints; placeholders are+ // enough to read their names, node ids and trigger events.+ const published = new Map(+ dataset.workflows+ .build({ ownerId: "validate:owner", issueTypeId: "validate:issueType" })+ .filter((workflow) => workflow.published)+ .map((workflow) => [workflow.name, workflow] as const)+ );++ const runStatuses = new Set<string>();+ dataset.workflows.runs.forEach((run, index) => {+ const where = `workflows.runs[${index}] (${run.status})`;+ runStatuses.add(run.status);+ checkInstant(fail, where, run.at);+ if (run.at.offset >= 0) fail(`${where}: at must be in the past`);++ const workflow = published.get(run.workflow);+ if (!workflow) {+ fail(`${where}: "${run.workflow}" is not a published seed workflow`);+ return;+ }+ const trigger = workflow.nodes.find((node) => node.type === "trigger");+ const event = (trigger?.data.events as string[] | undefined)?.[0];+ if (!trigger || !event) {+ fail(`${where}: workflow "${run.workflow}" has no trigger event`);+ }+ if (event?.startsWith("salesOrder.")) {+ const orderDate = ix.orderDateByRef.get(run.triggerRef);+ if (orderDate === undefined) {+ fail(`${where}: triggerRef "${run.triggerRef}" is not a sales order`);+ } else if (run.at.offset < orderDate) {+ fail(+ `${where}: fired at offset ${run.at.offset}, before its order was placed (${orderDate})`+ );+ }+ } else if (+ !ix.documentRefs.has(run.triggerRef, ix.documentRefs.seenBy.workflowRuns)+ ) {+ fail(`${where}: unknown triggerRef "${run.triggerRef}"`);+ }++ const actionNodeIds = new Set(+ workflow.nodes+ .filter((node) => node.type !== "trigger")+ .map((node) => node.id)+ );+ for (const step of run.steps) {+ if (!actionNodeIds.has(step.nodeId)) {+ fail(+ `${where}: step nodeId "${step.nodeId}" is not an action node of "${run.workflow}"`+ );+ }+ if ((step.status === "Failed") !== (step.error !== undefined)) {+ fail(+ `${where} step "${step.nodeId}": an error is required exactly when the step Failed`+ );+ }+ }+ const skipped = run.status === "Skipped";+ if (skipped !== (run.steps.length === 0)) {+ fail(+ `${where}: a Skipped run settles at load with no steps; every other run walks at least one`+ );+ }+ if (skipped !== (run.statusReason !== undefined)) {+ fail(+ `${where}: statusReason is required exactly when the run is Skipped`+ );+ }+ const anyFailed = run.steps.some((step) => step.status === "Failed");+ if (run.status === "Failed" && !anyFailed) {+ fail(`${where}: a Failed run needs a Failed step`);+ }+ if (run.status === "Succeeded" && anyFailed) {+ fail(`${where}: a Succeeded run cannot contain a Failed step`);+ }+ });+ checkCoverage(fail, { workflowRunStatus: runStatuses });+}++const MIN_MAINTENANCE_SCHEDULES = 3;+/** Completed dispatches the maintenance KPIs' previous-period window picks up. */+const BACKDATED_COMPLETION_WINDOW = { min: -55, max: -35 } as const;+const MIN_BACKDATED_COMPLETED_DISPATCHES = 2;+/** A Down dispatch's planned end bounds the scheduler's outage (open-ended = to the horizon). */+const MAX_DOWN_OUTAGE_DAYS = 2;+const MIN_REPLACEMENT_PARTS = 3;+const OPEN_DISPATCH_STATUSES = new Set(["Open", "Assigned", "In Progress"]);++/** Malformed times sort as midnight. */+function instantOrdinal(instant: InstantSpec): number {+ return instant.offset * 86_400 + (secondsOfDay(instant.time) ?? 0);+}++export function sparePartDrains(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { isTracked } = ix;+ // A Completed dispatch issues its spare parts from a shelf (inventory-ledger.ts).+ for (const dispatch of dataset.ops.maintenanceDispatches) {+ for (const part of dispatch.spareParts ?? []) {+ const where = `ops.maintenanceDispatches "${dispatch.key}" spare part "${part.item}"`;+ need("item", where, part.item);+ need("shelf", where, part.shelf);+ if (isTracked(part.item)) {+ fail(+ `${where}: tracked items need per-entity consumption the seed does not model`+ );+ }+ if (part.quantity <= 0) fail(`${where}: quantity must be positive`);+ }+ }+}++export function maintenance(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { jobByKey, standardCost } = ix;+ const { rootOpsOf } = ix.bom;+ const activeWorkCenters = ix.floor.active;+ const ops = dataset.ops;+ // Closed production events per day, by work center — what the MTBF KPI+ // divides by that day's reactive failures.+ const eventWorkCentersByDay = new Map<number, Set<string>>();+ const eventsJobSpec = jobByKey.get(dataset.production.eventsJobKey);+ if (eventsJobSpec) {+ rootOpsOf(eventsJobSpec.item)+ .slice(0, 2)+ .forEach((op, index) => {+ const events =+ dataset.production.shifts[index] ??+ dataset.production.shifts[0] ??+ [];+ for (const event of events) {+ if (!op.workCenter) continue;+ const day = eventWorkCentersByDay.get(event.startOffset) ?? new Set();+ day.add(op.workCenter);+ eventWorkCentersByDay.set(event.startOffset, day);+ }+ });+ }+ const hqWorkCenter = dataset.foundation.hqWorkCenter.name;++ if (ops.maintenanceSchedules.length < MIN_MAINTENANCE_SCHEDULES) {+ fail(+ `ops.maintenanceSchedules: ${ops.maintenanceSchedules.length} schedules — every dataset needs at least ${MIN_MAINTENANCE_SCHEDULES}`+ );+ }+ const scheduleWorkCenter = new Map<string, string>();+ const frequencies = new Set<string>();+ for (const schedule of ops.maintenanceSchedules) {+ const where = `ops.maintenanceSchedules "${schedule.key}"`;+ if (scheduleWorkCenter.has(schedule.key)) {+ fail(`${where}: duplicate schedule key`);+ }+ scheduleWorkCenter.set(schedule.key, schedule.workCenter);+ frequencies.add(schedule.frequency);+ need("maintainedWorkCenter", where, schedule.workCenter);+ if (schedule.estimatedDuration <= 0) {+ fail(`${where}: estimatedDuration must be positive`);+ }+ if (schedule.nextDueOffset < 0) {+ fail(`${where}: nextDueOffset ${schedule.nextDueOffset} is in the past`);+ }+ if (schedule.weekends !== undefined && schedule.frequency !== "Daily") {+ fail(`${where}: weekends applies to Daily schedules only`);+ }+ for (const part of schedule.spareParts ?? []) {+ need("item", `${where} spare part`, part.item);+ if (part.quantity <= 0) {+ fail(`${where} spare part "${part.item}": quantity must be positive`);+ }+ }+ }+ if (ops.maintenanceSchedules.length > 0 && frequencies.size < 3) {+ fail(+ `ops.maintenanceSchedules: only ${frequencies.size} distinct frequencies — spread them over at least 3`+ );+ }++ const seenDispatch = {+ status: new Set<string>(),+ severity: new Set<string>(),+ source: new Set<string>(),+ oeeImpact: new Set<string>()+ };+ const dispatchKeys = new Set<string>();+ for (const dispatch of ops.maintenanceDispatches) {+ const where = `ops.maintenanceDispatches "${dispatch.key}"`;+ if (dispatchKeys.has(dispatch.key))+ fail(`${where}: duplicate dispatch key`);+ dispatchKeys.add(dispatch.key);+ seenDispatch.status.add(dispatch.status);+ seenDispatch.severity.add(dispatch.severity);+ seenDispatch.source.add(dispatch.source);+ seenDispatch.oeeImpact.add(dispatch.oeeImpact);++ need("maintainedWorkCenter", where, dispatch.workCenter);+ if (+ (dispatch.source === "Scheduled") !==+ (dispatch.schedule !== undefined)+ ) {+ fail(`${where}: a schedule is required exactly when source is Scheduled`);+ }+ if (dispatch.schedule !== undefined) {+ const scheduleWc = scheduleWorkCenter.get(dispatch.schedule);+ if (scheduleWc === undefined) {+ fail(`${where}: unknown maintenance schedule "${dispatch.schedule}"`);+ } else if (scheduleWc !== dispatch.workCenter) {+ fail(+ `${where}: schedule "${dispatch.schedule}" is on "${scheduleWc}", not "${dispatch.workCenter}"`+ );+ }+ }+ if (+ (dispatch.source === "Non-Conformance") !==+ (dispatch.nonConformance !== undefined)+ ) {+ fail(+ `${where}: a nonConformance is required exactly when source is Non-Conformance`+ );+ }+ if (+ dispatch.nonConformance !== undefined &&+ !ix.ncrRefs.has(dispatch.nonConformance)+ ) {+ fail(`${where}: unknown NCR ref "${dispatch.nonConformance}"`);+ }+ for (const mode of [+ dispatch.suspectedFailureMode,+ dispatch.actualFailureMode+ ]) {+ if (mode !== undefined && !FAILURE_MODE_NAMES.has(mode)) {+ fail(`${where}: "${mode}" is not a bootstrap maintenanceFailureMode`);+ }+ }+ const started =+ dispatch.status === "In Progress" || dispatch.status === "Completed";+ const completed = dispatch.status === "Completed";+ if (started !== (dispatch.actualStart !== undefined)) {+ fail(+ `${where}: actualStart is required exactly when status is In Progress or Completed`+ );+ }+ if (completed !== (dispatch.actualEnd !== undefined)) {+ fail(`${where}: actualEnd is required exactly when status is Completed`);+ }+ if (!completed && dispatch.actualFailureMode !== undefined) {+ fail(+ `${where}: actualFailureMode is recorded on Completed dispatches only`+ );+ }+ if (!completed && (dispatch.spareParts ?? []).length > 0) {+ fail(`${where}: spare parts are issued on Completed dispatches only`);+ }++ for (const [label, instant] of [+ ["created", dispatch.created],+ ["plannedStart", dispatch.plannedStart],+ ["plannedEnd", dispatch.plannedEnd],+ ["actualStart", dispatch.actualStart],+ ["actualEnd", dispatch.actualEnd]+ ] as const) {+ if (instant) checkInstant(fail, `${where} ${label}`, instant);+ }+ if (dispatch.created.offset >= 0) {+ fail(`${where}: created must be in the past`);+ }+ if (+ instantOrdinal(dispatch.plannedEnd) <=+ instantOrdinal(dispatch.plannedStart)+ ) {+ fail(`${where}: plannedEnd must be after plannedStart`);+ }+ if (dispatch.actualStart) {+ if (dispatch.actualStart.offset >= 0) {+ fail(`${where}: actualStart must be in the past`);+ }+ if (+ instantOrdinal(dispatch.actualStart) < instantOrdinal(dispatch.created)+ ) {+ fail(`${where}: actualStart before the request was created`);+ }+ if (+ dispatch.actualEnd &&+ instantOrdinal(dispatch.actualEnd) <=+ instantOrdinal(dispatch.actualStart)+ ) {+ fail(`${where}: actualEnd must be after actualStart`);+ }+ }+ }+ const dispatches = ops.maintenanceDispatches;+ const scheduleByKey = new Map(+ ops.maintenanceSchedules.map((schedule) => [schedule.key, schedule])+ );+ for (const dispatch of dispatches) {+ const where = `ops.maintenanceDispatches "${dispatch.key}"`;+ for (const part of dispatch.spareParts ?? []) {+ if ((standardCost.get(part.item) ?? 0) <= 0) {+ fail(+ `${where} spare part "${part.item}": no standardCost, so the dispatch item's unitCost (spare-part cost KPI) is 0`+ );+ }+ }+ if (+ dispatch.workCenter === hqWorkCenter &&+ (dispatch.spareParts ?? []).length > 0+ ) {+ fail(`${where}: spare parts are drawn from plant shelves, not at HQ`);+ }+ if (dispatch.oeeImpact === "Down" && dispatch.status === "In Progress") {+ if (!dispatch.takesWorkCenterOffline) {+ fail(+ `${where}: an In Progress Down dispatch takes the work center offline`+ );+ }+ if (+ dispatch.plannedEnd.offset < 0 ||+ dispatch.plannedEnd.offset > MAX_DOWN_OUTAGE_DAYS+ ) {+ fail(+ `${where}: plannedEnd offset ${dispatch.plannedEnd.offset} must be 0…${MAX_DOWN_OUTAGE_DAYS} — it bounds the scheduler's outage`+ );+ }+ if (activeWorkCenters.has(dispatch.workCenter)) {+ fail(+ `${where}: "${dispatch.workCenter}" is down but has an operation In Progress`+ );+ }+ }+ }+ if (+ !dispatches.some(+ (d) =>+ d.status === "In Progress" &&+ d.oeeImpact === "Down" &&+ d.takesWorkCenterOffline === true+ )+ ) {+ fail(+ "ops.maintenanceDispatches: no In Progress dispatch with its work center Down (blocked display)"+ );+ }+ if (+ !dispatches.some(+ (d) =>+ d.source === "Reactive" &&+ eventWorkCentersByDay.get(d.created.offset)?.has(d.workCenter) === true+ )+ ) {+ fail(+ "ops.maintenanceDispatches: no Reactive dispatch created on a production-event day at that work center (MTBF KPI)"+ );+ }+ const backdated = dispatches.filter(+ (d) =>+ d.status === "Completed" &&+ d.actualEnd !== undefined &&+ d.actualEnd.offset >= BACKDATED_COMPLETION_WINDOW.min &&+ d.actualEnd.offset <= BACKDATED_COMPLETION_WINDOW.max+ );+ if (backdated.length < MIN_BACKDATED_COMPLETED_DISPATCHES) {+ fail(+ `ops.maintenanceDispatches: ${backdated.length} Completed dispatches finished ${BACKDATED_COMPLETION_WINDOW.min}…${BACKDATED_COMPLETION_WINDOW.max}, need ≥ ${MIN_BACKDATED_COMPLETED_DISPATCHES} (KPI trends)`+ );+ }+ // Due today from a Daily schedule that runs weekends too, so it holds on+ // whatever weekday the anchor falls; the generator has moved nextDue past it.+ const dueToday = dispatches.find(+ (d) =>+ d.source === "Scheduled" &&+ (d.status === "Open" || d.status === "Assigned") &&+ d.plannedStart.offset === 0+ );+ if (!dueToday) {+ fail(+ "ops.maintenanceDispatches: no open Scheduled dispatch planned for today (Open Scheduled tile, MES Today tab)"+ );+ } else {+ const schedule = scheduleByKey.get(dueToday.schedule ?? "");+ if (+ schedule &&+ (schedule.frequency !== "Daily" ||+ schedule.weekends === false ||+ schedule.nextDueOffset !== 1)+ ) {+ fail(+ `ops.maintenanceDispatches "${dueToday.key}": due today from "${schedule.key}", which must be Daily with weekends and next due tomorrow`+ );+ }+ }+ if (!dispatches.some((d) => d.workCenter === hqWorkCenter)) {+ fail(+ `ops.maintenanceDispatches: none at the HQ work center "${hqWorkCenter}" (the ERP list opens on HQ)`+ );+ }+ if (!ops.maintenanceSchedules.some((s) => s.workCenter === hqWorkCenter)) {+ fail(+ `ops.maintenanceSchedules: none at the HQ work center "${hqWorkCenter}" (the ERP list opens on HQ)`+ );+ }++ const partKeys = new Set<string>();+ for (const part of ops.replacementParts) {+ const where = `ops.replacementParts "${part.workCenter}" / "${part.item}"`;+ const key = `${part.workCenter}|${part.item}`;+ if (partKeys.has(key)) fail(`${where}: duplicate`);+ partKeys.add(key);+ need("maintainedWorkCenter", where, part.workCenter);+ need("item", where, part.item);+ if (!Number.isInteger(part.quantity) || part.quantity <= 0) {+ fail(`${where}: quantity ${part.quantity} must be a positive integer`);+ }+ }+ const partWorkCenters = new Set(+ ops.replacementParts.map((part) => part.workCenter)+ );+ if (+ ops.replacementParts.length < MIN_REPLACEMENT_PARTS ||+ partWorkCenters.size < 2+ ) {+ fail(+ `ops.replacementParts: ${ops.replacementParts.length} parts on ${partWorkCenters.size} work centers, need ≥ ${MIN_REPLACEMENT_PARTS} on ≥ 2`+ );+ }+ if (+ !dispatches.some(+ (d) =>+ OPEN_DISPATCH_STATUSES.has(d.status) &&+ partWorkCenters.has(d.workCenter)+ )+ ) {+ fail(+ "ops.replacementParts: no open dispatch's work center lists replacement parts (MES dispatch page)"+ );+ }++ checkCoverage(fail, {+ dispatchStatus: seenDispatch.status,+ dispatchSeverity: seenDispatch.severity,+ dispatchSource: seenDispatch.source,+ dispatchOeeImpact: seenDispatch.oeeImpact+ });+}++/** Excludes today: a today row pre-filters the MES schedule to one work center. */+const PEOPLE_ASSIGNMENT_WINDOW = { min: -2, max: 4 } as const;+const MIN_PEOPLE_ASSIGNMENT_DAYS = 5;+const MIN_PEOPLE_ASSIGNMENT_WORK_CENTERS = 3;+/** "Next week": an absence the board shows once the user pages forward. */+const PEOPLE_ABSENCE_WINDOW = { min: 7, max: 13 } as const;++export function peopleAndTime(ctx: ValidationCtx): void {+ const { dataset, fail, need } = ctx;+ const ops = dataset.ops;++ const clockIn = secondsOfDay(ops.openTimecard.clockIn);+ if (clockIn === null) {+ fail(+ `ops.openTimecard: clockIn "${ops.openTimecard.clockIn}" is not a UTC "HH:MM:SS"`+ );+ } else {+ const runningStarts = [+ OPEN_EVENT_TIME,+ dataset.production.batch.running.startTimeOfDay+ ];+ for (const job of dataset.production.jobs) {+ for (const override of job.operationOverrides ?? []) {+ if (override.running) {+ runningStarts.push(override.running.startTimeOfDay);+ }+ }+ }+ const earliest = Math.min(+ ...runningStarts.map((time) => secondsOfDay(time) ?? 0)+ );+ if (clockIn > earliest) {+ fail(+ `ops.openTimecard: clocked in at ${ops.openTimecard.clockIn}, after a production timer already running today`+ );+ }+ }++ const assignmentDays = new Set<number>();+ const assignedWorkCenters = new Set<string>();+ const seenAssignments = new Set<string>();+ ops.peopleAssignments.forEach((spec, index) => {+ const where = `ops.peopleAssignments[${index}]`;+ need("workCenter", where, spec.workCenter);+ need("shift", where, spec.shift);+ if (spec.dayOffset === 0) {+ fail(+ `${where}: an assignment today pre-filters the MES schedule to one work center`+ );+ } else if (+ spec.dayOffset < PEOPLE_ASSIGNMENT_WINDOW.min ||+ spec.dayOffset > PEOPLE_ASSIGNMENT_WINDOW.max+ ) {+ fail(+ `${where}: dayOffset ${spec.dayOffset} is outside the current-week window (${PEOPLE_ASSIGNMENT_WINDOW.min}…${PEOPLE_ASSIGNMENT_WINDOW.max})`+ );+ }+ // peopleAssignment is UNIQUE (companyId, employeeId, date, shiftId).+ const key = `${spec.dayOffset}|${spec.shift}`;+ if (seenAssignments.has(key)) {+ fail(`${where}: a second assignment on the same day and shift`);+ }+ seenAssignments.add(key);+ if (spec.overtimeHours !== undefined && !(spec.overtimeHours >= 0)) {+ fail(`${where}: overtimeHours must be ≥ 0`);+ }+ assignmentDays.add(spec.dayOffset);+ assignedWorkCenters.add(spec.workCenter);+ });+ if (assignmentDays.size < MIN_PEOPLE_ASSIGNMENT_DAYS) {+ fail(+ `ops.peopleAssignments: ${assignmentDays.size} days — every dataset needs at least ${MIN_PEOPLE_ASSIGNMENT_DAYS}`+ );+ }+ if (assignedWorkCenters.size < MIN_PEOPLE_ASSIGNMENT_WORK_CENTERS) {+ fail(+ `ops.peopleAssignments: ${assignedWorkCenters.size} work centers — every dataset needs at least ${MIN_PEOPLE_ASSIGNMENT_WORK_CENTERS}`+ );+ }++ if (ops.peopleAbsences.length === 0) {+ fail("ops.peopleAbsences: must not be empty");+ }+ const seenAbsences = new Set<string>();+ ops.peopleAbsences.forEach((spec, index) => {+ const where = `ops.peopleAbsences[${index}]`;+ if (spec.shift !== undefined) need("shift", where, spec.shift);+ if (+ spec.dayOffset < PEOPLE_ABSENCE_WINDOW.min ||+ spec.dayOffset > PEOPLE_ABSENCE_WINDOW.max+ ) {+ fail(+ `${where}: dayOffset ${spec.dayOffset} is outside next week (${PEOPLE_ABSENCE_WINDOW.min}…${PEOPLE_ABSENCE_WINDOW.max})`+ );+ }+ if (assignmentDays.has(spec.dayOffset)) {+ fail(`${where}: absent on a day the user is assigned to a station`);+ }+ const key = `${spec.dayOffset}|${spec.shift ?? ""}`;+ if (seenAbsences.has(key)) {+ fail(`${where}: a second absence on the same day and shift`);+ }+ seenAbsences.add(key);+ if (!spec.note.trim()) fail(`${where}: empty note`);+ });+}++/** The cleanup job deletes completed print jobs after 30 days. */+const PRINT_JOB_WINDOW = { min: -20, max: 0 } as const;+const PRINTABLE_JOB_STATUSES = new Set([+ "Ready",+ "In Progress",+ "Paused",+ "Completed",+ "Closed"+]);++function escapeRegExp(text: string): string {+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+}++/** Workflow builders are functions, so they are skipped. */+function collectStrings(value: unknown, into: Set<string>): void {+ if (typeof value === "string") {+ into.add(value);+ } else if (Array.isArray(value)) {+ for (const entry of value) collectStrings(entry, into);+ } else if (value && typeof value === "object") {+ for (const entry of Object.values(value)) collectStrings(entry, into);+ }+}++export function settingsSurfaces(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const { trackingByItem } = ix;+ const ops = dataset.ops;++ const attributeTypes = new Set<string>();+ const categoryNames = new Set<string>();+ ops.userAttributeCategories.forEach((category, index) => {+ const where = `ops.userAttributeCategories[${index}]`;+ if (categoryNames.has(category.name)) {+ fail(`${where}: duplicate category "${category.name}"`);+ }+ categoryNames.add(category.name);+ if (!category.emoji.trim()) fail(`${where}: empty emoji`);+ if (category.attributes.length === 0) fail(`${where}: no attributes`);+ const names = new Set<string>();+ category.attributes.forEach((attribute, attributeIndex) => {+ const at = `${where}.attributes[${attributeIndex}]`;+ if (names.has(attribute.name)) {+ fail(`${at}: duplicate attribute "${attribute.name}"`);+ }+ names.add(attribute.name);+ attributeTypes.add(attribute.dataType);+ if (attribute.dataType === "List") {+ const options = new Set(attribute.listOptions);+ if (+ attribute.listOptions.length === 0 ||+ options.size !== attribute.listOptions.length ||+ attribute.listOptions.some((option) => !option.trim())+ ) {+ fail(`${at}: listOptions must be non-empty, distinct and non-blank`);+ }+ if (!options.has(attribute.value)) {+ fail(+ `${at}: value "${attribute.value}" is not one of its listOptions`+ );+ }+ } else if (attribute.dataType === "Text" && !attribute.value.trim()) {+ fail(`${at}: empty Text value`);+ }+ });+ });+ checkCoverage(fail, { userAttributeType: attributeTypes });++ const fieldKeys = new Set<string>();+ ops.customFields.forEach((field, index) => {+ const where = `ops.customFields[${index}]`;+ const key = `${field.table}|${field.name}`;+ if (fieldKeys.has(key)) {+ fail(`${where}: duplicate field "${field.name}" on "${field.table}"`);+ }+ fieldKeys.add(key);+ const isList = field.dataType === "List";+ if (isList !== (field.listOptions !== undefined)) {+ fail(`${where}: listOptions are required on a List field and only there`);+ } else if (+ isList &&+ (field.listOptions!.length === 0 ||+ field.listOptions!.some((option) => !option.trim()))+ ) {+ fail(`${where}: listOptions must be non-empty and non-blank`);+ }+ });+ checkCoverage(fail, {+ customField: new Set(+ ops.customFields.map((field) => `${field.table}|${field.dataType}`)+ )+ });++ const datasetStrings = new Set<string>();+ collectStrings(dataset, datasetStrings);+ const sequenced = new Set<string>();+ ops.serialSequences.forEach((spec, index) => {+ const where = `ops.serialSequences[${index}]`;+ need("item", where, spec.item);+ if (sequenced.has(spec.item)) {+ fail(`${where}: a second sequence for "${spec.item}"`);+ }+ sequenced.add(spec.item);+ const tracking = trackingByItem.get(spec.item);+ if (tracking !== undefined && tracking !== "Serial") {+ fail(`${where}: "${spec.item}" is ${tracking}-tracked, not Serial`);+ }+ if (!Number.isInteger(spec.size) || spec.size < 1) {+ fail(`${where}: size must be an integer ≥ 1`);+ }+ if (!Number.isInteger(spec.next) || spec.next < 0) {+ fail(`${where}: next must be an integer ≥ 0`);+ }+ const pattern = new RegExp(+ `^${escapeRegExp(spec.prefix)}(\\d{${spec.size}})${escapeRegExp(spec.suffix ?? "")}$`+ );+ for (const text of datasetStrings) {+ const match = pattern.exec(text);+ if (match && Number(match[1]) > spec.next) {+ fail(+ `${where}: next ${spec.next} would re-issue "${text}", already seeded`+ );+ }+ }+ });+ for (const [item, tracking] of trackingByItem) {+ if (tracking === "Serial" && !sequenced.has(item)) {+ fail(`ops.serialSequences: Serial-tracked "${item}" has no sequence`);+ }+ }++ const route = dataset.foundation.printerRoute;+ if (ops.printJobs.length > 0 && (!route || route.format !== "zpl")) {+ fail("ops.printJobs: need a zpl foundation.printerRoute to print against");+ }+ const receipts = new Map(+ dataset.purchasing.purchaseOrders.flatMap((po) =>+ "receipt" in po && po.receipt+ ? [[po.receipt.ref, po.receipt] as const]+ : []+ )+ );+ const jobs = new Map(dataset.production.jobs.map((job) => [job.key, job]));+ const printStatuses = new Set<string>();+ const printOrigins = new Set<string>();+ ops.printJobs.forEach((spec, index) => {+ const where = `ops.printJobs[${index}]`;+ printStatuses.add(spec.status);+ printOrigins.add(spec.origin);+ const { source } = spec;+ if (source.kind === "Receipt") {+ const receipt = receipts.get(source.receipt);+ if (!receipt) {+ fail(`${where}: unknown receipt "${source.receipt}"`);+ } else if (receipt.status !== "Posted") {+ fail(`${where}: receipt "${source.receipt}" is not Posted`);+ } else {+ if (spec.at.offset < (receipt.postedOffset ?? 0)) {+ fail(`${where}: printed before its receipt posted`);+ }+ if (!receipt.lines.some((line) => line.item === spec.item)) {+ fail(`${where}: item "${spec.item}" is not on the receipt`);+ }+ }+ } else if (source.kind === "Job") {+ const job = jobs.get(source.job);+ if (!job) {+ fail(`${where}: unknown job "${source.job}"`);+ } else {+ if (!PRINTABLE_JOB_STATUSES.has(job.status)) {+ fail(`${where}: job "${source.job}" is ${job.status}`);+ }+ if (job.item !== spec.item) {+ fail(`${where}: item "${spec.item}" is not what the job builds`);+ }+ }+ } else {+ need("shelf", where, source.shelf);+ if (spec.item !== undefined) {+ fail(`${where}: a storage-unit label names no item`);+ }+ }+ if (source.kind !== "StorageUnit" && spec.item !== undefined) {+ need("item", where, spec.item);+ }+ if ((spec.status === "failed") !== (spec.error !== undefined)) {+ fail(`${where}: error is required on a failed job and only there`);+ }+ if (spec.status === "queued" ? spec.attempts !== 0 : spec.attempts < 1) {+ fail(`${where}: attempts must be 0 while queued and ≥ 1 once delivered`);+ }+ if (secondsOfDay(spec.at.time) === null) {+ fail(`${where}: time "${spec.at.time}" is not a UTC "HH:MM:SS"`);+ }+ if (+ spec.at.offset < PRINT_JOB_WINDOW.min ||+ spec.at.offset > PRINT_JOB_WINDOW.max+ ) {+ fail(+ `${where}: offset ${spec.at.offset} is outside ${PRINT_JOB_WINDOW.min}…${PRINT_JOB_WINDOW.max} (older completed jobs are cleaned up)`+ );+ }+ // Today's rows must already be in the past at a US plant's morning.+ if (+ spec.at.offset === 0 &&+ (secondsOfDay(spec.at.time) ?? 0) > (secondsOfDay(OPEN_EVENT_TIME) ?? 0)+ ) {+ fail(`${where}: today's print is after ${OPEN_EVENT_TIME} UTC`);+ }+ });+ checkCoverage(fail, {+ printJobStatus: printStatuses,+ printJobOrigin: printOrigins+ });+}++// Sales and storage rules as the rule builder would accept them.++const PRESENCE_OPS = new Set<RuleOperator>(["isSet", "isNotSet"]);+const LIST_OPS = new Set<RuleOperator>(["in", "notIn"]);++function ruleShape(spec: EnforcementRuleSpec): RuleShape {+ return spec.family === "sales" ? "sales" : `storage:${spec.targetType}`;+}++function checkRuleValue(+ where: string,+ kind: RuleValueKind,+ op: RuleOperator,+ value: RuleConditionValue | undefined,+ known: { storageTypes: Set<string>; customerTypes: Set<string> },+ fail: (message: string) => void+): void {+ if (PRESENCE_OPS.has(op)) {+ if (value !== undefined) fail(`${where}: ${op} takes no value`);+ return;+ }+ if (value === undefined) {+ fail(`${where}: ${op} needs a value`);+ return;+ }+ const isList = LIST_OPS.has(op);+ switch (kind) {+ case "number":+ if (typeof value !== "number") fail(`${where}: value must be a number`);+ return;+ case "boolean":+ if (typeof value !== "boolean") fail(`${where}: value must be a boolean`);+ return;+ case "enum":+ case "country": {+ const values = isList ? value : [value];+ if (+ !Array.isArray(values) ||+ values.length === 0 ||+ values.some((v) => typeof v !== "string")+ ) {+ fail(+ `${where}: ${op} needs ${isList ? "a non-empty string list" : "a string"}`+ );+ return;+ }+ if (+ kind === "country" &&+ values.some((v) => !COUNTRY_CODE.test(String(v)))+ ) {+ fail(`${where}: country codes are ISO alpha-2 ("US")`);+ }+ return;+ }+ case "storageType":+ if (+ typeof value !== "object" ||+ Array.isArray(value) ||+ !("storageType" in value)+ ) {+ fail(`${where}: value must be { storageType }`);+ } else if (!known.storageTypes.has(value.storageType)) {+ fail(`${where}: unknown storage type "${value.storageType}"`);+ }+ return;+ case "customerTypes":+ if (+ typeof value !== "object" ||+ Array.isArray(value) ||+ !("customerTypes" in value)+ ) {+ fail(`${where}: value must be { customerTypes }`);+ } else if (value.customerTypes.length === 0) {+ fail(`${where}: customerTypes is empty`);+ } else {+ for (const name of value.customerTypes) {+ if (!known.customerTypes.has(name)) {+ fail(`${where}: unknown customer type "${name}"`);+ }+ }+ }+ return;+ case "location":+ if (+ typeof value !== "object" ||+ Array.isArray(value) ||+ !("location" in value)+ ) {+ fail(`${where}: value must be { location }`);+ }+ return;+ }+}++export function enforcementRules(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need } = ctx;+ const storageTypes = ix.refs.storageType;+ const customerTypes = ix.refs.customerType;++ const shapesSeen = new Set<string>();+ const salesSeverities = new Set<string>();+ const ruleNames = new Set<string>();+ for (const spec of dataset.items.enforcementRules) {+ const shape = ruleShape(spec);+ const where = `items.enforcementRules "${spec.name}"`;+ shapesSeen.add(shape);+ if (spec.family === "sales") salesSeverities.add(spec.severity);+ const nameKey = `${spec.family}:${spec.name}`;+ if (ruleNames.has(nameKey)) {+ fail(`${where}: duplicate name within family "${spec.family}"`);+ }+ ruleNames.add(nameKey);+ if (spec.message.trim() === "") fail(`${where}: empty message`);+ if (spec.surfaces.length === 0) fail(`${where}: no surfaces`);+ if (new Set<string>(spec.surfaces).size !== spec.surfaces.length) {+ fail(`${where}: duplicate surface`);+ }+ if (spec.conditions.length === 0) fail(`${where}: no conditions`);+ for (const [index, condition] of spec.conditions.entries()) {+ const conditionWhere = `${where} condition ${index + 1}`;+ const field = RULE_FIELDS[condition.field];+ if (!field) {+ fail(+ `${conditionWhere}: field "${condition.field}" is not one the seed can author`+ );+ continue;+ }+ if (!field.shapes.includes(shape)) {+ fail(+ `${conditionWhere}: field "${condition.field}" is not available to a ${shape} rule`+ );+ }+ if (!field.ops.includes(condition.op)) {+ fail(+ `${conditionWhere}: operator "${condition.op}" is not allowed on "${condition.field}"`+ );+ }+ checkRuleValue(+ conditionWhere,+ field.value,+ condition.op,+ condition.value,+ { storageTypes, customerTypes },+ fail+ );+ }+ const targets = "workCenters" in spec ? spec.workCenters : spec.items;+ if (targets.length === 0) {+ fail(`${where}: no assignments — the rule applies to nothing`);+ }+ if (new Set(targets).size !== targets.length) {+ fail(`${where}: duplicate assignment`);+ }+ if ("workCenters" in spec) {+ for (const workCenter of spec.workCenters) {+ need("workCenter", where, workCenter);+ }+ } else {+ for (const item of spec.items) need("item", where, item);+ }+ }+ checkCoverage(fail, {+ enforcementRuleShape: shapesSeen,+ salesRuleSeverity: salesSeverities+ });+}++export function planning(ctx: ValidationCtx): void {+ const { dataset, ix, fail, need, needCustomer } = ctx;+ const { makePartIds } = ix;+ for (const id of dataset.planning.buyItemIds) {+ need("item", "planning.buyItemIds", id);+ }+ for (const id of dataset.planning.makeItemIds) {+ need("item", "planning.makeItemIds", id);+ }+ for (const projection of dataset.planning.demandProjections) {+ need("item", "planning.demandProjections", projection.readableId);+ }+ const order = dataset.planning.demandOrder;+ needCustomer("planning.demandOrder", order.customer);+ if (!dataset.foundation.shippingMethods.includes(order.shippingMethod)) {+ fail(+ `planning.demandOrder: unknown shipping method "${order.shippingMethod}"`+ );+ }+ if (+ order.promisedDateOffset < 0 ||+ order.promisedDateOffset >= HORIZON_DAYS+ ) {+ fail(+ `planning.demandOrder: promisedDateOffset ${order.promisedDateOffset} outside the ${HORIZON_DAYS}-day planning horizon`+ );+ }+ for (const line of order.lines)+ need("item", "planning.demandOrder", line.item);++ const hq = dataset.planning.hq;+ const buyPartIds = new Set(dataset.items.buyParts.map((p) => p.readableId));+ for (const id of hq.reorderItemIds)+ need("item", "planning.hq.reorderItemIds", id);+ if (!hq.reorderItemIds.some((id) => makePartIds.has(id))) {+ fail(+ "planning.hq.reorderItemIds: no make part, so production Material Planning at HQ is empty"+ );+ }+ if (!hq.reorderItemIds.some((id) => buyPartIds.has(id))) {+ fail(+ "planning.hq.reorderItemIds: no buy part, so purchasing Material Planning at HQ is empty"+ );+ }+ if (hq.demandProjections.length === 0) {+ fail("planning.hq.demandProjections: must not be empty");+ }+ for (const projection of hq.demandProjections) {+ if (!makePartIds.has(projection.readableId)) {+ fail(+ `planning.hq.demandProjections: "${projection.readableId}" is not a make part`+ );+ }+ if (projection.quantities.length > HORIZON_DAYS / 7) {+ fail(+ `planning.hq.demandProjections "${projection.readableId}": more weeks than the planning horizon`+ );+ }+ }+}++const RULES: Rule[] = [+ itemIdentity,+ foundation,+ items,+ openingStock,+ batchProperties,+ trackedStockAndMovements,+ uniqueDocumentRefs,+ sales,+ purchasing,+ jobs,+ floor,+ eventsJobAndPicking,+ sparePartDrains,+ netOnHand,+ genealogy,+ assembly,+ inspections,+ quality,+ changeOrders,+ accounting,+ postings,+ maintenance,+ workforce,+ workflowRuns,+ peopleAndTime,+ settingsSurfaces,+ enforcementRules,+ commercial,+ returnOrders,+ planning+];++export function validateDataset(dataset: Dataset): string[] {+ const ctx = createContext(dataset);+ for (const rule of RULES) rule(ctx);+ return ctx.violations;+}diff --git a/packages/database/src/datasets/verify.ts b/packages/database/src/datasets/verify.tsindex b52e22c0f1..e757b101cc 100644--- a/packages/database/src/datasets/verify.ts+++ b/packages/database/src/datasets/verify.ts@@ -14,7 +14,9 @@import type { PoolClient } from "pg";import { seedCompanyReferenceData } from "./bootstrap.ts";+import { COVERAGE_FLOORS, COVERAGE_SCOPES } from "./coverage.ts";import { applyDatasetTiers } from "./index.ts";+import { quote } from "./sql.ts";import { type Dataset, resolveCompanyTimeZone } from "./types.ts";const SCRATCH_COMPANY_NAME = "Dataset Drift Check";@@ -57,6 +59,35 @@ export async function resolveCheckUserId(}}+/** A tier that inserts nothing raises no error on its own. */+export async function findCoverageShortfalls(+ client: PoolClient,+ companyId: string+): Promise<string[]> {+ const tables = Object.keys(COVERAGE_FLOORS);+ const union = tables+ .map(+ (t) =>+ `SELECT '${t}' AS table_name, count(*)::int AS count FROM ${quote(t)} WHERE ${+ COVERAGE_SCOPES[t] ?? `"companyId" = $1`+ }`+ )+ .join(" UNION ALL ");+ const res = await client.query<{ table_name: string; count: number }>(union, [+ companyId+ ]);+ const counts = new Map(res.rows.map((r) => [r.table_name, r.count]));+ const shortfalls: string[] = [];+ for (const table of tables) {+ const floor = COVERAGE_FLOORS[table]!;+ const count = counts.get(table) ?? 0;+ if (count < floor) {+ shortfalls.push(`${table}: expected ≥ ${floor}, got ${count}`);+ }+ }+ return shortfalls;+}+/*** Apply one dataset to a throwaway company and roll the whole thing back.* Returns the failure rather than throwing it, so one broken dataset does not@@ -94,6 +125,16 @@ export async function verifyDataset(log});+ const shortfalls = await findCoverageShortfalls(client, companyId);+ if (shortfalls.length > 0) {+ return {+ key,+ ok: false,+ error: `${shortfalls.length} table(s) below their row-count floor (datasets/coverage.ts):\n ${shortfalls.join("\n ")}`,+ durationMs: performance.now() - startedAt+ };+ }+return { key, ok: true, durationMs: performance.now() - startedAt };} catch (err) {return {diff --git a/packages/database/src/datasets/wipe.ts b/packages/database/src/datasets/wipe.tsindex 546bd07c32..35400ea515 100644--- a/packages/database/src/datasets/wipe.ts+++ b/packages/database/src/datasets/wipe.ts@@ -1,5 +1,7 @@import type { PoolClient } from "pg";-import { quote, resetSequences } from "./sql.ts";+import { getGroupId, groups } from "../../supabase/functions/lib/seed.data.ts";+import { resolveDate } from "./dates.ts";+import { insertId, nextJournalEntryId, quote, resetSequences } from "./sql.ts";import type { Ctx } from "./types.ts";/**@@ -33,7 +35,9 @@ const PRESERVED_TABLES = new Set(["sequence","unitOfMeasure","userToCompany",- // Accounting records with trigger-enforced immutability (Posted journals cannot be deleted)+ // Accounting records with trigger-enforced immutability (Posted journals+ // cannot be deleted or updated — so neither can the periods they point at)+ "accountingPeriod","journal","journalLine",// Infrastructure owned by the developer or the platform@@ -70,6 +74,15 @@ const TRANSIENT_MRP_TABLES = ["supplyActual"];+// Their content CHECK (imagePath OR modelUploadId) cannot survive the FK-nulling+// pass, which nulls modelUploadId on a slide that shows a 3D model.+const MODEL_SLIDE_TABLES = [+ "assemblyInstructionStepSlide",+ "methodOperationStepSlide",+ "jobOperationStepSlide",+ "quoteOperationStepSlide"+];+type ForeignKey = {child: string;parent: string;@@ -197,9 +210,124 @@ async function nullNullableReferences(return count;}+// Rows a trigger forbids deleting, which the wipe would otherwise hit halfway+// through. Refusing before any write keeps the failure readable.+async function assertWipeable(ctx: Ctx): Promise<void> {+ const { client, companyId } = ctx;+ const partners = await client.query<{ count: number }>(+ `SELECT (SELECT count(*) FROM customer+ WHERE "companyId" = $1 AND "intercompanyCompanyId" IS NOT NULL)+ + (SELECT count(*) FROM supplier+ WHERE "companyId" = $1 AND "intercompanyCompanyId" IS NOT NULL)+ AS count`,+ [companyId]+ );+ const partnerCount = Number(partners.rows[0]?.count ?? 0);+ if (partnerCount > 0) {+ throw new Error(+ `Seed: this company trades with other companies in its group (${partnerCount} intercompany customer/supplier record(s)). Demo data can only be applied to a company without intercompany partners.`+ );+ }+ const cards = await client.query<{ count: number }>(+ `SELECT count(*) AS count FROM "cardTransaction"+ WHERE "companyId" = $1 AND status <> 'Draft'`,+ [companyId]+ );+ const cardCount = Number(cards.rows[0]?.count ?? 0);+ if (cardCount > 0) {+ throw new Error(+ `Seed: this company has ${cardCount} posted or voided card transaction(s), which cannot be deleted. Demo data can only be applied to a company without posted card transactions.`+ );+ }+}++const DOCUMENT_JOURNAL_SOURCES = [+ "Sales Invoice",+ "Purchase Invoice",+ "Payment",+ "Credit Memo",+ "Debit Memo",+ "Purchase Receipt",+ "Sales Shipment",+ "Inventory Adjustment"+];++/**+ * Posted journals cannot be deleted (journal_posted_immutable), but their+ * documents are about to be: void each as the posting functions do, so the GL+ * carries no balances for documents that no longer exist.+ */+async function reverseDocumentJournals(ctx: Ctx): Promise<void> {+ const { client, companyId } = ctx;+ const journals = await client.query<{+ id: string;+ journalEntryId: string;+ description: string | null;+ sourceType: string;+ }>(+ `SELECT j.id, j."journalEntryId", j.description, j."sourceType"+ FROM journal j+ WHERE j."companyId" = $1 AND j.status = 'Posted'+ AND j."sourceType"::text = ANY($2::text[])+ AND (+ EXISTS (+ SELECT 1 FROM "journalLine" l+ WHERE l."journalId" = j.id AND l."companyId" = $1 AND l."documentId" IN (+ SELECT id FROM "salesInvoice" WHERE "companyId" = $1+ UNION ALL SELECT id FROM "purchaseInvoice" WHERE "companyId" = $1+ UNION ALL SELECT id FROM payment WHERE "companyId" = $1+ UNION ALL SELECT id FROM memo WHERE "companyId" = $1+ UNION ALL SELECT id FROM receipt WHERE "companyId" = $1+ UNION ALL SELECT id FROM shipment WHERE "companyId" = $1+ UNION ALL SELECT id FROM "itemLedger" WHERE "companyId" = $1))+ -- a zero-cash payment's journal has no lines to match on+ OR j.id IN (SELECT "journalId" FROM payment WHERE "companyId" = $1)+ OR j.id IN (SELECT "journalId" FROM memo WHERE "companyId" = $1))+ ORDER BY j."postingDate", j."journalEntryId"`,+ [companyId, DOCUMENT_JOURNAL_SOURCES]+ );+ if (journals.rows.length === 0) return;+ const today = resolveDate(ctx.anchor, 0);+ const period = await client.query<{ id: string }>(+ `SELECT id FROM "accountingPeriod"+ WHERE "companyId" = $1 AND "startDate" <= $2 AND "endDate" >= $2+ ORDER BY id LIMIT 1`,+ [companyId, today]+ );+ for (const journal of journals.rows) {+ const voidId = await insertId(ctx, "journal", {+ journalEntryId: await nextJournalEntryId(ctx),+ accountingPeriodId: period.rows[0]?.id,+ description: `VOID ${journal.description ?? journal.journalEntryId}`,+ postingDate: today,+ sourceType: journal.sourceType,+ status: "Posted",+ postedAt: `${today}T12:00:00Z`,+ postedBy: ctx.userId+ });+ // As the invoice voids: negated amount and quantity, same references (a+ // payment or memo void keeps the quantity).+ await client.query(+ `INSERT INTO "journalLine"+ ("journalId", "accountId", description, amount, quantity, "documentType",+ "documentId", "documentLineReference", "journalLineReference", accrual,+ "companyId", "createdBy")+ SELECT $1, "accountId", 'VOID: ' || COALESCE(description, ''), -amount,+ CASE WHEN "documentType" IN ('Payment', 'Memo') THEN quantity ELSE -quantity END,+ "documentType", "documentId", "documentLineReference",+ "journalLineReference", accrual, "companyId", $2+ FROM "journalLine" WHERE "journalId" = $3 AND "companyId" = $4`,+ [voidId, ctx.userId, journal.id, companyId]+ );+ }+}+export async function wipeCompanyBusinessData(ctx: Ctx): Promise<void> {const { client, companyId } = ctx;+ await assertWipeable(ctx);+ await reverseDocumentJournals(ctx);+const tables = await companyScopedTables(client);const deleteSet = new Set(tables.filter((t) => !PRESERVED_TABLES.has(t)));@@ -211,7 +339,7 @@ export async function wipeCompanyBusinessData(ctx: Ctx): Promise<void> {// Deleting outright is safe and loses nothing: MRP regenerates these wholesale// on its next run, which is why the backup catalog also treats them as// transient (see TRANSIENT_TABLES in packages/jobs/src/backups/schema.ts).- for (const t of TRANSIENT_MRP_TABLES) {+ for (const t of [...TRANSIENT_MRP_TABLES, ...MODEL_SLIDE_TABLES]) {if (deleteSet.has(t)) {await client.query(`DELETE FROM ${quote(t)} WHERE "companyId" = $1`, [companyId@@ -224,6 +352,32 @@ export async function wipeCompanyBusinessData(ctx: Ctx): Promise<void> {(deleteSet.has(fk.child) || PRESERVED_TABLES.has(fk.child)));+ // The prevent_posted_{sales,purchase}_invoice_deletion interceptors refuse+ // DELETE for any status but Draft, even under app.sync_in_progress. This is a+ // re-seed wipe, not an app delete of a posted document, so reset them to+ // Draft first — otherwise re-applying over Paid / Voided invoices fails.+ for (const t of ["salesInvoice", "purchaseInvoice"]) {+ if (deleteSet.has(t)) {+ await client.query(+ `UPDATE ${quote(t)} SET status = 'Draft'+ WHERE "companyId" = $1 AND status <> 'Draft'`,+ [companyId]+ );+ }+ }++ // Settlements point at their target invoice/memo through ON DELETE RESTRICT+ // foreign keys, so they must go before the invoice headers below. Payments+ // and memos go with them: both carry a customer-XOR-supplier CHECK that the+ // FK-nulling pass would violate when it nulls the party they point at.+ for (const t of ["invoiceSettlement", "payment", "memo"]) {+ if (deleteSet.has(t)) {+ await client.query(`DELETE FROM ${quote(t)} WHERE "companyId" = $1`, [+ companyId+ ]);+ }+ }+// Delete lines with check constraints that would block nulling their item FKs.// salesOrderLine.itemId can't be set NULL (check requires it for Part/Material/Tool/etc).// Cascade via the parent headers — the headers are in deleteSet and will be deleted again@@ -256,6 +410,24 @@ export async function wipeCompanyBusinessData(ctx: Ctx): Promise<void> {]);}+ // Customer/supplier interceptors mint an org group per partner (id = the+ // partner's id) and per type, and nothing deletes them with the owner, so the+ // previous story's partners linger in group pickers. Drop the orphans;+ // bootstrap's roots are kept by id and employee-type groups are untouched.+ await client.query(+ `DELETE FROM "group" g+ WHERE g."companyId" = $1 AND g.id <> ALL($2::text[]) AND (+ (g."isCustomerOrgGroup" AND NOT EXISTS (+ SELECT 1 FROM customer o WHERE o.id = g.id AND o."companyId" = $1))+ OR (g."isSupplierOrgGroup" AND NOT EXISTS (+ SELECT 1 FROM supplier o WHERE o.id = g.id AND o."companyId" = $1))+ OR (g."isCustomerTypeGroup" AND NOT EXISTS (+ SELECT 1 FROM "customerType" o WHERE o.id = g.id AND o."companyId" = $1))+ OR (g."isSupplierTypeGroup" AND NOT EXISTS (+ SELECT 1 FROM "supplierType" o WHERE o.id = g.id AND o."companyId" = $1)))`,+ [companyId, groups.map((g) => getGroupId(g.idPrefix, companyId))]+ );+// location is preserved, but only the bootstrap one — the rest are seed data.// Re-point the employee at it first; employeeJob is preserved and NOT NULL.await client.query(diff --git a/packages/database/src/inspection-verdict.test.ts b/packages/database/src/inspection-verdict.test.tsnew file mode 100644index 0000000000..7e85f1c20f--- /dev/null+++ b/packages/database/src/inspection-verdict.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from "vitest";+import {+ computeLotStatus,+ deriveSampleStatus,+ valuateMeasurement+} from "../supabase/functions/shared/inspection-verdict.ts";+import { deriveSampleStatus as seededSampleStatus } from "./datasets/helpers/inspection.ts";++const feature = {+ type: "Measurement",+ nominalValue: "10",+ tolerancePlus: "+0.1",+ toleranceMinus: "-0.05"+};++describe("valuateMeasurement", () => {+ it("judges a numeric Measurement inside [nominal - |tol-|, nominal + |tol+|]", () => {+ expect(valuateMeasurement(feature, 10.1)).toBe("Passed");+ expect(valuateMeasurement(feature, 9.95)).toBe("Passed");+ expect(valuateMeasurement(feature, 10.11)).toBe("Failed");+ expect(valuateMeasurement(feature, null)).toBe("Pending");+ });++ it("treats an unparseable nominal as a pass/fail toggle", () => {+ const gdt = { ...feature, nominalValue: "⌖ 0.05 A B" };+ expect(valuateMeasurement(gdt, 10)).toBe("Pending");+ expect(valuateMeasurement(gdt, null, false)).toBe("Failed");+ });+});++describe("deriveSampleStatus", () => {+ const passed = (id: string) => ({+ inspectionFeatureId: id,+ status: "Passed"+ });+ it("fails on any failed reading", () => {+ expect(+ deriveSampleStatus(+ ["a", "b"],+ [passed("a"), { inspectionFeatureId: "b", status: "Failed" }]+ )+ ).toBe("Failed");+ });+ it("passes only once every lot feature has a passing reading", () => {+ expect(deriveSampleStatus(["a", "b"], [passed("a")])).toBe("Pending");+ expect(deriveSampleStatus(["a", "b"], [passed("a"), passed("b")])).toBe(+ "Passed"+ );+ });+ it("never passes a sample on a lot with no features", () => {+ expect(deriveSampleStatus([], [])).toBe("Pending");+ expect(+ seededSampleStatus([], {+ status: "Passed",+ inspectedOffset: 0,+ measurements: []+ })+ ).toBe("Pending");+ });+});++describe("computeLotStatus", () => {+ it("is In Progress once any sample has a verdict", () => {+ expect(computeLotStatus([])).toBe("Pending");+ expect(computeLotStatus([{ status: "Pending" }])).toBe("Pending");+ expect(+ computeLotStatus([{ status: "Pending" }, { status: "Failed" }])+ ).toBe("In Progress");+ });+});diff --git a/packages/database/src/quality.ts b/packages/database/src/quality.tsindex 1d605fac42..b7e4106e8f 100644--- a/packages/database/src/quality.ts+++ b/packages/database/src/quality.ts@@ -12,6 +12,11 @@ import type { Transaction } from "kysely";import { sql } from "kysely";import { getNextSequence } from "../supabase/functions/shared/get-next-sequence.ts";+import {+ computeLotStatus,+ deriveSampleStatus,+ valuateMeasurement+} from "../supabase/functions/shared/inspection-verdict.ts";import type { Kysely, KyselyDatabase } from "./client.ts";import type { SamplingPlanInput, SamplingStandard } from "./sampling.ts";import { resolveFeatureSamplingPlan, resolveSamplingPlan } from "./sampling.ts";@@ -20,6 +25,8 @@ type Ok<T> = { data: T; error: null };type Err = { data: null; error: { message: string; blockers?: unknown } };export type Result<T> = Ok<T> | Err;+export { valuateMeasurement };+export function errResult(message: string, blockers?: unknown): Err {return { data: null, error: { message, ...(blockers ? { blockers } : {}) } };}@@ -134,16 +141,6 @@ async function assertSampleNotLinked(}}-// Mirrors the old in-service helper. Terminal states (Passed/Failed/Partial)-// are owned by the disposition path, so the per-sample recompute only flips-// between Pending and In Progress.-function computeLotStatus(- samples: { status: string }[]-): "Pending" | "In Progress" {- const inspected = samples.filter((s) => s.status !== "Pending").length;- return inspected > 0 ? "In Progress" : "Pending";-}-// Entity-level side effects of a sample verdict (serial parts only): flip the// tracked entity's status and record the Inspect activity. Shared by the// pass/fail sample path and the derived-status measurement path. Only invoked@@ -656,46 +653,6 @@ export async function dispositionInspection(// 3. Measurements (document-driven lots)// --------------------------------------------------------------function parseSpecNumber(value: string | null | undefined): number | null {- if (value == null) return null;- const trimmed = value.trim();- if (trimmed === "") return null;- const parsed = Number(trimmed.replace(/^\+/, ""));- return Number.isNaN(parsed) ? null : parsed;-}--// Pure valuation of one reading against the live feature spec. Measurement-// features with a parseable nominal are judged numerically inside-// [nominal - |tol-|, nominal + |tol+|]; everything else (attribute features,-// GD&T strings that don't parse) is a pass/fail toggle.-export function valuateMeasurement(- feature: {- type: string;- nominalValue: string | null;- tolerancePlus: string | null;- toleranceMinus: string | null;- },- value: number | null,- passed?: boolean | null-): "Pending" | "Passed" | "Failed" {- const nominal =- feature.type === "Measurement"- ? parseSpecNumber(feature.nominalValue)- : null;-- if (feature.type === "Measurement" && nominal !== null) {- if (value == null) return "Pending";- const tolPlus = Math.abs(parseSpecNumber(feature.tolerancePlus) ?? 0);- const tolMinus = Math.abs(parseSpecNumber(feature.toleranceMinus) ?? 0);- return value >= nominal - tolMinus && value <= nominal + tolPlus- ? "Passed"- : "Failed";- }-- if (passed == null) return "Pending";- return passed ? "Passed" : "Failed";-}-// Records one cell of the features x samples grid. Valuates the reading,// upserts the measurement, derives the sample's status from its required// measurements (strict: no override), applies serial-entity side effects on@@ -832,12 +789,6 @@ export async function upsertInspectionMeasurement(measurementId = inserted.id;}- // Derive the sample's status. Sampling is count-based, not positional —- // a feature's n is the minimum number of readings across ANY samples- // (per-feature gating at disposition enforces the counts), so a sample's- // own verdict is: Failed the moment any of its readings fails, Passed- // once every plan feature has a passing reading on it (a fully-inspected- // unit), otherwise Pending (partially inspected).const lotFeatures = await trx.selectFrom("inspectionSamplingPlan").select(["inspectionFeatureId", "sampleSize"])@@ -849,20 +800,10 @@ export async function upsertInspectionMeasurement(.where("inspectionSampleId", "=", sample.id).execute();- const anyFailed = sampleMeasurements.some((m) => m.status === "Failed");- const allFeaturesPassed =- lotFeatures.length > 0 &&- lotFeatures.every(- (f) =>- sampleMeasurements.find(- (m) => m.inspectionFeatureId === f.inspectionFeatureId- )?.status === "Passed"- );- const derivedStatus: "Pending" | "Passed" | "Failed" = anyFailed- ? "Failed"- : allFeaturesPassed- ? "Passed"- : "Pending";+ const derivedStatus = deriveSampleStatus(+ lotFeatures.map((f) => f.inspectionFeatureId),+ sampleMeasurements+ );if (derivedStatus !== sample.status) {await trxdiff --git a/packages/database/src/seed-dev.ts b/packages/database/src/seed-dev.tsindex 81695aeef6..c64d38e3c0 100644--- a/packages/database/src/seed-dev.ts+++ b/packages/database/src/seed-dev.ts@@ -11,11 +11,19 @@* An email that belongs to no company bootstraps a brand new user + company* first, which is what `crbn up` relies on for [email protected].*+ * After the seed commits it runs MRP and the scheduler through+ * `@carbon/jobs`'s `plan:company` (skip with `--skip-plan`).+ ** Usage:* pnpm run db:seed:dev -- --email [email protected] [--dataset satellite]*/+import { spawnSync } from "node:child_process";+import { existsSync } from "node:fs";+import { homedir } from "node:os";+import path from "node:path";import process from "node:process";+import { fileURLToPath } from "node:url";import { getPostgresConnectionPool } from "./client.ts";import { bootstrap, DEV_PASSWORD } from "./datasets/bootstrap.ts";import { loadEnv, parseSeedArgs } from "./datasets/cli.ts";@@ -30,7 +38,8 @@ async function main() {email,dataset: datasetKey,tiers,- skipWipe+ skipWipe,+ skipPlan} = parseSeedArgs(datasetKeys());console.log(`\nSeeding development environment for: ${email} (${datasetKey})\n`@@ -38,6 +47,7 @@ async function main() {const pool = getPostgresConnectionPool(1);const client = await pool.connect();+ let seeded: { companyId: string; userId: string } | null = null;try {let resolved = await resolveCompany(client, email);@@ -75,6 +85,7 @@ async function main() {});await printSummary(client, companyId);+ seeded = { companyId, userId };console.log(`========================================Dev environment seeded successfully!@@ -92,6 +103,57 @@ Dev environment seeded successfully!client.release();await pool.end();}++ if (seeded && !skipPlan) planCompany(seeded);+}++// The engines reach Supabase over HTTPS; under portless that is its self-signed+// CA, which `crbn up` hands its apps the same way (packages/dev services/apps.ts).+function portlessCa(): Record<string, string> {+ const caPath = path.join(homedir(), ".portless", "ca.pem");+ return !process.env.NODE_EXTRA_CA_CERTS && existsSync(caPath)+ ? { NODE_EXTRA_CA_CERTS: caPath }+ : {};+}++// A spawned script, not an import: @carbon/planning depends on this package.+function planCompany({+ companyId,+ userId+}: {+ companyId: string;+ userId: string;+}) {+ const repoRoot = path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ "..",+ "..",+ ".."+ );+ const planned = spawnSync(+ "pnpm",+ [+ "--silent",+ "--filter",+ "@carbon/jobs",+ "plan:company",+ "--",+ "--company",+ companyId,+ "--user",+ userId+ ],+ {+ stdio: "inherit",+ cwd: repoRoot,+ env: { ...process.env, ...portlessCa() }+ }+ );+ if (planned.status !== 0) {+ console.warn(+ `⚠ Planning step failed — run it later with: pnpm --filter @carbon/jobs plan:company -- --company ${companyId} --user ${userId}`+ );+ }}main();diff --git a/packages/database/supabase/functions/shared/inspection-verdict.ts b/packages/database/supabase/functions/shared/inspection-verdict.tsnew file mode 100644index 0000000000..df1adf64d2--- /dev/null+++ b/packages/database/supabase/functions/shared/inspection-verdict.ts@@ -0,0 +1,79 @@+/**+ * Pure inspection verdicts shared by the engine (`@carbon/database/quality`) and+ * the dataset seed, so a seeded sample carries exactly the status the engine+ * would derive. No I/O and no kysely, so it loads in any runtime.+ */++export type InspectionVerdict = "Pending" | "Passed" | "Failed";++export type MeasurementFeatureSpec = {+ type: string;+ nominalValue: string | null;+ tolerancePlus: string | null;+ toleranceMinus: string | null;+};++export function parseSpecNumber(+ value: string | null | undefined+): number | null {+ if (value == null) return null;+ const trimmed = value.trim();+ if (trimmed === "") return null;+ const parsed = Number(trimmed.replace(/^\+/, ""));+ return Number.isNaN(parsed) ? null : parsed;+}++// Measurement features with a parseable nominal are judged numerically inside+// [nominal - |tol-|, nominal + |tol+|]; everything else (attribute features,+// GD&T strings that don't parse) is a pass/fail toggle.+export function valuateMeasurement(+ feature: MeasurementFeatureSpec,+ value: number | null,+ passed?: boolean | null+): InspectionVerdict {+ const nominal =+ feature.type === "Measurement"+ ? parseSpecNumber(feature.nominalValue)+ : null;++ if (feature.type === "Measurement" && nominal !== null) {+ if (value == null) return "Pending";+ const tolPlus = Math.abs(parseSpecNumber(feature.tolerancePlus) ?? 0);+ const tolMinus = Math.abs(parseSpecNumber(feature.toleranceMinus) ?? 0);+ return value >= nominal - tolMinus && value <= nominal + tolPlus+ ? "Passed"+ : "Failed";+ }++ if (passed == null) return "Pending";+ return passed ? "Passed" : "Failed";+}++// Sampling is count-based, not positional — a feature's n is the minimum+// number of readings across ANY samples (per-feature gating at disposition+// enforces the counts), so a sample's own verdict is: Failed the moment any of+// its readings fails, Passed once every lot feature has a passing reading on+// it (a fully-inspected unit), otherwise Pending. A lot with no features never+// passes a sample.+export function deriveSampleStatus(+ lotFeatureIds: readonly string[],+ measurements: readonly { inspectionFeatureId: string; status: string }[]+): InspectionVerdict {+ if (measurements.some((m) => m.status === "Failed")) return "Failed";+ const allFeaturesPassed =+ lotFeatureIds.length > 0 &&+ lotFeatureIds.every(+ (id) =>+ measurements.find((m) => m.inspectionFeatureId === id)?.status ===+ "Passed"+ );+ return allFeaturesPassed ? "Passed" : "Pending";+}++// Terminal states (Passed/Failed/Partial) are owned by the disposition path,+// so the per-sample recompute only flips between Pending and In Progress.+export function computeLotStatus(+ samples: readonly { status: string }[]+): "Pending" | "In Progress" {+ return samples.some((s) => s.status !== "Pending") ? "In Progress" : "Pending";+}diff --git a/packages/ee/src/workflows/seed-workflows.test.ts b/packages/ee/src/workflows/seed-workflows.test.tsindex 1062c59a4d..a8b15d26b3 100644--- a/packages/ee/src/workflows/seed-workflows.test.ts+++ b/packages/ee/src/workflows/seed-workflows.test.ts@@ -1,5 +1,6 @@import {buildSeedWorkflows,+ EVENT_SOURCES,SEED_WORKFLOW_BUILDERS} from "@carbon/database/seed-workflows";import { describe, expect, it } from "vitest";@@ -52,4 +53,29 @@ describe("dev seed workflows", () => {)).toEqual([]);});++ // Tier 11 subscribes each trigger's table from EVENT_SOURCES, which it cannot+ // read from this catalog (package cycle) — so pin the copy to the catalog here.+ it.each(+ Object.entries(EVENT_SOURCES)+ )("EVENT_SOURCES %s matches the catalog event", (eventId, source) => {+ const match = catalog.getEvent(eventId)?.match;+ expect(match).toBeDefined();+ expect(+ match && "table" in match+ ? { table: match.table, operation: match.operation }+ : null+ ).toEqual(source);+ });++ it("has an event source for every seeded trigger event", () => {+ const triggered = everyDataset.flatMap(([, workflow]) =>+ workflow.nodes.flatMap((node) =>+ node.type === "trigger"+ ? ((node.data.events as string[] | undefined) ?? [])+ : []+ )+ );+ expect(triggered.filter((id) => !(id in EVENT_SOURCES))).toEqual([]);+ });});diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.mdindex 96c8cbf9bb..333596b541 100644--- a/packages/jobs/AGENTS.md+++ b/packages/jobs/AGENTS.md@@ -34,6 +34,7 @@ pnpm --filter @carbon/jobs testpnpm --filter @carbon/jobs typecheckpnpm --filter @carbon/jobs dev:jobspnpm db:check:backups+pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP + schedule one company```## Key Exports@@ -68,6 +69,7 @@ pnpm db:check:backups- `src/workflows/actions/dispatcher.ts` is filled by `apps/erp/app/routes/api+/inngest.ts` with the canonical `callOperation` seam. Missing registration fails cleanly.- `src/workflows/engine/log.ts` redacts secret/token/password/header values before persisting step input.- Bare `tsx` scripts cannot rely on Vite's CJS/ESM interop. Keep runtime imports from packages without `"type":"module"` out of script dependency chains; type-only imports are safe.+- `src/demo-planning.ts` `planDemoCompany` runs MRP + `runLocationSchedule` over a company after a demo template commits; it never throws. Called by the `company-template` job's non-fatal `plan-template` step and by the `plan:company` script (`src/scripts/plan-company.ts`, spawned by `db:seed:dev`), which loads it through `createRequire` for the reason above. See `.claude/rules/onboarding-company-templates.md`.- `db:check:backups` is read-only when run directly. The pre-commit hook passes `--stage` and regenerates/stages `packages/jobs/manifests/schema.json` after a successful live-schema comparison.## Cross-Referencesdiff --git a/packages/jobs/package.json b/packages/jobs/package.jsonindex 021e3c326c..57808806b3 100644--- a/packages/jobs/package.json+++ b/packages/jobs/package.json@@ -58,6 +58,7 @@"scripts": {"db:check:backups": "tsx --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/scripts/check-backups.ts","dev:jobs": "pnpm dlx inngest-cli@latest dev --no-discovery -u http://localhost:3000/api/inngest",+ "plan:company": "tsx --env-file-if-exists=../../.env --env-file-if-exists=../../.env.local src/scripts/plan-company.ts","test": "vitest run","typecheck": "tsc --noEmit"},diff --git a/packages/jobs/src/backups/scope.test.ts b/packages/jobs/src/backups/scope.test.tsindex 5ac77205fa..18968f7d98 100644--- a/packages/jobs/src/backups/scope.test.ts+++ b/packages/jobs/src/backups/scope.test.ts@@ -10,6 +10,7 @@ import { describe, expect, it } from "vitest";import type { JobDatabase } from "../db";import type { ColumnInfo, ForeignKey, TableInfo } from "./schema";import {+ buildDanglingPredicate,buildExclusionPredicate,ExportScopeViolationError,formatScopeViolations,@@ -279,3 +280,31 @@ describe("purgeScopeViolations tenancy guard", () => {expect(pickMethod.scopeColumn).toBe("companyId");});});++describe("buildDanglingPredicate", () => {+ // The demo-revert shape: a kept identity row whose parent the wipe removed.+ const ability = table("ability", [col("id"), col("companyId")]);+ const employeeAbility = table(+ "employeeAbility",+ [col("id"), col("companyId"), col("employeeId"), col("abilityId")],+ [fk("employeeId", "user"), fk("abilityId", "ability")]+ );+ const names = new Map([ability, employeeAbility].map((t) => [t.name, t]));++ it("matches a NOT-NULL FK whose parent row is missing anywhere, not just out of scope", () => {+ const predicate = buildDanglingPredicate(employeeAbility, names);+ const text = compile(predicate!);+ expect(text).toContain(`"abilityId" NOT IN (SELECT "id" FROM "ability")`);+ // Retained targets (user, employee, …) are never treated as dangling.+ expect(text).not.toContain(`"user"`);+ });++ it("returns null when only nullable FKs could dangle", () => {+ const optional = table(+ "optionalLink",+ [col("id"), col("companyId"), col("abilityId", { nullable: true })],+ [fk("abilityId", "ability")]+ );+ expect(buildDanglingPredicate(optional, names)).toBeNull();+ });+});diff --git a/packages/jobs/src/backups/scope.ts b/packages/jobs/src/backups/scope.tsindex 0708b5df51..61590088d9 100644--- a/packages/jobs/src/backups/scope.ts+++ b/packages/jobs/src/backups/scope.ts@@ -534,3 +534,52 @@ export async function purgeScopeViolations(}return { deleted };}++/**+ * Rows `ON DELETE CASCADE` would have removed, had the restore wipe not run under+ * `session_replication_role='replica'`. Deliberately NOT "outside company scope":+ * the user must confirm deleting a live cross-company reference (`purgeScopeViolations`).+ */+export function buildDanglingPredicate(+ table: TableInfo,+ byName: Map<string, TableInfo>+): RawBuilder<unknown> | null {+ const colByName = new Map(table.columns.map((c) => [c.name, c]));+ const terms: RawBuilder<unknown>[] = [];+ for (const fk of table.foreignKeys) {+ if (fk.refColumn !== "id") continue;+ if (RETAINED_REF_TABLES.has(fk.refTable)) continue;+ if (!byName.has(fk.refTable)) continue;+ const col = colByName.get(fk.column);+ if (!col || col.isNullable) continue;+ terms.push(+ sql`${sql.id(fk.column)} NOT IN (SELECT ${sql.id("id")} FROM ${sql.id(+ fk.refTable+ )})`+ );+ }+ if (terms.length === 0) return null;+ return sql.join(terms, sql` OR `);+}++/** Children first; run inside the restore transaction. */+export async function deleteDanglingRows(+ trx: Kysely<KyselyDatabase>,+ tables: TableInfo[],+ byName: Map<string, TableInfo>,+ companyId: string,+ companyGroupId: string | null+): Promise<Array<{ table: string; rows: number }>> {+ const deleted: Array<{ table: string; rows: number }> = [];+ for (const table of [...tables].reverse()) {+ const predicate = buildDanglingPredicate(table, byName);+ if (!predicate) continue;+ const r = await sql`+ DELETE FROM ${sql.id(table.name)}+ WHERE ${buildScopeFilter(table, byName, companyId, companyGroupId)}+ AND (${predicate})`.execute(trx);+ const rows = Number(r.numAffectedRows ?? 0);+ if (rows > 0) deleted.push({ table: table.name, rows });+ }+ return deleted;+}diff --git a/packages/jobs/src/demo-planning.ts b/packages/jobs/src/demo-planning.tsnew file mode 100644index 0000000000..4c34a72649--- /dev/null+++ b/packages/jobs/src/demo-planning.ts@@ -0,0 +1,77 @@+import { getCarbonServiceRole } from "@carbon/auth/client.server";+import { runLocationSchedule, runMrp } from "@carbon/planning";+import { getJobDatabaseClient } from "./db";++export type DemoPlanningResult = {+ mrp: "ok" | string;+ schedule: { locationId: string; result: "ok" | string }[];+};++// runMrp rethrows raw PostgREST errors, which are plain objects.+function message(err: unknown): string {+ if (err instanceof Error) return err.message;+ if (err && typeof err === "object" && "message" in err) {+ return String(err.message);+ }+ return JSON.stringify(err);+}++/**+ * Same calls as the MRP cron and `api+/schedule.ts`. Must run after the seed commits+ * (both engines read over PostgREST). Never throws: the 3-hourly MRP cron is the backstop.+ */+export async function planDemoCompany({+ companyId,+ userId+}: {+ companyId: string;+ userId: string;+}): Promise<DemoPlanningResult> {+ let client: ReturnType<typeof getCarbonServiceRole>;+ let db: ReturnType<typeof getJobDatabaseClient>;+ try {+ client = getCarbonServiceRole();+ db = getJobDatabaseClient();+ } catch (err) {+ return { mrp: message(err), schedule: [] };+ }++ let mrp: DemoPlanningResult["mrp"] = "ok";+ try {+ await runMrp(client, db, {+ type: "company",+ id: companyId,+ companyId,+ userId+ });+ } catch (err) {+ mrp = message(err);+ }++ const schedule: DemoPlanningResult["schedule"] = [];+ let locationIds: string[] = [];+ try {+ const rows = await db+ .selectFrom("job")+ .select("locationId")+ .distinct()+ .where("companyId", "=", companyId)+ .where("status", "in", ["Ready", "In Progress", "Paused"])+ .where("locationId", "is not", null)+ .execute();+ locationIds = rows.flatMap((r) => (r.locationId ? [r.locationId] : []));+ } catch (err) {+ schedule.push({ locationId: "*", result: message(err) });+ }++ for (const locationId of locationIds) {+ try {+ await runLocationSchedule({ db, client, locationId, companyId, userId });+ schedule.push({ locationId, result: "ok" });+ } catch (err) {+ schedule.push({ locationId, result: message(err) });+ }+ }++ return { mrp, schedule };+}diff --git a/packages/jobs/src/inngest/functions/tasks/company-restore.ts b/packages/jobs/src/inngest/functions/tasks/company-restore.tsindex 3eb62c0cd4..8c0655dc12 100644--- a/packages/jobs/src/inngest/functions/tasks/company-restore.ts+++ b/packages/jobs/src/inngest/functions/tasks/company-restore.ts@@ -1,5 +1,6 @@import { getCarbonServiceRole } from "@carbon/auth/client.server";import { requireBackupsEntitlement } from "@carbon/ee/backups.server";+import { getLogger } from "@carbon/logger";import { chunkArray } from "@carbon/utils";import { NonRetriableError } from "inngest";import { sql } from "kysely";@@ -15,6 +16,7 @@ import {backupNameFromSource,bindValue,canSetReplicationRole,+ deleteDanglingRows,ExportScopeViolationError,getCompanyTableCatalog,isUserScopedIdentityTable,@@ -38,6 +40,8 @@ import { buildCompanyBackup } from "./company-export";const INSERT_CHUNK_SIZE = 200;+const log = getLogger("jobs", "company-restore");+type ServiceRole = ReturnType<typeof getCarbonServiceRole>;/**@@ -204,6 +208,26 @@ export async function wipeAndLoad(total: loadTables.length});}++ // Kept identity rows whose parent the wipe removed (replica mode skipped the+ // cascade) would fail every later export. A foreign restore already wiped them.+ if (!remap) {+ const dangling = await deleteDanglingRows(+ trx,+ catalog.tables.filter(+ (t) => isUserScopedIdentityTable(t) && t.scopeColumn === "companyId"+ ),+ byName,+ companyId,+ targetGroupId+ );+ if (dangling.length > 0) {+ log.warn("Restore: removed identity rows left dangling by the wipe", {+ companyId,+ deleted: dangling+ });+ }+ }});return { rows: inserted, idRewrite };diff --git a/packages/jobs/src/inngest/functions/tasks/company-template.ts b/packages/jobs/src/inngest/functions/tasks/company-template.tsindex bf95498ba3..1dc318f221 100644--- a/packages/jobs/src/inngest/functions/tasks/company-template.ts+++ b/packages/jobs/src/inngest/functions/tasks/company-template.ts@@ -6,15 +6,18 @@ import { datetime } from "@carbon/utils";import { NonRetriableError } from "inngest";import { applyTableRenames } from "../../../backups/renames";import { getJobDatabaseClient } from "../../../db";+import { planDemoCompany } from "../../../demo-planning";import { inngest } from "../../client";import {backupAssetsDir,backupDir,+ ExportScopeViolationError,getCompanyTableCatalog,type JobProgress,readBackup,removeStoragePrefix,restoreAssetsFromBackup,+ type ScopeViolation,throttleProgress,writeBackupManifest} from "./company-backup";@@ -47,6 +50,13 @@ type TemplateMeta = {includeGroup?: boolean;/** Live phase progress, so a run that takes minutes doesn't look hung. */progress?: JobProgress | null;+ planningError?: string | null;+ /** The pre-apply snapshot refused over the LIVE data — the one recoverable failure. */+ reason?: "scope-violations" | null;+ /** Per FK edge — never sum into a row count. */+ violations?: ScopeViolation[] | null;+ /** DISTINCT rows — the count the user is told. */+ violationRowsByTable?: Array<{ table: string; rows: number }> | null;};/**@@ -179,7 +189,7 @@ export const companyTemplateFunction = inngest.createFunction(snapshot: takeSnapshot = false} = event.data;- return await step.run("apply-template", async () => {+ const applied = await step.run("apply-template", async () => {const client = getCarbonServiceRole();const dataset = getDataset(datasetKey);@@ -218,7 +228,11 @@ export const companyTemplateFunction = inngest.createFunction(datasetKey,startedAt: datetime.timestamp(),// A retry, or a new run after a failed one, inherits that marker's error.- error: null+ error: null,+ planningError: null,+ reason: null,+ violations: null,+ violationRowsByTable: null}});@@ -286,6 +300,7 @@ export const companyTemplateFunction = inngest.createFunction(onProgress: (p) => report({ ...p, phase: "seed" })});} catch (err) {+ const message = err instanceof Error ? err.message : String(err);await writeTemplateMarker(client, {companyId,userId,@@ -294,9 +309,21 @@ export const companyTemplateFunction = inngest.createFunction(status: "failed",datasetKey,progress: null,- error: (err as Error).message+ error: message,+ ...(err instanceof ExportScopeViolationError+ ? {+ reason: "scope-violations",+ violations: err.violations,+ violationRowsByTable: err.rowsByTable+ }+ : {})}});+ // The snapshot guard's verdict is deterministic; a retry re-fails and+ // flickers the marker running → failed under the user's recovery button.+ if (err instanceof ExportScopeViolationError) {+ throw new NonRetriableError(message, { cause: err });+ }throw err;} finally {pgClient?.release();@@ -319,6 +346,48 @@ export const companyTemplateFunction = inngest.createFunction(return { templateRunId, datasetKey };});++ // Non-fatal: the data is committed, and the MRP cron heals a missed run.+ await step.run("plan-template", async () => {+ const planning = await planDemoCompany({ companyId, userId });+ const failures = [+ ...(planning.mrp === "ok" ? [] : [`MRP: ${planning.mrp}`]),+ ...planning.schedule+ .filter((s) => s.result !== "ok")+ .map((s) => `Schedule ${s.locationId}: ${s.result}`)+ ];+ if (failures.length === 0) return planning;++ const planningError = failures.join("; ");+ logger.error("Demo template planning failed", {+ companyId,+ templateRunId,+ planningError+ });+ try {+ // Only a marker still held for keep/revert records it — writing to a+ // cleared one would resurrect it as `running`.+ const client = getCarbonServiceRole();+ const marker = await readTemplateMarker(client, companyId);+ if (marker?.metadata.templateRunId === templateRunId) {+ await writeTemplateMarker(client, {+ companyId,+ userId,+ templateRunId,+ patch: { planningError }+ });+ }+ } catch (err) {+ logger.error("Failed to record planning error", {+ companyId,+ templateRunId,+ error: (err as Error).message+ });+ }+ return planning;+ });++ return applied;});diff --git a/packages/jobs/src/scripts/plan-company.ts b/packages/jobs/src/scripts/plan-company.tsnew file mode 100644index 0000000000..dc2f57b12a--- /dev/null+++ b/packages/jobs/src/scripts/plan-company.ts@@ -0,0 +1,86 @@+/**+ * Runs MRP and the scheduler over one company. `db:seed:dev` spawns it because+ * `@carbon/database` cannot import `@carbon/planning` (it depends on the database).+ * Best-effort: exits 0 even when a step fails; 1 only on bad arguments.+ */++import { createRequire } from "node:module";+import process from "node:process";+import { parseArgs } from "node:util";++// Loaded through require so tsx compiles the whole graph as CJS: as ESM, the+// named imports @carbon/planning takes from @carbon/database (a CJS package)+// fail to link under plain tsx.+const { planDemoCompany } = createRequire(import.meta.url)(+ "../demo-planning"+) as typeof import("../demo-planning");++function printUsage() {+ console.log(`+Usage: pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id>++Runs MRP, then the scheduler for every location with Ready / In Progress /+Paused jobs. Failures are reported but never fail the command.+Under portless, prefix NODE_EXTRA_CA_CERTS=~/.portless/ca.pem (db:seed:dev does).++Arguments:+ --company Required. The company to plan.+ --user Required. The user recorded as creator of the planning rows.+`);+}++async function main() {+ let values: { company?: string; user?: string; help?: boolean };+ try {+ ({ values } = parseArgs({+ args: process.argv.slice(2).filter((a) => a !== "--"),+ options: {+ company: { type: "string" },+ user: { type: "string" },+ help: { type: "boolean", short: "h", default: false }+ },+ strict: true+ }));+ } catch (err) {+ console.error(`Error: ${err instanceof Error ? err.message : err}`);+ printUsage();+ return 1;+ }++ if (values.help) {+ printUsage();+ return 0;+ }++ const companyId = values.company?.trim();+ const userId = values.user?.trim();+ if (!companyId || !userId) {+ console.error("Error: --company and --user are required");+ printUsage();+ return 1;+ }++ console.log(`\nPlanning company ${companyId}...`);+ const result = await planDemoCompany({ companyId, userId });++ console.log(result.mrp === "ok" ? " MRP ✓" : ` MRP ✗ ${result.mrp}`);+ if (result.schedule.length === 0) {+ console.log(" Schedule — no Ready / In Progress / Paused jobs");+ }+ for (const { locationId, result: outcome } of result.schedule) {+ console.log(+ outcome === "ok"+ ? ` Schedule ${locationId} ✓`+ : ` Schedule ${locationId} ✗ ${outcome}`+ );+ }+ return 0;+}++main()+ .catch((err) => {+ console.error(` Planning ✗ ${err instanceof Error ? err.message : err}`);+ return 0;+ })+ // Explicit exit: the shared pg pool keeps the event loop alive.+ .then((code) => process.exit(code));diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex c2798ad7b8..7da21654c3 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -5485,6 +5485,9 @@ msgstr "Aktion löschen"msgid "Delete Action"msgstr "Aktion löschen"+msgid "Delete and apply"+msgstr "Löschen und anwenden"+msgid "Delete and restore"msgstr "Löschen und wiederherstellen"@@ -6348,6 +6351,9 @@ msgstr "Jeder Fertigungsauftrag braucht seine eigene Chargennummer — oder kombmsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Jede Zeile ist ein Link aus den Daten dieses Unternehmens zu einer Zeile, die es nicht besitzt. Eine Sicherung mit diesen Zeilen könnte niemals wiederhergestellt werden."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Jede Zeile ist ein Link von den Daten dieses Unternehmens zu einer Zeile, die es nicht besitzt. Das Entfernen dieser Zeilen ermöglicht die Anwendung der Demo-Daten."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Jede Zeile ist ein Link aus den Daten dieses Unternehmens zu einer Zeile, die es nicht besitzt. Das Entfernen dieser Zeilen ermöglicht die Wiederherstellung."@@ -14147,6 +14153,9 @@ msgstr "Klausel entfernen"msgid "Remove condition"msgstr "Bedingung entfernen"+msgid "Remove corrupted data and apply"+msgstr "Beschädigte Daten entfernen und anwenden"+msgid "Remove corrupted data and restore"msgstr "Beschädigte Daten entfernen und wiederherstellen"@@ -17971,6 +17980,9 @@ msgstr "Diese Arbeitsgänge nutzen ein Verfahren mit mehreren Lieferanten. Wählmsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "Diese Teile werden durch dieses Teil ersetzt. Jede Regel ist auf dem alten Teil konfiguriert; öffnen Sie es, um die Regel zu ändern."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "Diese Zeilen sind Links zu Daten außerhalb dieses Unternehmens, daher kann keine Sicherungskopie Ihrer aktuellen Daten erstellt werden. Das Löschen kann nicht rückgängig gemacht werden. Falls sie sich als gemeinsam mit anderen Unternehmen in dieser Gruppe herausstellen, wird nichts gelöscht und die Demo-Daten werden nicht angewendet."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "Diese Zeilen verlinken auf Daten außerhalb dieses Unternehmens. Daher kann keine Sicherheitskopie Ihrer aktuellen Daten erstellt werden. Das Löschen kann nicht rückgängig gemacht werden. Sollten diese sich als gemeinsam mit anderen Unternehmen in dieser Gruppe herausstellen, wird nichts gelöscht und die Wiederherstellung wird nicht gestartet."@@ -20027,6 +20039,9 @@ msgstr "Warum sich der Bestand ändert — Positiv (gefunden), Negativ (verlorenmsgid "Why this backup failed"msgstr "Warum diese Sicherung fehlgeschlagen ist"+msgid "Why this failed"+msgstr "Warum das fehlgeschlagen ist"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Warum diese Zeile abgelehnt wird; auf dem druckbaren Angebot angezeigt und für Win-Loss-Berichterstattung aufgezeichnet."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex c2d66f38f5..1c75694284 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -5485,6 +5485,9 @@ msgstr "Delete action"msgid "Delete Action"msgstr "Delete Action"+msgid "Delete and apply"+msgstr "Delete and apply"+msgid "Delete and restore"msgstr "Delete and restore"@@ -6348,6 +6351,9 @@ msgstr "Each job needs its own lot number — or combine them into one lot."msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."@@ -14147,6 +14153,9 @@ msgstr "Remove clause"msgid "Remove condition"msgstr "Remove condition"+msgid "Remove corrupted data and apply"+msgstr "Remove corrupted data and apply"+msgid "Remove corrupted data and restore"msgstr "Remove corrupted data and restore"@@ -17971,6 +17980,9 @@ msgstr "These operations use a process with multiple suppliers. Choose a suppliemsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."@@ -20027,6 +20039,9 @@ msgstr "Why stock is changing — Positive (found), Negative (lost/scrap), or Semsgid "Why this backup failed"msgstr "Why this backup failed"+msgid "Why this failed"+msgstr "Why this failed"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 75eaaabec4..8294d243d1 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -5485,6 +5485,9 @@ msgstr "Eliminar acción"msgid "Delete Action"msgstr "Eliminar acción"+msgid "Delete and apply"+msgstr "Eliminar y aplicar"+msgid "Delete and restore"msgstr "Eliminar y restaurar"@@ -6348,6 +6351,9 @@ msgstr "Cada orden de trabajo necesita su propio número de lote — o combinarlmsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Cada línea es un vínculo de los datos de esta empresa a una fila que no posee. Una copia de seguridad con estas filas nunca podría restaurarse."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Cada línea es un vínculo de los datos de esta empresa a una fila que no le pertenece. Quitar esas filas permite aplicar los datos de demostración."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Cada línea es un vínculo de los datos de esta empresa a una fila que no posee. Eliminar esas filas permite ejecutar la restauración."@@ -14147,6 +14153,9 @@ msgstr "Quitar cláusula"msgid "Remove condition"msgstr "Quitar condición"+msgid "Remove corrupted data and apply"+msgstr "Quitar datos corruptos y aplicar"+msgid "Remove corrupted data and restore"msgstr "Quitar datos dañados y restaurar"@@ -17971,6 +17980,9 @@ msgstr "Estas operaciones utilizan un proceso con múltiples proveedores. Elijamsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "Estas piezas están siendo reemplazadas por ésta. Cada regla se establece en la pieza anterior; ábrela para cambiar la regla."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "Estas filas se vinculan a datos fuera de esta empresa, por lo que no se puede hacer una copia de seguridad de sus datos actuales. Eliminarlos no se puede deshacer. Si resulta que se comparten con otras empresas en este grupo, nada se elimina y los datos de demostración no se aplican."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "Estas filas contienen referencias a datos fuera de esta empresa, por lo que no se puede crear una copia de seguridad de los datos actuales. La eliminación de estas filas no se puede deshacer. Si se encuentran compartidas con otras empresas del grupo, nada se eliminará y la restauración no se iniciará."@@ -20027,6 +20039,9 @@ msgstr "Por qué las existencias están cambiando — Positivo (encontrado), Negmsgid "Why this backup failed"msgstr "Por qué falló esta copia de seguridad"+msgid "Why this failed"+msgstr "Por qué falló esto"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Por qué se rechaza esta línea; mostrado en el presupuesto imprimible y registrado para reportes de ganancia-pérdida."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 4e43c5e092..4c3194c4e4 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -5485,6 +5485,9 @@ msgstr "Supprimer l'action"msgid "Delete Action"msgstr "Supprimer l'action"+msgid "Delete and apply"+msgstr "Supprimer et appliquer"+msgid "Delete and restore"msgstr "Supprimer et restaurer"@@ -6348,6 +6351,9 @@ msgstr "Chaque ordre de fabrication a besoin de son propre numéro de lot — oumsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Chaque ligne est un lien entre les données de cette Société et une ligne qu'elle ne possède pas. Une sauvegarde avec ces lignes ne pourrait jamais être restaurée."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Chaque ligne est un lien entre les données de cette société et une ligne qu'elle ne possède pas. Retirer ces lignes permet d'appliquer les données de démonstration."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Chaque ligne est un lien entre les données de cette Société et une ligne qu'elle ne possède pas. Supprimer ces lignes permet à la restauration de s'exécuter."@@ -14147,6 +14153,9 @@ msgstr "Retirer la clause"msgid "Remove condition"msgstr "Retirer la condition"+msgid "Remove corrupted data and apply"+msgstr "Retirer les données corrompues et appliquer"+msgid "Remove corrupted data and restore"msgstr "Retirer les données corrompues et restaurer"@@ -17971,6 +17980,9 @@ msgstr "Ces opérations utilisent un procédé avec plusieurs fournisseurs. Choimsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "Ces pièces sont remplacées par celle-ci. Chaque règle est définie sur l'ancienne pièce ; ouvrez-la pour modifier la règle."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "Ces lignes sont liées à des données en dehors de cette société, c'est pourquoi une copie de sécurité de vos données actuelles ne peut pas être créée. La suppression de ces lignes ne peut pas être annulée. S'il s'avère que ces lignes sont partagées avec d'autres sociétés de ce groupe, rien n'est supprimé et les données de démonstration ne sont pas appliquées."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "Ces lignes sont liées à des données en dehors de cette Société, c'est pourquoi une copie de sécurité de vos données actuelles ne peut pas être créée. La suppression de ces lignes ne peut pas être annulée. S'il s'avère qu'elles sont partagées avec d'autres Sociétés de ce groupe, rien n'est supprimé et la restauration ne démarre pas."@@ -20027,6 +20039,9 @@ msgstr "Pourquoi le stock change — Positif (trouvé), Négatif (perdu/rebut) omsgid "Why this backup failed"msgstr "Raison de l'échec de cette sauvegarde"+msgid "Why this failed"+msgstr "Pourquoi cela a échoué"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Pourquoi cette ligne est refusée ; affiché sur le devis imprimable et enregistré pour les rapports gain-perte."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 03bea39855..5ab231a455 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -5485,6 +5485,9 @@ msgstr "क्रिया हटाएं"msgid "Delete Action"msgstr "कार्रवाई हटाएं"+msgid "Delete and apply"+msgstr "हटाएँ और लागू करें"+msgid "Delete and restore"msgstr "हटाएँ और पुनः स्थापित करें"@@ -6348,6 +6351,9 @@ msgstr "प्रत्येक जॉब को अपनी स्वयंmsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "प्रत्येक पंक्ति इस कंपनी के डेटा से एक ऐसी पंक्ति के लिए एक लिंक है जिसका यह मालिक नहीं है। इन पंक्तियों के साथ एक बैकअप को कभी भी पुनः स्थापित नहीं किया जा सकता।"+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "प्रत्येक पंक्ति इस कंपनी के डेटा से एक पंक्ति तक एक लिंक है जिसके लिए यह कंपनी मालिक नहीं है। उन पंक्तियों को निकालने से डेमो डेटा को लागू करने की अनुमति मिलती है।"+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "प्रत्येक पंक्ति इस कंपनी के डेटा से एक ऐसी पंक्ति के लिए एक लिंक है जिसका यह मालिक नहीं है। उन पंक्तियों को हटाने से पुनः स्थापन चल जाता है।"@@ -14147,6 +14153,9 @@ msgstr "खंड निकालें"msgid "Remove condition"msgstr "शर्त निकालें"+msgid "Remove corrupted data and apply"+msgstr "भ्रष्ट डेटा निकालें और लागू करें"+msgid "Remove corrupted data and restore"msgstr "भ्रष्ट डेटा निकालें और पुनर्स्थापित करें"@@ -17971,6 +17980,9 @@ msgstr "ये ऑपरेशन कई आपूर्तिकर्ताओmsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "ये पार्ट्स इसके द्वारा प्रतिस्थापित किए जा रहे हैं। प्रत्येक नियम पुराने पार्ट पर सेट है; नियम बदलने के लिए इसे खोलें।"+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "ये पंक्तियां इस कंपनी के बाहर के डेटा से जुड़ी हैं, इसलिए आपके वर्तमान डेटा की एक सुरक्षा प्रति नहीं बनाई जा सकती। उन्हें हटाना पूर्ववत् नहीं किया जा सकता। यदि वे इस समूह की अन्य कंपनियों के साथ साझा निकलते हैं, तो कुछ भी हटाया नहीं जाता और डेमो डेटा लागू नहीं किया जाता है।"+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "ये पंक्तियां इस कंपनी के बाहर के डेटा से जुड़ी हुई हैं, इसलिए आपके वर्तमान डेटा की सुरक्षा प्रति नहीं बनाई जा सकती। उन्हें हटाना पूर्ववत नहीं किया जा सकता। यदि वे इस समूह की अन्य कंपनियों के साथ साझा की जाती हैं, तो कुछ भी हटाया नहीं जाता है और पुनर्स्थापन शुरू नहीं होता है।"@@ -20027,6 +20039,9 @@ msgstr "स्टॉक क्यों बदल रहा है — सकाmsgid "Why this backup failed"msgstr "यह बैकअप क्यों विफल हुआ"+msgid "Why this failed"+msgstr "यह विफल क्यों हुआ"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "यह पंक्ति क्यों अस्वीकार की जा रही है; मुद्रण योग्य उद्धरण पर प्रदर्शित और जीत-हानि रिपोर्टिंग के लिए दर्ज।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 5d0798f1ef..95f2070e6e 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -5485,6 +5485,9 @@ msgstr "Elimina azione"msgid "Delete Action"msgstr "Elimina azione"+msgid "Delete and apply"+msgstr "Elimina e applica"+msgid "Delete and restore"msgstr "Elimina e ripristina"@@ -6348,6 +6351,9 @@ msgstr "Ogni Ordine di produzione richiede il suo numero di Lotto — oppure commsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Ogni riga è un collegamento dai dati di questa Azienda a una riga che non possiede. Un backup con queste righe non potrebbe mai essere ripristinato."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Ogni riga è un collegamento dai dati di questa azienda a una riga che non possiede. Rimuovere quelle righe consente di applicare i dati demo."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Ogni riga è un collegamento dai dati di questa Azienda a una riga che non possiede. La rimozione di queste righe consente l'esecuzione del ripristino."@@ -14147,6 +14153,9 @@ msgstr "Rimuovi clausola"msgid "Remove condition"msgstr "Rimuovi condizione"+msgid "Remove corrupted data and apply"+msgstr "Rimuovi dati corrotti e applica"+msgid "Remove corrupted data and restore"msgstr "Rimuovi i dati corrotti e ripristina"@@ -17971,6 +17980,9 @@ msgstr "Queste operazioni utilizzano un processo con più fornitori. Scegli un fmsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "Questi componenti sono sostituiti da questo. Ogni regola è impostata sul vecchio componente; aprilo per modificare la regola."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "Queste righe si collegano a dati al di fuori di questa azienda, quindi non è possibile creare una copia di sicurezza dei tuoi dati attuali. Eliminarli non può essere annullato. Se risultano condivisi con altre aziende in questo gruppo, nulla viene eliminato e i dati demo non vengono applicati."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "Queste righe sono collegate a dati esterni a questa azienda, pertanto non è possibile effettuare una copia di sicurezza dei dati attuali. La loro eliminazione non può essere annullata. Se risultano condivise con altre aziende del gruppo, nulla viene eliminato e il ripristino non si avvierà."@@ -20027,6 +20039,9 @@ msgstr "Perché la giacenza sta cambiando — Positivo (trovato), Negativo (persmsgid "Why this backup failed"msgstr "Motivo per cui questo backup è fallito"+msgid "Why this failed"+msgstr "Perché è fallito"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Perché questa linea viene rifiutata; visualizzato sul preventivo stampabile e registrato per i rapporti di vincita/perdita."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex dc1e831b21..6aba879db1 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -5485,6 +5485,9 @@ msgstr "アクションを削除"msgid "Delete Action"msgstr "アクションを削除"+msgid "Delete and apply"+msgstr "削除して適用"+msgid "Delete and restore"msgstr "削除して復元"@@ -6348,6 +6351,9 @@ msgstr "各製造指図は独自のロット番号が必要です。または1msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "各明細はこの会社のデータから、それが所有していない行へのリンクです。これらの行を含むバックアップは復元できません。"+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "各明細は、この会社のデータから所有していない行へのリンクです。これらの行を除去すれば、デモデータが適用されます。"+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "各明細はこの会社のデータから、それが所有していない行へのリンクです。それらの行を削除すると、復元を実行できます。"@@ -14147,6 +14153,9 @@ msgstr "条項を除去"msgid "Remove condition"msgstr "条件を除去"+msgid "Remove corrupted data and apply"+msgstr "破損したデータを除去して適用"+msgid "Remove corrupted data and restore"msgstr "破損データを除去して復元"@@ -17971,6 +17980,9 @@ msgstr "これらの工程は複数の仕入先に対応可能な工法を使用msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "これらの部品はこの部品で置き換わっています。各ルールは旧部品に設定されています;ルールを変更するには旧部品を開いてください。"+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "これらの行は、この会社の外部のデータにリンクしています。このため、現在のデータのセーフコピーを作成できません。これらの削除は取り消すことができません。これらがこのグループ内の他の会社と共有されている場合、何も削除されず、デモデータは適用されません。"+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "これらの行はこの会社外のデータにリンクしているため、現在のデータのバックアップを作成できません。削除を元に戻すことはできません。このグループ内の他の会社と共有されていることが判明した場合、何も削除されず、復元は開始されません。"@@ -20027,6 +20039,9 @@ msgstr "在庫が変わっている理由 — 正(見つかった)、負(msgid "Why this backup failed"msgstr "このバックアップが失敗した理由"+msgid "Why this failed"+msgstr "これが失敗した理由"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "この行が拒否されている理由。印刷可能な見積もりに表示され、win-loss報告用に記録されます。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex 85ac2c7f51..14ddecbb83 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -5485,6 +5485,9 @@ msgstr "작업 삭제"msgid "Delete Action"msgstr "작업 삭제"+msgid "Delete and apply"+msgstr "삭제 및 적용"+msgid "Delete and restore"msgstr "삭제 및 복원"@@ -6348,6 +6351,9 @@ msgstr "각 작업 지시는 자체 로트 번호가 필요합니다. 또는 이msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "각 라인은 이 회사 데이터에서 소유하지 않은 행으로의 링크입니다. 이 행들이 포함된 백업은 복원할 수 없습니다."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "각 라인은 이 회사가 소유하지 않은 행을 가리키는 링크입니다. 해당 행을 제거하면 데모 데이터를 적용할 수 있습니다."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "각 라인은 이 회사 데이터에서 소유하지 않은 행으로의 링크입니다. 해당 행들을 제거하면 복원을 실행할 수 있습니다."@@ -14147,6 +14153,9 @@ msgstr "절 제거"msgid "Remove condition"msgstr "조건 제거"+msgid "Remove corrupted data and apply"+msgstr "손상된 데이터 제거 및 적용"+msgid "Remove corrupted data and restore"msgstr "손상된 데이터 제거 및 복원"@@ -17971,6 +17980,9 @@ msgstr "이 공정들은 여러 공급업체에서 처리 가능합니다. 각msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "이 부품들이 이 부품으로 대체됩니다. 각 규칙은 기존 부품에 설정되어 있으니 규칙을 변경하려면 해당 부품을 열어주세요."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "이 행들은 이 회사 외부의 데이터로 연결되어 있으므로 현재 데이터의 백업 복사본을 만들 수 없습니다. 이를 삭제하면 되돌릴 수 없습니다. 이것이 이 그룹의 다른 회사들과 공유되는 것으로 판명되면 아무것도 삭제되지 않으며 데모 데이터도 적용되지 않습니다."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "이 행들은 이 회사 외부의 데이터와 연결되어 있으므로 현재 데이터의 안전한 사본을 만들 수 없습니다. 이들을 삭제하면 되돌릴 수 없습니다. 이들이 이 그룹의 다른 회사와 공유되는 경우, 아무것도 삭제되지 않고 복원이 시작되지 않습니다."@@ -20027,6 +20039,9 @@ msgstr "재고가 변경되는 이유 — 긍정(발견), 부정(손실/스크msgid "Why this backup failed"msgstr "이 백업이 실패한 이유"+msgid "Why this failed"+msgstr "이것이 실패한 이유"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "이 라인이 거절되는 이유로, 인쇄용 견적서에 표시되며 수주/실주 보고를 위해 기록됩니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 9b757e19e6..6da27b1398 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -5485,6 +5485,9 @@ msgstr "Usuń akcję"msgid "Delete Action"msgstr "Usuń akcję"+msgid "Delete and apply"+msgstr "Usuń i zastosuj"+msgid "Delete and restore"msgstr "Usuń i przywróć"@@ -6348,6 +6351,9 @@ msgstr "Każde zlecenie produkcyjne potrzebuje własnego numeru partii — lub pmsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Każdy wiersz to łącze z danych tej firmy do wiersza, którego nie jest właścicielem. Kopia bezpieczeństwa z tymi wierszami nigdy nie mogłaby być przywrócona."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Każda pozycja to połączenie danych z Twojej firmy z wierszem, którym nie dysponujesz. Usunięcie tych wierszy umożliwia zastosowanie danych demonstracyjnych."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Każdy wiersz to łącze z danych tej firmy do wiersza, którego nie jest właścicielem. Usunięcie tych wierszy umożliwia uruchomienie przywracania."@@ -14147,6 +14153,9 @@ msgstr "Usuń z listy klauzulę"msgid "Remove condition"msgstr "Usuń z listy warunek"+msgid "Remove corrupted data and apply"+msgstr "Usuń uszkodzone dane i zastosuj"+msgid "Remove corrupted data and restore"msgstr "Usuń uszkodzone dane i przywróć"@@ -17971,6 +17980,9 @@ msgstr "Te operacje korzystają z procesu z wieloma dostawcami. Wybierz dostawcmsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "Te części są zastępowane przez ten artykuł. Każda reguła jest ustawiona na starej części; otwórz ją, aby zmienić regułę."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "Te wiersze łączą się z danymi spoza tej firmy, dlatego nie można wykonać bezpiecznej kopii bieżących danych. Usunięcie ich nie może być cofnięte. Jeśli okaże się, że są udostępniane innym firmom w tej grupie, nic nie zostanie usunięte i dane demonstracyjne nie zostaną zastosowane."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "Te wiersze łączą się z danymi spoza tej firmy, dlatego nie można wykonać bezpiecznej kopii bieżących danych. Usunięcie ich nie może być cofnięte. Jeśli okaże się, że są współdzielone z innymi firmami w tej grupie, nic nie zostanie usunięte i przywracanie nie zostanie uruchomione."@@ -20027,6 +20039,9 @@ msgstr "Dlaczego zapas się zmienia — Pozytywnie (odnaleziono), Negatywnie (stmsgid "Why this backup failed"msgstr "Dlaczego ta kopia zapasowa nie powiodła się"+msgid "Why this failed"+msgstr "Dlaczego to się nie powiodło"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Dlaczego ta linia jest odrzucana; wyświetlane na drukowanym cytacie i zarejestrowane do raportowania win-loss."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 7da1fe72c3..6eb237329f 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -5485,6 +5485,9 @@ msgstr "Excluir ação"msgid "Delete Action"msgstr "Excluir Ação"+msgid "Delete and apply"+msgstr "Excluir e aplicar"+msgid "Delete and restore"msgstr "Excluir e restaurar"@@ -6348,6 +6351,9 @@ msgstr "Cada ordem de produção precisa de seu próprio número de lote — oumsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Cada linha é um vínculo dos dados desta empresa para uma linha que não é de sua propriedade. Um backup com essas linhas nunca poderia ser restaurado."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Cada linha é um link dos dados desta empresa para uma linha que ela não possui. Remover essas linhas permite que os dados de demonstração sejam aplicados."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Cada linha é um vínculo dos dados desta empresa para uma linha que não é de sua propriedade. Remover essas linhas permite que a restauração seja executada."@@ -14147,6 +14153,9 @@ msgstr "Remover cláusula"msgid "Remove condition"msgstr "Remover condição"+msgid "Remove corrupted data and apply"+msgstr "Remover dados corrompidos e aplicar"+msgid "Remove corrupted data and restore"msgstr "Remover dados corrompidos e restaurar"@@ -17971,6 +17980,9 @@ msgstr "Essas operações usam um processo com múltiplos fornecedores. Selecionmsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "Essas peças estão sendo substituídas por esta. Cada regra é definida na peça antiga; abra-a para alterar a regra."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "Essas linhas estão vinculadas a dados fora desta empresa, portanto, não é possível fazer uma cópia de segurança de seus dados atuais. Excluir essas linhas não pode ser desfeito. Se elas forem compartilhadas com outras empresas neste grupo, nada será excluído e os dados de demonstração não serão aplicados."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "Essas linhas estão vinculadas a dados fora desta empresa, portanto não é possível criar uma cópia de segurança dos seus dados atuais. A exclusão dessas linhas não pode ser desfeita. Se forem compartilhadas com outras empresas neste grupo, nada será excluído e a restauração não será iniciada."@@ -20027,6 +20039,9 @@ msgstr "Por que o estoque está mudando — Positivo (encontrado), Negativo (permsgid "Why this backup failed"msgstr "Por que este backup falhou"+msgid "Why this failed"+msgstr "Por que isso falhou"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Por que esta linha está sendo recusada; mostrado na cotação imprimível e registrado para relatórios de ganho-perda."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex daef581bda..4d3d3f3ce2 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -5485,6 +5485,9 @@ msgstr "Удалить действие"msgid "Delete Action"msgstr "Удалить действие"+msgid "Delete and apply"+msgstr "Удалить и применить"+msgid "Delete and restore"msgstr "Удалить и восстановить"@@ -6348,6 +6351,9 @@ msgstr "Каждый производственный заказ требуетmsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Каждая строка — это связь данных этой организации со строкой, которой она не владеет. Резервную копию с этими строками никогда не удастся восстановить."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Каждая Строка — это ссылка из данных этой Организации на Строку, которой она не владеет. Убрание этих Строк позволяет применить демо-данные."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Каждая строка — это связь данных этой организации со строкой, которой она не владеет. Удаление этих строк позволяет выполнить восстановление."@@ -14147,6 +14153,9 @@ msgstr "Убрать условие"msgid "Remove condition"msgstr "Убрать условие"+msgid "Remove corrupted data and apply"+msgstr "Убрать поврежденные данные и применить"+msgid "Remove corrupted data and restore"msgstr "Убрать поврежденные данные и восстановить"@@ -17971,6 +17980,9 @@ msgstr "Эти операции выполняются по процессу сmsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "Эти детали заменяются на эту. Каждое правило установлено на старой детали; откройте ее, чтобы изменить правило."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "Эти Строки ссылаются на данные вне этой Организации, поэтому невозможно создать резервную копию ваших текущих данных. Их удаление невозможно отменить. Если окажется, что они используются другими Организациями в этой группе, ничего не удаляется и демо-данные не применяются."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "Эти строки связаны с данными вне этой организации, поэтому не удаётся создать резервную копию текущих данных. Удаление их не может быть отменено. Если окажется, что они используются другими организациями в этой группе, ничего не удаляется и восстановление не начинается."@@ -20027,6 +20039,9 @@ msgstr "Почему изменяется запас — Положительнmsgid "Why this backup failed"msgstr "Почему эта резервная копия не удалась"+msgid "Why this failed"+msgstr "Почему это не удалось"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Почему эта строка отклоняется; отображается в печатаемом предложении и записывается для отчетов по победам и потерям."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex 795979a139..b2cd56465f 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -5485,6 +5485,9 @@ msgstr "Eylemi sil"msgid "Delete Action"msgstr "İşlemi Sil"+msgid "Delete and apply"+msgstr "Sil ve uygula"+msgid "Delete and restore"msgstr "Sil ve geri yükle"@@ -6348,6 +6351,9 @@ msgstr "Her İş emri kendi Lot numarasına ihtiyaç duyar — veya bunları birmsgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "Her satır, bu şirketin verilerinden sahibi olmadığı bir satıra bir bağlantıdır. Bu satırları içeren bir yedekleme asla geri yüklenemez."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "Her satır, bu şirketin verilerine ait olmayan bir satıra bağlantıdır. Bu satırları kaldırmak, demo verinin uygulanmasını sağlar."+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "Her satır, bu şirketin verilerinden sahibi olmadığı bir satıra bir bağlantıdır. Bu satırları kaldırmak geri yüklemenin çalışmasını sağlar."@@ -14147,6 +14153,9 @@ msgstr "Maddeyi kaldır"msgid "Remove condition"msgstr "Koşulu kaldır"+msgid "Remove corrupted data and apply"+msgstr "Bozulmuş veriyi kaldır ve uygula"+msgid "Remove corrupted data and restore"msgstr "Bozuk verileri kaldır ve geri yükle"@@ -17971,6 +17980,9 @@ msgstr "Bu operasyonlar birden fazla tedarikçili bir proses kullanır. Her birimsgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "Bu parçalar bu birim tarafından değiştiriliyor. Her kural eski parçaya ayarlanmış; kuralı değiştirmek için açın."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "Bu satırlar bu şirketin dışındaki verilere bağlantılı, bu yüzden mevcut verilerinizin güvenlik kopyası oluşturulamaz. Onları silmek geri alınamaz. Eğer bu grup içindeki diğer şirketlerle paylaşıldığı ortaya çıkarsa, hiçbir şey silinmez ve demo verileri uygulanmaz."+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "Bu satırlar bu Şirket dışındaki verilere bağlı olduğundan, mevcut verilerinizin bir güvenlik kopyası oluşturulamaz. Bu satırları silmek geri alınamaz. Bunların bu gruptaki diğer Şirketlerle paylaşıldığı anlaşılırsa, hiçbir şey silinmez ve geri yükleme başlamaz."@@ -20027,6 +20039,9 @@ msgstr "Stok neden değişiyor — Pozitif (bulundu), Negatif (kayboldu/Fire), vmsgid "Why this backup failed"msgstr "Bu yedek neden başarısız oldu"+msgid "Why this failed"+msgstr "Bu neden başarısız oldu"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "Bu satırın neden reddedildiği; yazdırılabilir teklifte gösterilir ve kazanç-kayıp raporlaması için kaydedilir."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex abec6b22e0..0a89697b3e 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -5485,6 +5485,9 @@ msgstr "删除操作"msgid "Delete Action"msgstr "删除操作"+msgid "Delete and apply"+msgstr "删除并应用"+msgid "Delete and restore"msgstr "删除并恢复"@@ -6348,6 +6351,9 @@ msgstr "每个工单需要自己的批次号 — 或将它们合并为一个批msgid "Each line is a link from this company's data to a row it doesn't own. A backup with these rows could never be restored."msgstr "每一行都是从该公司的数据链接到它不拥有的一行。包含这些行的备份永远无法恢复。"+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the demo data apply."+msgstr "每一行都是从此公司的数据指向其不拥有的行的链接。移除这些行可以应用演示数据。"+msgid "Each line is a link from this company's data to a row it doesn't own. Removing those rows lets the restore run."msgstr "每一行都是从该公司的数据链接到它不拥有的一行。删除这些行可以运行恢复。"@@ -14147,6 +14153,9 @@ msgstr "移除条款"msgid "Remove condition"msgstr "移除条件"+msgid "Remove corrupted data and apply"+msgstr "移除损坏的数据并应用"+msgid "Remove corrupted data and restore"msgstr "移除损坏数据并恢复"@@ -17971,6 +17980,9 @@ msgstr "这些工序使用的工艺支持多个供应商。请为每个工序选msgid "These parts are being replaced by this one. Each rule is set on the old part; open it to change the rule."msgstr "这些零件被此零件替代。每个规则都在旧零件上设置;打开它来更改规则。"+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the demo data isn't applied."+msgstr "这些行链接到此公司外部的数据,因此无法为您当前的数据创建安全副本。删除它们无法撤销。如果它们与此集团中的其他公司共享,则不会删除任何内容,演示数据也不会应用。"+msgid "These rows link to data outside this company, so a safety copy of your current data can't be made. Deleting them cannot be undone. If they turn out to be shared with other companies in this group, nothing is deleted and the restore doesn't start."msgstr "这些行链接到此公司外的数据,因此无法创建当前数据的安全备份。删除它们无法撤销。如果这些行实际上与此集团中的其他公司共享,则不删除任何行,且不启动还原。"@@ -20027,6 +20039,9 @@ msgstr "为什么库存在变化 — 正向(发现)、负向(丢失/报废msgid "Why this backup failed"msgstr "备份失败原因"+msgid "Why this failed"+msgstr "为什么失败"+msgid "Why this line is being declined; surfaced on the printable quote and recorded for win-loss reporting."msgstr "该行被拒绝的原因;显示在可打印报价上,并为损益报告记录。"diff --git a/packages/utils/src/field-registry.test.ts b/packages/utils/src/field-registry.test.tsnew file mode 100644index 0000000000..913d2f5983--- /dev/null+++ b/packages/utils/src/field-registry.test.ts@@ -0,0 +1,30 @@+import { RULE_FIELDS } from "@carbon/database/dataset-rule-fields";+import { describe, expect, it } from "vitest";+import {+ availableOperators,+ type FieldDef,+ getFieldsForSalesRules,+ getFieldsForTargetType+} from "./field-registry";++// @carbon/database keeps its own copy of the seedable rule fields (it cannot import+// this package); anything it allows must be offered here, or the seed writes rules the app refuses.+const FIELDS_BY_SHAPE: Record<string, FieldDef[]> = {+ sales: getFieldsForSalesRules(),+ "storage:item": getFieldsForTargetType("item"),+ "storage:workCenter": getFieldsForTargetType("workCenter")+};++describe("dataset RULE_FIELDS ⊆ the rule builder's registry", () => {+ it.each(+ Object.entries(RULE_FIELDS).flatMap(([path, field]) =>+ field.shapes.map((shape) => [path, shape, field.ops] as const)+ )+ )("%s on a %s rule", (path, shape, ops) => {+ const def = FIELDS_BY_SHAPE[shape]?.find((f) => f.path === path);+ expect(def, `${path} is not offered to a ${shape} rule`).toBeDefined();+ expect(ops.filter((op) => !availableOperators(def!).includes(op))).toEqual(+ []+ );+ });+});