@happyvertical/smrt-manufacturing 0.54.3 → 0.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +1 -1
- package/README.md +12 -2
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/manifest.json +1 -1
- package/dist/smrt-knowledge.json +7 -6
- package/dist/svelte/components/AssemblyForm.svelte +93 -12
- package/dist/svelte/components/AssemblyForm.svelte.d.ts +14 -3
- package/dist/svelte/components/AssemblyForm.svelte.d.ts.map +1 -1
- package/dist/svelte/components/ProductionRunList.svelte +197 -1
- package/dist/svelte/components/ProductionRunList.svelte.d.ts +15 -0
- package/dist/svelte/components/ProductionRunList.svelte.d.ts.map +1 -1
- package/dist/svelte/i18n.d.ts +23 -0
- package/dist/svelte/i18n.d.ts.map +1 -1
- package/dist/svelte/i18n.js +23 -0
- package/dist/svelte/index.d.ts +1 -1
- package/dist/svelte/index.d.ts.map +1 -1
- package/dist/svelte/index.js +1 -1
- package/dist/svelte/types.d.ts +40 -87
- package/dist/svelte/types.d.ts.map +1 -1
- package/dist/svelte/types.js +29 -85
- package/dist/views.d.ts +95 -0
- package/dist/views.d.ts.map +1 -0
- package/dist/views.js +72 -0
- package/dist/views.js.map +1 -0
- package/package.json +12 -8
package/dist/manifest.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"version": "1.0.0",
|
|
3
3
|
"timestamp": 0,
|
|
4
4
|
"packageName": "@happyvertical/smrt-manufacturing",
|
|
5
|
-
"packageVersion": "0.
|
|
5
|
+
"packageVersion": "0.55.0",
|
|
6
6
|
"objects": {
|
|
7
7
|
"@happyvertical/smrt-manufacturing:BillOfMaterialsCollection": {
|
|
8
8
|
"name": "billofmaterialscollection",
|
package/dist/smrt-knowledge.json
CHANGED
|
@@ -3,13 +3,13 @@
|
|
|
3
3
|
"sensitiveFieldsExcluded": true,
|
|
4
4
|
"generatedAt": "1970-01-01T00:00:00.000Z",
|
|
5
5
|
"packageName": "@happyvertical/smrt-manufacturing",
|
|
6
|
-
"packageVersion": "0.
|
|
6
|
+
"packageVersion": "0.55.0",
|
|
7
7
|
"sourceManifestPath": "dist/manifest.json",
|
|
8
8
|
"agentDocPath": "AGENTS.md",
|
|
9
9
|
"sourceHashes": {
|
|
10
|
-
"manifest": "
|
|
11
|
-
"packageJson": "
|
|
12
|
-
"agents": "
|
|
10
|
+
"manifest": "10f9e09298f959efbcd2f04fdf716ba9e5f9e9738978a65ff0049719339a0fbd",
|
|
11
|
+
"packageJson": "23d4154f4936e988d397f5435441c127b67fe577d0d7d5bc872e71642d27caa4",
|
|
12
|
+
"agents": "53bbb8d8dfd7e1dbd438a4ad1559be8cd1ad8ed46c726d5498d2dda5b3535054",
|
|
13
13
|
"moduleDoc:agents/multilevel-and-runs.md": "544d519356801f3cb3beb9e6d49a3e0eec93fdddf3f56150cf3141f766f98c9d"
|
|
14
14
|
},
|
|
15
15
|
"exports": [
|
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
"./manifest",
|
|
18
18
|
"./manifest.json",
|
|
19
19
|
"./svelte",
|
|
20
|
-
"./ui"
|
|
20
|
+
"./ui",
|
|
21
|
+
"./views"
|
|
21
22
|
],
|
|
22
23
|
"dependencies": {
|
|
23
24
|
"@happyvertical/logger": "catalog:",
|
|
@@ -2381,7 +2382,7 @@
|
|
|
2381
2382
|
"polymorphicAssociations": 0,
|
|
2382
2383
|
"uuidColumns": 37
|
|
2383
2384
|
},
|
|
2384
|
-
"agentDoc": "# @happyvertical/smrt-manufacturing\n\nBills of materials (multi-level through sub-assemblies), operations and routing, cost and labour rollup, production runs, and production-order stock movement. Strictly industry-neutral — the same primitives serve apparel, furniture, automotive, CPG, electronics, food production, custom hardware, and any vertical that builds finished goods from a recipe.\n\nSits on top of `@happyvertical/smrt-inventory` (stock) and `@happyvertical/smrt-products` (catalog: `Product`, `Material`, `Sku`), and works alongside the `ProductionOrder` Contract STI subtype already shipped in `@happyvertical/smrt-commerce`.\n\n## Models\n\n| Model | Purpose |\n|---|---|\n| `Assembly` | The product that is **made**, counterpart to `Material`. Cross-package STI subtype of `smrt-products` `Product` (`productType: 'assembly'`, `_meta_type: '@happyvertical/smrt-manufacturing:Assembly'`) in the shared `products` table. Own columns: `estimatedLabourMinutes` (integer, per unit; a save refuses anything but a whole number of minutes of zero or more), `defaultOperationId` (`@foreignKey(Operation)`, nullable, RESTRICT like `RoutingStep.operationId`: the operation work on it is booked to by default), `partReference` (the organization's drawing/part number). Name, price, tags come from `Product`; part number and stock from its `Sku` and inventory; structure from its bill; documents from `ProductAsset`. Exposure matches `Product` (REST list/get/create/update, MCP list/get), as the issue asks: unlike `Operation`, the assembly row has no service-owned invariant that generated writes could bypass. |\n| `BillOfMaterials` | Recipe for a finished product. `productId` (plain string) references the upstream `Product` or any STI subtype. Multiple revisions per product via `version` + `status` (`draft` / `active` / `superseded`). `conflictColumns: ['product_id', 'version', 'tenant_id']`. |\n| `BomLine` | One component on a BOM. `bomId` (FK), `componentSkuId` (plain string ref — the `Sku` model lives in `@happyvertical/smrt-products`; inventory tracks stock motion against the id), `qtyPerUnit`, `uom` (open-ended — `yards`, `each`, `grams`, `kg`, ...), `wastePercent`, `notes`. `conflictColumns: ['bom_id', 'component_sku_id', 'tenant_id']`. |\n| `Operation` | A kind of work (cut, weld, inspect), a managed list per tenant. `code` (unique per tenant; `conflictColumns: ['code', 'tenant_id']`, fixed once defined), `name`, `category`, `isActive` (retire/reinstate; never deleted, `delete()` throws), `requiredQualificationId` (nullable `@crossPackageRef('@happyvertical/smrt-human-resources:Qualification')`: metadata only, no dependency, unvalidated; an application reads it to gate who may start the operation). |\n| `ProductionRun` | A build against one bill, reported as it happens (\"25 to build, 12 done\"). `bomId` (`@foreignKey(BillOfMaterials)`, RESTRICT: pinned when created), `targetQty` and `completedQty` (decimal; completed is the sum of completions), `status` (`planned` / `in_progress` / `done` / `cancelled`). Generated list/get only; `ProductionRunService` owns writes. |\n| `ProductionRunCompletion` | One dated report on a run: `runId` (`@foreignKey(ProductionRun)`, CASCADE), `qty` (decimal, > 0), `completedAt`. Generated list/get only. |\n| `RoutingStep` | One operation in a BOM's optional routing. `bomId` (`@foreignKey(BillOfMaterials)`, CASCADE: a routing belongs to its bill), `operationId` (`@foreignKey(Operation)`, RESTRICT: operations are retired, never deleted), `sequence` (1..n, unique per bom), `estimatedMinutes` (decimal, per produced unit), `notes`. `conflictColumns: ['bom_id', 'sequence', 'tenant_id']`. |\n\nAll models are `@TenantScoped({ mode: 'optional' })` with a nullable `tenantId` so they can be used either tenant-scoped or globally.\n\n## Operations, routing and labour estimate\n\n- `OperationService` maintains the list (`define` rejects a duplicate code, including a retired one's; `rename`, `update`, `retire`, `reinstate`). `RoutingService.replaceRouting(bomId, steps)` swaps a bill's whole routing in one transaction and numbers it 1..n; a retired operation may stay on a routing that has it but cannot be newly added.\n- `BomService.computeLabourEstimate(bomId)` returns minutes and, only when the caller supplies `rateResolver` (hourly rate per `Operation`, mirroring `costResolver`), cost. No resolver means minutes only with `rateUnavailable` on each step. A bill with no routing returns an empty estimate; `computeMaterialCost` is unchanged.\n- `Operation` and `RoutingStep` expose generated list/get only; writes go through the services (generated create/update would upsert on a duplicate code or rename the code). `replaceRouting` saves the bill row inside its transaction (row lock) and retries on a revision conflict, so concurrent replacements serialize.\n- Deliberately absent: a default labour rate class (nothing here would use it; the resolver receives the whole `Operation` and can key on `code`/`category`), setup time, scheduling and work-centre capacity, and time recorded against an operation (that stays in `smrt-timesheets` or the application).\n- `./svelte` exports `OperationList` and `OperationForm` (props-driven; hosts persist through `OperationService`). Messages live in `src/svelte/i18n.ts`; component tests use the shared jsdom harness with axe assertions.\n- Tests: `operations-suite.ts` runs on SQLite (`operations.test.ts`) and PostgreSQL (`operations.optional.test.ts`, `pnpm test:postgres`; each test runs in its own tenant because PostgreSQL test data persists).\n\n## Assemblies — nesting lives in the bill\n\nA sub-assembly is a `BomLine` whose component SKU belongs to an `Assembly`; there is no children list on the model. `AssemblyService` is the one link from a line to what it names:\n\n| Method | Behavior |\n|---|---|\n| `resolveComponent(skuId, { tenantId? })` | `{ kind, sku, product, assembly, activeBom, buildable }`. `kind` is `assembly`, `material` (`Material`), `bought` (any other `Product`), or `missing` (unknown SKU, SKU with no product, or a non-UUID id; never throws). `activeBom` is the assembly's highest active bill, `null` when it has none; `buildable` is `assembly && activeBom`. Multi-level explosion (#3444) recurses on `activeBom` and stops at every other kind. |\n| `isAssembly(skuId)` | `resolveComponent(skuId).kind === 'assembly'`. |\n| `findActiveBom(productId, { tenantId? })` | Highest active bill. With `tenantId` (including `null`), that tenant's own bill, else a global one, and `resolveComponent` reads the SKU and product as that tenant's or global (through `tenant-scope.ts`, so a shared global component stays visible under a tenant context) and reports another tenant's as `missing`, whatever the tenant context; the cycle walk and `getBillStructure` pass the bill's own tenant, so a shared assembly resolves to the right tenant's bill on writes made without `withTenant()`. |\n| `getBillStructure(bomId)` | One level: the bill plus each line with its resolved component. Throws `BomNotFoundError`. |\n| `findCycle(productId, componentSkuIds)` | The path by which those components would make `productId` contain itself, following sub-assemblies' **active** bills only; `null` when none. |\n| `assertLineAcyclic(line)` / `assertBillAcyclic(bom)` | Throw `BomCycleError` (a `ValidationError`, code `MANUFACTURING_BOM_CYCLE`, `path` from the product back to itself). |\n\n**Cycle refusal runs in the models.** `BomLine.validateBeforeSave` checks every line save (draft bills too, so a loop is refused when written); `BillOfMaterials.validateBeforeSave` checks every save of an `active` bill (activation), including the lines of a stored bill with the same `(productId, version, tenantId)` that the save would upsert onto. The generated REST routes go through `save()`, so they refuse cycles as well. Not covered: re-pointing a `Sku.productId` (owned by `smrt-products`) and two concurrent saves that each close half of a loop.\n\n## Multi-level walks and production runs\n\nDetail: [agents/multilevel-and-runs.md](agents/multilevel-and-runs.md).\n\n- Every `BomService` method takes `{ levels }` (default `1`, unchanged; up to `MAX_EXPLOSION_DEPTH` = 32, or `'all'`). One walk (`services/structure-walk.ts`) serves `explode` (gross lines and totals), `planRequirements` (net of stock: available, short, what building a shortfall takes; facts, no make-or-buy policy), `canProduce`, cost and labour. A loop already in stored data fails with `BomStructureCycleError`; size limits with `BomExplosionLimitError`.\n- `ProductionRunService` writes `ProductionRun` / `ProductionRunCompletion` in one transaction per call, locking the run row through its revision-guarded save and retrying on a revision conflict; no adapter without `transaction()`. Stock moves only when the caller passes `consume` / `produce`.\n- A run is not commerce's `ProductionOrder` (a `Contract` with terms and money, in a package this one does not depend on); an application that has both links them.\n\n## Svelte components (`./svelte`)\n\nProps-driven; the host loads and persists. `AssemblyList` (a structural `policy` drops hidden columns), `AssemblyForm` (smrt-ui controls like `OperationForm`: `assembly`, `onsubmit`, `operations` for the default-operation picker, a retired or unlisted current operation stays selected and marked, `hiddenFields`/`readonlyFields` for the reader's field policy; price is major units in the form and integer minor units in `onsubmit`; `validateAssemblyForm` mirrors the model's whole-minutes rule). `smrt-fields` is not a dependency: never add `ObjectForm`, `BomEditor` (add/edit/remove lines through host handlers; a sub-assembly shows whether it has its own bill and expands read-only through `loadBill`), `BomStructureTree` (the read-only nested view). `ProductionRunList` (progress, status, and with `oncomplete` a quantity field per open run; rows from `toProductionRunView`), `RequirementsTree` (read-only `explode` / `planRequirements` result by level with totals; `toRequirementTree`, `toRequirementTotals`; internal `RequirementsTreeLevel`). Adapters: `toAssemblyView`, `toBomEditorLines`. Strings are under `manufacturing.` in `src/svelte/i18n.ts`; the package is strict for raw primitives, hardcoded strings and JSDoc.\n\n\n## BomService — planning helpers\n\n```typescript\nimport { BomService } from '@happyvertical/smrt-manufacturing';\n\nconst bom = await BomService.create({\n db,\n // Optional. Resolve unit cost for a component SKU.\n // Without this, every line rolls up to $0 and `costUnavailable` is set.\n costResolver: async (componentSkuId) => fetchLatestCost(componentSkuId),\n});\n\nconst rollup = await bom.computeMaterialCost(bomId);\n// { totalCost, currency, lineBreakdown, hasMissingCosts }\n\nconst requirements = await bom.explodeRequirements(bomId, 100);\n// [{ componentSkuId, totalQty, uom }, ...]\n\nconst check = await bom.canProduce(bomId, 100);\n// { ok: true } | { ok: false, shortages: [...] }\n```\n\n| Method | Behavior |\n|---|---|\n| `computeMaterialCost(bomId)` | Walks every BomLine, applies waste (`qtyPerUnit * (1 + wastePercent / 100)`), resolves unit costs via the optional `costResolver`, returns per-line breakdown plus rolled-up total. Lines with no cost set `costUnavailable: true` and contribute `0`. |\n| `explodeRequirements(bomId, qty)` | Returns a \"shopping list\" of materials needed for `qty` units. Duplicates across lines are summed. Does NOT mutate stock. |\n| `canProduce(bomId, qty)` | Calls `explodeRequirements`, then sums `available` stock across every location per component, returns `{ ok: true }` if everything's covered, else `{ ok: false, shortages: [...] }`. |\n| `explode` / `planRequirements` | Multi-level walks; see \"Multi-level walks\" above. Each method above also takes `{ levels }`. |\n\n## ProductionService — consume / produce\n\n```typescript\nimport { ProductionService } from '@happyvertical/smrt-manufacturing';\n\nconst production = await ProductionService.create({ db });\n\n// Drain materials at the factory.\nconst consumed = await production.consumeMaterials(\n { id: order.id, productId: order.productId, bomId: order.bomId },\n { locationId: factory.id, qty: runQty },\n);\n\n// Receive finished goods.\nconst produced = await production.produceFinishedGoods(\n { id: order.id, productId: order.productId },\n { locationId: factory.id, qty: runQty, finishedSkuId: variant.id },\n);\n\n// Or run both in one transaction — see \"Joint atomicity\" below.\nconst { consumed, produced } = await production.runProduction(\n { id: order.id, productId: order.productId, bomId: order.bomId },\n {\n consume: { locationId: factory.id, qty: runQty },\n produce: { locationId: factory.id, qty: runQty, finishedSkuId: variant.id },\n },\n);\n```\n\nAll three methods write through `StockService` and stamp every emitted `StockMovement` with `sourceType: 'ProductionOrder'` (override with the `sourceType` option, as `ProductionRunService` does) + the production order id so audit queries can roll them up later.\n\n### Joint atomicity — `runProduction` vs the two-call form\n\n`consumeMaterials` and `produceFinishedGoods` are each individually atomic, but calling them as two separate awaits is NOT jointly atomic — each opens its own `stockService.withTransaction(...)` scope. If something goes wrong between the two calls (process crash, transient adapter failure on the produce leg), you can land in a state where materials are deducted but no finished SKU receipt balances them. The audit ledger stays consistent within each call; what's missing is the cross-call invariant.\n\nWhen you need that invariant — typically make-to-stock flows where the factory step is invisible to the ledger — use `runProduction(order, { consume, produce })`. Both legs run inside one transaction; any failure (BOM shortage, adapter error, interceptor reject) rolls back both legs together.\n\nWhen NOT to use it: workflows where consume and produce represent a real wall-clock gap that downstream observers need to see (WIP dashboards, partial-run reporting, separate \"materials posted\" and \"production completed\" events on the dispatch bus). There, the two-call form is the right shape — each call is its own ledger event.\n\n### Location convention — explicit-arg design\n\nThe location where materials are consumed and finished goods are received is passed explicitly to `consumeMaterials` / `produceFinishedGoods`, not carried on the production order itself. Rationale:\n\n- The commerce `ProductionOrder` is a `Contract` STI subtype owned by `@happyvertical/smrt-commerce`. Adding an `originLocationId` field there would either need a schema change in commerce (cross-cutting) or a meta field that only manufacturing knows about (leaky).\n- Real shops often pick a location at run time (factory A is congested, route the run through factory B), so even if the order carried a default, the explicit-arg signature is the more flexible canonical form.\n- Callers that want a default can stash a `locationId` on their own production-order helper and pass it through.\n\n### Finished-SKU convention\n\nA `ProductionOrder` references a `productId`, but a `Product` typically has multiple SKUs (one per variant). The caller of `produceFinishedGoods` picks the concrete `finishedSkuId` because the multi-SKU mapping is application-specific (size run, finish mix, kit variant).\n\n## Opt-in DispatchBus hooks\n\nOff by default. Wire them up explicitly in the application's `smrt.ts`:\n\n```typescript\nimport { installManufacturingDispatchHandlers } from '@happyvertical/smrt-manufacturing';\n\nconst handlers = await installManufacturingDispatchHandlers({\n dispatchBus: bus,\n db,\n // Default: subscribe to production_order:posted, call consumeMaterials.\n installProductionPosted: true,\n // Default: don't auto-produce. Set to true if your shop emits a\n // separate production_order:completed event.\n installProductionCompleted: false,\n // Default: don't combine consume + produce on `posted`. Set to true\n // for make-to-stock-instantly workflows where the factory step is\n // invisible. Ignored when installProductionCompleted is true.\n producedOnPosted: false,\n});\n```\n\nThis subscribes to:\n\n- `production_order:posted` → `production.consumeMaterials(...)`; when `producedOnPosted: true` the handler instead calls `production.runProduction(...)` so consume + produce share one transaction. Process crashes or adapter errors between the two legs can never leave materials deducted with no finished-goods receipt.\n- `production_order:completed` → `production.produceFinishedGoods(...)` (opt-in)\n\nThe companion handlers for `contract:created` (reserve) and `fulfillment:shipped` (fulfil) live in `@happyvertical/smrt-inventory` — wire both packages' installers from `smrt.ts` to get the full lifecycle.\n\n## Tests\n\n`multilevel-suite.ts` (rolled back on PostgreSQL) and `production-run-suite.ts` (base handle, per-test tenant, for real concurrent transactions) follow the same SQLite / `*.optional.test.ts` pattern. `src/__tests__/assembly-suite.ts` runs on SQLite (`assembly.test.ts`) and on PostgreSQL (`assembly.optional.test.ts`, skipped without `DATABASE_URL`; `pnpm test:postgres` and the PostgreSQL CI lane run it on a transaction-scoped handle). Component tests under `src/svelte/__tests__` use jsdom and assert axe.\n\n## Gotchas\n\n- **`computeMaterialCost` without a resolver returns `$0`.** That is deliberate — manufacturing does not assume any particular cost source. A real wiring will plug in `@happyvertical/smrt-products` `Material.costPerUnit`, or a rolling average from purchase-order history, or a vendor price book. The `costUnavailable` flag tells UIs to surface \"unknown cost\" rather than silently rolling up zeros.\n- **`explodeRequirements` does not call any stock APIs.** It is a planning helper. To check whether the materials are actually on hand, use `canProduce`. To actually deduct them, use `ProductionService.consumeMaterials`.\n- **`canProduce` sums available stock across every location.** The planning question is \"do we have it at all?\". The operational question of \"which warehouse do we pull from?\" is left to the caller of `consumeMaterials`, which targets a single `locationId` per call.\n- **`consumeMaterials` propagates `InsufficientStockError`.** If a line would drive `available` below zero, the underlying `StockService.adjust` throws. Pre-flight with `canProduce` before posting if you want to avoid partial-failure mid-run.\n- **`consumeMaterials` is atomic across BOM lines.** All per-line deductions and their audit rows run inside a single `stockService.withTransaction(...)` scope (powered by `@happyvertical/sql >= 0.74.0`'s native `db.transaction()`). An `InsufficientStockError` on line N+1 rolls back lines 1..N so production-order posting never leaves materials half-consumed. The recommended pre-flight (`BomService.canProduce(orderId, qty)`) is still useful when you'd rather know upfront than discover the shortfall mid-run, but a missed pre-flight no longer corrupts state.\n- **`consumeMaterials` + `produceFinishedGoods` are NOT jointly atomic.** Each opens its own transaction. A failure on the produce leg leaves materials deducted with no finished SKU receipt to balance it. Use `runProduction(order, { consume, produce })` when you need both legs to commit or roll back together.\n- **Cross-package references are plain strings.** `BillOfMaterials.productId`, `BomLine.componentSkuId` and `BomLine.bomId` are plain string ids (changing them to UUID references needs a migration window); the newer models (`RoutingStep`, `ProductionRun`, `ProductionRunCompletion`) reference this package's own models with `@foreignKey`. The package does depend on `smrt-products` (for `Assembly` and the resolve helper), but the bill schema does not couple to the catalog's table layout.\n- **`Assembly` fields are columns, not `Meta<T>`.** Unlike `Material`, its own fields are ordinary columns this package adds to `products` (filterable over REST). The PostgreSQL suite asserts they land there.\n- **`AssemblyCollection` lists exact `Assembly` rows.** An application subtype (e.g. one adding a customer) has its own `_meta_type`; read it through its own collection or `ProductCollection` (`resolveComponent` uses `instanceof Assembly`, so subtypes resolve as assemblies).\n- **`conflictColumns` include `tenant_id`** on both models. NULL-matching semantics are handled by `@happyvertical/sql >= 0.74.0`; two saves with the same `(product_id, version, NULL)` tuple merge in place.\n- **Lazy table creation.** Like everything else in SMRT, the `manufacturing_boms` and `manufacturing_bom_lines` tables are created on first DB op via `syncSchema`. Safe for SSR. A `BomLine` save now reads `product_skus` and `products` for the cycle check.\n- **Cross-industry constraint.** This package's vocabulary stays generic. Apparel-specific concepts (`Style`, `Makeup`, `Colorway`, `tech-pack`, fashion `Season`) and their analogues in furniture / automotive / CPG live in the relevant template package, never here. PRs that introduce industry vocabulary should be rejected.\n\n## Source attribution\n\nEvery emitted `StockMovement` carries `sourceType: 'ProductionOrder'` plus `sourceId: order.id` so downstream queries can reconstruct \"what caused this movement\". Reason codes used:\n\n| reasonCode | Emitter | Note |\n|---|---|---|\n| `production_consume` | `ProductionService.consumeMaterials` | One per BOM line per consume call |\n| `production_produce` | `ProductionService.produceFinishedGoods` | One per produce call |\n| either, with `sourceType: 'ProductionRunCompletion'` | `ProductionRunService.recordCompletion` | Only when the caller passes `consume` / `produce` |\n\nThese join cleanly with the standard inventory reason codes (`receipt`, `reservation`, `release`, `fulfillment`, `transfer_out`, `transfer_in`, `adjustment`) defined in `@happyvertical/smrt-inventory`.\n\n## Dependencies\n\n| Package | Purpose |\n|---|---|\n| `@happyvertical/smrt-core` | SmrtObject / SmrtCollection / DispatchBus |\n| `@happyvertical/smrt-inventory` | StockService, stock levels, movements (the `Sku` model itself lives in `@happyvertical/smrt-products`; inventory tracks stock motion against the id) |\n| `@happyvertical/smrt-products` | `Product` (the `Assembly` STI base), `Material`, `Sku` for the resolve helper and cycle check |\n| `@happyvertical/smrt-ui` / `smrt-types` | Svelte controls, i18n, module UI slots |\n| `@happyvertical/smrt-tenancy` | Optional tenant scoping |\n| `@happyvertical/sql` | Database adapter |\n",
|
|
2385
|
+
"agentDoc": "# @happyvertical/smrt-manufacturing\n\nBills of materials (multi-level through sub-assemblies), operations and routing, cost and labour rollup, production runs, and production-order stock movement. Strictly industry-neutral — the same primitives serve apparel, furniture, automotive, CPG, electronics, food production, custom hardware, and any vertical that builds finished goods from a recipe.\n\nSits on top of `@happyvertical/smrt-inventory` (stock) and `@happyvertical/smrt-products` (catalog: `Product`, `Material`, `Sku`), and works alongside the `ProductionOrder` Contract STI subtype already shipped in `@happyvertical/smrt-commerce`.\n\n## Models\n\n| Model | Purpose |\n|---|---|\n| `Assembly` | The product that is **made**, counterpart to `Material`. Cross-package STI subtype of `smrt-products` `Product` (`productType: 'assembly'`, `_meta_type: '@happyvertical/smrt-manufacturing:Assembly'`) in the shared `products` table. Own columns: `estimatedLabourMinutes` (integer, per unit; a save refuses anything but a whole number of minutes of zero or more), `defaultOperationId` (`@foreignKey(Operation)`, nullable, RESTRICT like `RoutingStep.operationId`: the operation work on it is booked to by default), `partReference` (the organization's drawing/part number). Name, price, tags come from `Product`; part number and stock from its `Sku` and inventory; structure from its bill; documents from `ProductAsset`. Exposure matches `Product` (REST list/get/create/update, MCP list/get), as the issue asks: unlike `Operation`, the assembly row has no service-owned invariant that generated writes could bypass. |\n| `BillOfMaterials` | Recipe for a finished product. `productId` (plain string) references the upstream `Product` or any STI subtype. Multiple revisions per product via `version` + `status` (`draft` / `active` / `superseded`). `conflictColumns: ['product_id', 'version', 'tenant_id']`. |\n| `BomLine` | One component on a BOM. `bomId` (FK), `componentSkuId` (plain string ref — the `Sku` model lives in `@happyvertical/smrt-products`; inventory tracks stock motion against the id), `qtyPerUnit`, `uom` (open-ended — `yards`, `each`, `grams`, `kg`, ...), `wastePercent`, `notes`. `conflictColumns: ['bom_id', 'component_sku_id', 'tenant_id']`. |\n| `Operation` | A kind of work (cut, weld, inspect), a managed list per tenant. `code` (unique per tenant; `conflictColumns: ['code', 'tenant_id']`, fixed once defined), `name`, `category`, `isActive` (retire/reinstate; never deleted, `delete()` throws), `requiredQualificationId` (nullable `@crossPackageRef('@happyvertical/smrt-human-resources:Qualification')`: metadata only, no dependency, unvalidated; an application reads it to gate who may start the operation). |\n| `ProductionRun` | A build against one bill, reported as it happens (\"25 to build, 12 done\"). `bomId` (`@foreignKey(BillOfMaterials)`, RESTRICT: pinned when created), `targetQty` and `completedQty` (decimal; completed is the sum of completions), `status` (`planned` / `in_progress` / `done` / `cancelled`). Generated list/get only; `ProductionRunService` owns writes. |\n| `ProductionRunCompletion` | One dated report on a run: `runId` (`@foreignKey(ProductionRun)`, CASCADE), `qty` (decimal, > 0), `completedAt`. Generated list/get only. |\n| `RoutingStep` | One operation in a BOM's optional routing. `bomId` (`@foreignKey(BillOfMaterials)`, CASCADE: a routing belongs to its bill), `operationId` (`@foreignKey(Operation)`, RESTRICT: operations are retired, never deleted), `sequence` (1..n, unique per bom), `estimatedMinutes` (decimal, per produced unit), `notes`. `conflictColumns: ['bom_id', 'sequence', 'tenant_id']`. |\n\nAll models are `@TenantScoped({ mode: 'optional' })` with a nullable `tenantId` so they can be used either tenant-scoped or globally.\n\n## Operations, routing and labour estimate\n\n- `OperationService` maintains the list (`define` rejects a duplicate code, including a retired one's; `rename`, `update`, `retire`, `reinstate`). `RoutingService.replaceRouting(bomId, steps)` swaps a bill's whole routing in one transaction and numbers it 1..n; a retired operation may stay on a routing that has it but cannot be newly added.\n- `BomService.computeLabourEstimate(bomId)` returns minutes and, only when the caller supplies `rateResolver` (hourly rate per `Operation`, mirroring `costResolver`), cost. No resolver means minutes only with `rateUnavailable` on each step. A bill with no routing returns an empty estimate; `computeMaterialCost` is unchanged.\n- `Operation` and `RoutingStep` expose generated list/get only; writes go through the services (generated create/update would upsert on a duplicate code or rename the code). `replaceRouting` saves the bill row inside its transaction (row lock) and retries on a revision conflict, so concurrent replacements serialize.\n- Deliberately absent: a default labour rate class (nothing here would use it; the resolver receives the whole `Operation` and can key on `code`/`category`), setup time, scheduling and work-centre capacity, and time recorded against an operation (that stays in `smrt-timesheets` or the application).\n- `./svelte` exports `OperationList` and `OperationForm` (props-driven; hosts persist through `OperationService`). Messages live in `src/svelte/i18n.ts`; component tests use the shared jsdom harness with axe assertions.\n- Tests: `operations-suite.ts` runs on SQLite (`operations.test.ts`) and PostgreSQL (`operations.optional.test.ts`, `pnpm test:postgres`; each test runs in its own tenant because PostgreSQL test data persists).\n\n## Assemblies — nesting lives in the bill\n\nA sub-assembly is a `BomLine` whose component SKU belongs to an `Assembly`; there is no children list on the model. `AssemblyService` is the one link from a line to what it names:\n\n| Method | Behavior |\n|---|---|\n| `resolveComponent(skuId, { tenantId? })` | `{ kind, sku, product, assembly, activeBom, buildable }`. `kind` is `assembly`, `material` (`Material`), `bought` (any other `Product`), or `missing` (unknown SKU, SKU with no product, or a non-UUID id; never throws). `activeBom` is the assembly's highest active bill, `null` when it has none; `buildable` is `assembly && activeBom`. Multi-level explosion (#3444) recurses on `activeBom` and stops at every other kind. |\n| `isAssembly(skuId)` | `resolveComponent(skuId).kind === 'assembly'`. |\n| `findActiveBom(productId, { tenantId? })` | Highest active bill. With `tenantId` (including `null`), that tenant's own bill, else a global one, and `resolveComponent` reads the SKU and product as that tenant's or global (through `tenant-scope.ts`, so a shared global component stays visible under a tenant context) and reports another tenant's as `missing`, whatever the tenant context; the cycle walk and `getBillStructure` pass the bill's own tenant, so a shared assembly resolves to the right tenant's bill on writes made without `withTenant()`. |\n| `getBillStructure(bomId)` | One level: the bill plus each line with its resolved component. Throws `BomNotFoundError`. |\n| `findCycle(productId, componentSkuIds)` | The path by which those components would make `productId` contain itself, following sub-assemblies' **active** bills only; `null` when none. |\n| `assertLineAcyclic(line)` / `assertBillAcyclic(bom)` | Throw `BomCycleError` (a `ValidationError`, code `MANUFACTURING_BOM_CYCLE`, `path` from the product back to itself). |\n\n**Cycle refusal runs in the models.** `BomLine.validateBeforeSave` checks every line save (draft bills too, so a loop is refused when written); `BillOfMaterials.validateBeforeSave` checks every save of an `active` bill (activation), including the lines of a stored bill with the same `(productId, version, tenantId)` that the save would upsert onto. The generated REST routes go through `save()`, so they refuse cycles as well. Not covered: re-pointing a `Sku.productId` (owned by `smrt-products`) and two concurrent saves that each close half of a loop.\n\n## Multi-level walks and production runs\n\nDetail: [agents/multilevel-and-runs.md](agents/multilevel-and-runs.md).\n\n- Every `BomService` method takes `{ levels }` (default `1`, unchanged; up to `MAX_EXPLOSION_DEPTH` = 32, or `'all'`). One walk (`services/structure-walk.ts`) serves `explode` (gross lines and totals), `planRequirements` (net of stock: available, short, what building a shortfall takes; facts, no make-or-buy policy), `canProduce`, cost and labour. A loop already in stored data fails with `BomStructureCycleError`; size limits with `BomExplosionLimitError`.\n- `ProductionRunService` writes `ProductionRun` / `ProductionRunCompletion` in one transaction per call, locking the run row through its revision-guarded save and retrying on a revision conflict; no adapter without `transaction()`. Stock moves only when the caller passes `consume` / `produce`.\n- A run is not commerce's `ProductionOrder` (a `Contract` with terms and money, in a package this one does not depend on); an application that has both links them.\n\n## Svelte components (`./svelte`)\n\nProps-driven; the host loads and persists. `AssemblyList` (a structural `policy` drops hidden columns), `AssemblyForm` (smrt-ui controls like `OperationForm`: `assembly`, `onsubmit(values, formData)`, `operations` for the default-operation picker, `showSkuCode` for a required part-number field (`values.skuCode`; host-reported messages through `errors.fields.skuCode`), `extraFields` snippet inside the form, a retired or unlisted current operation stays selected and marked, `hiddenFields`/`readonlyFields` for the reader's field policy; price is major units in the form and integer minor units in `onsubmit`; `validateAssemblyForm` mirrors the model's whole-minutes rule). `smrt-fields` is not a dependency: never add `ObjectForm`, `BomEditor` (add/edit/remove lines through host handlers; a sub-assembly shows whether it has its own bill and expands read-only through `loadBill`), `BomStructureTree` (the read-only nested view). `ProductionRunList` (progress, status, and with `oncomplete` a quantity field per open run; `onsettarget`/`onfinish`/`oncancel` each add their control only when given, finish and cancel behind a `ConfirmDialog`; rows from `toProductionRunView`), `RequirementsTree` (read-only `explode` / `planRequirements` result by level with totals; `toRequirementTree`, `toRequirementTotals`; internal `RequirementsTreeLevel`). Adapters: `toAssemblyView`, `toBomEditorLines`; the BOM and requirement adapters live in `src/views.ts` (no runtime imports, exported as `./views`, re-exported by `./svelte`: keep it component-free). Strings are under `manufacturing.` in `src/svelte/i18n.ts`; the package is strict for raw primitives, hardcoded strings and JSDoc.\n\n\n## BomService — planning helpers\n\n```typescript\nimport { BomService } from '@happyvertical/smrt-manufacturing';\n\nconst bom = await BomService.create({\n db,\n // Optional. Resolve unit cost for a component SKU.\n // Without this, every line rolls up to $0 and `costUnavailable` is set.\n costResolver: async (componentSkuId) => fetchLatestCost(componentSkuId),\n});\n\nconst rollup = await bom.computeMaterialCost(bomId);\n// { totalCost, currency, lineBreakdown, hasMissingCosts }\n\nconst requirements = await bom.explodeRequirements(bomId, 100);\n// [{ componentSkuId, totalQty, uom }, ...]\n\nconst check = await bom.canProduce(bomId, 100);\n// { ok: true } | { ok: false, shortages: [...] }\n```\n\n| Method | Behavior |\n|---|---|\n| `computeMaterialCost(bomId)` | Walks every BomLine, applies waste (`qtyPerUnit * (1 + wastePercent / 100)`), resolves unit costs via the optional `costResolver`, returns per-line breakdown plus rolled-up total. Lines with no cost set `costUnavailable: true` and contribute `0`. |\n| `explodeRequirements(bomId, qty)` | Returns a \"shopping list\" of materials needed for `qty` units. Duplicates across lines are summed. Does NOT mutate stock. |\n| `canProduce(bomId, qty)` | Calls `explodeRequirements`, then sums `available` stock across every location per component, returns `{ ok: true }` if everything's covered, else `{ ok: false, shortages: [...] }`. |\n| `explode` / `planRequirements` | Multi-level walks; see \"Multi-level walks\" above. Each method above also takes `{ levels }`. |\n\n## ProductionService — consume / produce\n\n```typescript\nimport { ProductionService } from '@happyvertical/smrt-manufacturing';\n\nconst production = await ProductionService.create({ db });\n\n// Drain materials at the factory.\nconst consumed = await production.consumeMaterials(\n { id: order.id, productId: order.productId, bomId: order.bomId },\n { locationId: factory.id, qty: runQty },\n);\n\n// Receive finished goods.\nconst produced = await production.produceFinishedGoods(\n { id: order.id, productId: order.productId },\n { locationId: factory.id, qty: runQty, finishedSkuId: variant.id },\n);\n\n// Or run both in one transaction — see \"Joint atomicity\" below.\nconst { consumed, produced } = await production.runProduction(\n { id: order.id, productId: order.productId, bomId: order.bomId },\n {\n consume: { locationId: factory.id, qty: runQty },\n produce: { locationId: factory.id, qty: runQty, finishedSkuId: variant.id },\n },\n);\n```\n\nAll three methods write through `StockService` and stamp every emitted `StockMovement` with `sourceType: 'ProductionOrder'` (override with the `sourceType` option, as `ProductionRunService` does) + the production order id so audit queries can roll them up later.\n\n### Joint atomicity — `runProduction` vs the two-call form\n\n`consumeMaterials` and `produceFinishedGoods` are each individually atomic, but calling them as two separate awaits is NOT jointly atomic — each opens its own `stockService.withTransaction(...)` scope. If something goes wrong between the two calls (process crash, transient adapter failure on the produce leg), you can land in a state where materials are deducted but no finished SKU receipt balances them. The audit ledger stays consistent within each call; what's missing is the cross-call invariant.\n\nWhen you need that invariant — typically make-to-stock flows where the factory step is invisible to the ledger — use `runProduction(order, { consume, produce })`. Both legs run inside one transaction; any failure (BOM shortage, adapter error, interceptor reject) rolls back both legs together.\n\nWhen NOT to use it: workflows where consume and produce represent a real wall-clock gap that downstream observers need to see (WIP dashboards, partial-run reporting, separate \"materials posted\" and \"production completed\" events on the dispatch bus). There, the two-call form is the right shape — each call is its own ledger event.\n\n### Location convention — explicit-arg design\n\nThe location where materials are consumed and finished goods are received is passed explicitly to `consumeMaterials` / `produceFinishedGoods`, not carried on the production order itself. Rationale:\n\n- The commerce `ProductionOrder` is a `Contract` STI subtype owned by `@happyvertical/smrt-commerce`. Adding an `originLocationId` field there would either need a schema change in commerce (cross-cutting) or a meta field that only manufacturing knows about (leaky).\n- Real shops often pick a location at run time (factory A is congested, route the run through factory B), so even if the order carried a default, the explicit-arg signature is the more flexible canonical form.\n- Callers that want a default can stash a `locationId` on their own production-order helper and pass it through.\n\n### Finished-SKU convention\n\nA `ProductionOrder` references a `productId`, but a `Product` typically has multiple SKUs (one per variant). The caller of `produceFinishedGoods` picks the concrete `finishedSkuId` because the multi-SKU mapping is application-specific (size run, finish mix, kit variant).\n\n## Opt-in DispatchBus hooks\n\nOff by default. Wire them up explicitly in the application's `smrt.ts`:\n\n```typescript\nimport { installManufacturingDispatchHandlers } from '@happyvertical/smrt-manufacturing';\n\nconst handlers = await installManufacturingDispatchHandlers({\n dispatchBus: bus,\n db,\n // Default: subscribe to production_order:posted, call consumeMaterials.\n installProductionPosted: true,\n // Default: don't auto-produce. Set to true if your shop emits a\n // separate production_order:completed event.\n installProductionCompleted: false,\n // Default: don't combine consume + produce on `posted`. Set to true\n // for make-to-stock-instantly workflows where the factory step is\n // invisible. Ignored when installProductionCompleted is true.\n producedOnPosted: false,\n});\n```\n\nThis subscribes to:\n\n- `production_order:posted` → `production.consumeMaterials(...)`; when `producedOnPosted: true` the handler instead calls `production.runProduction(...)` so consume + produce share one transaction. Process crashes or adapter errors between the two legs can never leave materials deducted with no finished-goods receipt.\n- `production_order:completed` → `production.produceFinishedGoods(...)` (opt-in)\n\nThe companion handlers for `contract:created` (reserve) and `fulfillment:shipped` (fulfil) live in `@happyvertical/smrt-inventory` — wire both packages' installers from `smrt.ts` to get the full lifecycle.\n\n## Tests\n\n`multilevel-suite.ts` (rolled back on PostgreSQL) and `production-run-suite.ts` (base handle, per-test tenant, for real concurrent transactions) follow the same SQLite / `*.optional.test.ts` pattern. `src/__tests__/assembly-suite.ts` runs on SQLite (`assembly.test.ts`) and on PostgreSQL (`assembly.optional.test.ts`, skipped without `DATABASE_URL`; `pnpm test:postgres` and the PostgreSQL CI lane run it on a transaction-scoped handle). Component tests under `src/svelte/__tests__` use jsdom and assert axe.\n\n## Gotchas\n\n- **`computeMaterialCost` without a resolver returns `$0`.** That is deliberate — manufacturing does not assume any particular cost source. A real wiring will plug in `@happyvertical/smrt-products` `Material.costPerUnit`, or a rolling average from purchase-order history, or a vendor price book. The `costUnavailable` flag tells UIs to surface \"unknown cost\" rather than silently rolling up zeros.\n- **`explodeRequirements` does not call any stock APIs.** It is a planning helper. To check whether the materials are actually on hand, use `canProduce`. To actually deduct them, use `ProductionService.consumeMaterials`.\n- **`canProduce` sums available stock across every location.** The planning question is \"do we have it at all?\". The operational question of \"which warehouse do we pull from?\" is left to the caller of `consumeMaterials`, which targets a single `locationId` per call.\n- **`consumeMaterials` propagates `InsufficientStockError`.** If a line would drive `available` below zero, the underlying `StockService.adjust` throws. Pre-flight with `canProduce` before posting if you want to avoid partial-failure mid-run.\n- **`consumeMaterials` is atomic across BOM lines.** All per-line deductions and their audit rows run inside a single `stockService.withTransaction(...)` scope (powered by `@happyvertical/sql >= 0.74.0`'s native `db.transaction()`). An `InsufficientStockError` on line N+1 rolls back lines 1..N so production-order posting never leaves materials half-consumed. The recommended pre-flight (`BomService.canProduce(orderId, qty)`) is still useful when you'd rather know upfront than discover the shortfall mid-run, but a missed pre-flight no longer corrupts state.\n- **`consumeMaterials` + `produceFinishedGoods` are NOT jointly atomic.** Each opens its own transaction. A failure on the produce leg leaves materials deducted with no finished SKU receipt to balance it. Use `runProduction(order, { consume, produce })` when you need both legs to commit or roll back together.\n- **Cross-package references are plain strings.** `BillOfMaterials.productId`, `BomLine.componentSkuId` and `BomLine.bomId` are plain string ids (changing them to UUID references needs a migration window); the newer models (`RoutingStep`, `ProductionRun`, `ProductionRunCompletion`) reference this package's own models with `@foreignKey`. The package does depend on `smrt-products` (for `Assembly` and the resolve helper), but the bill schema does not couple to the catalog's table layout.\n- **`Assembly` fields are columns, not `Meta<T>`.** Unlike `Material`, its own fields are ordinary columns this package adds to `products` (filterable over REST). The PostgreSQL suite asserts they land there.\n- **`AssemblyCollection` lists exact `Assembly` rows.** An application subtype (e.g. one adding a customer) has its own `_meta_type`; read it through its own collection or `ProductCollection` (`resolveComponent` uses `instanceof Assembly`, so subtypes resolve as assemblies).\n- **`conflictColumns` include `tenant_id`** on both models. NULL-matching semantics are handled by `@happyvertical/sql >= 0.74.0`; two saves with the same `(product_id, version, NULL)` tuple merge in place.\n- **Lazy table creation.** Like everything else in SMRT, the `manufacturing_boms` and `manufacturing_bom_lines` tables are created on first DB op via `syncSchema`. Safe for SSR. A `BomLine` save now reads `product_skus` and `products` for the cycle check.\n- **Cross-industry constraint.** This package's vocabulary stays generic. Apparel-specific concepts (`Style`, `Makeup`, `Colorway`, `tech-pack`, fashion `Season`) and their analogues in furniture / automotive / CPG live in the relevant template package, never here. PRs that introduce industry vocabulary should be rejected.\n\n## Source attribution\n\nEvery emitted `StockMovement` carries `sourceType: 'ProductionOrder'` plus `sourceId: order.id` so downstream queries can reconstruct \"what caused this movement\". Reason codes used:\n\n| reasonCode | Emitter | Note |\n|---|---|---|\n| `production_consume` | `ProductionService.consumeMaterials` | One per BOM line per consume call |\n| `production_produce` | `ProductionService.produceFinishedGoods` | One per produce call |\n| either, with `sourceType: 'ProductionRunCompletion'` | `ProductionRunService.recordCompletion` | Only when the caller passes `consume` / `produce` |\n\nThese join cleanly with the standard inventory reason codes (`receipt`, `reservation`, `release`, `fulfillment`, `transfer_out`, `transfer_in`, `adjustment`) defined in `@happyvertical/smrt-inventory`.\n\n## Dependencies\n\n| Package | Purpose |\n|---|---|\n| `@happyvertical/smrt-core` | SmrtObject / SmrtCollection / DispatchBus |\n| `@happyvertical/smrt-inventory` | StockService, stock levels, movements (the `Sku` model itself lives in `@happyvertical/smrt-products`; inventory tracks stock motion against the id) |\n| `@happyvertical/smrt-products` | `Product` (the `Assembly` STI base), `Material`, `Sku` for the resolve helper and cycle check |\n| `@happyvertical/smrt-ui` / `smrt-types` | Svelte controls, i18n, module UI slots |\n| `@happyvertical/smrt-tenancy` | Optional tenant scoping |\n| `@happyvertical/sql` | Database adapter |\n",
|
|
2385
2386
|
"moduleDocs": [
|
|
2386
2387
|
{
|
|
2387
2388
|
"path": "agents/multilevel-and-runs.md",
|
|
@@ -14,13 +14,22 @@
|
|
|
14
14
|
* `readonlyFields` is shown but not editable (a price a viewer may see but
|
|
15
15
|
* not change). Neither is checked, and `onsubmit` carries its initial value
|
|
16
16
|
* unchanged, so a host should save only fields the reader may write.
|
|
17
|
+
*
|
|
18
|
+
* `showSkuCode` adds the part number (the code of the assembly's `Sku`): it
|
|
19
|
+
* must not be empty, arrives trimmed as `values.skuCode`, and takes the
|
|
20
|
+
* host's own message (a code already in use) through `errors.fields.skuCode`.
|
|
21
|
+
* `extraFields` renders host fields inside the form itself, so they submit
|
|
22
|
+
* with it: `onsubmit` receives the form's `FormData` as its second argument,
|
|
23
|
+
* carrying every named control, the host's included.
|
|
17
24
|
*/
|
|
18
25
|
|
|
19
26
|
import { Button } from '@happyvertical/smrt-ui';
|
|
20
27
|
import { Form, Input, Select, Textarea } from '@happyvertical/smrt-ui/forms';
|
|
21
28
|
import { useI18n } from '@happyvertical/smrt-ui/i18n';
|
|
29
|
+
import type { Snippet } from 'svelte';
|
|
22
30
|
import { M } from '../i18n.js';
|
|
23
31
|
import {
|
|
32
|
+
type AssemblyFormErrors,
|
|
24
33
|
type AssemblyFormField,
|
|
25
34
|
type AssemblyFormInitial,
|
|
26
35
|
type AssemblyFormInvalidField,
|
|
@@ -37,8 +46,12 @@ const { t } = useI18n();
|
|
|
37
46
|
export interface AssemblyFormProps {
|
|
38
47
|
/** The assembly being edited; omit or pass null to add one. */
|
|
39
48
|
assembly?: AssemblyFormInitial | null;
|
|
40
|
-
/**
|
|
41
|
-
|
|
49
|
+
/**
|
|
50
|
+
* Invoked with trimmed, checked values, and the form's `FormData` (every
|
|
51
|
+
* named control, including those from `extraFields`). The form never
|
|
52
|
+
* persists.
|
|
53
|
+
*/
|
|
54
|
+
onsubmit: (values: AssemblyFormValues, formData: FormData) => void;
|
|
42
55
|
/** Invoked when the form is canceled; omit to hide the cancel button. */
|
|
43
56
|
oncancel?: () => void;
|
|
44
57
|
/** Blocks input and submission while the host saves. */
|
|
@@ -51,6 +64,12 @@ export interface AssemblyFormProps {
|
|
|
51
64
|
hiddenFields?: readonly AssemblyFormField[];
|
|
52
65
|
/** Fields the reader may see but not change: rendered read-only. */
|
|
53
66
|
readonlyFields?: readonly AssemblyFormField[];
|
|
67
|
+
/** Shows the part number (SKU code) field, required when shown. */
|
|
68
|
+
showSkuCode?: boolean;
|
|
69
|
+
/** Host-reported errors: a message under a field, or for the whole form. */
|
|
70
|
+
errors?: AssemblyFormErrors;
|
|
71
|
+
/** Host fields rendered inside the form, before its actions. */
|
|
72
|
+
extraFields?: Snippet;
|
|
54
73
|
}
|
|
55
74
|
|
|
56
75
|
const {
|
|
@@ -62,6 +81,9 @@ const {
|
|
|
62
81
|
currency = 'USD',
|
|
63
82
|
hiddenFields = [],
|
|
64
83
|
readonlyFields = [],
|
|
84
|
+
showSkuCode = false,
|
|
85
|
+
errors: hostErrors = {},
|
|
86
|
+
extraFields,
|
|
65
87
|
}: AssemblyFormProps = $props();
|
|
66
88
|
|
|
67
89
|
const uid = $props.id();
|
|
@@ -88,6 +110,7 @@ let estimatedLabourMinutes = $state(
|
|
|
88
110
|
);
|
|
89
111
|
let defaultOperationId = $state(initialFormState.draft.defaultOperationId);
|
|
90
112
|
let tags = $state(initialFormState.draft.tags);
|
|
113
|
+
let skuCode = $state(initialFormState.draft.skuCode ?? '');
|
|
91
114
|
let invalid = $state<AssemblyFormInvalidField[]>([]);
|
|
92
115
|
let appliedAssembly: AssemblyFormInitial | null = initialFormState.assembly;
|
|
93
116
|
let appliedExponent = initialFormState.exponent;
|
|
@@ -112,10 +135,12 @@ $effect(() => {
|
|
|
112
135
|
estimatedLabourMinutes = draft.estimatedLabourMinutes;
|
|
113
136
|
defaultOperationId = draft.defaultOperationId;
|
|
114
137
|
tags = draft.tags;
|
|
138
|
+
skuCode = draft.skuCode ?? '';
|
|
115
139
|
invalid = [];
|
|
116
140
|
});
|
|
117
141
|
|
|
118
|
-
const shown = (field: AssemblyFormField) =>
|
|
142
|
+
const shown = (field: AssemblyFormField) =>
|
|
143
|
+
!hiddenFields.includes(field) && (field !== 'skuCode' || showSkuCode);
|
|
119
144
|
const locked = (field: AssemblyFormField) =>
|
|
120
145
|
loading || readonlyFields.includes(field);
|
|
121
146
|
|
|
@@ -160,33 +185,49 @@ function errorMessage(field: AssemblyFormInvalidField): string {
|
|
|
160
185
|
return t(M['manufacturing.assembly_form.error_name']);
|
|
161
186
|
case 'price':
|
|
162
187
|
return t(M['manufacturing.assembly_form.error_price']);
|
|
188
|
+
case 'skuCode':
|
|
189
|
+
return t(M['manufacturing.assembly_form.error_sku_code']);
|
|
163
190
|
default:
|
|
164
191
|
return t(M['manufacturing.assembly_form.error_labour']);
|
|
165
192
|
}
|
|
166
193
|
}
|
|
167
194
|
|
|
168
|
-
const errors = $derived(
|
|
169
|
-
invalid.map((field) => ({ field, message: errorMessage(field) })),
|
|
170
|
-
|
|
195
|
+
const errors = $derived([
|
|
196
|
+
...invalid.map((field) => ({ field, message: errorMessage(field) })),
|
|
197
|
+
// A host message on a field the form already rejected is not repeated.
|
|
198
|
+
...Object.entries(hostErrors.fields ?? {})
|
|
199
|
+
.filter(
|
|
200
|
+
([field, message]) =>
|
|
201
|
+
message &&
|
|
202
|
+
shown(field as AssemblyFormField) &&
|
|
203
|
+
!invalid.includes(field as AssemblyFormInvalidField),
|
|
204
|
+
)
|
|
205
|
+
.map(([field, message]) => ({
|
|
206
|
+
field: field as AssemblyFormField,
|
|
207
|
+
message: message as string,
|
|
208
|
+
})),
|
|
209
|
+
]);
|
|
171
210
|
|
|
172
|
-
function errorId(field:
|
|
211
|
+
function errorId(field: AssemblyFormField): string {
|
|
173
212
|
return `${uid}-error-${field}`;
|
|
174
213
|
}
|
|
175
214
|
|
|
176
215
|
function describedBy(
|
|
177
|
-
field:
|
|
216
|
+
field: AssemblyFormField | null,
|
|
178
217
|
hintId?: string,
|
|
179
218
|
): string | undefined {
|
|
180
219
|
const ids = [
|
|
181
220
|
hintId,
|
|
182
|
-
field &&
|
|
221
|
+
field && errors.some((error) => error.field === field)
|
|
222
|
+
? errorId(field)
|
|
223
|
+
: undefined,
|
|
183
224
|
];
|
|
184
225
|
return ids.filter(Boolean).join(' ') || undefined;
|
|
185
226
|
}
|
|
186
227
|
|
|
187
228
|
const policyProtected = $derived([...hiddenFields, ...readonlyFields]);
|
|
188
229
|
|
|
189
|
-
function handleSubmit() {
|
|
230
|
+
function handleSubmit(event?: Event) {
|
|
190
231
|
const draft = {
|
|
191
232
|
name,
|
|
192
233
|
description,
|
|
@@ -196,12 +237,16 @@ function handleSubmit() {
|
|
|
196
237
|
estimatedLabourMinutes,
|
|
197
238
|
defaultOperationId,
|
|
198
239
|
tags,
|
|
240
|
+
...(showSkuCode ? { skuCode } : {}),
|
|
199
241
|
};
|
|
200
242
|
// A field the reader left as it was keeps its stored value exactly (a tag
|
|
201
243
|
// with a comma, a price this form cannot express); the name is always checked.
|
|
202
244
|
const initialDraft = assemblyFormDraft(assembly, exponent);
|
|
203
245
|
const untouched = (Object.keys(draft) as AssemblyFormField[]).filter(
|
|
204
|
-
(field) =>
|
|
246
|
+
(field) =>
|
|
247
|
+
field !== 'name' &&
|
|
248
|
+
field !== 'skuCode' &&
|
|
249
|
+
draft[field] === initialDraft[field],
|
|
205
250
|
);
|
|
206
251
|
const protectedFields = [...policyProtected, ...untouched];
|
|
207
252
|
const result = validateAssemblyForm(draft, policyProtected, exponent);
|
|
@@ -214,7 +259,14 @@ function handleSubmit() {
|
|
|
214
259
|
return;
|
|
215
260
|
}
|
|
216
261
|
invalid = [];
|
|
217
|
-
|
|
262
|
+
const form = (event?.currentTarget ?? event?.target) as
|
|
263
|
+
| HTMLFormElement
|
|
264
|
+
| null
|
|
265
|
+
| undefined;
|
|
266
|
+
onsubmit(
|
|
267
|
+
keepProtectedFields(checked.values, assembly, protectedFields),
|
|
268
|
+
new FormData(form instanceof HTMLFormElement ? form : undefined),
|
|
269
|
+
);
|
|
218
270
|
}
|
|
219
271
|
</script>
|
|
220
272
|
|
|
@@ -270,6 +322,29 @@ function handleSubmit() {
|
|
|
270
322
|
</div>
|
|
271
323
|
{/if}
|
|
272
324
|
|
|
325
|
+
{#if shown('skuCode')}
|
|
326
|
+
<div class="field">
|
|
327
|
+
<label for="{uid}-sku-code">
|
|
328
|
+
{t(M['manufacturing.assembly_form.sku_code'])}<span class="required" aria-hidden="true">*</span>
|
|
329
|
+
</label>
|
|
330
|
+
<Input
|
|
331
|
+
id="{uid}-sku-code"
|
|
332
|
+
name="skuCode"
|
|
333
|
+
type="text"
|
|
334
|
+
autocomplete="off"
|
|
335
|
+
bind:value={skuCode}
|
|
336
|
+
required
|
|
337
|
+
readonly={readonlyFields.includes('skuCode')}
|
|
338
|
+
disabled={loading}
|
|
339
|
+
aria-invalid={errors.some((error) => error.field === 'skuCode') ? 'true' : undefined}
|
|
340
|
+
aria-describedby={describedBy('skuCode', `${uid}-sku-code-hint`)}
|
|
341
|
+
/>
|
|
342
|
+
<span class="hint" id="{uid}-sku-code-hint">
|
|
343
|
+
{t(M['manufacturing.assembly_form.sku_code_help'])}
|
|
344
|
+
</span>
|
|
345
|
+
</div>
|
|
346
|
+
{/if}
|
|
347
|
+
|
|
273
348
|
{#if shown('category')}
|
|
274
349
|
<div class="field">
|
|
275
350
|
<label for="{uid}-category">{t(M['manufacturing.assembly_form.category'])}</label>
|
|
@@ -366,6 +441,12 @@ function handleSubmit() {
|
|
|
366
441
|
</div>
|
|
367
442
|
{/if}
|
|
368
443
|
|
|
444
|
+
{@render extraFields?.()}
|
|
445
|
+
|
|
446
|
+
{#if hostErrors.form}
|
|
447
|
+
<p class="errors" role="alert">{hostErrors.form}</p>
|
|
448
|
+
{/if}
|
|
449
|
+
|
|
369
450
|
{#if errors.length > 0}
|
|
370
451
|
<div class="errors" role="alert">
|
|
371
452
|
<ul>
|
|
@@ -1,9 +1,14 @@
|
|
|
1
|
-
import
|
|
1
|
+
import type { Snippet } from 'svelte';
|
|
2
|
+
import { type AssemblyFormErrors, type AssemblyFormField, type AssemblyFormInitial, type AssemblyFormValues, type OperationView } from '../types.js';
|
|
2
3
|
export interface AssemblyFormProps {
|
|
3
4
|
/** The assembly being edited; omit or pass null to add one. */
|
|
4
5
|
assembly?: AssemblyFormInitial | null;
|
|
5
|
-
/**
|
|
6
|
-
|
|
6
|
+
/**
|
|
7
|
+
* Invoked with trimmed, checked values, and the form's `FormData` (every
|
|
8
|
+
* named control, including those from `extraFields`). The form never
|
|
9
|
+
* persists.
|
|
10
|
+
*/
|
|
11
|
+
onsubmit: (values: AssemblyFormValues, formData: FormData) => void;
|
|
7
12
|
/** Invoked when the form is canceled; omit to hide the cancel button. */
|
|
8
13
|
oncancel?: () => void;
|
|
9
14
|
/** Blocks input and submission while the host saves. */
|
|
@@ -16,6 +21,12 @@ export interface AssemblyFormProps {
|
|
|
16
21
|
hiddenFields?: readonly AssemblyFormField[];
|
|
17
22
|
/** Fields the reader may see but not change: rendered read-only. */
|
|
18
23
|
readonlyFields?: readonly AssemblyFormField[];
|
|
24
|
+
/** Shows the part number (SKU code) field, required when shown. */
|
|
25
|
+
showSkuCode?: boolean;
|
|
26
|
+
/** Host-reported errors: a message under a field, or for the whole form. */
|
|
27
|
+
errors?: AssemblyFormErrors;
|
|
28
|
+
/** Host fields rendered inside the form, before its actions. */
|
|
29
|
+
extraFields?: Snippet;
|
|
19
30
|
}
|
|
20
31
|
declare const AssemblyForm: import("svelte").Component<AssemblyFormProps, {}, "">;
|
|
21
32
|
type AssemblyForm = ReturnType<typeof AssemblyForm>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssemblyForm.svelte.d.ts","sourceRoot":"","sources":["../../../src/svelte/components/AssemblyForm.svelte.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"AssemblyForm.svelte.d.ts","sourceRoot":"","sources":["../../../src/svelte/components/AssemblyForm.svelte.ts"],"names":[],"mappings":"AA6BA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEtC,OAAO,EACL,KAAK,kBAAkB,EACvB,KAAK,iBAAiB,EACtB,KAAK,mBAAmB,EAExB,KAAK,kBAAkB,EAIvB,KAAK,aAAa,EAEnB,MAAM,aAAa,CAAC;AAGrB,MAAM,WAAW,iBAAiB;IAChC,+DAA+D;IAC/D,QAAQ,CAAC,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACtC;;;;OAIG;IACH,QAAQ,EAAE,CAAC,MAAM,EAAE,kBAAkB,EAAE,QAAQ,EAAE,QAAQ,KAAK,IAAI,CAAC;IACnE,yEAAyE;IACzE,QAAQ,CAAC,EAAE,MAAM,IAAI,CAAC;IACtB,wDAAwD;IACxD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,yEAAyE;IACzE,UAAU,CAAC,EAAE,SAAS,aAAa,EAAE,CAAC;IACtC,8DAA8D;IAC9D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,mDAAmD;IACnD,YAAY,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC5C,oEAAoE;IACpE,cAAc,CAAC,EAAE,SAAS,iBAAiB,EAAE,CAAC;IAC9C,mEAAmE;IACnE,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,4EAA4E;IAC5E,MAAM,CAAC,EAAE,kBAAkB,CAAC;IAC5B,gEAAgE;IAChE,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAuVD,QAAA,MAAM,YAAY,uDAAwC,CAAC;AAC3D,KAAK,YAAY,GAAG,UAAU,CAAC,OAAO,YAAY,CAAC,CAAC;AACpD,eAAe,YAAY,CAAC"}
|