Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(production): strict backflush review fixes and kanban scan messages
naveenkashc5b852b8a543
diff --git a/.ai/plans/2026-10-16-strict-backflush-review-fixes.md b/.ai/plans/2026-10-16-strict-backflush-review-fixes.mddeleted file mode 100644index 03154dab90..0000000000--- a/.ai/plans/2026-10-16-strict-backflush-review-fixes.md+++ /dev/null@@ -1,76 +0,0 @@-# Plan: strict backflush self-review fixes--- Date: 2026-10-16-- Spec: `.ai/specs/2026-10-14-strict-backflush.md`-- Source: the self-review of PR #1931 (branch `naveenkash/strict-backflush`), after commit `bdb26a1ab5`.-- Rule: no commit and no push until the user asks.--## Decisions--| # | Decision | Reason |-|---|----------|--------|-| D1 | The Pull From of a picked line is the source bin of its EARLIEST pick line whose destination is the line's current bin. If there is no such pick line, the Pull From is `jobMaterial.storageUnitId`. | A pick moves `jobMaterial.storageUnitId` to lineside. The pick line keeps the source, and `restoreJobMaterialSource` already treats it as the warehouse source. A later picking list takes the fullest bin, so the earliest line is the one that names the Pull From. No schema change on `jobMaterial`. |-| D2 | In SQL job completion, a picked line draws from its lineside bin first, up to its on-hand. The remainder comes from the Pull From under the strict rules. | The TypeScript path already draws picks first. The SQL path must give the same answer. |-| D3 | A short bin no longer skips its ledger row in SQL. The function raises after the loop, so the row rolls back. | Later materials on the same bin then see the refused need, and one refusal names every shortfall. |-| D4 | Both paths lock every (bin, item) key in one sorted pass before the first draw, through one SQL function. | Two completions then take locks in the same order and cannot deadlock. |-| D5 | Strict backflush applies only at a location that `getPullFromLocations` returns (an active work center and an active storage unit). | Activation exempts the other locations. Without this, a job there can never complete. |-| D6 | The dry run stops right after the strict check, before any ledger, cost or journal row. | It answers the only question it asks, and it no longer holds the journal sequence lock. |-| D7 | The jobs drawer lists only lines a backflush would refuse: stocked, not batch or serial, quantity still to issue. | The card says the next backflush will be refused. A batch or serial line, or a fully issued line, never is. |-| D8 | The card counts come from SQL counts. The drawers keep the full lists. | The parent loader re-runs on every drawer search, sort and page. |-| D9 | The materials popover follows `conventions-ui.md` "Popovers inside Drawers / Dialogs", not `modal`. | The rule is written for exactly this case and adds a visible scrollbar. |--## Tasks--### A. Picks and the Pull From (Must fix 1)-- [x] A1. Add `resolvePullFromStorageUnit` to `packages/server-functions/src/lib/strict-backflush.ts` (D1). (Since the 2026-10-19 merge with main: `apps/erp/app/modules/shared/strict-backflush.ts`.)-- [x] A2. Use it in `issueJobOperationMaterials` and in `partToOperation`.-- [x] A3. In the migration, apply D1 and D2 to `backflush_job_materials`.-- [x] A4. Add live-database tests: a partial pick at operation completion and at job completion.--### B. Locks, rounding, refused needs (risks)-- [x] B1. Add `lock_strict_backflush_bins(p_company_id, p_keys)` to the migration. Use it from SQL and TypeScript (D4).-- [x] B2. Compare and format quantities with `round(…, 5)` in SQL.-- [x] B3. Apply D3 in SQL.-- [x] B4. Scope the SQL `item` join and the storage unit name read by `companyId`.-- [x] B5. Make the missing-bin message the same in SQL and TypeScript.--### C. Exempt locations (D5)-- [x] C1. Strict applies only at a pull-from location, in TypeScript and SQL.--### D. Dry run and messages-- [x] D1. Stop the dry run after the strict check (D6).-- [x] D2. Run the inspection disposition dry run before the lot closes. Add a dry run before the scrap insert.-- [x] D3. After a production quantity is recorded, prefix a failed issue with "Units recorded, but".-- [x] D4. MES serial completion: print the label only after the server accepts.-- [x] D5. Batch phase 2: keep the refusal's 409.--### E. Activation and release gates-- [x] E1. Gate the activation in `upsertMakeMethodVersion` callers.-- [x] E2. Run the release check on every move to Ready from Draft or Planned.--### F. Settings card and drawers-- [x] F1. SQL counts for the card (D8).-- [x] F2. Jobs list semantics (D7). Use `activeJobStatuses`.-- [x] F3. A failed read shows an error, not an empty or missing row.-- [x] F4. Drawer search covers Locations and Status.-- [x] F5. Popover per D9. Fix the production `AGENTS.md` line.-- [x] F6. Minor: dead `?? true`, deep import.--### G. UI-- [x] G1. The BoM badge uses the pull-from locations from the loader, collapsed and expanded.-- [x] G2. The badge follows the item after the line's item changes.-- [x] G3. The Release dialog fails closed on a read error.-- [x] G4. Translation gaps: `BatchReleaseModal` list text, "WIP", "Default Storage Unit".--### H. Tests and docs-- [x] H1. Pure tests: `pageInMemory`, lock-key ordering.-- [x] H2. Docs: `packages/database/AGENTS.md`, `packages/server-functions/AGENTS.md`, settings and production `AGENTS.md`, `.ai/lessons.md`, the spec.-- [x] H3. Gates: Biome, typecheck (database, server-functions, erp, mes), tests, translations.--## Notes--- E1: the change-notice draft (`createChangeNoticeDraftMethod`) still freezes a Draft base as Active without the check. The freeze is a side effect of opening the notice. Release still refuses the jobs. The spec's production `AGENTS.md` section records this.-- A4: the live-database tests are written, not run. They create and delete a scratch company, and the user asks before any database write.-- Not done, by choice: one `issue` call that records production and issues materials in one transaction. It would remove the dry run and its race, but it changes 4 callers. The "Units completed, but" message covers the race for now.-- Not done, by choice: activation checks that a Pull From is set, not that its bin is active or at the right location.-- The glossary check flags 2 Hindi strings for the plural "भंडारण इकाइयाँ". The catalog's own "Storage Units" uses the same form and is flagged the same way: the checker does not know the Hindi plural.diff --git a/.ai/plans/2026-10-17-release-checks-every-path.md b/.ai/plans/2026-10-17-release-checks-every-path.mddeleted file mode 100644index a007b03af2..0000000000--- a/.ai/plans/2026-10-17-release-checks-every-path.md+++ /dev/null@@ -1,78 +0,0 @@-# Plan: the release checks on every path to Ready--- Date: 2026-10-17-- Spec: `.ai/specs/2026-10-14-strict-backflush.md`-- Request: "implement in the Kanban and verify all the places … rigorous testing" (user, 2026-10-17).-- Rule: no commit and no push until the user asks.--## Every path that sets a job to Ready--| Path | Before this plan |-|---|---|-| Release dialog / status post (`x+/job+/$jobId.status.tsx`) | `getJobReleaseReadiness`, then `releaseJobs` |-| Bulk release (`x+/job+/release.tsx`) | `getJobReleaseReadiness` + `jobReleaseProblems`, then `releaseJobs` |-| Batch release (`releaseBatchMemberJobs`) | `getJobReleaseReadiness` + `jobReleaseProblems`, then `releaseJobs` |-| Kanban scan with `autoRelease` (`api+/kanban.$id.tsx`) | none: writes `status: "Ready"` directly |-| MCP / API tool `production_updateJobStatus` | none: `updateJobStatus` writes any status |--No SQL function sets a job to Ready. The SQL writes of `'Ready'` are on `jobOperation`.--## Decisions--| # | Decision | Reason |-|---|----------|--------|-| D1 | `updateJobStatus` (the MCP / API tool) refuses a move from Draft or Planned to Ready while `jobReleaseProblems` or "nothing to make" applies. | It is the one function every caller outside the app reaches. A refusal there covers the API and any later caller. |-| D2 | `writeJobStatus` (no `@mcp` tag) is the unguarded write. `releaseJobs` and the status route call it, after their own check. | They already ran the check. A second run per job would double the reads of a bulk release. The API cannot reach a function with no `@mcp` tag. |-| D3 | The kanban scan with `autoRelease` runs `jobReleaseBlockers`, then `releaseJobs`, then one schedule run. Its outside operations go on the supplier's newest Draft PO, else a new one. | Bulk release is the closest path with no dialog: same checks, same release (requirements, MRP, Ready, outside operation purchase orders, release date). Bulk release also refuses a supplier with a Draft PO, so a planner can choose one; no one at a kanban card can, so the scan reuses it (found in the browser test). |-| D4 | A kanban job that fails the checks stays Draft and stays linked to the kanban. The scan goes to the job page with a message that names the problems. MES is not opened. | The scan is not lost, and the planner sees what to fix. Opening MES for a job that is not released would start work on it. |-| D5 | With strict backflush on at the job's location, job creation gives a line the BoM's Pull From, else the item's default storage unit (`pickMethod`). It never takes the fullest bin. | The fullest bin is a guess, not a choice. With no Pull From and no default, the line has no storage unit, so release refuses it. |--## Tasks--- [x] T1. `production.service.ts`: split `updateJobStatus` into the guarded MCP function (D1) and `writeJobStatus` (D2).-- [x] T2. Point `releaseJobs`, `planDraftJob` and the status route at `writeJobStatus`.-- [x] T3. `api+/kanban.$id.tsx`: checks, `releaseJobs`, schedule, flash message (D3, D4).-- [x] T4. `get-method`: no fullest-bin fallback under strict backflush (D5), in both places that pick a line's bin.-- [x] T5. Tests: the guard (unit), the kanban decision (unit), get-method under strict (live database).-- [x] T6. Browser: a kanban scan with a missing storage unit, with everything set, and with `autoStartJob`; the job status route; the API tool.-- [x] T7. Docs: production `AGENTS.md`, kanban rule, spec, PR description; lesson on guarding a state by its writers.-- [x] T8. Gates: Biome, typecheck (database, server-functions, erp, mes), tests, translations.--## Browser test (2026-10-19)--Stack on this worktree's own localhost ports (the portless proxy needs sudo, and another worktree held the shared ports). Company: Carbon Development, strict backflush and Prevent negative stock on.--| # | Case | Result |-|---|------|--------|-| 1 | Kanban scan, BUS-STR-001, every line has a bin | J000027 Ready, release date set, scheduled, outside operation on a new Draft PO; scan opened the operation in MES |-| 2 | Same kanban again | Collision page; no second job |-| 3 | Kanban scan, STRESS-BOM (no operations), auto-release + auto-start | J000028–J000031, J000036 stay Draft and linked; scan lands on the job, not MES |-| 4 | Kanban scan with BRG-6201's default storage unit cleared | J000033 Draft with one line without a bin; toast names BRG-6201 |-| 5 | Kanban scan after the default was restored | J000034 Ready; its outside operation went on the existing Draft PO000019 |-| 6 | Kanban scan with auto-start | J000035 started (In Progress) and opened in MES |-| 7 | Release dialog, J000033 | "Missing Storage Units: BRG-6201", Release Job disabled |-| 8 | Bulk release, J000033 | "Could not release 1: J000033 (set a Pull From storage unit on BRG-6201; …)" |-| 9 | Plain status post Ready, J000033 | Refused, stays Draft (the toast of a hand-built HTML form post was not seen) |-| 10 | API `updateJobStatus` Ready, J000033 | HTTP 400 `RELEASE_REFUSED`, names BRG-6201 |-| 11 | API `updateJobStatus` Ready, J000032 (clean) | HTTP 200, Ready |-| 12 | API Paused → Ready, J000005 | HTTP 200 (a resume is not a release); set back to Paused |-| 13 | Pause, then Resume in the job header, J000035 | Paused, then Ready |--Bugs found and fixed:-- The refusal toast never showed: `data(…, flash)` from the kanban loader was cleared by the root's `flashMiddleware`. Now `throw redirect(jobPage, flash)`.-- After the first kanban release created a Draft PO for the outside operation supplier, every later scan was refused with "choose a purchase order". The kanban release now reuses the supplier's newest Draft PO.-- Kanban collision "Remove Job" said "Job cancelled" but only unlinks the job. The copy now says "Job removed from the kanban".-- `crbn up --no-hibernate` left a stale `asleep` marker in place, and the dev servers held every request for 120 s. `crbn up` now clears it for its own stack.--Noted, not changed: an API key without Purchasing view gets "has no supplier" for an outside operation, because the check reads with the caller's permissions.--## Merge with main (2026-10-19)--Main moved the server functions into the ERP modules and unpublished `updateJobStatus`. The merge changed these names:--| Before | After |-|---|---|-| D1: `updateJobStatus` guard, `RELEASE_REFUSED` | Removed. The API's release is main's `releaseJobs` (`production_releaseJobs`), which runs `jobReleaseProblems`. `updateJobStatus` is not published. |-| D2: `writeJobStatus` | Removed. Main's `updateJobStatus` is the unpublished write. Its `source` option carries the kanban telemetry. |-| D3: `releaseKanbanJob` in `api+/kanban.$id.tsx`, `jobReleaseBlockers` | A closure inside `scanKanban` (`inventory.server.ts`). It runs `jobReleaseProblems` (main's readiness includes "nothing to make"), then `releaseCheckedJobs` with `source: "kanban"`. |-| D5: `withFullestBin` in `packages/server-functions/src/get-method` | `getMethod` in `production.service.ts`. |diff --git a/.ai/specs/2026-10-14-strict-backflush.md b/.ai/specs/2026-10-14-strict-backflush.mdindex a94226a1a8..b476297bb9 100644--- a/.ai/specs/2026-10-14-strict-backflush.md+++ b/.ai/specs/2026-10-14-strict-backflush.md@@ -56,7 +56,7 @@ Example: the BoM says "pull 10 × PART-123 from Shelf A-4". Shelf A-4 has 6 and| 3 | Which locations need a Pull From | Each location that has at least one active work center and at least one active storage unit. | Pull From is stored per location (`methodMaterial.storageUnitIds`). A location with no work center builds nothing. A location with no storage unit has no bin a line could name, so a Pull From there can never be set. || 4 | Draft methods | Release refuses a job whose pulled line has no `storageUnitId`. | A job can come from a Draft method, so the activation check alone has a gap. || 5 | Picked stock | The material's picks and unclaimed lineside stock are consumed first, as today. The strict rule applies to the remainder, against the line's Pull From. After a pick, the Pull From is the source bin of the line's oldest pick line into its current bin (`pullFromStorageUnit`). Job completion (SQL) draws a picked line from its lineside bin first, up to what the bin holds, then the rest from the Pull From. | A pick moves stock out of the Pull From bin with a transfer, so the records stay correct. Picking also moves `jobMaterial.storageUnitId` to the lineside bin, so that column no longer names the Pull From. The pick line keeps it. A later picking list takes the fullest bin, so only the oldest pick line names the Pull From. |-| 4a | Every path to Ready | Each path that sets a job to Ready runs the release checks: `releaseJobs` (the Release dialog, bulk release, planning, the API), batch release, and a kanban scan with auto-release. `updateJobStatus` is not published. A kanban job that fails them stays Draft and stays linked; the scan lands on the job with the reason. | A check on some paths only is a check a user can step around. The kanban scan and the API wrote the status directly. |+| 4a | Every path to Ready | Each path that sets a job to Ready runs the release checks: `releaseJobs` (the Release dialog, bulk release, planning, the API), batch release, and a kanban scan with auto-release. `updateJobStatus` is not published. A kanban job that fails them stays Draft and stays linked; the scan lands on the job with the reason. A kanban job whose method could not be copied is not released either, and the scan says so. | A check on some paths only is a check a user can step around. The kanban scan and the API wrote the status directly. || 4b | Job creation under strict backflush | A job line gets the BoM's Pull From, else the item's default storage unit. It never takes the fullest bin. A line with neither has no storage unit, and release refuses the job. | The fullest bin is a guess that depends on where the stock is. It let a job built from a BoM with no Pull From pass release. || 5a | Locations without a pull-from bin | Strict backflush applies only at a location from decision 3. Elsewhere the backflush, release and the badges behave as with the setting off. | Activation asks for no Pull From there, so a refusal there could never be fixed. || 6a | Negative stock under strict bins | A second switch, `companySettings.preventNegativeBackflush` ("Prevent negative stock", default `true`), nested under Strict Backflush and only active while it is on. Off: the material is still drawn only from its own storage unit, and that storage unit may go below zero. A missing storage unit is refused either way. | A company can want strict bins (accurate per-location stock) without the hard stop on a short bin. Default `true` keeps the behavior the setting shipped with. |@@ -73,7 +73,6 @@ Example: the BoM says "pull 10 × PART-123 from Shelf A-4". Shelf A-4 has 6 and|---|---|| Manual issue of an unplanned part (`partToOperation` with no `materialId`) | No material line exists, so there is no Pull From to enforce. || Maintenance dispatch issue (`maintenanceDispatchInventory`) | It is not a job backflush. |-| Kanban auto-release and the MCP status tools | They skip every release check today. The backflush refusal still stops them later. |## Data Model Changes@@ -108,7 +107,7 @@ No new table. No RLS change.| `convertDocument` `methodVersionToActive` (`shared.service.ts`) | If the setting is on, load the version's lines and the locations with an active work center. Throw `InvalidInputError` that lists each part once, separated by "; ". || `issueMaterial` `issueJobOperationMaterials` (`inventory.service.ts`) | If the setting is on, the remainder after the pick budgets uses `material.storageUnitId` only. `assertBinCovers` counts the rows already planned in this call. No fallback bin, no fullest-bin switch. || `issueMaterial` `partToOperation` (planned material) | If the setting is on and the issue consumes stock, use `material.storageUnitId` only and run `assertBinCovers`. A return (positive adjustment) does not change. |-| `issueInput` `jobOperation` (`@carbon/api/postings`) | New optional `dryRun: boolean`. If `dryRun` is true and strict backflush is off, return at once. If it is on, run the issue in a transaction and roll it back. |+| `issueInput` `jobOperationDryRun` (`@carbon/api/postings`, in `MES_POSTINGS`) | The strict check of a `jobOperation` issue, with no writes (`dryRunJobOperationIssues`). Its own type rather than a `dryRun` flag, so an older ERP refuses it instead of issuing for real. A no-op when strict backflush is off. Several operations checked together count each other's demand on a shared bin. || `getJobReleaseReadiness` | Each job gets `materialsWithoutStorageUnit: { id, description }[]`. The list is empty when the setting is off. || `jobReleaseProblems` | Adds "set a Pull From storage unit on PART-1, PART-2". || `releaseJobs` (Release dialog path) | Refuses a job with `materialsWithoutStorageUnit` and names the parts. |@@ -151,7 +150,6 @@ No new table. No RLS change.| The dry run adds one transaction per MES completion | Low | It runs only when strict backflush is on. || Two completions draw the same bin at the same moment | Med | Both checks take a transaction-scoped advisory lock on (company, bin, item). Other stock movements (shipments, transfers) do not take it. || Two batch members draw the same bin | Low | Each member's dry run passes alone. Phase 2 then refuses the second member, and the batch stays Completing until a retry. |-| Kanban and MCP release skip the release check | Low | The backflush refusal still applies. Listed as out of scope. |## Open Questions@@ -168,10 +166,12 @@ No new table. No RLS change.## Changelog- 2026-10-14: Created from the backflush rules design discussion.+- 2026-10-19: Review fixes: the dry run is its own posting type (`jobOperationDryRun`); batch completion checks every member in one dry run; Consume First swaps never take the fullest bin under strict backflush; a completion dry-run refusal keeps its status category.- 2026-10-19: Merged main, which moved the server functions into the ERP modules and unpublished `updateJobStatus`. The strict backflush code moved with them (see the API table). Every path to Ready now runs `jobReleaseProblems`, then `releaseCheckedJobs`. The `updateJobStatus` guard and `jobReleaseBlockers` are gone: main's `releaseJobs` is the published release, and its readiness already covers "nothing to make".- 2026-10-19: Browser test of every path to Ready. A kanban release reuses the supplier's newest Draft PO for outside operations (no one at a scan can choose one), and a refused scan shows its reason on the job page.-- 2026-10-17: Every path to Ready now runs the release checks: the kanban scan with auto-release (through `releaseJobs`) and the API tool `updateJobStatus` were missed (decision 4a). Job creation under strict backflush no longer takes the fullest bin (decision 4b). Plan `.ai/plans/2026-10-17-release-checks-every-path.md`.-- 2026-10-16: Self-review fixes (plan `.ai/plans/2026-10-16-strict-backflush-review-fixes.md`): after a partial pick, the rest now comes from the Pull From, not lineside (decision 5, TypeScript and SQL); strict backflush skips a location with no pull-from bin (decision 5a); both paths lock every (bin, item) pair in one order before the first draw; SQL compares rounded quantities and counts a refused need; the dry run stops at the strict check; the inspection lot is checked before it closes; the New Version route checks activation; every release path checks storage units; the card counts with SQL and the jobs list holds only lines a backflush would refuse (decision 8); the BoM badges use the pull-from locations.+- 2026-10-19: A kanban scan whose Get Method fails names the failure instead of leaving a silent Draft job (decision 4a). The kanban release runs on the scan's own handles. `apps/erp/test/database/kanban-scan.test.ts` covers the refused, released and method-failure scans. Removed the stale out-of-scope and risk rows that said kanban and MCP skip the release checks.+- 2026-10-17: Every path to Ready now runs the release checks: the kanban scan with auto-release (through `releaseJobs`) and the API tool `updateJobStatus` were missed (decision 4a). Job creation under strict backflush no longer takes the fullest bin (decision 4b).+- 2026-10-16: Self-review fixes: after a partial pick, the rest now comes from the Pull From, not lineside (decision 5, TypeScript and SQL); strict backflush skips a location with no pull-from bin (decision 5a); both paths lock every (bin, item) pair in one order before the first draw; SQL compares rounded quantities and counts a refused need; the dry run stops at the strict check; the inspection lot is checked before it closes; the New Version route checks activation; every release path checks storage units; the card counts with SQL and the jobs list holds only lines a backflush would refuse (decision 8); the BoM badges use the pull-from locations.- 2026-10-16: The settings card counts open jobs with a material that has no storage unit, and both counts open a searchable drawer instead of an inline list (user request).- 2026-10-16: The drawers show locations as pills. A materials cell shows 3 part IDs, and "+N more" opens the full list in a popover that scrolls (user request).- 2026-10-16: Split the no-negative rule into its own switch, `preventNegativeBackflush` (decision 6a, user request).diff --git a/.claude/rules/kanban-system.md b/.claude/rules/kanban-system.mdindex ead0272532..8665e16cfd 100644--- a/.claude/rules/kanban-system.md+++ b/.claude/rules/kanban-system.md@@ -76,7 +76,7 @@ RLS: SELECT = any employee role; INSERT/UPDATE/DELETE = `inventory_create`/`inveAPI routes in `apps/erp/app/routes/api+/`: `kanban.$id.tsx`, `kanban.collision.$id.tsx`, `kanban.start.$id.tsx`, `kanban.complete.$id.tsx`, `kanban.link.$id.tsx`.`kanban.$id.tsx` (the "order"/create scan) calls `scanKanban` (`inventory.server.ts`), which branches on `replenishmentSystem` and returns what it made; the route picks the page:-- **Make** — if a job is already linked (`jobReadableId`) it returns `collision` and the route opens the collision page (no duplicate job); otherwise creates a job from the item and links it (`updateKanbanJob`). With `autoRelease`, `scanKanban` runs the release checks (`getJobReleaseReadiness` + `jobReleaseProblems` — nothing to make, manufacturing blocked, assemblies without operations, outside operations without a supplier, strict backflush lines with no storage unit), then `releaseCheckedJobs` as the system on behalf of the scanner, so a scanner without production update can still release (recalculate, MRP, Ready, outside-operation POs, release date; telemetry `source: "kanban"`), then `runLocationSchedule` once the job is Ready. Unlike `releaseJobs`, a supplier's Draft PO is not a blocker — no one at a kanban card can choose one — so the outside operations go on the supplier's newest Draft PO (highest `purchaseOrderId`), else a new one; otherwise the first scan's PO blocked every later scan. A job that fails the checks stays Draft, stays linked, and the scan returns a `message`; the route throws `redirect(jobPage, flash(…))` with it. Returning the flash with `data()` does not work: the root's `flashMiddleware` clears it on the same request. Only a released job sends the scanner to MES: `autoStartJob` opens its first operation's start, else the operation. See `apps/erp/app/modules/production/AGENTS.md` → "Every path to Ready".+- **Make** — if a job is already linked (`jobReadableId`) it returns `collision` and the route opens the collision page (no duplicate job); otherwise creates a job from the item and links it (`updateKanbanJob`). With `autoRelease`, `scanKanban` runs the release checks (`getJobReleaseReadiness` + `jobReleaseProblems` — nothing to make, manufacturing blocked, assemblies without operations, outside operations without a supplier, strict backflush lines with no storage unit), then `releaseCheckedJobs` as the system on behalf of the scanner (a system context built from the scan's own service-role client and `pg`), so a scanner without production update can still release (recalculate, MRP, Ready, outside-operation POs, release date; telemetry `source: "kanban"`), then `runLocationSchedule` once the job is Ready. Unlike `releaseJobs`, a supplier's Draft PO is not a blocker — no one at a kanban card can choose one — so the outside operations go on the supplier's newest Draft PO (highest `purchaseOrderId`), else a new one; otherwise the first scan's PO blocked every later scan. A job that fails the checks stays Draft, stays linked, and the scan returns a `message`. So does a job whose Get Method (`upsertJobMethod`) failed, with or without `autoRelease`: it is never released; the route throws `redirect(jobPage, flash(…))` with it. Returning the flash with `data()` does not work: the root's `flashMiddleware` clears it on the same request. Only a released job sends the scanner to MES: `autoStartJob` opens its first operation's start, else the operation. See `apps/erp/app/modules/production/AGENTS.md` → "Every path to Ready".- **Buy** — reuses an existing draft/planned PO for the supplier (or creates one), adds a PO line with the kanban qty (applying `conversionFactor`/`purchaseUnitOfMeasureCode`/storage unit), redirects to the PO.- **Transfer** — calls `replenishKanban` (`inventory.service.ts`, ported from the `kanban-replenish` server function) with `mode: "scan"`, which writes a Released stock transfer with one line: `itemId`, `fromStorageUnitId` → `storageUnitId` (to), `quantity`, and serial/batch flags from `item.itemTrackingType` (a serial line of qty > 1 splits into qty-1 lines, `expandSerialTrackedLines`). The transfer carries `stockTransfer.kanbanId` and a Tiptap note "Kanban replenishment — … Signal: scan by <user>." Redirects to the stock transfer, where the qty can be **partially picked** at pick time. Each scan makes a new transfer, with no level test. Storage rules are NOT evaluated (a QR scan can't show the acknowledge dialog the interactive wizard uses). `scanKanban` calls it as the scanner (`invokePosting` with the scanner's client and `{ as: replenishKanbanPermission }`): scan mode needs `create: "inventory"`, the same check the `stockTransfer` RLS rule made when the route inserted directly. Never drop the client or the `as` — that lets any employee create transfers. The function re-checks that both bins belong to the company and the kanban's location (CWE-639).- **Buy and Make** — not a kanban option (the enum has no such value).diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.mdindex 688cfabcf7..4d609844e0 100644--- a/apps/erp/app/modules/inventory/AGENTS.md+++ b/apps/erp/app/modules/inventory/AGENTS.md@@ -90,7 +90,7 @@ Each operation is one `defineServiceFn` const in `inventory.server.ts`. A route| `upsertBatchProperty` / `updateBatchPropertyOrder` / `deleteBatchProperty` | `inventory+/batch-property+/*` | `update: inventory`; a new property also needs `create` on parts or inventory (RLS) || `generatePickingList` / `deletePickingList` | `picking-list+/new.tsx`, `$pickingListId.delete.tsx` | — || `correctStockMovement`, `updateTrackedEntityExpiry`, `createInventoryReconciliationJournal` | `stock-movements+/$ledgerId.correct.tsx`, `tracked-entity.expiry.tsx`, `reports+/inventory-valuation.reconcile.tsx` | See Key Service Functions; the reconcile journal needs `create: accounting` |-| `scanKanban` | `api+/kanban.$id.tsx` (the card's QR code; a GET, employees only) | Make: a job (auto-release: recalculated, planned, scheduled, Ready); Buy: a line on the supplier's open Draft / Planned PO or a new one; Transfer: `kanban-replenish` as the scanner. Returns what it made; the route picks the page |+| `scanKanban` | `api+/kanban.$id.tsx` (the card's QR code; a GET, employees only) | Make: a job (auto-release: the release checks, then `releaseCheckedJobs` and the schedule; a refused job stays Draft and the scan returns a `message`); Buy: a line on the supplier's open Draft / Planned PO or a new one; Transfer: `kanban-replenish` as the scanner. Returns what it made; the route picks the page |A blocking rule is data, not an error: `post`, `create`, `setStatus` and `adjust` return `{ violations, ruleNames }` and change nothing; the route returns it to `useRuleViolations`, which re-sends with `acknowledged: true`. The primitives they replaced are no longer published (`insertManualInventoryAdjustment`, `insertInventoryCount`, `upsertReceipt`, `updatePickingListStatus`, `upsertPickingList`, `pickPickingListLine`, `setPickingListLineTrackedEntity`, `upsertShipment`, `insertStockTransfer`, `updateStockTransferStatus`, `updateWarehouseTransferStatus`, `upsertWarehouseTransferLine`, `deleteWarehouseTransferLine`, `deleteStorageUnit`, `deleteStorageUnitCascade`).diff --git a/apps/erp/app/modules/inventory/inventory.server.ts b/apps/erp/app/modules/inventory/inventory.server.tsindex dc8926bdff..fb545ecf39 100644--- a/apps/erp/app/modules/inventory/inventory.server.ts+++ b/apps/erp/app/modules/inventory/inventory.server.ts@@ -4,6 +4,7 @@import {type CarbonError,+ createServiceContext,defineServiceFn} from "@carbon/api/service-fn.server";import { paged, payload, run, unwrap } from "@carbon/api/service-tools.server";@@ -46,7 +47,6 @@ import {upsertPurchaseOrderLine} from "~/modules/purchasing/purchasing.service";import { recordSalesRuleOutcome } from "~/modules/sales/sales.service";-import { systemContext } from "~/modules/service-context.server";import {getCompanySettings,getNextSequence@@ -3373,7 +3373,8 @@ export type KanbanScan =/*** The job it made. `operationId` is its first operation when the kanban* releases the job; `startAs` how to start it when the kanban starts it.- * `message` says why an auto-release job was not released.+ * `message` says why the job was not released, or that its method could+ * not be copied.*/| {type: "job";@@ -3393,8 +3394,8 @@ export type KanbanScan =* after the item's lead time, copies the item's method and links the job to* the kanban; with auto-release it runs the release checks, then releases the* job (`releaseCheckedJobs`) and runs the location's schedule. A job that- * fails the checks stays Draft and `message` names the problems. A kanban- * that already has a job is a+ * fails the checks, or whose method could not be copied, stays Draft and+ * `message` names the problems. A kanban that already has a job is a* collision. Buy: adds a line to the supplier's open Draft or Planned purchase* order, or a new Draft one, priced from the supplier part in the order's* currency. Transfer: releases a stock transfer to the kanban's storage unit@@ -3418,9 +3419,9 @@ export const scanKanban = defineServiceFn({}const card = kanban.data;- /** A kanban job's auto-release: the release checks, then the release. No one- * at a kanban card can choose a purchase order, so unlike `releaseJobs` a- * supplier's newest Draft PO is reused rather than a blocker. */+ /** No one at a kanban card can choose a purchase order, so unlike+ * `releaseJobs` a supplier's newest Draft PO is reused rather than a+ * blocker. */async function releaseKanbanJob(jobId: string,locationId: string@@ -3459,10 +3460,13 @@ export const scanKanban = defineServiceFn({// As the system, like the job it releases: the scanner may not hold// production update, and the status write runs on the caller's client.- const system = systemContext({- companyId,- companyGroupId: ctx.company.groupId,- onBehalfOf: userId+ const system = createServiceContext({+ actor: { type: "system", onBehalfOf: userId },+ company: ctx.company,+ caller: serviceRole,+ system: () => serviceRole,+ pg: () => ctx.asSystem.pg,+ kv: () => ctx.kv});const result = await releaseCheckedJobs(system, {jobIds: [jobId],@@ -3552,10 +3556,10 @@ export const scanKanban = defineServiceFn({},{ skipMethod: true, skipRecalculate: true, source: "kanban" });- const jobId = createdJob.data?.id;- if (createdJob.error || !jobId) {+ if (createdJob.error || !createdJob.data) {return ctx.error("internal", "Failed to create job", createdJob.error);}+ const jobId = createdJob.data.id;const [method, associated] = await Promise.all([upsertJobMethod(serviceRole, ctx.asSystem.pg, "itemToJob", {@@ -3583,8 +3587,12 @@ export const scanKanban = defineServiceFn({if (method.error) {logger.error("Kanban operation failed", { error: method.error });}- const release =- !method.error && card.autoRelease+ const release = method.error+ ? {+ released: false,+ message: `${createdJob.data.jobId} was created, but its method could not be copied. Use Get Method on the job before releasing it.`+ }+ : card.autoRelease? await releaseKanbanJob(jobId, card.locationId!): { released: false, message: null };diff --git a/apps/erp/app/modules/inventory/inventory.service.ts b/apps/erp/app/modules/inventory/inventory.service.tsindex 5a98bb40dc..a67a01da94 100644--- a/apps/erp/app/modules/inventory/inventory.service.ts+++ b/apps/erp/app/modules/inventory/inventory.service.ts@@ -18798,7 +18798,11 @@ export async function postInventoryAdjustment(}type ItemLedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];-class DryRunRollback extends Error {}+class DryRunRollback extends Error {+ constructor(readonly plannedRows: ItemLedgerInsert[] = []) {+ super("Dry run");+ }+}export const postPickingPermission = {} satisfies PermissionRule<z.output<typeof postPickingInput>@@ -20840,7 +20844,8 @@ async function issueJobOperationMaterials(accountDefaults,dimensionMap,db,- dryRun = false+ dryRun = false,+ plannedElsewhere = []}: {jobOperationId: string;quantity: number;@@ -20853,6 +20858,9 @@ async function issueJobOperationMaterials(db: Kysely<KyselyDatabase>;// Throw DryRunRollback after the strict check, before any ledger row.dryRun?: boolean;+ // Rows earlier operations of the same dry run plan to draw, so operations+ // sharing a bin are checked against their combined demand.+ plannedElsewhere?: ItemLedgerInsert[];}) {const materialsToIssue = await trx@@ -20947,7 +20955,8 @@ async function issueJobOperationMaterials(const pullFrom = strict? await resolvePullFromStorageUnits(trx, companyId, materialsToIssue): new Map<string, string | null>();- if (strict && preventNegative) {+ // A dry run's locks would end with its rollback; the real issue takes them.+ if (strict && preventNegative && !dryRun) {await lockStrictBins(trx,companyId,@@ -21020,9 +21029,10 @@ async function issueJobOperationMaterials(locationId: job.locationId,storageUnitId,quantity: remaining,- plannedRows: itemLedgerInserts,+ plannedRows: [...plannedElsewhere, ...itemLedgerInserts],preventNegative,- jobReadableId: job.jobId+ jobReadableId: job.jobId,+ lock: !dryRun});if (problem) strictProblems.push(problem);// Kept when refused, so a later material on the bin counts this need.@@ -21130,7 +21140,7 @@ async function issueJobOperationMaterials(}if (strictProblems.length > 0) throw strictBackflushRefusal(strictProblems);- if (dryRun) throw new DryRunRollback();+ if (dryRun) throw new DryRunRollback(itemLedgerInserts);// Total material cost this call relieved from inventory into WIP — the// jobOperationScrap case posts its WIP→scrap journal from this figure so a@@ -22568,6 +22578,7 @@ export const issueMaterialPermission = {jobCompleteMakeToOrder: {},jobOperation: { update: "production" },jobOperationBatchComplete: { update: "production" },+ jobOperationDryRun: { update: "production" },jobOperationBatchOutput: { update: "production" },jobOperationSerialComplete: { update: "production" },jobOperationScrap: { update: "production" },@@ -22588,6 +22599,61 @@ export const issueMaterialPermission = {* Issues material and records production against jobs, operations, tracked* entities and maintenance dispatches, per `type`.*/+/**+ * The strict backflush check of issuing each operation's materials, with no+ * writes. The operations are checked together, so two that draw the same Pull+ * From bin are refused when their combined demand exceeds it. Throws the 409+ * refusal; a no-op when strict backflush is off.+ */+export async function dryRunJobOperationIssues(+ db: Kysely<KyselyDatabase>,+ args: {+ companyId: string;+ userId: string;+ operations: { id: string; quantity: number }[];+ }+): Promise<void> {+ const { companyId, userId } = args;+ const operations = args.operations.filter((op) => op.quantity > 0);+ if (operations.length === 0) return;+ if (!(await isStrictBackflush(db, companyId))) return;++ const { accountDefaults, dimensionMap } = await loadConsumeAccountingContext(+ db,+ companyId+ );+ try {+ await db.transaction().execute(async (trx) => {+ const postingStatus = await journalPostingStatus(trx, companyId);+ const planned: ItemLedgerInsert[] = [];+ for (const op of operations) {+ try {+ await issueJobOperationMaterials(trx, {+ jobOperationId: op.id,+ quantity: op.quantity,+ companyId,+ userId,+ postingStatus,+ accountDefaults,+ dimensionMap,+ db,+ dryRun: true,+ plannedElsewhere: planned+ });+ } catch (err) {+ if (!(err instanceof DryRunRollback)) throw err;+ planned.push(...err.plannedRows);+ }+ }+ // The material loop writes `quantityIssued` before the dry-run exit, so+ // the transaction must never commit.+ throw new DryRunRollback();+ });+ } catch (err) {+ if (!(err instanceof DryRunRollback)) throw err;+ }+}+export async function issueMaterial(ctx: ServiceContext,raw: z.input<typeof issueInput>@@ -22608,37 +22674,37 @@ export async function issueMaterial(switch (validatedPayload.type) {case "jobOperation": {- const { id, companyId, quantity, userId, dryRun } = validatedPayload;-- if (dryRun && !(await isStrictBackflush(db, companyId))) break;+ const { id, companyId, quantity, userId } = validatedPayload;const { accountDefaults, dimensionMap } =await loadConsumeAccountingContext(db, companyId);- try {- await db.transaction().execute(async (trx) => {- // Provisional before the company's accounting cutover, Posted after it.- const postingStatus = await journalPostingStatus(trx, companyId);- await issueJobOperationMaterials(trx, {- jobOperationId: id,- quantity,- companyId,- userId,- postingStatus,- accountDefaults,- dimensionMap,- db,- dryRun- });- // Reached on a dry run only when the operation had nothing to issue.- if (dryRun) throw new DryRunRollback();+ await db.transaction().execute(async (trx) => {+ // Provisional before the company's accounting cutover, Posted after it.+ const postingStatus = await journalPostingStatus(trx, companyId);+ await issueJobOperationMaterials(trx, {+ jobOperationId: id,+ quantity,+ companyId,+ userId,+ postingStatus,+ accountDefaults,+ dimensionMap,+ db});- } catch (err) {- if (!(err instanceof DryRunRollback)) throw err;- }+ });break;}+ case "jobOperationDryRun": {+ const { id, companyId, quantity, userId } = validatedPayload;+ await dryRunJobOperationIssues(db, {+ companyId,+ userId,+ operations: [{ id, quantity }]+ });+ break;+ }case "jobOperationBatchComplete": {const { trackedEntityId, companyId, userId, ...row } = validatedPayload;await assertProductionQuantityLinks(db, companyId, row);diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex 82fb4090b0..c01dfb52c7 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -26,9 +26,9 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced- **Which lines, which locations.** `needsPullFrom` (`@carbon/database/strict-backflush`): not Make to Order, item type Material / Part / Consumable, item not Non-Inventory. The locations are `getPullFromLocations` / `isPullFromLocation` — each with an active work center AND an active storage unit (a location with no storage unit has no bin a line could name). Strict backflush does not apply anywhere else: activation, release, the backflush, the badges and the settings card all skip such a location.- **Activation.** `getMethodPartsMissingPullFrom` + `activationRefusalMessage` (`@carbon/database/strict-backflush`). `convertDocument` `methodVersionToActive` (`shared.service.ts`) refuses through `assertMethodHasPullFrom` (`~/modules/shared/strict-backflush`); `createMethodVersion` (`items.server.ts`, behind the New Version route), which makes a single Draft version Active, refuses the same way before it writes. The change-notice draft (`createChangeNoticeDraftMethod`) freezes a Draft base as Active without the check: that is a side effect of opening the notice, and release still refuses the jobs.- **Release.** `getJobReleaseReadiness` returns `materialsWithoutStorageUnit` per job (`materialsWithoutStorageUnit` in `job-release-logic.ts`, one entry per part; jobs at other locations are skipped), and every path that sets a job to Ready refuses on it — see "Every path to Ready" below. `JobStartModal` lists the parts and disables Release Job; while the pull-from locations load it assumes the job's location needs them, and a failed read shows an error and disables Release.-- **Job creation.** With strict backflush on at the job's location, `getMethod` (`production.service.ts`) gives a line the BoM's Pull From, else the item's default storage unit (`pickMethod`), and never the fullest bin (`withFullestBin` in its item prefetch, the same gate in `createItemDefaults`). A line with neither stays without a storage unit, so the job shows in the settings drawer and release refuses it. With the setting off, the fullest bin is still the last fallback.+- **Job creation.** With strict backflush on at the job's location, `getMethod` (`production.service.ts`) gives a line the BoM's Pull From, else the item's default storage unit (`pickMethod`), and never the fullest bin (`withFullestBin` in its item prefetch, the same gate in `createItemDefaults`, and `getStorageUnitId(…, allowFullestBin)` in `itemDerivedJobMaterialFields`, which the Consume First swaps use). A line with neither stays without a storage unit, so the job shows in the settings drawer and release refuses it. With the setting off, the fullest bin is still the last fallback.- **Backflush.** `issueJobOperationMaterials` and `partToOperation` (`issueMaterial`, `inventory.service.ts`; planned material, consuming issue) take picked and unclaimed lineside stock first, then what no pick covered from the line's Pull From only (`assertBinCovers` / `binCoverProblem` in `~/modules/shared/strict-backflush`: 409, names the part, the bin, need and have). A pick points `jobMaterial.storageUnitId` at lineside (`pointJobMaterialAtLineside`), so the Pull From is resolved by `resolvePullFromStorageUnits` → `pullFromStorageUnit`: the source bin of the line's OLDEST pick line into its current bin, else the line's own bin. Before the first draw, `lockStrictBins` takes `pg_advisory_xact_lock(hashtextextended('strict-backflush:<companyId>:<bin>:<item>', 0))` for every (Pull From, item) pair in key-hash order; SQL locks the same keys in the same order, so two completions cannot deadlock. Every shortfall is collected and refused once; a refused material still counts its need against the bin, so the refusal names the whole shortfall. A refusal is a toast, so every strict message goes through `summarizeList`: the first 5 part names or 3 shortfalls, then "and N more" (the full shortfall list is logged). SQL `backflush_job_materials` (`20261015163040_strict-backflush.sql`) does the same at job completion: a picked line is drawn from lineside first (up to its on-hand), the rest from the Pull From; quantities compare at `round(…, 5)`.-- **Produced units with no consumption.** Callers that record a production quantity before they call `issue` first invoke `issue` `jobOperation` with `dryRun: true`; `issueJobOperationMaterials` throws `DryRunRollback` right after the strict check, before any ledger, cost or journal row, and the call is a no-op when the setting is off. MES callers go through `checkStrictBackflush` (`apps/mes/app/services/quality.server.ts`, which posts the dry run to the ERP through `erpPosting`): `complete.tsx`, `end.$operationId.tsx`, `inspection-lot.$id.complete-passed.tsx`, and `inspection-lot.$id.disposition.tsx`, which checks completion plus scrap BEFORE it closes the lot (a closed lot cannot be dispositioned again). ERP `completeOperation` (`production.server.ts`) and batch completion (`completeBatch`, `production.service.ts`) dry-run too; batch phase 2 keeps a refusal's 409. The dry run narrows the race, it does not close it (its lock ends with its rollback), so a failure after the units are recorded says "Units completed, but …" — the operator must not record them again.+- **Produced units with no consumption.** Callers that record a production quantity before they call `issue` first invoke `issue` with `type: "jobOperationDryRun"` (its own type, not a flag on `jobOperation`, so an ERP that predates it refuses it instead of issuing for real). It runs `dryRunJobOperationIssues` (`inventory.service.ts`): `issueJobOperationMaterials` with `dryRun` stops right after the strict check, before any ledger, cost or journal row, and the whole transaction always rolls back (the material loop updates `quantityIssued` before that point). It takes no locks and is a no-op when the setting is off. Several operations are checked in one dry run, each counting the rows the earlier ones plan to draw, so batch completion holds members that share a bin to their combined demand. MES callers go through `checkStrictBackflush` (`apps/mes/app/services/quality.server.ts`, which posts the dry run to the ERP through `erpPosting`): `complete.tsx`, `end.$operationId.tsx`, `inspection-lot.$id.complete-passed.tsx`, and `inspection-lot.$id.disposition.tsx`, which checks completion plus scrap BEFORE it closes the lot (a closed lot cannot be dispositioned again). ERP `completeOperation` (`production.server.ts`; a refusal keeps its category through `serverFnFailure`) and batch completion (`completeBatch`, `production.service.ts`, one dry run for every member) dry-run too; batch phase 2 keeps a refusal's 409. The dry run narrows the race, it does not close it (its lock ends with its rollback), so a failure after the units are recorded says "Units completed, but …" — the operator must not record them again.- **Existing Active methods and released jobs are never changed** when the setting turns on. Settings → Items counts both gaps with `getStrictBackflushGapCounts` (`settings.service.ts`, two `count(DISTINCT …)` statements; a failed count shows an error line, never a clean card) and each count's Review button opens a route drawer (`settings+/items.methods-missing-pull-from.tsx`, `items.jobs-missing-storage-unit.tsx`) over `getActiveMethodsMissingPullFrom` / `getOpenJobsMissingStorageUnit` (`settings.service.ts`). Each count and its list share one query builder (`methodLinesMissingPullFrom`, `jobLinesMissingStorageUnit`, the SQL form of `needsPullFrom`), so they cannot disagree. The jobs list holds only lines a backflush would refuse: stocked, not batch or serial, quantity still to issue, at a pull-from location. The drawers page in memory with `pageInMemory` (`~/utils/query`) in a searchable, paged `Table` (`ui/StrictBackflush/StrictBackflushTables.tsx`); a failed read flashes an error and returns to the page. A long list never goes in the card itself. Locations render as `Enumerable` pills; a materials cell shows 3 part IDs and a "+N more" popover with all of them, which stops wheel and touch propagation so it scrolls inside the drawer (`conventions-ui.md`, "Popovers inside Drawers").- **Badges.** The BoM and job BoM editors mark a line red ("No storage unit"), collapsed and open, from `usePullFromLocationIds` (`~/hooks/usePullFromLocationIds`, the cached `api+/items.pull-from-locations.ts`) — the same locations activation and release use. A changed line item's tracking type is kept until the line is saved, so the badge follows the new item.@@ -117,7 +117,7 @@ pnpm --filter erp test|---|---|| `releaseJobs` (Release dialog, bulk release, planning, API/MCP) | `jobReleaseProblems` per job, then `releaseCheckedJobs` || Batch release (`releaseBatchMemberJobs`) | `jobReleaseProblems`, all-or-nothing, then `releaseCheckedJobs` |- | Kanban scan with `autoRelease` (`scanKanban`, `inventory.server.ts`) | `jobReleaseProblems`, then `releaseCheckedJobs` as the system on behalf of the scanner (`source: "kanban"`; outside operations go on the supplier's newest Draft PO, else a new one — no one is there to choose), then `runLocationSchedule`. A refused job stays Draft and linked to the kanban; the route redirects to the job with a flash naming the problems, and MES is not opened |+ | Kanban scan with `autoRelease` (`scanKanban`, `inventory.server.ts`) | `jobReleaseProblems`, then `releaseCheckedJobs` as the system on behalf of the scanner (`source: "kanban"`; outside operations go on the supplier's newest Draft PO, else a new one — no one is there to choose), then `runLocationSchedule`. A refused job stays Draft and linked to the kanban; the route redirects to the job with a flash naming the problems, and MES is not opened. A job whose Get Method failed is not released either, and the flash says so |`resumeJob` (Paused → Ready) is not a release. `updateJobStatus` is not published, so the API cannot set Ready without the checks. No SQL function sets a job to Ready (the SQL writes of `'Ready'` are on `jobOperation`). A new path to Ready must run `jobReleaseProblems` before `releaseCheckedJobs`.- `getJobMaterialsWithQuantityOnHand` — BOM with on-hand for shortfall visibilitydiff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex 2290b9f9bc..ba3c5a2cfb 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -25,7 +25,8 @@ import { z } from "zod";import {cancelOpenPickingListsForJob,issueMaterial,- mergeTrackedEntities+ mergeTrackedEntities,+ serverFnFailure} from "~/modules/inventory/inventory.service";import { getDefaultStorageUnitForJob } from "~/modules/inventory/inventory.utils";import {@@ -2871,15 +2872,11 @@ export const completeOperation = defineServiceFn({const check = await invokePosting(ctx,"issue",- { type: "jobOperation", id: operationId, quantity, dryRun: true },+ { type: "jobOperationDryRun", id: operationId, quantity },issueMaterial);if (check.error) {- return ctx.error(- check.error.status === 409 ? "conflict" : "internal",- check.error.message,- check.error- );+ return serverFnFailure(ctx, check.error, check.error.message);}const recorded = await createProductionQuantity(ctx, {diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 04f8ea2257..de2a63c775 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -20707,6 +20707,11 @@ async function itemDerivedJobMaterialFields(opts: {lineStorageUnitId?: string;}) {const { trx, companyId, itemId, locationId, lineStorageUnitId } = opts;+ const { strict } = await getStrictBackflushSettings(+ trx,+ companyId,+ locationId+ );const [item, replenishment, storageUnitId] = await Promise.all([readItemWithCost(trx, itemId, companyId),@@ -20716,7 +20721,7 @@ async function itemDerivedJobMaterialFields(opts: {.where("itemId", "=", itemId).where("companyId", "=", companyId).executeTakeFirst(),- getStorageUnitId(trx, itemId, locationId, lineStorageUnitId)+ getStorageUnitId(trx, itemId, locationId, lineStorageUnitId, !strict)]);if (!item) return null;@@ -24009,30 +24014,26 @@ async function completeBatch(let glEvents: { id: string; postedToGL: boolean }[] = [];// Strict backflush: refuse before phase 1 writes, since phase 2 issues after- // it commits. A completed batch skips this, so a retry still gets the- // "already completed" answer.+ // it commits. Every member is checked in one dry run, so members sharing a+ // bin are held to their combined demand. A completed batch skips this, so a+ // retry still gets the "already completed" answer.const batchStatus = await db.selectFrom("jobOperationBatch").select("status").where("id", "=", batchId).where("companyId", "=", companyId).executeTakeFirst();- const system = { db, companyId, userId };- for (const m of batchStatus?.status === "Completed" ? [] : members) {- if (m.quantity <= 0) continue;- const check = await invokePosting(- system,- "issue",- {+ if (batchStatus?.status !== "Completed") {+ await inventoryPostings.dryRunJobOperationIssues(db, {+ companyId,+ userId,+ operations: members.map((m) => ({id: m.jobOperationId,- type: "jobOperation",- quantity: m.quantity,- dryRun: true- },- inventoryPostings.issueMaterial- );- if (check.error) throw check.error;+ quantity: m.quantity+ }))+ });}+ const system = { db, companyId, userId };await db.transaction().execute(async (trx) => {const batch = await trxdiff --git a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsxindex 9449f245e5..dfb5215615 100644--- a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx+++ b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx@@ -62,7 +62,6 @@ export function BatchReleaseModal({{});- // `staleTime: 0`: the checks are read again each time the modal opens.const readinessQuery = useLoaderQuery<JobReleaseReadiness>(path.to.api.batchReleaseReadiness(target),{ staleTime: 0 }diff --git a/apps/erp/app/modules/settings/types.ts b/apps/erp/app/modules/settings/types.tsindex 7915bcd4f3..d23df81a6b 100644--- a/apps/erp/app/modules/settings/types.ts+++ b/apps/erp/app/modules/settings/types.ts@@ -59,7 +59,6 @@ export type MethodMissingPullFrom = {readableId: string;name: string;version: number;- /** The pulled, stocked materials on this version with a gap. */materials: string[];/** The locations at least one of those materials has no Pull From at. */locations: string[];@@ -72,6 +71,5 @@ export type JobMissingStorageUnit = {status: Database["public"]["Enums"]["jobStatus"];readableId: string | null;locationName: string | null;- /** The materials the backflush would refuse: no storage unit. */materials: string[];};diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.tsindex 65a10ba9a6..8b215a090c 100644--- a/apps/erp/app/modules/shared/shared.service.ts+++ b/apps/erp/app/modules/shared/shared.service.ts@@ -15797,7 +15797,9 @@ export async function getStorageUnitId(trx: Transaction<DB>,itemId: string,locationId: string,- storageUnitId?: string+ storageUnitId?: string,+ /** False under strict backflush: the fullest bin is a guess, not a choice. */+ allowFullestBin = true): Promise<string | undefined> {if (storageUnitId) return storageUnitId;@@ -15809,6 +15811,7 @@ export async function getStorageUnitId(.executeTakeFirst();if (pickMethod?.defaultStorageUnitId) return pickMethod.defaultStorageUnitId;+ if (!allowFullestBin) return undefined;const storageUnitWithHighestQuantity =await getStorageUnitWithHighestQuantity(trx, itemId, locationId);diff --git a/apps/erp/app/modules/shared/strict-backflush.ts b/apps/erp/app/modules/shared/strict-backflush.tsindex f9ed135a38..728b1bb547 100644--- a/apps/erp/app/modules/shared/strict-backflush.ts+++ b/apps/erp/app/modules/shared/strict-backflush.ts@@ -46,6 +46,8 @@ type BinCoverArgs = {plannedRows: LedgerInsert[];preventNegative: boolean;jobReadableId: string;+ /** False in a dry run: its lock would end with its rollback. */+ lock?: boolean;};export async function resolvePullFromStorageUnits(@@ -132,7 +134,9 @@ export async function binCoverProblem(// Held until the caller's transaction ends, so two completions cannot both// pass the check and overdraw the bin.- await lockStrictBins(db, companyId, [{ storageUnitId, itemId }]);+ if (args.lock !== false) {+ await lockStrictBins(db, companyId, [{ storageUnitId, itemId }]);+ }const row = await db.selectFrom("itemLedger")diff --git a/apps/erp/test/__snapshots__/posting-permissions.test.ts.snap b/apps/erp/test/__snapshots__/posting-permissions.test.ts.snapindex b284830303..6d03cb9fb2 100644--- a/apps/erp/test/__snapshots__/posting-permissions.test.ts.snap+++ b/apps/erp/test/__snapshots__/posting-permissions.test.ts.snap@@ -65,6 +65,9 @@ exports[`posting permissions > match the reviewed manifest 1`] = `"jobOperationBatchOutput": {"update": "production",},+ "jobOperationDryRun": {+ "update": "production",+ },"jobOperationScrap": {"update": "production",},@@ -406,6 +409,9 @@ exports[`posting permissions > match the reviewed manifest 2`] = `"jobOperationBatchOutput": {"update": "production",},+ "jobOperationDryRun": {+ "update": "production",+ },"jobOperationScrap": {"update": "production",},diff --git a/apps/erp/test/database/fixtures/local-supabase.ts b/apps/erp/test/database/fixtures/local-supabase.tsindex ed72480698..f60e4affd9 100644--- a/apps/erp/test/database/fixtures/local-supabase.ts+++ b/apps/erp/test/database/fixtures/local-supabase.ts@@ -6,13 +6,7 @@ import { existsSync, readFileSync } from "node:fs";import type { Database } from "@carbon/database";import { createClient, type SupabaseClient } from "@supabase/supabase-js";-/**- * The local stack's PostgREST, as the service role, from the `.env.local` that- * `crbn up` writes. The unit-test config stubs SUPABASE_URL and the key, so a- * service function's Supabase reads need the real values from that file. Null- * when there is no local stack: the tests that need it skip.- */-export function localServiceRoleClient(): SupabaseClient<Database> | null {+function localEnv(): Record<string, string> | null {const file = [".env.local", "../../.env.local"].find((path) =>existsSync(path));@@ -22,8 +16,25 @@ export function localServiceRoleClient(): SupabaseClient<Database> | null {const match = line.match(/^\s*([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/);if (match?.[1] && match[2] !== undefined) env[match[1]] = match[2].trim();}- const port = env.PORT_API;- const key = env.SUPABASE_SERVICE_ROLE_KEY;+ return env;+}++/** The unit-test config stubs the service-role key; a test that runs a+ * posting through the local client mocks `@carbon/env` with this one. */+export function localServiceRoleKey(): string | null {+ return localEnv()?.SUPABASE_SERVICE_ROLE_KEY ?? null;+}++/**+ * The local stack's PostgREST, as the service role, from the `.env.local` that+ * `crbn up` writes. The unit-test config stubs SUPABASE_URL and the key, so a+ * service function's Supabase reads need the real values from that file. Null+ * when there is no local stack: the tests that need it skip.+ */+export function localServiceRoleClient(): SupabaseClient<Database> | null {+ const env = localEnv();+ const port = env?.PORT_API;+ const key = env?.SUPABASE_SERVICE_ROLE_KEY;if (!port || !key) return null;return createClient<Database>(`http://localhost:${port}`, key, {auth: { autoRefreshToken: false, persistSession: false }diff --git a/apps/erp/test/database/kanban-scan.test.ts b/apps/erp/test/database/kanban-scan.test.tsnew file mode 100644index 0000000000..509b5d61fb--- /dev/null+++ b/apps/erp/test/database/kanban-scan.test.ts@@ -0,0 +1,229 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++// Runs against the local database and PostgREST; skipped without them.++import { createServiceContext } from "@carbon/api/service-fn.server";+import { expect, vi } from "vitest";+import { scanKanban } from "../../app/modules/inventory/inventory.server";+import {+ alwaysPostFixture,+ type Fixture,+ seed,+ USER,+ workCenterFixture+} from "./fixtures/always-post";+import { databaseTest, hasLocalDatabase } from "./fixtures/local-database";+import { localServiceRoleClient } from "./fixtures/local-supabase";++// Get Method is a posting, and the posting gate tells the system by its key.+vi.mock("@carbon/env", async (importOriginal) => {+ const { localServiceRoleKey } = await import("./fixtures/local-supabase");+ return {+ ...(await importOriginal<object>()),+ SUPABASE_SERVICE_ROLE_KEY: localServiceRoleKey() ?? "test"+ };+});++const client = hasLocalDatabase ? localServiceRoleClient() : null;+const scanTest = (name: string, fn: () => Promise<void>) =>+ databaseTest(name, async () => {+ if (!client) return;+ await fn();+ });++function context(f: Fixture) {+ return createServiceContext({+ actor: { type: "system", onBehalfOf: USER },+ company: { id: f.companyId, groupId: f.groupId },+ caller: client as never,+ system: () => client as never,+ pg: () => f.db,+ kv: () => {+ throw new Error("The scan uses no kv");+ }+ });+}++/** An auto-release Make kanban under strict backflush. Its BoM line has a+ * Pull From only when `pullFrom`. */+async function strictKanban(f: Fixture, { pullFrom }: { pullFrom: boolean }) {+ const kanbanId = `${f.prefix}-kanban`;+ const workCenterId = await workCenterFixture(f);+ await seed(f, async (trx) => {+ await trx+ .insertInto("sequence")+ .values({+ table: "job",+ name: "Job",+ prefix: "J",+ next: 0,+ size: 6,+ step: 1,+ companyId: f.companyId+ })+ .execute();+ const shelf = await trx+ .insertInto("storageUnit")+ .values({+ name: "Shelf A",+ locationId: f.locationId,+ companyId: f.companyId,+ createdBy: USER+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ const process = await trx+ .insertInto("process")+ .values({+ name: "Assemble",+ defaultStandardFactor: "Hours/Piece",+ companyId: f.companyId,+ createdBy: USER+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ const method = await trx+ .insertInto("makeMethod")+ .values({+ itemId: f.assemblyId,+ version: 99,+ companyId: f.companyId,+ createdBy: USER+ })+ .returning("id")+ .executeTakeFirstOrThrow();+ await trx+ .insertInto("methodOperation")+ .values({+ makeMethodId: method.id,+ processId: process.id,+ workCenterId,+ description: "Assemble",+ laborTime: 1,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("methodMaterial")+ .values({+ makeMethodId: method.id,+ itemId: f.partId,+ itemType: "Part",+ methodType: "Pull from Inventory",+ quantity: 2,+ unitOfMeasureCode: "EA",+ storageUnitIds: pullFrom ? { [f.locationId]: shelf.id } : {},+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .insertInto("kanban")+ .values({+ id: kanbanId,+ itemId: f.assemblyId,+ replenishmentSystem: "Make",+ quantity: 5,+ locationId: f.locationId,+ purchaseUnitOfMeasureCode: "EA",+ autoRelease: true,+ companyId: f.companyId,+ createdBy: USER+ })+ .execute();+ await trx+ .updateTable("companySettings")+ .set({ requireBackflushStorageUnit: true })+ .where("id", "=", f.companyId)+ .execute();+ });+ return kanbanId;+}++const messageOf = (scan: Awaited<ReturnType<typeof scanKanban>>) =>+ scan.data?.type === "job" ? scan.data.message : undefined;++async function kanbanJob(f: Fixture, kanbanId: string) {+ const kanban = await f.db+ .selectFrom("kanban")+ .select("jobId")+ .where("id", "=", kanbanId)+ .executeTakeFirstOrThrow();+ return f.db+ .selectFrom("job")+ .select(["id", "jobId", "status"])+ .where("id", "=", kanban.jobId!)+ .executeTakeFirstOrThrow();+}++scanTest(+ "a kanban job that fails the release checks stays Draft and says why",+ async () => {+ const f = await alwaysPostFixture();+ try {+ const kanbanId = await strictKanban(f, { pullFrom: false });++ const scan = await scanKanban(context(f), { kanbanId });++ expect(scan.error).toBeNull();+ const job = await kanbanJob(f, kanbanId);+ expect(job.status).toBe("Draft");+ expect(scan.data).toMatchObject({+ type: "job",+ jobId: job.id,+ operationId: null+ });+ expect(messageOf(scan)).toBe(+ `${job.jobId} was created but not released: set a Pull From storage unit on ${f.prefix}-PART`+ );+ } finally {+ await f.cleanup();+ }+ }+);++scanTest("a kanban job that passes the release checks is released", async () => {+ const f = await alwaysPostFixture();+ try {+ const kanbanId = await strictKanban(f, { pullFrom: true });++ const scan = await scanKanban(context(f), { kanbanId });++ expect(scan.error).toBeNull();+ expect(messageOf(scan)).toBeNull();+ const job = await kanbanJob(f, kanbanId);+ expect(job.status).toBe("Ready");+ expect(scan.data).toMatchObject({ operationId: expect.any(String) });+ } finally {+ await f.cleanup();+ }+});++scanTest(+ "a kanban job whose method could not be copied stays Draft and says so",+ async () => {+ const f = await alwaysPostFixture();+ try {+ const kanbanId = await strictKanban(f, { pullFrom: true });+ await f.db+ .deleteFrom("makeMethod")+ .where("itemId", "=", f.assemblyId)+ .where("companyId", "=", f.companyId)+ .execute();++ const scan = await scanKanban(context(f), { kanbanId });++ expect(scan.error).toBeNull();+ const job = await kanbanJob(f, kanbanId);+ expect(job.status).toBe("Draft");+ expect(messageOf(scan)).toBe(+ `${job.jobId} was created, but its method could not be copied. Use Get Method on the job before releasing it.`+ );+ } finally {+ await f.cleanup();+ }+ }+);diff --git a/apps/erp/test/database/strict-backflush.test.ts b/apps/erp/test/database/strict-backflush.test.tsindex 44d2d13cd0..6457c0667d 100644--- a/apps/erp/test/database/strict-backflush.test.ts+++ b/apps/erp/test/database/strict-backflush.test.ts@@ -5,6 +5,7 @@import { sql } from "kysely";import { expect } from "vitest";import {+ dryRunJobOperationIssues,issueMaterial,postInventoryAdjustment as postInventoryAdjustmentBody} from "../../app/modules/inventory/inventory.service";@@ -331,6 +332,43 @@ databaseTest(});+databaseTest(+ "a batch dry run holds operations that share a bin to their combined demand",+ async () => {+ const f = await alwaysPostFixture();+ try {+ const shelfA = await storageUnit(f, "Shelf A");+ await stockBin(f, shelfA, 3);+ const first = await jobFixture(f, "1");+ const second = await jobFixture(f, "2");+ await setMaterialBin(f, first.materialId, shelfA);+ await setMaterialBin(f, second.materialId, shelfA);+ await setStrict(f, true);++ const check = (operationIds: string[]) =>+ dryRunJobOperationIssues(f.db, {+ companyId: f.companyId,+ userId: USER,+ operations: operationIds.map((id) => ({ id, quantity: 1 }))+ });++ // Each needs 2 of the 3 on the shelf: alone each fits, together not.+ await check([first.operationId]);+ await check([second.operationId]);+ await expect(+ check([first.operationId, second.operationId])+ ).rejects.toMatchObject({+ status: 409,+ message: `Not enough ${f.prefix}-PART in ${f.prefix} Shelf A: need 2, have 1`+ });+ expect(await consumption(f, first.jobId)).toEqual([]);+ expect(await consumption(f, second.jobId)).toEqual([]);+ } finally {+ await f.cleanup();+ }+ }+);+databaseTest("a dry run reports the refusal and writes nothing", async () => {const f = await alwaysPostFixture();try {@@ -341,29 +379,26 @@ databaseTest("a dry run reports the refusal and writes nothing", async () => {unwrap(await issue(f.ctx, {- type: "jobOperation",+ type: "jobOperationDryRun",id: job.operationId,- quantity: 1,- dryRun: true+ quantity: 1}));await setStrict(f, true);const short = await issue(f.ctx, {- type: "jobOperation",+ type: "jobOperationDryRun",id: job.operationId,- quantity: 1,- dryRun: true+ quantity: 1});expect(short.error?.status).toBe(409);await stockBin(f, shelfA, 1);unwrap(await issue(f.ctx, {- type: "jobOperation",+ type: "jobOperationDryRun",id: job.operationId,- quantity: 1,- dryRun: true+ quantity: 1}));expect(await consumption(f, job.jobId)).toEqual([]);diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.tsindex d1fedd390a..93a06cdcb7 100644--- a/apps/mes/app/services/quality.server.ts+++ b/apps/mes/app/services/quality.server.ts@@ -627,9 +627,8 @@ export async function checkStrictBackflush(args: {{ companyId: args.companyId, userId: args.userId },{id: args.jobOperationId,- type: "jobOperation",- quantity: args.quantity,- dryRun: true+ type: "jobOperationDryRun",+ quantity: args.quantity});if (check.error) {diff --git a/packages/api/src/postings.ts b/packages/api/src/postings.tsindex b9c36ae8a0..51f197ef2e 100644--- a/packages/api/src/postings.ts+++ b/packages/api/src/postings.ts@@ -30,8 +30,14 @@ export const issueInput = z.discriminatedUnion("type", [z.object({type: z.literal("jobOperation"),quantity: z.number(),- id: z.string(),- dryRun: z.boolean().optional()+ id: z.string()+ }),+ // The strict backflush check of a "jobOperation" issue, with no writes. Its+ // own type, so an ERP that predates it refuses it rather than issuing.+ z.object({+ type: z.literal("jobOperationDryRun"),+ quantity: z.number(),+ id: z.string()}),z.object({type: z.literal("jobOperationBatchComplete"),@@ -554,6 +560,7 @@ export const MES_POSTINGS = {"convertEntity","jobOperation","jobOperationBatchComplete",+ "jobOperationDryRun","jobOperationScrap","jobOperationSerialComplete","maintenanceDispatchInventory",