Skip to content

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

feat(production): strict backflush — Pull From required, backflush only from it

naveenkashd084030f7927
diff --git a/.ai/plans/2026-10-14-strict-backflush.md b/.ai/plans/2026-10-14-strict-backflush.md
new file mode 100644
index 0000000000..ec73e1a07c
--- /dev/null
+++ b/.ai/plans/2026-10-14-strict-backflush.md
@@ -0,0 +1,268 @@
+# Strict backflush — implementation plan
+
+**Spec:** .ai/specs/2026-10-14-strict-backflush.md
+**Research:** none (every decision came from the user in the design chat)
+**Branch:** naveenkash/mxnb2
+
+## Progress
+- [x] Task 1: Write the migration (column + `backflush_job_materials` fork)
+- [x] Task 2: Apply the migration and regenerate the types
+- [x] Task 3: Add the pure rule module `@carbon/database/strict-backflush`
+- [x] Task 4: Add the server-function helpers and enforce them in `issue`
+- [x] Task 5: Gate method activation in `convert`
+- [x] Task 6: Show the activation refusal in the ERP
+- [x] Task 7: Refuse job release with a line that has no storage unit
+- [x] Task 8: Add the settings card and its services
+- [x] Task 9: Mark Pull From as required in the BoM editor
+- [x] Task 10: MES dry run and refusal messages
+- [x] Task 11: Docs, MCP digest, translations
+- [x] Task 12: Final verification
+
+## Dependencies
+Task 2 needs Task 1. Tasks 3–10 need Task 2 (types). Tasks 4, 5 and 7 need Task 3. Task 10 needs Task 4. Task 6 needs Task 5. Tasks 8 and 9 are independent of each other. Task 12 is last.
+
+No task commits. The user asks before each commit.
+
+---
+
+## Task 1: Write the migration
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_strict-backflush.sql`
+- Copy from (precedent): `packages/database/supabase/migrations/20261009010412_job-costing-always-post.sql`, lines 13 to the end of `backflush_job_materials`
+
+**Steps:**
+1. Run `pnpm db:migrate:new strict-backflush`.
+2. Add the column:
+ ```sql
+ ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "requireBackflushStorageUnit" BOOLEAN NOT NULL DEFAULT false;
+ ```
+3. Copy `backflush_job_materials` from `20261009010412` without changes.
+4. Declare `v_strict BOOLEAN;` and `v_item_tracking_type TEXT;`.
+5. Before the loop, read `requireBackflushStorageUnit` from `companySettings` into `v_strict`. Use `COALESCE(…, false)`.
+6. Add `LEFT JOIN "item" i ON i.id = jm."itemId"` to the loop query. Select `i."itemTrackingType"`.
+7. If `v_strict` and the tracking type is not `Non-Inventory`, replace the whole storage unit step with the strict branch:
+ - If `jm."storageUnitId"` is null, raise `'% has no Pull From storage unit on job %'`.
+ - Sum the untracked on-hand of the item at that bin, location and company.
+ - If the sum is less than the quantity to issue, raise `'Not enough % in %: need %, have %'`.
+8. Keep the existing storage unit step unchanged in the `ELSE` branch.
+9. Diff the new function body against the `20261009010412` body.
+
+**Verify:**
+```bash
+diff <(awk '/FUNCTION public.backflush_job_materials/,/^\$function\$;/' packages/database/supabase/migrations/20261009010412_job-costing-always-post.sql) <(awk '/FUNCTION public.backflush_job_materials/,/^\$function\$;/' packages/database/supabase/migrations/*_strict-backflush.sql)
+# Expected: only the declarations, the settings read, the join, and the strict branch differ
+```
+
+**Out of scope:** `complete_job_to_inventory`. Do not copy it.
+
+## Task 2: Apply the migration and regenerate the types
+
+**Depends on:** 1
+**Steps:**
+1. Run `pnpm db:migrate`.
+2. Run `pnpm run generate:types`.
+
+**Verify:**
+```bash
+grep -c "requireBackflushStorageUnit" packages/database/src/types.ts
+# Expected: 3 or more (Row, Insert, Update)
+```
+
+If the local database is down, STOP and report. Do not hand-edit the types.
+
+## Task 3: Add the pure rule module
+
+**Depends on:** 2
+**Files:**
+- Create: `packages/database/src/strict-backflush.ts`
+- Create: `packages/database/src/strict-backflush.test.ts`
+- Modify: `packages/database/package.json` — add the export `"./strict-backflush": "./src/strict-backflush.ts"`
+- Copy from (precedent): `packages/database/src/supersession-pick.ts` and its test
+
+**Steps:**
+1. Export `PULLED_ITEM_TYPES = ["Material", "Part", "Consumable"]`.
+2. Export `needsPullFrom({ methodType, itemType, itemTrackingType })`. It returns true for a pulled, stocked line (spec decision 2).
+3. Export `missingPullFromLocations(storageUnitIds, locationIds)`. It returns each location id with no non-empty storage unit.
+4. Export `binShortfall({ onHand, alreadyDrawn, quantity })`. It returns the quantity the bin cannot cover, or 0.
+5. Test each function. Include a null `itemTrackingType`, a `Make to Order` line, an empty-string bin, and stock drawn earlier in the same call.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/database exec vitest run src/strict-backflush.test.ts
+# Expected: all tests pass
+```
+
+## Task 4: Add the server-function helpers and enforce them in `issue`
+
+**Depends on:** 3
+**Files:**
+- Create: `packages/server-functions/src/lib/strict-backflush.ts`
+- Modify: `packages/server-functions/src/issue/index.ts` — `issueJobOperationMaterials`, the `partToOperation` planned-material branch, the `jobOperation` input and case
+
+**Steps:**
+1. In the new file, write `isStrictBackflush(trx, companyId)`. It reads `companySettings.requireBackflushStorageUnit`.
+2. Write `assertBinCovers(trx, { companyId, itemId, locationId, storageUnitId, quantity, plannedRows })`.
+3. If `storageUnitId` is null, throw `ServerFnError("<part> has no Pull From storage unit on this job", 409)`.
+4. Otherwise sum the untracked on-hand at the bin. Subtract the planned rows for the same item and bin. Use `binShortfall`.
+5. If there is a shortfall, throw `ServerFnError("Not enough <part> in <bin>: need <n>, have <m>", 409)`.
+6. In `issueJobOperationMaterials`, read `isStrictBackflush` once.
+7. If strict and the item is Inventory-tracked, give the remainder `material.storageUnitId`, then run `assertBinCovers` with `itemLedgerInserts`.
+8. In that strict branch, skip the pick-method lookup, the fullest-bin lookup and the short-bin switch.
+9. In `partToOperation` with a `materialId`, apply the same strict branch to a consuming issue only.
+10. Add `dryRun: z.boolean().optional()` to the `jobOperation` input.
+11. In the `jobOperation` case, if `dryRun` and not strict, return at once.
+12. If `dryRun` and strict, run the issue and throw a private rollback sentinel at the end of the transaction. Catch only that sentinel.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/server-functions
+# Expected: 0 errors
+pnpm --filter @carbon/server-functions test
+# Expected: same pass/fail count as before the change
+```
+
+**Out of scope:** the unplanned-part branch, `maintenanceDispatchInventory`, batch and serial issue.
+
+## Task 5: Gate method activation in `convert`
+
+**Depends on:** 3
+**Files:**
+- Modify: `packages/server-functions/src/convert/index.ts` — `methodVersionToActive`
+
+**Steps:**
+1. Before the transaction, read `isStrictBackflush(db, companyId)`.
+2. If strict, load the version's `methodMaterial` rows with `item.itemTrackingType` and `item.readableIdWithRevision`.
+3. Load the location ids and names that have an active work center for the company.
+4. Filter the lines with `needsPullFrom`. Then find their gaps with `missingPullFromLocations`.
+5. If any gap exists, throw `InvalidInputError`. The message lists each part once, separated by "; ".
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/server-functions
+# Expected: 0 errors
+```
+
+## Task 6: Show the activation refusal in the ERP
+
+**Depends on:** 5
+**Files:**
+- Modify: `apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx` — return `update.error.message` when it is not empty
+- Modify: `apps/erp/app/modules/items/items.server.ts` — `applyChangeNotice` returns `activated.error.message` when it is not empty
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+```
+
+## Task 7: Refuse job release with a line that has no storage unit
+
+**Depends on:** 3
+**Files:**
+- Modify: `apps/erp/app/modules/production/production.service.ts` — `JobReleaseReadiness`, `getJobReleaseReadiness`
+- Modify: `apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts` — `jobReleaseProblems`
+- Modify: `apps/erp/app/routes/x+/job+/$jobId.status.tsx` — the Release dialog branch
+- Modify: `apps/erp/test/job-release-logic.test.ts`, `apps/erp/test/job-release-readiness.test.ts`
+
+**Steps:**
+1. Add `materialsWithoutStorageUnit: { id: string; description: string }[]` to each readiness job.
+2. In `getJobReleaseReadiness`, read the setting. If it is off, return empty lists.
+3. If it is on, load the jobs' `jobMaterial` rows with `item.itemTrackingType`. Keep the `needsPullFrom` lines with no `storageUnitId`.
+4. In `jobReleaseProblems`, add `set a Pull From storage unit on <parts>`.
+5. In `$jobId.status.tsx`, refuse with that text when the list is not empty.
+6. Update both tests for the new field. Add one test for the new problem text.
+
+**Verify:**
+```bash
+pnpm --filter erp exec vitest run test/job-release-logic.test.ts test/job-release-readiness.test.ts
+# Expected: all tests pass
+```
+
+## Task 8: Add the settings card and its services
+
+**Depends on:** 3
+**Files:**
+- Modify: `apps/erp/app/modules/settings/settings.service.ts` — `updateRequireBackflushStorageUnitSetting(client, companyId, enabled)` and `getActiveMethodsMissingPullFrom(db, companyId)`
+- Modify: `apps/erp/app/routes/x+/settings+/items.tsx` — intent `requireBackflushStorageUnit`, loader count, the card
+- Copy from (precedent): the "BoM Explorer" card and `updateBomExplorerReadableIdSetting` in the same files
+
+**Steps:**
+1. `getActiveMethodsMissingPullFrom` uses Kysely. It loads Active make methods with their lines and the work-center locations. It returns `{ count, methods }`, with at most 10 methods.
+2. The loader calls it only when the setting is on.
+3. Add the card under "Bill of Materials". Copy the BoM Explorer card layout.
+4. When the count is above 0, list the parts with links to `path.to.partMake(itemId, makeMethodId)`.
+
+If an Active method's parent item is not a Part, link to the item's own make route. If no such route exists, STOP and report.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+```
+
+## Task 9: Mark Pull From as required in the BoM editor
+
+**Depends on:** 2
+**Files:**
+- Modify: `apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx`
+- Copy from (precedent): `useCompanySettings` in `apps/erp/app/hooks/useCompanySettings.tsx`
+
+**Steps:**
+1. Read `requireBackflushStorageUnit` with `useCompanySettings()`.
+2. If strict, pass `isOptional={false}` to the Storage Unit field of a pulled line.
+3. If strict and the line has no bin for the location, show the badge "No storage unit".
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp
+# Expected: 0 errors
+```
+
+## Task 10: MES dry run and refusal messages
+
+**Depends on:** 4
+**Files:**
+- Modify: `apps/mes/app/routes/x+/complete.tsx`, `apps/mes/app/routes/x+/end.$operationId.tsx`, `apps/mes/app/services/quality.server.ts` — dry run before `insertProductionQuantity`
+- Modify: the same files plus `apps/mes/app/routes/x+/scrap.tsx` and `apps/mes/app/routes/x+/issue.tsx` — show `error.message || <old fallback>`
+
+**Steps:**
+1. Before each untracked `insertProductionQuantity`, invoke `issue` with `type: "jobOperation"`, the same id and quantity, and `dryRun: true`.
+2. If the dry run fails, return the old error response with the server's message. Record nothing.
+3. In each `issue` error toast, use the server's message, with the old text as the fallback.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=mes
+# Expected: 0 errors
+```
+
+## Task 11: Docs, MCP digest, translations
+
+**Depends on:** 4–10
+**Steps:**
+1. Add a "Strict backflush" section to `.claude/rules/inventory-system.md`. Name the setting, the three gates, and the files.
+2. Run `pnpm run generate:mcp`.
+3. Run `pnpm run lingui:extract`.
+4. Run `pnpm --filter @carbon/checks license-headers`.
+
+**Verify:**
+```bash
+git status --short
+# Expected: the digest, the .po catalogs and the rule file changed; no unrelated files
+```
+
+## Task 12: Final verification
+
+**Depends on:** all
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/database --filter=@carbon/server-functions --filter=erp --filter=mes
+# Expected: 0 errors
+pnpm --filter @carbon/database test && pnpm --filter @carbon/server-functions test
+# Expected: no new failures
+pnpm exec biome check <changed files>
+# Expected: no errors
+```
diff --git a/.ai/playbooks/strict-backflush.md b/.ai/playbooks/strict-backflush.md
new file mode 100644
index 0000000000..c6b26e01d5
--- /dev/null
+++ b/.ai/playbooks/strict-backflush.md
@@ -0,0 +1,47 @@
+# Strict Backflush
+
+Last tested: 2026-10-15
+Routes: `/x/settings/items`, `/x/part/<itemId>/make/<makeMethodId>`, `/x/job/<jobId>`,
+`/x/production/jobs`, `/x/picking-list/schedule`, MES `/x/operation/<jobOperationId>`
+
+## Prerequisites
+- Satellite demo dataset ("Carbon Development"). Manufacturing Plant has storage units
+ A1-L1 … A3-L3 and lineside floors; Headquarters has a work center but NO storage unit.
+- PCB-ADCS-R1 (`item_FGQD2WDhDcoMJWVDTNdEWV`) has a 2-line BoM (PCB-BARE-REV3,
+ MAT-CONFCOAT) and no open change notice. SAW-001 v2 is locked by a change notice —
+ "Set as Active Version" is disabled there for an unrelated reason.
+- Seeded jobs (J000003 Planned, J000004 Draft) have no `jobMaterial.storageUnitId`.
+
+## Steps
+### 1. Settings — `/x/settings/items` → "Strict Backflush" card switch.
+Expect "Strict backflush is on" and "1 active method has materials with no Pull From"
+with a link (SAW-001).
+### 2. Activation — part make page → version button ("V1 Draft") → hover "Version 1 Draft"
+→ "Set as Active Version" → "Make Active". With gaps: toast
+"Set a Pull From storage unit before you activate this version: <part>; <part>".
+### 3. Release — job page → "Release". With gaps the dialog shows "Missing Storage Units"
+(one entry per part) and "Release Job" is disabled. Bulk: jobs list → row checkbox →
+selection-count button → "Release Jobs" → toast "Could not release 1: J000003 (set a Pull From …)".
+### 4. MES completion — operation page → "Log completed" → "Increase" → "Log Completed".
+Short bin: toast "Not enough A in BIN: need n, have m; Not enough B …" and NO
+`productionQuantity` row. Covered bin: "Operation finished successfully", consumption only
+from the line's bin.
+### 5. ERP job complete — job page → "Complete" → "Increase" → "Complete Job".
+Short bin: toast lists every short material (SQL `backflush_job_materials`).
+### 6. Picked stock — `/x/picking-list/schedule` → select job → "Generate Picking List 1" →
+"Pick" each line → MES completion consumes from the lineside bin, no refusal.
+### 7. MES manual issue — operation page → material row "Issue Material" → "Issue".
+
+## Selector Notes
+- BoM / job BoM line Storage Unit combobox does not open from an `agent-browser click`
+ on its ref: read its rect with `eval` and use `mouse move/down/up` on it.
+- After a BoM line saves it collapses but its form stays in the DOM (hidden). Reload
+ before editing a second line, or a ref match may land in the hidden form.
+- Inventory adjustment modal: wait ~1 s after opening before clicking the storage unit
+ combobox (the backdrop still covers it). If the storage unit is not chosen, the
+ adjustment silently goes to the UNASSIGNED bin.
+- Number fields (react-aria): `fill` then `press Tab`, and check the hidden input.
+
+## Common Failures
+- Saving a BoM line resyncs `methodType` to the item's default (Buy items become
+ Purchase to Order) — pre-existing behavior, not strict backflush.
diff --git a/.ai/runs/2026-10-14-strict-backflush.md b/.ai/runs/2026-10-14-strict-backflush.md
new file mode 100644
index 0000000000..e6f25884c4
--- /dev/null
+++ b/.ai/runs/2026-10-14-strict-backflush.md
@@ -0,0 +1,32 @@
+# Feature run: Strict backflush (CARBON-113)
+
+- Date: 2026-10-14
+- Mode: fully-autonomous
+- Request: "sounds good write the spec and implement it" (after the design and decisions 1–7 in the chat)
+- Phase plan: research [skip — the user resolved every decision in the chat] · spec [run] · plan [run] · execute [run] · test [skip — the user did not ask for a browser test] · self-review [run]
+
+## Decisions
+
+- Spec gate: every open question has a human answer from the chat ("sounds good" to recommendations 1–7). No autonomous resolution was necessary for the 7 questions. — 2026-10-14
+- Spec, autonomous detail: the Pull From requirement covers Purchase to Order lines too. The BoM editor labels them "Pull From" and the backflush consumes them from a bin. — 2026-10-14
+- Spec, autonomous detail: MES records the production quantity before it issues material. A strict refusal at that point would leave produced units with no consumption. The MES routes run the issue as a dry run first, only when strict backflush is on. — 2026-10-14
+- Plan gate: plan approved autonomously after the STE-80 pass. — 2026-10-14
+- Execute: no commits. The user's standing rule is "ask before every commit". The execute skill's per-task commit is replaced by per-task verification. — 2026-10-14
+
+- Execute: the strict-backflush docs went into `apps/erp/app/modules/production/AGENTS.md`, not `.claude/rules/inventory-system.md`. The production module owns backflush, and rules document committed code only. — 2026-10-14
+- Self-review: added a transaction-scoped advisory lock on (company, bin, item) to the TypeScript and SQL bin checks, against two completions overdrawing one bin. The migration file changed after `pnpm db:migrate` applied it locally, so the local `backflush_job_materials` has no lock until it is re-applied. — 2026-10-14
+- Self-review: the DB-backed regression file `packages/server-functions/src/strict-backflush.test.ts` was not run. It creates and deletes a scratch company, and the user asks before any database write. — 2026-10-14
+
+- Browser test (user request 2026-10-15): ran through the UI as the dev user. The user asked for the test, so the UI writes (settings, BoM edits, 2 jobs, releases, picks, completions, inventory adjustments) are part of it. A script error put 1 PCB-BARE-REV3 and 1 MAT-CONFCOAT into the unassigned bin; both were set back to 0 through the same form. The migration's function was re-applied locally (`psql -f`) to test the SQL fix. — 2026-10-15
+
+## Phase log
+
+- spec: `.ai/specs/2026-10-14-strict-backflush.md` — STE-80 pass done
+- plan: `.ai/plans/2026-10-14-strict-backflush.md` — STE-80 pass done, all 12 tasks checked
+- execute: typecheck green (`@carbon/database`, `@carbon/server-functions`, `erp`, `mes`); tests green (ERP 2054, MES 69, server functions 365, database 476, checks 305); Biome clean; clobbers clean
+- self-review: lock added (above); no other must-fix
+- browser test: 6 bugs found and fixed (see the spec changelog, 2026-10-15); playbook `.ai/playbooks/strict-backflush.md`; gates green again (ERP 2057, MES 69, server functions 365, database 476, checks 305)
+
+## Outcome
+
+- Committed and pushed on the user's request (2026-10-15), PR opened. The branch was fast-forwarded to origin/main first; the migration moved to `20261015122149_strict-backflush.sql` so it is newer than main's latest. Translations filled by `/translate` (120 strings + 14 re-translated where the glossary term was dropped).
diff --git a/.ai/specs/2026-10-14-strict-backflush.md b/.ai/specs/2026-10-14-strict-backflush.md
new file mode 100644
index 0000000000..5443b65ec9
--- /dev/null
+++ b/.ai/specs/2026-10-14-strict-backflush.md
@@ -0,0 +1,168 @@
+# Strict backflush
+
+> Status: implemented
+> Author: naveenkash
+> Date: 2026-10-14
+> Ticket: CARBON-113 — Backflush rules
+
+## TLDR
+
+Strict backflush is a company setting on **Settings → Items**. It is off by default. When it is on, three rules apply:
+
+1. A method version cannot become Active while a pulled material line has no Pull From storage unit.
+2. A job cannot be released while a pulled material line has no storage unit.
+3. A backflush takes material only from the material line's storage unit. If that storage unit holds too little stock, Carbon refuses the backflush, and the operation or the job does not complete.
+
+Picked stock at the lineside bin still counts. Batch and serial issue does not change.
+
+## Overview diagram
+
+```mermaid
+flowchart LR
+ subgraph Before
+ B1["Material line bin"] --> B2["else pick method bin"]
+ B2 --> B3["else fullest bin"]
+ B3 --> B4["consume, can go negative"]
+ end
+ subgraph After["After, strict backflush on"]
+ A1["Material line bin"]:::hot --> A2["bin covers the quantity?"]:::new
+ A2 -->|"yes"| A3["consume"]
+ A2 -->|"no"| A4["refuse, nothing posts"]:::new
+ end
+ classDef hot stroke-width:3px
+ classDef new stroke-dasharray:4 3
+```
+
+## Problem Statement
+
+A material controller keeps the same part in more than one storage unit. The BoM line names the storage unit that production must pull from ("Pull From"). Today Carbon does not hold the backflush to it:
+
+| Path | File | What it does when the Pull From bin is empty or short |
+|---|---|---|
+| Operation completion | `packages/server-functions/src/issue/index.ts` `issueJobOperationMaterials` | Uses the pick method's default bin, then the fullest bin. If the chosen bin is short, it switches to the fullest bin. |
+| Job completion | SQL `backflush_job_materials` (`20261009010412_job-costing-always-post.sql`) | Uses the pick method's default bin, then the fullest bin. A warehouse bin is not capped, so it can go negative. A lineside bin is capped silently, so the job consumes less than it needs. |
+| Manual issue and step-record backflush | `issue` `partToOperation` | Uses the pick method's default bin, then the fullest bin. |
+| Method activation | `convert` `methodVersionToActive` | Does not check the materials. |
+
+Example: the BoM says "pull 10 × PART-123 from Shelf A-4". Shelf A-4 has 6 and Shelf B-2 has 50. The operation completes, and Carbon takes all 10 from Shelf B-2. The records for both shelves are now wrong.
+
+## Proposed Solution
+
+### Design Decisions
+
+| # | Decision | Choice | Rationale |
+|---|---|---|---|
+| 1 | Where the setting lives | One company setting, `companySettings.requireBackflushStorageUnit`, on Settings → Items. Default `false`. | The rule is a warehouse policy, not a property of one part. A per-item flag leaves unflagged parts on the old behavior with no warning. |
+| 2 | Which lines need a Pull From | A method material line needs a Pull From when its `methodType` is not `Make to Order`, its `itemType` is Material, Part or Consumable, and its item's `itemTrackingType` is not `Non-Inventory`. | The backflush reads exactly these lines (`issueJobOperationMaterials`, `backflush_job_materials`). A Make to Order line is built, not pulled. A Purchase to Order line is consumed from a bin, and the BoM editor labels it "Pull From". |
+| 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. | 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. |
+| 6 | Where a shortage stops the work | At operation completion (MES and ERP), at job completion, and at manual issue of a planned material. | If only job completion stopped, the operation would take stock from another bin first. |
+| 7 | Batch and serial items | The activation and release checks include them. Their issue flow does not change. | An operator scans the unit, and the unit knows its own bin. |
+| 8 | Methods that are already Active | Carbon does not change them. The settings card shows how many Active methods have a gap, and lists them. | Changing a live method without warning is a large risk. |
+| 9 | Produced units with no consumption | MES records a production quantity before it calls `issue`. When strict backflush is on, MES first runs `issue` as a dry run (all writes rolled back). If the dry run fails, MES records nothing. | Without the dry run, a refusal leaves produced units with no material consumed. A retry then records the units a second time. |
+| 10 | Error text | The refusal names the part, the storage unit, the quantity needed and the quantity on hand. One refusal lists every short material. MES and ERP show the server's message instead of a fixed fallback. | "Failed to issue materials" tells the operator nothing to fix. A refusal that names one part at a time makes the material controller fix them one retry at a time. |
+| 11 | One rule, three users | The line predicate lives once in `@carbon/database/strict-backflush`. Activation, release and the settings card all read it. | Three copies of the rule would drift apart. |
+
+### Out of scope
+
+| Path | Why |
+|---|---|
+| 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
+
+One new column. One function replaced.
+
+```sql
+ALTER TABLE "companySettings"
+ ADD COLUMN "requireBackflushStorageUnit" BOOLEAN NOT NULL DEFAULT false;
+```
+
+`backflush_job_materials` is replaced with a copy of its live definition (`20261009010412_job-costing-always-post.sql`). The only changes are in the storage unit step:
+
+1. Read `requireBackflushStorageUnit` once, before the loop.
+2. If the setting is on and the item is stocked, use `jobMaterial.storageUnitId` only.
+3. If that storage unit is null, `RAISE EXCEPTION` with the part name.
+4. Take `pg_advisory_xact_lock` on the key `strict-backflush:<companyId>:<storageUnitId>:<itemId>`. The TypeScript check takes the same key.
+5. If the storage unit's untracked on-hand is less than the quantity, `RAISE EXCEPTION` with the part, the storage unit, the quantity needed and the on-hand.
+6. If the setting is off, the function behaves exactly as before.
+
+No new table. No RLS change.
+
+## API / Service Changes
+
+| Where | Change |
+|---|---|
+| `packages/database/src/strict-backflush.ts` (new, export `@carbon/database/strict-backflush`) | `needsPullFrom(line)`, `missingPullFromLocations(storageUnitIds, locationIds)`. Pure, unit-tested. |
+| `packages/server-functions/src/lib/strict-backflush.ts` (new) | `isStrictBackflush(trx, companyId)` reads the setting. `assertBinCovers(trx, …)` takes the bin lock, then throws a `ServerFnError` with status 409 when the bin is missing or short. `assertMethodHasPullFrom(db, …)` is the activation check. |
+| `@carbon/database/strict-backflush` | Also `getPullFromLocations(db, companyId)`: the one query for "locations with an active work center". |
+| `convert` `methodVersionToActive` | 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 "; ". |
+| `issue` `issueJobOperationMaterials` | 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. |
+| `issue` `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. |
+| `issue` input `jobOperation` | 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. |
+| `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". |
+| `$jobId.status.tsx` (Release dialog path) | Refuses a job with `materialsWithoutStorageUnit` and names the parts. |
+| `settings.service.ts` | `updateRequireBackflushStorageUnitSetting` and `getActiveMethodsMissingPullFrom(db, companyId)`. |
+| `versions.activate.$id.tsx`, `applyChangeNotice` | Show the server's message when activation fails. |
+| MES `complete.tsx`, `end.$operationId.tsx`, `quality.server.ts` | Run the `dryRun` issue before `insertProductionQuantity`. Show the server's message. |
+| MES `scrap.tsx`, `issue.tsx` | Show the server's message. |
+| ERP `completeOperation`, `batch-operations` `complete` | Run the `dryRun` issue before the production quantity is written (batch: before phase 1). |
+| MES `end.$operationId.tsx` serial branch | Stop on an `issue` error. Before this change the route ignored the error and finished the operation. |
+| MES `backflushUntrackedMaterialsOnStepRecord` | The failure message lists the server's messages instead of bare item ids. |
+
+## UI Changes
+
+- **Settings → Items → Bill of Materials:** a new "Strict Backflush" card with a switch. When strict backflush is on, the card shows "N active methods have materials with no Pull From". It lists up to 10 of the parts, each linked to its make method.
+- **Job → Release dialog:** when strict backflush is on, a "Missing Storage Units" warning lists each part once and disables Release Job.
+- **Job → BoM line:** the same red "No storage unit" badge, and Storage Unit is not marked optional.
+- **Part → Manufacturing → BoM line:** when strict backflush is on, the Storage Unit field is no longer marked optional. A line with no Pull From for the selected location shows the badge "No storage unit" instead of "Default Storage Unit".
+- **Errors:** activation, release, MES completion and ERP job completion show the refusal text as a toast.
+
+## Acceptance Criteria
+
+- [ ] With strict backflush off, every path behaves as before. All existing `issue`, `get-method` and `convert` tests pass.
+- [ ] A user turns on strict backflush. A BoM has a Part line with no Pull From at a location that has a work center. The user activates the version and sees an error that names each part once: "Set a Pull From storage unit before you activate this version: MAT-GAAS-CELL; MAT-CF-LAM; MAT-KAPTON". The version stays Draft.
+- [ ] The same line is a Make to Order line, or a Non-Inventory item. Activation succeeds.
+- [ ] A Draft job has a pulled Inventory line with no `storageUnitId`. Release refuses and names the part.
+- [ ] A job line pulls 10 from Shelf A-4. Shelf A-4 holds 6, Shelf B-2 holds 50. The operator completes the operation in MES. Carbon shows "Not enough PART-123 in Shelf A-4: need 10, have 6". No production quantity, no ledger row and no journal is written.
+- [ ] Shelf A-4 holds 10. The operation completes, and the ledger row is against Shelf A-4.
+- [ ] 6 of the 10 were picked to the lineside bin, and Shelf A-4 holds 4. The operation completes. 6 come from the lineside bin and 4 from Shelf A-4.
+- [ ] ERP Job → Complete with a short bin shows the refusal text, and the job stays open.
+- [ ] The settings card shows the count of Active methods with a gap.
+- [ ] Unit tests pin `needsPullFrom`, `missingPullFromLocations` and the shortfall arithmetic.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| Operators are blocked mid-job by a stock error | Med | This is the requested behavior. The message names the part, the bin and the quantities. The setting is off by default. |
+| The SQL fork drops a branch of `backflush_job_materials` | High | Fork from the newest definition (`20261009010412`). Diff the new body against it so that only the strict hunks differ (lesson "Forking a SQL function migration"). |
+| A refusal at job completion inside the MES Finish trigger shows a fixed message | Low | The operation-completion check runs first and catches most shortfalls. The ERP Job → Complete route already shows the RAISE text. |
+| 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
+
+- [x] Company toggle or per item? — **Answer:** company-wide on Settings → Items (user, 2026-10-13).
+- [x] Which locations must have a Pull From? — **Answer:** each location with at least one active work center (user, 2026-10-13).
+- [x] Draft methods feed jobs. Check at release too? — **Answer:** yes, refuse release of a job line with no storage unit (user, 2026-10-13).
+- [x] Does picked stock at the lineside bin count? — **Answer:** yes; the strict rule applies to the remainder (user, 2026-10-13).
+- [x] Where does a shortage stop the work? — **Answer:** at operation completion and at job completion (user, 2026-10-14).
+- [x] Batch and serial items? — **Answer:** require the Pull From at activation; the issue flow does not change (user, 2026-10-13).
+- [x] Methods already Active when the setting turns on? — **Answer:** do not change them; show the count and the list on the settings card (user, 2026-10-14).
+- [x] Purchase to Order lines? — **Autonomous:** include them. The backflush consumes them from a bin, and the editor labels them "Pull From".
+- [x] Produced units with no consumption after a refusal? — **Autonomous:** MES runs a dry-run issue first when strict backflush is on.
+
+## Changelog
+
+- 2026-10-14: Created from the CARBON-113 design discussion.
+- 2026-10-15: Long lists. A 20-line BoM produced a 912-character toast that ran off a small screen and faded before it could be read. Every strict refusal now names the first entries and counts the rest (`summarizeList`: 5 part names, 3 shortfalls; the SQL caps at 3 too). The Release dialog keeps the full list in a scroll box, and a collapsed BoM or job BoM row shows a red "No storage unit" badge.
+- 2026-10-15: The activation error names only the parts, not the locations (user request).
+- 2026-10-15: Browser test. Fixed: a location with a work center but no storage unit blocked activation for good; the release list named a part twice; the Release dialog did not warn before submit; the job BoM line showed "Default Storage Unit" and "Optional"; a refusal named only the first short material (TypeScript and SQL).
+- 2026-10-14: Implemented. Added the bin lock, the dry run in ERP `completeOperation` and batch completion, and the MES serial-branch error check (found during the build).
diff --git a/apps/erp/app/hooks/useCompanySettings.tsx b/apps/erp/app/hooks/useCompanySettings.tsx
index 0861e4ab5b..8b5ef5d019 100644
--- a/apps/erp/app/hooks/useCompanySettings.tsx
+++ b/apps/erp/app/hooks/useCompanySettings.tsx
@@ -27,6 +27,7 @@ type CompanySettings = Partial<
| "digitalQuoteEnabled"
| "digitalQuoteIncludesPurchaseOrders"
| "mrpRunTime"
+ | "requireBackflushStorageUnit"
| "showBomExplorerReadableId"
| "showCurrencyTrailingZeros"
| "showCustomerReadableId"
diff --git a/apps/erp/app/modules/items/items.server.ts b/apps/erp/app/modules/items/items.server.ts
index be01229baf..618e003b08 100644
--- a/apps/erp/app/modules/items/items.server.ts
+++ b/apps/erp/app/modules/items/items.server.ts
@@ -693,7 +693,11 @@ async function releaseAffectedItem(
userId
});
if (activated.error) {
- return { error: { message: "Failed to activate method" } };
+ return {
+ error: {
+ message: activated.error.message || "Failed to activate method"
+ }
+ };
}
// Reveal the new item for Revision / New Part (Version edits the same item).
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index e4c481acd4..5a98cb33e9 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -5,6 +5,7 @@
"use client";
import { useCarbon } from "@carbon/auth";
import type { Database } from "@carbon/database";
+import { needsPullFrom } from "@carbon/database/strict-backflush";
import { ValidatedForm } from "@carbon/form";
import {
Badge,
@@ -86,6 +87,7 @@ import {
} from "~/components/SortableList";
import { CompactEmpty } from "~/components/Table/components/Compact/CompactEmpty";
import { usePermissions, useUrlParams, useUser } from "~/hooks";
+import { useCompanySettings } from "~/hooks/useCompanySettings";
import type {
MethodItemType,
MethodType,
@@ -256,13 +258,30 @@ const BillOfMaterial = ({
configurationRules?.map((rule) => [rule.field, rule]) ?? []
);
+ // Strict backflush: mark collapsed rows with no Pull From at the user's
+ // location — the same test as the open line's "No storage unit" badge.
+ const companySettings = useCompanySettings();
+ const { defaults } = useUser();
+ const missingPullFrom = (material: Material) =>
+ companySettings?.requireBackflushStorageUnit === true &&
+ !!defaults.locationId &&
+ needsPullFrom({
+ methodType: material.methodType,
+ itemType: material.itemType,
+ itemTrackingType: material.item?.itemTrackingType ?? null
+ }) &&
+ !(material.storageUnitIds as Record<string, string> | null)?.[
+ defaults.locationId
+ ];
+
const materials = makeItems(
items,
Array.from(materialsById.values()),
orderState,
checkedState,
rulesByField,
- replenishmentSystem
+ replenishmentSystem,
+ missingPullFrom
).sort((a, b) => a.data.order - b.data.order);
const onToggleItem = (id: string) => {
@@ -697,6 +716,17 @@ function MaterialForm({
item.data.item?.replenishmentSystem ?? replenishmentSystem ?? "Buy"
});
+ // Strict backflush: a pulled, stocked line must name the storage unit it is
+ // backflushed from before its method version can be made active.
+ const companySettings = useCompanySettings();
+ const requiresPullFrom =
+ companySettings?.requireBackflushStorageUnit === true &&
+ needsPullFrom({
+ methodType: itemData.methodType,
+ itemType,
+ itemTrackingType: item.data.item?.itemTrackingType ?? null
+ });
+
// methodType/sourcingType are read-only mirrors of the component item
// (see method-material-sourcing rule). Re-sync them when the loader row
// changes — e.g. after the properties panel updates the default method type —
@@ -980,15 +1010,22 @@ function MaterialForm({
: ""
)}
/>
- <Badge variant="secondary">
- <LuGitPullRequest className="size-3 mr-1" />
- {storageUnits.options?.find(
- (s) => s.value === itemData.storageUnitIds[locationId ?? ""]
- )?.label ??
- (itemData.methodType === "Make to Order"
- ? "WIP"
- : "Default Storage Unit")}
- </Badge>
+ {requiresPullFrom && !itemData.storageUnitIds[locationId ?? ""] ? (
+ <Badge variant="red">
+ <LuGitPullRequest className="size-3 mr-1" />
+ <Trans>No storage unit</Trans>
+ </Badge>
+ ) : (
+ <Badge variant="secondary">
+ <LuGitPullRequest className="size-3 mr-1" />
+ {storageUnits.options?.find(
+ (s) => s.value === itemData.storageUnitIds[locationId ?? ""]
+ )?.label ??
+ (itemData.methodType === "Make to Order"
+ ? "WIP"
+ : "Default Storage Unit")}
+ </Badge>
+ )}
<IconButton
icon={<LuChevronRight />}
aria-label={
@@ -1058,7 +1095,7 @@ function MaterialForm({
}
}));
}}
- isOptional
+ isOptional={!requiresPullFrom}
/>
</div>
</div>
@@ -1221,7 +1258,8 @@ function makeItems(
orderState: OrderState,
checkedState: CheckedState,
rulesByField?: Map<string, ConfigurationRule>,
- replenishmentSystem?: string
+ replenishmentSystem?: string,
+ missingPullFrom?: (material: Material) => boolean
): ItemWithData[] {
return materials.map((material) => {
const order = material.id
@@ -1234,7 +1272,8 @@ function makeItems(
order,
checked,
rulesByField,
- replenishmentSystem
+ replenishmentSystem,
+ missingPullFrom?.(material) ?? false
);
});
}
@@ -1256,7 +1295,8 @@ function makeItem(
order: number,
checked: boolean,
rulesByField?: Map<string, ConfigurationRule>,
- replenishmentSystem?: string
+ replenishmentSystem?: string,
+ missingPullFrom = false
): ItemWithData {
const hasRules = material.id
? materialHasRules(material.id, rulesByField)
@@ -1274,6 +1314,7 @@ function makeItem(
items.find((i) => i.id === material.itemId)?.supersessionMode
}
hasRules={hasRules}
+ missingPullFrom={missingPullFrom}
/>
),
checked,
diff --git a/apps/erp/app/modules/items/ui/Item/MethodRow.tsx b/apps/erp/app/modules/items/ui/Item/MethodRow.tsx
index ac9c224e82..f0b5a32fae 100644
--- a/apps/erp/app/modules/items/ui/Item/MethodRow.tsx
+++ b/apps/erp/app/modules/items/ui/Item/MethodRow.tsx
@@ -89,7 +89,8 @@ export function MaterialRowTitle({
itemId,
itemType,
supersessionMode,
- hasRules
+ hasRules,
+ missingPullFrom
}: {
readableId?: string | null;
description?: string | null;
@@ -97,12 +98,21 @@ export function MaterialRowTitle({
itemType?: string | null;
supersessionMode?: Parameters<typeof ItemLifecycleBadge>[0]["mode"];
hasRules?: boolean;
+ /** Strict backflush: the line has no storage unit to backflush from. Shown
+ * on the collapsed row so a long BoM's gaps are found without opening
+ * every line. */
+ missingPullFrom?: boolean;
}) {
return (
<VStack spacing={0} className="py-1 cursor-pointer max-md:py-0">
<div className="flex w-full min-w-0 items-center gap-2 group">
<h3 className="font-semibold min-w-0 truncate">{readableId ?? ""}</h3>
<ItemLifecycleBadge mode={supersessionMode} />
+ {missingPullFrom && (
+ <Badge variant="red" className="shrink-0">
+ <Trans>No storage unit</Trans>
+ </Badge>
+ )}
{hasRules && (
<LuSquareFunction className="h-3.5 w-3.5 text-emerald-500 shrink-0" />
)}
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 223be5668c..0de63e3aa5 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -18,6 +18,17 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
- **Scheduling** — forecast-first finite scheduling run **IN-PROCESS in Node** via `runLocationSchedule` / `runExpediteWhatIf` from `@carbon/planning` (the ERP app and `@carbon/jobs` call it directly; the engine lives in `packages/planning/src/scheduling/`). It regenerates a **whole LOCATION** in one deterministic FORWARD-ASAP pass (no backward JIT pass in placement, no `initial`/`reschedule` modes). Machine availability comes from a per-work-center ladder: `workCenter.alwaysOn` = 24×7 lights-out → explicit `workCenterShift` rows → the location's `shift` rows → a stock Mon–Fri 8h week; open maintenance dispatches flagged `takesWorkCenterOffline` subtract downtime from those windows. Work centers are finite (capacity 1 — one op at a time) AND, for ability-gated processes, qualified PEOPLE are finite: work only accumulates while a qualified employee is on shift (`employeeShift` ⋈ `shift`; no shift assignment = the job location's calendar) and not reserved elsewhere. Started ops net **remaining work** only — labor+machine scaled by `(1 − quantityComplete/operationQuantity)`, setup done once any `productionEvent` exists. Placements persist as `capacityReservation` rows (a materialized output: delete-by-job + bulk insert per run, `scenarioId IS NULL`; `WorkCenter` + `Employee` kinds — `OperatorPool` is read-tolerated legacy, never written); the run also writes `job.projectedCompletionAt` (forecast finish) and clears the job's schedule-outdated stamps. **Dual dates** (`20260818031629_dual-dates.sql`, spec `.ai/specs/2026-08-15-dual-dates-due-vs-projected.md`): every regen writes each op's forward projection — `startDate` (projected start day) + `jobOperation.projectedCompletionAt` (projected finish instant) — and DIFF-writes `jobOperation.dueDate` from a backward demand-anchored need-by pass (`computeNeedByDates`, `packages/planning/src/scheduling/need-by-calculator.ts` — a pure pre-placement step: reverse-topo from `job.dueDate`, `operationLeadTime` + assembly lead times, day lengths from the work centers' real calendars). Targets NEVER floor placement; `manuallyScheduled` = a human owns the need-by (the pin is taken as-is, propagates upstream, and is never overwritten — pinned ops still place normally; the old frozen-window branch is gone). An op projected past its need-by gets an informational amber behind-target state (BOP rows, ops-board `ItemCard`, MES operation detail) — never per-op `hasConflict`; when the job is late, the cause sentence appends "First behind target: {op} (due X, projected Y)". `jobOperation.priority` = the per-work-center placement order (reservation start ascending) — one source of truth for dispatch order (there is no configurable dispatch-sequencing policy). **People assignments** (manning board, `peopleAssignment`) make a staffed station a TEAM: the station still runs ONE op at a time, but the whole team present is booked on that op together — labor is parallelized across the present people (two people halve the labor wall-clock; setup and machine time are never compressed). Gated ops team-book people∩qualified on their assigned dates, falling back to an any-qualified single-person relay — but the board is a COMMITMENT, not a soft preference: the fallback may only draw on true FLOATERS (people with NO board assignment anywhere in the horizon, via `assignmentsByEmployee.has(id)`). A person you have manned anywhere is spoken for and is never pulled to a station they weren't assigned to — so moving your only welder off a station makes that station's op an unschedulable placeholder (visible on the Forecast) rather than silently double-booking the welder or shoving the op onto an unmanned weekend. A blank board leaves every qualified person a floater ⇒ classic any-qualified fallback, unchanged. Ungated ops at a staffed station are manned the same way with machine-only fallback. **Require-staffing policy** (`location.requiresStaffing`, per-location, default off, edited on the Production settings page (Settings → Production → Scheduling)): when ON, the scheduler places work ONLY where an operator is manned — the gated floater fallback and the ungated machine-only fallback are both removed, EXCEPT lights-out (`workCenter.alwaysOn`) stations keep running unattended. An op with no manned coverage (and not lights-out) becomes an unschedulable placeholder, so work routes to the staffed work centers and unstaffed ones get nothing. Threaded through `provider.getLocationRequiresStaffing` + `getAlwaysOnWorkCenterIds` → `FiniteSchedulingContext.requiresStaffing` + `capacity.workCenter.alwaysOn`. `peopleAbsence` subtracts the person's availability for that date everywhere; `peopleAssignment.overtimeHours` lengthens the person's day (window extension) and `peopleAssignment.hours` splits deal the day out per station sequentially — all as pure window edits before allocation. A blank board changes nothing. To reschedule, call `notifyScheduleInputsChanged` (stamps jobs; the debounced wave regenerates the whole location) — never direct date writes. An expedite what-if (`expediteJobId`) re-runs the sim with one job first, simulate-only, and returns its projected completion.
- **Ability requirements** — resolved through the operation's PROCESS: `process.requiresAbility` → the ability linked 1:1 to the process (`ability.processId`) → **presence-based** `employeeAbility` qualification (a row exists ∧ not expired; no `active`/`trainingCompleted` gate). Gates both the scheduler's operator pools and MES operation start. There are no operation-level ability tables.
+### Strict backflush
+
+`companySettings.requireBackflushStorageUnit` (Settings → Items → Strict Backflush, off by default; spec `.ai/specs/2026-10-14-strict-backflush.md`). When it is on, a stocked material is consumed only from its own storage unit, and a missing or short bin refuses the work instead of drawing from another bin:
+
+- **Which lines.** `needsPullFrom` (`@carbon/database/strict-backflush`): not Make to Order, item type Material / Part / Consumable, item not Non-Inventory. The locations are `getPullFromLocations` — each with an active work center AND an active storage unit (a location with no storage unit has no bin a line could name, so requiring one there would block activation for good). Activation, release and the settings card all read these two.
+- **Activation.** `convert` `methodVersionToActive` calls `assertMethodHasPullFrom` (`packages/server-functions/src/lib/strict-backflush.ts`) and refuses a version with a line missing a Pull From at one of those locations.
+- **Release.** `getJobReleaseReadiness` returns `materialsWithoutStorageUnit` per job (`materialsWithoutStorageUnit` in `job-release-logic.ts`, one entry per part); `jobReleaseProblems`, the Release dialog route and `BatchReleaseModal` refuse on it. `JobStartModal` runs the same function before submit, lists the parts and disables Release Job. The BoM editor and the job BoM editor show a red "No storage unit" badge on such a line.
+- **Backflush.** `issueJobOperationMaterials` and `partToOperation` (planned material, consuming issue) consume what no pick covered from `jobMaterial.storageUnitId` only, through `assertBinCovers` (409, names the part, the bin, need and have; it first takes `pg_advisory_xact_lock` on `strict-backflush:<companyId>:<bin>:<item>`, the same key the SQL takes). Picked and unclaimed lineside stock is still drawn first. `issueJobOperationMaterials` collects every shortfall (`binCoverProblem`) and refuses once; the SQL does the same. A refusal is a toast, so every strict message goes through `summarizeList` (`@carbon/database/strict-backflush`): the first 5 part names or 3 shortfalls, then "and N more" (the full shortfall list is logged). The Release dialog shows the full list in a scroll box; collapsed BoM and job BoM rows carry the red "No storage unit" badge (`MaterialRowTitle` `missingPullFrom`). SQL `backflush_job_materials` (`20261015122149_strict-backflush.sql`) raises the same refusal at job completion.
+- **Produced units with no consumption.** Callers that record a production quantity before they call `issue` — MES `complete.tsx`, `end.$operationId.tsx`, `quality.server.ts` `postBulkCompletion`, ERP `completeOperation`, `batch-operations` `complete` — first invoke `issue` `jobOperation` with `dryRun: true` (a rolled-back run; a no-op when the setting is off).
+- **Existing Active methods are never changed** when the setting turns on; `getActiveMethodsMissingPullFrom` lists them on the settings card.
+
### Job completion
`complete_job_to_inventory` (SQL, newest `20261014135003_lock-production-events-at-job-completion.sql` (locks the unposted events it posts), before it `20261009010412_job-costing-always-post.sql` and `20261006221601_complete-job-to-asset.sql`, forked from the guarded definition in `20260925121735_rpc-function-guards.sql`) is the single choke point: the ERP complete route, the API/MCP `completeJob` tool and the `sync_finish_job_operation` trigger interceptor all go through it.
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 697f0f7916..0ee3dabecf 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -125,6 +125,7 @@ import type {
} from "./types";
import {
makeMethodsMissingOperations,
+ materialsWithoutStorageUnit,
outsideOperationsNeedingPurchaseOrders,
resolveOperationSupplier
} from "./ui/Jobs/job-release-logic";
@@ -1939,7 +1940,7 @@ export async function getJobMaterialsByMethodId(
const result = await client
.from("jobMaterial")
.select(
- "*, item(replenishmentSystem), jobMaterialStep(jobOperationStepId, quantity)"
+ "*, item(replenishmentSystem, itemTrackingType), jobMaterialStep(jobOperationStepId, quantity)"
)
.eq("jobMakeMethodId", jobMakeMethodId)
.order("order", { ascending: true });
@@ -1947,7 +1948,7 @@ export async function getJobMaterialsByMethodId(
return (await client
.from("jobMaterial")
.select(
- "*, item(replenishmentSystem), jobMaterialStep(jobOperationStepId)"
+ "*, item(replenishmentSystem, itemTrackingType), jobMaterialStep(jobOperationStepId)"
)
.eq("jobMakeMethodId", jobMakeMethodId)
.order("order", { ascending: true })) as unknown as typeof result;
@@ -2970,6 +2971,9 @@ export type JobReleaseReadiness = {
}[];
// The suppliers this job's outside operations go on a purchase order for.
supplierIds: string[];
+ // Strict backflush: pulled, stocked lines with no storage unit to
+ // backflush from. Always empty while the setting is off.
+ materialsWithoutStorageUnit: { id: string; description: string }[];
}[];
// Suppliers whose outside operations release will put on a purchase order,
// with the Draft POs the planner may add them to instead of a new one.
@@ -2979,6 +2983,49 @@ export type JobReleaseReadiness = {
}[];
};
+// Strict backflush (companySettings.requireBackflushStorageUnit): a job may not
+// be released while a pulled, stocked line has no storage unit, because its
+// backflush would be refused. Keyed by job id; empty while the setting is off.
+async function getMaterialsWithoutStorageUnit(
+ client: SupabaseClient<Database>,
+ jobIds: string[],
+ companyId: string
+): Promise<{
+ data: Record<string, { id: string; description: string }[]>;
+ error: PostgrestError | null;
+}> {
+ const settings = await client
+ .from("companySettings")
+ .select("requireBackflushStorageUnit")
+ .eq("id", companyId)
+ .maybeSingle();
+ if (settings.error) return { data: {}, error: settings.error };
+ if (settings.data?.requireBackflushStorageUnit !== true)
+ return { data: {}, error: null };
+
+ const lines = await fetchAllByIds(jobIds, (batch) =>
+ client
+ .from("jobMaterial")
+ .select(
+ "id, jobId, description, methodType, itemType, storageUnitId, item(itemTrackingType, readableIdWithRevision)"
+ )
+ .in("jobId", batch)
+ .eq("companyId", companyId)
+ .is("storageUnitId", null)
+ .order("id")
+ );
+ if (lines.error) return { data: {}, error: lines.error };
+
+ const byJob: Record<string, { id: string; description: string }[]> = {};
+ for (const [jobId, jobLines] of Object.entries(
+ groupBy(lines.data ?? [], (line) => line.jobId)
+ )) {
+ const missing = materialsWithoutStorageUnit(jobLines);
+ if (missing.length > 0) byJob[jobId] = missing;
+ }
+ return { data: byJob, error: null };
+}
+
// What stands between these jobs and release, read in one query per table for
// any number of jobs. The job Release dialog and batch release both read it, so
// a job released through a batch is held to the job page's rules.
@@ -3036,6 +3083,14 @@ export async function getJobReleaseReadiness(
jobs.error ?? roots.error ?? materials.error ?? operations.error;
if (failed) return { data: null, error: failed };
+ const withoutStorageUnit = await getMaterialsWithoutStorageUnit(
+ client,
+ jobIds,
+ companyId
+ );
+ if (withoutStorageUnit.error)
+ return { data: null, error: withoutStorageUnit.error };
+
const outsideOperationIds = (operations.data ?? [])
.filter((op) => op.operationType === "Outside Processing")
.map((op) => op.id);
@@ -3182,7 +3237,8 @@ export async function getJobReleaseReadiness(
: []
)
)
- ]
+ ],
+ materialsWithoutStorageUnit: withoutStorageUnit.data[job.id] ?? []
})),
suppliers: supplierIds.map((supplierId) => ({
supplierId,
@@ -10926,6 +10982,19 @@ export async function completeOperation(
}
}
+ // Strict backflush: refuse before the production quantity is recorded, so a
+ // short storage unit never leaves units completed with no material
+ // consumed. A no-op when strict backflush is off.
+ const check = await serverFns
+ .as({ client, db, companyId, userId })
+ .invoke("issue", {
+ id: args.operationId,
+ type: "jobOperation",
+ quantity: args.quantity,
+ dryRun: true
+ });
+ if (check.error) return { data: null, error: check.error };
+
// 1. Record produced quantity.
const insertProduction = await client
.from("productionQuantity")
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
index bd434fec96..b4207eef0b 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
@@ -2,6 +2,7 @@
// 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.
+import { summarizeList } from "@carbon/database/strict-backflush";
import {
Alert,
AlertDescription,
@@ -73,7 +74,8 @@ export function BatchReleaseModal({
(job) =>
job.manufacturingBlocked ||
job.missingAssemblies.length > 0 ||
- job.outsideOperationsWithoutSupplier.length > 0
+ job.outsideOperationsWithoutSupplier.length > 0 ||
+ job.materialsWithoutStorageUnit.length > 0
);
const jobIds = (readiness?.jobs ?? []).map((job) => job.jobId);
const canRelease = !!readiness && blocked.length === 0 && !isSubmitting;
@@ -136,7 +138,13 @@ export function BatchReleaseModal({
op.missing === "choose"
? t`choose a supplier for ${op.description} on the job`
: t`${op.description} has no supplier`
- )
+ ),
+ job.materialsWithoutStorageUnit.length > 0 &&
+ t`set a Pull From storage unit on ${summarizeList(
+ job.materialsWithoutStorageUnit.map(
+ (m) => m.description
+ )
+ )}`
]
.filter(Boolean)
.join("; ")}
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
index ddbe6861d5..469fa97f11 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -4,6 +4,7 @@
"use client";
import { useCarbon } from "@carbon/auth";
+import { needsPullFrom } from "@carbon/database/strict-backflush";
import { ValidatedForm } from "@carbon/form";
import {
Badge,
@@ -77,6 +78,7 @@ import {
useUrlParams,
useUser
} from "~/hooks";
+import { useCompanySettings } from "~/hooks/useCompanySettings";
import { ItemTrackingType } from "~/modules/items";
import {
MaterialRowDetails,
@@ -98,6 +100,7 @@ type Material = z.infer<typeof jobMaterialValidator> & {
requiresSerialTracking: boolean;
item?: {
replenishmentSystem: string | null;
+ itemTrackingType?: string | null;
} | null;
};
@@ -133,14 +136,21 @@ function makeItems(
items: ItemType[],
materials: Material[],
orderState: OrderState,
- checkedState: CheckedState
+ checkedState: CheckedState,
+ missingPullFrom?: (material: Material) => boolean
): ItemWithData[] {
return materials.map((material) => {
const order = material.id
? (orderState[material.id] ?? material.order)
: material.order;
const checked = material.id ? (checkedState[material.id] ?? false) : false;
- return makeItem(items, material, order, checked);
+ return makeItem(
+ items,
+ material,
+ order,
+ checked,
+ missingPullFrom?.(material) ?? false
+ );
});
}
@@ -148,7 +158,8 @@ function makeItem(
items: ItemType[],
material: Material,
order: number,
- checked: boolean
+ checked: boolean,
+ missingPullFrom = false
): ItemWithData {
const itemReadableId = getItemReadableId(items, material.itemId);
return {
@@ -162,6 +173,7 @@ function makeItem(
supersessionMode={
items.find((i) => i.id === material.itemId)?.supersessionMode
}
+ missingPullFrom={missingPullFrom}
/>
),
checked: checked,
@@ -281,11 +293,23 @@ const JobBillOfMaterial = ({
});
const [storeItems] = useItems();
+ // Strict backflush: mark collapsed rows with no storage unit to backflush
+ // from — the same test as the open line's "No storage unit" badge.
+ const companySettings = useCompanySettings();
+ const missingPullFrom = (material: Material) =>
+ companySettings?.requireBackflushStorageUnit === true &&
+ !material.storageUnitId &&
+ needsPullFrom({
+ methodType: material.methodType ?? null,
+ itemType: material.itemType ?? null,
+ itemTrackingType: material.item?.itemTrackingType ?? null
+ });
const items = makeItems(
storeItems,
Array.from(materialsById.values()),
orderState,
- checkedState
+ checkedState,
+ missingPullFrom
).sort((a, b) => a.data.order - b.data.order);
const jobData = useRouteData<{ job: Job }>(path.to.job(jobId));
@@ -722,6 +746,18 @@ function MaterialForm({
const locationId = routeData?.job?.locationId ?? undefined;
const storageUnits = useStorageUnits(locationId);
+ // Strict backflush: a pulled, stocked line is backflushed only from its own
+ // storage unit, so "Default Storage Unit" would hide a line that will be
+ // refused at release and at backflush.
+ const companySettings = useCompanySettings();
+ const requiresPullFrom =
+ companySettings?.requireBackflushStorageUnit === true &&
+ needsPullFrom({
+ methodType: itemData.methodType,
+ itemType,
+ itemTrackingType: item.data.item?.itemTrackingType ?? null
+ });
+
const isTracked =
itemData.requiresBatchTracking || itemData.requiresSerialTracking;
@@ -846,15 +882,22 @@ function MaterialForm({
: ""
)}
/>
- <Badge variant="secondary">
- <LuGitPullRequest className="size-3 mr-1" />
- {storageUnits.options?.find(
- (s) => s.value === itemData.storageUnitId
- )?.label ??
- (itemData.methodType === "Make to Order"
- ? t`WIP`
- : t`Default Storage Unit`)}
- </Badge>
+ {requiresPullFrom && !itemData.storageUnitId ? (
+ <Badge variant="red">
+ <LuGitPullRequest className="size-3 mr-1" />
+ <Trans>No storage unit</Trans>
+ </Badge>
+ ) : (
+ <Badge variant="secondary">
+ <LuGitPullRequest className="size-3 mr-1" />
+ {storageUnits.options?.find(
+ (s) => s.value === itemData.storageUnitId
+ )?.label ??
+ (itemData.methodType === "Make to Order"
+ ? t`WIP`
+ : t`Default Storage Unit`)}
+ </Badge>
+ )}
<IconButton
icon={<LuChevronRight />}
aria-label={
@@ -901,6 +944,7 @@ function MaterialForm({
}}
locationId={locationId}
itemId={itemData.itemId}
+ isOptional={!requiresPullFrom}
/>
</div>
</div>
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
index 8219132100..e65e7e70ae 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -83,6 +83,7 @@ import {
useRouteData,
useUser
} from "~/hooks";
+import { useCompanySettings } from "~/hooks/useCompanySettings";
import { useSuppliers } from "~/stores";
import { generateBomIds } from "~/utils/bom";
import { path } from "~/utils/path";
@@ -96,7 +97,10 @@ import {
getReceivableSerialUnits,
type JobReceiptSnapshot
} from "./job-complete-logic";
-import { makeMethodsMissingOperations } from "./job-release-logic";
+import {
+ makeMethodsMissingOperations,
+ materialsWithoutStorageUnit
+} from "./job-release-logic";
const JobHeader = () => {
const navigate = useNavigate();
@@ -623,7 +627,14 @@ export function JobStartModal({
}) {
const { carbon } = useCarbon();
const [suppliers] = useSuppliers();
+ const companySettings = useCompanySettings();
+ const strictBackflush = companySettings?.requireBackflushStorageUnit === true;
const [loading, setLoading] = useState(true);
+ // Strict backflush: lines whose backflush would be refused. The release
+ // route refuses them too; showing them here saves a failed submit.
+ const [missingStorageUnits, setMissingStorageUnits] = useState<
+ { id: string; description: string }[]
+ >([]);
const [missingOperationAssemblies, setMissingOperationAssemblies] = useState<
{ bomId: string; description: string }[]
>([]);
@@ -657,20 +668,30 @@ export function JobStartModal({
const validate = async (choicesOverride?: Record<string, string>) => {
if (!carbon || !job) return;
- const [makeMethod, materials, operations, methodTree] = await Promise.all([
- carbon
- .from("jobMakeMethod")
- .select("*")
- .eq("jobId", job.id!)
- .is("parentMaterialId", null)
- .single(),
- carbon
- .from("jobMaterialWithMakeMethodId")
- .select("*")
- .eq("jobId", job.id!),
- carbon.from("jobOperation").select("*").eq("jobId", job.id!),
- getJobMethodTree(carbon, job.id!)
- ]);
+ const [makeMethod, materials, operations, methodTree, storageUnitLines] =
+ await Promise.all([
+ carbon
+ .from("jobMakeMethod")
+ .select("*")
+ .eq("jobId", job.id!)
+ .is("parentMaterialId", null)
+ .single(),
+ carbon
+ .from("jobMaterialWithMakeMethodId")
+ .select("*")
+ .eq("jobId", job.id!),
+ carbon.from("jobOperation").select("*").eq("jobId", job.id!),
+ getJobMethodTree(carbon, job.id!),
+ strictBackflush
+ ? carbon
+ .from("jobMaterial")
+ .select(
+ "id, description, methodType, itemType, storageUnitId, item(itemTrackingType, readableIdWithRevision)"
+ )
+ .eq("jobId", job.id!)
+ .is("storageUnitId", null)
+ : Promise.resolve({ data: [] })
+ ]);
// Check for existing purchase order lines for outside operations
const outsideOperations =
@@ -871,6 +892,9 @@ export function JobStartModal({
flushSync(() => {
setMissingOperationAssemblies(missingAssemblies);
+ setMissingStorageUnits(
+ materialsWithoutStorageUnit(storageUnitLines.data ?? [])
+ );
// Show the release UI whenever there are outside operations still needing handling,
// whether or not they have a supplier yet
@@ -932,6 +956,7 @@ export function JobStartModal({
<ModalBody>
<VStack>
{missingOperationAssemblies.length === 0 &&
+ missingStorageUnits.length === 0 &&
eachOutsideOperationHasASupplier && (
<p className="text-sm">
<Trans>
@@ -1073,6 +1098,25 @@ export function JobStartModal({
</AlertDescription>
</Alert>
)}
+ {missingStorageUnits.length > 0 && (
+ <Alert variant="warning">
+ <LuTriangleAlert />
+ <AlertTitle>
+ <Trans>Missing Storage Units</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>
+ Strict backflush is on. Set a Pull From storage unit on
+ these materials before releasing:
+ </Trans>
+ <ul className="mt-2 list-disc pl-4 space-y-1 max-h-48 overflow-y-auto">
+ {missingStorageUnits.map((material) => (
+ <li key={material.id}>{material.description}</li>
+ ))}
+ </ul>
+ </AlertDescription>
+ </Alert>
+ )}
{!eachOutsideOperationHasASupplier && hasOutsideOperations && (
<Alert variant="warning">
<LuTriangleAlert />
@@ -1119,6 +1163,7 @@ export function JobStartModal({
isDisabled={
fetcher.state !== "idle" ||
missingOperationAssemblies.length > 0 ||
+ missingStorageUnits.length > 0 ||
!eachOutsideOperationHasASupplier
}
type="submit"
diff --git a/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts
index 7669b6c71d..e0f8edecd8 100644
--- a/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts
+++ b/apps/erp/app/modules/production/ui/Jobs/job-release-logic.ts
@@ -6,6 +6,11 @@
// released as part of a batch is held to exactly the rules the job page applies.
// Pure — no JSX/lingui — and unit-tested by apps/erp/test/job-release-logic.test.ts.
+import {
+ needsPullFrom,
+ summarizeList
+} from "@carbon/database/strict-backflush";
+
export type ReleaseMaterial = {
jobMaterialMakeMethodId: string | null;
methodType: string | null;
@@ -97,6 +102,7 @@ export function jobReleaseProblems(job: {
description: string;
missing: "none" | "choose";
}[];
+ materialsWithoutStorageUnit: { description: string }[];
}): string[] {
return [
...(job.manufacturingBlocked ? ["manufacturing is blocked"] : []),
@@ -113,6 +119,50 @@ export function jobReleaseProblems(job: {
op.missing === "choose"
? `choose a supplier for ${op.description} on the job`
: `${op.description} has no supplier`
- )
+ ),
+ // Strict backflush: these lines' backflush would be refused.
+ ...(job.materialsWithoutStorageUnit.length > 0
+ ? [
+ `set a Pull From storage unit on ${summarizeList(
+ job.materialsWithoutStorageUnit.map((m) => m.description)
+ )}`
+ ]
+ : [])
];
}
+
+export type StorageUnitLine = {
+ id: string;
+ description: string;
+ methodType: string | null;
+ itemType: string | null;
+ storageUnitId: string | null;
+ item: {
+ itemTrackingType: string | null;
+ readableIdWithRevision: string | null;
+ } | null;
+};
+
+// Strict backflush: the pulled, stocked lines with no storage unit to
+// backflush from, one entry per part — a part used on two lines needs the
+// same fix, so naming it twice only lengthens the message.
+export function materialsWithoutStorageUnit(
+ lines: StorageUnitLine[]
+): { id: string; description: string }[] {
+ const byDescription = new Map<string, { id: string; description: string }>();
+ for (const line of lines) {
+ if (line.storageUnitId) continue;
+ if (
+ !needsPullFrom({
+ methodType: line.methodType,
+ itemType: line.itemType,
+ itemTrackingType: line.item?.itemTrackingType ?? null
+ })
+ )
+ continue;
+ const description = line.item?.readableIdWithRevision || line.description;
+ if (!byDescription.has(description))
+ byDescription.set(description, { id: line.id, description });
+ }
+ return [...byDescription.values()];
+}
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index 17bda4fcea..1b29c6194b 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -6,6 +6,12 @@ import { SUPABASE_URL } from "@carbon/auth";
import type { Database, Json } from "@carbon/database";
import { getCompanyTimeZone } from "@carbon/database";
import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import {
+ getPullFromLocations,
+ missingPullFromLocations,
+ needsPullFrom,
+ PULLED_ITEM_TYPES
+} from "@carbon/database/strict-backflush";
import type {
DocumentBlock,
DocumentSectionPlacement,
@@ -1218,6 +1224,112 @@ export async function updateBomExplorerReadableIdSetting(
.eq("id", companyId);
}
+/** @mcp update */
+export async function updateRequireBackflushStorageUnitSetting(
+ client: SupabaseClient<Database>,
+ companyId: string,
+ requireBackflushStorageUnit: boolean
+) {
+ return client
+ .from("companySettings")
+ .update({ requireBackflushStorageUnit })
+ .eq("id", companyId);
+}
+
+const MISSING_PULL_FROM_SHOWN = 10;
+
+// Strict backflush: the Active make methods with a pulled, stocked line that
+// has no Pull From at a location with an active work center. Turning the
+// setting on leaves these methods Active; the settings card lists them.
+// Kysely, not PostgREST: a company's Active BoM lines can pass the 1000-row cap.
+export async function getActiveMethodsMissingPullFrom(
+ db: Kysely<KyselyDatabase>,
+ companyId: string
+): Promise<{
+ data: {
+ count: number;
+ methods: {
+ makeMethodId: string;
+ itemId: string;
+ itemType: string;
+ readableId: string;
+ }[];
+ } | null;
+ error: Error | null;
+}> {
+ try {
+ const [lines, locations] = await Promise.all([
+ db
+ .selectFrom("methodMaterial")
+ .innerJoin("makeMethod", (join) =>
+ join
+ .onRef("makeMethod.id", "=", "methodMaterial.makeMethodId")
+ .on("makeMethod.companyId", "=", companyId)
+ .on("makeMethod.status", "=", "Active")
+ )
+ .innerJoin("item as component", "component.id", "methodMaterial.itemId")
+ .innerJoin("item as parent", "parent.id", "makeMethod.itemId")
+ .where("methodMaterial.companyId", "=", companyId)
+ .where("methodMaterial.methodType", "!=", "Make to Order")
+ .where("methodMaterial.itemType", "in", [...PULLED_ITEM_TYPES])
+ .select([
+ "makeMethod.id as makeMethodId",
+ "parent.id as itemId",
+ "parent.type as itemType",
+ "parent.readableIdWithRevision as readableId",
+ "methodMaterial.methodType",
+ "methodMaterial.itemType as lineItemType",
+ "methodMaterial.storageUnitIds",
+ "component.itemTrackingType"
+ ])
+ .execute(),
+ getPullFromLocations(db, companyId)
+ ]);
+
+ const locationIds = locations.map((location) => location.id);
+ const methods = new Map<
+ string,
+ {
+ makeMethodId: string;
+ itemId: string;
+ itemType: string;
+ readableId: string;
+ }
+ >();
+ for (const line of lines) {
+ if (methods.has(line.makeMethodId)) continue;
+ if (
+ !needsPullFrom({
+ methodType: line.methodType,
+ itemType: line.lineItemType,
+ itemTrackingType: line.itemTrackingType
+ })
+ )
+ continue;
+ if (missingPullFromLocations(line.storageUnitIds, locationIds).length > 0)
+ methods.set(line.makeMethodId, {
+ makeMethodId: line.makeMethodId,
+ itemId: line.itemId,
+ itemType: line.itemType,
+ readableId: line.readableId ?? line.itemId
+ });
+ }
+
+ const sorted = [...methods.values()].sort((a, b) =>
+ a.readableId.localeCompare(b.readableId)
+ );
+ return {
+ data: {
+ count: sorted.length,
+ methods: sorted.slice(0, MISSING_PULL_FROM_SHOWN)
+ },
+ error: null
+ };
+ } catch (error) {
+ return { data: null, error: error as Error };
+ }
+}
+
/** @mcp update */
export async function updatePlmReleaseControlSetting(
client: SupabaseClient<Database>,
diff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
index 5d10bbda8e..47c0b96814 100644
--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json
@@ -1,5 +1,5 @@
{
- "totalTools": 1556,
+ "totalTools": 1557,
"modules": 15,
"tools": [
{"name":"account_deleteUserAttributeValue","classification":"DESTRUCTIVE","paramCount":2,"schema":"0d38e12233b4","response":"bcde375ebd4c","injectAuth":"companyId+userId","permission":"none","paginates":false},
@@ -688,7 +688,7 @@
{"name":"production_getJobMaterial","classification":"READ","paramCount":1,"schema":"5aa329400da2","response":"7cdf48a49d7f","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialItemIds","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"32068a500dfe","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialPurchaseOrderLines","classification":"READ","paramCount":2,"schema":"a396a00de3b2","response":"b12e99320d04","injectAuth":"companyId","permission":"production:view","paginates":false},
- {"name":"production_getJobMaterialsByMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"562cd876b859","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getJobMaterialsByMethodId","classification":"READ","paramCount":1,"schema":"c32158774ba3","response":"0fbc727fb078","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialShortfallByItem","classification":"READ","paramCount":4,"schema":"644b4df6515a","response":"8a62dcc3c7f9","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialSupplyJobLines","classification":"READ","paramCount":2,"schema":"a396a00de3b2","response":"acbcf89b1800","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobMaterialsWithQuantityOnHand","classification":"READ","paramCount":3,"schema":"ef9bf176c913","response":"be0a4b3c547b","injectAuth":"companyId","permission":"production:view","paginates":false,"defaults":"always"},
@@ -712,7 +712,7 @@
{"name":"production_getJobPromiseDate","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"bd69f777e8e9","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobPurchaseOrderLines","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"309dea2a265c","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobReceiptSnapshot","classification":"READ","paramCount":1,"schema":"4999bd4be598","response":"af63ddd51939","injectAuth":"companyId","permission":"production:view","paginates":false},
- {"name":"production_getJobReleaseReadiness","classification":"READ","paramCount":1,"schema":"267b4780c1d3","response":"9712d0076586","injectAuth":"companyId","permission":"production:view","paginates":false},
+ {"name":"production_getJobReleaseReadiness","classification":"READ","paramCount":1,"schema":"267b4780c1d3","response":"5c6a7a473fa2","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobs","classification":"READ","paramCount":1,"schema":"ed8b79d0644f","response":"be55a4e21412","injectAuth":"companyId","permission":"production:view","paginates":true,"defaults":"always"},
{"name":"production_getJobsByDateRange","classification":"READ","paramCount":3,"schema":"00794c516592","response":"847ba339f22a","injectAuth":"companyId","permission":"production:view","paginates":false},
{"name":"production_getJobsBySalesOrderLine","classification":"READ","paramCount":1,"schema":"58e3c9762923","response":"be55a4e21412","injectAuth":"companyId","permission":"production:view","paginates":false},
@@ -1421,7 +1421,7 @@
{"name":"settings_getCompany","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"81a93f0029ec","injectAuth":"companyId","permission":"settings:view","paginates":false},
{"name":"settings_getCompanyIntegrations","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"3a98b34db51d","injectAuth":"companyId","permission":"settings:view","paginates":false},
{"name":"settings_getCompanyPlan","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"none","injectAuth":"companyId","permission":"settings:view","paginates":false},
- {"name":"settings_getCompanySettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"689a7e333d99","injectAuth":"companyId","permission":"settings:view","paginates":false},
+ {"name":"settings_getCompanySettings","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"d8783d378f25","injectAuth":"companyId","permission":"settings:view","paginates":false},
{"name":"settings_getConfig","classification":"READ","paramCount":0,"schema":"efddc7bd8bbc","response":"aa1021ff34cf","injectAuth":"companyId","permission":"settings:view","paginates":false},
{"name":"settings_getCurrentSequence","classification":"READ","paramCount":1,"schema":"f55836d6d401","response":"00404e686415","injectAuth":"companyId","permission":"settings:view","paginates":false},
{"name":"settings_getCustomField","classification":"READ","paramCount":1,"schema":"3797626bd17e","response":"a533a796c094","injectAuth":"companyId","permission":"settings:view","paginates":false},
@@ -1486,6 +1486,7 @@
{"name":"settings_updatePlmReleaseControlSetting","classification":"WRITE","paramCount":1,"schema":"b74d1adb972d","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},
{"name":"settings_updatePurchasePriceUpdateTimingSetting","classification":"WRITE","paramCount":1,"schema":"6e01697e737c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},
{"name":"settings_updateQuoteLineCategoryMarkups","classification":"WRITE","paramCount":1,"schema":"46b636ff84f8","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},
+ {"name":"settings_updateRequireBackflushStorageUnitSetting","classification":"WRITE","paramCount":1,"schema":"2f238b14da00","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},
{"name":"settings_updateRequireCustomerContactSetting","classification":"WRITE","paramCount":1,"schema":"4cff457269be","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},
{"name":"settings_updateRequireSupplierContactSetting","classification":"WRITE","paramCount":1,"schema":"36a0cd98c43c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},
{"name":"settings_updateReturnPickedMaterialTimingSetting","classification":"WRITE","paramCount":1,"schema":"59acd7763b9c","response":"bcde375ebd4c","injectAuth":"companyId","permission":"settings:update","paginates":false},
diff --git a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx
index ea58be777a..ab9e5f9d42 100644
--- a/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/versions.activate.$id.tsx
@@ -96,9 +96,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
companyId,
error: update.error
});
+ // A refusal the user can fix (strict backflush: a line with no Pull From)
+ // carries its own message; a data-layer failure arrives with none.
return {
success: false,
- message: "Failed to activate method version"
+ message: update.error.message || "Failed to activate method version"
};
}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
index c332c50fa3..8cc32c026f 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts
@@ -167,7 +167,8 @@ function setup() {
manufacturingBlocked: false,
missingAssemblies: [],
outsideOperationsWithoutSupplier: [],
- supplierIds: []
+ supplierIds: [],
+ materialsWithoutStorageUnit: []
}
],
suppliers: []
@@ -258,7 +259,8 @@ describe("Job release status action", () => {
{ makeMethodId: "mm-2", description: "Bracket" }
],
outsideOperationsWithoutSupplier: [],
- supplierIds: []
+ supplierIds: [],
+ materialsWithoutStorageUnit: []
}
],
suppliers: []
@@ -272,6 +274,38 @@ describe("Job release status action", () => {
expect(runLocationSchedule).not.toHaveBeenCalled();
expect(success).not.toHaveBeenCalled();
});
+
+ it("refuses release under strict backflush when a line has no storage unit", async () => {
+ vi.mocked(getJobReleaseReadiness).mockResolvedValue({
+ data: {
+ jobs: [
+ {
+ id: "job-1",
+ jobId: "J000001",
+ status: "Draft",
+ manufacturingBlocked: false,
+ missingAssemblies: [],
+ outsideOperationsWithoutSupplier: [],
+ supplierIds: [],
+ materialsWithoutStorageUnit: [
+ { id: "jm-1", description: "BOLT-10" }
+ ]
+ }
+ ],
+ suppliers: []
+ },
+ error: null
+ });
+
+ await expect(runRelease()).rejects.toBeInstanceOf(Response);
+
+ expect(error).toHaveBeenCalledWith(
+ null,
+ "Set a Pull From storage unit before releasing: BOLT-10"
+ );
+ expect(updateJobStatus).not.toHaveBeenCalled();
+ expect(runLocationSchedule).not.toHaveBeenCalled();
+ });
});
describe("Job status tenancy", () => {
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
index d173909615..7f24284980 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
@@ -6,6 +6,7 @@ import { assertIsPost, error, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import { flash } from "@carbon/auth/session.server";
+import { summarizeList } from "@carbon/database/strict-backflush";
import { getLogger } from "@carbon/logger";
import { runLocationSchedule } from "@carbon/planning";
import { serverFns } from "@carbon/server-functions";
@@ -128,6 +129,23 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ const withoutStorageUnit =
+ readiness.data?.jobs[0]?.materialsWithoutStorageUnit ?? [];
+ if (withoutStorageUnit.length > 0) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(
+ request,
+ error(
+ null,
+ `Set a Pull From storage unit before releasing: ${summarizeList(
+ withoutStorageUnit.map((m) => m.description)
+ )}`
+ )
+ )
+ );
+ }
+
try {
await stampSupplierChoices({
jobId: id,
diff --git a/apps/erp/app/routes/x+/job+/release.test.ts b/apps/erp/app/routes/x+/job+/release.test.ts
index 3db6495871..5361f0c6c6 100644
--- a/apps/erp/app/routes/x+/job+/release.test.ts
+++ b/apps/erp/app/routes/x+/job+/release.test.ts
@@ -62,6 +62,7 @@ const ready = (id: string, overrides: Record<string, unknown> = {}) => ({
missingAssemblies: [],
outsideOperationsWithoutSupplier: [],
supplierIds: [] as string[],
+ materialsWithoutStorageUnit: [],
...overrides
});
diff --git a/apps/erp/app/routes/x+/settings+/items.tsx b/apps/erp/app/routes/x+/settings+/items.tsx
index 643e533557..907c4dba62 100644
--- a/apps/erp/app/routes/x+/settings+/items.tsx
+++ b/apps/erp/app/routes/x+/settings+/items.tsx
@@ -6,6 +6,7 @@ import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import { Hidden, Select, Submit, ValidatedForm, validator } from "@carbon/form";
+import { getLogger } from "@carbon/logger";
import {
Card,
CardContent,
@@ -21,25 +22,30 @@ import {
} from "@carbon/react";
import { redirect } from "@carbon/utils";
import { msg } from "@lingui/core/macro";
-import { Trans, useLingui } from "@lingui/react/macro";
+import { Plural, Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect } from "react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { useFetcher, useLoaderData } from "react-router";
+import { Link, useFetcher, useLoaderData } from "react-router";
import { SettingsPage, SettingsPageHeading } from "~/components/SettingsPage";
import SettingsSectionHeader from "~/components/SettingsSectionHeader";
import { plmReleaseControl } from "~/modules/items";
import {
+ getActiveMethodsMissingPullFrom,
getCompanySettings,
plmReleaseControlValidator,
updateAllowLowercaseItemIdsSetting,
updateBomExplorerReadableIdSetting,
updateMaterialGeneratedIdsSetting,
updateMetricSettings,
- updatePlmReleaseControlSetting
+ updatePlmReleaseControlSetting,
+ updateRequireBackflushStorageUnitSetting
} from "~/modules/settings";
+import { getDatabaseClient } from "~/services/database.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
+const logger = getLogger("erp", "settings-items");
+
export const handle: Handle = {
breadcrumb: msg`Items`,
to: path.to.itemsSettings
@@ -59,7 +65,27 @@ export async function loader({ request }: LoaderFunctionArgs) {
error(companySettings.error, "Failed to get company settings")
)
);
- return { companySettings: companySettings.data };
+
+ // Strict backflush leaves Active methods as they are; the card lists the
+ // ones with a gap so they can be fixed.
+ let methodsMissingPullFrom: Awaited<
+ ReturnType<typeof getActiveMethodsMissingPullFrom>
+ >["data"] = null;
+ if (companySettings.data.requireBackflushStorageUnit) {
+ const missing = await getActiveMethodsMissingPullFrom(
+ getDatabaseClient(),
+ companyId
+ );
+ if (missing.error) {
+ logger.error("Failed to read methods missing a Pull From", {
+ companyId,
+ error: missing.error
+ });
+ }
+ methodsMissingPullFrom = missing.data;
+ }
+
+ return { companySettings: companySettings.data, methodsMissingPullFrom };
}
export async function action({ request }: ActionFunctionArgs) {
@@ -102,6 +128,17 @@ export async function action({ request }: ActionFunctionArgs) {
return { success: true, message: "Item ID casing setting updated" };
}
+ case "requireBackflushStorageUnit": {
+ const result = await updateRequireBackflushStorageUnitSetting(
+ client,
+ companyId,
+ enabled
+ );
+ if (result.error)
+ return { success: false, message: result.error.message };
+ return { success: true, message: "Strict backflush setting updated" };
+ }
+
case "bomExplorerReadableId": {
const result = await updateBomExplorerReadableIdSetting(
client,
@@ -137,7 +174,8 @@ export async function action({ request }: ActionFunctionArgs) {
export default function ItemsSettingsRoute() {
const { t } = useLingui();
- const { companySettings } = useLoaderData<typeof loader>();
+ const { companySettings, methodsMissingPullFrom } =
+ useLoaderData<typeof loader>();
const fetcher = useFetcher<typeof action>();
const releaseControlLabels: Record<
@@ -191,6 +229,16 @@ export default function ItemsSettingsRoute() {
[fetcher]
);
+ const handleStrictBackflushToggle = useCallback(
+ (checked: boolean) => {
+ fetcher.submit(
+ { intent: "requireBackflushStorageUnit", enabled: String(checked) },
+ { method: "POST" }
+ );
+ },
+ [fetcher]
+ );
+
const handleBomExplorerReadableIdToggle = useCallback(
(checked: boolean) => {
fetcher.submit(
@@ -342,6 +390,84 @@ export default function ItemsSettingsRoute() {
</CardContent>
</Card>
+ <Card>
+ <CardHeader>
+ <CardTitle>
+ <Trans>Strict Backflush</Trans>
+ </CardTitle>
+ <CardDescription>
+ <Trans>
+ Backflush each material only from the storage unit on its
+ material line, and stop the operation or job when that storage
+ unit does not have enough stock.
+ </Trans>
+ </CardDescription>
+ </CardHeader>
+ <CardContent>
+ <VStack spacing={4}>
+ <HStack className="justify-between items-center w-full">
+ <VStack className="items-start" spacing={1}>
+ <span className="font-medium">
+ {companySettings.requireBackflushStorageUnit ? (
+ <Trans>Strict backflush is on</Trans>
+ ) : (
+ <Trans>Strict backflush is off</Trans>
+ )}
+ </span>
+ <span className="text-sm text-muted-foreground">
+ {companySettings.requireBackflushStorageUnit ? (
+ <Trans>
+ A method version needs a Pull From storage unit on each
+ pulled material before it can be made active.
+ </Trans>
+ ) : (
+ <Trans>
+ A short storage unit falls back to another storage unit
+ with stock.
+ </Trans>
+ )}
+ </span>
+ </VStack>
+ <Switch
+ checked={companySettings.requireBackflushStorageUnit ?? false}
+ onCheckedChange={handleStrictBackflushToggle}
+ disabled={isToggling}
+ />
+ </HStack>
+ {methodsMissingPullFrom && methodsMissingPullFrom.count > 0 && (
+ <VStack className="items-start w-full" spacing={1}>
+ <span className="text-sm font-medium">
+ <Plural
+ value={methodsMissingPullFrom.count}
+ one="# active method has materials with no Pull From"
+ other="# active methods have materials with no Pull From"
+ />
+ </span>
+ <ul className="text-sm list-disc pl-4 space-y-1">
+ {methodsMissingPullFrom.methods.map((method) => {
+ const to = makeMethodPath(method);
+ return (
+ <li key={method.makeMethodId}>
+ {to ? (
+ <Link
+ to={to}
+ className="underline-offset-2 hover:underline"
+ >
+ {method.readableId}
+ </Link>
+ ) : (
+ method.readableId
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ </VStack>
+ )}
+ </VStack>
+ </CardContent>
+ </Card>
+
<SettingsSectionHeader>
<Trans>Units</Trans>
</SettingsSectionHeader>
@@ -433,3 +559,20 @@ export default function ItemsSettingsRoute() {
</ScrollArea>
);
}
+
+function makeMethodPath(method: {
+ itemId: string;
+ itemType: string;
+ makeMethodId: string;
+}): string | null {
+ switch (method.itemType) {
+ case "Part":
+ return path.to.partMake(method.itemId, method.makeMethodId);
+ case "Tool":
+ return path.to.toolMake(method.itemId, method.makeMethodId);
+ case "Service":
+ return path.to.serviceMake(method.itemId, method.makeMethodId);
+ default:
+ return null;
+ }
+}
diff --git a/apps/erp/test/job-release-logic.test.ts b/apps/erp/test/job-release-logic.test.ts
index ff6767e2fc..88ed3667ee 100644
--- a/apps/erp/test/job-release-logic.test.ts
+++ b/apps/erp/test/job-release-logic.test.ts
@@ -5,6 +5,7 @@
import { describe, expect, it } from "vitest";
import {
jobReleaseProblems,
+ materialsWithoutStorageUnit,
makeMethodsMissingOperations,
outsideOperationsNeedingPurchaseOrders,
resolveOperationSupplier,
@@ -108,7 +109,8 @@ describe("jobReleaseProblems", () => {
const ready = {
manufacturingBlocked: false,
missingAssemblies: [],
- outsideOperationsWithoutSupplier: []
+ outsideOperationsWithoutSupplier: [],
+ materialsWithoutStorageUnit: []
};
it("finds nothing to fix on a job that is ready", () => {
@@ -126,13 +128,81 @@ describe("jobReleaseProblems", () => {
outsideOperationsWithoutSupplier: [
{ description: "Heat Treat", missing: "choose" },
{ description: "Paint", missing: "none" }
+ ],
+ materialsWithoutStorageUnit: [
+ { description: "BOLT-10" },
+ { description: "NUT-10" }
]
})
).toEqual([
"manufacturing is blocked",
"no operations on Bracket, Housing",
"choose a supplier for Heat Treat on the job",
- "Paint has no supplier"
+ "Paint has no supplier",
+ "set a Pull From storage unit on BOLT-10; NUT-10"
]);
});
});
+
+describe("jobReleaseProblems with a long BoM", () => {
+ it("names the first five parts and counts the rest", () => {
+ expect(
+ jobReleaseProblems({
+ manufacturingBlocked: false,
+ missingAssemblies: [],
+ outsideOperationsWithoutSupplier: [],
+ materialsWithoutStorageUnit: Array.from({ length: 40 }, (_, i) => ({
+ description: `PART-${i + 1}`
+ }))
+ })
+ ).toEqual([
+ "set a Pull From storage unit on PART-1; PART-2; PART-3; PART-4; PART-5; and 35 more"
+ ]);
+ });
+});
+
+describe("materialsWithoutStorageUnit", () => {
+ const line = {
+ methodType: "Pull from Inventory",
+ itemType: "Part",
+ storageUnitId: null,
+ item: { itemTrackingType: "Inventory", readableIdWithRevision: "BOLT-10" }
+ };
+
+ it("names each part once, even when it is on several lines", () => {
+ expect(
+ materialsWithoutStorageUnit([
+ { ...line, id: "jm-1", description: "Bolt" },
+ { ...line, id: "jm-2", description: "Bolt" }
+ ])
+ ).toEqual([{ id: "jm-1", description: "BOLT-10" }]);
+ });
+
+ it("skips lines with a storage unit, built lines and non-stock items", () => {
+ expect(
+ materialsWithoutStorageUnit([
+ { ...line, id: "jm-1", description: "Bolt", storageUnitId: "bin-1" },
+ {
+ ...line,
+ id: "jm-2",
+ description: "Bracket",
+ methodType: "Make to Order"
+ },
+ {
+ ...line,
+ id: "jm-3",
+ description: "Paint",
+ item: { itemTrackingType: "Non-Inventory", readableIdWithRevision: "PAINT" }
+ }
+ ])
+ ).toEqual([]);
+ });
+
+ it("falls back to the line description when the item has no readable id", () => {
+ expect(
+ materialsWithoutStorageUnit([
+ { ...line, id: "jm-1", description: "Bolt", item: null }
+ ])
+ ).toEqual([{ id: "jm-1", description: "Bolt" }]);
+ });
+});
diff --git a/apps/erp/test/job-release-readiness.test.ts b/apps/erp/test/job-release-readiness.test.ts
index d2013061b8..b198547377 100644
--- a/apps/erp/test/job-release-readiness.test.ts
+++ b/apps/erp/test/job-release-readiness.test.ts
@@ -31,6 +31,7 @@ function cappedClient(tables: Record<string, Record<string, unknown>[]>) {
rows = rows.filter((row) => values.includes(row[column] as string));
return chain;
};
+ chain.maybeSingle = async () => ({ data: rows[0] ?? null, error: null });
chain.range = async (from: number, to: number) => ({
data: rows.slice(from, Math.min(to + 1, from + ROW_CAP)),
error: null
@@ -115,7 +116,8 @@ describe("getJobReleaseReadiness", () => {
{ makeMethodId: "sub-late", description: "Late Bracket" }
],
outsideOperationsWithoutSupplier: [],
- supplierIds: ["supplier-a"]
+ supplierIds: ["supplier-a"],
+ materialsWithoutStorageUnit: []
}
]);
expect(data?.suppliers).toEqual([
@@ -126,6 +128,71 @@ describe("getJobReleaseReadiness", () => {
]);
});
+ it("lists pulled, stocked lines with no storage unit under strict backflush", async () => {
+ const line = {
+ jobId: "job-1",
+ storageUnitId: null,
+ methodType: "Pull from Inventory",
+ itemType: "Part"
+ };
+ const { client } = cappedClient({
+ companySettings: [{ requireBackflushStorageUnit: true }],
+ job: [{ id: "job-1", jobId: "J000001", status: "Planned", item: null }],
+ jobMakeMethod: [{ id: "root", jobId: "job-1" }],
+ jobOperation: [
+ {
+ id: "op-1",
+ jobId: "job-1",
+ jobMakeMethodId: "root",
+ operationType: "Process",
+ operationSupplierProcessId: null,
+ processId: "machining",
+ description: "Machine"
+ }
+ ],
+ jobMaterial: [
+ {
+ ...line,
+ id: "jm-bolt",
+ description: "Bolt",
+ item: {
+ itemTrackingType: "Inventory",
+ readableIdWithRevision: "BOLT-10"
+ }
+ },
+ // Built in the job, not pulled.
+ {
+ ...line,
+ id: "jm-sub",
+ methodType: "Make to Order",
+ description: "Bracket",
+ item: { itemTrackingType: "Inventory", readableIdWithRevision: "B-1" }
+ },
+ // Holds no stock, so nothing is backflushed.
+ {
+ ...line,
+ id: "jm-labor",
+ description: "Paint",
+ item: {
+ itemTrackingType: "Non-Inventory",
+ readableIdWithRevision: "PAINT"
+ }
+ }
+ ]
+ });
+
+ const { data, error } = await getJobReleaseReadiness(
+ client,
+ ["job-1"],
+ "company-1"
+ );
+
+ expect(error).toBeNull();
+ expect(data?.jobs[0]?.materialsWithoutStorageUnit).toEqual([
+ { id: "jm-bolt", description: "BOLT-10" }
+ ]);
+ });
+
it("reads a whole page of jobs without one long id list", async () => {
const jobIds = Array.from({ length: 250 }, (_, index) => `job-${index}`);
const { client, inFilterSizes } = cappedClient({
diff --git a/apps/mes/app/routes/x+/complete.tsx b/apps/mes/app/routes/x+/complete.tsx
index 90b2eab985..bf4ad0232f 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -209,7 +209,10 @@ export async function action({ request }: ActionFunctionArgs) {
return data(
{},
await flash(request, {
- ...error(response.error, "Failed to complete job operation"),
+ ...error(
+ response.error,
+ response.error.message || "Failed to complete job operation"
+ ),
flash: "error"
})
);
@@ -273,7 +276,10 @@ export async function action({ request }: ActionFunctionArgs) {
return data(
{},
await flash(request, {
- ...error(response.error, "Failed to complete job operation"),
+ ...error(
+ response.error,
+ response.error.message || "Failed to complete job operation"
+ ),
flash: "error"
})
);
@@ -325,6 +331,32 @@ export async function action({ request }: ActionFunctionArgs) {
} else {
// biome-ignore lint/correctness/noUnusedVariables: suppressed due to migration
const { trackedEntityId, trackingType, ...d } = validation.data;
+
+ // Strict backflush: refuse before the production quantity is recorded, so
+ // a short storage unit never leaves units completed with no material
+ // consumed. A no-op when strict backflush is off.
+ const check = await serverFns
+ .system({ db: getDatabaseClient(), companyId, userId })
+ .invoke("issue", {
+ id: validation.data.jobOperationId,
+ type: "jobOperation",
+ quantity: validation.data.quantity,
+ dryRun: true
+ });
+
+ if (check.error) {
+ return data(
+ {},
+ await flash(request, {
+ ...error(
+ check.error,
+ check.error.message || "Failed to issue materials"
+ ),
+ flash: "error"
+ })
+ );
+ }
+
const insertProduction = await insertProductionQuantity(client, {
...d,
companyId,
@@ -356,7 +388,10 @@ export async function action({ request }: ActionFunctionArgs) {
return data(
{},
await flash(request, {
- ...error(issued.error, "Failed to issue materials"),
+ ...error(
+ issued.error,
+ issued.error.message || "Failed to issue materials"
+ ),
flash: "error"
})
);
diff --git a/apps/mes/app/routes/x+/end.$operationId.tsx b/apps/mes/app/routes/x+/end.$operationId.tsx
index 597dbe7b22..9701f2e6ac 100644
--- a/apps/mes/app/routes/x+/end.$operationId.tsx
+++ b/apps/mes/app/routes/x+/end.$operationId.tsx
@@ -198,6 +198,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
notes: "Generated by QR code"
});
+ if (response.error) {
+ return redirect(
+ path.to.operation(operationId),
+ await flash(request, {
+ ...error(
+ response.error,
+ response.error.message || "Failed to complete job operation"
+ ),
+ flash: "error"
+ })
+ );
+ }
+
const newTrackedEntityId = response.data?.newTrackedEntityId;
if (newTrackedEntityId) {
@@ -272,13 +285,41 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return redirect(
path.to.operation(operationId),
await flash(request, {
- ...error(response.error, "Failed to complete job operation"),
+ ...error(
+ response.error,
+ response.error.message || "Failed to complete job operation"
+ ),
flash: "error"
})
);
}
}
} else {
+ // Strict backflush: refuse before the production quantity is recorded,
+ // so a short storage unit never leaves units completed with no material
+ // consumed. A no-op when strict backflush is off.
+ const check = await serverFns
+ .system({ db: getDatabaseClient(), companyId, userId })
+ .invoke("issue", {
+ id: operationId,
+ type: "jobOperation",
+ quantity: quantityToComplete,
+ dryRun: true
+ });
+
+ if (check.error) {
+ return redirect(
+ path.to.operation(operationId),
+ await flash(request, {
+ ...error(
+ check.error,
+ check.error.message || "Failed to issue materials"
+ ),
+ flash: "error"
+ })
+ );
+ }
+
const insertProduction = await insertProductionQuantity(
serviceRole,
{
@@ -316,7 +357,10 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return redirect(
path.to.operation(operationId),
await flash(request, {
- ...error(issued.error, "Failed to issue materials"),
+ ...error(
+ issued.error,
+ issued.error.message || "Failed to issue materials"
+ ),
flash: "error"
})
);
diff --git a/apps/mes/app/routes/x+/issue.tsx b/apps/mes/app/routes/x+/issue.tsx
index fc5e6739dc..794a4227e1 100644
--- a/apps/mes/app/routes/x+/issue.tsx
+++ b/apps/mes/app/routes/x+/issue.tsx
@@ -116,7 +116,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (issued.error) {
throw redirect(
requestReferrer(request) ?? path.to.operations,
- await flash(request, error(issued.error, "Failed to issue material"))
+ await flash(
+ request,
+ error(issued.error, issued.error.message || "Failed to issue material")
+ )
);
}
diff --git a/apps/mes/app/routes/x+/scrap.tsx b/apps/mes/app/routes/x+/scrap.tsx
index 78bfc936d9..67c4570c3d 100644
--- a/apps/mes/app/routes/x+/scrap.tsx
+++ b/apps/mes/app/routes/x+/scrap.tsx
@@ -58,7 +58,10 @@ export async function action({ request }: ActionFunctionArgs) {
{},
await flash(
request,
- error(issued.error, "Failed to record scrap quantity")
+ error(
+ issued.error,
+ issued.error.message || "Failed to record scrap quantity"
+ )
)
);
}
diff --git a/apps/mes/app/services/operations.service.ts b/apps/mes/app/services/operations.service.ts
index 398676b16c..fd34aa16be 100644
--- a/apps/mes/app/services/operations.service.ts
+++ b/apps/mes/app/services/operations.service.ts
@@ -1551,13 +1551,15 @@ export async function backflushUntrackedMaterialsOnStepRecord(
quantity: delta,
adjustmentType: "Negative Adjmt."
});
- if (issued.error) failures.push(material.itemId);
+ // The server's refusal (strict backflush names the part and the storage
+ // unit) says more than the bare item id.
+ if (issued.error) failures.push(issued.error.message || material.itemId);
}
return {
error: failures.length
? new Error(
- `Backflush failed for ${failures.length} material(s): ${failures.join(", ")}`
+ `Backflush failed for ${failures.length} material(s): ${failures.join("; ")}`
)
: null
};
diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.ts
index 8ba1077a0b..ce99981bbc 100644
--- a/apps/mes/app/services/quality.server.ts
+++ b/apps/mes/app/services/quality.server.ts
@@ -572,11 +572,36 @@ export async function postBulkCompletion(
...args.eventIds
});
if (response.error) {
- return { error: response.error, message: "Failed to complete units" };
+ return {
+ error: response.error,
+ message: response.error.message || "Failed to complete units"
+ };
}
return { error: null, message: null };
}
+ // Strict backflush: refuse before the production quantity is recorded, so a
+ // short storage unit never leaves units completed with no material
+ // consumed. A no-op when strict backflush is off.
+ const check = await serverFns
+ .system({
+ db: getDatabaseClient(),
+ companyId: args.companyId,
+ userId: args.userId
+ })
+ .invoke("issue", {
+ id: state.jobOperationId,
+ type: "jobOperation",
+ quantity: args.quantity,
+ dryRun: true
+ });
+ if (check.error) {
+ return {
+ error: check.error,
+ message: check.error.message || "Failed to issue materials"
+ };
+ }
+
const insertResult = await insertProductionQuantity(client, {
jobOperationId: state.jobOperationId,
quantity: args.quantity,
@@ -607,7 +632,8 @@ export async function postBulkCompletion(
if (issued.error) {
return {
error: issued.error,
- message: "Units completed, but failed to issue materials"
+ message:
+ issued.error.message || "Units completed, but failed to issue materials"
};
}
diff --git a/packages/database/package.json b/packages/database/package.json
index 0897f076fb..47a5f7b20d 100644
--- a/packages/database/package.json
+++ b/packages/database/package.json
@@ -31,6 +31,7 @@
"./supersession-pick": "./src/supersession-pick.ts",
"./account-import": "./src/account-import.ts",
"./account-import-reads": "./src/account-import-reads.ts",
+ "./strict-backflush": "./src/strict-backflush.ts",
"./supplier-part-price": "./src/supplier-part-price.ts",
"./contract-schedule": "./src/contract-schedule.ts",
"./contract-revenue-schedule": "./src/contract-revenue-schedule.ts",
diff --git a/packages/database/src/strict-backflush.test.ts b/packages/database/src/strict-backflush.test.ts
new file mode 100644
index 0000000000..f55bdb20d1
--- /dev/null
+++ b/packages/database/src/strict-backflush.test.ts
@@ -0,0 +1,132 @@
+// 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.
+
+import { describe, expect, it } from "vitest";
+import {
+ binShortfall,
+ missingPullFromLocations,
+ needsPullFrom,
+ summarizeList
+} from "./strict-backflush.ts";
+
+describe("needsPullFrom", () => {
+ const stocked = {
+ methodType: "Pull from Inventory",
+ itemType: "Part",
+ itemTrackingType: "Inventory"
+ };
+
+ it("requires a bin on a pulled, stocked line", () => {
+ expect(needsPullFrom(stocked)).toBe(true);
+ });
+
+ it("requires a bin on a Purchase to Order line", () => {
+ expect(needsPullFrom({ ...stocked, methodType: "Purchase to Order" })).toBe(
+ true
+ );
+ });
+
+ it("requires a bin on batch and serial lines", () => {
+ expect(needsPullFrom({ ...stocked, itemTrackingType: "Batch" })).toBe(true);
+ expect(needsPullFrom({ ...stocked, itemTrackingType: "Serial" })).toBe(
+ true
+ );
+ });
+
+ it("treats an unknown tracking type as stocked", () => {
+ expect(needsPullFrom({ ...stocked, itemTrackingType: null })).toBe(true);
+ });
+
+ it("skips a Make to Order line, which is built, not pulled", () => {
+ expect(needsPullFrom({ ...stocked, methodType: "Make to Order" })).toBe(
+ false
+ );
+ });
+
+ it("skips a Non-Inventory item, which holds no stock", () => {
+ expect(
+ needsPullFrom({ ...stocked, itemTrackingType: "Non-Inventory" })
+ ).toBe(false);
+ });
+
+ it("skips tools and services, which a backflush never consumes", () => {
+ expect(needsPullFrom({ ...stocked, itemType: "Tool" })).toBe(false);
+ expect(needsPullFrom({ ...stocked, itemType: "Service" })).toBe(false);
+ });
+});
+
+describe("missingPullFromLocations", () => {
+ it("returns the locations with no bin", () => {
+ expect(
+ missingPullFromLocations({ plant: "bin-1" }, ["plant", "annex"])
+ ).toEqual(["annex"]);
+ });
+
+ it("treats a cleared bin (empty string) as missing", () => {
+ expect(missingPullFromLocations({ plant: "" }, ["plant"])).toEqual([
+ "plant"
+ ]);
+ });
+
+ it("treats a null or malformed map as missing everywhere", () => {
+ expect(missingPullFromLocations(null, ["plant"])).toEqual(["plant"]);
+ expect(missingPullFromLocations("bin-1", ["plant"])).toEqual(["plant"]);
+ });
+
+ it("requires nothing when no location has a work center", () => {
+ expect(missingPullFromLocations({}, [])).toEqual([]);
+ });
+});
+
+describe("binShortfall", () => {
+ it("is 0 when the bin covers the quantity", () => {
+ expect(binShortfall({ onHand: 10, alreadyDrawn: 0, quantity: 10 })).toBe(0);
+ });
+
+ it("is the uncovered quantity when the bin is short", () => {
+ expect(binShortfall({ onHand: 6, alreadyDrawn: 0, quantity: 10 })).toBe(4);
+ });
+
+ it("counts what earlier rows of the same backflush draw", () => {
+ expect(binShortfall({ onHand: 10, alreadyDrawn: 7, quantity: 5 })).toBe(2);
+ });
+
+ it("treats a negative bin as empty", () => {
+ expect(binShortfall({ onHand: -3, alreadyDrawn: 0, quantity: 2 })).toBe(2);
+ });
+
+ it("ignores float noise", () => {
+ expect(
+ binShortfall({ onHand: 0.3, alreadyDrawn: 0.1, quantity: 0.2 })
+ ).toBe(0);
+ });
+});
+
+describe("summarizeList", () => {
+ const parts = Array.from({ length: 120 }, (_, i) => `PART-${i + 1}`);
+
+ it("lists every entry up to the limit", () => {
+ expect(summarizeList(["A", "B"])).toBe("A; B");
+ expect(summarizeList(parts.slice(0, 5))).toBe(
+ "PART-1; PART-2; PART-3; PART-4; PART-5"
+ );
+ });
+
+ it("names the first entries and counts the rest", () => {
+ expect(summarizeList(parts)).toBe(
+ "PART-1; PART-2; PART-3; PART-4; PART-5; and 115 more"
+ );
+ expect(summarizeList(parts, 3)).toBe(
+ "PART-1; PART-2; PART-3; and 117 more"
+ );
+ });
+
+ it("stays short however many entries there are", () => {
+ expect(summarizeList(parts).length).toBeLessThan(80);
+ });
+
+ it("is empty for no entries", () => {
+ expect(summarizeList([])).toBe("");
+ });
+});
diff --git a/packages/database/src/strict-backflush.ts b/packages/database/src/strict-backflush.ts
new file mode 100644
index 0000000000..d874752a10
--- /dev/null
+++ b/packages/database/src/strict-backflush.ts
@@ -0,0 +1,122 @@
+// 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.
+
+// Strict backflush (companySettings.requireBackflushStorageUnit,
+// .ai/specs/2026-10-14-strict-backflush.md). One rule for "which material
+// lines must name a Pull From storage unit", read by method activation
+// (`convert`), job release and the Settings → Items card, so the three can
+// never disagree about which lines count.
+
+import type { Kysely, KyselyDatabase } from "./client.ts";
+import { round } from "./precision.ts";
+
+// The item types a backflush consumes (`issueJobOperationMaterials`, SQL
+// `backflush_job_materials`). Tools and services are never consumed.
+export const PULLED_ITEM_TYPES = ["Material", "Part", "Consumable"] as const;
+
+export type PullFromLine = {
+ methodType: string | null;
+ itemType: string | null;
+ itemTrackingType: string | null;
+};
+
+// A line is pulled from a bin when it is not built in the job (Make to Order)
+// and its item holds stock. Purchase to Order lines count: the goods are
+// received into a bin and backflushed from it. Batch and serial lines count
+// too — the operator scans the unit, but planning and picking still read the
+// line's bin.
+export function needsPullFrom(line: PullFromLine): boolean {
+ if (line.methodType === "Make to Order") return false;
+ if (
+ !PULLED_ITEM_TYPES.includes(
+ line.itemType as (typeof PULLED_ITEM_TYPES)[number]
+ )
+ )
+ return false;
+ return line.itemTrackingType !== "Non-Inventory";
+}
+
+// `methodMaterial.storageUnitIds` maps locationId → storageUnitId. An empty
+// string is what the BoM editor writes when a bin is cleared, so it counts as
+// missing.
+export function missingPullFromLocations(
+ storageUnitIds: unknown,
+ locationIds: readonly string[]
+): string[] {
+ const map =
+ storageUnitIds && typeof storageUnitIds === "object"
+ ? (storageUnitIds as Record<string, unknown>)
+ : {};
+ return locationIds.filter((locationId) => {
+ const storageUnitId = map[locationId];
+ return typeof storageUnitId !== "string" || storageUnitId.length === 0;
+ });
+}
+
+// The locations a pulled line needs a Pull From at: each one with an active
+// work center AND an active storage unit. A location with no work center
+// builds nothing; one with no storage unit has no bin a line could name (a
+// test lab at head office), so requiring one there would block activation
+// for good.
+export async function getPullFromLocations(
+ db: Kysely<KyselyDatabase>,
+ companyId: string
+): Promise<{ id: string; name: string }[]> {
+ return db
+ .selectFrom("location")
+ .where("location.companyId", "=", companyId)
+ .where((eb) =>
+ eb.exists(
+ eb
+ .selectFrom("workCenter")
+ .whereRef("workCenter.locationId", "=", "location.id")
+ .where("workCenter.companyId", "=", companyId)
+ .where("workCenter.active", "=", true)
+ .select("workCenter.id")
+ )
+ )
+ .where((eb) =>
+ eb.exists(
+ eb
+ .selectFrom("storageUnit")
+ .whereRef("storageUnit.locationId", "=", "location.id")
+ .where("storageUnit.companyId", "=", companyId)
+ .where("storageUnit.active", "=", true)
+ .select("storageUnit.id")
+ )
+ )
+ .select(["location.id", "location.name"])
+ .orderBy("location.name")
+ .execute();
+}
+
+// A refusal is shown as a toast, so it names only the first `limit` entries and
+// counts the rest. A 20-line BoM otherwise produced a 900-character toast that
+// ran off the screen and faded before it could be read.
+export const MESSAGE_LIST_LIMIT = 5;
+
+export function summarizeList(
+ entries: readonly string[],
+ limit: number = MESSAGE_LIST_LIMIT
+): string {
+ if (entries.length <= limit) return entries.join("; ");
+ return `${entries.slice(0, limit).join("; ")}; and ${entries.length - limit} more`;
+}
+
+// What the bin cannot cover. `alreadyDrawn` is what earlier rows of the same
+// backflush take from this bin before they are written, so two materials of
+// one operation sharing a bin cannot both count the same stock.
+export function binShortfall({
+ onHand,
+ alreadyDrawn,
+ quantity
+}: {
+ onHand: number;
+ alreadyDrawn: number;
+ quantity: number;
+}): number {
+ const available = Math.max(onHand - alreadyDrawn, 0);
+ const shortfall = round(quantity - available);
+ return shortfall > 0 ? shortfall : 0;
+}
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index b6d77dc365..03ebdd2128 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -102384,6 +102384,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.accountingActivatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.requireBackflushStorageUnit"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.leaseIncrementalBorrowingRate"
},
@@ -102656,6 +102659,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.accountingActivatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.requireBackflushStorageUnit"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.leaseIncrementalBorrowingRate"
},
@@ -102882,6 +102888,9 @@ export default {
{
$ref: "#/parameters/rowFilter.companySettings.accountingActivatedBy"
},
+ {
+ $ref: "#/parameters/rowFilter.companySettings.requireBackflushStorageUnit"
+ },
{
$ref: "#/parameters/rowFilter.companySettings.leaseIncrementalBorrowingRate"
},
@@ -166663,6 +166672,7 @@ export default {
"leaseDefaultDiscountRate",
"invoiceAutomation",
"invoiceNotificationGroup",
+ "requireBackflushStorageUnit",
"leaseIncrementalBorrowingRate",
"leaseShortTermExpedient",
"leaseReminderDays"
@@ -167039,6 +167049,11 @@ export default {
format: "text",
type: "string"
},
+ requireBackflushStorageUnit: {
+ default: false,
+ format: "boolean",
+ type: "boolean"
+ },
leaseIncrementalBorrowingRate: {
default: 6,
format: "numeric",
@@ -222616,6 +222631,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.companySettings.requireBackflushStorageUnit": {
+ name: "requireBackflushStorageUnit",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"rowFilter.companySettings.leaseIncrementalBorrowingRate": {
name: "leaseIncrementalBorrowingRate",
required: false,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 59a9fb40cb..7684d83240 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -8365,6 +8365,7 @@ export type Database = {
qualityDispatchNotificationGroup: string[] | null
qualityIssueTarget: number
quoteLineCategoryMarkups: Json | null
+ requireBackflushStorageUnit: boolean
requireCustomerContactAndLocation: boolean
requireMfa: boolean
requireSupplierContactAndLocation: boolean
@@ -8438,6 +8439,7 @@ export type Database = {
qualityDispatchNotificationGroup?: string[] | null
qualityIssueTarget?: number
quoteLineCategoryMarkups?: Json | null
+ requireBackflushStorageUnit?: boolean
requireCustomerContactAndLocation?: boolean
requireMfa?: boolean
requireSupplierContactAndLocation?: boolean
@@ -8511,6 +8513,7 @@ export type Database = {
qualityDispatchNotificationGroup?: string[] | null
qualityIssueTarget?: number
quoteLineCategoryMarkups?: Json | null
+ requireBackflushStorageUnit?: boolean
requireCustomerContactAndLocation?: boolean
requireMfa?: boolean
requireSupplierContactAndLocation?: boolean
diff --git a/packages/database/supabase/migrations/20261015122149_strict-backflush.sql b/packages/database/supabase/migrations/20261015122149_strict-backflush.sql
new file mode 100644
index 0000000000..6647027253
--- /dev/null
+++ b/packages/database/supabase/migrations/20261015122149_strict-backflush.sql
@@ -0,0 +1,512 @@
+-- Strict backflush (.ai/specs/2026-10-14-strict-backflush.md, CARBON-113).
+--
+-- companySettings.requireBackflushStorageUnit turns it on (off by default).
+-- backflush_job_materials is copied from its live definition
+-- (20261009010412_job-costing-always-post.sql) with one change: when the
+-- setting is on, a stocked material is consumed only from
+-- jobMaterial.storageUnitId, and a missing or short bin raises instead of
+-- falling back to the pick method's bin or the fullest bin. With the setting
+-- off the function is unchanged.
+
+ALTER TABLE "companySettings"
+ ADD COLUMN IF NOT EXISTS "requireBackflushStorageUnit" BOOLEAN NOT NULL DEFAULT false;
+
+CREATE OR REPLACE FUNCTION public.backflush_job_materials(p_job_id text, p_quantity_complete numeric, p_company_id text, p_user_id text)
+ RETURNS void
+ LANGUAGE plpgsql
+ SET search_path TO 'public'
+AS $function$
+DECLARE
+ v_job_quantity NUMERIC;
+ v_job_location_id TEXT;
+ v_job_id_readable TEXT;
+ v_ratio NUMERIC;
+ v_target NUMERIC;
+ v_material RECORD;
+ v_material_qty_to_issue NUMERIC;
+ v_material_storage_unit_id TEXT;
+ v_bin_work_center_id TEXT;
+ v_bin_on_hand NUMERIC;
+ v_strict BOOLEAN;
+ v_storage_unit_name TEXT;
+ v_strict_problems TEXT[] := '{}';
+ v_material_costing_method TEXT;
+ v_material_standard_cost NUMERIC;
+ v_material_unit_cost NUMERIC;
+ v_material_item_posting_group_id TEXT;
+ v_material_cogs_total NUMERIC;
+ v_cost_layer RECORD;
+ v_remaining_to_consume NUMERIC;
+ v_layer_unit_cost NUMERIC;
+ v_quantity_from_layer NUMERIC;
+ v_adjustment_child RECORD;
+ v_child_budget NUMERIC;
+ v_child_apply NUMERIC;
+ v_child_per_unit NUMERIC;
+ v_posting_status "journalEntryStatus";
+ v_company_group_id TEXT;
+ v_raw_materials_account TEXT;
+ v_finished_goods_account TEXT;
+ v_material_inventory_account TEXT;
+ v_material_inventory_description TEXT;
+ v_wip_account TEXT;
+ v_dimension_item_posting_group TEXT;
+ v_dimension_item TEXT;
+ v_dimension_location TEXT;
+ v_bf_item_ids TEXT[] := '{}';
+ v_bf_quantities NUMERIC[] := '{}';
+ v_bf_storage_unit_ids TEXT[] := '{}';
+ v_bf_journal_id TEXT;
+ v_bf_journal_entry_id TEXT;
+ v_bf_accounting_period_id TEXT;
+ v_bf_journal_line_ref TEXT;
+ v_bf_jl_id TEXT;
+ v_bf_jl_ids TEXT[];
+ v_bf_posting_group_ids TEXT[];
+ v_bf_line_item_ids TEXT[];
+ v_company_today DATE := company_today(p_company_id);
+BEGIN
+ -- Never let a NULL user reach NOT NULL audit columns; fall back to the job creator
+ p_user_id := COALESCE(p_user_id, (SELECT "createdBy" FROM "job" WHERE id = p_job_id));
+
+ -- Fetch job details
+ SELECT quantity, "locationId", "jobId"
+ INTO STRICT v_job_quantity, v_job_location_id, v_job_id_readable
+ FROM "job"
+ WHERE id = p_job_id;
+
+ IF v_job_quantity IS NULL OR v_job_quantity <= 0 THEN
+ RETURN;
+ END IF;
+
+ v_ratio := p_quantity_complete / v_job_quantity;
+
+ -- Strict backflush (.ai/specs/2026-10-14-strict-backflush.md): a stocked
+ -- material is consumed only from its own storage unit, and a short bin
+ -- refuses the whole completion instead of drawing from another bin.
+ SELECT COALESCE("requireBackflushStorageUnit", false) INTO v_strict
+ FROM "companySettings"
+ WHERE id = p_company_id;
+ v_strict := COALESCE(v_strict, false);
+
+ -- Backflush non-tracked materials
+ FOR v_material IN
+ SELECT jm.id, jm."itemId", jm."quantityToIssue", jm."quantityIssued",
+ jm."estimatedQuantity", jm."storageUnitId", jm."defaultStorageUnit",
+ i."itemTrackingType", i."readableIdWithRevision" AS "itemReadableId"
+ FROM "jobMaterial" jm
+ LEFT JOIN "item" i ON i.id = jm."itemId"
+ WHERE jm."jobId" = p_job_id
+ AND jm."itemType" IN ('Material', 'Part', 'Consumable')
+ AND jm."methodType" != 'Make to Order'
+ AND jm."requiresBatchTracking" = false
+ AND jm."requiresSerialTracking" = false
+ AND jm."quantityToIssue" > 0
+ LOOP
+ -- Prorate: only issue what's needed for the completed quantity
+ v_target := v_material."estimatedQuantity" * v_ratio;
+ v_material_qty_to_issue := GREATEST(v_target - COALESCE(v_material."quantityIssued", 0), 0);
+
+ IF v_material_qty_to_issue <= 0 THEN
+ CONTINUE;
+ END IF;
+
+ IF v_strict AND COALESCE(v_material."itemTrackingType", 'Inventory') <> 'Non-Inventory' THEN
+ v_material_storage_unit_id := v_material."storageUnitId";
+
+ -- Every material the bins cannot cover is collected and refused together
+ -- after the loop, so the material controller sees them all at once.
+ IF v_material_storage_unit_id IS NULL THEN
+ v_strict_problems := v_strict_problems || format(
+ '%s has no Pull From storage unit on job %s',
+ COALESCE(v_material."itemReadableId", v_material."itemId"), v_job_id_readable
+ );
+ CONTINUE;
+ END IF;
+
+ -- Serialize strict draws on this bin and item until the transaction
+ -- ends; the TypeScript backflush (assertBinCovers) takes the same key.
+ PERFORM pg_advisory_xact_lock(hashtextextended(
+ 'strict-backflush:' || p_company_id || ':' || v_material_storage_unit_id
+ || ':' || v_material."itemId",
+ 0
+ ));
+
+ SELECT COALESCE(SUM(quantity), 0) INTO v_bin_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_material."itemId"
+ AND "storageUnitId" = v_material_storage_unit_id
+ AND "locationId" = v_job_location_id
+ AND "companyId" = p_company_id
+ AND "trackedEntityId" IS NULL;
+
+ IF v_bin_on_hand < v_material_qty_to_issue THEN
+ SELECT name INTO v_storage_unit_name
+ FROM "storageUnit"
+ WHERE id = v_material_storage_unit_id;
+
+ v_strict_problems := v_strict_problems || format(
+ 'Not enough %s in %s: need %s, have %s',
+ COALESCE(v_material."itemReadableId", v_material."itemId"),
+ COALESCE(v_storage_unit_name, v_material_storage_unit_id),
+ trim_scale(v_material_qty_to_issue),
+ trim_scale(GREATEST(v_bin_on_hand, 0))
+ );
+ CONTINUE;
+ END IF;
+ ELSE
+ -- Resolve storage unit (strict backflush off: the pre-existing fallbacks)
+ v_material_storage_unit_id := v_material."storageUnitId";
+
+ IF v_material_storage_unit_id IS NULL AND v_material."defaultStorageUnit" THEN
+ SELECT "defaultStorageUnitId" INTO v_material_storage_unit_id
+ FROM "pickMethod"
+ WHERE "itemId" = v_material."itemId"
+ AND "locationId" = v_job_location_id
+ AND "companyId" = p_company_id;
+ END IF;
+
+ IF v_material_storage_unit_id IS NULL THEN
+ SELECT "storageUnitId" INTO v_material_storage_unit_id
+ FROM "itemLedger"
+ WHERE "itemId" = v_material."itemId"
+ AND "locationId" = v_job_location_id
+ AND "storageUnitId" IS NOT NULL
+ GROUP BY "storageUnitId"
+ HAVING SUM(quantity) > 0
+ ORDER BY SUM(quantity) DESC
+ LIMIT 1;
+ END IF;
+
+ -- Clamp lineside draws to actual untracked on-hand. An early per-operation
+ -- return (returnPickedMaterialTiming = 'operation') or a manual transfer can
+ -- leave the lineside bin short of the prorated target; never post a
+ -- consumption the bin cannot supply. Warehouse bins (no workCenterId) keep
+ -- the historical unclamped behavior.
+ v_bin_work_center_id := NULL;
+ IF v_material_storage_unit_id IS NOT NULL THEN
+ SELECT su."workCenterId" INTO v_bin_work_center_id
+ FROM "storageUnit" su
+ WHERE su.id = v_material_storage_unit_id;
+
+ IF v_bin_work_center_id IS NOT NULL THEN
+ SELECT COALESCE(SUM(quantity), 0) INTO v_bin_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_material."itemId"
+ AND "storageUnitId" = v_material_storage_unit_id
+ AND "locationId" = v_job_location_id
+ AND "companyId" = p_company_id
+ AND "trackedEntityId" IS NULL;
+
+ v_material_qty_to_issue := LEAST(v_material_qty_to_issue, GREATEST(v_bin_on_hand, 0));
+
+ IF v_material_qty_to_issue <= 0 THEN
+ CONTINUE;
+ END IF;
+ END IF;
+ END IF;
+ END IF;
+
+ INSERT INTO "itemLedger" (
+ "entryType", "documentType", "documentId", "companyId",
+ "itemId", quantity, "locationId", "storageUnitId", "createdBy"
+ ) VALUES (
+ 'Consumption', 'Job Consumption', p_job_id, p_company_id,
+ v_material."itemId", -v_material_qty_to_issue,
+ v_job_location_id, v_material_storage_unit_id, p_user_id
+ );
+
+ UPDATE "jobMaterial"
+ SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_material_qty_to_issue
+ WHERE id = v_material.id;
+
+ v_bf_item_ids := v_bf_item_ids || v_material."itemId";
+ v_bf_quantities := v_bf_quantities || v_material_qty_to_issue;
+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || COALESCE(v_material_storage_unit_id, '');
+ END LOOP;
+
+ -- The refusal is shown as a toast: name the first three shortfalls and
+ -- count the rest (strictBackflushRefusal in @carbon/server-functions does
+ -- the same), so a long BoM cannot produce a wall of text.
+ IF array_length(v_strict_problems, 1) > 3 THEN
+ RAISE EXCEPTION '%; and % more',
+ array_to_string(v_strict_problems[1:3], '; '),
+ array_length(v_strict_problems, 1) - 3;
+ ELSIF array_length(v_strict_problems, 1) > 0 THEN
+ RAISE EXCEPTION '%', array_to_string(v_strict_problems, '; ');
+ END IF;
+
+ -- Every company posts; the accounting cutover decides the status
+ -- (.ai/specs/2026-10-08-accounting-cutover.md section 1).
+ v_posting_status := journal_posting_status(p_company_id);
+
+ IF array_length(v_bf_item_ids, 1) IS NULL OR array_length(v_bf_item_ids, 1) = 0 THEN
+ RETURN;
+ END IF;
+
+ -- Fetch company group
+ SELECT "companyGroupId"
+ INTO STRICT v_company_group_id
+ FROM company
+ WHERE id = p_company_id;
+
+ -- Fetch account defaults
+ SELECT "rawMaterialsAccount", "finishedGoodsAccount", "workInProgressAccount"
+ INTO STRICT v_raw_materials_account, v_finished_goods_account, v_wip_account
+ FROM "accountDefault"
+ WHERE "companyId" = p_company_id;
+
+ -- Fetch dimension IDs
+ SELECT
+ MAX(CASE WHEN "entityType" = 'ItemPostingGroup' THEN id END),
+ MAX(CASE WHEN "entityType" = 'Item' THEN "id" END),
+ MAX(CASE WHEN "entityType" = 'Location' THEN id END)
+ INTO v_dimension_item_posting_group, v_dimension_item, v_dimension_location
+ FROM dimension
+ WHERE "companyGroupId" = v_company_group_id
+ AND active = true
+ AND "entityType" IN ('ItemPostingGroup', 'Item', 'Location');
+
+ -- Get accounting period
+ SELECT id INTO v_bf_accounting_period_id
+ FROM "accountingPeriod"
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_company_today
+ AND "endDate" >= v_company_today
+ AND status = 'Active'
+ LIMIT 1;
+
+ IF v_bf_accounting_period_id IS NULL AND v_posting_status = 'Posted' THEN
+ UPDATE "accountingPeriod"
+ SET status = 'Inactive'
+ WHERE status = 'Active' AND "companyId" = p_company_id;
+
+ UPDATE "accountingPeriod"
+ SET status = 'Active'
+ WHERE "companyId" = p_company_id
+ AND "startDate" <= v_company_today
+ AND "endDate" >= v_company_today
+ RETURNING id INTO v_bf_accounting_period_id;
+
+ IF v_bf_accounting_period_id IS NULL THEN
+ INSERT INTO "accountingPeriod" (
+ "startDate", "endDate", "companyId", status, "createdBy"
+ ) VALUES (
+ date_trunc('month', v_company_today)::DATE,
+ (date_trunc('month', v_company_today) + INTERVAL '1 month' - INTERVAL '1 day')::DATE,
+ p_company_id, 'Active', 'system'
+ )
+ RETURNING id INTO v_bf_accounting_period_id;
+ END IF;
+ END IF;
+
+ -- A Provisional journal has no accounting period (spec section 1).
+ IF v_posting_status <> 'Posted' THEN
+ v_bf_accounting_period_id := NULL;
+ END IF;
+
+ v_bf_journal_entry_id := get_next_sequence('journalEntry', p_company_id);
+
+ INSERT INTO journal (
+ "journalEntryId", "accountingPeriodId", description,
+ "postingDate", "companyId", "sourceType", status,
+ "postedAt", "postedBy", "createdBy"
+ ) VALUES (
+ v_bf_journal_entry_id, v_bf_accounting_period_id,
+ 'Material Issue — Job ' || v_job_id_readable,
+ v_company_today, p_company_id, 'Job Consumption', v_posting_status,
+ NOW(), p_user_id, p_user_id
+ )
+ RETURNING id INTO v_bf_journal_id;
+
+ v_bf_jl_ids := '{}';
+ v_bf_posting_group_ids := '{}';
+ v_bf_line_item_ids := '{}';
+
+ FOR i IN 1..array_length(v_bf_item_ids, 1)
+ LOOP
+ -- Get itemCost for COGS calculation
+ SELECT "costingMethod", "standardCost", "unitCost", "itemPostingGroupId"
+ INTO v_material_costing_method, v_material_standard_cost, v_material_unit_cost, v_material_item_posting_group_id
+ FROM "itemCost"
+ WHERE "itemId" = v_bf_item_ids[i]
+ AND "companyId" = p_company_id;
+
+ IF v_material_costing_method IS NULL THEN
+ CONTINUE;
+ END IF;
+
+ -- Calculate COGS based on costing method
+ v_material_cogs_total := 0;
+
+ IF v_material_costing_method = 'Standard' THEN
+ v_material_cogs_total := COALESCE(v_material_standard_cost, 0) * v_bf_quantities[i];
+
+ ELSIF v_material_costing_method = 'Average' THEN
+ v_material_cogs_total := COALESCE(v_material_unit_cost, 0) * v_bf_quantities[i];
+
+ ELSIF v_material_costing_method IN ('FIFO', 'LIFO') THEN
+ v_remaining_to_consume := v_bf_quantities[i];
+
+ FOR v_cost_layer IN
+ SELECT id, quantity, cost, "remainingQuantity"
+ FROM "costLedger"
+ WHERE "itemId" = v_bf_item_ids[i]
+ AND "companyId" = p_company_id
+ AND "remainingQuantity" > 0
+ -- adjustment child rows are consumed with their parent, not as layers
+ AND adjustment = false
+ AND "appliesToCostLedgerId" IS NULL
+ -- 'Purchase Order' rows are planning/cost-history artifacts, not layers
+ AND ("documentType" IS NULL OR "documentType" <> 'Purchase Order')
+ ORDER BY
+ CASE WHEN v_material_costing_method = 'FIFO' THEN "postingDate" END ASC,
+ CASE WHEN v_material_costing_method = 'LIFO' THEN "postingDate" END DESC,
+ CASE WHEN v_material_costing_method = 'FIFO' THEN "createdAt" END ASC,
+ CASE WHEN v_material_costing_method = 'LIFO' THEN "createdAt" END DESC
+ LOOP
+ EXIT WHEN v_remaining_to_consume <= 0;
+
+ v_layer_unit_cost := CASE
+ WHEN v_cost_layer.quantity > 0 THEN v_cost_layer.cost / v_cost_layer.quantity
+ ELSE 0
+ END;
+
+ v_quantity_from_layer := LEAST(v_remaining_to_consume, v_cost_layer."remainingQuantity");
+ v_material_cogs_total := v_material_cogs_total + v_quantity_from_layer * v_layer_unit_cost;
+ v_remaining_to_consume := v_remaining_to_consume - v_quantity_from_layer;
+
+ UPDATE "costLedger"
+ SET "remainingQuantity" = "remainingQuantity" - v_quantity_from_layer
+ WHERE id = v_cost_layer.id;
+
+ -- Consume the layer's cost-adjustment children (invoice-vs-receipt
+ -- price corrections linked via "appliesToCostLedgerId") alongside the
+ -- parent: each adjusted unit carries a bump of child.cost/child.quantity.
+ -- Mirrors shared/calculate-cogs.ts.
+ v_child_budget := v_quantity_from_layer;
+ FOR v_adjustment_child IN
+ SELECT id, quantity, cost, "remainingQuantity"
+ FROM "costLedger"
+ WHERE "appliesToCostLedgerId" = v_cost_layer.id
+ AND "remainingQuantity" > 0
+ ORDER BY "createdAt" ASC
+ LOOP
+ EXIT WHEN v_child_budget <= 0;
+
+ v_child_per_unit := CASE
+ WHEN v_adjustment_child.quantity > 0
+ THEN v_adjustment_child.cost / v_adjustment_child.quantity
+ ELSE 0
+ END;
+
+ v_child_apply := LEAST(v_adjustment_child."remainingQuantity", v_child_budget);
+ v_material_cogs_total := v_material_cogs_total + v_child_apply * v_child_per_unit;
+ v_child_budget := v_child_budget - v_child_apply;
+
+ UPDATE "costLedger"
+ SET "remainingQuantity" = "remainingQuantity" - v_child_apply
+ WHERE id = v_adjustment_child.id;
+ END LOOP;
+ END LOOP;
+
+ -- Fallback for negative inventory
+ IF v_remaining_to_consume > 0 THEN
+ v_material_cogs_total := v_material_cogs_total + v_remaining_to_consume * COALESCE(v_material_unit_cost, 0);
+ END IF;
+ END IF;
+
+ IF v_material_cogs_total <= 0 THEN
+ CONTINUE;
+ END IF;
+
+ -- Resolve Raw Materials vs Finished Goods from the consumed item:
+ -- Buy → Raw Materials; Make / Buy and Make → Finished Goods.
+ SELECT
+ CASE WHEN i2."replenishmentSystem" = 'Buy' THEN v_raw_materials_account ELSE v_finished_goods_account END,
+ CASE WHEN i2."replenishmentSystem" = 'Buy' THEN 'Raw Materials Account' ELSE 'Finished Goods Account' END
+ INTO v_material_inventory_account, v_material_inventory_description
+ FROM "item" i2
+ WHERE i2."id" = v_bf_item_ids[i]
+ AND i2."companyId" = p_company_id;
+
+ v_bf_journal_line_ref := nanoid();
+
+ -- DR WIP
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_bf_journal_id, v_wip_account, 'WIP Account',
+ v_material_cogs_total, v_bf_quantities[i],
+ 'Job Consumption', p_job_id, 'job:' || p_job_id,
+ v_bf_journal_line_ref, p_company_id
+ )
+ RETURNING id INTO v_bf_jl_id;
+
+ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;
+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');
+ v_bf_line_item_ids := v_bf_line_item_ids || COALESCE(v_bf_item_ids[i], '');
+
+ -- CR Inventory (Raw Materials or Finished Goods by item)
+ INSERT INTO "journalLine" (
+ "journalId", "accountId", description, amount, quantity,
+ "documentType", "documentId", "documentLineReference",
+ "journalLineReference", "companyId"
+ ) VALUES (
+ v_bf_journal_id, v_material_inventory_account, v_material_inventory_description,
+ -v_material_cogs_total, v_bf_quantities[i],
+ 'Job Consumption', p_job_id, 'job:' || p_job_id,
+ v_bf_journal_line_ref, p_company_id
+ )
+ RETURNING id INTO v_bf_jl_id;
+
+ v_bf_jl_ids := v_bf_jl_ids || v_bf_jl_id;
+ v_bf_posting_group_ids := v_bf_posting_group_ids || COALESCE(v_material_item_posting_group_id, '');
+ v_bf_line_item_ids := v_bf_line_item_ids || COALESCE(v_bf_item_ids[i], '');
+
+ -- Cost ledger entry for consumption
+ INSERT INTO "costLedger" (
+ "itemLedgerType", "costLedgerType", adjustment,
+ "documentType", "documentId", "itemId",
+ quantity, cost, "remainingQuantity", "companyId"
+ ) VALUES (
+ 'Consumption', 'Direct Cost', false,
+ 'Job Consumption', p_job_id, v_bf_item_ids[i],
+ -v_bf_quantities[i], -v_material_cogs_total,
+ 0, p_company_id
+ );
+ END LOOP;
+
+ -- Dimensions for material consumption journal lines
+ IF array_length(v_bf_jl_ids, 1) IS NOT NULL THEN
+ FOR i IN 1..array_length(v_bf_jl_ids, 1)
+ LOOP
+ IF v_bf_posting_group_ids[i] != '' AND v_dimension_item_posting_group IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_bf_jl_ids[i], v_dimension_item_posting_group, v_bf_posting_group_ids[i], p_company_id
+ );
+ END IF;
+
+ IF v_dimension_item IS NOT NULL AND v_bf_line_item_ids[i] != '' THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_bf_jl_ids[i], v_dimension_item, v_bf_line_item_ids[i], p_company_id
+ );
+ END IF;
+
+ IF v_job_location_id IS NOT NULL AND v_dimension_location IS NOT NULL THEN
+ INSERT INTO "journalLineDimension" (
+ "journalLineId", "dimensionId", "valueId", "companyId"
+ ) VALUES (
+ v_bf_jl_ids[i], v_dimension_location, v_job_location_id, p_company_id
+ );
+ END IF;
+ END LOOP;
+ END IF;
+END;
+$function$;
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 3c62ecfabf..b319c31410 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261014164752",
+ "schemaVersion": "20261015122149",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-14T17:39:46.819Z",
+ "exportedAt": "2026-10-15T12:44:43.893Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -479,6 +479,7 @@
"accountingCutoverDate",
"accountingActivatedAt",
"accountingActivatedBy",
+ "requireBackflushStorageUnit",
"leaseIncrementalBorrowingRate",
"leaseShortTermExpedient",
"leaseReminderDays"
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index ad9a7f28dd..d82ded7bb8 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -60,6 +60,10 @@ msgstr "(auf mehr als ein Carbon-Konto abgebildet)"
msgid "(not an Equity posting account)"
msgstr "(kein Eigenkapital-Buchungskonto)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# Aktive Methode hat Materialien ohne Entnahme-Lagereinheit} other {# Aktive Methoden haben Materialien ohne Entnahme-Lagereinheit}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# blockierter Datensatz} other {# blockierte Datensätze}}"
@@ -1107,6 +1111,9 @@ msgstr "Ein Werkstoff ist ein physischer Artikel, der zur Herstellung eines Teil
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "Ein Prüfmittel (Schieblehre, Schraublehre, Rachenlehre, CMM), das als Datensatz erfasst und an einen wiederkehrenden Kalibrierplan gebunden ist."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "Eine Methodenversion benötigt eine Entnahme-Lagereinheit bei jedem Material, bevor die Methode Aktiv werden kann."
+
msgid "A name is required to save a view"
msgstr "Ein Name ist erforderlich, um eine Ansicht zu speichern"
@@ -1428,6 +1435,9 @@ msgstr "Der Status einer Lieferung ändert sich"
msgid "A shipment's tracking number changes"
msgstr "Die Verfolgungsnummer einer Lieferung ändert sich"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "Eine Lagereinheit mit unzureichendem Bestand weicht auf eine andere Lagereinheit mit Bestand aus."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "Ein kurzfristiges Leasing kann 12 Monate ab Beginn nicht überschreiten. Beenden Sie es und geben Sie die Verlängerung als neues Leasing ein."
@@ -3822,6 +3832,9 @@ msgstr "Zurück zur Rückverfolgbarkeit"
msgid "Backflush"
msgstr "Retrograde Entnahme"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Retrograde Entnahme für jedes Material nur aus der Lagereinheit dieser Position durchführen und den Arbeitsgang oder Fertigungsauftrag stoppen, wenn die Lagereinheit nicht genug Bestand hat."
+
msgid "Background"
msgstr "Hintergrund"
@@ -13447,6 +13460,9 @@ msgstr "Fehlende Arbeitsgänge"
msgid "Missing Shipping Costs"
msgstr "Fehlende Versandkosten"
+msgid "Missing Storage Units"
+msgstr "Fehlende Lagereinheiten"
+
msgid "Missing Suppliers"
msgstr "Fehlende Lieferanten"
@@ -20239,6 +20255,10 @@ msgstr "Sitzung gesperrt"
msgid "Set a customer on this return to add from a shipment."
msgstr "Legen Sie einen Kunden für diese Rücksendung fest, um aus einer Lieferung hinzuzufügen."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "Entnahme-Lagereinheit für {0} festlegen"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Wählen Sie einen Lieferanten für diese Rückgabe aus, um Positionen von einem Wareneingang hinzuzufügen."
@@ -21296,6 +21316,18 @@ msgstr "Lineare Abschreibung von Finanzierungslease-Nutzungsrechts-Vermögenswer
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "Lineare Leasingkosten von Betriebsleasings und Zahlungen von kurzfristigen Leasings"
+msgid "Strict Backflush"
+msgstr "Strikte Retrograde Entnahme"
+
+msgid "Strict backflush is off"
+msgstr "Strikte Retrograde Entnahme ist deaktiviert"
+
+msgid "Strict backflush is on"
+msgstr "Strikte Retrograde Entnahme ist aktiviert"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "Strikte Retrograde Entnahme ist aktiviert. Legen Sie eine Entnahme-Lagereinheit für diese Materialien fest, bevor Sie freigeben:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 5aa6d9b318..ca697136a1 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -60,6 +60,10 @@ msgstr "(mapped to more than one Carbon account)"
msgid "(not an Equity posting account)"
msgstr "(not an Equity posting account)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# blocking record} other {# blocking records}}"
@@ -1107,6 +1111,9 @@ msgstr "A material is a physical item used to make a part that can be used acros
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+
msgid "A name is required to save a view"
msgstr "A name is required to save a view"
@@ -1428,6 +1435,9 @@ msgstr "A shipment's status changes"
msgid "A shipment's tracking number changes"
msgstr "A shipment's tracking number changes"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "A short storage unit falls back to another storage unit with stock."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
@@ -3822,6 +3832,9 @@ msgstr "Back to traceability"
msgid "Backflush"
msgstr "Backflush"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+
msgid "Background"
msgstr "Background"
@@ -13447,6 +13460,9 @@ msgstr "Missing Operations"
msgid "Missing Shipping Costs"
msgstr "Missing Shipping Costs"
+msgid "Missing Storage Units"
+msgstr "Missing Storage Units"
+
msgid "Missing Suppliers"
msgstr "Missing Suppliers"
@@ -20239,6 +20255,10 @@ msgstr "Session locked"
msgid "Set a customer on this return to add from a shipment."
msgstr "Set a customer on this return to add from a shipment."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "set a Pull From storage unit on {0}"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Set a supplier on this return to add from a receipt."
@@ -21296,6 +21316,18 @@ msgstr "Straight-line amortization of finance lease right-of-use assets"
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "Straight-line lease cost of operating leases, and the payments of short-term leases"
+msgid "Strict Backflush"
+msgstr "Strict Backflush"
+
+msgid "Strict backflush is off"
+msgstr "Strict backflush is off"
+
+msgid "Strict backflush is on"
+msgstr "Strict backflush is on"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index f20fdec8db..a7e8a81de7 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -60,6 +60,10 @@ msgstr "(asignado a más de una cuenta de Carbon)"
msgid "(not an Equity posting account)"
msgstr "(no es una cuenta de Contabilización de Patrimonio)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# método activo tiene materiales sin Extraer de} other {# métodos activos tienen materiales sin Extraer de}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# registro bloqueante} other {# registros bloqueantes}}"
@@ -1107,6 +1111,9 @@ msgstr "Un material es un artículo físico utilizado para hacer una pieza que s
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "Un instrumento de medición (calibrador, micrómetro, calibrador de pasadores, MMC) rastreado como un registro y sujeto a un cronograma de calibración recurrente."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "Una versión del método necesita una unidad de almacenamiento de origen en cada material antes de que pueda activarse."
+
msgid "A name is required to save a view"
msgstr "Se requiere un nombre para guardar una vista"
@@ -1428,6 +1435,9 @@ msgstr "El estado de un envío cambia"
msgid "A shipment's tracking number changes"
msgstr "El número de seguimiento de un envío cambia"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "Una unidad de almacenamiento con existencias insuficientes recurre a otra unidad de almacenamiento con existencias."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "Un arrendamiento a corto plazo no puede extenderse más allá de 12 meses desde el comienzo. Finalícelo e ingrese la extensión como un nuevo arrendamiento."
@@ -3822,6 +3832,9 @@ msgstr "Volver a trazabilidad"
msgid "Backflush"
msgstr "Consumo retroactivo"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Realice el consumo retroactivo de cada material solo desde la unidad de almacenamiento en su línea de material y detenga la operación u orden de trabajo cuando esa unidad de almacenamiento no tenga suficientes existencias."
+
msgid "Background"
msgstr "Fondo"
@@ -13447,6 +13460,9 @@ msgstr "Operaciones Faltantes"
msgid "Missing Shipping Costs"
msgstr "Costos de envío faltantes"
+msgid "Missing Storage Units"
+msgstr "Unidades de almacenamiento faltantes"
+
msgid "Missing Suppliers"
msgstr "Proveedores Faltantes"
@@ -20239,6 +20255,10 @@ msgstr "Sesión bloqueada"
msgid "Set a customer on this return to add from a shipment."
msgstr "Establezca un cliente en esta devolución para agregar desde un envío."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "Configurar una unidad de almacenamiento de origen en {0}"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Establecer un proveedor en esta devolución para agregar desde una recepción."
@@ -21296,6 +21316,18 @@ msgstr "Amortización lineal de activos de derecho de uso de arrendamiento finan
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "Costo de arrendamiento lineal de arrendamientos operativos y los pagos de arrendamientos a corto plazo"
+msgid "Strict Backflush"
+msgstr "Consumo retroactivo estricto"
+
+msgid "Strict backflush is off"
+msgstr "Consumo retroactivo estricto está desactivado"
+
+msgid "Strict backflush is on"
+msgstr "Consumo retroactivo estricto está activado"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "Consumo retroactivo estricto está activado. Configure una unidad de almacenamiento de origen en estos materiales antes de liberar:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 7cc54695b4..874575f6f6 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -60,6 +60,10 @@ msgstr "(Associé à plusieurs comptes Carbon)"
msgid "(not an Equity posting account)"
msgstr "(pas un compte de comptabilisation de capitaux propres)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# méthode active a des matières sans unité de prélèvement} other {# méthodes actives ont des matières sans unité de prélèvement}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# enregistrement bloquant} other {# enregistrements bloquants}}"
@@ -1107,6 +1111,9 @@ msgstr "Une matière est un article physique utilisé pour fabriquer une pièce
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "Un instrument de mesure (pied à coulisse, micromètre, pige, MMT) suivi en tant qu'enregistrement et soumis à un calendrier d'étalonnage récurrent."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "Une version de méthode a besoin d'une unité de stockage de prélèvement pour chaque matière prélevée avant de pouvoir être rendue active."
+
msgid "A name is required to save a view"
msgstr "Un nom est requis pour enregistrer une vue"
@@ -1428,6 +1435,9 @@ msgstr "Le statut d'une expédition change"
msgid "A shipment's tracking number changes"
msgstr "Le numéro de suivi d'une expédition change"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "Une unité de stockage insuffisante bascule vers une autre unité de stockage ayant du stock."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "Une location à court terme ne peut pas s'étendre au-delà de 12 mois à compter de sa date de début. Mettez-la fin et saisissez l'extension en tant que nouvelle location."
@@ -3822,6 +3832,9 @@ msgstr "Retour à la traçabilité"
msgid "Backflush"
msgstr "Post-consommation"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Post-consommer chaque matière uniquement depuis l'unité de stockage de sa ligne de matière, et arrêter l'opération ou l'ordre de fabrication quand cette unité de stockage n'a pas assez de stock."
+
msgid "Background"
msgstr "Arrière-plan"
@@ -13447,6 +13460,9 @@ msgstr "Opérations manquantes"
msgid "Missing Shipping Costs"
msgstr "Frais de port manquants"
+msgid "Missing Storage Units"
+msgstr "Unités de stockage manquantes"
+
msgid "Missing Suppliers"
msgstr "Fournisseurs manquants"
@@ -20239,6 +20255,10 @@ msgstr "Session verrouillée"
msgid "Set a customer on this return to add from a shipment."
msgstr "Définissez un client sur ce retour pour ajouter à partir d'une expédition."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "Définir une unité de stockage de prélèvement sur {0}"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Définir un fournisseur sur ce retour pour ajouter à partir d'une réception."
@@ -21296,6 +21316,18 @@ msgstr "Amortissement linéaire des droits d'utilisation pour baux de financemen
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "Charge de bail linéaire des baux d'exploitation, et les paiements des baux à court terme"
+msgid "Strict Backflush"
+msgstr "Post-consommation stricte"
+
+msgid "Strict backflush is off"
+msgstr "Post-consommation stricte désactivée"
+
+msgid "Strict backflush is on"
+msgstr "Post-consommation stricte activée"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "La post-consommation stricte est activée. Définir une unité de stockage de prélèvement sur ces matières avant le lancement :"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 69f896a7f9..387575b774 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -60,6 +60,10 @@ msgstr "(एक से अधिक Carbon खातों में मैप
msgid "(not an Equity posting account)"
msgstr "(इक्विटी पोस्टिंग खाता नहीं है)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# सक्रिय विधि में खींचने की भंडारण इकाई के बिना सामग्री है} other {# सक्रिय विधियों में खींचने की भंडारण इकाई के बिना सामग्री है}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# अवरोधक रिकॉर्ड} other {# अवरोधक रिकॉर्डें}}"
@@ -1107,6 +1111,9 @@ msgstr "एक सामग्री एक भौतिक आइटम है
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "एक माप उपकरण (कैलिपर, माइक्रोमीटर, पिन गेज, CMM) जिसे एक रिकॉर्ड के रूप में ट्रैक किया जाता है और एक आवर्ती अंशांकन शेड्यूल का पालन किया जाता है।"
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "एक विधि संस्करण को सक्रिय बनाने से पहले प्रत्येक खींची गई सामग्री पर एक खींचने की भंडारण इकाई की आवश्यकता होती है।"
+
msgid "A name is required to save a view"
msgstr "एक दृश्य को सहेजने के लिए एक नाम आवश्यक है"
@@ -1428,6 +1435,9 @@ msgstr "किसी शिपमेंट की स्थिति में
msgid "A shipment's tracking number changes"
msgstr "एक शिपमेंट का ट्रैकिंग नंबर बदल जाता है"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "एक अपर्याप्त भंडारण इकाई दूसरी भंडारण इकाई पर वापस आती है जिसमें स्टॉक है।"
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "एक अल्पकालिक संपत्ति शुरुआत से 12 महीने के बाद नहीं चल सकती। इसे समाप्त करें और विस्तार को एक नई पट्टा के रूप में दर्ज करें।"
@@ -3822,6 +3832,9 @@ msgstr "ट्रेसेबिलिटी पर वापस जाएं"
msgid "Backflush"
msgstr "बैकफ्लश"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "प्रत्येक सामग्री को केवल इसकी सामग्री पंक्ति पर भंडारण इकाई से बैकफ्लश करें, और जब वह भंडारण इकाई में पर्याप्त स्टॉक नहीं है तो ऑपरेशन या जॉब को रोकें।"
+
msgid "Background"
msgstr "पृष्ठभूमि"
@@ -13447,6 +13460,9 @@ msgstr "ऑपरेशन गायब हैं"
msgid "Missing Shipping Costs"
msgstr "शिपिंग लागत अनुपलब्ध"
+msgid "Missing Storage Units"
+msgstr "लापता भंडारण इकाइयाँ"
+
msgid "Missing Suppliers"
msgstr "आपूर्तिकर्ता गायब हैं"
@@ -20239,6 +20255,10 @@ msgstr "सत्र लॉक किया गया"
msgid "Set a customer on this return to add from a shipment."
msgstr "शिपमेंट से जोड़ने के लिए इस वापसी पर एक ग्राहक सेट करें।"
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "खींचने की भंडारण इकाई को {0} पर सेट करें"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "प्राप्ति से जोड़ने के लिए इस रिटर्न पर एक आपूर्तिकर्ता सेट करें।"
@@ -21296,6 +21316,18 @@ msgstr "वित्त पट्टा उपयोग के अधिका
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "परिचालन पट्टा की सरल-रेखा पट्टा लागत, और अल्पकालिक पट्टा का भुगतान"
+msgid "Strict Backflush"
+msgstr "सख्त बैकफ्लश"
+
+msgid "Strict backflush is off"
+msgstr "सख्त बैकफ्लश बंद है"
+
+msgid "Strict backflush is on"
+msgstr "सख्त बैकफ्लश चालू है"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "सख्त बैकफ्लश चालू है। इन सामग्रियों पर खींचने की भंडारण इकाई सेट करें रिलीज़ करने से पहले:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index ab89e3b08f..01686810b1 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -60,6 +60,10 @@ msgstr "(associato a più di un account Carbon)"
msgid "(not an Equity posting account)"
msgstr "(non un account di registrazione Patrimonio netto)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# Metodo Attivo ha Materiali senza Prelevamento da} other {# Metodi Attivi hanno Materiali senza Prelevamento da}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# record bloccante} other {# record bloccanti}}"
@@ -1107,6 +1111,9 @@ msgstr "Un materiale è un articolo fisico utilizzato per realizzare un componen
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "Uno strumento di misura (calibro, micrometro, calibro di spessore, CMM) tracciato come un record e sottoposto a un programma di taratura ricorrente."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "Una versione di Metodo richiede un'Unità di stoccaggio di Prelevamento da su ogni materiale prima che possa essere resa Attiva."
+
msgid "A name is required to save a view"
msgstr "Un nome è obbligatorio per salvare una vista"
@@ -1428,6 +1435,9 @@ msgstr "Lo stato della spedizione cambia"
msgid "A shipment's tracking number changes"
msgstr "Il numero di tracciamento di una spedizione cambia"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "Un'Unità di stoccaggio insufficiente ricorre a un'altra Unità di stoccaggio con Giacenza."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "Una locazione a breve termine non può durare più di 12 mesi dalla data di inizio. Terminarla e inserire l'estensione come una nuova locazione."
@@ -3822,6 +3832,9 @@ msgstr "Torna alla tracciabilità"
msgid "Backflush"
msgstr "Backflush"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Consuma con Backflush ogni materiale solo dall'Unità di stoccaggio sulla sua riga e arresta l'Operazione o l'Ordine di produzione quando quell'Unità di stoccaggio non ha Giacenza sufficiente."
+
msgid "Background"
msgstr "Sfondo"
@@ -13447,6 +13460,9 @@ msgstr "Operazioni Mancanti"
msgid "Missing Shipping Costs"
msgstr "Spese di spedizione mancanti"
+msgid "Missing Storage Units"
+msgstr "Unità di stoccaggio mancanti"
+
msgid "Missing Suppliers"
msgstr "Fornitori Mancanti"
@@ -20239,6 +20255,10 @@ msgstr "Sessione bloccata"
msgid "Set a customer on this return to add from a shipment."
msgstr "Imposta un cliente su questo reso per aggiungere da una spedizione."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "Imposta un'Unità di stoccaggio di Prelevamento da su {0}"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Imposta un fornitore su questo reso per aggiungere da un'entrata merci."
@@ -21296,6 +21316,18 @@ msgstr "Ammortamento a quote costanti dei cespiti di diritto d'uso del lease fin
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "Costo del lease a quote costanti dei lease operativi e i pagamenti dei lease a breve termine"
+msgid "Strict Backflush"
+msgstr "Backflush rigoroso"
+
+msgid "Strict backflush is off"
+msgstr "Backflush rigoroso disattivato"
+
+msgid "Strict backflush is on"
+msgstr "Backflush rigoroso attivato"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "Backflush rigoroso è attivato. Imposta un'Unità di stoccaggio di Prelevamento da su questi materiali prima di rilasciare:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index cb0bd161f8..8287843db8 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -60,6 +60,10 @@ msgstr "(複数のCarbonアカウントにマップされています)"
msgid "(not an Equity posting account)"
msgstr "(純資産転記勘定科目ではありません)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# 個の有効な製法に「抽出元」未設定の材料があります} other {# 個の有効な製法に「抽出元」未設定の材料があります}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# ブロック中のレコード} other {# ブロック中のレコード}}"
@@ -1107,6 +1111,9 @@ msgstr "材料は部品を製造するために使用される物理的品目で
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "キャリパー、マイクロメーター、ピンゲージ、CMM などの測定器で、レコードとして追跡され、定期的な校正スケジュールに従います。"
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "製法バージョンを有効にする前に、各抽出材料に抽出元保管ユニットを設定する必要があります。"
+
msgid "A name is required to save a view"
msgstr "ビューを保存するには名前が必要です"
@@ -1428,6 +1435,9 @@ msgstr "出荷のステータスが変更される"
msgid "A shipment's tracking number changes"
msgstr "出荷の追跡番号が変更される"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "在庫が不足している保管ユニットは、在庫がある別の保管ユニットにフォールバックします。"
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "短期資産はcommencement(開始日)から12ヶ月を超えて実行することはできません。終了してから、延長を新しいリースとして入力してください。"
@@ -3822,6 +3832,9 @@ msgstr "トレーサビリティに戻る"
msgid "Backflush"
msgstr "バックフラッシュ"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "各材料をその材料明細上の保管ユニットからのみバックフラッシュし、その保管ユニットに十分な在庫がない場合は工程または製造指図を停止します。"
+
msgid "Background"
msgstr "背景"
@@ -13447,6 +13460,9 @@ msgstr "工程が不足しています"
msgid "Missing Shipping Costs"
msgstr "送料が不足しています"
+msgid "Missing Storage Units"
+msgstr "保管ユニット未設定"
+
msgid "Missing Suppliers"
msgstr "仕入先が不足しています"
@@ -20239,6 +20255,10 @@ msgstr "セッションがロック中"
msgid "Set a customer on this return to add from a shipment."
msgstr "出荷から追加するにはこのリターンに得意先を設定してください。"
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "{0} に抽出元保管ユニットを設定する"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "この返品に仕入先を設定して入荷から追加"
@@ -21296,6 +21316,18 @@ msgstr "ファイナンスリース使用権資産の定額償却"
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "運用リースの定額リース費用および短期リースの支払"
+msgid "Strict Backflush"
+msgstr "厳密なバックフラッシュ"
+
+msgid "Strict backflush is off"
+msgstr "厳密なバックフラッシュは無効です"
+
+msgid "Strict backflush is on"
+msgstr "厳密なバックフラッシュは有効です"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "厳密なバックフラッシュが有効です。これらの材料をリリースする前に抽出元保管ユニットを設定してください:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 4a6296690f..6dbc78aad3 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -60,6 +60,10 @@ msgstr "(하나 이상의 Carbon 계정에 매핑됨)"
msgid "(not an Equity posting account)"
msgstr "(자본 전기 계정이 아님)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# 활성 방법에 Pull From 보관 단위가 없는 자재가 있습니다} other {# 활성 방법에 Pull From 보관 단위가 없는 자재가 있습니다}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# 차단 레코드} other {# 차단 레코드}}"
@@ -1107,6 +1111,9 @@ msgstr "자재는 부품을 만드는 데 사용되는 물리적 품목으로
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "계측기(캘리퍼, 마이크로미터, 핀 게이지, CMM)로 기록으로 추적되며 반복되는 교정 일정을 유지합니다."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "방법 버전을 활성화하려면 각 자재에 Pull From 보관 단위가 설정되어야 합니다."
+
msgid "A name is required to save a view"
msgstr "보기를 저장하려면 이름이 필요합니다"
@@ -1428,6 +1435,9 @@ msgstr "출하의 상태가 변경됨"
msgid "A shipment's tracking number changes"
msgstr "출하의 추적 번호가 변경됨"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "보관 단위의 재고가 부족하면 재고가 있는 다른 보관 단위로 전환됩니다."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "단기 자산은 개시일로부터 12개월을 초과하여 운영할 수 없습니다. 종료하고 연장을 새로운 리스로 입력합니다."
@@ -3822,6 +3832,9 @@ msgstr "추적성으로 돌아가기"
msgid "Backflush"
msgstr "백플러시"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "각 자재를 자재 라인의 보관 단위에서만 백플러시하고, 해당 보관 단위의 재고가 부족할 때 공정 또는 작업 지시를 중지합니다."
+
msgid "Background"
msgstr "배경"
@@ -13447,6 +13460,9 @@ msgstr "누락된 공정작업"
msgid "Missing Shipping Costs"
msgstr "누락된 운송비"
+msgid "Missing Storage Units"
+msgstr "보관 단위 누락"
+
msgid "Missing Suppliers"
msgstr "누락된 공급업체"
@@ -20239,6 +20255,10 @@ msgstr "세션 잠김"
msgid "Set a customer on this return to add from a shipment."
msgstr "출하에서 추가할 고객을 이 반품에 설정하세요."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "{0}에 Pull From 보관 단위를 설정합니다"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "이 반품에 공급업체를 지정하여 입고에서 추가하세요."
@@ -21296,6 +21316,18 @@ msgstr "금융 리스 사용권 자산의 정액법 상각"
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "운영 리스의 정액법 리스 원가 및 단기 리스의 지불"
+msgid "Strict Backflush"
+msgstr "엄격한 백플러시"
+
+msgid "Strict backflush is off"
+msgstr "엄격한 백플러시가 꺼져 있습니다"
+
+msgid "Strict backflush is on"
+msgstr "엄격한 백플러시가 켜져 있습니다"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "엄격한 백플러시가 켜져 있습니다. 릴리스 전에 이 자재들에 Pull From 보관 단위를 설정하세요:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index a4b23d5e06..5366c66fac 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -60,6 +60,10 @@ msgstr "(zmapowane na więcej niż jedno konto Carbon)"
msgid "(not an Equity posting account)"
msgstr "(nie jest kontem Kapitału własnego do księgowania)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# aktywna metoda ma materiały bez magazynu pobrania} other {# aktywne metody mają materiały bez magazynu pobrania}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# rekord blokujący} other {# rekordy blokujące}}"
@@ -1107,6 +1111,9 @@ msgstr "Materiał to przedmiot fizyczny używany do wykonania części, który m
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "Przyrząd pomiarowy (suwmiarka, mikrometr, czop wzorcujący, CMM) śledzony jako rekord i poddawany cyklicznym okresom wzorcowania."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "Wersja metody wymaga ustawienia jednostki magazynowej do poboru dla każdego materiału do pobrania, zanim będzie można ją ustawić jako Aktywną."
+
msgid "A name is required to save a view"
msgstr "Nazwa jest wymagana, aby zapisać widok"
@@ -1428,6 +1435,9 @@ msgstr "Status wysyłki zmienia się"
msgid "A shipment's tracking number changes"
msgstr "Zmiana numeru śledzenia wysyłki"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "Jednostka magazynowa z niewystarczającym zapasem przechodzi na inną jednostkę magazynową."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "Zasób krótkoterminowy nie może trwać dłużej niż 12 miesięcy od daty rozpoczęcia. Zakończ go i wprowadź przedłużenie jako nową umowę najmu."
@@ -3822,6 +3832,9 @@ msgstr "Powrót do identyfikowalności"
msgid "Backflush"
msgstr "Pobranie wsteczne"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Pobieranie wsteczne każdego materiału wyłącznie z jednostki magazynowej na jego pozycji materiału oraz zatrzymanie operacji lub zlecenia produkcyjnego, gdy ta jednostka magazynowa nie ma wystarczającego zapasu."
+
msgid "Background"
msgstr "Tło"
@@ -13447,6 +13460,9 @@ msgstr "Brakujące operacje"
msgid "Missing Shipping Costs"
msgstr "Brakujące koszty wysyłki"
+msgid "Missing Storage Units"
+msgstr "Brakujące jednostki magazynowe"
+
msgid "Missing Suppliers"
msgstr "Brakujący dostawcy"
@@ -20239,6 +20255,10 @@ msgstr "Sesja zablokowana"
msgid "Set a customer on this return to add from a shipment."
msgstr "Ustaw klienta na tym zwrocie, aby dodać z wysyłki."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "ustaw jednostkę magazynową do poboru dla {0}"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Ustaw dostawcę w tym zwrocie, aby dodać z przyjęcia."
@@ -21296,6 +21316,18 @@ msgstr "Amortyzacja równomierna prawa do użytkowania środka trwałego w leasi
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "Koszt leasingu równomierna leasingów operacyjnych i płatności leasingów krótkoterminowych"
+msgid "Strict Backflush"
+msgstr "Ścisłe pobranie wsteczne"
+
+msgid "Strict backflush is off"
+msgstr "Ścisłe pobranie wsteczne jest wyłączone"
+
+msgid "Strict backflush is on"
+msgstr "Ścisłe pobranie wsteczne jest włączone"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "Pobranie wsteczne ze ścisłą kontrolą jest włączone. Ustaw jednostkę magazynową do poboru na tych materiałach przed wydaniem:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 336b091809..85b1ed4308 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -60,6 +60,10 @@ msgstr "(mapeado para mais de uma conta Carbon)"
msgid "(not an Equity posting account)"
msgstr "(não é uma conta de contabilização de Patrimônio líquido)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# método ativo possui materiais sem unidade de armazenamento de origem} other {# métodos ativos possuem materiais sem unidade de armazenamento de origem}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# registro bloqueador} other {# registros bloqueadores}}"
@@ -1107,6 +1111,9 @@ msgstr "Um material é um item físico usado para fabricar uma peça que pode se
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "Um instrumento de medição (paquímetro, micrômetro, medidor de pino, CMM) rastreado como um registro e mantido em um cronograma de calibração recorrente."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "Uma versão do método precisa de uma unidade de armazenamento de origem em cada material obtido antes de poder ser ativada."
+
msgid "A name is required to save a view"
msgstr "Um nome é necessário para salvar uma visualização"
@@ -1428,6 +1435,9 @@ msgstr "O status da remessa muda"
msgid "A shipment's tracking number changes"
msgstr "O número de rastreamento de uma remessa muda"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "Uma unidade de armazenamento com estoque insuficiente volta para outra unidade de armazenamento com estoque."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "Um ativo de curto prazo não pode estender-se além de 12 meses a partir do início. Termine-o e insira a extensão como um novo arrendamento."
@@ -3822,6 +3832,9 @@ msgstr "Voltar para rastreabilidade"
msgid "Backflush"
msgstr "Baixa automática"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Realizar a baixa automática de cada material apenas da unidade de armazenamento na sua linha de material, e parar a operação ou ordem de produção quando essa unidade de armazenamento não tiver estoque suficiente."
+
msgid "Background"
msgstr "Fundo"
@@ -13447,6 +13460,9 @@ msgstr "Operações Ausentes"
msgid "Missing Shipping Costs"
msgstr "Fretes ausentes"
+msgid "Missing Storage Units"
+msgstr "Unidades de Armazenamento Ausentes"
+
msgid "Missing Suppliers"
msgstr "Fornecedores Ausentes"
@@ -20239,6 +20255,10 @@ msgstr "Sessão bloqueada"
msgid "Set a customer on this return to add from a shipment."
msgstr "Defina um cliente nesta devolução para adicionar de uma remessa."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "definir uma unidade de armazenamento de origem em {0}"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Defina um fornecedor nesta devolução para adicionar de um recebimento."
@@ -21296,6 +21316,18 @@ msgstr "Amortização linear de ativos de direito de uso de arrendamento finance
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "Custo de aluguel linear de aluguéis operacionais e pagamentos de aluguéis de curto prazo"
+msgid "Strict Backflush"
+msgstr "Baixa Automática Rigorosa"
+
+msgid "Strict backflush is off"
+msgstr "A baixa automática rigorosa está desativada"
+
+msgid "Strict backflush is on"
+msgstr "A baixa automática rigorosa está ativada"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "A baixa automática rigorosa está ativada. Defina uma unidade de armazenamento de origem para esses materiais antes de liberar:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 2ca5334d31..246fa7dac1 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -60,6 +60,10 @@ msgstr "(сопоставлено с несколькими счетами Carbo
msgid "(not an Equity posting account)"
msgstr "(не счет проведения собственного капитала)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# активный метод имеет материалы без места отпуска} other {# активные методы имеют материалы без места отпуска}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# блокирующая запись} other {# блокирующие записи}}"
@@ -1107,6 +1111,9 @@ msgstr "Материал — это физический элемент, при
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "Средство измерения (кронциркуль, микрометр, щуп, CMM) отслеживаемое как запись и регулярно проходящее калибровку по графику."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "Версия метода требует установки единицы хранения для получения на каждом материале перед тем, как её можно сделать активной."
+
msgid "A name is required to save a view"
msgstr "Требуется имя для сохранения представления"
@@ -1428,6 +1435,9 @@ msgstr "Статус отгрузки изменился"
msgid "A shipment's tracking number changes"
msgstr "Номер отслеживания отгрузки изменился"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "Единица хранения с недостаточным запасом переходит на другую единицу хранения с наличием."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "Краткосрочный актив не может длиться более 12 месяцев с момента начала. Завершите его и введите продление как новую аренду."
@@ -3822,6 +3832,9 @@ msgstr "Вернуться к прослеживаемости"
msgid "Backflush"
msgstr "Ретроградное списание"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Ретроградное списание выполняется только из единицы хранения, указанной в строке материала, с остановкой операции или производственного заказа при недостаточном запасе."
+
msgid "Background"
msgstr "Фон"
@@ -13447,6 +13460,9 @@ msgstr "Отсутствуют операции"
msgid "Missing Shipping Costs"
msgstr "Отсутствующие стоимости доставки"
+msgid "Missing Storage Units"
+msgstr "Отсутствующие единицы хранения"
+
msgid "Missing Suppliers"
msgstr "Отсутствуют поставщики"
@@ -20239,6 +20255,10 @@ msgstr "Сеанс заблокирован"
msgid "Set a customer on this return to add from a shipment."
msgstr "Укажите покупателя для этого возврата, чтобы добавить из отгрузки."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "установить единицу хранения для получения на {0}"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Установите поставщика для этого возврата, чтобы добавить из поступления."
@@ -21296,6 +21316,18 @@ msgstr "Линейная амортизация активов прав поль
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "Линейная себестоимость операционного лизинга и платежи краткосрочного лизинга"
+msgid "Strict Backflush"
+msgstr "Строгое ретроградное списание"
+
+msgid "Strict backflush is off"
+msgstr "строгое ретроградное списание отключено"
+
+msgid "Strict backflush is on"
+msgstr "строгое ретроградное списание включено"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "Включено строгое ретроградное списание. Установите единицу хранения для получения на эти материалы перед отпуском:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index b4ef89f070..cf1d92414f 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -60,6 +60,10 @@ msgstr "(birden fazla Carbon hesabına eşleştirildi)"
msgid "(not an Equity posting account)"
msgstr "(Özkaynak muhasebeleştirme hesabı değildir)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {# aktif yöntemde Çekilecek Depo olmayan malzeme vardır} other {# aktif yöntemde Çekilecek Depo olmayan malzemeler vardır}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# engelleme kaydı} other {# engelleme kaydı}}"
@@ -1107,6 +1111,9 @@ msgstr "Malzeme, bir Parça yapmak için kullanılan ve birden fazla İş emirle
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "Ölçüm aleti (kumpas, mikrometre, pin ölçüm aleti, CMM) bir kayıt olarak izlenen ve yinelenen bir kalibrasyon çizelgesine tabi tutulan."
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "Bir yöntem sürümü, aktif hale gelmeden önce her çekilen malzeme için çekilecek bir depolama birimine ihtiyaç duyar."
+
msgid "A name is required to save a view"
msgstr "Bir görünüm kaydetmek için bir isim gereklidir"
@@ -1428,6 +1435,9 @@ msgstr "Sevkiyatın durumu değişti"
msgid "A shipment's tracking number changes"
msgstr "Bir sevkiyatın takip numarası değişti"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "Yetersiz stoklu bir depolama birimi stok içeren başka bir depolama birimine geri döner."
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "Kısa vadeli kıymet başlangıcından 12 aydan sonra devam edemez. Bunu bitirin ve uzantıyı yeni bir kiralama olarak girin."
@@ -3822,6 +3832,9 @@ msgstr "İzlenebilirliğe geri dön"
msgid "Backflush"
msgstr "Geriye dönük tüketim"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "Her malzemeyi yalnızca malzeme satırındaki depolama biriminden geriye dönük tüket, ve bu depolama birimi yeterli stoka sahip olmadığında operasyonu veya iş emrini durdur."
+
msgid "Background"
msgstr "Arka plan"
@@ -13447,6 +13460,9 @@ msgstr "Eksik operasyonlar"
msgid "Missing Shipping Costs"
msgstr "Eksik nakliye bedelleri"
+msgid "Missing Storage Units"
+msgstr "Eksik Depolama Birimleri"
+
msgid "Missing Suppliers"
msgstr "Tedarikçi Eksikleri"
@@ -20239,6 +20255,10 @@ msgstr "Oturum Kilitli"
msgid "Set a customer on this return to add from a shipment."
msgstr "Sevkiyattan eklemek için bu iade işlemine bir müşteri belirleyin."
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "{0} için çekilecek bir depolama birimi ayarla"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "Mal kabulünden eklemek için bu iade kaydında bir tedarikçi belirleyin."
@@ -21296,6 +21316,18 @@ msgstr "Finansal kira kullanım hakkı varlıklarının doğrusal amortismanı"
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "İşletme kiralarının doğrusal kira gideri ve kısa vadeli kiralar ödemeleri"
+msgid "Strict Backflush"
+msgstr "Sıkı Geriye Dönük Tüketim"
+
+msgid "Strict backflush is off"
+msgstr "Sıkı geriye dönük tüketim kapalı"
+
+msgid "Strict backflush is on"
+msgstr "Sıkı geriye dönük tüketim açık"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "Kesin geriye dönük tüketim açık. Bu malzemeler için çekilecek bir depolama birimi serbest bırakmadan önce ayarla:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 4e1ebebb5c..7467dc1d09 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -60,6 +60,10 @@ msgstr "(映射到多个 Carbon 账户)"
msgid "(not an Equity posting account)"
msgstr "(非所有者权益过账账户)"
+#. placeholder {0}: methodsMissingPullFrom.count
+msgid "{0, plural, one {# active method has materials with no Pull From} other {# active methods have materials with no Pull From}}"
+msgstr "{0, plural, one {#个启用的方法包含没有取货存储单元的物料} other {#个启用的方法包含没有取货存储单元的物料}}"
+
#. placeholder {0}: check.count
msgid "{0, plural, one {# blocking record} other {# blocking records}}"
msgstr "{0, plural, one {# 条阻止记录} other {# 条阻止记录}}"
@@ -1107,6 +1111,9 @@ msgstr "原材料是用于制造零件的物质物品,可跨多个工单使用
msgid "A measurement instrument (caliper, micrometer, pin gauge, CMM) tracked as a record and held to a recurring calibration schedule."
msgstr "一个测量仪器(游标卡尺、千分尺、塞规、CMM)作为记录进行追踪,并按照周期性校准计划进行维护。"
+msgid "A method version needs a Pull From storage unit on each pulled material before it can be made active."
+msgstr "方法版本需要在每个物料上设置取货存储单元,才能启用。"
+
msgid "A name is required to save a view"
msgstr "需要名称才能保存查看"
@@ -1428,6 +1435,9 @@ msgstr "发货单的状态已更改"
msgid "A shipment's tracking number changes"
msgstr "发货的跟踪号变更"
+msgid "A short storage unit falls back to another storage unit with stock."
+msgstr "当存储单元库存不足时,将使用另一个有库存的存储单元。"
+
msgid "A short-term asset cannot run past 12 months from the commencement. End it and enter the extension as a new lease."
msgstr "短期资产不能超过开始日期后的 12 个月。结束它并将延期作为新租赁输入。"
@@ -3822,6 +3832,9 @@ msgstr "返回可追溯性"
msgid "Backflush"
msgstr "倒冲"
+msgid "Backflush each material only from the storage unit on its material line, and stop the operation or job when that storage unit does not have enough stock."
+msgstr "仅从物料行指定的存储单元倒冲每个物料,当该存储单元库存不足时,停止该工序或工单。"
+
msgid "Background"
msgstr "背景"
@@ -13447,6 +13460,9 @@ msgstr "缺失的工序"
msgid "Missing Shipping Costs"
msgstr "缺少运费"
+msgid "Missing Storage Units"
+msgstr "缺少存储单元"
+
msgid "Missing Suppliers"
msgstr "缺少供应商"
@@ -20239,6 +20255,10 @@ msgstr "会话已锁定"
msgid "Set a customer on this return to add from a shipment."
msgstr "在此退货上设置客户以从发货中添加。"
+#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
+msgid "set a Pull From storage unit on {0}"
+msgstr "为 {0} 设置取货存储单元"
+
msgid "Set a supplier on this return to add from a receipt."
msgstr "为此退货指定供应商以从其收货中添加"
@@ -21296,6 +21316,18 @@ msgstr "融资租赁使用权资产的直线摊销"
msgid "Straight-line lease cost of operating leases, and the payments of short-term leases"
msgstr "经营租赁直线租赁成本和短期租赁付款"
+msgid "Strict Backflush"
+msgstr "严格倒冲"
+
+msgid "Strict backflush is off"
+msgstr "严格倒冲已关闭"
+
+msgid "Strict backflush is on"
+msgstr "严格倒冲已启用"
+
+msgid "Strict backflush is on. Set a Pull From storage unit on these materials before releasing:"
+msgstr "严格倒冲已启用。释放前,请为这些物料设置取货存储单元:"
+
msgid "Stripe"
msgstr "Stripe"
diff --git a/packages/server-functions/src/batch-operations/index.ts b/packages/server-functions/src/batch-operations/index.ts
index b65591f20c..0cb69b0e52 100644
--- a/packages/server-functions/src/batch-operations/index.ts
+++ b/packages/server-functions/src/batch-operations/index.ts
@@ -457,6 +457,23 @@ async function completeBatch(
// inside the transaction: freshly sliced on the first attempt, re-loaded on resume.
let glEvents: { id: string; postedToGL: boolean }[] = [];
+ // Strict backflush: phase 2 issues each member's materials after phase 1 has
+ // committed, so a short storage unit is refused here first, before anything
+ // is written. Each member is checked on its own; two members drawing the
+ // same bin can still fail in phase 2, which leaves the batch resumable.
+ // A no-op when strict backflush is off.
+ const checker = ServerFnContext.system({ db, companyId, userId });
+ for (const m of members) {
+ if (m.quantity <= 0) continue;
+ const check = await issue(checker, {
+ id: m.jobOperationId,
+ type: "jobOperation",
+ quantity: m.quantity,
+ dryRun: true
+ });
+ if (check.error) throw check.error;
+ }
+
await db.transaction().execute(async (trx) => {
const batch = await trx
.selectFrom("jobOperationBatch")
diff --git a/packages/server-functions/src/convert/index.ts b/packages/server-functions/src/convert/index.ts
index a0da0c6e81..bbfc4d7344 100644
--- a/packages/server-functions/src/convert/index.ts
+++ b/packages/server-functions/src/convert/index.ts
@@ -28,6 +28,10 @@ import { z } from "zod";
import { defineServerFn } from "../define-server-fn";
import { NotFoundError } from "../errors";
import getMethod from "../get-method";
+import {
+ assertMethodHasPullFrom,
+ isStrictBackflush
+} from "../lib/strict-backflush";
import { getSupplierPartPriceConverter } from "../lib/supplier-part-currency";
import { ServerFnContext } from "../server-fn-context";
@@ -187,6 +191,10 @@ const convert = defineServerFn({
if (makeMethod.error) throw new Error(makeMethod.error.message);
if (!makeMethod.data) throw new NotFoundError("Make method not found");
+ if (await isStrictBackflush(db, companyId)) {
+ await assertMethodHasPullFrom(db, { makeMethodId, companyId });
+ }
+
const [relatedMakeMethods, draftQuotes, draftJobs] = await inOrder([
() =>
many(db, "makeMethod", {
diff --git a/packages/server-functions/src/issue/index.ts b/packages/server-functions/src/issue/index.ts
index bd760f5901..cf5ef28a10 100644
--- a/packages/server-functions/src/issue/index.ts
+++ b/packages/server-functions/src/issue/index.ts
@@ -73,6 +73,12 @@ import {
getStorageUnitWithHighestQuantity,
updatePickMethodDefaultStorageUnitIfNeeded
} from "../lib/storage-units";
+import {
+ assertBinCovers,
+ binCoverProblem,
+ isStrictBackflush,
+ strictBackflushRefusal
+} from "../lib/strict-backflush";
import reschedule from "../reschedule";
import { ServerFnContext } from "../server-fn-context";
import {
@@ -225,6 +231,9 @@ async function issueJobOperationMaterials(
jobOperationId,
companyId
});
+ const strict = await isStrictBackflush(trx, companyId);
+ // Strict backflush: every material the bins cannot cover, refused together.
+ const strictProblems: string[] = [];
const takenShared: SharedTakes = new Map();
for await (const material of materialsToIssue) {
// Cap the backflush at the material's remaining unissued requirement,
@@ -277,7 +286,33 @@ async function issueJobOperationMaterials(
}
}
- if (remaining > 0) {
+ if (remaining > 0 && strict && itemIdIsTracked.get(material.itemId)) {
+ // Strict backflush: what no pick covered comes from the material's own
+ // storage unit only — no pick-method bin, no fullest bin — and a
+ // missing or short bin refuses the whole completion.
+ const problem = await binCoverProblem(trx, {
+ companyId,
+ itemId: material.itemId,
+ locationId: job.locationId,
+ storageUnitId: material.storageUnitId,
+ quantity: remaining,
+ plannedRows: itemLedgerInserts
+ });
+ if (problem) strictProblems.push(problem);
+ itemLedgerInserts.push({
+ entryType: "Consumption",
+ documentType: "Job Consumption",
+ documentId: jobId,
+ documentLineId: jobOperationId,
+ companyId,
+ itemId: material.itemId,
+ quantity: -remaining,
+ locationId: job.locationId,
+ storageUnitId: material.storageUnitId,
+ postingDate: today,
+ createdBy: userId
+ });
+ } else if (remaining > 0) {
let proposedStorageUnitId = material.storageUnitId;
if (!proposedStorageUnitId) {
@@ -367,6 +402,10 @@ async function issueJobOperationMaterials(
.execute();
}
+ // Nothing above is committed until the transaction ends, so throwing here
+ // rolls back every row this call wrote.
+ if (strictProblems.length > 0) throw strictBackflushRefusal(strictProblems);
+
// Total material cost this call relieved from inventory into WIP — the
// jobOperationScrap case posts its WIP→scrap journal from this figure so a
// second calculateCOGS pass never double-relieves cost layers.
@@ -901,6 +940,9 @@ const logger = getLogger("server-functions", "issue");
type ItemLedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];
+// Thrown at the end of a dry-run transaction so Kysely rolls every write back.
+class DryRunRollback extends Error {}
+
/** Each `type` adds its own fields (`newTrackedEntityId`, `readableId`, …). */
export type IssueResult = { success: boolean; message?: string } & Record<
string,
@@ -922,7 +964,11 @@ export const issueInput = z.discriminatedUnion("type", [
z.object({
type: z.literal("jobOperation"),
quantity: z.number(),
- id: z.string()
+ id: z.string(),
+ // Strict backflush: run the issue and roll it back, so a caller that
+ // records the production quantity first can refuse before it writes
+ // anything. A no-op when strict backflush is off.
+ dryRun: z.boolean().optional()
}),
z.object({
type: z.literal("jobOperationBatchComplete"),
@@ -2021,25 +2067,32 @@ const issue = defineServerFn({
switch (validatedPayload.type) {
case "jobOperation": {
- const { id, companyId, quantity, userId } = validatedPayload;
+ const { id, companyId, quantity, userId, dryRun } = validatedPayload;
+
+ if (dryRun && !(await isStrictBackflush(db, companyId))) break;
const { accountDefaults, dimensionMap } =
await loadConsumeAccountingContext(db, companyId);
- 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
+ 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
+ });
+ if (dryRun) throw new DryRunRollback();
});
- });
+ } catch (err) {
+ if (!(err instanceof DryRunRollback)) throw err;
+ }
break;
}
@@ -3022,6 +3075,24 @@ const issue = defineServerFn({
}
}
if (item?.itemTrackingType === "Inventory" && remaining !== 0) {
+ // Strict backflush: a consuming issue takes what no pick
+ // covered from the material's own storage unit only. A return
+ // keeps the bin chosen above.
+ if (
+ adjustmentType !== "Positive Adjmt." &&
+ remaining > 0 &&
+ (await isStrictBackflush(trx, companyId))
+ ) {
+ storageUnitId = material.storageUnitId;
+ await assertBinCovers(trx, {
+ companyId,
+ itemId: material.itemId,
+ locationId: job?.locationId!,
+ storageUnitId,
+ quantity: remaining,
+ plannedRows: itemLedgerInserts
+ });
+ }
itemLedgerInserts.push({
entryType: "Consumption",
documentType: "Job Consumption",
diff --git a/packages/server-functions/src/lib/strict-backflush.ts b/packages/server-functions/src/lib/strict-backflush.ts
new file mode 100644
index 0000000000..64462a6efd
--- /dev/null
+++ b/packages/server-functions/src/lib/strict-backflush.ts
@@ -0,0 +1,199 @@
+// 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.
+
+// Strict backflush (companySettings.requireBackflushStorageUnit,
+// .ai/specs/2026-10-14-strict-backflush.md): a stocked material is consumed
+// only from its own storage unit, and a missing or short bin refuses the
+// backflush instead of falling back to another bin. The SQL job-completion
+// backflush (`backflush_job_materials`) enforces the same rule.
+
+import type { Database } from "@carbon/database";
+import type { KyselyDatabase as DB } from "@carbon/database/client";
+import {
+ binShortfall,
+ getPullFromLocations,
+ missingPullFromLocations,
+ needsPullFrom,
+ summarizeList
+} from "@carbon/database/strict-backflush";
+import { getLogger } from "@carbon/logger";
+import { round } from "@carbon/utils";
+import { type Kysely, sql } from "kysely";
+import { InvalidInputError, ServerFnError } from "../errors";
+
+const logger = getLogger("server-functions", "strict-backflush");
+
+type LedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];
+
+export async function isStrictBackflush(
+ db: Kysely<DB>,
+ companyId: string
+): Promise<boolean> {
+ const row = await db
+ .selectFrom("companySettings")
+ .where("id", "=", companyId)
+ .select("requireBackflushStorageUnit")
+ .executeTakeFirst();
+ return row?.requireBackflushStorageUnit === true;
+}
+
+type BinCoverArgs = {
+ companyId: string;
+ itemId: string;
+ locationId: string;
+ storageUnitId: string | null | undefined;
+ quantity: number;
+ plannedRows: LedgerInsert[];
+};
+
+/**
+ * Refuses (409) when `storageUnitId` is missing or cannot cover `quantity`.
+ * `plannedRows` are the ledger rows this backflush has built but not yet
+ * written — their draws on the same item and bin are subtracted first.
+ */
+export async function assertBinCovers(
+ db: Kysely<DB>,
+ args: BinCoverArgs
+): Promise<void> {
+ const problem = await binCoverProblem(db, args);
+ if (problem) throw strictBackflushRefusal([problem]);
+}
+
+// A shortfall reads "Not enough X in BIN: need n, have m" — long enough that
+// three of them fill a toast.
+const SHORTFALLS_SHOWN = 3;
+
+/** One refusal for every material the backflush cannot cover, so the
+ * material controller fixes them all before the operator retries. The toast
+ * names the first few and counts the rest; the log keeps the full list. */
+export function strictBackflushRefusal(problems: string[]): ServerFnError {
+ if (problems.length > SHORTFALLS_SHOWN) {
+ logger.warn("Strict backflush refused", { problems });
+ }
+ return new ServerFnError(summarizeList(problems, SHORTFALLS_SHOWN), 409);
+}
+
+/**
+ * Why `storageUnitId` cannot cover `quantity` — a missing bin or a short one —
+ * or null when it can. Takes the bin's lock either way (see below).
+ */
+export async function binCoverProblem(
+ db: Kysely<DB>,
+ args: BinCoverArgs
+): Promise<string | null> {
+ const { companyId, itemId, locationId, storageUnitId, quantity } = args;
+
+ if (!storageUnitId) {
+ const item = await readItemName(db, itemId, companyId);
+ return `${item} has no Pull From storage unit on this job`;
+ }
+
+ // Serialize strict draws on this bin and item until the caller's transaction
+ // ends, so two completions cannot both pass the check and overdraw it. SQL
+ // `backflush_job_materials` takes the same key.
+ await sql`SELECT pg_advisory_xact_lock(hashtextextended(${`strict-backflush:${companyId}:${storageUnitId}:${itemId}`}, 0))`.execute(
+ db
+ );
+
+ const row = await db
+ .selectFrom("itemLedger")
+ .where("itemId", "=", itemId)
+ .where("storageUnitId", "=", storageUnitId)
+ .where("locationId", "=", locationId)
+ .where("companyId", "=", companyId)
+ .where("trackedEntityId", "is", null)
+ .select((eb) => eb.fn.sum<number>("quantity").as("onHand"))
+ .executeTakeFirst();
+ const onHand = Number(row?.onHand ?? 0);
+
+ const alreadyDrawn = args.plannedRows
+ .filter(
+ (planned) =>
+ planned.itemId === itemId && planned.storageUnitId === storageUnitId
+ )
+ .reduce((sum, planned) => sum - Number(planned.quantity), 0);
+
+ if (binShortfall({ onHand, alreadyDrawn, quantity }) === 0) return null;
+
+ const [item, storageUnit] = await Promise.all([
+ readItemName(db, itemId, companyId),
+ db
+ .selectFrom("storageUnit")
+ .where("id", "=", storageUnitId)
+ .where("companyId", "=", companyId)
+ .select("name")
+ .executeTakeFirst()
+ ]);
+ const have = round(Math.max(onHand - alreadyDrawn, 0));
+ return `Not enough ${item} in ${storageUnit?.name ?? storageUnitId}: need ${round(quantity)}, have ${have}`;
+}
+
+/**
+ * Refuses (400) to activate a make method while a pulled, stocked line has no
+ * Pull From storage unit at one of `getPullFromLocations` (an active work
+ * center and an active storage unit).
+ */
+export async function assertMethodHasPullFrom(
+ db: Kysely<DB>,
+ args: { makeMethodId: string; companyId: string }
+): Promise<void> {
+ const { makeMethodId, companyId } = args;
+
+ const [lines, locations] = await Promise.all([
+ db
+ .selectFrom("methodMaterial")
+ .innerJoin("item", "item.id", "methodMaterial.itemId")
+ .where("methodMaterial.makeMethodId", "=", makeMethodId)
+ .where("methodMaterial.companyId", "=", companyId)
+ .select([
+ "methodMaterial.methodType",
+ "methodMaterial.itemType",
+ "methodMaterial.storageUnitIds",
+ "methodMaterial.order",
+ "item.id as itemId",
+ "item.itemTrackingType",
+ "item.readableIdWithRevision"
+ ])
+ .orderBy("methodMaterial.order")
+ .execute(),
+ getPullFromLocations(db, companyId)
+ ]);
+
+ const locationIds = locations.map((location) => location.id);
+
+ // One entry per part: the toast names what to fix, not where.
+ const parts = [
+ ...new Set(
+ lines
+ .filter(needsPullFrom)
+ .filter(
+ (line) =>
+ missingPullFromLocations(line.storageUnitIds, locationIds).length >
+ 0
+ )
+ .map((line) => line.readableIdWithRevision ?? line.itemId)
+ )
+ ];
+
+ if (parts.length === 0) return;
+
+ const list = summarizeList(parts);
+ throw new InvalidInputError(
+ `Set a Pull From storage unit before you activate this version: ${list}`
+ );
+}
+
+async function readItemName(
+ db: Kysely<DB>,
+ itemId: string,
+ companyId: string
+): Promise<string> {
+ const item = await db
+ .selectFrom("item")
+ .where("id", "=", itemId)
+ .where("companyId", "=", companyId)
+ .select("readableIdWithRevision")
+ .executeTakeFirst();
+ return item?.readableIdWithRevision ?? itemId;
+}
diff --git a/packages/server-functions/src/strict-backflush.test.ts b/packages/server-functions/src/strict-backflush.test.ts
new file mode 100644
index 0000000000..773f221f3b
--- /dev/null
+++ b/packages/server-functions/src/strict-backflush.test.ts
@@ -0,0 +1,358 @@
+// 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.
+
+// Strict backflush against the live database
+// (.ai/specs/2026-10-14-strict-backflush.md). With the setting on, a stocked
+// material is consumed only from its own storage unit and a missing or short
+// bin refuses the backflush; with it off, the old fallbacks still apply.
+
+import { sql } from "kysely";
+import { expect } from "vitest";
+import {
+ alwaysPostFixture,
+ type Fixture,
+ jobFixture,
+ seed,
+ USER,
+ unwrap,
+ workCenterFixture
+} from "./always-post-test-fixture";
+import issue from "./issue";
+import { assertMethodHasPullFrom } from "./lib/strict-backflush";
+import { databaseTest } from "./local-database-test-fixture";
+import postInventoryAdjustment from "./post-inventory-adjustment";
+
+async function setStrict(f: Fixture, on: boolean) {
+ await f.db
+ .updateTable("companySettings")
+ .set({ requireBackflushStorageUnit: on })
+ .where("id", "=", f.companyId)
+ .execute();
+}
+
+async function storageUnit(f: Fixture, name: string): Promise<string> {
+ const row = await f.db
+ .insertInto("storageUnit")
+ .values({
+ name: `${f.prefix} ${name}`,
+ locationId: f.locationId,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ return row.id;
+}
+
+async function stockBin(f: Fixture, storageUnitId: string, quantity: number) {
+ unwrap(
+ await postInventoryAdjustment(f.ctx, {
+ adjustmentType: "Positive Adjmt.",
+ itemId: f.partId,
+ locationId: f.locationId,
+ storageUnitId,
+ quantity
+ })
+ );
+}
+
+async function setMaterialBin(
+ f: Fixture,
+ materialId: string,
+ storageUnitId: string | null
+) {
+ await f.db
+ .updateTable("jobMaterial")
+ .set({ storageUnitId })
+ .where("id", "=", materialId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+}
+
+async function consumption(f: Fixture, jobId: string) {
+ return f.db
+ .selectFrom("itemLedger")
+ .select(["storageUnitId", "quantity"])
+ .where("documentId", "=", jobId)
+ .where("entryType", "=", "Consumption")
+ .where("companyId", "=", f.companyId)
+ .execute()
+ .then((rows) =>
+ rows.map((row) => ({ ...row, quantity: Number(row.quantity) }))
+ );
+}
+
+databaseTest(
+ "strict backflush refuses a short bin and never draws from another one",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const shelfA = await storageUnit(f, "Shelf A");
+ const shelfB = await storageUnit(f, "Shelf B");
+ await stockBin(f, shelfA, 1);
+ await stockBin(f, shelfB, 10);
+ const job = await jobFixture(f);
+ await setMaterialBin(f, job.materialId, shelfA);
+ await setStrict(f, true);
+
+ const result = await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1
+ });
+ expect(result.error?.status).toBe(409);
+ expect(result.error?.message).toBe(
+ `Not enough ${f.prefix}-PART in ${f.prefix} Shelf A: need 2, have 1`
+ );
+ expect(await consumption(f, job.jobId)).toEqual([]);
+
+ // Topped up, the same completion draws from Shelf A only.
+ await stockBin(f, shelfA, 1);
+ unwrap(
+ await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1
+ })
+ );
+ expect(await consumption(f, job.jobId)).toEqual([
+ { storageUnitId: shelfA, quantity: -2 }
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "strict backflush refuses a material with no storage unit",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const shelfB = await storageUnit(f, "Shelf B");
+ await stockBin(f, shelfB, 10);
+ const job = await jobFixture(f);
+ await setStrict(f, true);
+
+ const result = await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1
+ });
+ expect(result.error?.message).toBe(
+ `${f.prefix}-PART has no Pull From storage unit on this job`
+ );
+ expect(await consumption(f, job.jobId)).toEqual([]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "with strict backflush off, a short bin still falls back to the fullest one",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const shelfA = await storageUnit(f, "Shelf A");
+ const shelfB = await storageUnit(f, "Shelf B");
+ await stockBin(f, shelfA, 1);
+ await stockBin(f, shelfB, 10);
+ const job = await jobFixture(f);
+ await setMaterialBin(f, job.materialId, shelfA);
+
+ unwrap(
+ await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1
+ })
+ );
+ expect(await consumption(f, job.jobId)).toEqual([
+ { storageUnitId: shelfB, quantity: -2 }
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest("a dry run reports the refusal and writes nothing", async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const shelfA = await storageUnit(f, "Shelf A");
+ await stockBin(f, shelfA, 1);
+ const job = await jobFixture(f);
+ await setMaterialBin(f, job.materialId, shelfA);
+
+ // Off: a no-op, even though the bin is short.
+ unwrap(
+ await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1,
+ dryRun: true
+ })
+ );
+
+ await setStrict(f, true);
+ const short = await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1,
+ dryRun: true
+ });
+ expect(short.error?.status).toBe(409);
+
+ // Covered: the dry run succeeds and rolls every write back.
+ await stockBin(f, shelfA, 1);
+ unwrap(
+ await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1,
+ dryRun: true
+ })
+ );
+ expect(await consumption(f, job.jobId)).toEqual([]);
+ const material = await f.db
+ .selectFrom("jobMaterial")
+ .select("quantityIssued")
+ .where("id", "=", job.materialId)
+ .executeTakeFirstOrThrow();
+ expect(Number(material.quantityIssued ?? 0)).toBe(0);
+ } finally {
+ await f.cleanup();
+ }
+});
+
+databaseTest(
+ "strict manual issue of a planned material uses only its own bin",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const shelfA = await storageUnit(f, "Shelf A");
+ const shelfB = await storageUnit(f, "Shelf B");
+ await stockBin(f, shelfA, 1);
+ await stockBin(f, shelfB, 10);
+ const job = await jobFixture(f);
+ await setMaterialBin(f, job.materialId, shelfA);
+ await setStrict(f, true);
+
+ const result = await issue(f.ctx, {
+ type: "partToOperation",
+ id: job.operationId,
+ itemId: f.partId,
+ materialId: job.materialId,
+ quantity: 2,
+ adjustmentType: "Negative Adjmt."
+ });
+ expect(result.error?.message).toBe(
+ `Not enough ${f.prefix}-PART in ${f.prefix} Shelf A: need 2, have 1`
+ );
+ expect(await consumption(f, job.jobId)).toEqual([]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "the SQL job-completion backflush refuses a short bin under strict backflush",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const shelfA = await storageUnit(f, "Shelf A");
+ const shelfB = await storageUnit(f, "Shelf B");
+ await stockBin(f, shelfA, 1);
+ await stockBin(f, shelfB, 10);
+ const job = await jobFixture(f);
+ await setMaterialBin(f, job.materialId, shelfA);
+ await setStrict(f, true);
+
+ await expect(
+ sql`SELECT backflush_job_materials(${job.jobId}, 1, ${f.companyId}, ${USER})`.execute(
+ f.db
+ )
+ ).rejects.toThrow(
+ `Not enough ${f.prefix}-PART in ${f.prefix} Shelf A: need 2, have 1`
+ );
+ expect(await consumption(f, job.jobId)).toEqual([]);
+
+ await setMaterialBin(f, job.materialId, null);
+ await expect(
+ sql`SELECT backflush_job_materials(${job.jobId}, 1, ${f.companyId}, ${USER})`.execute(
+ f.db
+ )
+ ).rejects.toThrow(`${f.prefix}-PART has no Pull From storage unit`);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "activation needs a Pull From at each location with an active work center",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const shelfA = await storageUnit(f, "Shelf A");
+ const makeMethodId = `${f.prefix}-make-method`;
+ await seed(f, async (trx) => {
+ await trx
+ .insertInto("makeMethod")
+ .values({
+ id: makeMethodId,
+ itemId: f.assemblyId,
+ version: 99,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("methodMaterial")
+ .values({
+ makeMethodId,
+ itemId: f.partId,
+ itemType: "Part",
+ methodType: "Pull from Inventory",
+ quantity: 2,
+ unitOfMeasureCode: "EA",
+ storageUnitIds: {},
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ });
+
+ // No location has a work center yet, so nothing needs a bin.
+ await assertMethodHasPullFrom(f.db, {
+ makeMethodId,
+ companyId: f.companyId
+ });
+
+ await workCenterFixture(f);
+ await expect(
+ assertMethodHasPullFrom(f.db, {
+ makeMethodId,
+ companyId: f.companyId
+ })
+ ).rejects.toThrow(
+ `Set a Pull From storage unit before you activate this version: ${f.prefix}-PART`
+ );
+
+ await f.db
+ .updateTable("methodMaterial")
+ .set({ storageUnitIds: { [f.locationId]: shelfA } })
+ .where("makeMethodId", "=", makeMethodId)
+ .execute();
+ await assertMethodHasPullFrom(f.db, {
+ makeMethodId,
+ companyId: f.companyId
+ });
+ } finally {
+ await f.cleanup();
+ }
+ }
+);