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): release kanban jobs as the system; use useAction for mutations

naveenkasha24eebe0b3e9
diff --git a/.claude/rules/kanban-system.md b/.claude/rules/kanban-system.md
index f4a7353d3b..ead0272532 100644
--- a/.claude/rules/kanban-system.md
+++ b/.claude/rules/kanban-system.md
@@ -76,7 +76,7 @@ RLS: SELECT = any employee role; INSERT/UPDATE/DELETE = `inventory_create`/`inve
API routes in `apps/erp/app/routes/api+/`: `kanban.$id.tsx`, `kanban.collision.$id.tsx`, `kanban.start.$id.tsx`, `kanban.complete.$id.tsx`, `kanban.link.$id.tsx`.
`kanban.$id.tsx` (the "order"/create scan) calls `scanKanban` (`inventory.server.ts`), which branches on `replenishmentSystem` and returns what it made; the route picks the page:
-- **Make** — if a job is already linked (`jobReadableId`) it returns `collision` and the route opens the collision page (no duplicate job); otherwise creates a job from the item and links it (`updateKanbanJob`). With `autoRelease`, `scanKanban` runs the release checks (`getJobReleaseReadiness` + `jobReleaseProblems` — nothing to make, manufacturing blocked, assemblies without operations, outside operations without a supplier, strict backflush lines with no storage unit), then `releaseCheckedJobs` (recalculate, MRP, Ready, outside-operation POs, release date; telemetry `source: "kanban"`), then `runLocationSchedule` once the job is Ready. Unlike `releaseJobs`, a supplier's Draft PO is not a blocker — no one at a kanban card can choose one — so the outside operations go on the supplier's newest Draft PO (highest `purchaseOrderId`), else a new one; otherwise the first scan's PO blocked every later scan. A job that fails the checks stays Draft, stays linked, and the scan returns a `message`; the route throws `redirect(jobPage, flash(…))` with it. Returning the flash with `data()` does not work: the root's `flashMiddleware` clears it on the same request. Only a released job sends the scanner to MES: `autoStartJob` opens its first operation's start, else the operation. See `apps/erp/app/modules/production/AGENTS.md` → "Every path to Ready".
+- **Make** — if a job is already linked (`jobReadableId`) it returns `collision` and the route opens the collision page (no duplicate job); otherwise creates a job from the item and links it (`updateKanbanJob`). With `autoRelease`, `scanKanban` runs the release checks (`getJobReleaseReadiness` + `jobReleaseProblems` — nothing to make, manufacturing blocked, assemblies without operations, outside operations without a supplier, strict backflush lines with no storage unit), then `releaseCheckedJobs` as the system on behalf of the scanner, so a scanner without production update can still release (recalculate, MRP, Ready, outside-operation POs, release date; telemetry `source: "kanban"`), then `runLocationSchedule` once the job is Ready. Unlike `releaseJobs`, a supplier's Draft PO is not a blocker — no one at a kanban card can choose one — so the outside operations go on the supplier's newest Draft PO (highest `purchaseOrderId`), else a new one; otherwise the first scan's PO blocked every later scan. A job that fails the checks stays Draft, stays linked, and the scan returns a `message`; the route throws `redirect(jobPage, flash(…))` with it. Returning the flash with `data()` does not work: the root's `flashMiddleware` clears it on the same request. Only a released job sends the scanner to MES: `autoStartJob` opens its first operation's start, else the operation. See `apps/erp/app/modules/production/AGENTS.md` → "Every path to Ready".
- **Buy** — reuses an existing draft/planned PO for the supplier (or creates one), adds a PO line with the kanban qty (applying `conversionFactor`/`purchaseUnitOfMeasureCode`/storage unit), redirects to the PO.
- **Transfer** — calls `replenishKanban` (`inventory.service.ts`, ported from the `kanban-replenish` server function) with `mode: "scan"`, which writes a Released stock transfer with one line: `itemId`, `fromStorageUnitId` → `storageUnitId` (to), `quantity`, and serial/batch flags from `item.itemTrackingType` (a serial line of qty > 1 splits into qty-1 lines, `expandSerialTrackedLines`). The transfer carries `stockTransfer.kanbanId` and a Tiptap note "Kanban replenishment — … Signal: scan by <user>." Redirects to the stock transfer, where the qty can be **partially picked** at pick time. Each scan makes a new transfer, with no level test. Storage rules are NOT evaluated (a QR scan can't show the acknowledge dialog the interactive wizard uses). `scanKanban` calls it as the scanner (`invokePosting` with the scanner's client and `{ as: replenishKanbanPermission }`): scan mode needs `create: "inventory"`, the same check the `stockTransfer` RLS rule made when the route inserted directly. Never drop the client or the `as` — that lets any employee create transfers. The function re-checks that both bins belong to the company and the kanban's location (CWE-639).
- **Buy and Make** — not a kanban option (the enum has no such value).
diff --git a/apps/erp/app/modules/inventory/inventory.server.ts b/apps/erp/app/modules/inventory/inventory.server.ts
index 5a944dfa84..9ef461f56d 100644
--- a/apps/erp/app/modules/inventory/inventory.server.ts
+++ b/apps/erp/app/modules/inventory/inventory.server.ts
@@ -46,6 +46,7 @@ import {
upsertPurchaseOrderLine
} from "~/modules/purchasing/purchasing.service";
import { recordSalesRuleOutcome } from "~/modules/sales/sales.service";
+import { systemContext } from "~/modules/service-context.server";
import {
getCompanySettings,
getNextSequence
@@ -3412,7 +3413,14 @@ export const scanKanban = defineServiceFn({
};
}
- const result = await releaseCheckedJobs(ctx, {
+ // As the system, like the job it releases: the scanner may not hold
+ // production update, and the status write runs on the caller's client.
+ const system = systemContext({
+ companyId,
+ companyGroupId: ctx.company.groupId,
+ onBehalfOf: userId
+ });
+ const result = await releaseCheckedJobs(system, {
jobIds: [jobId],
purchaseOrdersBySupplierId: Object.fromEntries(
(readiness.data?.suppliers ?? []).map((supplier) => [
diff --git a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
index f94318d529..0f303005f0 100644
--- a/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
+++ b/apps/erp/app/modules/items/ui/Item/BillOfMaterial.tsx
@@ -57,12 +57,7 @@ import {
LuTrash,
LuTruck
} from "react-icons/lu";
-import {
- useFetcher,
- useFetchers,
- useParams,
- useSearchParams
-} from "react-router";
+import { useFetchers, useParams, useSearchParams } from "react-router";
import type { z } from "zod";
import { MethodIcon, SourcingTypeIcon } from "~/components";
import { ConfigurationEditor } from "~/components/Configurator/ConfigurationEditor";
@@ -99,6 +94,8 @@ import type {
MethodType,
SourcingType
} from "~/modules/shared/types";
+import type { action as updateMaterialAction } from "~/routes/x+/items+/methods+/material.$id";
+import type { action as createMaterialAction } from "~/routes/x+/items+/methods+/material.new";
import type { Item as ItemType } from "~/stores";
import { useItems } from "~/stores";
import { path } from "~/utils/path";
@@ -207,7 +204,7 @@ const BillOfMaterial = ({
const [items] = useItems();
const itemName = getItemById(items, makeMethod.itemId)?.name;
- const fetcher = useFetcher<{}>();
+ const fetcher = useAction();
const deleteMaterialFetcher = useAction();
const [searchParams] = useSearchParams();
@@ -654,11 +651,21 @@ function MaterialForm({
}) {
const { t } = useLingui();
const { carbon } = useCarbon();
- const methodMaterialFetcher = useFetcher<{
- id: string;
- success: boolean;
- message: string;
- }>();
+ const methodMaterialFetcher = useAction<
+ typeof createMaterialAction | typeof updateMaterialAction
+ >({
+ onSuccess: (data) => {
+ // A refused save returns `{ id: null }` and flashes its own error.
+ if (!data.id) return;
+ // The saved row replaces the temporary one when the page reloads.
+ setTemporaryItems((prev) => {
+ const { [item.id]: _, ...rest } = prev;
+ return rest;
+ });
+ if ("message" in data) toast.success(data.message);
+ onSubmit();
+ }
+ });
const params = useParams();
const parentItemId = propParentItemId ?? params.itemId;
const { company, defaults } = useUser();
@@ -682,22 +689,6 @@ function MaterialForm({
const sourcingDisclosure = useDisclosure();
const backflushDisclosure = useDisclosure();
- useEffect(() => {
- // Remove from temporary items after successful submission
- if (methodMaterialFetcher.data && methodMaterialFetcher.data.id) {
- // Clear temporary item after successful save
- setTemporaryItems((prev) => {
- const { [item.id]: _, ...rest } = prev;
- return rest;
- });
-
- if (methodMaterialFetcher.data.success) {
- toast.success(methodMaterialFetcher.data.message);
- }
- onSubmit();
- }
- }, [item.id, methodMaterialFetcher.data, setTemporaryItems, onSubmit]);
-
const [itemType, setItemType] = useState<MethodItemType>(item.data.itemType);
const [itemData, setItemData] = useState<{
itemId: string;
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.md
index 96d165f7c3..82fb4090b0 100644
--- a/apps/erp/app/modules/production/AGENTS.md
+++ b/apps/erp/app/modules/production/AGENTS.md
@@ -117,7 +117,7 @@ pnpm --filter erp test
|---|---|
| `releaseJobs` (Release dialog, bulk release, planning, API/MCP) | `jobReleaseProblems` per job, then `releaseCheckedJobs` |
| Batch release (`releaseBatchMemberJobs`) | `jobReleaseProblems`, all-or-nothing, then `releaseCheckedJobs` |
- | Kanban scan with `autoRelease` (`scanKanban`, `inventory.server.ts`) | `jobReleaseProblems`, then `releaseCheckedJobs` (`source: "kanban"`; outside operations go on the supplier's newest Draft PO, else a new one — no one is there to choose), then `runLocationSchedule`. A refused job stays Draft and linked to the kanban; the route redirects to the job with a flash naming the problems, and MES is not opened |
+ | Kanban scan with `autoRelease` (`scanKanban`, `inventory.server.ts`) | `jobReleaseProblems`, then `releaseCheckedJobs` as the system on behalf of the scanner (`source: "kanban"`; outside operations go on the supplier's newest Draft PO, else a new one — no one is there to choose), then `runLocationSchedule`. A refused job stays Draft and linked to the kanban; the route redirects to the job with a flash naming the problems, and MES is not opened |
`resumeJob` (Paused → Ready) is not a release. `updateJobStatus` is not published, so the API cannot set Ready without the checks. No SQL function sets a job to Ready (the SQL writes of `'Ready'` are on `jobOperation`). A new path to Ready must run `jobReleaseProblems` before `releaseCheckedJobs`.
- `getJobMaterialsWithQuantityOnHand` — BOM with on-hand for shortfall visibility
diff --git a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
index ab42c94577..9449f245e5 100644
--- a/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
+++ b/apps/erp/app/modules/production/ui/Batches/BatchReleaseModal.tsx
@@ -3,6 +3,7 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { MESSAGE_LIST_LIMIT } from "@carbon/database/strict-backflush";
+import { useLoaderQuery } from "@carbon/query";
import {
Alert,
AlertDescription,
@@ -20,7 +21,7 @@ import {
import { Trans, useLingui } from "@lingui/react/macro";
import { useEffect, useState } from "react";
import { LuShoppingCart, LuTriangleAlert } from "react-icons/lu";
-import { Link, useFetcher } from "react-router";
+import { Link } from "react-router";
import Select from "~/components/Select";
import SupplierAvatar from "~/components/SupplierAvatar";
import { path } from "~/utils/path";
@@ -57,22 +58,19 @@ export function BatchReleaseModal({
? 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 }
- >();
const [purchaseOrders, setPurchaseOrders] = useState<Record<string, string>>(
{}
);
- const url = path.to.api.batchReleaseReadiness(target);
- // biome-ignore lint/correctness/useExhaustiveDependencies: load once per target
- useEffect(() => {
- readinessFetcher.load(url);
- }, [url]);
-
- const result = readinessFetcher.data;
- const readiness = result && "jobs" in result ? result : null;
- const loadError = result && "error" in result ? result.error : null;
+ // `staleTime: 0`: the checks are read again each time the modal opens.
+ const readinessQuery = useLoaderQuery<JobReleaseReadiness>(
+ path.to.api.batchReleaseReadiness(target),
+ { staleTime: 0 }
+ );
+ const readiness = readinessQuery.data ?? null;
+ const loadError = readinessQuery.isError
+ ? t`Failed to check the batch's jobs`
+ : null;
useEffect(() => {
if (!readiness) return;
diff --git a/apps/erp/app/routes/api+/kanban.collision.$id.tsx b/apps/erp/app/routes/api+/kanban.collision.$id.tsx
index 206e920670..819d1a4b89 100644
--- a/apps/erp/app/routes/api+/kanban.collision.$id.tsx
+++ b/apps/erp/app/routes/api+/kanban.collision.$id.tsx
@@ -5,11 +5,12 @@
import { error, notFound, success } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { useAction } from "@carbon/query";
import { Button, Heading } from "@carbon/react";
import { redirect } from "@carbon/utils";
import { LuTriangleAlert } from "react-icons/lu";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router";
-import { data, Link, useFetcher, useLoaderData } from "react-router";
+import { data, Link, useLoaderData } from "react-router";
import { getKanban } from "~/modules/inventory/inventory.service";
import {
getJob,
@@ -79,7 +80,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
export default function KanbanCollisionRoute() {
const { id, existingJob } = useLoaderData<typeof loader>();
- const fetcher = useFetcher<typeof action>();
+ const fetcher = useAction<typeof action>();
if (!existingJob) return null;
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 0cefef0bfb..6cdde48d3f 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Fehler beim Hinzufügen von Zeilen"
msgid "Failed to apply pricing rules"
msgstr "Preisregeln konnten nicht angewendet werden"
+msgid "Failed to check the batch's jobs"
+msgstr "Die Aufträge des Loses konnten nicht überprüft werden"
+
msgid "Failed to convert image"
msgstr "Fehler beim Konvertieren des Bildes"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 209dc26fd3..51bc90ff1f 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Failed to add lines"
msgid "Failed to apply pricing rules"
msgstr "Failed to apply pricing rules"
+msgid "Failed to check the batch's jobs"
+msgstr "Failed to check the batch's jobs"
+
msgid "Failed to convert image"
msgstr "Failed to convert image"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 3085cb4c74..0e1d3fc2b6 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Error al agregar líneas"
msgid "Failed to apply pricing rules"
msgstr "No se pudieron aplicar las reglas de precios"
+msgid "Failed to check the batch's jobs"
+msgstr "No se pudieron comprobar las órdenes de trabajo del lote de producción"
+
msgid "Failed to convert image"
msgstr "Error al convertir imagen"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index e89ff8986f..3bb4ca8706 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Échec de l'ajout des lignes"
msgid "Failed to apply pricing rules"
msgstr "Impossible d'appliquer les règles de prix"
+msgid "Failed to check the batch's jobs"
+msgstr "Impossible de vérifier les ordres de fabrication du lot de production"
+
msgid "Failed to convert image"
msgstr "Échec de la conversion d'image"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 86b47c4b61..7fb15762f7 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -9741,6 +9741,9 @@ msgstr "पंक्तियां जोड़ने में विफल"
msgid "Failed to apply pricing rules"
msgstr "मूल्य निर्धारण नियम लागू करने में विफल"
+msgid "Failed to check the batch's jobs"
+msgstr "बैच की जॉब्स की जाँच नहीं हो सकी"
+
msgid "Failed to convert image"
msgstr "छवि परिवर्तित करने में विफल"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 7ba006b30a..49ecd2949f 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Impossibile aggiungere righe"
msgid "Failed to apply pricing rules"
msgstr "Impossibile applicare le regole di prezzo"
+msgid "Failed to check the batch's jobs"
+msgstr "Impossibile controllare gli ordini di produzione nel lotto"
+
msgid "Failed to convert image"
msgstr "Conversione immagine non riuscita"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index c985d0bff4..bbeb90b110 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -9741,6 +9741,9 @@ msgstr "行を追加できませんでした"
msgid "Failed to apply pricing rules"
msgstr "価格ルールの適用に失敗しました"
+msgid "Failed to check the batch's jobs"
+msgstr "バッチの製造指図を確認できませんでした"
+
msgid "Failed to convert image"
msgstr "画像の変換に失敗しました"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 389d6ab0a9..1ab52b6351 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -9741,6 +9741,9 @@ msgstr "라인 추가 실패"
msgid "Failed to apply pricing rules"
msgstr "가격 규칙을 적용하지 못했습니다"
+msgid "Failed to check the batch's jobs"
+msgstr "배치의 작업 지시를 확인하지 못했습니다"
+
msgid "Failed to convert image"
msgstr "이미지 전환 실패"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 52ad8d8f63..c55fda2566 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Nie udało się dodać wierszy"
msgid "Failed to apply pricing rules"
msgstr "Nie udało się zastosować reguł cenowych"
+msgid "Failed to check the batch's jobs"
+msgstr "Nie udało się sprawdzić zleceń partii produkcyjnej"
+
msgid "Failed to convert image"
msgstr "Nie udało się przekonwertować obrazu."
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index 1fbb09f9cc..ffe1c75b05 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Falha ao adicionar linhas"
msgid "Failed to apply pricing rules"
msgstr "Falha ao aplicar as regras de preço"
+msgid "Failed to check the batch's jobs"
+msgstr "Não foi possível verificar as ordens de produção do lote de produção"
+
msgid "Failed to convert image"
msgstr "Falha ao converter imagem"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 792ecb40b0..4565b453f2 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Ошибка при добавлении строк"
msgid "Failed to apply pricing rules"
msgstr "Не удалось применить правила ценообразования"
+msgid "Failed to check the batch's jobs"
+msgstr "Не удалось проверить производственные заказы серии"
+
msgid "Failed to convert image"
msgstr "Ошибка преобразования изображения"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index e0787e33a8..3810b320a7 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -9741,6 +9741,9 @@ msgstr "Satırlar ekleme başarısız oldu"
msgid "Failed to apply pricing rules"
msgstr "Fiyatlandırma kuralları uygulanamadı"
+msgid "Failed to check the batch's jobs"
+msgstr "Partinin iş emirleri kontrol edilemedi"
+
msgid "Failed to convert image"
msgstr "Resim dönüştürme başarısız oldu"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index d925b6019c..eba0765089 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -9741,6 +9741,9 @@ msgstr "添加行失败"
msgid "Failed to apply pricing rules"
msgstr "无法应用定价规则"
+msgid "Failed to check the batch's jobs"
+msgstr "无法检查生产批次的工单"
+
msgid "Failed to convert image"
msgstr "图像转换失败"