@happyvertical/smrt-inventory 0.57.36 → 0.57.38

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.
@@ -2,7 +2,7 @@
2
2
  "version": "1.0.0",
3
3
  "timestamp": 0,
4
4
  "packageName": "@happyvertical/smrt-inventory",
5
- "packageVersion": "0.57.36",
5
+ "packageVersion": "0.57.38",
6
6
  "objects": {
7
7
  "@happyvertical/smrt-inventory:InventoryLocationCollection": {
8
8
  "name": "inventorylocationcollection",
@@ -3,13 +3,13 @@
3
3
  "sensitiveFieldsExcluded": true,
4
4
  "generatedAt": "1970-01-01T00:00:00.000Z",
5
5
  "packageName": "@happyvertical/smrt-inventory",
6
- "packageVersion": "0.57.36",
6
+ "packageVersion": "0.57.38",
7
7
  "sourceManifestPath": "dist/manifest.json",
8
8
  "agentDocPath": "AGENTS.md",
9
9
  "sourceHashes": {
10
- "manifest": "351b814c9de6981916c85863ffab5192826a7dc9f3329a09e7f2f4c7cc33fc03",
11
- "packageJson": "5e466522e29b0d30c36eb4533f1d9f2200deb83a8c1abbf5255a147302326abc",
12
- "agents": "4e963e1bc75c7fbf383eb7d31ef6ac37bcfb08b73bd26871c70817997a3c1f29"
10
+ "manifest": "765e1fea854af3eeabadc46c800bb924c6a6f7c229e724c83e85b45de31ca2b6",
11
+ "packageJson": "9e9d24d0a0982dab43bd5929cfd364dca95bbd1834ea3ff75334dfbc1ad8006b",
12
+ "agents": "6129c749e8f78b68280151bbacd0d1a2577499de4c423c2ed1a97f02a79b81ea"
13
13
  },
14
14
  "exports": [
15
15
  ".",
@@ -2254,7 +2254,7 @@
2254
2254
  "polymorphicAssociations": 0,
2255
2255
  "uuidColumns": 56
2256
2256
  },
2257
- "agentDoc": "# @happyvertical/smrt-inventory\n\nMulti-location stock tracking. Strictly industry-neutral — the same primitives serve apparel, furniture, automotive, CPG, electronics, and any other vertical that counts discrete units across locations.\n\n## Models\n\n| Model | Purpose |\n|---|---|\n| _(catalog shapes — `Product`, `Material`, `ProductVariant`, `Sku` — live in `@happyvertical/smrt-products`)_ | Sku is the smallest sellable / countable unit; its `attributes` JSON carries axis-value pins. ProductVariant is the per-product axis declaration. Import either from `@happyvertical/smrt-products` directly. |\n| `InventoryLocation` | Warehouse / factory / retail / in-transit / virtual. Open-ended `kind` string. Optional `placeId` references `@happyvertical/smrt-places`. `conflictColumns: ['code', 'tenant_id']`. |\n| `StockLevel` | Materialized `qty` for a `(skuId, locationId, state)` tuple. Upserted in place. **Mutated only by `StockService`.** States: `available`, `allocated`, `wip`, `qc_hold`, `damaged`. |\n| `StockMovement` | Append-only audit log. Every `StockService` mutation writes one (or two for `transfer`). `sourceType` + `sourceId` carry cross-package attribution. |\n\n| `Lot` | A traceable batch or serial (`inventory_lots`). `conflictColumns: ['identity_key','tenant_id']`, every create insert-only. **Written only by `LotService`.** |\n| `LotStockLevel` | Per-lot balance for `(lotId, locationId, state)` (`inventory_lot_stock_levels`). **Mutated only by `StockService`** when `lotId` is passed. |\n| `LotUsage` | A lot used by a consumer: the trace edge. Never deleted; `status: 'unlinked'` after a correction. `consumerType: 'Lot'` marks assembly lineage. |\n| `LotCorrection` | Append-only correction trail (`conflictColumns: ['id']`); reason mandatory. |\n| `LotDocument` | Asset attached to a lot (`assetId` is a cross-package ref); detached, never deleted. |\n\nAll inventory models (`InventoryLocation`, `StockLevel`, `StockMovement`, and the lot models) use `@TenantScoped({ mode: 'optional' })` + nullable `tenantId` so they can be used either tenant-scoped or globally. The catalog shapes (`Product`, `Material`, `ProductVariant`, `Sku`) live in `@happyvertical/smrt-products` and carry their own tenant decoration there.\n\n## StockService — the only sanctioned way to mutate stock\n\n```typescript\nimport { createStockService } from '@happyvertical/smrt-inventory';\n\nconst service = await createStockService({ db });\nawait service.receive(skuId, locationId, qty, { sourceType, sourceId });\nawait service.reserve(skuId, locationId, qty, { sourceType, sourceId });\nawait service.release(skuId, locationId, qty, { sourceType, sourceId });\nawait service.fulfill(skuId, locationId, qty, { sourceType, sourceId });\nawait service.transfer(skuId, fromLocId, toLocId, qty, { sourceType, sourceId });\nawait service.adjust(skuId, locationId, delta, { sourceType, sourceId });\n```\n\n| Method | Behavior | Movement reason |\n|---|---|---|\n| `receive` | +qty available — purchase receipt, return, production produce | `receipt` |\n| `reserve` | available → allocated. Throws `InsufficientStockError` on overdraw | `reservation` |\n| `release` | allocated → available (order cancel) | `release` |\n| `fulfill` | -qty allocated. Stock leaves the building | `fulfillment` |\n| `transfer` | move stock between locations (writes two movements) | `transfer_out`, `transfer_in` |\n| `adjust` | signed delta — cycle counts and one-off corrections | `adjustment` |\n\nAll methods reject zero / negative / non-finite quantities except `adjust`, which accepts non-zero signed deltas. Negative deltas that would drive a state below zero throw `InsufficientStockError`.\n\n## LotService — lots and serials (additive, #3459)\n\n`createLotService({ db })` (with `withTransaction`, same pattern as `StockService`) is the only writer of the lot tables. `receiveLot` records identity only and moves no stock; compose with `StockService` in one transaction via `createLotService({ db: tx.db })`. Passing `lotId` to a `StockService` mutation applies the same deltas to `LotStockLevel`, enforces non-negative at lot level (`InsufficientStockError.lotId`), validates the lot (`LotNotFoundError`, `LotMismatchError` when `lot.skuId` differs), and stamps `StockMovement.lotId`.\n\n- `Lot.identityKey` is the only DB-unique key: `u:<kind>:<sku>:<SEARCHKEY>` for unique lots and all serials (hashed if over 160 chars), `k:<idempotencyKey>` for idempotent receipts, else a random `r:` key. So a lot number repeats by default (one supplier lot, two receipts); `DuplicateLotError` only for unique ones.\n- Corrections (`correctLotNumber`, `correctAttributes`, `setStatus`, `unlinkUsage`, `detachDocument`) require a reason, are refused when nothing changes, and write a `LotCorrection`. They `save()` the lot so concurrent changes conflict on its revision; retry the loser.\n- `recordUsage` is idempotent per consumer; `exclusive` (default for serials) throws `LotInUseError` for a second consumer.\n- `traceForward(lotId)` / `traceBack(consumerType, consumerId)` follow `consumerType: 'Lot'` usages with a path-based cycle guard and `depth` (default 10).\n- `StockService` does not consult `lot.status`: callers decide what a quarantined or void lot may do. A repeated `idempotencyKey` returns the first lot even if the other fields differ; a repeated `recordUsage` for the same consumer returns the existing usage unchanged (its `qty` is ignored).\n- No authorization inside the package; callers authorize. Nothing assumes an id format, so a consumer's data migration may insert rows with its own ids.\n- Schema upgrade is additive: five new tables and one nullable column, `inventory_stock_movements.lot_id`. `StockLevel`'s unique key is unchanged. Runtime never creates schema: generate and apply the normal migration first (`smrt doctor --db`); no data copy is needed.\n\n## Opt-in DispatchBus hooks\n\nOff by default. Wire them up explicitly in the application's `smrt.ts`:\n\n```typescript\nimport { installInventoryDispatchHandlers } from '@happyvertical/smrt-inventory';\n\nconst handlers = await installInventoryDispatchHandlers({\n dispatchBus: bus,\n db, // or stockService: existingService\n});\n```\n\nThis subscribes to:\n- `contract:created` → calls `service.reserve()` for every line inside one `stockService.withTransaction(...)`, attributed to `('Contract', payload.contractId)`\n- `fulfillment:shipped` → calls `service.fulfill()` for every line inside one `stockService.withTransaction(...)`, attributed to `('Fulfillment', payload.fulfillmentId)`\n\nBoth handlers are atomic across lines: a shortfall on line N rolls back lines 1..N-1 so the event is all-or-nothing. Without this guarantee, `DispatchBus` would only log the async handler error and a partially-reserved (or partially-fulfilled) contract would have no compensating event to fix it.\n\nPer-handler toggles: `installContractReserved`, `installFulfillmentShipped`. The `production_order:posted` hook is deliberately not installed here — it depends on the BOM model and ships in `@happyvertical/smrt-manufacturing` (issue #1250).\n\n## Schema migration (Phase 1 release)\n\nThe `Sku` model moved out of this package and into `@happyvertical/smrt-products`. Previously it lived in this package's `inventory_skus` table; it now lives in `product_skus` over there.\n\n**Upgrade procedure** for deployed consumers:\n\n1. **Let the framework create the destination table first.** Boot the new version once with `@happyvertical/smrt-products` registered in your `SmrtClassOptions`; the lazy `syncSchema` path will create `product_skus` with the right primary key, NOT NULL, UNIQUE (`code`, `tenant_id`), and indexes — they're derived from the `Sku` model decorators and would be stripped by a raw `CREATE TABLE AS SELECT`.\n\n2. **Idempotently copy rows across.** SQLite + Postgres:\n\n ```sql\n BEGIN;\n INSERT INTO product_skus (\n id, slug, context, created_at, updated_at,\n tenant_id, product_id, code, barcode, name,\n attributes, weight_grams, parent_sku_id, active\n )\n SELECT\n id, slug, context, created_at, updated_at,\n tenant_id, product_id, code, barcode, name,\n attributes, weight_grams, parent_sku_id, active\n FROM inventory_skus\n WHERE NOT EXISTS (\n SELECT 1 FROM product_skus p WHERE p.id = inventory_skus.id\n );\n COMMIT;\n ```\n\n3. **Drop the legacy table** once you've verified row counts match:\n\n ```sql\n DROP TABLE IF EXISTS inventory_skus;\n ```\n\n`StockLevel.skuId` and `StockMovement.skuId` carry plain string ids that still resolve to the same rows after the rename, so no inventory data has to move.\n\n## Gotchas\n\n- **Movements are append-only.** The materialized `StockLevel` row is derived state; the `StockMovement` ledger is the source of truth. Never let CRUD UIs expose update/delete on the movement table. If you find yourself wanting to \"fix\" a movement row, write a compensating `adjust()` call instead.\n- **Never call `StockLevel.create()` or `save()` directly.** Going around `StockService` silently desyncs the audit log and breaks cycle counts.\n- **Cross-industry constraint.** This package's vocabulary stays generic: `InventoryLocation`, `StockLevel`, `StockMovement`. Apparel-specific concepts (`Style`, `Makeup`, `Colorway`, fashion `Season`, tech-pack metadata) and their analogues in furniture / automotive / CPG live in the relevant template package, never here. PRs that introduce industry vocabulary should be rejected.\n- **Cross-package references are plain strings.** `skuId`, `placeId`, `sourceId` — all plain string ids, never `@foreignKey()`. Inventory's stock-motion logic only ever reads StockLevel/StockMovement; it doesn't follow `skuId` back to the catalog's Sku table, so the layering stays loose.\n- **`conflictColumns` include `tenant_id`** on `InventoryLocation` and `StockLevel`. NULL-matching semantics (`(code, NULL) IS NOT DISTINCT FROM (code, NULL)`) are handled by `@happyvertical/sql >= 0.74.0` natively, so two saves with the same `(code, NULL)` tuple correctly merge in place. Pass `nullsDistinct: true` at the sql layer to opt back into NULL-distinct semantics.\n- **Atomic per-method, transactional across composition.** Each `StockService` mutation (`receive` / `reserve` / `release` / `fulfill` / `transfer` / `adjust`) wraps every write in a single `db.transaction(...)` (via `@happyvertical/sql >= 0.74.0`). Partial failure rolls the whole call back — level writes and the matching `StockMovement` audit row commit together or not at all. `transfer` writes both legs (source decrement, destination increment, and both audit rows) inside one tx, so a failure mid-`transfer` is fully reverted.\n Callers composing multiple `StockService` calls into one logical unit (e.g. consuming materials line-by-line for a production order) should wrap them in `await stockService.withTransaction(async (tx) => { ... })` — `tx` is a tx-bound `StockService` with the same public API; mutation calls inside the callback share one transaction and either all commit or all roll back.\n If the underlying SQL adapter does not expose `transaction()` (extremely rare — all four built-in `@happyvertical/sql >= 0.74.0` adapters implement it), the service degrades to non-atomic serial writes and emits a one-time `console.warn`.\n- **Concurrent reservations: tightened, not bulletproof.** `@happyvertical/sql >= 0.74.0` serialises null-aware *upserts* via a per-key in-process lock (SQLite) or advisory lock (Postgres). That lock fixed the row-creation race (issue #1246) — two concurrent `create()` calls on the same conflict-column tuple no longer race the underlying `INSERT ... ON CONFLICT`. The first `StockLevel` row for a key is now created insert-only (#3204): a concurrent first write fails on the unique key and its transaction rolls back (retry it) instead of upserting over the winner's qty. It does NOT serialise the read-modify-write compound that `reserve` / `fulfill` / `transfer` / `adjust` perform on an existing row: each method reads the current level (`SELECT`), computes the new value in JS, then writes it back (`UPDATE` via `save()` on the loaded row). The whole compound is inside one `db.transaction(...)` from round-3, so the level write and audit row commit together — but two concurrent transactions on the same `(skuId, locationId)` can each see the same starting balance, compute the same decrement, and double-spend. Awaited (serial) calls always behave correctly. Use a job queue (e.g. `@happyvertical/smrt-jobs`) or your own mutex when you need hard atomicity across concurrent callers. The full fix is `SELECT ... FOR UPDATE` inside the same transaction (Postgres) or upgrading the journal mode (SQLite); deferred until we see a real high-contention workload that warrants it.\n\n## Source attribution\n\nEvery `StockMovement` carries `sourceType` + `sourceId` so downstream queries can reconstruct \"what caused this movement\". Conventions used by the built-in dispatch handlers:\n\n| sourceType | Emitter | Note |\n|---|---|---|\n| `Contract` | `smrt-commerce` `contract:created` | All reservation/release/fulfilment legs caused by a contract |\n| `Fulfillment` | `smrt-commerce` `fulfillment:shipped` | Outbound shipment |\n| `PurchaseOrder` | (your code) | Inbound receipt |\n| `CycleCount` | (your code) | Adjustments from physical counts |\n| `TransferOrder` | (your code) | Both legs of a transfer |\n| `ProductionOrder` | `smrt-manufacturing` (issue #1250) | Materials consumed + finished goods produced |\n\n## Replenishment and browser components\n\n`StockService.setReorderPolicy()` is the sanctioned metadata writer for nullable\n`StockLevel.reorderPoint` / `reorderQuantity` on the available SKU/location row.\nIt does not change quantity or emit a movement. `findBelowReorderPoint()` uses\npublic tenant-filtered collection reads and strict less-than semantics.\n`StockMutationOptions.actorProfileId` propagates to every movement, including\nboth transfer legs; null retains compatibility for automation. It is a qualified\ncross-package profile reference, not an authorization decision.\n\n`src/svelte/` exports data-driven components through `./svelte`. Server callers\nown authentication and persistence callbacks; never import backend models into\nthis entry or expose ledger mutations as CRUD. Package `typecheck` includes\nSvelte checks and `test` includes DOM component tests. See README for the public\nprops, service contracts, and additive schema upgrade requirements.\n",
2257
+ "agentDoc": "# @happyvertical/smrt-inventory\n\nMulti-location stock tracking. Strictly industry-neutral — the same primitives serve apparel, furniture, automotive, CPG, electronics, and any other vertical that counts discrete units across locations.\n\n## Models\n\n| Model | Purpose |\n|---|---|\n| _(catalog shapes — `Product`, `Material`, `ProductVariant`, `Sku` — live in `@happyvertical/smrt-products`)_ | Sku is the smallest sellable / countable unit; its `attributes` JSON carries axis-value pins. ProductVariant is the per-product axis declaration. Import either from `@happyvertical/smrt-products` directly. |\n| `InventoryLocation` | Warehouse / factory / retail / in-transit / virtual. Open-ended `kind` string. Optional `placeId` references `@happyvertical/smrt-places`. `conflictColumns: ['code', 'tenant_id']`. |\n| `StockLevel` | Materialized `qty` for a `(skuId, locationId, state)` tuple. Upserted in place. **Mutated only by `StockService`.** States: `available`, `allocated`, `wip`, `qc_hold`, `damaged`. |\n| `StockMovement` | Append-only audit log. Every `StockService` mutation writes one (or two for `transfer`). `sourceType` + `sourceId` carry cross-package attribution. |\n\n| `Lot` | A traceable batch or serial (`inventory_lots`). `conflictColumns: ['identity_key','tenant_id']`, every create insert-only. **Written only by `LotService`.** |\n| `LotStockLevel` | Per-lot balance for `(lotId, locationId, state)` (`inventory_lot_stock_levels`). **Mutated only by `StockService`** when `lotId` is passed. |\n| `LotUsage` | A lot used by a consumer: the trace edge. Never deleted; `status: 'unlinked'` after a correction. `consumerType: 'Lot'` marks assembly lineage. |\n| `LotCorrection` | Append-only correction trail (`conflictColumns: ['id']`); reason mandatory. |\n| `LotDocument` | Asset attached to a lot (`assetId` is a cross-package ref); detached, never deleted. |\n\nAll inventory models (`InventoryLocation`, `StockLevel`, `StockMovement`, and the lot models) use `@TenantScoped({ mode: 'optional' })` + nullable `tenantId` so they can be used either tenant-scoped or globally. The catalog shapes (`Product`, `Material`, `ProductVariant`, `Sku`) live in `@happyvertical/smrt-products` and carry their own tenant decoration there.\n\n## StockService — the only sanctioned way to mutate stock\n\n```typescript\nimport { createStockService } from '@happyvertical/smrt-inventory';\n\nconst service = await createStockService({ db });\nawait service.receive(skuId, locationId, qty, { sourceType, sourceId });\nawait service.reserve(skuId, locationId, qty, { sourceType, sourceId });\nawait service.release(skuId, locationId, qty, { sourceType, sourceId });\nawait service.fulfill(skuId, locationId, qty, { sourceType, sourceId });\nawait service.transfer(skuId, fromLocId, toLocId, qty, { sourceType, sourceId });\nawait service.adjust(skuId, locationId, delta, { sourceType, sourceId });\n```\n\n| Method | Behavior | Movement reason |\n|---|---|---|\n| `receive` | +qty available — purchase receipt, return, production produce | `receipt` |\n| `reserve` | available → allocated. Throws `InsufficientStockError` on overdraw | `reservation` |\n| `release` | allocated → available (order cancel) | `release` |\n| `fulfill` | -qty allocated. Stock leaves the building | `fulfillment` |\n| `transfer` | move stock between locations (writes two movements) | `transfer_out`, `transfer_in` |\n| `adjust` | signed delta — cycle counts and one-off corrections | `adjustment` |\n\nAll methods reject zero / negative / non-finite quantities except `adjust`, which accepts non-zero signed deltas. Negative deltas that would drive a state below zero throw `InsufficientStockError`.\n\n## LotService — lots and serials (additive, #3459)\n\n`createLotService({ db })` (with `withTransaction`, same pattern as `StockService`) is the only writer of the lot tables. `receiveLot` records identity only and moves no stock; compose with `StockService` in one transaction via `createLotService({ db: tx.db })`. Passing `lotId` to a `StockService` mutation applies the same deltas to `LotStockLevel`, enforces non-negative at lot level (`InsufficientStockError.lotId`), validates the lot (`LotNotFoundError`, `LotMismatchError` when `lot.skuId` differs), and stamps `StockMovement.lotId`.\n\n- `Lot.identityKey` is the only DB-unique key: `u:<kind>:<sku>:<SEARCHKEY>` for unique lots and all serials (hashed if over 160 chars), `k:<idempotencyKey>` for idempotent receipts, else a random `r:` key. So a lot number repeats by default (one supplier lot, two receipts); `DuplicateLotError` only for unique ones.\n- Corrections (`correctLotNumber`, `correctAttributes`, `setStatus`, `unlinkUsage`, `detachDocument`) require a reason, are refused when nothing changes, and write a `LotCorrection`. They `save()` the lot so concurrent changes conflict on its revision; retry the loser.\n- `recordUsage` is idempotent per consumer; `exclusive` (default for serials) throws `LotInUseError` for a second consumer.\n- `traceForward(lotId)` / `traceBack(consumerType, consumerId)` follow `consumerType: 'Lot'` usages with a path-based cycle guard and `depth` (default 10).\n- `StockService` does not consult `lot.status`: callers decide what a quarantined or void lot may do. A repeated `idempotencyKey` returns the first lot even if the other fields differ; a repeated `recordUsage` for the same consumer returns the existing usage unchanged (its `qty` is ignored).\n- No authorization inside the package; callers authorize. Nothing assumes an id format, so a consumer's data migration may insert rows with its own ids.\n- Schema upgrade is additive: five new tables and one nullable column, `inventory_stock_movements.lot_id`. `StockLevel`'s unique key is unchanged. Runtime never creates schema: generate and apply the normal migration first (`smrt doctor --db`); no data copy is needed.\n\n## Opt-in DispatchBus hooks\n\nOff by default. Wire them up explicitly in the application's `smrt.ts`:\n\n```typescript\nimport { installInventoryDispatchHandlers } from '@happyvertical/smrt-inventory';\n\nconst handlers = await installInventoryDispatchHandlers({\n dispatchBus: bus,\n db, // or stockService: existingService\n});\n```\n\nThis subscribes to:\n- `contract:created` → calls `service.reserve()` for every line inside one `stockService.withTransaction(...)`, attributed to `('Contract', payload.contractId)`\n- `fulfillment:shipped` → calls `service.fulfill()` for every line inside one `stockService.withTransaction(...)`, attributed to `('Fulfillment', payload.fulfillmentId)`\n\nBoth handlers are atomic across lines: a shortfall on line N rolls back lines 1..N-1 so the event is all-or-nothing. Without this guarantee, `DispatchBus` would only log the async handler error and a partially-reserved (or partially-fulfilled) contract would have no compensating event to fix it.\n\nPer-handler toggles: `installContractReserved`, `installFulfillmentShipped`. The `production_order:posted` hook is deliberately not installed here — it depends on the BOM model and ships in `@happyvertical/smrt-manufacturing` (issue #1250).\n\n## Schema migration (Phase 1 release)\n\nThe `Sku` model moved out of this package and into `@happyvertical/smrt-products`. Previously it lived in this package's `inventory_skus` table; it now lives in `product_skus` over there.\n\n**Upgrade procedure** for deployed consumers:\n\n1. **Create the destination table with the explicit migration workflow first.** Runtime never creates application schema, so booting the new version does not create `product_skus`. With `@happyvertical/smrt-products` registered, generate and apply the normal migration (`smrt db:status`, then `smrt db:migrate`) and confirm `smrt db:status --parity` is clean. That creates `product_skus` with the right primary key, NOT NULL, UNIQUE (`code`, `tenant_id`), and indexes derived from the `Sku` model decorators; a raw `CREATE TABLE AS SELECT` would strip them. Do this before step 2 so the keys and indexes exist before any rows are copied.\n\n2. **Idempotently copy rows across.** SQLite + Postgres:\n\n ```sql\n BEGIN;\n INSERT INTO product_skus (\n id, slug, context, created_at, updated_at,\n tenant_id, product_id, code, barcode, name,\n attributes, weight_grams, parent_sku_id, active\n )\n SELECT\n id, slug, context, created_at, updated_at,\n tenant_id, product_id, code, barcode, name,\n attributes, weight_grams, parent_sku_id, active\n FROM inventory_skus\n WHERE NOT EXISTS (\n SELECT 1 FROM product_skus p WHERE p.id = inventory_skus.id\n );\n COMMIT;\n ```\n\n3. **Drop the legacy table** once you've verified row counts match:\n\n ```sql\n DROP TABLE IF EXISTS inventory_skus;\n ```\n\n`StockLevel.skuId` and `StockMovement.skuId` carry plain string ids that still resolve to the same rows after the rename, so no inventory data has to move.\n\n## Gotchas\n\n- **Movements are append-only.** The materialized `StockLevel` row is derived state; the `StockMovement` ledger is the source of truth. Never let CRUD UIs expose update/delete on the movement table. If you find yourself wanting to \"fix\" a movement row, write a compensating `adjust()` call instead.\n- **Never call `StockLevel.create()` or `save()` directly.** Going around `StockService` silently desyncs the audit log and breaks cycle counts.\n- **Cross-industry constraint.** This package's vocabulary stays generic: `InventoryLocation`, `StockLevel`, `StockMovement`. Apparel-specific concepts (`Style`, `Makeup`, `Colorway`, fashion `Season`, tech-pack metadata) and their analogues in furniture / automotive / CPG live in the relevant template package, never here. PRs that introduce industry vocabulary should be rejected.\n- **Cross-package references are plain strings.** `skuId`, `placeId`, `sourceId` — all plain string ids, never `@foreignKey()`. Inventory's stock-motion logic only ever reads StockLevel/StockMovement; it doesn't follow `skuId` back to the catalog's Sku table, so the layering stays loose.\n- **`conflictColumns` include `tenant_id`** on `InventoryLocation` and `StockLevel`. NULL-matching semantics (`(code, NULL) IS NOT DISTINCT FROM (code, NULL)`) are handled by `@happyvertical/sql >= 0.74.0` natively, so two saves with the same `(code, NULL)` tuple correctly merge in place. Pass `nullsDistinct: true` at the sql layer to opt back into NULL-distinct semantics.\n- **Atomic per-method, transactional across composition.** Each `StockService` mutation (`receive` / `reserve` / `release` / `fulfill` / `transfer` / `adjust`) wraps every write in a single `db.transaction(...)` (via `@happyvertical/sql >= 0.74.0`). Partial failure rolls the whole call back — level writes and the matching `StockMovement` audit row commit together or not at all. `transfer` writes both legs (source decrement, destination increment, and both audit rows) inside one tx, so a failure mid-`transfer` is fully reverted.\n Callers composing multiple `StockService` calls into one logical unit (e.g. consuming materials line-by-line for a production order) should wrap them in `await stockService.withTransaction(async (tx) => { ... })` — `tx` is a tx-bound `StockService` with the same public API; mutation calls inside the callback share one transaction and either all commit or all roll back.\n If the underlying SQL adapter does not expose `transaction()` (extremely rare — all four built-in `@happyvertical/sql >= 0.74.0` adapters implement it), the service degrades to non-atomic serial writes and emits a one-time `console.warn`.\n- **Concurrent reservations: tightened, not bulletproof.** `@happyvertical/sql >= 0.74.0` serialises null-aware *upserts* via a per-key in-process lock (SQLite) or advisory lock (Postgres). That lock fixed the row-creation race (issue #1246) — two concurrent `create()` calls on the same conflict-column tuple no longer race the underlying `INSERT ... ON CONFLICT`. The first `StockLevel` row for a key is now created insert-only (#3204): a concurrent first write fails on the unique key and its transaction rolls back (retry it) instead of upserting over the winner's qty. It does NOT serialise the read-modify-write compound that `reserve` / `fulfill` / `transfer` / `adjust` perform on an existing row: each method reads the current level (`SELECT`), computes the new value in JS, then writes it back (`UPDATE` via `save()` on the loaded row). The whole compound is inside one `db.transaction(...)` from round-3, so the level write and audit row commit together — but two concurrent transactions on the same `(skuId, locationId)` can each see the same starting balance, compute the same decrement, and double-spend. Awaited (serial) calls always behave correctly. Use a job queue (e.g. `@happyvertical/smrt-jobs`) or your own mutex when you need hard atomicity across concurrent callers. The full fix is `SELECT ... FOR UPDATE` inside the same transaction (Postgres) or upgrading the journal mode (SQLite); deferred until we see a real high-contention workload that warrants it.\n\n## Source attribution\n\nEvery `StockMovement` carries `sourceType` + `sourceId` so downstream queries can reconstruct \"what caused this movement\". Conventions used by the built-in dispatch handlers:\n\n| sourceType | Emitter | Note |\n|---|---|---|\n| `Contract` | `smrt-commerce` `contract:created` | All reservation/release/fulfilment legs caused by a contract |\n| `Fulfillment` | `smrt-commerce` `fulfillment:shipped` | Outbound shipment |\n| `PurchaseOrder` | (your code) | Inbound receipt |\n| `CycleCount` | (your code) | Adjustments from physical counts |\n| `TransferOrder` | (your code) | Both legs of a transfer |\n| `ProductionOrder` | `smrt-manufacturing` (issue #1250) | Materials consumed + finished goods produced |\n\n## Replenishment and browser components\n\n`StockService.setReorderPolicy()` is the sanctioned metadata writer for nullable\n`StockLevel.reorderPoint` / `reorderQuantity` on the available SKU/location row.\nIt does not change quantity or emit a movement. `findBelowReorderPoint()` uses\npublic tenant-filtered collection reads and strict less-than semantics.\n`StockMutationOptions.actorProfileId` propagates to every movement, including\nboth transfer legs; null retains compatibility for automation. It is a qualified\ncross-package profile reference, not an authorization decision.\n\n`src/svelte/` exports data-driven components through `./svelte`. Server callers\nown authentication and persistence callbacks; never import backend models into\nthis entry or expose ledger mutations as CRUD. Package `typecheck` includes\nSvelte checks and `test` includes DOM component tests. See README for the public\nprops, service contracts, and additive schema upgrade requirements.\n",
2258
2258
  "recipes": [
2259
2259
  {
2260
2260
  "id": "inventory.stock",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@happyvertical/smrt-inventory",
3
- "version": "0.57.36",
3
+ "version": "0.57.38",
4
4
  "description": "Multi-location stock tracking for the SMRT framework — Sku, InventoryLocation, StockLevel, StockMovement, lot and serial tracking, and stock-mutation and lot services",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -24,14 +24,14 @@
24
24
  }
25
25
  },
26
26
  "dependencies": {
27
- "@happyvertical/logger": "^0.109.0",
28
- "@happyvertical/smrt-core": "0.57.36",
29
- "@happyvertical/smrt-tenancy": "0.57.36",
30
- "@happyvertical/sql": "^0.109.0",
31
- "@happyvertical/smrt-ui": "0.57.36"
27
+ "@happyvertical/logger": "^0.110.0",
28
+ "@happyvertical/smrt-core": "0.57.38",
29
+ "@happyvertical/smrt-tenancy": "0.57.38",
30
+ "@happyvertical/sql": "^0.110.0",
31
+ "@happyvertical/smrt-ui": "0.57.38"
32
32
  },
33
33
  "devDependencies": {
34
- "@happyvertical/smrt-vitest": "0.57.36",
34
+ "@happyvertical/smrt-vitest": "0.57.38",
35
35
  "@types/node": "24.13.6",
36
36
  "typescript": "6.0.3",
37
37
  "vite": "8.1.6",