Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
fix(production): report a job's release outcome truthfully
naveenkashb8eb8fbf9a69
diff --git a/apps/erp/app/modules/production/AGENTS.md b/apps/erp/app/modules/production/AGENTS.mdindex e7669883dc..24f2da69f6 100644--- a/apps/erp/app/modules/production/AGENTS.md+++ b/apps/erp/app/modules/production/AGENTS.md@@ -84,7 +84,7 @@ pnpm --filter @carbon/erp test- `convertSalesOrderLinesToJobs` — creates jobs from sales order Make to Order lines; each job takes the order line's `configuration` (else the converted quote line's, via `resolveJobConfiguration` in `~/modules/sales`) and is built with `itemToJob` instead of `quoteLineToJob` when the order line was reconfigured- `getJob` / `getJobs` / `getJobMethodTree` / `getJobMethodTreeArray` — job reads with method hierarchy-- `releaseJobs` (`production.server.ts`) — the one release path (recalc, MRP, status Ready, outside-operation POs, releasedDate); returns the supplier→PO map with the POs it created so a caller releasing job by job keeps one PO per supplier. Callers: the job Release dialog (`$jobId.status.tsx`), batch release (`releaseBatchMemberJobs`), and the jobs table's bulk **Release Jobs** action (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`). Bulk release has no dialog: each selected Draft/Planned job is checked on its own (`getJobReleaseReadiness` once for the selection — every read goes through `fetchAllByIds`, which sends each id list in groups of 100 (an `in` filter rides in the URL) and pages each group with `fetchAllRecords` (a page of jobs passes PostgREST's 1000-row cap); pinned by `test/job-release-readiness.test.ts` — `jobReleaseProblems` in `ui/Jobs/job-release-logic.ts`, plus zero quantity and — via the per-job `supplierIds` — a supplier with Draft POs to choose from); a job with a problem is skipped and named in the toast's `failed` list, the rest release, then `runLocationSchedule` runs once per location. Pinned by `routes/x+/job+/release.test.ts`+- `releaseJobs` (`production.server.ts`) — the one release path (recalc, MRP, status Ready, outside-operation POs, releasedDate); returns the supplier→PO map with the POs it created so a caller releasing job by job keeps one PO per supplier, and `releasedJobIds` — the jobs that ARE Ready when it returns, so a PO failure after the flip is reported as "released, but …" and the job is still scheduled (bulk route `warnings`, job page flash). The flip is guarded: `updateJobStatus(..., { fromStatuses: ["Draft", "Planned"] })` adds `.in("status", …)` to the UPDATE and returns `updated: false` when the row no longer matched (someone cancelled or released it during the recalc/MRP), so the release stops instead of resurrecting the job; pinned by `test/job-status-guard.test.ts`. A failed MRP run is logged and never blocks the release (the 3-hourly MRP cron and Material Planning's Recalculate repair it); a failed `releasedDate` write is reported as "released, but …" because nothing else writes that date and the completion-time KPI reads it. Pinned by `test/release-jobs.test.ts`. Callers: the job Release dialog (`$jobId.status.tsx`), batch release (`releaseBatchMemberJobs`), and the jobs table's bulk **Release Jobs** action (`x+/job+/release.tsx`, `path.to.bulkReleaseJob`). Bulk release has no dialog: each selected Draft/Planned job is checked on its own (`getJobReleaseReadiness` once for the selection — every read goes through `fetchAllByIds`, which sends each id list in groups of 100 (an `in` filter rides in the URL) and pages each group with `fetchAllRecords` (a page of jobs passes PostgREST's 1000-row cap); pinned by `test/job-release-readiness.test.ts` — `jobReleaseProblems` in `ui/Jobs/job-release-logic.ts`, plus zero quantity and — via the per-job `supplierIds` — a supplier with Draft POs to choose from); a job with a problem is skipped and named in the toast's `failed` list, the rest release, then `runLocationSchedule` runs once per location. Pinned by `routes/x+/job+/release.test.ts`- `getJobMaterialsWithQuantityOnHand` — BOM with on-hand for shortfall visibility- `getJobMaterialShortfallByItem` — priority-adjusted shortfall calculation- `getJobOrderStatusMap` — procurement status indicators per materialdiff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex 286b034ff6..75609fc09b 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -6,6 +6,7 @@ import { getCarbonServiceRole } from "@carbon/auth/client.server";import type { Database } from "@carbon/database";import type { Kysely, KyselyDatabase } from "@carbon/database/client";import { ASSEMBLER_SERVICE_URL } from "@carbon/env";+import { getLogger } from "@carbon/logger";import { serverFns } from "@carbon/server-functions";import { datetime, getErrorMessage } from "@carbon/utils";import type { SupabaseClient } from "@supabase/supabase-js";@@ -17,6 +18,8 @@ import {} from "./production.service";import { jobReleaseProblems } from "./ui/Jobs/job-release-logic";+const logger = getLogger("erp", "production");+// The geometry (assembler) service backs model conversion and motion planning.// When it's unreachable those actions can't run, so loaders probe its health and// the UI soft-gates the assembler-dependent controls. Result cached so a@@ -75,6 +78,9 @@ export async function isAssemblerServiceHealthy(): Promise<boolean> {// supplier's first "new" PO is reused for the jobs after it, so a batch puts// each supplier's outside operations from every member job on one PO. The map// is returned with those POs filled in, for a caller releasing job by job.+// `releasedJobIds` are the jobs that ARE Ready when this returns — on an error+// after the status flip (purchase orders) the job is released, and the caller+// must still schedule it and say so.// Validation (getJobReleaseReadiness) is the caller's, BEFORE this runs.export async function releaseJobs({client,@@ -93,9 +99,16 @@ export async function releaseJobs({}): Promise<{error: string | null;purchaseOrdersBySupplierId: Record<string, string>;+ releasedJobIds: string[];}> {const serviceRole = getCarbonServiceRole();const purchaseOrders = { ...purchaseOrdersBySupplierId };+ const releasedJobIds: string[] = [];+ const fail = (error: string) => ({+ error,+ purchaseOrdersBySupplierId: purchaseOrders,+ releasedJobIds+ });for (const id of jobIds) {const recalc = await recalculateJobRequirements(serviceRole, db, {@@ -103,27 +116,39 @@ export async function releaseJobs({companyId,userId});- if (recalc.error) {- return {- error: `Failed to recalculate job ${id}`,- purchaseOrdersBySupplierId: purchaseOrders- };- }+ if (recalc.error) return fail(`Failed to recalculate job ${id}`);- await runMRP(serviceRole, db, { type: "job", id, companyId, userId });+ // A failed plan never blocks a release: the scheduled MRP run (every 3+ // hours) and Material Planning's Recalculate both repair it.+ const mrp = await runMRP(serviceRole, db, {+ type: "job",+ id,+ companyId,+ userId+ });+ if (mrp.error) {+ logger.error("MRP failed during job release", {+ companyId,+ jobId: id,+ error: mrp.error+ });+ }+ // Only a job still waiting for release flips: the caller checked the+ // status before the recalculation and MRP above, and someone may have+ // cancelled or released it since.const update = await updateJobStatus(client, {id,companyId,status: "Ready",- updatedBy: userId+ updatedBy: userId,+ fromStatuses: ["Draft", "Planned"]});- if (update.error) {- return {- error: `Failed to release job ${id}`,- purchaseOrdersBySupplierId: purchaseOrders- };+ if (update.error) return fail(`Failed to release job ${id}`);+ if (!update.updated) {+ return fail(`Job ${id} is no longer Draft or Planned`);}+ releasedJobIds.push(id);const purchaseOrder = await serverFns.system({ db, companyId, userId })@@ -133,26 +158,41 @@ export async function releaseJobs({purchaseOrdersBySupplierId: purchaseOrders});if (purchaseOrder.error) {- return {- error: getErrorMessage(+ return fail(+ `Job ${id} is released, but its purchase orders could not be created: ${getErrorMessage(purchaseOrder.error,- `Failed to create purchase orders for job ${id}`- ),- purchaseOrdersBySupplierId: purchaseOrders- };+ "unknown error"+ )}`+ );}Object.assign(purchaseOrders,purchaseOrder.data?.purchaseOrderIdsBySupplierId ?? {});- await client+ // The date feeds the completion-time KPI and nothing else writes it, so a+ // silent failure would be permanent.+ const stamped = await client.from("job").update({ releasedDate: datetime.timestamp() }).eq("id", id).eq("companyId", companyId);+ if (stamped.error) {+ logger.error("Failed to stamp the release date", {+ companyId,+ jobId: id,+ error: stamped.error+ });+ return fail(+ `Job ${id} is released, but its release date could not be saved`+ );+ }}- return { error: null, purchaseOrdersBySupplierId: purchaseOrders };+ return {+ error: null,+ purchaseOrdersBySupplierId: purchaseOrders,+ releasedJobIds+ };}// Releasing a batch releases its Draft/Planned member jobs through the samediff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 169d6e8ea5..df24e7a4fd 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -3177,9 +3177,14 @@ export async function updateJobStatus(status: (typeof jobStatus)[number];assignee?: string | null;updatedBy: string;+ // Flip only from one of these statuses. A release reads the status, then+ // runs for a while (recalculate, MRP) before it writes; a job someone+ // cancelled in between must not come back as Ready. `updated` is false+ // when the row no longer matched.+ fromStatuses?: (typeof jobStatus)[number][];}) {- const { id, companyId, status, assignee, updatedBy } = params;+ const { id, companyId, status, assignee, updatedBy, fromStatuses } = params;// Reopening a job (leaving a completed state) must clear completedDate so it// isn't left stale. Done in the same UPDATE as status so the job event@@ -3196,7 +3201,7 @@ export async function updateJobStatus(.eq("companyId", companyId).maybeSingle();- const result = await client+ const update = client.from("job").update({status,@@ -3205,9 +3210,15 @@ export async function updateJobStatus(updatedAt: new Date().toISOString(),...(clearsCompletion ? { completedDate: null } : {})})- .eq("id", id);+ .eq("id", id)+ .eq("companyId", companyId);+ const result = fromStatuses+ ? await update.in("status", fromStatuses).select("id")+ : await update;+ const updated =+ !result.error && (!fromStatuses || (result.data?.length ?? 0) > 0);- if (!result.error && prior.data && prior.data.status !== status) {+ if (updated && prior.data && prior.data.status !== status) {if (status === "Ready") {await raiseMoment("production.jobReleased", {outputs: { job: { id }, releasedBy: { id: updatedBy } },@@ -3231,7 +3242,7 @@ export async function updateJobStatus(}}- return result;+ return { ...result, updated };}/** @mcp update */diff --git a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsxindex b8dd2171e4..6236958b0a 100644--- a/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx+++ b/apps/erp/app/modules/production/ui/Jobs/JobsTable.tsx@@ -703,6 +703,13 @@ const JobsTable = memo((props: JobsTableProps) => {: t`Released ${result.released} jobs`);}+ if (result.warnings.length) {+ toast.error(+ t`Released with problems: ${result.warnings+ .map((w) => `${w.readableId} (${w.message})`)+ .join(", ")}`+ );+ }if (result.failed.length) {toast.error(t`Could not release ${result.failed.length}: ${result.faileddiff --git a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.jsonindex 139f1b5d1c..d8a65ce583 100644--- a/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json+++ b/apps/erp/app/routes/api+/mcp+/lib/tool-manifest.digest.json@@ -791,7 +791,7 @@{"name":"production_updateJobOperationOrder","classification":"WRITE","paramCount":1,"schema":"c822495a7892","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},{"name":"production_updateJobOperationStatus","classification":"WRITE","paramCount":2,"schema":"b22654081076","response":"ac4a3201b981","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"context":"updatedBy=userId"},{"name":"production_updateJobOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},- {"name":"production_updateJobStatus","classification":"WRITE","paramCount":3,"schema":"bb0874693c4d","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},+ {"name":"production_updateJobStatus","classification":"WRITE","paramCount":4,"schema":"458fa5786030","response":"8394fbabd845","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false},{"name":"production_updateKanbanJob","classification":"WRITE","paramCount":2,"schema":"2c22838be2d2","response":"bcde375ebd4c","injectAuth":"companyId+updatedBy+userId","permission":"production:update","paginates":false},{"name":"production_updateMethodOperationStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},{"name":"production_updateProcedureStepOrder","classification":"WRITE","paramCount":1,"schema":"d19d08f2d129","response":"646de62ab761","injectAuth":"companyId+updatedBy","permission":"production:update","paginates":false,"result":"envelopes"},diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts b/apps/erp/app/routes/x+/job+/$jobId.status.test.tsindex d6718a13c0..b9d9fec4f0 100644--- a/apps/erp/app/routes/x+/job+/$jobId.status.test.ts+++ b/apps/erp/app/routes/x+/job+/$jobId.status.test.ts@@ -88,7 +88,11 @@ vi.mock("~/modules/production/production.server", async () => {updatedBy: userId});}- return { error: null, purchaseOrdersBySupplierId: {} };+ return {+ error: null,+ purchaseOrdersBySupplierId: {},+ releasedJobIds: jobIds+ };})};});diff --git a/apps/erp/app/routes/x+/job+/$jobId.status.tsx b/apps/erp/app/routes/x+/job+/$jobId.status.tsxindex db577af9aa..982213ef61 100644--- a/apps/erp/app/routes/x+/job+/$jobId.status.tsx+++ b/apps/erp/app/routes/x+/job+/$jobId.status.tsx@@ -121,6 +121,15 @@ export async function action({ request, params }: ActionFunctionArgs) {)});if (released.error) {+ // The job is Ready when it came back released (its purchase orders+ // failed after the flip): schedule it, then say what failed.+ if (released.releasedJobIds.includes(id)) {+ try {+ await scheduleJobLocation({ id, companyId, userId });+ } catch (err) {+ logger.error("Error", { error: err });+ }+ }throw redirect(requestReferrer(request) ?? path.to.job(id),await flash(request, error(null, released.error))diff --git a/apps/erp/app/routes/x+/job+/release.test.ts b/apps/erp/app/routes/x+/job+/release.test.tsindex 035599318b..b7812936b2 100644--- a/apps/erp/app/routes/x+/job+/release.test.ts+++ b/apps/erp/app/routes/x+/job+/release.test.ts@@ -107,9 +107,10 @@ const run = (jobIds: string[]) =>beforeEach(() => {vi.clearAllMocks();vi.mocked(releaseJobs).mockImplementation(- async ({ purchaseOrdersBySupplierId }) => ({+ async ({ jobIds, purchaseOrdersBySupplierId }) => ({error: null,- purchaseOrdersBySupplierId+ purchaseOrdersBySupplierId,+ releasedJobIds: jobIds}));});@@ -138,6 +139,7 @@ describe("bulk job release", () => {expect(result).toEqual({success: true,released: 2,+ warnings: [],failed: [],scheduled: true});@@ -219,10 +221,11 @@ describe("bulk job release", () => {},error: null});- vi.mocked(releaseJobs).mockResolvedValue({+ vi.mocked(releaseJobs).mockImplementation(async ({ jobIds }) => ({error: null,- purchaseOrdersBySupplierId: { "supplier-a": "po-new" }- });+ purchaseOrdersBySupplierId: { "supplier-a": "po-new" },+ releasedJobIds: jobIds+ }));await run(["j1", "j2"]);@@ -249,7 +252,8 @@ describe("bulk job release", () => {});vi.mocked(releaseJobs).mockImplementation(async ({ jobIds }) => ({error: jobIds[0] === "j2" ? "Failed to recalculate job j2" : null,- purchaseOrdersBySupplierId: {}+ purchaseOrdersBySupplierId: {},+ releasedJobIds: jobIds[0] === "j2" ? [] : jobIds}));const result = await run(["j1", "j2", "j3", "j4"]);@@ -264,6 +268,39 @@ describe("bulk job release", () => {).toEqual(["location-1", "location-2"]);});+ it("counts and schedules a job released before its purchase orders failed", async () => {+ setup([job("j1"), job("j2", { locationId: "location-2" })]);+ vi.mocked(getJobReleaseReadiness).mockResolvedValue({+ data: { jobs: [ready("j1"), ready("j2")], suppliers: [] },+ error: null+ });+ vi.mocked(releaseJobs).mockImplementation(async ({ jobIds }) => ({+ error:+ jobIds[0] === "j1"+ ? "Job j1 is released, but its purchase orders could not be created: no supplier currency"+ : null,+ purchaseOrdersBySupplierId: {},+ releasedJobIds: jobIds+ }));++ const result = await run(["j1", "j2"]);++ expect(result).toMatchObject({+ released: 2,+ failed: [],+ warnings: [+ {+ readableId: "J1",+ message:+ "Job j1 is released, but its purchase orders could not be created: no supplier currency"+ }+ ]+ });+ expect(+ vi.mocked(runLocationSchedule).mock.calls.map(([args]) => args.locationId)+ ).toEqual(["location-1", "location-2"]);+ });+it("says so when the released jobs could not be scheduled", async () => {setup([job("j1")]);vi.mocked(getJobReleaseReadiness).mockResolvedValue({diff --git a/apps/erp/app/routes/x+/job+/release.tsx b/apps/erp/app/routes/x+/job+/release.tsxindex 8ab3c65c8f..1ad8300db3 100644--- a/apps/erp/app/routes/x+/job+/release.tsx+++ b/apps/erp/app/routes/x+/job+/release.tsx@@ -92,6 +92,8 @@ export async function action({ request }: ActionFunctionArgs) {let released = 0;const failed: { readableId: string; message: string }[] = [];+ // Released, with something left to fix on the job (its purchase orders).+ const warnings: { readableId: string; message: string }[] = [];const locationIds = new Set<string>();for (const job of releasable) {const ready = readinessByJobId.get(job.id);@@ -129,9 +131,16 @@ export async function action({ request }: ActionFunctionArgs) {jobId: job.id,error: result.error});- failed.push({ readableId: job.jobId, message: result.error });+ }+ // The job is Ready when its id came back released, error or not; a job+ // that is Ready must be scheduled and counted, whatever failed after.+ if (!result.releasedJobIds.includes(job.id)) {+ failed.push({ readableId: job.jobId, message: result.error ?? "" });continue;}+ if (result.error) {+ warnings.push({ readableId: job.jobId, message: result.error });+ }locationIds.add(job.locationId);released += 1;@@ -159,5 +168,5 @@ export async function action({ request }: ActionFunctionArgs) {}}- return { success: true as const, released, failed, scheduled };+ return { success: true as const, released, warnings, failed, scheduled };}diff --git a/apps/erp/test/job-status-guard.test.ts b/apps/erp/test/job-status-guard.test.tsnew file mode 100644index 0000000000..ff574e3b10--- /dev/null+++ b/apps/erp/test/job-status-guard.test.ts@@ -0,0 +1,87 @@+// 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 { beforeEach, describe, expect, it, vi } from "vitest";++// The service's imports reach the glossary, whose `msg` macro only runs compiled.+vi.mock("@lingui/core/macro", () => ({+ msg: (strings: TemplateStringsArray) => ({ id: strings.join("") })+}));+vi.mock("@carbon/lib/workflows", () => ({ raiseMoment: vi.fn() }));+vi.mock("@carbon/lib/telemetry", () => ({+ asJobSource: vi.fn(),+ trackWorkEvent: vi.fn()+}));++import { raiseMoment } from "@carbon/lib/workflows";+import { updateJobStatus } from "../app/modules/production/production.service";++// A job row behind a chainable client stand-in. The UPDATE applies its `in`+// filter on the status, as the database would, and returns the rows it changed.+function clientWith(job: { id: string; status: string }) {+ const calls: string[] = [];+ const chain: Record<string, any> = {};+ let statusFilter: string[] | null = null;+ for (const method of ["select", "update", "eq"]) {+ chain[method] = vi.fn(() => chain);+ }+ chain.in = vi.fn((_column: string, values: string[]) => {+ calls.push("in");+ statusFilter = values;+ return chain;+ });+ chain.maybeSingle = vi.fn(async () => ({+ data: { status: job.status },+ error: null+ }));+ chain.then = (resolve: (value: unknown) => unknown) => {+ const matched = !statusFilter || statusFilter.includes(job.status);+ return Promise.resolve({+ data: matched ? [{ id: job.id }] : [],+ error: null+ }).then(resolve);+ };+ return { client: { from: () => chain } as any, calls };+}++const release = (client: any) =>+ updateJobStatus(client, {+ id: "job-1",+ companyId: "company-1",+ status: "Ready",+ updatedBy: "user-1",+ fromStatuses: ["Draft", "Planned"]+ });++beforeEach(() => vi.clearAllMocks());++describe("updateJobStatus with fromStatuses", () => {+ it("flips a job that is still waiting for release", async () => {+ const { client, calls } = clientWith({ id: "job-1", status: "Planned" });+ const result = await release(client);+ expect(calls).toEqual(["in"]);+ expect(result.updated).toBe(true);+ expect(raiseMoment).toHaveBeenCalledTimes(1);+ });++ it("leaves a job someone cancelled in the meantime alone", async () => {+ const { client } = clientWith({ id: "job-1", status: "Cancelled" });+ const result = await release(client);+ expect(result.error).toBeNull();+ expect(result.updated).toBe(false);+ expect(raiseMoment).not.toHaveBeenCalled();+ });++ it("flips without a guard when no statuses are given", async () => {+ const { client, calls } = clientWith({ id: "job-1", status: "Cancelled" });+ const result = await updateJobStatus(client, {+ id: "job-1",+ companyId: "company-1",+ status: "Ready",+ updatedBy: "user-1"+ });+ expect(calls).toEqual([]);+ expect(result.updated).toBe(true);+ });+});diff --git a/apps/erp/test/release-jobs.test.ts b/apps/erp/test/release-jobs.test.tsnew file mode 100644index 0000000000..e2c2b4d11c--- /dev/null+++ b/apps/erp/test/release-jobs.test.ts@@ -0,0 +1,102 @@+// 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 { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@carbon/auth/client.server", () => ({+ getCarbonServiceRole: vi.fn(() => ({}))+}));+vi.mock("@carbon/env", () => ({ ASSEMBLER_SERVICE_URL: "" }));+vi.mock("@carbon/logger", () => ({+ getLogger: () => ({ error: vi.fn() })+}));+vi.mock("@carbon/server-functions", () => ({+ serverFns: {+ system: () => ({+ invoke: vi.fn(async () => ({+ data: { purchaseOrderIdsBySupplierId: {} },+ error: null+ }))+ })+ }+}));+vi.mock("../app/modules/production/production.service", () => ({+ getJobReleaseReadiness: vi.fn(),+ recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),+ runMRP: vi.fn(async () => ({ data: null, error: null })),+ updateJobStatus: vi.fn(async () => ({ error: null, updated: true }))+}));++import {+ runMRP,+ updateJobStatus+} from "../app/modules/production/production.service";+import { releaseJobs } from "../app/modules/production/production.server";++// The release-date write: a chainable, thenable stand-in for the user client.+function clientWith(stamp: { error: null | { message: string } }) {+ const chain: Record<string, any> = {};+ for (const method of ["update", "eq"]) chain[method] = () => chain;+ chain.then = (resolve: (value: unknown) => unknown) =>+ Promise.resolve({ data: null, ...stamp }).then(resolve);+ return { from: () => chain } as any;+}++const release = (client: any, jobIds = ["job-1"]) =>+ releaseJobs({+ client,+ db: {} as any,+ jobIds,+ companyId: "company-1",+ userId: "user-1",+ purchaseOrdersBySupplierId: {}+ });++beforeEach(() => vi.clearAllMocks());++describe("releaseJobs", () => {+ it("releases past a failed MRP run", async () => {+ vi.mocked(runMRP).mockResolvedValueOnce({+ data: null,+ error: new Error("planning blew up")+ });+ const result = await release(clientWith({ error: null }));+ expect(result).toEqual({+ error: null,+ purchaseOrdersBySupplierId: {},+ releasedJobIds: ["job-1"]+ });+ });++ it("flips only a job still Draft or Planned, and stops when it is not", async () => {+ vi.mocked(updateJobStatus).mockResolvedValueOnce({+ error: null,+ updated: false+ } as any);+ const result = await release(clientWith({ error: null }), [+ "job-1",+ "job-2"+ ]);+ expect(vi.mocked(updateJobStatus).mock.calls[0]?.[1]).toMatchObject({+ status: "Ready",+ fromStatuses: ["Draft", "Planned"]+ });+ expect(result).toEqual({+ error: "Job job-1 is no longer Draft or Planned",+ purchaseOrdersBySupplierId: {},+ releasedJobIds: []+ });+ });++ it("reports a failed release-date write on a job that is released", async () => {+ const result = await release(+ clientWith({ error: { message: "connection reset" } })+ );+ expect(result).toEqual({+ error: "Job job-1 is released, but its release date could not be saved",+ purchaseOrdersBySupplierId: {},+ releasedJobIds: ["job-1"]+ });+ });+});diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 0353c08eaa..f8e7c00e50 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -14923,6 +14923,10 @@ msgstr "Freigegebene Revision"msgid "Released revision is locked"msgstr "Freigegebene Revision ist gesperrt"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Freigegeben mit Problemen: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Die Freigabe des Loses gibt seine Fertigungsaufträge frei, und jeder muss für die Werkstatt bereit sein."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex ff1e862efe..448f3f99a8 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -14923,6 +14923,10 @@ msgstr "Released revision"msgid "Released revision is locked"msgstr "Released revision is locked"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Released with problems: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Releasing the batch releases its jobs, and each one must be ready for the floor."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 47f0e380ca..ca7d2709f1 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -14923,6 +14923,10 @@ msgstr "Revisión lanzada"msgid "Released revision is locked"msgstr "La revisión lanzada está bloqueada"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Liberado con problemas: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Liberar el lote de producción libera sus órdenes de trabajo, y cada una debe estar lista para la planta."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 62bf395937..8c67cfd074 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -14923,6 +14923,10 @@ msgstr "Révision publiée"msgid "Released revision is locked"msgstr "La révision publiée est verrouillée"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Lancé avec des problèmes : {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Lancer le lot de production lance ses ordres de fabrication, et chacun doit être prêt pour l'atelier."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 02ccd5c21f..2c40d9fd1f 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -14923,6 +14923,10 @@ msgstr "जारी रिवीजन"msgid "Released revision is locked"msgstr "जारी रिवीजन लॉक है"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "समस्याओं के साथ जारी: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "बैच जारी करने से इसकी जॉब्स जारी हो जाती हैं, और प्रत्येक को शॉप फ्लोर के लिए तैयार होना चाहिए।"@@ -18770,7 +18774,7 @@ msgid "The SAML metadata URL published by your identity provider"msgstr "आपके आइडेंटिटी प्रदाता द्वारा प्रकाशित SAML मेटाडेटा URL"msgid "The schedule could not be updated after the release"-msgstr "रिलीज के बाद शेड्यूल को अपडेट नहीं किया जा सका"+msgstr "जारी करने के बाद शेड्यूल को अपडेट नहीं किया जा सका"msgid "The schedule used to spread this asset's cost over its useful life (straight-line, declining balance, units of production)."msgstr "यह शेड्यूल जिसका उपयोग इस संपत्ति की लागत को इसके उपयोगी जीवन (सीधी लाइन मूल्यह्रास, ह्रासमान शेष, उत्पादन की इकाई) पर फैलाने के लिए किया जाता है।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex 2764d21346..fae60db10f 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -14923,6 +14923,10 @@ msgstr "Revisione rilasciata"msgid "Released revision is locked"msgstr "La revisione rilasciata è bloccata"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Rilasciato con problemi: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Rilasciare il lotto di produzione rilascia i suoi ordini di produzione, e ognuno deve essere pronto per l'officina."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 936910e62e..fab2124385 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -14923,6 +14923,10 @@ msgstr "リリースされたリビジョン"msgid "Released revision is locked"msgstr "発行済みリビジョンはロック中です"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "リリース済(警告あり): {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "バッチをリリースするとその製造指図がリリースされ、それぞれが製造現場に対応可能である必要があります。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex ce1c2d8efc..75b0a5f9d7 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -14923,6 +14923,10 @@ msgstr "릴리스된 리비전"msgid "Released revision is locked"msgstr "릴리스된 리비전은 잠김입니다."+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "릴리스됨 (문제 있음): {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "배치를 릴리스하면 포함된 작업 지시들도 릴리스되고, 각각은 현장에 준비되어야 합니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex d6986321d9..a19e4472dd 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -14923,6 +14923,10 @@ msgstr "Zwolniona rewizja"msgid "Released revision is locked"msgstr "Zwolniona rewizja jest zablokowana"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Zwolniono z problemami: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Zwolnienie partii produkcyjnej zwalnia jej zlecenia produkcyjne, a każde musi być gotowe na halę produkcyjną."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex d050afd726..87d1a72f9d 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -14923,6 +14923,10 @@ msgstr "Revisão lançada"msgid "Released revision is locked"msgstr "A revisão lançada está bloqueada"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Liberado com problemas: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Liberar o lote de produção libera suas ordens de produção, e cada uma deve estar pronta para o chão de fábrica."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex 3127cdf76d..e599b27ebb 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -14923,6 +14923,10 @@ msgstr "Выпущенная ревизия"msgid "Released revision is locked"msgstr "Выпущенная ревизия заблокирована"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Запущено с проблемами: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Запуск серии запускает её производственные заказы, и каждый должен быть готов к цеху."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex e27555a126..686e2dc57b 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -14923,6 +14923,10 @@ msgstr "Yayınlanan revizyon"msgid "Released revision is locked"msgstr "Yayınlanan revizyon kilitlidir"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "Sorunlarla serbest bırakıldı: {0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "Partiyi serbest bırakmak iş emirlerini serbest bırakır ve her birinin atölye için hazır olması gerekir."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 52fcee7272..530f294915 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -14923,6 +14923,10 @@ msgstr "已下达修订版"msgid "Released revision is locked"msgstr "已下达修订版已锁定"+#. placeholder {0}: result.warnings .map((w) => `${w.readableId} (${w.message})`) .join(", ")+msgid "Released with problems: {0}"+msgstr "已下达,存在问题:{0}"+msgid "Releasing the batch releases its jobs, and each one must be ready for the floor."msgstr "下达生产批次会下达其工单,每个工单都必须为车间做好准备。"