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.

fix(production): strict backflush review fixes

naveenkasheac8ebafb1e7
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 10278bb2f0..90f1788cf5 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -3699,3 +3699,33 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Rule:** Before adding a unique index, list every writer of the table, interceptors included, and give each one `ON CONFLICT … DO NOTHING` or a conflict-safe update in the same change. When a composite unique key includes a nullable column, assume it deduplicates nothing for rows where that column is NULL.
**Applies to:** `membership` and its interceptors in `packages/database/src/event-system/handlers/`, and any unique key with a nullable column.
+
+## A pick moves a job material's storage unit to lineside, so the line no longer names its Pull From
+
+**Context:** Strict backflush (2026-10-16) consumed what no pick covered from `jobMaterial.storageUnitId`.
+
+**Problem:** Posting a pick calls `pointJobMaterialAtLineside`, which overwrites `jobMaterial.storageUnitId` with the lineside bin. After a partial pick, the remainder was checked against lineside (already drawn) instead of the warehouse bin the BoM named. With negative stock prevented it refused a completion the shelf could cover. With it allowed, it drove lineside negative. The TypeScript and SQL paths had the same bug, and no test picked anything.
+
+**Rule:** Never read `jobMaterial.storageUnitId` as "the Pull From" once picking may have run. The pick line keeps the source (`pickingListLine.storageUnitId`). Use the oldest pick line into the line's current bin (`pullFromStorageUnit`, `@carbon/database/strict-backflush`). A later list is sourced from the fullest bin, so do not use the newest one. Any test of a bin rule needs a case with a partial pick.
+
+**Applies to:** strict backflush, and any rule keyed on a job material's bin (picking, returns, lineside credit, consumption).
+
+## A module the browser bundles must not reach the Kysely runtime, even through a helper
+
+**Context:** Strict backflush (2026-10-16). `@carbon/database/strict-backflush` is imported by BoM UI components and by `settings.service.ts`, which the module barrel bundles for the browser.
+
+**Problem:** Using `inOrder` from `@carbon/database/rows` there would have imported `kysely` at runtime into the client bundle; typecheck does not see it. Separately, `settings.server.ts` gained an import of `~/utils/query`, which imports the `@carbon/auth` barrel. That barrel runs a Lingui `msg` macro, which plain vitest cannot compile, so 2 unrelated test files stopped loading.
+
+**Rule:** In a client-bundled module, import only types from `kysely` and `./client`. Run two awaits instead of `inOrder`. Raw `sql` belongs in a `*.server.ts`. Before adding an import to a file that tests import, check what that import's barrel pulls in, then run the module's tests.
+
+**Applies to:** `@carbon/database` subpaths read by UI, `{module}.service.ts`, `{module}.server.ts` imported by vitest files.
+
+## A Lingui placeholder is named after its expression, so a refactor can silently drop translations
+
+**Context:** Strict backflush (2026-10-16) changed `<Plural value={methodsMissingPullFrom} …>` to `<Plural value={gaps.methods} …>`.
+
+**Problem:** A member expression has no name, so the message id changed from `{methodsMissingPullFrom, plural, …}` to `{0, plural, …}`. `lingui:extract --clean` then deleted the old id and its 12 translations, and the new id came back untranslated.
+
+**Rule:** Pass a plain, named variable to `Plural`, `t` and `Trans` placeholders, and keep the name when refactoring. If extract drops translations by mistake, restore the catalogs from git (`git checkout HEAD -- packages/locale/locales`), fix the name, and extract again.
+
+**Applies to:** every `Plural` / `t\`…${x}\`` / `<Trans>` with an interpolation.
diff --git a/.ai/plans/2026-10-16-strict-backflush-review-fixes.md b/.ai/plans/2026-10-16-strict-backflush-review-fixes.md
new file mode 100644
index 0000000000..897fdaf4bd
--- /dev/null
+++ b/.ai/plans/2026-10-16-strict-backflush-review-fixes.md
@@ -0,0 +1,76 @@
+# Plan: strict backflush self-review fixes
+
+- Date: 2026-10-16
+- Spec: `.ai/specs/2026-10-14-strict-backflush.md`
+- Source: the self-review of PR #1931 (branch `naveenkash/strict-backflush`), after commit `bdb26a1ab5`.
+- Rule: no commit and no push until the user asks.
+
+## Decisions
+
+| # | Decision | Reason |
+|---|----------|--------|
+| D1 | The Pull From of a picked line is the source bin of its EARLIEST pick line whose destination is the line's current bin. If there is no such pick line, the Pull From is `jobMaterial.storageUnitId`. | A pick moves `jobMaterial.storageUnitId` to lineside. The pick line keeps the source, and `restoreJobMaterialSource` already treats it as the warehouse source. A later picking list takes the fullest bin, so the earliest line is the one that names the Pull From. No schema change on `jobMaterial`. |
+| D2 | In SQL job completion, a picked line draws from its lineside bin first, up to its on-hand. The remainder comes from the Pull From under the strict rules. | The TypeScript path already draws picks first. The SQL path must give the same answer. |
+| D3 | A short bin no longer skips its ledger row in SQL. The function raises after the loop, so the row rolls back. | Later materials on the same bin then see the refused need, and one refusal names every shortfall. |
+| D4 | Both paths lock every (bin, item) key in one sorted pass before the first draw, through one SQL function. | Two completions then take locks in the same order and cannot deadlock. |
+| D5 | Strict backflush applies only at a location that `getPullFromLocations` returns (an active work center and an active storage unit). | Activation exempts the other locations. Without this, a job there can never complete. |
+| D6 | The dry run stops right after the strict check, before any ledger, cost or journal row. | It answers the only question it asks, and it no longer holds the journal sequence lock. |
+| D7 | The jobs drawer lists only lines a backflush would refuse: stocked, not batch or serial, quantity still to issue. | The card says the next backflush will be refused. A batch or serial line, or a fully issued line, never is. |
+| D8 | The card counts come from SQL counts. The drawers keep the full lists. | The parent loader re-runs on every drawer search, sort and page. |
+| D9 | The materials popover follows `conventions-ui.md` "Popovers inside Drawers / Dialogs", not `modal`. | The rule is written for exactly this case and adds a visible scrollbar. |
+
+## Tasks
+
+### A. Picks and the Pull From (Must fix 1)
+- [x] A1. Add `resolvePullFromStorageUnit` to `packages/server-functions/src/lib/strict-backflush.ts` (D1).
+- [x] A2. Use it in `issueJobOperationMaterials` and in `partToOperation`.
+- [x] A3. In the migration, apply D1 and D2 to `backflush_job_materials`.
+- [x] A4. Add live-database tests: a partial pick at operation completion and at job completion.
+
+### B. Locks, rounding, refused needs (risks)
+- [x] B1. Add `lock_strict_backflush_bins(p_company_id, p_keys)` to the migration. Use it from SQL and TypeScript (D4).
+- [x] B2. Compare and format quantities with `round(…, 5)` in SQL.
+- [x] B3. Apply D3 in SQL.
+- [x] B4. Scope the SQL `item` join and the storage unit name read by `companyId`.
+- [x] B5. Make the missing-bin message the same in SQL and TypeScript.
+
+### C. Exempt locations (D5)
+- [x] C1. Strict applies only at a pull-from location, in TypeScript and SQL.
+
+### D. Dry run and messages
+- [x] D1. Stop the dry run after the strict check (D6).
+- [x] D2. Run the inspection disposition dry run before the lot closes. Add a dry run before the scrap insert.
+- [x] D3. After a production quantity is recorded, prefix a failed issue with "Units recorded, but".
+- [x] D4. MES serial completion: print the label only after the server accepts.
+- [x] D5. Batch phase 2: keep the refusal's 409.
+
+### E. Activation and release gates
+- [x] E1. Gate the activation in `upsertMakeMethodVersion` callers.
+- [x] E2. Run the release check on every move to Ready from Draft or Planned.
+
+### F. Settings card and drawers
+- [x] F1. SQL counts for the card (D8).
+- [x] F2. Jobs list semantics (D7). Use `activeJobStatuses`.
+- [x] F3. A failed read shows an error, not an empty or missing row.
+- [x] F4. Drawer search covers Locations and Status.
+- [x] F5. Popover per D9. Fix the production `AGENTS.md` line.
+- [x] F6. Minor: dead `?? true`, deep import.
+
+### G. UI
+- [x] G1. The BoM badge uses the pull-from locations from the loader, collapsed and expanded.
+- [x] G2. The badge follows the item after the line's item changes.
+- [x] G3. The Release dialog fails closed on a read error.
+- [x] G4. Translation gaps: `BatchReleaseModal` list text, "WIP", "Default Storage Unit".
+
+### H. Tests and docs
+- [x] H1. Pure tests: `pageInMemory`, lock-key ordering.
+- [x] H2. Docs: `packages/database/AGENTS.md`, `packages/server-functions/AGENTS.md`, settings and production `AGENTS.md`, `.ai/lessons.md`, the spec.
+- [x] H3. Gates: Biome, typecheck (database, server-functions, erp, mes), tests, translations.
+
+## Notes
+
+- E1: the change-notice draft (`createChangeNoticeDraftMethod`) still freezes a Draft base as Active without the check. The freeze is a side effect of opening the notice. Release still refuses the jobs. The spec's production `AGENTS.md` section records this.
+- A4: the live-database tests are written, not run. They create and delete a scratch company, and the user asks before any database write.
+- Not done, by choice: one `issue` call that records production and issues materials in one transaction. It would remove the dry run and its race, but it changes 4 callers. The "Units completed, but" message covers the race for now.
+- Not done, by choice: activation checks that a Pull From is set, not that its bin is active or at the right location.
+- The glossary check flags 2 Hindi strings for the plural "भंडारण इकाइयाँ". The catalog's own "Storage Units" uses the same form and is flagged the same way: the checker does not know the Hindi plural.
diff --git a/.ai/specs/2026-10-14-strict-backflush.md b/.ai/specs/2026-10-14-strict-backflush.md
index cece184d72..2eaa6c6ccf 100644
--- a/.ai/specs/2026-10-14-strict-backflush.md
+++ b/.ai/specs/2026-10-14-strict-backflush.md
@@ -55,12 +55,13 @@ Example: the BoM says "pull 10 × PART-123 from Shelf A-4". Shelf A-4 has 6 and
| 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. |
+| 5 | Picked stock | The material's picks and unclaimed lineside stock are consumed first, as today. The strict rule applies to the remainder, against the line's Pull From. After a pick, the Pull From is the source bin of the line's oldest pick line into its current bin (`pullFromStorageUnit`). Job completion (SQL) draws a picked line from its lineside bin first, up to what the bin holds, then the rest from the Pull From. | A pick moves stock out of the Pull From bin with a transfer, so the records stay correct. Picking also moves `jobMaterial.storageUnitId` to the lineside bin, so that column no longer names the Pull From. The pick line keeps it. A later picking list takes the fullest bin, so only the oldest pick line names the Pull From. |
+| 5a | Locations without a pull-from bin | Strict backflush applies only at a location from decision 3. Elsewhere the backflush, release and the badges behave as with the setting off. | Activation asks for no Pull From there, so a refusal there could never be fixed. |
| 6a | Negative stock under strict bins | A second switch, `companySettings.preventNegativeBackflush` ("Prevent negative stock", default `true`), nested under Strict Backflush and only active while it is on. Off: the material is still drawn only from its own storage unit, and that storage unit may go below zero. A missing storage unit is refused either way. | A company can want strict bins (accurate per-location stock) without the hard stop on a short bin. Default `true` keeps the behavior the setting shipped with. |
| 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, jobs already released | Carbon does not change them. The settings card counts Active methods with a gap and open jobs (Ready, In Progress, Paused) with a material that has no storage unit. Each count opens a drawer with the full list, searchable and paged. | Changing a live method or job without warning is a large risk. A card can hold a count, not a list of hundreds. |
-| 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. |
+| 8 | Methods that are already Active, jobs already released | Carbon does not change them. The settings card counts Active methods with a gap and open jobs (Ready, In Progress, Paused) whose next backflush would be refused: a stocked line with no storage unit, not batch or serial, with quantity still to issue, at a location from decision 3. Each count opens a drawer with the full list, searchable and paged. A count and its list read the same query. | Changing a live method or job without warning is a large risk. A card can hold a count, not a list of hundreds. |
+| 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. The dry run stops after the strict check, before any ledger, cost or journal row. If the dry run fails, MES records nothing. An inspection lot runs the dry run before the lot closes. A failure after the units are recorded says "Units completed, but …". | 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. |
@@ -165,6 +166,7 @@ No new table. No RLS change.
## Changelog
- 2026-10-14: Created from the backflush rules design discussion.
+- 2026-10-16: Self-review fixes (plan `.ai/plans/2026-10-16-strict-backflush-review-fixes.md`): after a partial pick, the rest now comes from the Pull From, not lineside (decision 5, TypeScript and SQL); strict backflush skips a location with no pull-from bin (decision 5a); both paths lock every (bin, item) pair in one order before the first draw; SQL compares rounded quantities and counts a refused need; the dry run stops at the strict check; the inspection lot is checked before it closes; the New Version route checks activation; every release path checks storage units; the card counts with SQL and the jobs list holds only lines a backflush would refuse (decision 8); the BoM badges use the pull-from locations.
- 2026-10-16: The settings card counts open jobs with a material that has no storage unit, and both counts open a searchable drawer instead of an inline list (user request).
- 2026-10-16: The drawers show locations as pills. A materials cell shows 3 part IDs, and "+N more" opens the full list in a popover that scrolls (user request).
- 2026-10-16: Split the no-negative rule into its own switch, `preventNegativeBackflush` (decision 6a, user request).
diff --git a/apps/erp/app/hooks/usePullFromLocationIds.ts b/apps/erp/app/hooks/usePullFromLocationIds.ts
new file mode 100644
index 0000000000..1e9708d85d
--- /dev/null
+++ b/apps/erp/app/hooks/usePullFromLocationIds.ts
@@ -0,0 +1,22 @@
+// 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 { useLoaderQuery } from "@carbon/query";
+import type { loader } from "~/routes/api+/items.pull-from-locations";
+import { path } from "~/utils/path";
+import { useCompanySettings } from "./useCompanySettings";
+
+/**
+ * Strict backflush: the locations a pulled line needs a Pull From at, or null
+ * while the setting is off or the list is still loading (a badge shows
+ * nothing until it is known).
+ */
+export function usePullFromLocationIds(): string[] | null {
+ const companySettings = useCompanySettings();
+ const strict = companySettings?.requireBackflushStorageUnit === true;
+ const query = useLoaderQuery<typeof loader>(
+ strict ? path.to.api.pullFromLocations : null
+ );
+ return strict ? (query.data?.data ?? null) : null;
+}
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index 5a98cb33e9..373adbdeff 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -5,7 +5,10 @@
"use client";
import { useCarbon } from "@carbon/auth";
import type { Database } from "@carbon/database";
-import { needsPullFrom } from "@carbon/database/strict-backflush";
+import {
+ missingPullFromLocations,
+ needsPullFrom
+} from "@carbon/database/strict-backflush";
import { ValidatedForm } from "@carbon/form";
import {
Badge,
@@ -87,7 +90,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 { usePullFromLocationIds } from "~/hooks/usePullFromLocationIds";
import type {
MethodItemType,
MethodType,
@@ -258,21 +261,18 @@ 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();
+ // Strict backflush: mark collapsed rows with no Pull From at a location
+ // that needs one — the test activation refuses on (`convert`).
+ const pullFromLocationIds = usePullFromLocationIds();
const missingPullFrom = (material: Material) =>
- companySettings?.requireBackflushStorageUnit === true &&
- !!defaults.locationId &&
+ pullFromLocationIds !== null &&
needsPullFrom({
methodType: material.methodType,
itemType: material.itemType,
itemTrackingType: material.item?.itemTrackingType ?? null
}) &&
- !(material.storageUnitIds as Record<string, string> | null)?.[
- defaults.locationId
- ];
+ missingPullFromLocations(material.storageUnitIds, pullFromLocationIds)
+ .length > 0;
const materials = makeItems(
items,
@@ -717,14 +717,26 @@ function MaterialForm({
});
// 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();
+ // backflushed from, at the selected location when that location needs one,
+ // before its method version can be made active. A changed item's tracking
+ // type comes from `onItemChange`, keyed by the item it was read for.
+ const pullFromLocationIds = usePullFromLocationIds();
+ const [changedItemTracking, setChangedItemTracking] = useState<{
+ itemId: string;
+ itemTrackingType: string | null;
+ } | null>(null);
+ const itemTrackingType =
+ changedItemTracking?.itemId === itemData.itemId
+ ? changedItemTracking.itemTrackingType
+ : (item.data.item?.itemTrackingType ?? null);
const requiresPullFrom =
- companySettings?.requireBackflushStorageUnit === true &&
+ pullFromLocationIds !== null &&
+ !!locationId &&
+ pullFromLocationIds.includes(locationId) &&
needsPullFrom({
methodType: itemData.methodType,
itemType,
- itemTrackingType: item.data.item?.itemTrackingType ?? null
+ itemTrackingType
});
// methodType/sourcingType are read-only mirrors of the component item
@@ -794,6 +806,10 @@ function MaterialForm({
requiresSerialTracking: item.data?.itemTrackingType === "Serial",
itemReplenishmentSystem: item.data?.replenishmentSystem ?? "Buy"
}));
+ setChangedItemTracking({
+ itemId,
+ itemTrackingType: item.data?.itemTrackingType ?? null
+ });
if (item.data?.type) {
setItemType(item.data.type as MethodItemType);
}
@@ -1022,8 +1038,8 @@ function MaterialForm({
(s) => s.value === itemData.storageUnitIds[locationId ?? ""]
)?.label ??
(itemData.methodType === "Make to Order"
- ? "WIP"
- : "Default Storage Unit")}
+ ? t`WIP`
+ : t`Default Storage Unit`)}
</Badge>
)}
<IconButton
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 5d89c44bc5..4a47169244 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -20,14 +20,15 @@ Work orders (jobs), scheduling, routings (operations), bill of materials, proced
### 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, never another bin. A missing bin refuses the work. A short bin refuses it only while `companySettings.preventNegativeBackflush` is on (the nested "Prevent negative stock" switch, on by default); with it off the bin is drawn below zero. `getStrictBackflushSettings` (`packages/server-functions/src/lib/strict-backflush.ts`) reads both, and `binCoverProblem` skips the quantity check and its lock when negative stock is allowed; the SQL reads the same two columns:
-
-- **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` (`20261015163040_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 and released jobs are never changed** when the setting turns on. The settings card counts both gaps — `getActiveMethodsMissingPullFrom` (Active methods with a material missing a Pull From) and `getOpenJobsMissingStorageUnit` (Ready / In Progress / Paused jobs with a material that has no storage unit; release would refuse them, but they are past it) — and each count's Review button opens a route drawer (`settings+/items.methods-missing-pull-from.tsx`, `items.jobs-missing-storage-unit.tsx`) with the full list in a searchable, paged `Table` (`ui/StrictBackflush/StrictBackflushTables.tsx`; the loaders page in memory with `pageInMemory` from `~/utils/query`). A long list never goes in the card itself. Locations render as `Enumerable` pills; a materials cell shows 3 part IDs and a "+N more" button that opens all of them in a scrolling popover. The popover is `modal` — it renders in a portal outside the drawer, and without its own scroll lock the drawer's lock cancels the wheel over it.
+`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 Pull From, never another bin. A missing bin refuses the work. A short bin refuses it only while `companySettings.preventNegativeBackflush` is on (the nested "Prevent negative stock" switch, on by default); with it off the bin is drawn below zero. `getStrictBackflushSettings(db, companyId, locationId?)` (`@carbon/database/strict-backflush`) reads both; given a location, `strict` is false there unless it is a pull-from location (below). The SQL reads the same columns and makes the same location test.
+
+- **Which lines, which locations.** `needsPullFrom` (`@carbon/database/strict-backflush`): not Make to Order, item type Material / Part / Consumable, item not Non-Inventory. The locations are `getPullFromLocations` / `isPullFromLocation` — each with an active work center AND an active storage unit (a location with no storage unit has no bin a line could name). Strict backflush does not apply anywhere else: activation, release, the backflush, the badges and the settings card all skip such a location.
+- **Activation.** `getMethodPartsMissingPullFrom` + `activationRefusalMessage` (`@carbon/database/strict-backflush`). `convert` `methodVersionToActive` refuses through `assertMethodHasPullFrom` (`packages/server-functions/src/lib/strict-backflush.ts`); the New Version route (`x+/items+/methods+/version.new.tsx`), which makes a single Draft version Active, refuses the same way before it writes. The change-notice draft (`createChangeNoticeDraftMethod`) freezes a Draft base as Active without the check: that is a side effect of opening the notice, and release still refuses the jobs.
+- **Release.** `getJobReleaseReadiness` returns `materialsWithoutStorageUnit` per job (`materialsWithoutStorageUnit` in `job-release-logic.ts`, one entry per part; jobs at other locations are skipped). `$jobId.status.tsx` refuses on it for every move to Ready from Draft or Planned (the dialog, a plain post, the API); resuming a Paused job is not a release. `jobReleaseProblems` and `BatchReleaseModal` refuse on it too. `JobStartModal` lists the parts and disables Release Job; while the pull-from locations load it assumes the job's location needs them, and a failed read shows an error and disables Release.
+- **Backflush.** `issueJobOperationMaterials` and `partToOperation` (planned material, consuming issue) take picked and unclaimed lineside stock first, then what no pick covered from the line's Pull From only (`assertBinCovers` / `binCoverProblem`: 409, names the part, the bin, need and have). A pick points `jobMaterial.storageUnitId` at lineside (`pointJobMaterialAtLineside`), so the Pull From is resolved by `resolvePullFromStorageUnits` → `pullFromStorageUnit`: the source bin of the line's OLDEST pick line into its current bin, else the line's own bin. Before the first draw, `lockStrictBins` takes `pg_advisory_xact_lock(hashtextextended('strict-backflush:<companyId>:<bin>:<item>', 0))` for every (Pull From, item) pair in key-hash order; SQL locks the same keys in the same order, so two completions cannot deadlock. Every shortfall is collected and refused once; a refused material still counts its need against the bin, so the refusal names the whole shortfall. A refusal is a toast, so every strict message goes through `summarizeList`: the first 5 part names or 3 shortfalls, then "and N more" (the full shortfall list is logged). SQL `backflush_job_materials` (`20261015163040_strict-backflush.sql`) does the same at job completion: a picked line is drawn from lineside first (up to its on-hand), the rest from the Pull From; quantities compare at `round(…, 5)`.
+- **Produced units with no consumption.** Callers that record a production quantity before they call `issue` first invoke `issue` `jobOperation` with `dryRun: true`; `issueJobOperationMaterials` throws `DryRunRollback` right after the strict check, before any ledger, cost or journal row, and the call is a no-op when the setting is off. MES callers go through `checkStrictBackflush` (`apps/mes/app/services/quality.server.ts`): `complete.tsx`, `end.$operationId.tsx`, `inspection-lot.$id.complete-passed.tsx`, and `inspection-lot.$id.disposition.tsx`, which checks completion plus scrap BEFORE it closes the lot (a closed lot cannot be dispositioned again). ERP `completeOperation` and `batch-operations` `complete` dry-run too; batch phase 2 keeps a refusal's 409. The dry run narrows the race, it does not close it (its lock ends with its rollback), so a failure after the units are recorded says "Units completed, but …" — the operator must not record them again.
+- **Existing Active methods and released jobs are never changed** when the setting turns on. Settings → Items counts both gaps with `getStrictBackflushGapCounts` (`settings.server.ts`, two `count(DISTINCT …)` statements; a failed count shows an error line, never a clean card) and each count's Review button opens a route drawer (`settings+/items.methods-missing-pull-from.tsx`, `items.jobs-missing-storage-unit.tsx`) over `getActiveMethodsMissingPullFrom` / `getOpenJobsMissingStorageUnit` (`settings.server.ts`). Each count and its list share one query builder (`methodLinesMissingPullFrom`, `jobLinesMissingStorageUnit`, the SQL form of `needsPullFrom`), so they cannot disagree. The jobs list holds only lines a backflush would refuse: stocked, not batch or serial, quantity still to issue, at a pull-from location. The drawers page in memory with `pageInMemory` (`~/utils/query`) in a searchable, paged `Table` (`ui/StrictBackflush/StrictBackflushTables.tsx`); a failed read flashes an error and returns to the page. A long list never goes in the card itself. Locations render as `Enumerable` pills; a materials cell shows 3 part IDs and a "+N more" popover with all of them, which stops wheel and touch propagation so it scrolls inside the drawer (`conventions-ui.md`, "Popovers inside Drawers").
+- **Badges.** The BoM and job BoM editors mark a line red ("No storage unit"), collapsed and open, from `usePullFromLocationIds` (`~/hooks`, the cached `api+/items.pull-from-locations.ts`) — the same locations activation and release use. A changed line item's tracking type is kept until the line is saved, so the badge follows the new item.
### Job completion
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 0ee3dabecf..ca429fd109 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -2985,7 +2985,9 @@ 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.
+// backflush would be refused. Keyed by job id; empty while the setting is off,
+// and for a job at a location strict backflush skips (no active work center or
+// no active storage unit — `getPullFromLocations`).
async function getMaterialsWithoutStorageUnit(
client: SupabaseClient<Database>,
jobIds: string[],
@@ -3007,7 +3009,7 @@ async function getMaterialsWithoutStorageUnit(
client
.from("jobMaterial")
.select(
- "id, jobId, description, methodType, itemType, storageUnitId, item(itemTrackingType, readableIdWithRevision)"
+ "id, jobId, description, methodType, itemType, storageUnitId, item(itemTrackingType, readableIdWithRevision), job(locationId)"
)
.in("jobId", batch)
.eq("companyId", companyId)
@@ -3016,9 +3018,42 @@ async function getMaterialsWithoutStorageUnit(
);
if (lines.error) return { data: {}, error: lines.error };
+ const jobLocationIds = [
+ ...new Set(
+ (lines.data ?? []).flatMap((line) =>
+ line.job?.locationId ? [line.job.locationId] : []
+ )
+ )
+ ];
+ // The same test as getPullFromLocations, for these jobs' locations only:
+ // one row per location that has an active work center and storage unit.
+ const pullFromLocations =
+ jobLocationIds.length === 0
+ ? { data: [], error: null }
+ : await client
+ .from("location")
+ .select("id, workCenter!inner(id), storageUnit!inner(id)")
+ .in("id", jobLocationIds)
+ .eq("companyId", companyId)
+ .eq("workCenter.active", true)
+ .eq("storageUnit.active", true)
+ .limit(1, { referencedTable: "workCenter" })
+ .limit(1, { referencedTable: "storageUnit" });
+ if (pullFromLocations.error)
+ return { data: {}, error: pullFromLocations.error };
+ const strictLocationIds = new Set(
+ (pullFromLocations.data ?? []).map((location) => location.id)
+ );
+
const byJob: Record<string, { id: string; description: string }[]> = {};
for (const [jobId, jobLines] of Object.entries(
- groupBy(lines.data ?? [], (line) => line.jobId)
+ groupBy(
+ (lines.data ?? []).filter(
+ (line) =>
+ line.job?.locationId && strictLocationIds.has(line.job.locationId)
+ ),
+ (line) => line.jobId
+ )
)) {
const missing = materialsWithoutStorageUnit(jobLines);
if (missing.length > 0) byJob[jobId] = missing;
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
index b4207eef0b..2164ce1b95 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
@@ -2,7 +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 { MESSAGE_LIST_LIMIT } from "@carbon/database/strict-backflush";
import {
Alert,
AlertDescription,
@@ -46,6 +46,18 @@ export function BatchReleaseModal({
onClose: () => void;
}) {
const { t } = useLingui();
+ // The first few parts, then a count — a whole translated sentence either
+ // way, so the "and N more" is translated too.
+ const storageUnitReason = (materials: { description: string }[]) => {
+ const names = materials
+ .slice(0, MESSAGE_LIST_LIMIT)
+ .map((material) => material.description)
+ .join(", ");
+ const more = materials.length - MESSAGE_LIST_LIMIT;
+ return more > 0
+ ? t`set a Pull From storage unit on ${names} and ${more} more`
+ : t`set a Pull From storage unit on ${names}`;
+ };
const readinessFetcher = useFetcher<
JobReleaseReadiness | { error: string }
>();
@@ -140,11 +152,7 @@ export function BatchReleaseModal({
: 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
- )
- )}`
+ storageUnitReason(job.materialsWithoutStorageUnit)
]
.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 469fa97f11..4044cfc034 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -78,7 +78,7 @@ import {
useUrlParams,
useUser
} from "~/hooks";
-import { useCompanySettings } from "~/hooks/useCompanySettings";
+import { usePullFromLocationIds } from "~/hooks/usePullFromLocationIds";
import { ItemTrackingType } from "~/modules/items";
import {
MaterialRowDetails,
@@ -293,11 +293,15 @@ const JobBillOfMaterial = ({
});
const [storeItems] = useItems();
+ const jobData = useRouteData<{ job: Job }>(path.to.job(jobId));
// 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();
+ // from, when the job's location needs one — the test release refuses on.
+ const pullFromLocationIds = usePullFromLocationIds();
+ const jobLocationId = jobData?.job?.locationId;
const missingPullFrom = (material: Material) =>
- companySettings?.requireBackflushStorageUnit === true &&
+ pullFromLocationIds !== null &&
+ !!jobLocationId &&
+ pullFromLocationIds.includes(jobLocationId) &&
!material.storageUnitId &&
needsPullFrom({
methodType: material.methodType ?? null,
@@ -311,8 +315,6 @@ const JobBillOfMaterial = ({
checkedState,
missingPullFrom
).sort((a, b) => a.data.order - b.data.order);
-
- const jobData = useRouteData<{ job: Job }>(path.to.job(jobId));
const isDisabled = ["Completed", "Cancelled"].includes(
jobData?.job?.status ?? ""
);
@@ -685,6 +687,11 @@ function MaterialForm({
});
};
+ const [changedItemTracking, setChangedItemTracking] = useState<{
+ itemId: string;
+ itemTrackingType: string | null;
+ } | null>(null);
+
const onItemChange = async (itemId: string) => {
if (!carbon) return;
if (itemId === params.itemId) {
@@ -730,6 +737,10 @@ function MaterialForm({
storageUnitId: pickMethod.data?.defaultStorageUnitId ?? "",
itemReplenishmentSystem: item.data?.replenishmentSystem ?? "Buy"
}));
+ setChangedItemTracking({
+ itemId,
+ itemTrackingType: item.data?.itemTrackingType ?? null
+ });
if (item.data?.type) {
setItemType(item.data.type as MethodItemType);
@@ -748,14 +759,21 @@ function MaterialForm({
// 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();
+ // refused at release and at backflush. A changed item's tracking type comes
+ // from `onItemChange`, keyed by the item it was read for.
+ const pullFromLocationIds = usePullFromLocationIds();
+ const itemTrackingType =
+ changedItemTracking?.itemId === itemData.itemId
+ ? changedItemTracking.itemTrackingType
+ : (item.data.item?.itemTrackingType ?? null);
const requiresPullFrom =
- companySettings?.requireBackflushStorageUnit === true &&
+ pullFromLocationIds !== null &&
+ !!locationId &&
+ pullFromLocationIds.includes(locationId) &&
needsPullFrom({
methodType: itemData.methodType,
itemType,
- itemTrackingType: item.data.item?.itemTrackingType ?? null
+ itemTrackingType
});
const isTracked =
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
index 22c0889bba..f230dbd0d7 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobHeader.tsx
@@ -84,6 +84,7 @@ import {
useUser
} from "~/hooks";
import { useCompanySettings } from "~/hooks/useCompanySettings";
+import { usePullFromLocationIds } from "~/hooks/usePullFromLocationIds";
import { useSuppliers } from "~/stores";
import { generateBomIds } from "~/utils/bom";
import { path } from "~/utils/path";
@@ -631,10 +632,19 @@ export function JobStartModal({
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<
+ // route refuses them too; showing them here saves a failed submit. They
+ // count only at a location that needs a Pull From — assumed while that list
+ // loads, so the dialog never offers a release the route refuses.
+ const pullFromLocationIds = usePullFromLocationIds();
+ const strictAtJobLocation =
+ strictBackflush &&
+ (pullFromLocationIds === null ||
+ (!!job?.locationId && pullFromLocationIds.includes(job.locationId)));
+ const [storageUnitGaps, setStorageUnitGaps] = useState<
{ id: string; description: string }[]
>([]);
+ const [storageUnitCheckFailed, setStorageUnitCheckFailed] = useState(false);
+ const missingStorageUnits = strictAtJobLocation ? storageUnitGaps : [];
const [missingOperationAssemblies, setMissingOperationAssemblies] = useState<
{ bomId: string; description: string }[]
>([]);
@@ -691,7 +701,7 @@ export function JobStartModal({
.eq("jobId", job.id!)
.eq("companyId", job.companyId!)
.is("storageUnitId", null)
- : Promise.resolve({ data: [] })
+ : Promise.resolve({ data: [], error: null })
]);
// Check for existing purchase order lines for outside operations
@@ -893,9 +903,10 @@ export function JobStartModal({
flushSync(() => {
setMissingOperationAssemblies(missingAssemblies);
- setMissingStorageUnits(
+ setStorageUnitGaps(
materialsWithoutStorageUnit(storageUnitLines.data ?? [])
);
+ setStorageUnitCheckFailed(!!storageUnitLines.error);
// Show the release UI whenever there are outside operations still needing handling,
// whether or not they have a supplier yet
@@ -958,6 +969,7 @@ export function JobStartModal({
<VStack>
{missingOperationAssemblies.length === 0 &&
missingStorageUnits.length === 0 &&
+ !(strictAtJobLocation && storageUnitCheckFailed) &&
eachOutsideOperationHasASupplier && (
<p className="text-sm">
<Trans>
@@ -1099,6 +1111,21 @@ export function JobStartModal({
</AlertDescription>
</Alert>
)}
+ {strictAtJobLocation && storageUnitCheckFailed && (
+ <Alert variant="destructive">
+ <LuTriangleAlert />
+ <AlertTitle>
+ <Trans>Storage Units Not Checked</Trans>
+ </AlertTitle>
+ <AlertDescription>
+ <Trans>
+ Could not check the storage units of this job's
+ materials. Close this dialog and open it again to try
+ again.
+ </Trans>
+ </AlertDescription>
+ </Alert>
+ )}
{missingStorageUnits.length > 0 && (
<Alert variant="warning">
<LuTriangleAlert />
@@ -1165,6 +1192,7 @@ export function JobStartModal({
fetcher.state !== "idle" ||
missingOperationAssemblies.length > 0 ||
missingStorageUnits.length > 0 ||
+ (strictAtJobLocation && storageUnitCheckFailed) ||
!eachOutsideOperationHasASupplier
}
type="submit"
diff --git a/apps/erp/app/modules/settings/AGENTS.md b/apps/erp/app/modules/settings/AGENTS.md
index b9a599af08..621fbbfb7f 100644
--- a/apps/erp/app/modules/settings/AGENTS.md
+++ b/apps/erp/app/modules/settings/AGENTS.md
@@ -77,6 +77,7 @@ pnpm run lint
- Webhook + API-key READ helpers stay here (`getWebhook(s)` / `getWebhookTables`, `getApiKey(s)`); the commercial AUTHORING writers moved to `@carbon/ee` behind the entitlement lock — `upsertApiKey` / `deleteApiKey` (`@carbon/ee/api-keys.server`, `API_KEYS`) and `upsertWebhook` / `deleteWebhook` / `deactivateWebhooks` (`@carbon/ee/webhooks.server`, `WEBHOOKS`)
- `insertCompany` / `insertSubsidiary` / `updateSubsidiary` / `deleteSubsidiary` / `seedCompany` / `updateCompany` / `updateCompanyPlan`
- `updateLeasePolicySettings` (the ASC 842 lessor thresholds `leaseMajorPartThresholdPercent` / `leaseSubstantiallyAllThresholdPercent` and `leaseDefaultDiscountRate`, percentage points) — written from `x+/settings+/accounting.tsx` (intent `leasePolicy`); applies to later rental activations only. Revenue recognition has no setting of its own. The same page's General Ledger card has no switch: it shows "Accounting since {date}" from `companySettings.accountingCutoverDate`, or "Accounting is not set up" and a "Set up accounting" button to the enable wizard (`x+/accounting+/activation`, see accounting AGENTS). The test is `hasAccountingCutover` (`~/modules/accounting/accounting.utils`). After the cutover the card shows a warning alert when documents posted on or after the cutover have no journal: the loader awaits `hasLegacyDocuments` (one statement of EXISTS tests, `@carbon/database/accounting-cutover-reads`), because it decides whether the alert exists, and streams the count (`getLegacyDocumentCounts`, read with `useResolved`). The alert's "Write missing journals" button posts intent `journal-legacy`, which invokes the `journal-legacy-documents` server function; it needs `update: settings` and `update: accounting`. `updateAccountingEnabledSetting` is gone, and the `accountingEnabled` column is unused
+- Strict backflush (Settings → Items, `x+/settings+/items.tsx`, intents `requireBackflushStorageUnit` / `preventNegativeBackflush`): `updateRequireBackflushStorageUnitSetting` / `updatePreventNegativeBackflushSetting` (`companySettings`). The card's gaps are `getStrictBackflushGapCounts`, and its two drawers read `getActiveMethodsMissingPullFrom` / `getOpenJobsMissingStorageUnit` — all three in `settings.server.ts` (raw SQL through Kysely; `settings.service.ts` is browser-bundled). Row types `MethodMissingPullFrom` / `JobMissingStorageUnit` are in `types.ts`. The feature itself: `apps/erp/app/modules/production/AGENTS.md` → Strict backflush
- `updateLogoLight|LightIcon|Dark|DarkIcon|Watermark` — store the storage path on `company`, not a URL (readers prefix it)
- `listCompanyBackupFolders` / `deleteCompanyBackup` / `getCompanyRestoreRuns` / `getCompanyExportRun` (`backups.service.ts`); `exportCompanyBackup` (`backups.server.ts`, sends `carbon/company-export`); `getCompanyBackups` — the Backups loader's list, which computes each backup's live compatibility verdict via `@carbon/jobs/backups` — and the restore triggers live in `backups.server.ts`
- Planning (Settings → Planning, `x+/settings+/planning.tsx`, cards in `ui/Planning/`): `setRescheduleToleranceDays` / `setDefaultPlanningHorizonDays` / `setForecastConsumptionWindow` (`companySettings`), and the action owner ladder — `setDefaultResponsibleEmployee` (company), `setLocationResponsibleEmployee` (`location.responsibleEmployee`; returns the row, since a user without `resources_update` matches none under RLS and the route reports that), `upsertItemPostingGroupResponsibility` (item group at a location; updates in place so `createdBy` survives, inserts a new cell, and a null employee deletes the row), read back by `getItemPostingGroupResponsibilities`. The item rung is `itemPlanning.responsibleEmployee`, edited on the item. The scheduled MRP time is `updateMrpRunTimeSetting` (`companySettings.mrpRunTime`, null = every 3 hours), edited on the same page. Cards and intents: `ResponsibleEmployeeCard` (`setCompanyDefault` / `setLocation` / `setItemGroup`), `RescheduleToleranceCard` (`setTolerance`), `PlanningHorizonCard` (`setPlanningHorizon`), `ForecastConsumptionCard` (`setForecastConsumption`), `MrpScheduleCard` (`setMrpSchedule` → `updateMrpRunTimeSetting`); validators `mrpScheduleValidator`, `rescheduleToleranceValidator`, `planningHorizonValidator`, `forecastConsumptionValidator` (`settings.models.ts`; `settings.models.mrp-schedule.test.ts`). The `companySettings` columns: `defaultResponsibleEmployee`, `rescheduleToleranceDays` (default 7), `defaultPlanningHorizonDays` (null = no fence), `forecastConsumptionBackwardPeriods` / `forecastConsumptionForwardPeriods` (defaults 4 / 1), `mrpRunTime` (TIME; null = every 3 hours — `useMrpScheduleDescription` in `~/hooks` renders it). Nav: `useSettingsSubmodules.tsx` → `path.to.planningSettings` (`/x/settings/planning`).
diff --git a/apps/erp/app/modules/settings/settings.server.ts b/apps/erp/app/modules/settings/settings.server.ts
index 4716b4a4c9..5378308f51 100644
--- a/apps/erp/app/modules/settings/settings.server.ts
+++ b/apps/erp/app/modules/settings/settings.server.ts
@@ -5,6 +5,13 @@
import { bustApiKeyCache } from "@carbon/auth/auth.server";
import { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database, Json } from "@carbon/database";
+import { activeJobStatuses } from "@carbon/database";
+import type { Kysely, KyselyDatabase } from "@carbon/database/client";
+import {
+ getPullFromLocations,
+ missingPullFromLocations,
+ PULLED_ITEM_TYPES
+} from "@carbon/database/strict-backflush";
import {
getIntegrationConfigById,
getIntegrationIdsByRole,
@@ -19,8 +26,13 @@ import { patchRampSettings } from "@carbon/ee/ramp.server";
import { redis } from "@carbon/kv";
import { getLogger } from "@carbon/logger";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { sql } from "kysely";
import type { z } from "zod";
-import type { Integration } from "~/modules/settings/types";
+import type {
+ Integration,
+ JobMissingStorageUnit,
+ MethodMissingPullFrom
+} from "~/modules/settings/types";
import { sanitize } from "~/utils/supabase";
import { oeeDevicesCacheKey } from "./oee-devices-cache";
import type { customFieldValidator } from "./settings.models";
@@ -867,3 +879,243 @@ export async function getSyncOperationReadableIds(
return Object.fromEntries(results.flat());
}
+
+// Strict backflush leaves Active methods and released jobs as they are. The
+// Settings → Items card counts the ones with a gap, and its drawers list them.
+// Both read the same query, so a count and its drawer cannot disagree. The
+// filters are the SQL form of `needsPullFrom` (@carbon/database/strict-backflush;
+// a null tracking type counts as stocked there too), so a count is one
+// statement — the card re-runs on every drawer search, sort and page. Kysely,
+// not PostgREST: a company's lines can pass the 1000-row cap.
+
+// Active BoM lines with no Pull From at one of `locationIds`.
+function methodLinesMissingPullFrom(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ locationIds: string[]
+) {
+ return db
+ .selectFrom("methodMaterial")
+ .innerJoin("makeMethod", (join) =>
+ join
+ .onRef("makeMethod.id", "=", "methodMaterial.makeMethodId")
+ .on("makeMethod.companyId", "=", companyId)
+ .on("makeMethod.status", "=", "Active")
+ )
+ .innerJoin("item as component", (join) =>
+ join
+ .onRef("component.id", "=", "methodMaterial.itemId")
+ .on("component.companyId", "=", companyId)
+ )
+ .where("methodMaterial.companyId", "=", companyId)
+ .where("methodMaterial.methodType", "!=", "Make to Order")
+ .where("methodMaterial.itemType", "in", [...PULLED_ITEM_TYPES])
+ .where(
+ sql<boolean>`COALESCE("component"."itemTrackingType", 'Inventory') <> 'Non-Inventory'`
+ )
+ .where(
+ sql<boolean>`EXISTS (SELECT 1 FROM unnest(${locationIds}::text[]) AS loc WHERE COALESCE("methodMaterial"."storageUnitIds" ->> loc, '') = '')`
+ );
+}
+
+// Lines on open jobs that the job's next backflush would refuse: no storage
+// unit, stocked, not batch or serial (their issue flow is unchanged), still
+// something to issue, at a location where strict backflush applies.
+function jobLinesMissingStorageUnit(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ locationIds: string[]
+) {
+ return db
+ .selectFrom("jobMaterial")
+ .innerJoin("job", (join) =>
+ join
+ .onRef("job.id", "=", "jobMaterial.jobId")
+ .on("job.companyId", "=", companyId)
+ .on("job.status", "in", [...activeJobStatuses])
+ )
+ .innerJoin("item as component", (join) =>
+ join
+ .onRef("component.id", "=", "jobMaterial.itemId")
+ .on("component.companyId", "=", companyId)
+ )
+ .where("job.locationId", "in", locationIds)
+ .where("jobMaterial.companyId", "=", companyId)
+ .where("jobMaterial.storageUnitId", "is", null)
+ .where("jobMaterial.methodType", "!=", "Make to Order")
+ .where("jobMaterial.itemType", "in", [...PULLED_ITEM_TYPES])
+ .where("jobMaterial.requiresBatchTracking", "=", false)
+ .where("jobMaterial.requiresSerialTracking", "=", false)
+ .where("jobMaterial.quantityToIssue", ">", 0)
+ .where(
+ sql<boolean>`COALESCE("component"."itemTrackingType", 'Inventory') <> 'Non-Inventory'`
+ );
+}
+
+export async function getStrictBackflushGapCounts(
+ db: Kysely<KyselyDatabase>,
+ companyId: string
+): Promise<{
+ data: { methods: number; jobs: number } | null;
+ error: Error | null;
+}> {
+ try {
+ // One query at a time: each would otherwise take its own pooled connection.
+ const locationIds = (await getPullFromLocations(db, companyId)).map(
+ (location) => location.id
+ );
+ if (locationIds.length === 0) {
+ return { data: { methods: 0, jobs: 0 }, error: null };
+ }
+ const methods = await methodLinesMissingPullFrom(db, companyId, locationIds)
+ .select(
+ sql<string>`count(DISTINCT "methodMaterial"."makeMethodId")`.as("count")
+ )
+ .executeTakeFirst();
+ const jobs = await jobLinesMissingStorageUnit(db, companyId, locationIds)
+ .select(sql<string>`count(DISTINCT "job"."id")`.as("count"))
+ .executeTakeFirst();
+ return {
+ data: {
+ methods: Number(methods?.count ?? 0),
+ jobs: Number(jobs?.count ?? 0)
+ },
+ error: null
+ };
+ } catch (error) {
+ return { data: null, error: error as Error };
+ }
+}
+
+export async function getActiveMethodsMissingPullFrom(
+ db: Kysely<KyselyDatabase>,
+ companyId: string
+): Promise<{ data: MethodMissingPullFrom[] | null; error: Error | null }> {
+ try {
+ const locations = await getPullFromLocations(db, companyId);
+ if (locations.length === 0) return { data: [], error: null };
+ const locationIds = locations.map((location) => location.id);
+ const locationName = new Map(
+ locations.map((location) => [location.id, location.name])
+ );
+
+ const lines = await methodLinesMissingPullFrom(db, companyId, locationIds)
+ .innerJoin("item as parent", (join) =>
+ join
+ .onRef("parent.id", "=", "makeMethod.itemId")
+ .on("parent.companyId", "=", companyId)
+ )
+ .select([
+ "makeMethod.id as makeMethodId",
+ "makeMethod.version",
+ "parent.id as itemId",
+ "parent.type as itemType",
+ "parent.readableIdWithRevision as readableId",
+ "parent.name",
+ "methodMaterial.storageUnitIds",
+ "component.id as componentId",
+ "component.readableIdWithRevision as componentReadableId"
+ ])
+ .execute();
+
+ const methods = new Map<
+ string,
+ Omit<MethodMissingPullFrom, "materials" | "locations"> & {
+ materials: Set<string>;
+ locations: Set<string>;
+ }
+ >();
+ for (const line of lines) {
+ const method = methods.get(line.makeMethodId) ?? {
+ makeMethodId: line.makeMethodId,
+ itemId: line.itemId,
+ itemType: line.itemType,
+ readableId: line.readableId ?? line.itemId,
+ name: line.name,
+ version: Number(line.version),
+ materials: new Set<string>(),
+ locations: new Set<string>()
+ };
+ method.materials.add(line.componentReadableId ?? line.componentId);
+ for (const id of missingPullFromLocations(
+ line.storageUnitIds,
+ locationIds
+ ))
+ method.locations.add(locationName.get(id) ?? id);
+ methods.set(line.makeMethodId, method);
+ }
+
+ return {
+ data: [...methods.values()]
+ .map((method) => ({
+ ...method,
+ materials: [...method.materials].sort(),
+ locations: [...method.locations].sort()
+ }))
+ .sort((a, b) => a.readableId.localeCompare(b.readableId)),
+ error: null
+ };
+ } catch (error) {
+ return { data: null, error: error as Error };
+ }
+}
+
+export async function getOpenJobsMissingStorageUnit(
+ db: Kysely<KyselyDatabase>,
+ companyId: string
+): Promise<{ data: JobMissingStorageUnit[] | null; error: Error | null }> {
+ try {
+ const locationIds = (await getPullFromLocations(db, companyId)).map(
+ (location) => location.id
+ );
+ if (locationIds.length === 0) return { data: [], error: null };
+
+ const lines = await jobLinesMissingStorageUnit(db, companyId, locationIds)
+ .leftJoin("item as jobItem", (join) =>
+ join
+ .onRef("jobItem.id", "=", "job.itemId")
+ .on("jobItem.companyId", "=", companyId)
+ )
+ .leftJoin("location", (join) =>
+ join
+ .onRef("location.id", "=", "job.locationId")
+ .on("location.companyId", "=", companyId)
+ )
+ .select([
+ "job.id",
+ "job.jobId",
+ "job.status",
+ "jobItem.readableIdWithRevision as readableId",
+ "location.name as locationName",
+ "component.id as componentId",
+ "component.readableIdWithRevision as componentReadableId"
+ ])
+ .execute();
+
+ const jobs = new Map<
+ string,
+ Omit<JobMissingStorageUnit, "materials"> & { materials: Set<string> }
+ >();
+ for (const line of lines) {
+ const job = jobs.get(line.id) ?? {
+ id: line.id,
+ jobId: line.jobId,
+ status: line.status,
+ readableId: line.readableId,
+ locationName: line.locationName,
+ materials: new Set<string>()
+ };
+ job.materials.add(line.componentReadableId ?? line.componentId);
+ jobs.set(line.id, job);
+ }
+
+ return {
+ data: [...jobs.values()]
+ .map((job) => ({ ...job, materials: [...job.materials].sort() }))
+ .sort((a, b) => a.jobId.localeCompare(b.jobId)),
+ error: null
+ };
+ } catch (error) {
+ return { data: null, error: error as Error };
+ }
+}
diff --git a/apps/erp/app/modules/settings/settings.service.ts b/apps/erp/app/modules/settings/settings.service.ts
index eb99d78882..6c8dfce041 100644
--- a/apps/erp/app/modules/settings/settings.service.ts
+++ b/apps/erp/app/modules/settings/settings.service.ts
@@ -6,12 +6,6 @@ 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,
@@ -1248,205 +1242,6 @@ export async function updatePreventNegativeBackflushSetting(
.eq("id", companyId);
}
-export type MethodMissingPullFrom = {
- makeMethodId: string;
- itemId: string;
- itemType: string;
- readableId: string;
- name: string;
- version: number;
- /** The pulled, stocked materials on this version with a gap. */
- materials: string[];
- /** The locations at least one of those materials has no Pull From at. */
- locations: string[];
-};
-
-// Strict backflush: every Active make method with a pulled, stocked line that
-// has no Pull From at a location with an active work center and a storage
-// unit. Turning the setting on leaves these methods Active; the settings card
-// counts them and its drawer 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: MethodMissingPullFrom[] | null; error: Error | null }> {
- try {
- // One query at a time: run together, each would take its own pooled
- // connection, and opening one costs more than these reads do.
- const lines = await 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",
- "makeMethod.version",
- "parent.id as itemId",
- "parent.type as itemType",
- "parent.readableIdWithRevision as readableId",
- "parent.name",
- "methodMaterial.methodType",
- "methodMaterial.itemType as lineItemType",
- "methodMaterial.storageUnitIds",
- "component.itemTrackingType",
- "component.id as componentId",
- "component.readableIdWithRevision as componentReadableId"
- ])
- .execute();
- const locations = await getPullFromLocations(db, companyId);
-
- const locationIds = locations.map((location) => location.id);
- const locationName = new Map(
- locations.map((location) => [location.id, location.name])
- );
- const methods = new Map<
- string,
- Omit<MethodMissingPullFrom, "materials" | "locations"> & {
- materials: Set<string>;
- locations: Set<string>;
- }
- >();
- for (const line of lines) {
- if (
- !needsPullFrom({
- methodType: line.methodType,
- itemType: line.lineItemType,
- itemTrackingType: line.itemTrackingType
- })
- )
- continue;
- const missing = missingPullFromLocations(
- line.storageUnitIds,
- locationIds
- );
- if (missing.length === 0) continue;
-
- const method = methods.get(line.makeMethodId) ?? {
- makeMethodId: line.makeMethodId,
- itemId: line.itemId,
- itemType: line.itemType,
- readableId: line.readableId ?? line.itemId,
- name: line.name,
- version: Number(line.version),
- materials: new Set<string>(),
- locations: new Set<string>()
- };
- method.materials.add(line.componentReadableId ?? line.componentId);
- for (const id of missing)
- method.locations.add(locationName.get(id) ?? id);
- methods.set(line.makeMethodId, method);
- }
-
- return {
- data: [...methods.values()]
- .map((method) => ({
- ...method,
- materials: [...method.materials].sort(),
- locations: [...method.locations].sort()
- }))
- .sort((a, b) => a.readableId.localeCompare(b.readableId)),
- error: null
- };
- } catch (error) {
- return { data: null, error: error as Error };
- }
-}
-
-export type JobMissingStorageUnit = {
- id: string;
- jobId: string;
- status: Database["public"]["Enums"]["jobStatus"];
- readableId: string | null;
- locationName: string | null;
- /** The pulled, stocked materials on this job with no storage unit. */
- materials: string[];
-};
-
-// The jobs already on the floor (released before strict backflush was turned
-// on, or edited since) that have a pulled, stocked line with no storage unit.
-// Release refuses such a job, but these are past release — their next
-// backflush will be refused instead, so the settings card counts them and its
-// drawer lists them.
-const OPEN_JOB_STATUSES = ["Ready", "In Progress", "Paused"] as const;
-
-export async function getOpenJobsMissingStorageUnit(
- db: Kysely<KyselyDatabase>,
- companyId: string
-): Promise<{ data: JobMissingStorageUnit[] | null; error: Error | null }> {
- try {
- const lines = await db
- .selectFrom("jobMaterial")
- .innerJoin("job", (join) =>
- join
- .onRef("job.id", "=", "jobMaterial.jobId")
- .on("job.companyId", "=", companyId)
- .on("job.status", "in", [...OPEN_JOB_STATUSES])
- )
- .innerJoin("item as component", "component.id", "jobMaterial.itemId")
- .leftJoin("item as jobItem", "jobItem.id", "job.itemId")
- .leftJoin("location", "location.id", "job.locationId")
- .where("jobMaterial.companyId", "=", companyId)
- .where("jobMaterial.storageUnitId", "is", null)
- .where("jobMaterial.methodType", "!=", "Make to Order")
- .where("jobMaterial.itemType", "in", [...PULLED_ITEM_TYPES])
- .select([
- "job.id",
- "job.jobId",
- "job.status",
- "jobItem.readableIdWithRevision as readableId",
- "location.name as locationName",
- "jobMaterial.methodType",
- "jobMaterial.itemType",
- "component.itemTrackingType",
- "component.id as componentId",
- "component.readableIdWithRevision as componentReadableId"
- ])
- .execute();
-
- const jobs = new Map<
- string,
- Omit<JobMissingStorageUnit, "materials"> & { materials: Set<string> }
- >();
- for (const line of lines) {
- if (
- !needsPullFrom({
- methodType: line.methodType,
- itemType: line.itemType,
- itemTrackingType: line.itemTrackingType
- })
- )
- continue;
- const job = jobs.get(line.id) ?? {
- id: line.id,
- jobId: line.jobId,
- status: line.status,
- readableId: line.readableId,
- locationName: line.locationName,
- materials: new Set<string>()
- };
- job.materials.add(line.componentReadableId ?? line.componentId);
- jobs.set(line.id, job);
- }
-
- return {
- data: [...jobs.values()]
- .map((job) => ({ ...job, materials: [...job.materials].sort() }))
- .sort((a, b) => a.jobId.localeCompare(b.jobId)),
- 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/modules/settings/types.ts b/apps/erp/app/modules/settings/types.ts
index a282c8c4c7..7915bcd4f3 100644
--- a/apps/erp/app/modules/settings/types.ts
+++ b/apps/erp/app/modules/settings/types.ts
@@ -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 type { Database } from "@carbon/database";
import type {
getApiKeys,
getCompanies,
@@ -49,3 +50,28 @@ export type ItemSerialSequence = NonNullable<
export type Webhook = NonNullable<
Awaited<ReturnType<typeof getWebhooks>>["data"]
>[number];
+
+/** An Active make method with a pulled, stocked line missing a Pull From. */
+export type MethodMissingPullFrom = {
+ makeMethodId: string;
+ itemId: string;
+ itemType: string;
+ readableId: string;
+ name: string;
+ version: number;
+ /** The pulled, stocked materials on this version with a gap. */
+ materials: string[];
+ /** The locations at least one of those materials has no Pull From at. */
+ locations: string[];
+};
+
+/** An open job whose next backflush strict backflush would refuse. */
+export type JobMissingStorageUnit = {
+ id: string;
+ jobId: string;
+ status: Database["public"]["Enums"]["jobStatus"];
+ readableId: string | null;
+ locationName: string | null;
+ /** The materials the backflush would refuse: no storage unit. */
+ materials: string[];
+};
diff --git a/apps/erp/app/modules/settings/ui/StrictBackflush/StrictBackflushTables.tsx b/apps/erp/app/modules/settings/ui/StrictBackflush/StrictBackflushTables.tsx
index d27abe2040..0eddc2dac0 100644
--- a/apps/erp/app/modules/settings/ui/StrictBackflush/StrictBackflushTables.tsx
+++ b/apps/erp/app/modules/settings/ui/StrictBackflush/StrictBackflushTables.tsx
@@ -25,10 +25,7 @@ import { Hyperlink, Table } from "~/components";
import { Enumerable } from "~/components/Enumerable";
import JobStatus from "~/modules/production/ui/Jobs/JobStatus";
import { path } from "~/utils/path";
-import type {
- JobMissingStorageUnit,
- MethodMissingPullFrom
-} from "../../settings.service";
+import type { JobMissingStorageUnit, MethodMissingPullFrom } from "../../types";
// The make-method page of a method's item, by item type. Only Parts, Tools and
// Services carry make methods with their own route.
@@ -68,20 +65,22 @@ function PartList({ parts, label }: { parts: string[]; label: string }) {
</span>
))}
{more > 0 && (
- // Modal: the drawer's scroll lock blocks the wheel outside the drawer,
- // and the popover renders in a portal outside it. A modal popover
- // takes the lock itself, so its list scrolls.
- <Popover modal>
+ <Popover>
<PopoverTrigger asChild>
<Button variant="link" size="sm" className="text-muted-foreground">
{t`+${more} more`}
</Button>
</PopoverTrigger>
+ {/* Rendered outside the drawer, whose scroll lock swallows the
+ wheel and touch events: stop them here, or the list cannot
+ scroll (conventions-ui.md, "Popovers inside Drawers"). */}
<PopoverContent
align="start"
collisionPadding={8}
className="w-64 p-0"
aria-label={label}
+ onWheel={(event) => event.stopPropagation()}
+ onTouchMove={(event) => event.stopPropagation()}
>
{/* A phone's sheet titles itself from aria-label. */}
{!isPhone && (
@@ -92,7 +91,7 @@ function PartList({ parts, label }: { parts: string[]; label: string }) {
</span>
</PopoverHeader>
)}
- <ul className="max-h-72 overflow-y-auto py-1 text-sm">
+ <ul className="max-h-72 overflow-y-auto py-1 text-sm scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
{parts.map((part) => (
<li key={part} className="truncate px-4 py-1" title={part}>
{part}
diff --git a/apps/erp/app/routes/api+/items.pull-from-locations.ts b/apps/erp/app/routes/api+/items.pull-from-locations.ts
new file mode 100644
index 0000000000..57edabc75f
--- /dev/null
+++ b/apps/erp/app/routes/api+/items.pull-from-locations.ts
@@ -0,0 +1,33 @@
+// 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 { requirePermissions } from "@carbon/auth/auth.server";
+import { getPullFromLocations } from "@carbon/database/strict-backflush";
+import { getLogger } from "@carbon/logger";
+import { cachedClientLoader, RefreshRate } from "@carbon/query/cache";
+import type { LoaderFunctionArgs } from "react-router";
+import { getDatabaseClient } from "~/services/database.server";
+
+const logger = getLogger("erp", "items-pull-from-locations");
+
+// Strict backflush: the locations a pulled line needs a Pull From at (an
+// active work center and an active storage unit). The BoM badges read it, so
+// they mark the same lines activation refuses.
+export async function loader({ request }: LoaderFunctionArgs) {
+ const { companyId } = await requirePermissions(request, {});
+ try {
+ const locations = await getPullFromLocations(
+ getDatabaseClient(),
+ companyId
+ );
+ return { data: locations.map((location) => location.id), error: null };
+ } catch (error) {
+ logger.error("Failed to read pull-from locations", { companyId, error });
+ return { data: null, error: "Failed to read pull-from locations" };
+ }
+}
+
+export const clientLoader = cachedClientLoader<typeof loader>({
+ staleTime: RefreshRate.Medium
+});
diff --git a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx b/apps/erp/app/routes/x+/items+/methods+/version.new.tsx
index d5d30b17ba..1e470ae6ca 100644
--- a/apps/erp/app/routes/x+/items+/methods+/version.new.tsx
+++ b/apps/erp/app/routes/x+/items+/methods+/version.new.tsx
@@ -6,6 +6,11 @@ import { assertIsPost, error } 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 {
+ activationRefusalMessage,
+ getMethodPartsMissingPullFrom,
+ getStrictBackflushSettings
+} from "@carbon/database/strict-backflush";
import { validationError, validator } from "@carbon/form";
import { redirect } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
@@ -37,6 +42,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
// spinning fresh method versions at Done and never stages/reserves a pending
// revision, so there is nothing for an open CO to lock against.
+ // A single Draft version becomes Active as the new one is created. Strict
+ // backflush refuses that activation the way the Activate action does
+ // (`convert` methodVersionToActive), before anything is written.
+ if (validation.data.activeVersionId) {
+ const db = getDatabaseClient();
+ const { strict } = await getStrictBackflushSettings(db, companyId);
+ if (strict) {
+ const parts = await getMethodPartsMissingPullFrom(db, {
+ makeMethodId: validation.data.activeVersionId,
+ companyId
+ });
+ if (parts.length > 0) {
+ return data(
+ { id: null },
+ await flash(request, error(null, activationRefusalMessage(parts)))
+ );
+ }
+ }
+ }
+
const insertMethodOperation = await upsertMakeMethodVersion(client, {
...validation.data,
companyId,
diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
index 7f24284980..92fb0a3767 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx
@@ -59,11 +59,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ let readiness: Awaited<ReturnType<typeof getJobReleaseReadiness>> | null =
+ null;
if (status === "Ready") {
const { data } = await client
.from("job")
.select(
- "quantity, salesOrderLineId, fixedAssetClassId, fixedAssetId, item(itemTrackingType, itemReplenishment(manufacturingBlocked))"
+ "status, quantity, salesOrderLineId, fixedAssetClassId, fixedAssetId, item(itemTrackingType, itemReplenishment(manufacturingBlocked))"
)
.eq("id", id)
.single();
@@ -105,42 +107,56 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
}
+
+ // Releasing (the dialog, or a plain post of Ready on a Draft or Planned
+ // job — the API and MCP path): strict backflush refuses a pulled line with
+ // no storage unit on every path. Resuming a Paused job is not a release.
+ if (
+ shouldSchedule ||
+ data?.status === "Draft" ||
+ data?.status === "Planned"
+ ) {
+ readiness = await getJobReleaseReadiness(client, [id], companyId);
+ if (readiness.error) {
+ throw redirect(
+ requestReferrer(request) ?? path.to.job(id),
+ await flash(request, error(readiness.error, "Failed to validate job"))
+ );
+ }
+
+ 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)
+ )}`
+ )
+ )
+ );
+ }
+ }
}
// The Release dialog: the shared release path (also run by batch release),
// re-checking what the dialog checked, then one schedule run for the location.
if (status === "Ready" && shouldSchedule) {
- const readiness = await getJobReleaseReadiness(client, [id], companyId);
- const missing = readiness.data?.jobs[0]?.missingAssemblies ?? [];
- if (readiness.error || missing.length > 0) {
- throw redirect(
- requestReferrer(request) ?? path.to.job(id),
- await flash(
- request,
- error(
- readiness.error,
- readiness.error
- ? "Failed to validate job"
- : `Assign an operation to each assembly before releasing: ${missing
- .map((m) => m.description)
- .join(", ")}`
- )
- )
- );
- }
-
- const withoutStorageUnit =
- readiness.data?.jobs[0]?.materialsWithoutStorageUnit ?? [];
- if (withoutStorageUnit.length > 0) {
+ const missing = readiness?.data?.jobs[0]?.missingAssemblies ?? [];
+ if (missing.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)
- )}`
+ `Assign an operation to each assembly before releasing: ${missing
+ .map((m) => m.description)
+ .join(", ")}`
)
)
);
diff --git a/apps/erp/app/routes/x+/settings+/items.jobs-missing-storage-unit.tsx b/apps/erp/app/routes/x+/settings+/items.jobs-missing-storage-unit.tsx
index cb5b6381f6..b470cfae31 100644
--- a/apps/erp/app/routes/x+/settings+/items.jobs-missing-storage-unit.tsx
+++ b/apps/erp/app/routes/x+/settings+/items.jobs-missing-storage-unit.tsx
@@ -2,7 +2,9 @@
// 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 { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
import { getLogger } from "@carbon/logger";
import {
Drawer,
@@ -11,13 +13,12 @@ import {
DrawerHeader,
DrawerTitle
} from "@carbon/react";
+import { redirect } from "@carbon/utils";
import { Trans } from "@lingui/react/macro";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData, useNavigate } from "react-router";
-import {
- getOpenJobsMissingStorageUnit,
- JobsMissingStorageUnitTable
-} from "~/modules/settings";
+import { JobsMissingStorageUnitTable } from "~/modules/settings";
+import { getOpenJobsMissingStorageUnit } from "~/modules/settings/settings.server";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";
import { pageInMemory } from "~/utils/query";
@@ -40,12 +41,26 @@ export async function loader({ request }: LoaderFunctionArgs) {
companyId,
error: jobs.error
});
+ // An empty table would read as "nothing to fix".
+ throw redirect(
+ path.to.itemsSettings,
+ await flash(
+ request,
+ error(jobs.error, "Failed to load the open jobs missing a storage unit")
+ )
+ );
}
const page = pageInMemory(
jobs.data ?? [],
new URL(request.url).searchParams,
- (job) => [job.jobId, job.readableId, job.locationName, ...job.materials]
+ (job) => [
+ job.jobId,
+ job.status,
+ job.readableId,
+ job.locationName,
+ ...job.materials
+ ]
);
return { jobs: page.rows, count: page.count };
}
diff --git a/apps/erp/app/routes/x+/settings+/items.methods-missing-pull-from.tsx b/apps/erp/app/routes/x+/settings+/items.methods-missing-pull-from.tsx
index 09754221d7..77b13281e8 100644
--- a/apps/erp/app/routes/x+/settings+/items.methods-missing-pull-from.tsx
+++ b/apps/erp/app/routes/x+/settings+/items.methods-missing-pull-from.tsx
@@ -2,7 +2,9 @@
// 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 { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
import { getLogger } from "@carbon/logger";
import {
Drawer,
@@ -11,13 +13,12 @@ import {
DrawerHeader,
DrawerTitle
} from "@carbon/react";
+import { redirect } from "@carbon/utils";
import { Trans } from "@lingui/react/macro";
import type { LoaderFunctionArgs } from "react-router";
import { useLoaderData, useNavigate } from "react-router";
-import {
- getActiveMethodsMissingPullFrom,
- MethodsMissingPullFromTable
-} from "~/modules/settings";
+import { MethodsMissingPullFromTable } from "~/modules/settings";
+import { getActiveMethodsMissingPullFrom } from "~/modules/settings/settings.server";
import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";
import { pageInMemory } from "~/utils/query";
@@ -40,12 +41,25 @@ export async function loader({ request }: LoaderFunctionArgs) {
companyId,
error: methods.error
});
+ // An empty table would read as "nothing to fix".
+ throw redirect(
+ path.to.itemsSettings,
+ await flash(
+ request,
+ error(methods.error, "Failed to load the methods missing a Pull From")
+ )
+ );
}
const page = pageInMemory(
methods.data ?? [],
new URL(request.url).searchParams,
- (method) => [method.readableId, method.name, ...method.materials]
+ (method) => [
+ method.readableId,
+ method.name,
+ ...method.materials,
+ ...method.locations
+ ]
);
return { methods: page.rows, count: page.count };
}
diff --git a/apps/erp/app/routes/x+/settings+/items.tsx b/apps/erp/app/routes/x+/settings+/items.tsx
index 5fc0910ea1..7cf9cae091 100644
--- a/apps/erp/app/routes/x+/settings+/items.tsx
+++ b/apps/erp/app/routes/x+/settings+/items.tsx
@@ -33,9 +33,7 @@ import { SettingsPage, SettingsPageHeading } from "~/components/SettingsPage";
import SettingsSectionHeader from "~/components/SettingsSectionHeader";
import { plmReleaseControl } from "~/modules/items";
import {
- getActiveMethodsMissingPullFrom,
getCompanySettings,
- getOpenJobsMissingStorageUnit,
plmReleaseControlValidator,
updateAllowLowercaseItemIdsSetting,
updateBomExplorerReadableIdSetting,
@@ -45,6 +43,7 @@ import {
updatePreventNegativeBackflushSetting,
updateRequireBackflushStorageUnitSetting
} from "~/modules/settings";
+import { getStrictBackflushGapCounts } from "~/modules/settings/settings.server";
import { getDatabaseClient } from "~/services/database.server";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -73,34 +72,29 @@ export async function loader({ request }: LoaderFunctionArgs) {
// Strict backflush leaves Active methods and released jobs as they are; the
// card counts the ones with a gap and links to a drawer listing them all.
- let methodsMissingPullFrom: number | null = null;
- let jobsMissingStorageUnit: number | null = null;
+ // `gaps` is null while the setting is off; `gapsError` says the count failed,
+ // so the card never reads as clean when it could not look.
+ let gaps: { methods: number; jobs: number } | null = null;
+ let gapsError = false;
if (companySettings.data.requireBackflushStorageUnit) {
- const db = getDatabaseClient();
- // One at a time: each read would otherwise take its own pooled connection.
- const methods = await getActiveMethodsMissingPullFrom(db, companyId);
- if (methods.error) {
- logger.error("Failed to read methods missing a Pull From", {
- companyId,
- error: methods.error
- });
- }
- methodsMissingPullFrom = methods.data?.length ?? null;
-
- const jobs = await getOpenJobsMissingStorageUnit(db, companyId);
- if (jobs.error) {
- logger.error("Failed to read open jobs missing a storage unit", {
+ const counts = await getStrictBackflushGapCounts(
+ getDatabaseClient(),
+ companyId
+ );
+ if (counts.error) {
+ logger.error("Failed to count strict backflush gaps", {
companyId,
- error: jobs.error
+ error: counts.error
});
+ gapsError = true;
}
- jobsMissingStorageUnit = jobs.data?.length ?? null;
+ gaps = counts.data;
}
return {
companySettings: companySettings.data,
- methodsMissingPullFrom,
- jobsMissingStorageUnit
+ gaps,
+ gapsError
};
}
@@ -201,8 +195,10 @@ export async function action({ request }: ActionFunctionArgs) {
export default function ItemsSettingsRoute() {
const { t } = useLingui();
- const { companySettings, methodsMissingPullFrom, jobsMissingStorageUnit } =
- useLoaderData<typeof loader>();
+ const { companySettings, gaps, gapsError } = useLoaderData<typeof loader>();
+ // Named for the Plural messages' placeholders.
+ const methodsMissingPullFrom = gaps?.methods ?? 0;
+ const jobsMissingStorageUnit = gaps?.jobs ?? 0;
const fetcher = useFetcher<typeof action>();
const releaseControlLabels: Record<
@@ -495,50 +491,56 @@ export default function ItemsSettingsRoute() {
</span>
</VStack>
<Switch
- checked={companySettings.preventNegativeBackflush ?? true}
+ checked={companySettings.preventNegativeBackflush}
onCheckedChange={handlePreventNegativeBackflushToggle}
disabled={
isToggling || !companySettings.requireBackflushStorageUnit
}
/>
</HStack>
- {methodsMissingPullFrom !== null &&
- methodsMissingPullFrom > 0 && (
- <GapRow
- to={path.to.itemsSettingsMethodsMissingPullFrom}
- label={
- <Plural
- value={methodsMissingPullFrom}
- one="# active method has materials with no Pull From"
- other="# active methods have materials with no Pull From"
- />
- }
- description={
- <Trans>
- Set a Pull From on each one through a new version.
- </Trans>
- }
- />
- )}
- {jobsMissingStorageUnit !== null &&
- jobsMissingStorageUnit > 0 && (
- <GapRow
- to={path.to.itemsSettingsJobsMissingStorageUnit}
- label={
- <Plural
- value={jobsMissingStorageUnit}
- one="# open job has materials with no storage unit"
- other="# open jobs have materials with no storage unit"
- />
- }
- description={
- <Trans>
- Their next backflush will be refused until each material
- has a storage unit.
- </Trans>
- }
- />
- )}
+ {gapsError && (
+ <p className="w-full border-t pt-4 text-sm text-destructive">
+ <Trans>
+ Could not check for active methods and open jobs with gaps.
+ Reload the page to try again.
+ </Trans>
+ </p>
+ )}
+ {methodsMissingPullFrom > 0 && (
+ <GapRow
+ to={path.to.itemsSettingsMethodsMissingPullFrom}
+ label={
+ <Plural
+ value={methodsMissingPullFrom}
+ one="# active method has materials with no Pull From"
+ other="# active methods have materials with no Pull From"
+ />
+ }
+ description={
+ <Trans>
+ Set a Pull From on each one through a new version.
+ </Trans>
+ }
+ />
+ )}
+ {jobsMissingStorageUnit > 0 && (
+ <GapRow
+ to={path.to.itemsSettingsJobsMissingStorageUnit}
+ label={
+ <Plural
+ value={jobsMissingStorageUnit}
+ one="# open job has materials with no storage unit"
+ other="# open jobs have materials with no storage unit"
+ />
+ }
+ description={
+ <Trans>
+ Their next backflush will be refused until each material
+ has a storage unit.
+ </Trans>
+ }
+ />
+ )}
</VStack>
</CardContent>
</Card>
diff --git a/apps/erp/app/utils/page-in-memory.test.ts b/apps/erp/app/utils/page-in-memory.test.ts
new file mode 100644
index 0000000000..c3dcb363e7
--- /dev/null
+++ b/apps/erp/app/utils/page-in-memory.test.ts
@@ -0,0 +1,93 @@
+// 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, vi } from "vitest";
+
+// @carbon/auth's barrel pulls in a Lingui macro plain vitest cannot run (see
+// query.test.ts). Only the URL number parser is used here, so stand it in.
+vi.mock("@carbon/auth", () => ({
+ badRequest: vi.fn(),
+ parseNumberFromUrlParam: (
+ params: URLSearchParams,
+ key: string,
+ fallback: number
+ ) => {
+ const value = params.get(key);
+ return value === null ? fallback : Number(value);
+ }
+}));
+
+const { pageInMemory } = await import("./query");
+
+type Row = { id: string; version: number; materials: string[] };
+
+const rows: Row[] = [
+ { id: "PART-10", version: 2, materials: ["BOLT"] },
+ { id: "PART-2", version: 10, materials: ["NUT", "WASHER"] },
+ { id: "PART-1", version: 2, materials: ["SCREW"] }
+];
+
+const page = (query: string) =>
+ pageInMemory(rows, new URLSearchParams(query), (row) => [
+ row.id,
+ ...row.materials
+ ]);
+
+describe("pageInMemory", () => {
+ it("keeps the input order with no sort", () => {
+ expect(page("").rows.map((row) => row.id)).toEqual([
+ "PART-10",
+ "PART-2",
+ "PART-1"
+ ]);
+ });
+
+ it("searches every searchable value, shown or not", () => {
+ const result = page("search=washer");
+ expect(result.rows.map((row) => row.id)).toEqual(["PART-2"]);
+ expect(result.count).toBe(1);
+ });
+
+ it("sorts ids by their numbers, not character by character", () => {
+ expect(page("sort=id:asc").rows.map((row) => row.id)).toEqual([
+ "PART-1",
+ "PART-2",
+ "PART-10"
+ ]);
+ });
+
+ it("sorts numbers as numbers and an array by its first entry", () => {
+ expect(page("sort=version:desc").rows.map((row) => row.id)).toEqual([
+ "PART-2",
+ "PART-10",
+ "PART-1"
+ ]);
+ expect(page("sort=materials:asc").rows.map((row) => row.id)).toEqual([
+ "PART-10",
+ "PART-2",
+ "PART-1"
+ ]);
+ });
+
+ it("breaks a tie on the first sort with the second", () => {
+ expect(
+ page("sort=version:asc&sort=id:asc").rows.map((row) => row.id)
+ ).toEqual(["PART-1", "PART-10", "PART-2"]);
+ });
+
+ it("leaves rows in place for a sort key no row has", () => {
+ expect(page("sort=missing:asc").rows.map((row) => row.id)).toEqual([
+ "PART-10",
+ "PART-2",
+ "PART-1"
+ ]);
+ });
+
+ it("pages after filtering and counts every match", () => {
+ const result = page("limit=20&offset=2");
+ expect(result.rows.map((row) => row.id)).toEqual(["PART-1"]);
+ expect(result.count).toBe(3);
+ expect(page("offset=10").rows).toEqual([]);
+ });
+});
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 439f261be9..31cb4e0ee6 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -268,6 +268,7 @@ export const path = {
processes: `${api}/resources/processes`,
productionKpi: (key: string) =>
generatePath(`${api}/production/kpi/${key}`),
+ pullFromLocations: `${api}/items/pull-from-locations`,
purchaseInvoice: (id: string) =>
generatePath(`${api}/purchase-invoice/${id}`),
purchaseOrderFinalize: (id: string) =>
diff --git a/apps/erp/test/job-release-readiness.test.ts b/apps/erp/test/job-release-readiness.test.ts
index b198547377..5a87fcfad8 100644
--- a/apps/erp/test/job-release-readiness.test.ts
+++ b/apps/erp/test/job-release-readiness.test.ts
@@ -23,7 +23,7 @@ function cappedClient(tables: Record<string, Record<string, unknown>[]>) {
from: (table: string) => {
let rows = tables[table] ?? [];
const chain: Record<string, any> = {};
- for (const method of ["select", "eq", "is", "order"]) {
+ for (const method of ["select", "eq", "is", "order", "limit"]) {
chain[method] = () => chain;
}
chain.in = (column: string, values: string[]) => {
@@ -128,15 +128,20 @@ describe("getJobReleaseReadiness", () => {
]);
});
- it("lists pulled, stocked lines with no storage unit under strict backflush", async () => {
+ // `location` holds the locations the client returns as pull-from locations
+ // (an active work center and storage unit); the stand-in does not evaluate
+ // the embedded filters, so the table lists only those.
+ function strictReadinessTables(pullFromLocationIds: string[]) {
const line = {
jobId: "job-1",
storageUnitId: null,
methodType: "Pull from Inventory",
- itemType: "Part"
+ itemType: "Part",
+ job: { locationId: "loc-plant" }
};
- const { client } = cappedClient({
+ return {
companySettings: [{ requireBackflushStorageUnit: true }],
+ location: pullFromLocationIds.map((id) => ({ id })),
job: [{ id: "job-1", jobId: "J000001", status: "Planned", item: null }],
jobMakeMethod: [{ id: "root", jobId: "job-1" }],
jobOperation: [
@@ -179,7 +184,11 @@ describe("getJobReleaseReadiness", () => {
}
}
]
- });
+ };
+ }
+
+ it("lists pulled, stocked lines with no storage unit under strict backflush", async () => {
+ const { client } = cappedClient(strictReadinessTables(["loc-plant"]));
const { data, error } = await getJobReleaseReadiness(
client,
@@ -193,6 +202,20 @@ describe("getJobReleaseReadiness", () => {
]);
});
+ it("skips a job at a location with no active work center or storage unit", async () => {
+ // Activation never asked for a Pull From there, so release must not.
+ const { client } = cappedClient(strictReadinessTables([]));
+
+ const { data, error } = await getJobReleaseReadiness(
+ client,
+ ["job-1"],
+ "company-1"
+ );
+
+ expect(error).toBeNull();
+ expect(data?.jobs[0]?.materialsWithoutStorageUnit).toEqual([]);
+ });
+
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 bf4ad0232f..68ef7371e9 100644
--- a/apps/mes/app/routes/x+/complete.tsx
+++ b/apps/mes/app/routes/x+/complete.tsx
@@ -20,6 +20,7 @@ import {
finishJobOperation,
insertProductionQuantity
} from "~/services/operations.service";
+import { checkStrictBackflush } from "~/services/quality.server";
import { readOrigin, withOrigin } from "~/utils/origin";
import { path } from "~/utils/path";
@@ -190,6 +191,21 @@ export async function action({ request }: ActionFunctionArgs) {
const newTrackedEntityId = response.data?.newTrackedEntityId as
| string
| undefined;
+ // A refused completion (a strict backflush shortfall) rolled back: print
+ // nothing for it.
+ if (response.error) {
+ return data(
+ {},
+ await flash(request, {
+ ...error(
+ response.error,
+ response.error.message || "Failed to complete job operation"
+ ),
+ flash: "error"
+ })
+ );
+ }
+
// Print the entity that was just completed (from form), not the new reserved one
const completedEntityId = validation.data.trackedEntityId;
@@ -205,19 +221,6 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
- if (response.error) {
- return data(
- {},
- await flash(request, {
- ...error(
- response.error,
- response.error.message || "Failed to complete job operation"
- ),
- flash: "error"
- })
- );
- }
-
if (willBeFinished) {
const finishOperation = await finishJobOperation(
serviceRole,
@@ -335,23 +338,18 @@ export async function action({ request }: ActionFunctionArgs) {
// 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
- });
+ const check = await checkStrictBackflush({
+ jobOperationId: validation.data.jobOperationId,
+ quantity: validation.data.quantity,
+ companyId,
+ userId
+ });
if (check.error) {
return data(
{},
await flash(request, {
- ...error(
- check.error,
- check.error.message || "Failed to issue materials"
- ),
+ ...error(check.error, check.message!),
flash: "error"
})
);
@@ -385,12 +383,14 @@ export async function action({ request }: ActionFunctionArgs) {
});
if (issued.error) {
+ // The units are recorded: say so, or the operator retries and records
+ // them twice.
return data(
{},
await flash(request, {
...error(
issued.error,
- issued.error.message || "Failed to issue materials"
+ `Units completed, but ${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 9701f2e6ac..c7b119bb22 100644
--- a/apps/mes/app/routes/x+/end.$operationId.tsx
+++ b/apps/mes/app/routes/x+/end.$operationId.tsx
@@ -20,6 +20,7 @@ import {
insertProductionQuantity,
isSerialEntityIncompleteForOperation
} from "~/services/operations.service";
+import { checkStrictBackflush } from "~/services/quality.server";
import { path } from "~/utils/path";
const logger = getLogger("mes", "end-operation");
@@ -298,23 +299,18 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
// 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
- });
+ const check = await checkStrictBackflush({
+ jobOperationId: operationId,
+ quantity: quantityToComplete,
+ companyId,
+ userId
+ });
if (check.error) {
return redirect(
path.to.operation(operationId),
await flash(request, {
- ...error(
- check.error,
- check.error.message || "Failed to issue materials"
- ),
+ ...error(check.error, check.message!),
flash: "error"
})
);
@@ -354,12 +350,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
});
if (issued.error) {
+ // The units are recorded: say so, or the operator retries and records
+ // them twice.
return redirect(
path.to.operation(operationId),
await flash(request, {
...error(
issued.error,
- issued.error.message || "Failed to issue materials"
+ `Units completed, but ${issued.error.message || "failed to issue materials"}`
),
flash: "error"
})
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx
index b6aaf7640a..e3829a17f0 100644
--- a/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.complete-passed.tsx
@@ -13,6 +13,7 @@ import { getDatabaseClient } from "~/services/database.server";
import { inspectionCompletePassedValidator } from "~/services/models";
import { returnPickedRemainders } from "~/services/operations.service";
import {
+ checkStrictBackflush,
getInspectionOutcomeState,
getSerialCompletionCandidates,
postBulkCompletion,
@@ -106,6 +107,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
`Passed units (${candidates.length}) exceed the operation's remaining quantity (${state.opRemaining}) — quantities were already recorded from the actions menu`
);
}
+ // Strict backflush: refuse before the first unit completes, not after
+ // some of them.
+ const backflushCheck = await checkStrictBackflush({
+ jobOperationId: state.jobOperationId,
+ quantity: candidates.length,
+ companyId,
+ userId
+ });
+ if (backflushCheck.error) {
+ return fail(backflushCheck.error, backflushCheck.message!);
+ }
const completions = await postSerialCompletions(serviceRole, {
candidates,
jobOperationId: state.jobOperationId,
@@ -145,6 +157,17 @@ export async function action({ request, params }: ActionFunctionArgs) {
return fail(null, "No passed units to complete");
}
+ // Strict backflush: refuse before the production quantity is recorded.
+ const backflushCheck = await checkStrictBackflush({
+ jobOperationId: state.jobOperationId,
+ quantity,
+ companyId,
+ userId
+ });
+ if (backflushCheck.error) {
+ return fail(backflushCheck.error, backflushCheck.message!);
+ }
+
const completion = await postBulkCompletion(serviceRole, client, state, {
quantity,
eventIds,
diff --git a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx
index ccae62b944..4d73b41f29 100644
--- a/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx
+++ b/apps/mes/app/routes/x+/inspection-lot.$id.disposition.tsx
@@ -18,6 +18,7 @@ import {
insertScrapQuantity
} from "~/services/operations.service";
import {
+ checkStrictBackflush,
createInspectionRejectionIssue,
getInspectionOutcomeState,
getSerialCompletionCandidates,
@@ -207,6 +208,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
+ // Strict backflush: completion and scrap both backflush the operation's
+ // materials. Refuse before the lot closes — a closed lot cannot be
+ // dispositioned again, so a refusal after it would strand the units.
+ const backflushCheck = await checkStrictBackflush({
+ jobOperationId: state.jobOperationId,
+ quantity: completionQuantity + (scrapReasonId ? scrapTotal : 0),
+ companyId,
+ userId
+ });
+ if (backflushCheck.error) {
+ return fail(backflushCheck.error, backflushCheck.message!);
+ }
+
// ---------------------------------------------------------------
// 2. Close the lot FIRST — the one-shot requireOpen update is the
// serialization point; a concurrent second POST dies here before
diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.ts
index ce99981bbc..59b7636493 100644
--- a/apps/mes/app/services/quality.server.ts
+++ b/apps/mes/app/services/quality.server.ts
@@ -580,28 +580,6 @@ export async function postBulkCompletion(
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,
@@ -630,16 +608,52 @@ export async function postBulkCompletion(
quantity: args.quantity
});
if (issued.error) {
+ // The units are recorded: say so, or the operator retries and records
+ // them twice.
return {
error: issued.error,
- message:
- issued.error.message || "Units completed, but failed to issue materials"
+ message: `Units completed, but ${issued.error.message || "failed to issue materials"}`
};
}
return { error: null, message: null };
}
+/**
+ * Strict backflush: whether the operation's materials can be backflushed for
+ * `quantity` units — a dry run of `issue` `jobOperation`, rolled back. Call it
+ * before the first write of a completion (closing a lot, recording units), so a
+ * short storage unit refuses the whole action instead of leaving it half done.
+ * A no-op when strict backflush is off.
+ */
+export async function checkStrictBackflush(args: {
+ jobOperationId: string;
+ quantity: number;
+ companyId: string;
+ userId: string;
+}): Promise<{ error: unknown | null; message: string | null }> {
+ if (args.quantity <= 0) return { error: null, message: null };
+ const check = await serverFns
+ .system({
+ db: getDatabaseClient(),
+ companyId: args.companyId,
+ userId: args.userId
+ })
+ .invoke("issue", {
+ id: args.jobOperationId,
+ type: "jobOperation",
+ quantity: args.quantity,
+ dryRun: true
+ });
+ if (check.error) {
+ return {
+ error: check.error,
+ message: check.error.message || "Failed to issue materials"
+ };
+ }
+ return { error: null, message: null };
+}
+
// Auto-creates the optional NCR documenting a rejected (or partially rejected)
// inspection lot — failed features (measured values vs. spec) + sampling
// summary in the description — and links it back via nonConformanceInspection.
diff --git a/packages/database/AGENTS.md b/packages/database/AGENTS.md
index 282176b6eb..71fa75a31c 100644
--- a/packages/database/AGENTS.md
+++ b/packages/database/AGENTS.md
@@ -80,6 +80,7 @@ pnpm --filter @carbon/database authz migration <name> # ship unshipped rules/h
| `./account-import` | Client-safe, pure. The chart of accounts import planner: `planAccountImport(chartRows, defaultRows, ctx, resolutions)` (the customer's chart and default accounts file + group context → claims, updates, creates, merges, plain deletes, `replacements` (accounts in use that need a target row, with the pick), role and fixed asset class moves, errors), `isApplicable`, `REFERENCE_POLICY` (every foreign key to `account` as a policy union — `repoint`, `repoint-if-status`, `repoint-if-parent-status`, `history`; the `apply-account-import` live test compares it with the catalog), `requiredRoles`, `ROLE_NAMES`, `assetClassKey` / `assetClassLabel` / `defaultKeyLabel`, `classOfAccountType`. Pinned by `account-import.test.ts` |
| `./account-import-reads` | Server-only. `loadAccountImportContext(db, companyGroupId, companyId)` — the chart, the group's companies (with their cutover), defaults and fixed asset classes, and per account the references a merge moves (documents, posted or not, Draft or Provisional journal lines, and the references with no foreign key) and the history it cannot, one query per table. `isAccountInUse(db, companyGroupId, accountId)` — whether anything in the group refers to an account, from the same list, so a false answer means a delete will not be refused |
| `./supersession-pick` | The supersession rules shared by MRP, get-method and picking (`buildSupersessionRedirectMap`, `buildConsumeFirstHops`, `settleConsumeFirstLine`, `resolveMadeLinePull`, `consumableInWholeAssemblies`, …) |
+| `./strict-backflush` | Client-safe (type-only Kysely import; no `./rows`, so the BoM badges can bundle it). The strict backflush rules shared by activation, release, the backflush, the badges and the settings card: `needsPullFrom` / `PULLED_ITEM_TYPES`, `missingPullFromLocations`, `getPullFromLocations` / `isPullFromLocation` (an active work center AND an active storage unit), `getStrictBackflushSettings` (the location gates `strict`), `getMethodPartsMissingPullFrom` + `activationRefusalMessage`, `pullFromStorageUnit` (a picked line's Pull From: the oldest pick line's source), `strictBackflushLockKey` (the advisory lock key SQL `backflush_job_materials` builds too), `binShortfall`, `summarizeList` / `MESSAGE_LIST_LIMIT`. Pinned by `strict-backflush.test.ts` |
| `./supplier-part-price` | Supplier part prices are stored as quoted (per purchase unit, in the part's `currencyCode`); `convertUnitPrice` puts one on a purchase document in its currency, `buildSupplierPriceMap` turns them into base per-inventory-unit costing breaks. Shared by the ERP, `methods.ts` and the server functions so every reader converts the same way |
| `./picked-consumption` | Consumption follows what was picked (`linesideCredit`, `getPickedBudgets`, `allocateAcrossBudgets`, …) — the one definition of usable lineside stock shared by the pick-list generator and the `issue` backflush |
| `./machine-time` | Every function takes a Kysely transaction (`KyselyTx`). The locks and writes that end machine time, shared by the OEE sync, the MES Machine button, the device mapping writes and the Sense uninstall hook: `lockWorkCenterDevice` (`FOR UPDATE` on the work center's `workCenterDevice` row), `lockMachinePress` (that lock, then a transaction advisory lock per work center — the one lock order every writer takes), `recordManualMachinePress` (a Machine Start/Pause: takes the press time under the locks unless given, ends every open Machine event on the work center at it, and on a mapped work center ends the open unattributed time and sets `lastManualChangeAt` via `GREATEST` and `unplannedPressAt` via `LEAST`; returns `{ mapped, endedEventIds, pressedAt }`), `endSensorMachineTime` (ends the `system` Machine events and the open unattributed time when a device leaves a work center). Pinned by `machine-time.test.ts` (needs `SUPABASE_DB_URL`). See `.claude/rules/oee-provider.md` |
diff --git a/packages/database/src/strict-backflush.test.ts b/packages/database/src/strict-backflush.test.ts
index f55bdb20d1..e764cc22a5 100644
--- a/packages/database/src/strict-backflush.test.ts
+++ b/packages/database/src/strict-backflush.test.ts
@@ -4,9 +4,12 @@
import { describe, expect, it } from "vitest";
import {
+ activationRefusalMessage,
binShortfall,
missingPullFromLocations,
needsPullFrom,
+ pullFromStorageUnit,
+ strictBackflushLockKey,
summarizeList
} from "./strict-backflush.ts";
@@ -130,3 +133,68 @@ describe("summarizeList", () => {
expect(summarizeList([])).toBe("");
});
});
+
+describe("pullFromStorageUnit", () => {
+ it("is the line's own bin when nothing was picked", () => {
+ expect(pullFromStorageUnit("SHELF-A", [])).toBe("SHELF-A");
+ });
+
+ it("is the bin a pick took the line from, once the line points at lineside", () => {
+ expect(
+ pullFromStorageUnit("LINESIDE", [
+ { storageUnitId: "SHELF-A", toStorageUnitId: "LINESIDE" }
+ ])
+ ).toBe("SHELF-A");
+ });
+
+ it("takes the oldest pick: a later list sources from the fullest bin", () => {
+ expect(
+ pullFromStorageUnit("LINESIDE", [
+ { storageUnitId: "SHELF-A", toStorageUnitId: "LINESIDE" },
+ { storageUnitId: "SHELF-B", toStorageUnitId: "LINESIDE" }
+ ])
+ ).toBe("SHELF-A");
+ });
+
+ it("ignores picks into another bin, and picks with no source", () => {
+ expect(
+ pullFromStorageUnit("SHELF-A", [
+ { storageUnitId: "SHELF-B", toStorageUnitId: "LINESIDE" },
+ { storageUnitId: null, toStorageUnitId: "SHELF-A" },
+ { storageUnitId: "SHELF-A", toStorageUnitId: "SHELF-A" }
+ ])
+ ).toBe("SHELF-A");
+ });
+
+ it("is null for a line with no bin", () => {
+ expect(
+ pullFromStorageUnit(null, [
+ { storageUnitId: "SHELF-A", toStorageUnitId: "LINESIDE" }
+ ])
+ ).toBeNull();
+ });
+});
+
+describe("strictBackflushLockKey", () => {
+ it("is the key SQL backflush_job_materials builds", () => {
+ // 'strict-backflush:' || company || ':' || bin || ':' || item
+ expect(strictBackflushLockKey("CO", "BIN", "ITEM")).toBe(
+ "strict-backflush:CO:BIN:ITEM"
+ );
+ });
+});
+
+describe("activationRefusalMessage", () => {
+ it("names the parts and caps the list", () => {
+ expect(activationRefusalMessage(["PART-1", "PART-2"])).toBe(
+ "Set a Pull From storage unit before you activate this version: PART-1; PART-2"
+ );
+ expect(
+ activationRefusalMessage(
+ Array.from({ length: 8 }, (_, index) => `PART-${index + 1}`)
+ )
+ ).toBe(
+ "Set a Pull From storage unit before you activate this version: PART-1; PART-2; PART-3; PART-4; PART-5; and 3 more"
+ );
+ });
+});
diff --git a/packages/database/src/strict-backflush.ts b/packages/database/src/strict-backflush.ts
index d874752a10..1ed5fefe90 100644
--- a/packages/database/src/strict-backflush.ts
+++ b/packages/database/src/strict-backflush.ts
@@ -6,7 +6,8 @@
// .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.
+// never disagree about which lines count. The backflush reads the location
+// test, the Pull From of a picked line and the lock key from here too.
import type { Kysely, KyselyDatabase } from "./client.ts";
import { round } from "./precision.ts";
@@ -59,10 +60,7 @@ export function missingPullFromLocations(
// 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 }[]> {
+function pullFromLocations(db: Kysely<KyselyDatabase>, companyId: string) {
return db
.selectFrom("location")
.where("location.companyId", "=", companyId)
@@ -85,12 +83,154 @@ export async function getPullFromLocations(
.where("storageUnit.active", "=", true)
.select("storageUnit.id")
)
- )
+ );
+}
+
+export async function getPullFromLocations(
+ db: Kysely<KyselyDatabase>,
+ companyId: string
+): Promise<{ id: string; name: string }[]> {
+ return pullFromLocations(db, companyId)
.select(["location.id", "location.name"])
.orderBy("location.name")
.execute();
}
+// Whether strict backflush applies at a job's location. Activation exempts
+// the other locations, so a backflush there must not refuse a line for a bin
+// it could never name.
+export async function isPullFromLocation(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ locationId: string
+): Promise<boolean> {
+ const row = await pullFromLocations(db, companyId)
+ .where("location.id", "=", locationId)
+ .select("location.id")
+ .executeTakeFirst();
+ return row !== undefined;
+}
+
+export type StrictBackflushSettings = {
+ strict: boolean;
+ /** Only meaningful while `strict`: refuse a short bin instead of letting it
+ * go negative. */
+ preventNegative: boolean;
+};
+
+/**
+ * The company's strict backflush settings. With `locationId`, `strict` is also
+ * false at a location `getPullFromLocations` leaves out (no active work center
+ * or no active storage unit): activation never asked for a Pull From there.
+ */
+export async function getStrictBackflushSettings(
+ db: Kysely<KyselyDatabase>,
+ companyId: string,
+ locationId?: string | null
+): Promise<StrictBackflushSettings> {
+ const row = await db
+ .selectFrom("companySettings")
+ .where("id", "=", companyId)
+ .select(["requireBackflushStorageUnit", "preventNegativeBackflush"])
+ .executeTakeFirst();
+ const strict =
+ row?.requireBackflushStorageUnit === true &&
+ (!locationId || (await isPullFromLocation(db, companyId, locationId)));
+ return {
+ strict,
+ preventNegative: row?.preventNegativeBackflush !== false
+ };
+}
+
+/**
+ * The parts of a make method that block its activation: pulled, stocked lines
+ * with no Pull From at one of `getPullFromLocations`. One entry per part — the
+ * refusal names what to fix, not where. Read by the `convert` activation and
+ * the New Version route.
+ */
+export async function getMethodPartsMissingPullFrom(
+ db: Kysely<KyselyDatabase>,
+ args: { makeMethodId: string; companyId: string }
+): Promise<string[]> {
+ const { makeMethodId, companyId } = args;
+
+ // Two awaits, not `inOrder`: this module is bundled for the browser (the BoM
+ // badges read `needsPullFrom`), and `./rows` brings the Kysely runtime.
+ const lines = await db
+ .selectFrom("methodMaterial")
+ .innerJoin("item", "item.id", "methodMaterial.itemId")
+ .where("methodMaterial.makeMethodId", "=", makeMethodId)
+ .where("methodMaterial.companyId", "=", companyId)
+ .where("item.companyId", "=", companyId)
+ .select([
+ "methodMaterial.methodType",
+ "methodMaterial.itemType",
+ "methodMaterial.storageUnitIds",
+ "methodMaterial.order",
+ "item.id as itemId",
+ "item.itemTrackingType",
+ "item.readableIdWithRevision"
+ ])
+ .orderBy("methodMaterial.order")
+ .execute();
+ const locations = await getPullFromLocations(db, companyId);
+
+ const locationIds = locations.map((location) => location.id);
+ return [
+ ...new Set(
+ lines
+ .filter(needsPullFrom)
+ .filter(
+ (line) =>
+ missingPullFromLocations(line.storageUnitIds, locationIds).length >
+ 0
+ )
+ .map((line) => line.readableIdWithRevision ?? line.itemId)
+ )
+ ];
+}
+
+export function activationRefusalMessage(parts: readonly string[]): string {
+ return `Set a Pull From storage unit before you activate this version: ${summarizeList(parts)}`;
+}
+
+export type PickLineBins = {
+ storageUnitId: string | null;
+ toStorageUnitId: string | null;
+};
+
+// The Pull From of a job material line. Posting a pick points the line at the
+// lineside bin it was picked to (`pointJobMaterialAtLineside`), so after a pick
+// `storageUnitId` no longer names the Pull From. The pick line still holds it:
+// the picking list generator sources a line from its Pull From. `pickLines`
+// must be oldest first — a later list for the same line is generated after the
+// pointer moved, and sources from the fullest warehouse bin instead. SQL
+// `backflush_job_materials` resolves the same way.
+export function pullFromStorageUnit(
+ storageUnitId: string | null,
+ pickLines: readonly PickLineBins[]
+): string | null {
+ if (!storageUnitId) return null;
+ const pick = pickLines.find(
+ (line) =>
+ line.toStorageUnitId === storageUnitId &&
+ line.storageUnitId !== null &&
+ line.storageUnitId !== storageUnitId
+ );
+ return pick?.storageUnitId ?? storageUnitId;
+}
+
+// The advisory lock key for strict draws on one bin and item. SQL
+// `backflush_job_materials` builds the same string; both lock with
+// `pg_advisory_xact_lock(hashtextextended(key, 0))`.
+export function strictBackflushLockKey(
+ companyId: string,
+ storageUnitId: string,
+ itemId: string
+): string {
+ return `strict-backflush:${companyId}:${storageUnitId}:${itemId}`;
+}
+
// 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.
diff --git a/packages/database/supabase/migrations/20261015163040_strict-backflush.sql b/packages/database/supabase/migrations/20261015163040_strict-backflush.sql
index cc7ca04b0c..f2e469a237 100644
--- a/packages/database/supabase/migrations/20261015163040_strict-backflush.sql
+++ b/packages/database/supabase/migrations/20261015163040_strict-backflush.sql
@@ -5,10 +5,11 @@
-- short bin does under it: refuse, or let the bin go negative.
-- backflush_job_materials is copied from its live definition
-- (20261009010412_job-costing-always-post.sql) with one change: when strict
--- backflush is on, a stocked material is consumed only from
--- jobMaterial.storageUnitId — a missing bin raises, and a short bin raises
--- only while preventNegativeBackflush is on — instead of falling back to the
--- pick method's bin or the fullest bin. With strict backflush off the
+-- backflush is on at the job's location, a stocked material is consumed only
+-- from its Pull From — a missing bin raises, and a short bin raises only while
+-- preventNegativeBackflush is on — instead of falling back to the pick
+-- method's bin or the fullest bin. A picked line is drawn from its lineside
+-- bin first and the rest from its Pull From. With strict backflush off the
-- function is unchanged.
ALTER TABLE "companySettings"
@@ -37,6 +38,10 @@ DECLARE
v_prevent_negative BOOLEAN;
v_storage_unit_name TEXT;
v_strict_problems TEXT[] := '{}';
+ v_pull_from TEXT;
+ v_lineside_take NUMERIC;
+ v_issue_total NUMERIC;
+ v_lock_key BIGINT;
v_material_costing_method TEXT;
v_material_standard_cost NUMERIC;
v_material_unit_cost NUMERIC;
@@ -100,13 +105,70 @@ BEGIN
v_strict := COALESCE(v_strict, false);
v_prevent_negative := COALESCE(v_prevent_negative, true);
+ -- Strict backflush applies only where activation asks for a Pull From: a
+ -- location with an active work center and an active storage unit
+ -- (getPullFromLocations in @carbon/database/strict-backflush).
+ v_strict := v_strict
+ AND EXISTS (
+ SELECT 1 FROM "workCenter"
+ WHERE "locationId" = v_job_location_id
+ AND "companyId" = p_company_id
+ AND active = true
+ )
+ AND EXISTS (
+ SELECT 1 FROM "storageUnit"
+ WHERE "locationId" = v_job_location_id
+ AND "companyId" = p_company_id
+ AND active = true
+ );
+
+ -- Lock every Pull From this completion may draw, in one order (by key hash),
+ -- before the first draw: two completions drawing the same bins then cannot
+ -- deadlock. lockStrictBins in @carbon/server-functions locks in the same
+ -- order with the same keys.
+ IF v_strict AND v_prevent_negative THEN
+ FOR v_lock_key IN
+ SELECT DISTINCT hashtextextended(
+ 'strict-backflush:' || p_company_id || ':' || pf."pullFrom" || ':' || jm."itemId",
+ 0
+ )
+ FROM "jobMaterial" jm
+ LEFT JOIN "item" i ON i.id = jm."itemId" AND i."companyId" = p_company_id
+ CROSS JOIN LATERAL (
+ SELECT COALESCE((
+ SELECT pll."storageUnitId"
+ FROM "pickingListLine" pll
+ WHERE pll."jobMaterialId" = jm.id
+ AND pll."companyId" = p_company_id
+ AND pll."toStorageUnitId" = jm."storageUnitId"
+ AND pll."storageUnitId" IS NOT NULL
+ AND pll."storageUnitId" <> jm."storageUnitId"
+ ORDER BY pll."createdAt", pll.id
+ LIMIT 1
+ ), jm."storageUnitId") AS "pullFrom"
+ ) pf
+ WHERE jm."jobId" = p_job_id
+ AND jm."companyId" = p_company_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
+ AND COALESCE(i."itemTrackingType", 'Inventory') <> 'Non-Inventory'
+ AND pf."pullFrom" IS NOT NULL
+ ORDER BY 1
+ LOOP
+ PERFORM pg_advisory_xact_lock(v_lock_key);
+ END LOOP;
+ END IF;
+
-- 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"
+ LEFT JOIN "item" i ON i.id = jm."itemId" AND i."companyId" = p_company_id
WHERE jm."jobId" = p_job_id
AND jm."itemType" IN ('Material', 'Part', 'Consumable')
AND jm."methodType" != 'Make to Order'
@@ -123,11 +185,11 @@ BEGIN
END IF;
IF v_strict AND COALESCE(v_material."itemTrackingType", 'Inventory') <> 'Non-Inventory' THEN
- v_material_storage_unit_id := v_material."storageUnitId";
+ v_issue_total := v_material_qty_to_issue;
-- 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
+ IF v_material."storageUnitId" 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
@@ -135,17 +197,61 @@ BEGIN
CONTINUE;
END IF;
- -- A short bin is refused only while negative stock is prevented; with it
- -- allowed, the material is drawn from its own bin even below zero.
- IF v_prevent_negative THEN
- -- 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
- ));
+ -- A pick points the line at the lineside bin it was picked to. The
+ -- oldest pick line into that bin still names the Pull From
+ -- (pullFromStorageUnit in @carbon/database/strict-backflush).
+ v_pull_from := COALESCE((
+ SELECT pll."storageUnitId"
+ FROM "pickingListLine" pll
+ WHERE pll."jobMaterialId" = v_material.id
+ AND pll."companyId" = p_company_id
+ AND pll."toStorageUnitId" = v_material."storageUnitId"
+ AND pll."storageUnitId" IS NOT NULL
+ AND pll."storageUnitId" <> v_material."storageUnitId"
+ ORDER BY pll."createdAt", pll.id
+ LIMIT 1
+ ), v_material."storageUnitId");
+
+ -- A picked line: what was picked is drawn from lineside first, up to
+ -- what the bin holds.
+ IF v_pull_from <> v_material."storageUnitId" THEN
+ SELECT COALESCE(SUM(quantity), 0) INTO v_bin_on_hand
+ FROM "itemLedger"
+ WHERE "itemId" = v_material."itemId"
+ AND "storageUnitId" = v_material."storageUnitId"
+ AND "locationId" = v_job_location_id
+ AND "companyId" = p_company_id
+ AND "trackedEntityId" IS NULL;
+
+ v_lineside_take := LEAST(v_material_qty_to_issue, GREATEST(v_bin_on_hand, 0));
+
+ IF v_lineside_take > 0 THEN
+ 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_lineside_take,
+ v_job_location_id, v_material."storageUnitId", p_user_id
+ );
+
+ v_bf_item_ids := v_bf_item_ids || v_material."itemId";
+ v_bf_quantities := v_bf_quantities || v_lineside_take;
+ v_bf_storage_unit_ids := v_bf_storage_unit_ids || v_material."storageUnitId";
+
+ v_material_qty_to_issue := v_material_qty_to_issue - v_lineside_take;
+ END IF;
+ END IF;
+
+ -- The rest comes from the Pull From only. A short Pull From is refused
+ -- only while negative stock is prevented; with it allowed, the material
+ -- is drawn from its Pull From even below zero. A refused material still
+ -- writes its row below (the function raises before anything commits),
+ -- so a later material on the same bin counts this need too. The lock
+ -- was taken before the loop.
+ v_material_storage_unit_id := v_pull_from;
+ IF v_material_qty_to_issue > 0 AND v_prevent_negative THEN
SELECT COALESCE(SUM(quantity), 0) INTO v_bin_on_hand
FROM "itemLedger"
WHERE "itemId" = v_material."itemId"
@@ -154,19 +260,19 @@ BEGIN
AND "companyId" = p_company_id
AND "trackedEntityId" IS NULL;
- IF v_bin_on_hand < v_material_qty_to_issue THEN
+ IF round(v_bin_on_hand, 5) < round(v_material_qty_to_issue, 5) THEN
SELECT name INTO v_storage_unit_name
FROM "storageUnit"
- WHERE id = v_material_storage_unit_id;
+ WHERE id = v_material_storage_unit_id
+ AND "companyId" = p_company_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))
+ trim_scale(round(v_material_qty_to_issue, 5)),
+ trim_scale(round(GREATEST(v_bin_on_hand, 0), 5))
);
- CONTINUE;
END IF;
END IF;
ELSE
@@ -220,24 +326,28 @@ BEGIN
END IF;
END IF;
END IF;
+ v_issue_total := v_material_qty_to_issue;
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
- );
+ -- Strict: a picked line can be covered by lineside alone.
+ IF v_material_qty_to_issue > 0 THEN
+ 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
+ );
+
+ 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 IF;
UPDATE "jobMaterial"
- SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_material_qty_to_issue
+ SET "quantityIssued" = COALESCE("quantityIssued", 0) + v_issue_total
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
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 884247b67b..b4a92c8afd 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -5,7 +5,7 @@
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-16T06:06:27.959Z",
+ "exportedAt": "2026-10-16T06:58:25.255Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index cc2e19f8f1..cf90a2adc7 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -6051,6 +6051,12 @@ msgstr "Region konnte nicht analysiert werden: {0}"
msgid "Could not build PDF. Try again."
msgstr "PDF konnte nicht erstellt werden. Versuchen Sie es erneut."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "Aktive Methoden und offene Fertigungsaufträge mit Lücken konnten nicht überprüft werden. Laden Sie die Seite neu, um es erneut zu versuchen."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "Die Lagereinheiten der Materialien dieses Fertigungsauftrags konnten nicht überprüft werden. Schließen Sie diesen Dialog und öffnen Sie ihn erneut, um es erneut zu versuchen."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Legen Sie einen Kunden für diese Rücksendung fest, um aus einer Liefer
msgid "Set a Pull From on each one through a new version."
msgstr "Legen Sie für jede eine Entnahme über eine neue Version fest."
-#. 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 Pull From storage unit on {names}"
+msgstr "eine Lagereinheit zum Entnehmen auf {names} festlegen"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "eine Lagereinheit zum Entnehmen auf {names} und {more} weitere 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."
@@ -21330,6 +21338,9 @@ msgstr "Lagereinheiten"
msgid "Storage Units"
msgstr "Lagereinheiten"
+msgid "Storage Units Not Checked"
+msgstr "Lagereinheiten nicht überprüft"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Speichern Sie eine feste Anzahl von Tagen auf diesem Artikel. Das Verfallstartdatum wird auf jedem Los oder jeder Seriennummer gesetzt, wenn sie erstellt wird (oder wenn das Auslöseverfahren ausgeführt wird, falls festgelegt)."
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 986caabb7e..b85bbe65b6 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -6051,6 +6051,12 @@ msgstr "Could not analyze region: {0}"
msgid "Could not build PDF. Try again."
msgstr "Could not build PDF. Try again."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Set a customer on this return to add from a shipment."
msgid "Set a Pull From on each one through a new version."
msgstr "Set a Pull From on each one through a new version."
-#. 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 Pull From storage unit on {names}"
+msgstr "set a Pull From storage unit on {names}"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "set a Pull From storage unit on {names} and {more} more"
msgid "Set a supplier on this return to add from a receipt."
msgstr "Set a supplier on this return to add from a receipt."
@@ -21330,6 +21338,9 @@ msgstr "storage units"
msgid "Storage Units"
msgstr "Storage Units"
+msgid "Storage Units Not Checked"
+msgstr "Storage Units Not Checked"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 902c99ae37..ddb8c0e0fe 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -6051,6 +6051,12 @@ msgstr "No se pudo analizar la región: {0}"
msgid "Could not build PDF. Try again."
msgstr "No se pudo crear el PDF. Intenta de nuevo."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "No se pudo verificar métodos activos y órdenes de trabajo abiertas con brechas. Recarga la página para volver a intentar."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "No se pudieron verificar las unidades de almacenamiento de los materiales de esta orden de trabajo. Cierra este diálogo y ábrelo de nuevo para volver a intentar."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Establezca un cliente en esta devolución para agregar desde un envío."
msgid "Set a Pull From on each one through a new version."
msgstr "Establezca un Extraer de en cada uno a través de una nueva versión."
-#. 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 Pull From storage unit on {names}"
+msgstr "establecer una unidad de almacenamiento de extracción para {names}"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "establecer una unidad de almacenamiento de extracción para {names} y {more} más"
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."
@@ -21330,6 +21338,9 @@ msgstr "unidades de almacenamiento"
msgid "Storage Units"
msgstr "Unidades de Almacenamiento"
+msgid "Storage Units Not Checked"
+msgstr "Unidades de almacenamiento sin verificar"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Almacenar cantidad fija de días en este artículo. La fecha de inicio de caducidad se establece en cada lote de producción o serial cuando se crea (o cuando se ejecuta el proceso de desencadenador, si se configura)."
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 4c33ac0198..e88302ce44 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -6051,6 +6051,12 @@ msgstr "Impossible d'analyser la région : {0}"
msgid "Could not build PDF. Try again."
msgstr "Impossible de créer le PDF. Réessayez."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "Impossible de vérifier les méthodes actives et les ordres de fabrication ouverts avec des lacunes. Rechargez la page pour réessayer."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "Impossible de vérifier les unités de stockage des matériaux de cet ordre de fabrication. Fermez cette boîte de dialogue et ouvrez-la à nouveau pour réessayer."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Définissez un client sur ce retour pour ajouter à partir d'une expédi
msgid "Set a Pull From on each one through a new version."
msgstr "Définissez un Prélèvement depuis pour chacun via une nouvelle version."
-#. 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 Pull From storage unit on {names}"
+msgstr "définir une unité de stockage Prélever de sur {names}"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "définir une unité de stockage Prélever de sur {names} et {more} de plus"
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."
@@ -21330,6 +21338,9 @@ msgstr "unités de stockage"
msgid "Storage Units"
msgstr "Unités de stockage"
+msgid "Storage Units Not Checked"
+msgstr "Unités de stockage non vérifiées"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Stocker un nombre fixe de jours sur cet article. La date de début de péremption est définie sur chaque lot de production ou numéro de série lors de sa création (ou lorsque le processus déclencheur s'exécute, s'il est défini)."
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 8bd59477c9..efa4a392af 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -6051,6 +6051,12 @@ msgstr "क्षेत्र का विश्लेषण नहीं क
msgid "Could not build PDF. Try again."
msgstr "PDF नहीं बना सके। फिर से कोशिश करें।"
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "सक्रिय विधियों और अंतराल वाले खुले जॉब की जांच नहीं कर सके। पृष्ठ को फिर से लोड करने का प्रयास करें।"
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "इस जॉब की सामग्री की भंडारण इकाइयाँ जाँची नहीं जा सकीं। फिर से प्रयास करने के लिए इस संवाद को बंद करके दोबारा खोलें।"
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "शिपमेंट से जोड़ने के लिए इस
msgid "Set a Pull From on each one through a new version."
msgstr "एक नए संस्करण के माध्यम से प्रत्येक पर Pull From निर्दिष्ट करें।"
-#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
-msgid "set a Pull From storage unit on {0}"
-msgstr "खींचने की भंडारण इकाई को {0} पर सेट करें"
+msgid "set a Pull From storage unit on {names}"
+msgstr "{names} पर खींचने की भंडारण इकाई सेट करें"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "{names} और {more} अधिक पर खींचने की भंडारण इकाई सेट करें"
msgid "Set a supplier on this return to add from a receipt."
msgstr "प्राप्ति से जोड़ने के लिए इस रिटर्न पर एक आपूर्तिकर्ता सेट करें।"
@@ -21330,6 +21338,9 @@ msgstr "भंडारण इकाइयाँ"
msgid "Storage Units"
msgstr "भंडारण इकाइयाँ"
+msgid "Storage Units Not Checked"
+msgstr "भंडारण इकाइयाँ जाँची नहीं गईं"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "इस आइटम पर निश्चित संख्या के दिनों के लिए भंडारण करें। समाप्ति प्रारंभ तिथि प्रत्येक बैच या सीरीयल पर सेट की जाती है जब यह बनाया जाता है (या जब ट्रिगर प्रक्रिया चलती है, यदि सेट है)।"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 2df504426f..f18e0afd85 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -6051,6 +6051,12 @@ msgstr "Impossibile analizzare la regione: {0}"
msgid "Could not build PDF. Try again."
msgstr "Impossibile creare il PDF. Riprova."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "Non è stato possibile verificare i metodi attivi e gli ordini di produzione aperti con lacune. Ricaricare la pagina per riprovare."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "Non è stato possibile verificare le unità di stoccaggio dei materiali di questo ordine di produzione. Chiudere questa finestra di dialogo e aprirla di nuovo per riprovare."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Imposta un cliente su questo reso per aggiungere da una spedizione."
msgid "Set a Pull From on each one through a new version."
msgstr "Imposta un Pull From su ognuno tramite una nuova versione."
-#. 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 Pull From storage unit on {names}"
+msgstr "impostare un'unità di stoccaggio Preleva da su {names}"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "impostare un'unità di stoccaggio Preleva da su {names} e {more} altri"
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."
@@ -21330,6 +21338,9 @@ msgstr "unità di stoccaggio"
msgid "Storage Units"
msgstr "Unità di Stoccaggio"
+msgid "Storage Units Not Checked"
+msgstr "Unità di stoccaggio non verificate"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Archivia un numero fisso di giorni su questo articolo. La data di inizio della scadenza viene impostata su ogni lotto o seriale quando viene creato (o quando il processo di attivazione viene eseguito, se impostato)."
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index d4f0f664f2..d278cef4c7 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -6051,6 +6051,12 @@ msgstr "領域を分析できませんでした: {0}"
msgid "Could not build PDF. Try again."
msgstr "PDFを作成できませんでした。もう一度お試しください。"
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "有効な製法およびギャップのあるオープンな製造指図を確認できませんでした。ページをリロードして再度お試しください。"
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "この製造指図の材料の保管ユニットを確認できませんでした。このダイアログをクローズして、もう一度開いて、再度お試しください。"
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "出荷から追加するにはこのリターンに得意先を設定し
msgid "Set a Pull From on each one through a new version."
msgstr "新しいバージョンで各々に引き出し元を設定してください。"
-#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
-msgid "set a Pull From storage unit on {0}"
-msgstr "{0} に抽出元保管ユニットを設定する"
+msgid "set a Pull From storage unit on {names}"
+msgstr "プルフロム保管ユニットを{names}に設定"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "プルフロム保管ユニットを{names}およびその他{more}個に設定"
msgid "Set a supplier on this return to add from a receipt."
msgstr "この返品に仕入先を設定して入荷から追加"
@@ -21330,6 +21338,9 @@ msgstr "保管ユニット"
msgid "Storage Units"
msgstr "保管ユニット"
+msgid "Storage Units Not Checked"
+msgstr "保管ユニット未確認"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "このアイテムの使用期限を固定日数で管理します。各バッチまたはシリアルの使用期限開始日は、作成時(またはトリガープロセスが実行された場合)に設定されます。"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index d15609a7d0..c55317c510 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -6051,6 +6051,12 @@ msgstr "영역을 분석할 수 없습니다: {0}"
msgid "Could not build PDF. Try again."
msgstr "PDF를 생성할 수 없습니다. 다시 시도하세요."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "활성 방법 및 간격이 있는 미결 작업 지시를 확인할 수 없습니다. 페이지를 다시 로드하여 다시 시도하십시오."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "이 작업 지시 자재의 보관 단위를 확인할 수 없습니다. 이 대화를 닫고 다시 열어서 다시 시도하십시오."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "출하에서 추가할 고객을 이 반품에 설정하세요."
msgid "Set a Pull From on each one through a new version."
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 Pull From storage unit on {names}"
+msgstr "{names}의 위치에서 인수할 보관 단위 설정"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "{names} 및 {more}개 항목의 위치에서 인수할 보관 단위 설정"
msgid "Set a supplier on this return to add from a receipt."
msgstr "이 반품에 공급업체를 지정하여 입고에서 추가하세요."
@@ -21330,6 +21338,9 @@ msgstr "보관 단위"
msgid "Storage Units"
msgstr "보관 단위"
+msgid "Storage Units Not Checked"
+msgstr "보관 단위 미확인"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "이 품목에 고정 일수를 저장합니다. 유통기한 시작일은 각 배치 또는 시리얼이 생성될 때(또는 트리거 공법이 실행될 때, 설정된 경우) 설정됩니다."
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 38101d005b..94fb84ccb2 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -6051,6 +6051,12 @@ msgstr "Nie można analizować regionu: {0}"
msgid "Could not build PDF. Try again."
msgstr "Nie można było zbudować pliku PDF. Spróbuj ponownie."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "Nie można sprawdzić aktywnych metod i otwartych zleceń produkcyjnych z przerwami. Załaduj stronę ponownie, aby spróbować ponownie."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "Nie można sprawdzić jednostek magazynowych materiałów tego zlecenia produkcyjnego. Zamknij to okno dialogowe i otwórz je ponownie, aby spróbować ponownie."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Ustaw klienta na tym zwrocie, aby dodać z wysyłki."
msgid "Set a Pull From on each one through a new version."
msgstr "Ustaw Pull From dla każdego poprzez nową wersję."
-#. 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 Pull From storage unit on {names}"
+msgstr "ustaw jednostkę magazynową Pobierz z na {names}"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "ustaw jednostkę magazynową Pobierz z na {names} i {more} więcej"
msgid "Set a supplier on this return to add from a receipt."
msgstr "Ustaw dostawcę w tym zwrocie, aby dodać z przyjęcia."
@@ -21330,6 +21338,9 @@ msgstr "jednostki magazynowania"
msgid "Storage Units"
msgstr "Jednostki magazynowe"
+msgid "Storage Units Not Checked"
+msgstr "Jednostki magazynowe nie sprawdzono"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Przechowuj przez ustaloną liczbę dni na tym artykule. Data rozpoczęcia terminu ważności jest ustawiana na każdej partii produkcyjnej lub numerze seryjnym podczas jej utworzenia (lub gdy uruchomi się proces wyzwalający, jeśli ustawiony)."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index ea6a31c35e..7504ca1d0f 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -6051,6 +6051,12 @@ msgstr "Não foi possível analisar a região: {0}"
msgid "Could not build PDF. Try again."
msgstr "Não foi possível criar o PDF. Tente novamente."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "Não foi possível verificar Métodos Ativos e Ordens de produção Abertas com lacunas. Recarregue a página para tentar novamente."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "Não foi possível verificar as Unidades de armazenamento dos materiais desta Ordem de produção. Feche este diálogo e abra-o novamente para tentar novamente."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Defina um cliente nesta devolução para adicionar de uma remessa."
msgid "Set a Pull From on each one through a new version."
msgstr "Defina uma origem em cada um através de uma nova versão."
-#. 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 Pull From storage unit on {names}"
+msgstr "definir uma Unidade de armazenamento de Puxar De em {names}"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "definir uma Unidade de armazenamento de Puxar De em {names} e {more} mais"
msgid "Set a supplier on this return to add from a receipt."
msgstr "Defina um fornecedor nesta devolução para adicionar de um recebimento."
@@ -21330,6 +21338,9 @@ msgstr "unidades de armazenamento"
msgid "Storage Units"
msgstr "Unidades de Armazenamento"
+msgid "Storage Units Not Checked"
+msgstr "Unidades de armazenamento não verificadas"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Armazene um número fixo de dias neste item. A data de início da validade é definida em cada lote ou série quando é criado (ou quando o processo de acionamento é executado, se configurado)."
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index bbf75d2431..1f334cd245 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -6051,6 +6051,12 @@ msgstr "Не удалось проанализировать регион: {0}"
msgid "Could not build PDF. Try again."
msgstr "Не удалось создать PDF. Попробуйте еще раз."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "Не удалось проверить действующие методы и незакрытые производственные заказы на наличие разрывов. Перезагрузите страницу, чтобы повторить попытку."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "Не удалось проверить единицы хранения материалов этого производственного заказа. Закройте это диалоговое окно и откройте его снова, чтобы повторить попытку."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Укажите покупателя для этого возврата,
msgid "Set a Pull From on each one through a new version."
msgstr "Установите источник для каждого из них через новую версию."
-#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
-msgid "set a Pull From storage unit on {0}"
-msgstr "установить единицу хранения для получения на {0}"
+msgid "set a Pull From storage unit on {names}"
+msgstr "установить единицу хранения вытягивания для {names}"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "установить единицу хранения вытягивания для {names} и еще {more} наименований"
msgid "Set a supplier on this return to add from a receipt."
msgstr "Установите поставщика для этого возврата, чтобы добавить из поступления."
@@ -21330,6 +21338,9 @@ msgstr "единицы хранения"
msgid "Storage Units"
msgstr "Единицы хранения"
+msgid "Storage Units Not Checked"
+msgstr "Единицы хранения не проверены"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Хранить фиксированное количество дней для этой номенклатуры. Дата начала срока годности устанавливается для каждой серии или серийного номера при его создании (или когда запускается процесс триггера, если установлен)."
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 7db76b58a2..32ea5a9229 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -6051,6 +6051,12 @@ msgstr "Bölge analiz edilemedi: {0}"
msgid "Could not build PDF. Try again."
msgstr "PDF oluşturulamadı. Lütfen tekrar deneyin."
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "Boşluğu olan Aktif Yöntemler ve Açık İş emirleri kontrol edilemedi. Sayfayı yenileyerek yeniden deneyin."
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "Bu İş emrinin malzemelerin Depolama birimleri kontrol edilemedi. İletişim kutusunu kapatıp yeniden açmayı deneyin."
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "Sevkiyattan eklemek için bu iade işlemine bir müşteri belirleyin."
msgid "Set a Pull From on each one through a new version."
msgstr "Her biri için yeni bir sürüm üzerinden çekme kaynağı 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 Pull From storage unit on {names}"
+msgstr "{names} için Çekme Depolama Birimi ayarla"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "{names} ve {more} diğer için Çekme 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."
@@ -21330,6 +21338,9 @@ msgstr "depolama birimleri"
msgid "Storage Units"
msgstr "Depolama Birimleri"
+msgid "Storage Units Not Checked"
+msgstr "Depolama Birimleri Kontrol Edilmedi"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "Bu öğe için sabit bir gün sayısı saklayın. Son kullanma tarihi başlangıç tarihi, her parti veya seri oluşturulduğunda (veya tetikleyici işlem ayarlanmışsa çalıştığında) belirlenir."
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 02a693ba44..4281d9788c 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -6051,6 +6051,12 @@ msgstr "无法分析区域:{0}"
msgid "Could not build PDF. Try again."
msgstr "无法生成 PDF。请重试。"
+msgid "Could not check for active methods and open jobs with gaps. Reload the page to try again."
+msgstr "无法检查启用方法和未结工单中的缺口。请重新加载页面重试。"
+
+msgid "Could not check the storage units of this job's materials. Close this dialog and open it again to try again."
+msgstr "无法检查此工单物料的存储单元。关闭此对话框并重新打开重试。"
+
#. placeholder {0}: d.failed.length
#. placeholder {1}: d.failed .map((f) => f.readableId) .join(", ")
msgid "Could not dissolve {0}: {1} — production already recorded"
@@ -20287,9 +20293,11 @@ msgstr "在此退货上设置客户以从发货中添加。"
msgid "Set a Pull From on each one through a new version."
msgstr "通过新版本为每个物料设置拉取来源。"
-#. placeholder {0}: summarizeList( job.materialsWithoutStorageUnit.map( (m) => m.description ) )
-msgid "set a Pull From storage unit on {0}"
-msgstr "为 {0} 设置取货存储单元"
+msgid "set a Pull From storage unit on {names}"
+msgstr "在{names}上设置拉取存储单元"
+
+msgid "set a Pull From storage unit on {names} and {more} more"
+msgstr "在{names}和{more}个其他项目上设置拉取存储单元"
msgid "Set a supplier on this return to add from a receipt."
msgstr "为此退货指定供应商以从其收货中添加"
@@ -21330,6 +21338,9 @@ msgstr "存储单元"
msgid "Storage Units"
msgstr "存储单元"
+msgid "Storage Units Not Checked"
+msgstr "存储单元未检查"
+
msgid "Store a fixed number of days on this item. Expiry start date is set on each batch or serial when it's created (or when the trigger process runs, if set)."
msgstr "在此物料上存储固定天数。在创建每个生产批次或序列号时(或触发工艺运行时,如果已设置)设置有效期开始日期。"
diff --git a/packages/server-functions/AGENTS.md b/packages/server-functions/AGENTS.md
index 96dd30ebb8..f2a629d6aa 100644
--- a/packages/server-functions/AGENTS.md
+++ b/packages/server-functions/AGENTS.md
@@ -383,7 +383,9 @@ pnpm --filter @carbon/checks test
| `./errors` | `ServerFnError`, `InvalidInputError`, `ForbiddenError`, `NotFoundError`, `isDataLayerError`, `toServerFnError` — the classes, for `instanceof` and `new` |
| `./<name>` | one server function as the default export, plus its input schema and result types (`src/<name>/index.ts`) |
-Shared posting internals live in `src/lib/` (not exported): `get-accounting-period` (`resolveAccountingPeriod`, `getCurrentAccountingPeriod`, `getAccountingPeriodForDate`), `get-posting-group` (`getDefaultPostingGroup`, `resolveInventoryAccount`), `calculate-cogs` (`calculateCOGS`: reads and locks the open layers, then writes what `relieveLayers` from `@carbon/database/cost-relief` returns), `storage-units`, `require-accounting-cutover` (`assertAccountingCutover`, see Journals and the accounting cutover), `cutover-void` (`refuseVoidBeforeCutover`, `assertNoMigrationClearing`, the void messages and `TIME_ENTRY_BEFORE_CUTOVER_ERROR`), `postable` (`assertPostable` — only a Draft or Pending document is posted; called BEFORE the function's `try`, whose failure handler resets the document to Draft), `fixed-asset-writes` (`FixedAssetWrites` — asset changes decided while the journal is built are staged and applied inside the posting transaction, never written on `db` directly), `asset-transfer` (the capitalization / return-to-inventory journal line builders, used by `post-asset-transfer` and `post-rental-agreement`), `cost-layer-order` (`leavingTrackedEntityIds`, and `orderLayersForConsumption` re-exported from `@carbon/database/cost-relief` — a serial unit is costed from its own layer first), `contract-ledger` (`lockContractPositions`, `loadContractPositions` — the contract movement ledger's position lock and grouped read, shared by `post-sales-invoice`, `post-memo` and the recognition run's `synthesizeContractRevenue`; `samePosition`, the float-tolerant equality of two positions, used by `post-sales-invoice`; `signedCreditAmount`, a signed credit as an account's natural-balance journal amount, used by `post-sales-invoice` and `post-memo`), `party-dimensions` (`loadPartyDimensions`, `partyDimensionValues`, `partyDimensionValuesFrom` — the Customer / CustomerType or Supplier / SupplierType dimensions on every line of a payment or memo journal, used by `post-payment` and `post-memo` and their rebuilds), `cost-center-project-dimensions` (`costCenterAndProjectDimensions` — the oldest active Cost Center and Project dimensions, used by `post-charge`, `post-reimbursement` and their legacy builders), `document-journal-lines` (`documentJournalLines` — the lines one document's chain owns, read only from journals with a `DOCUMENT_JOURNAL_STATUSES` status; used by `post-receipt`, `post-shipment`, `post-sales-invoice` and `post-purchase-invoice`), `sales-invoice-stand-ins` (`salesInvoiceStandIns`, `STAND_IN_CLASS` — the stand-in lines of a sales invoice journal, used by `post-sales-invoice` and its legacy builder), `void-journal` (`insertNegatedJournal` — voids a journal with a negated copy dated the void date, each line negated with its documents, account default role and dimensions; used by the charge, reimbursement and lease voids), `journal-line-ids` (`allocateJournalLineIds` — the ids of a journal's lines drawn in one statement, used by `post-charge`, `post-reimbursement` and `post-lease`), `currency-decimals` (`currencyDecimals` — a currency's settlement precision, the group's `currency.decimalPlaces`; billed amounts such as rental billing periods and lease payment rows are rounded to it), `lease-payment-rows` (`cutLeasePaymentRows` — the ONE cutter of a lessee lease's payment rows, its Modify slice from `remainingLeasePayments` in `@carbon/utils`, used by `create-lease-invoices`' `rollOpenEndedLeasePayments` and `post-lease`'s Modify; the one helper here the ERP also calls, re-exported from `@carbon/server-functions/create-lease-invoices` for `regenerateLeasePayments` / `updateDraftLease` / `saveDraftLeaseLine`, which cut rows inside their own Kysely transaction), and the inventory-adjustment core — `post-adjustment` (`bookAdjustment`, `createAdjustmentJournal`, `loadOpenCostLayers`), the pure row builders in `plan-adjustment` and `post-adjustment-cost` (`computeCurrentUnitCost`). Pure logic that the apps also need goes to `@carbon/utils` / `@carbon/database`, not here.
+Shared posting internals live in `src/lib/` (not exported): `get-accounting-period` (`resolveAccountingPeriod`, `getCurrentAccountingPeriod`, `getAccountingPeriodForDate`), `get-posting-group` (`getDefaultPostingGroup`, `resolveInventoryAccount`), `calculate-cogs` (`calculateCOGS`: reads and locks the open layers, then writes what `relieveLayers` from `@carbon/database/cost-relief` returns), `storage-units`, `require-accounting-cutover` (`assertAccountingCutover`, see Journals and the accounting cutover), `cutover-void` (`refuseVoidBeforeCutover`, `assertNoMigrationClearing`, the void messages and `TIME_ENTRY_BEFORE_CUTOVER_ERROR`), `postable` (`assertPostable` — only a Draft or Pending document is posted; called BEFORE the function's `try`, whose failure handler resets the document to Draft), `fixed-asset-writes` (`FixedAssetWrites` — asset changes decided while the journal is built are staged and applied inside the posting transaction, never written on `db` directly), `asset-transfer` (the capitalization / return-to-inventory journal line builders, used by `post-asset-transfer` and `post-rental-agreement`), `cost-layer-order` (`leavingTrackedEntityIds`, and `orderLayersForConsumption` re-exported from `@carbon/database/cost-relief` — a serial unit is costed from its own layer first), `contract-ledger` (`lockContractPositions`, `loadContractPositions` — the contract movement ledger's position lock and grouped read, shared by `post-sales-invoice`, `post-memo` and the recognition run's `synthesizeContractRevenue`; `samePosition`, the float-tolerant equality of two positions, used by `post-sales-invoice`; `signedCreditAmount`, a signed credit as an account's natural-balance journal amount, used by `post-sales-invoice` and `post-memo`), `party-dimensions` (`loadPartyDimensions`, `partyDimensionValues`, `partyDimensionValuesFrom` — the Customer / CustomerType or Supplier / SupplierType dimensions on every line of a payment or memo journal, used by `post-payment` and `post-memo` and their rebuilds), `cost-center-project-dimensions` (`costCenterAndProjectDimensions` — the oldest active Cost Center and Project dimensions, used by `post-charge`, `post-reimbursement` and their legacy builders), `document-journal-lines` (`documentJournalLines` — the lines one document's chain owns, read only from journals with a `DOCUMENT_JOURNAL_STATUSES` status; used by `post-receipt`, `post-shipment`, `post-sales-invoice` and `post-purchase-invoice`), `sales-invoice-stand-ins` (`salesInvoiceStandIns`, `STAND_IN_CLASS` — the stand-in lines of a sales invoice journal, used by `post-sales-invoice` and its legacy builder), `void-journal` (`insertNegatedJournal` — voids a journal with a negated copy dated the void date, each line negated with its documents, account default role and dimensions; used by the charge, reimbursement and lease voids), `journal-line-ids` (`allocateJournalLineIds` — the ids of a journal's lines drawn in one statement, used by `post-charge`, `post-reimbursement` and `post-lease`), `currency-decimals` (`currencyDecimals` — a currency's settlement precision, the group's `currency.decimalPlaces`; billed amounts such as rental billing periods and lease payment rows are rounded to it), `lease-payment-rows` (`cutLeasePaymentRows` — the ONE cutter of a lessee lease's payment rows, its Modify slice from `remainingLeasePayments` in `@carbon/utils`, used by `create-lease-invoices`' `rollOpenEndedLeasePayments` and `post-lease`'s Modify; the one helper here the ERP also calls, re-exported from `@carbon/server-functions/create-lease-invoices` for `regenerateLeasePayments` / `updateDraftLease` / `saveDraftLeaseLine`, which cut rows inside their own Kysely transaction), and the inventory-adjustment core — `post-adjustment` (`bookAdjustment`, `createAdjustmentJournal`, `loadOpenCostLayers`), the pure row builders in `plan-adjustment` and `post-adjustment-cost` (`computeCurrentUnitCost`), and strict backflush — `strict-backflush` (`resolvePullFromStorageUnits`, `lockStrictBins`, `binCoverProblem` / `assertBinCovers`, `strictBackflushRefusal`, `assertMethodHasPullFrom`; the rules and reads they share with the apps live in `@carbon/database/strict-backflush`). Pure logic that the apps also need goes to `@carbon/utils` / `@carbon/database`, not here.
+
+**`issue` `jobOperation` with `dryRun: true`** answers "would strict backflush refuse this completion?" without writing: it runs `issueJobOperationMaterials` in a transaction that throws `DryRunRollback` right after the strict check, and is a no-op when strict backflush is off. A caller that records a production quantity BEFORE it calls `issue` must dry-run first (MES `checkStrictBackflush`, ERP `completeOperation`, `batch-operations` `complete`), or a refusal leaves units recorded with no material consumed. The dry run's lock ends with its rollback, so it narrows the race and does not close it.
`src/post-receipt/posting-lines.ts` (pure) builds the journal lines of a purchase order
receipt (`purchaseReceiptLineCosts`, `buildPurchaseReceiptJournalLines`) and of a sales
diff --git a/packages/server-functions/src/batch-operations/index.ts b/packages/server-functions/src/batch-operations/index.ts
index 0cb69b0e52..193e06293c 100644
--- a/packages/server-functions/src/batch-operations/index.ts
+++ b/packages/server-functions/src/batch-operations/index.ts
@@ -462,10 +462,18 @@ async function completeBatch(
// 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) {
+ // A completed batch skips the check, so a retry still gets the
+ // "already completed" answer from the transaction below.
+ const batchStatus = await db
+ .selectFrom("jobOperationBatch")
+ .select("status")
+ .where("id", "=", batchId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ const system = ServerFnContext.system({ db, companyId, userId });
+ for (const m of batchStatus?.status === "Completed" ? [] : members) {
if (m.quantity <= 0) continue;
- const check = await issue(checker, {
+ const check = await issue(system, {
id: m.jobOperationId,
type: "jobOperation",
quantity: m.quantity,
@@ -727,7 +735,6 @@ async function completeBatch(
// Phase 2 (post-commit, idempotent). Any throw leaves the batch Completing; a
// retry re-runs these steps alone. Runs as the system: the batch completion
// itself was authorized.
- const system = ServerFnContext.system({ db, companyId, userId });
for (const m of members) {
if (m.quantity <= 0) continue;
const issued = await issue(system, {
@@ -736,8 +743,12 @@ async function completeBatch(
quantity: m.quantity
});
if (issued.error) {
- throw new Error(
- `Failed to issue materials for operation ${m.jobOperationId}: ${issued.error.message}`
+ // Keep the refusal's status: a strict backflush shortfall is a 409 the
+ // operator fixes by stocking the bin and completing again (which
+ // resumes), not a server error.
+ throw new ServerFnError(
+ `Failed to issue materials for operation ${m.jobOperationId}: ${issued.error.message}`,
+ issued.error instanceof ServerFnError ? issued.error.status : 500
);
}
}
diff --git a/packages/server-functions/src/issue/index.ts b/packages/server-functions/src/issue/index.ts
index f1897eaef3..32f301a6e1 100644
--- a/packages/server-functions/src/issue/index.ts
+++ b/packages/server-functions/src/issue/index.ts
@@ -78,6 +78,8 @@ import {
binCoverProblem,
getStrictBackflushSettings,
isStrictBackflush,
+ lockStrictBins,
+ resolvePullFromStorageUnits,
strictBackflushRefusal
} from "../lib/strict-backflush";
import reschedule from "../reschedule";
@@ -135,7 +137,8 @@ async function issueJobOperationMaterials(
postingStatus,
accountDefaults,
dimensionMap,
- db
+ db,
+ dryRun = false
}: {
jobOperationId: string;
quantity: number;
@@ -146,6 +149,9 @@ async function issueJobOperationMaterials(
accountDefaults: ConsumeAccountDefaults;
dimensionMap: Map<string, string>;
db: Kysely<KyselyDatabase>;
+ // Stop after the strict backflush check: throw DryRunRollback before any
+ // ledger, cost or journal row is built (the caller rolls back).
+ dryRun?: boolean;
}
) {
const materialsToIssue = await trx
@@ -234,9 +240,26 @@ async function issueJobOperationMaterials(
});
const { strict, preventNegative } = await getStrictBackflushSettings(
trx,
- companyId
+ companyId,
+ job.locationId
);
- // Strict backflush: every material the bins cannot cover, refused together.
+ // Strict backflush: what no pick covers comes from each material's Pull
+ // From, and every material the bins cannot cover is refused together.
+ const pullFrom = strict
+ ? await resolvePullFromStorageUnits(trx, companyId, materialsToIssue)
+ : new Map<string, string | null>();
+ if (strict && preventNegative) {
+ await lockStrictBins(
+ trx,
+ companyId,
+ materialsToIssue
+ .filter((material) => itemIdIsTracked.get(material.itemId))
+ .map((material) => ({
+ storageUnitId: pullFrom.get(material.id),
+ itemId: material.itemId
+ }))
+ );
+ }
const strictProblems: string[] = [];
const takenShared: SharedTakes = new Map();
for await (const material of materialsToIssue) {
@@ -294,16 +317,20 @@ async function issueJobOperationMaterials(
// 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 storageUnitId = pullFrom.get(material.id) ?? null;
const problem = await binCoverProblem(trx, {
companyId,
itemId: material.itemId,
locationId: job.locationId,
- storageUnitId: material.storageUnitId,
+ storageUnitId,
quantity: remaining,
plannedRows: itemLedgerInserts,
- preventNegative
+ preventNegative,
+ jobReadableId: job.jobId
});
if (problem) strictProblems.push(problem);
+ // Kept even when refused: a later material on the same bin then counts
+ // this need, so the refusal names every shortfall at once.
itemLedgerInserts.push({
entryType: "Consumption",
documentType: "Job Consumption",
@@ -313,7 +340,7 @@ async function issueJobOperationMaterials(
itemId: material.itemId,
quantity: -remaining,
locationId: job.locationId,
- storageUnitId: material.storageUnitId,
+ storageUnitId,
postingDate: today,
createdBy: userId
});
@@ -410,6 +437,7 @@ async function issueJobOperationMaterials(
// 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);
+ if (dryRun) throw new DryRunRollback();
// Total material cost this call relieved from inventory into WIP — the
// jobOperationScrap case posts its WIP→scrap journal from this figure so a
@@ -2091,8 +2119,10 @@ const issue = defineServerFn({
postingStatus,
accountDefaults,
dimensionMap,
- db
+ db,
+ dryRun
});
+ // Reached on a dry run only when the operation had nothing to issue.
if (dryRun) throw new DryRunRollback();
});
} catch (err) {
@@ -2984,7 +3014,8 @@ const issue = defineServerFn({
trx
.selectFrom("job")
.where("id", "=", jobOperation?.jobId!)
- .select("locationId")
+ .where("companyId", "=", companyId)
+ .select(["locationId", "jobId"])
.executeTakeFirst(),
trx
.selectFrom("item")
@@ -3085,10 +3116,19 @@ const issue = defineServerFn({
// keeps the bin chosen above.
const strictSettings =
adjustmentType !== "Positive Adjmt." && remaining > 0
- ? await getStrictBackflushSettings(trx, companyId)
+ ? await getStrictBackflushSettings(
+ trx,
+ companyId,
+ job?.locationId
+ )
: null;
if (strictSettings?.strict) {
- storageUnitId = material.storageUnitId;
+ storageUnitId =
+ (
+ await resolvePullFromStorageUnits(trx, companyId, [
+ material
+ ])
+ ).get(material.id) ?? null;
await assertBinCovers(trx, {
companyId,
itemId: material.itemId,
@@ -3096,7 +3136,8 @@ const issue = defineServerFn({
storageUnitId,
quantity: remaining,
plannedRows: itemLedgerInserts,
- preventNegative: strictSettings.preventNegative
+ preventNegative: strictSettings.preventNegative,
+ jobReadableId: job?.jobId ?? material.jobId
});
}
itemLedgerInserts.push({
diff --git a/packages/server-functions/src/lib/strict-backflush.ts b/packages/server-functions/src/lib/strict-backflush.ts
index 0d34b9bd9d..5eebb7e8aa 100644
--- a/packages/server-functions/src/lib/strict-backflush.ts
+++ b/packages/server-functions/src/lib/strict-backflush.ts
@@ -13,10 +13,12 @@ import type { Database } from "@carbon/database";
import type { KyselyDatabase as DB } from "@carbon/database/client";
import { inOrder } from "@carbon/database/rows";
import {
+ activationRefusalMessage,
binShortfall,
- getPullFromLocations,
- missingPullFromLocations,
- needsPullFrom,
+ getMethodPartsMissingPullFrom,
+ getStrictBackflushSettings,
+ pullFromStorageUnit,
+ strictBackflushLockKey,
summarizeList
} from "@carbon/database/strict-backflush";
import { getLogger } from "@carbon/logger";
@@ -28,27 +30,10 @@ const logger = getLogger("server-functions", "strict-backflush");
type LedgerInsert = Database["public"]["Tables"]["itemLedger"]["Insert"];
-export type StrictBackflushSettings = {
- strict: boolean;
- /** Only meaningful while `strict`: refuse a short bin instead of letting it
- * go negative. */
- preventNegative: boolean;
-};
-
-export async function getStrictBackflushSettings(
- db: Kysely<DB>,
- companyId: string
-): Promise<StrictBackflushSettings> {
- const row = await db
- .selectFrom("companySettings")
- .where("id", "=", companyId)
- .select(["requireBackflushStorageUnit", "preventNegativeBackflush"])
- .executeTakeFirst();
- return {
- strict: row?.requireBackflushStorageUnit === true,
- preventNegative: row?.preventNegativeBackflush !== false
- };
-}
+export {
+ getStrictBackflushSettings,
+ type StrictBackflushSettings
+} from "@carbon/database/strict-backflush";
export async function isStrictBackflush(
db: Kysely<DB>,
@@ -61,13 +46,76 @@ type BinCoverArgs = {
companyId: string;
itemId: string;
locationId: string;
+ /** The material's Pull From (`resolvePullFromStorageUnits`). */
storageUnitId: string | null | undefined;
quantity: number;
plannedRows: LedgerInsert[];
/** Refuse a short bin (true) or let it go negative (false). */
preventNegative: boolean;
+ /** The job's readable id, for the missing-bin message. */
+ jobReadableId: string;
};
+/**
+ * The Pull From of each material, by job material id. A pick points a line at
+ * lineside; `pullFromStorageUnit` recovers the bin it was picked from, so what
+ * no pick covered still comes from the Pull From.
+ */
+export async function resolvePullFromStorageUnits(
+ db: Kysely<DB>,
+ companyId: string,
+ materials: { id: string; storageUnitId: string | null }[]
+): Promise<Map<string, string | null>> {
+ const ids = materials.map((material) => material.id);
+ const pickLines =
+ ids.length === 0
+ ? []
+ : await db
+ .selectFrom("pickingListLine")
+ .where("companyId", "=", companyId)
+ .where("jobMaterialId", "in", ids)
+ .where("storageUnitId", "is not", null)
+ .select(["jobMaterialId", "storageUnitId", "toStorageUnitId"])
+ .orderBy("createdAt")
+ .orderBy("id")
+ .execute();
+ return new Map(
+ materials.map((material) => [
+ material.id,
+ pullFromStorageUnit(
+ material.storageUnitId,
+ pickLines.filter((line) => line.jobMaterialId === material.id)
+ )
+ ])
+ );
+}
+
+/**
+ * Takes the strict lock of every (bin, item) pair for the rest of the
+ * caller's transaction, in one fixed order (by key hash), so two completions
+ * drawing the same pairs cannot deadlock. SQL `backflush_job_materials` locks
+ * in the same order. Locks are re-entrant, so taking one twice is harmless.
+ */
+export async function lockStrictBins(
+ db: Kysely<DB>,
+ companyId: string,
+ pairs: { storageUnitId: string | null | undefined; itemId: string }[]
+): Promise<void> {
+ const keys = [
+ ...new Set(
+ pairs.flatMap((pair) =>
+ pair.storageUnitId
+ ? [strictBackflushLockKey(companyId, pair.storageUnitId, pair.itemId)]
+ : []
+ )
+ )
+ ];
+ if (keys.length === 0) return;
+ await sql`SELECT pg_advisory_xact_lock(k) FROM (SELECT DISTINCT hashtextextended(key, 0) AS k FROM unnest(${keys}::text[]) AS key ORDER BY k) AS locks`.execute(
+ db
+ );
+}
+
/**
* Refuses (409) when `storageUnitId` is missing or cannot cover `quantity`.
* `plannedRows` are the ledger rows this backflush has built but not yet
@@ -108,7 +156,7 @@ export async function binCoverProblem(
if (!storageUnitId) {
const item = await readItemName(db, itemId, companyId);
- return `${item} has no Pull From storage unit on this job`;
+ return `${item} has no Pull From storage unit on job ${args.jobReadableId}`;
}
// Negative stock allowed: the material is drawn from its own bin whatever
@@ -116,11 +164,9 @@ export async function binCoverProblem(
if (!args.preventNegative) return null;
// 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
- );
+ // ends, so two completions cannot both pass the check and overdraw it.
+ // A caller drawing several pairs locks them all first (`lockStrictBins`).
+ await lockStrictBins(db, companyId, [{ storageUnitId, itemId }]);
const row = await db
.selectFrom("itemLedger")
@@ -165,51 +211,10 @@ export async function assertMethodHasPullFrom(
db: Kysely<DB>,
args: { makeMethodId: string; companyId: string }
): Promise<void> {
- const { makeMethodId, companyId } = args;
-
- const [lines, locations] = await inOrder([
- () =>
- 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}`
- );
+ const parts = await getMethodPartsMissingPullFrom(db, args);
+ if (parts.length > 0) {
+ throw new InvalidInputError(activationRefusalMessage(parts));
+ }
}
async function readItemName(
diff --git a/packages/server-functions/src/strict-backflush.test.ts b/packages/server-functions/src/strict-backflush.test.ts
index 02f1df576f..8dd2263251 100644
--- a/packages/server-functions/src/strict-backflush.test.ts
+++ b/packages/server-functions/src/strict-backflush.test.ts
@@ -23,14 +23,100 @@ 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) {
+// Strict backflush applies only at a location with an active work center and
+// an active storage unit. Every test creates its storage units; turning the
+// setting on adds the work center, unless the test is about its absence.
+async function setStrict(
+ f: Fixture,
+ on: boolean,
+ { withWorkCenter = true }: { withWorkCenter?: boolean } = {}
+) {
await f.db
.updateTable("companySettings")
.set({ requireBackflushStorageUnit: on })
.where("id", "=", f.companyId)
.execute();
+ if (on && withWorkCenter) await workCenterFixture(f);
+}
+
+// Picks `quantity` of a job's material from `from` to `to` the way
+// post-picking does: a live pick line, the transfer in the ledger, and the
+// material pointed at the bin it was picked to.
+async function pick(
+ f: Fixture,
+ job: { jobId: string; materialId: string },
+ from: string,
+ to: string,
+ quantity: number
+) {
+ await seed(f, async (trx) => {
+ const list = await trx
+ .insertInto("pickingList")
+ .values({
+ pickingListId: `${job.jobId}-PL`,
+ locationId: f.locationId,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .returning("id")
+ .executeTakeFirstOrThrow();
+ await trx
+ .insertInto("pickingListLine")
+ .values({
+ pickingListId: list.id,
+ jobId: job.jobId,
+ jobMaterialId: job.materialId,
+ itemId: f.partId,
+ quantityToPick: 2,
+ quantityPicked: quantity,
+ storageUnitId: from,
+ toStorageUnitId: to,
+ status: "Picked",
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+ await trx
+ .insertInto("itemLedger")
+ .values([
+ {
+ entryType: "Transfer",
+ documentType: "Direct Transfer",
+ documentId: list.id,
+ itemId: f.partId,
+ quantity: -quantity,
+ locationId: f.locationId,
+ storageUnitId: from,
+ companyId: f.companyId,
+ createdBy: USER
+ },
+ {
+ entryType: "Transfer",
+ documentType: "Direct Transfer",
+ documentId: list.id,
+ itemId: f.partId,
+ quantity,
+ locationId: f.locationId,
+ storageUnitId: to,
+ companyId: f.companyId,
+ createdBy: USER
+ }
+ ])
+ .execute();
+ await trx
+ .updateTable("jobMaterial")
+ .set({ storageUnitId: to })
+ .where("id", "=", job.materialId)
+ .where("companyId", "=", f.companyId)
+ .execute();
+ });
}
+const byBin = (rows: { storageUnitId: string | null; quantity: number }[]) =>
+ [...rows].sort((a, b) =>
+ (a.storageUnitId ?? "").localeCompare(b.storageUnitId ?? "")
+ );
+
async function storageUnit(f: Fixture, name: string): Promise<string> {
const row = await f.db
.insertInto("storageUnit")
@@ -141,7 +227,7 @@ databaseTest(
quantity: 1
});
expect(result.error?.message).toBe(
- `${f.prefix}-PART has no Pull From storage unit on this job`
+ `${f.prefix}-PART has no Pull From storage unit on job J-1`
);
expect(await consumption(f, job.jobId)).toEqual([]);
} finally {
@@ -188,7 +274,7 @@ databaseTest(
quantity: 1
});
expect(missing.error?.message).toBe(
- `${f.prefix}-PART has no Pull From storage unit on this job`
+ `${f.prefix}-PART has no Pull From storage unit on job J-2`
);
// Job completion (SQL) draws its own bin below zero too.
@@ -412,3 +498,148 @@ databaseTest(
}
}
);
+
+databaseTest(
+ "after a partial pick, the rest comes from the Pull From, not from lineside",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ const shelfA = await storageUnit(f, "Shelf A");
+ const lineside = await storageUnit(f, "Lineside");
+ await stockBin(f, shelfA, 4);
+ await setStrict(f, true);
+
+ // Operation completion: the picked 1 from lineside, the other 1 from
+ // Shelf A — the bin the line was picked from, not lineside again.
+ const job = await jobFixture(f);
+ await setMaterialBin(f, job.materialId, shelfA);
+ await pick(f, job, shelfA, lineside, 1);
+ unwrap(
+ await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1
+ })
+ );
+ expect(byBin(await consumption(f, job.jobId))).toEqual(
+ byBin([
+ { storageUnitId: lineside, quantity: -1 },
+ { storageUnitId: shelfA, quantity: -1 }
+ ])
+ );
+
+ // Job completion (SQL): the same split.
+ const second = await jobFixture(f, "2");
+ await setMaterialBin(f, second.materialId, shelfA);
+ await pick(f, second, shelfA, lineside, 1);
+ await sql`SELECT backflush_job_materials(${second.jobId}, 1, ${f.companyId}, ${USER})`.execute(
+ f.db
+ );
+ expect(byBin(await consumption(f, second.jobId))).toEqual(
+ byBin([
+ { storageUnitId: lineside, quantity: -1 },
+ { storageUnitId: shelfA, quantity: -1 }
+ ])
+ );
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "strict backflush skips a location with no active work center",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ // Activation asks for no Pull From here, so the backflush must not
+ // refuse a line for missing one: the old fallback (the fullest bin)
+ // applies.
+ const shelfB = await storageUnit(f, "Shelf B");
+ await stockBin(f, shelfB, 10);
+ await setStrict(f, true, { withWorkCenter: false });
+
+ const job = await jobFixture(f);
+ unwrap(
+ await issue(f.ctx, {
+ type: "jobOperation",
+ id: job.operationId,
+ quantity: 1
+ })
+ );
+ expect(await consumption(f, job.jobId)).toEqual([
+ { storageUnitId: shelfB, quantity: -2 }
+ ]);
+
+ const second = await jobFixture(f, "2");
+ await sql`SELECT backflush_job_materials(${second.jobId}, 1, ${f.companyId}, ${USER})`.execute(
+ f.db
+ );
+ expect(await consumption(f, second.jobId)).toEqual([
+ { storageUnitId: shelfB, quantity: -2 }
+ ]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);
+
+databaseTest(
+ "the SQL refusal counts every short material against a shared bin",
+ async () => {
+ const f = await alwaysPostFixture();
+ try {
+ // Two lines of 2 on one bin holding 1: both are refused, and the
+ // second sees the first's need already drawn ("have 0"), so the
+ // refusal states the bin's whole shortfall at once. Without that, the
+ // second would read "have 1" and the user would fix it in two rounds.
+ // Holds in either order the loop visits the lines.
+ const shelfA = await storageUnit(f, "Shelf A");
+ await stockBin(f, shelfA, 1);
+ await setStrict(f, true);
+ const job = await jobFixture(f);
+ await setMaterialBin(f, job.materialId, shelfA);
+ const makeMethod = await f.db
+ .selectFrom("jobMakeMethod")
+ .select("id")
+ .where("jobId", "=", job.jobId)
+ .where("companyId", "=", f.companyId)
+ .executeTakeFirstOrThrow();
+ await f.db
+ .insertInto("jobMaterial")
+ .values({
+ jobId: job.jobId,
+ jobMakeMethodId: makeMethod.id,
+ jobOperationId: job.operationId,
+ itemId: f.partId,
+ itemType: "Part",
+ methodType: "Pull from Inventory",
+ description: "Bracket",
+ quantity: 2,
+ estimatedQuantity: 2,
+ unitOfMeasureCode: "EA",
+ storageUnitId: shelfA,
+ companyId: f.companyId,
+ createdBy: USER
+ })
+ .execute();
+
+ const refusal =
+ await sql`SELECT backflush_job_materials(${job.jobId}, 1, ${f.companyId}, ${USER})`
+ .execute(f.db)
+ .then(
+ () => null,
+ (error: Error) => error.message
+ );
+ expect(refusal).toContain(
+ `Not enough ${f.prefix}-PART in ${f.prefix} Shelf A: need 2, have 1`
+ );
+ expect(refusal).toContain(
+ `Not enough ${f.prefix}-PART in ${f.prefix} Shelf A: need 2, have 0`
+ );
+ expect(await consumption(f, job.jobId)).toEqual([]);
+ } finally {
+ await f.cleanup();
+ }
+ }
+);