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
// 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 {
DEFAULT_HANDLE,
entityValue,
type RuntimeValue
} from "@carbon/ee/workflows";
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { EngineStep, RunPayload } from "./execute";
vi.mock("@carbon/ee/workflows.server", () => ({
workflowsEnabledForCompany: vi.fn(async () => true)
}));
vi.mock("../../db", () => ({ getJobDatabaseClient: () => ({}) }));
vi.mock("./log", () => ({
loadRunContext: vi.fn(),
claimRun: vi.fn(async () => true),
finishRun: vi.fn(async () => {})
}));
vi.mock("./ledger", () => ({
claimStep: vi.fn(async () => ({ claimed: true, stepRunId: "s1" })),
settleStep: vi.fn(async () => {}),
failInterruptedSteps: vi.fn(async () => 0)
}));
// @carbon/auth builds its Supabase client at import time; ./owner imports it.
vi.mock("@carbon/auth", () => ({}));
vi.mock("@carbon/auth/client.server", () => ({}));
// The owner's reads are faked; the permission rule itself is real.
vi.mock("./owner", async (importOriginal) => ({
...(await importOriginal<typeof import("./owner")>()),
// The engine reads the company custom fields through this client; a bare {} has no
// `.from`, so the stub answers that one query with an empty list.
getOwnerClient: vi.fn(async () => ({
from: () => ({
select: () => ({
eq: () => ({ eq: async () => ({ data: [], error: null }) })
})
})
})),
readOwnerPermissions: vi.fn()
}));
vi.mock("../actions", () => ({ createWorkflowServices: vi.fn() }));
const { executeWorkflowRun } = await import("./execute");
const { loadRunContext, claimRun, finishRun } = await import("./log");
const { claimStep, settleStep } = await import("./ledger");
const { readOwnerPermissions } = await import("./owner");
/** The owner's Purchasing grants in co1. */
function purchasing(...actions: ("view" | "create" | "update" | "delete")[]) {
const grant = (action: string) =>
actions.includes(action as never) ? ["co1"] : [];
return {
purchasing: {
view: grant("view"),
create: grant("create"),
update: grant("update"),
delete: grant("delete")
}
};
}
const { createWorkflowServices } = await import("../actions");
const definition = {
formatVersion: 2,
nodes: [
{
id: "t1",
type: "trigger",
position: { x: 0, y: 0 },
data: { events: ["purchaseOrder.status.changed"], origin: "Both" }
},
{
id: "act",
type: "action",
position: { x: 0, y: 1 },
data: {
action: "purchaseOrder.update",
inputs: {
purchaseOrder: { kind: "ref", nodeId: "t1", output: "record" }
}
}
}
],
edges: [
{
id: "e1",
source: "t1",
sourceHandle: DEFAULT_HANDLE,
target: "act",
targetHandle: "in"
}
]
};
const payload: RunPayload = {
runId: "run1",
companyId: "co1",
workflowId: "wf1",
workflowVersionId: "wv1",
eventId: "purchaseOrder.status.changed",
ownerId: "u1",
sourceEventId: "pgmq:1",
trigger: {
kind: "record",
table: "purchaseOrder",
recordId: "po1",
operation: "UPDATE",
record: { id: "po1" },
before: { id: "po1", status: "Draft" },
after: { id: "po1", status: "To Receive" }
}
};
const logger = { info: vi.fn(), error: vi.fn() };
function harness() {
const ids: string[] = [];
const step: EngineStep = {
run: async (id, handler) => {
ids.push(id);
return handler();
}
};
return { ids, step };
}
const runAction = vi.fn(
async (_id: string, _inputs: Record<string, RuntimeValue>) => ({
ok: true as const,
outputs: { record: entityValue("purchaseOrder", "po1") }
})
);
beforeEach(() => {
vi.clearAllMocks();
vi.mocked(claimRun).mockResolvedValue(true);
vi.mocked(readOwnerPermissions).mockResolvedValue(
purchasing("view", "update")
);
vi.mocked(claimStep).mockResolvedValue({ claimed: true, stepRunId: "s1" });
vi.mocked(createWorkflowServices).mockReturnValue({
runAction,
runIntegration: async () => ({ ok: false as const, error: "not stubbed" }),
runOperation: async () => ({ ok: false, error: "not stubbed" }),
search: async () => ({ ok: false, error: "not stubbed" })
});
vi.mocked(loadRunContext).mockResolvedValue({
run: {
id: "run1",
companyId: "co1",
ownerId: "u1",
workflowId: "wf1",
workflowVersionId: "wv1",
eventId: "purchaseOrder.status.changed",
status: "Queued"
},
workflowPublished: true,
companyGroupId: "cg1",
version: definition
});
});
describe("the owner's permissions", () => {
it("fails the action step by name when the owner has lost the module", async () => {
const { step } = harness();
// The trigger's own view check still passes; only the action's update is gone.
vi.mocked(readOwnerPermissions).mockResolvedValue(purchasing("view"));
const result = await executeWorkflowRun({ payload, step, logger });
expect(vi.mocked(settleStep).mock.calls.at(-1)?.[1]).toMatchObject({
status: "Failed",
error: "The owner of this workflow no longer has access to Purchasing."
});
expect(runAction).not.toHaveBeenCalled();
expect(result.status).toBe("Failed");
});
it("refuses the whole run when the trigger's own module is gone", async () => {
const { ids, step } = harness();
vi.mocked(readOwnerPermissions).mockResolvedValue(purchasing());
await executeWorkflowRun({ payload, step, logger });
expect(ids).toEqual(["load", "custom-fields", "permissions"]);
expect(vi.mocked(finishRun).mock.calls.at(-1)?.[1]).toMatchObject({
status: "Failed",
error: "The owner of this workflow no longer has access to Purchasing."
});
});
});
describe("a second delivery of the same event", () => {
it("runs no node, because only a Queued row may be claimed", async () => {
const { ids, step } = harness();
vi.mocked(claimRun).mockResolvedValue(false);
const result = await executeWorkflowRun({ payload, step, logger });
expect(result).toEqual({ runId: "run1", status: "Duplicate", steps: 0 });
expect(ids).toEqual(["load"]);
expect(claimStep).not.toHaveBeenCalled();
expect(runAction).not.toHaveBeenCalled();
});
});
/**
* The run row's `error` was hard-coded `null` unless the step CAP was hit, so every
* ordinary failure — the common case — reached the run page as a bare
* "Failed at <step>." The reason was sitting in the step row the whole time.
* A real report: a Google Calendar step failed with "Cannot read properties of
* undefined (reading 'length')" and the run page showed nothing at all.
*/
describe("a failed run says WHY it failed", () => {
const VENDOR_ERROR =
"Google Calendar rejected this: Cannot read properties of undefined (reading 'length')";
it("carries the failing step's error onto the run", async () => {
const { step } = harness();
runAction.mockResolvedValueOnce({
ok: false,
error: VENDOR_ERROR
} as never);
const result = await executeWorkflowRun({ payload, step, logger });
expect(result.status).toBe("Failed");
// The run row is what the run page leads with — not the step row.
expect(vi.mocked(finishRun).mock.calls.at(-1)?.[1]).toMatchObject({
status: "Failed",
error: VENDOR_ERROR
});
});
// A run that genuinely succeeded must not acquire an error from a previous one.
it("leaves the error null when nothing failed", async () => {
const { step } = harness();
const result = await executeWorkflowRun({ payload, step, logger });
expect(result.status).toBe("Succeeded");
expect(vi.mocked(finishRun).mock.calls.at(-1)?.[1]).toMatchObject({
status: "Succeeded",
error: null
});
});
});