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): number a job's serial units in the completion's transaction
Raul728b86ff773e
diff --git a/apps/erp/app/modules/production/production.server.ts b/apps/erp/app/modules/production/production.server.tsindex 6e9f1d1081..89081cc08e 100644--- a/apps/erp/app/modules/production/production.server.ts+++ b/apps/erp/app/modules/production/production.server.ts@@ -876,7 +876,8 @@ export const closeJob = defineServiceFn({* rules; its message says what to fix (a `rule` error). When the item's serial* number timing (its own, else the company's) is release or production, the* units the completion takes are split off the job's seed, created when no- * record holds them yet, and numbered first. Then the picked material the job did not+ * record holds them yet, and numbered first, in the completion's transaction,+ * so a refused completion spends no numbers. Then the picked material the job did not* consume is returned to the warehouse; a failure there leaves the job* completed and is returned as `warning`.*@@ -898,38 +899,45 @@ export const completeJob = defineServiceFn({// The units this completion takes may be unnumbered, or still one unsplit// seed (a deferred serial number timing, or a job left so when its timing// changed): the receipt is their first touch, so split and number them- // before the RPC receives them.- try {- await service.numberSerialUnitsForCompletion(ctx.asSystem.pg, {- jobId,- quantityComplete,- companyId- });- } catch (error) {- return ctx.error(- "internal",- "Failed to number the serial units being completed",- error- );- }+ // before complete_job_to_inventory receives them. Both run in one+ // transaction, as in the sync_finish_job_operation interceptor, so a+ // refused completion spends no serial numbers.+ const completed = await ctx.transaction(async (tx) => {+ try {+ await service.numberSerialUnitsForCompletion(tx.asSystem.pg, {+ jobId,+ quantityComplete,+ companyId+ });+ } catch (error) {+ return ctx.error(+ "internal",+ "Failed to number the serial units being completed",+ error+ );+ }- // It must NOT write job.quantityShipped: that column is advanced only by- // post-shipment, and the shipment builder ships quantityComplete less it.- const rpc = await ctx.asCaller.supabase.rpc("complete_job_to_inventory", {- p_job_id: jobId,- p_quantity_complete: quantityComplete,- p_storage_unit_id: storageUnitId,- p_location_id: locationId,- p_company_id: companyId,- p_user_id: userId+ // It must NOT write job.quantityShipped: that column is advanced only by+ // post-shipment, and the shipment builder ships quantityComplete less it.+ try {+ await service.completeJobToInventory(tx.asSystem.pg, {+ jobId,+ quantityComplete,+ storageUnitId,+ locationId,+ companyId,+ userId+ });+ } catch (error) {+ return ctx.error(+ "rule",+ (error instanceof Error && error.message) || "Failed to complete job",+ error+ );+ }+ return null;});- if (rpc.error) {- return ctx.error(- "rule",- rpc.error.message || "Failed to complete job",- rpc.error- );- }+ if (completed.error) return completed.error;// A re-completion is supported; the job id is the idempotency key, so a// repeat collapses rather than counting a second completion.diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.tsindex 8550346acf..4d823279b8 100644--- a/apps/erp/app/modules/production/production.service.ts+++ b/apps/erp/app/modules/production/production.service.ts@@ -12807,7 +12807,8 @@ export async function assignSerialNumbers(* the `sync_finish_job_operation` interceptor (an operation marked Done) share* one implementation. It is a no-op when every unit taken is numbered, for an* item with no serial sequence, and when the job cannot cover the completion.- * It commits on its own, before the RPC.+ * `completeJob` runs it in the completion's own transaction, so a refused+ * completion rolls the numbering back.*/export async function numberSerialUnitsForCompletion(db: Kysely<KyselyDatabase>,@@ -12823,6 +12824,34 @@ export async function numberSerialUnitsForCompletion(return { numbered: Number(result.rows[0]?.numbered ?? 0) };}+/**+ * Receive a job's completion through `complete_job_to_inventory`, on the given+ * connection or transaction. It throws when the function refuses; the message+ * says what to fix.+ */+export async function completeJobToInventory(+ db: Kysely<KyselyDatabase>,+ args: {+ jobId: string;+ quantityComplete: number;+ storageUnitId?: string;+ locationId?: string;+ companyId: string;+ userId: string;+ }+) {+ await sql`+ SELECT complete_job_to_inventory(+ p_job_id := ${args.jobId},+ p_quantity_complete := ${args.quantityComplete}::numeric,+ p_storage_unit_id := ${args.storageUnitId ?? null},+ p_location_id := ${args.locationId ?? null},+ p_company_id := ${args.companyId},+ p_user_id := ${args.userId}+ )+ `.execute(db);+}+const sandboxLogger = getLogger("erp", "configuration-rule");/**diff --git a/apps/erp/test/database/serial-number-timing.test.ts b/apps/erp/test/database/serial-number-timing.test.tsindex fa7d03be98..f532ec65d9 100644--- a/apps/erp/test/database/serial-number-timing.test.ts+++ b/apps/erp/test/database/serial-number-timing.test.ts@@ -390,6 +390,37 @@ describe.skipIf(!client)("serial number timing", () => {}});+ it("spends no number when the completion is refused after numbering", async () => {+ const f = await alwaysPostFixture();+ try {+ await stockPart(f, 20);+ await serialSetup(f, "production");+ const job = await untouchedSerialJob(f, "refused", 3);++ // The receipt into a storage unit that does not exist fails after the+ // units are split and numbered.+ const result = await completeJob(contextFor(f), {+ jobId: job.jobId,+ quantityComplete: 2,+ storageUnitId: "no-such-storage-unit",+ locationId: f.locationId+ });++ expect(result.error?.category).toBe("rule");+ expect(await units(f, job.makeMethodId)).toEqual([+ expect.objectContaining({ readableId: null, quantity: 3 })+ ]);+ const sequence = await f.db+ .selectFrom("itemSerialSequence")+ .select("next")+ .where("itemId", "=", f.assemblyId)+ .executeTakeFirstOrThrow();+ expect(Number(sequence.next)).toBe(0);+ } finally {+ await f.cleanup();+ }+ });+it("creates the units no row holds when a completion follows the shop floor", async () => {const f = await alwaysPostFixture();try {diff --git a/apps/erp/test/job-lifecycle.test.ts b/apps/erp/test/job-lifecycle.test.tsindex 32a0af45a2..e5ab9fed2c 100644--- a/apps/erp/test/job-lifecycle.test.ts+++ b/apps/erp/test/job-lifecycle.test.ts@@ -58,8 +58,10 @@ vi.mock("../app/modules/shared/shared.service", async (importOriginal) => {vi.mock("@carbon/planning", () => ({ runLocationSchedule: vi.fn() }));vi.mock("../app/modules/production/production.service", async (importOriginal) => ({...(await importOriginal<object>()),- // The SQL numbering needs a database; serial-number-timing.test.ts covers it.+ // The SQL numbering and receipt need a database;+ // serial-number-timing.test.ts covers them.numberSerialUnitsForCompletion: vi.fn(async () => ({ numbered: 0 })),+ completeJobToInventory: vi.fn(async () => {}),recalculateJobRequirements: vi.fn(async () => ({ data: null, error: null })),runMRP: vi.fn(async () => ({ data: null, error: null })),returnPickedRemaindersForJob: vi.fn(async () => ({ data: {}, error: null })),@@ -70,6 +72,7 @@ vi.mock("../app/modules/production/production.service", async (importOriginal) =}));import {+ completeJobToInventory,returnPickedRemaindersForJob,upsertProductionQuantity} from "../app/modules/production/production.service";@@ -86,11 +89,8 @@ import { createServiceContext } from "@carbon/api/service-fn.server";/** Every status the job was moved to, with the statuses the move allowed. */let statusWrites: { status: unknown; fromStatuses?: unknown }[] = [];-/** The user client: the job as read, its status writes, and the completion RPC's answer. */-function callerWith(- job: Record<string, unknown> | null,- rpc: { error: { message: string } | null } = { error: null }-) {+/** The user client: the job as read and its status writes. */+function callerWith(job: Record<string, unknown> | null) {const read: Record<string, unknown> = {};for (const method of ["select", "eq"]) read[method] = () => read;read.maybeSingle = async () => ({ data: job, error: null });@@ -108,10 +108,7 @@ function callerWith(};return write;};- return {- from: () => ({ ...read, update }),- rpc: async () => ({ data: null, ...rpc })- };+ return { from: () => ({ ...read, update }) };}const contextWith = (caller: unknown) =>@@ -126,7 +123,9 @@ const contextWith = (caller: unknown) =>company: { id: "c1", groupId: "g1" },caller: caller as never,system: () => ({}) as never,- pg: () => ({}) as never,+ // An open transaction: ctx.transaction joins it, and the service+ // functions that would use it are stubbed above.+ pg: () => ({ isTransaction: true }) as never,kv: () => ({}) as never});@@ -267,11 +266,10 @@ describe("completeJob", () => {completeJob(contextWith(caller), { jobId: "j1", quantityComplete: 5 });it("returns the database's refusal as a rule, and returns nothing picked", async () => {- const result = await complete(- callerWith(null, {- error: { message: "Quantity is below what was received" }- })+ vi.mocked(completeJobToInventory).mockRejectedValueOnce(+ new Error("Quantity is below what was received"));+ const result = await complete(callerWith(null));expect(result.error).toMatchObject({category: "rule",message: "Quantity is below what was received"