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(quality): make issue disposition quantity editable (#1612)

BettrCallRaulfbb70a035413
diff --git a/.ai/lessons.md b/.ai/lessons.md
index b75f4b4327..5f0cc32fe1 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -1561,3 +1561,13 @@ full-screen ERP route.
**Rule:** Two layers, both required. (1) Any `json`/`jsonb` value written through Kysely in an edge function goes through `lib/json.ts` `toJson()`, which pre-serialises every non-null shape so the wire value is valid JSON text. (2) A validator for a rich-text column is never `z.any()`; use the shared `optionalTiptapDoc` / `toTiptapDoc` in `shared.models.ts`, which turns text, a JSON-encoded doc, or a doc object into a tiptap document and rejects the rest. Put `.optional()` AFTER the transform or zod infers a required key. When an edge function fails opaquely, read the function's own log (Supabase management API `function_logs`), not the caller's.
**Applies to:** `packages/database/supabase/functions/**` Kysely inserts of `internalNotes`, `externalNotes`, `customFields`, `priceTrace`, `configuration`, `additionalCharges`; every `*.models.ts` field that feeds a rich-text column (the purchasing `notes: z.any()` fields still need this).
+
+## An unchecked supabase-js insert turns a NOT NULL violation into silence
+
+**Context:** Inspection rejects were supposed to seed `nonConformanceItemTrackedEntity` links on the NCR's default Scrap row so the MRB could split or reassign specific entities. Nothing ever appeared. Both writers — `x+/inspection+/$id.reject.tsx` and `x+/issue+/new.tsx`'s job-operation auto-link — built their rows without `nonConformanceId`, which is `NOT NULL` on that table (`20260421130000_nc-item-tracked-entity.sql`).
+
+**Problem:** Every such insert returned a 23502, and nobody read it. The reject route did `await (serviceRole as any).from(...).insert(rows)` and discarded the result entirely, so the feature had never worked in production and no error surfaced anywhere. supabase-js does not throw — it resolves to `{ data, error }` — so an unchecked insert is indistinguishable from a successful one, and the `as any` cast additionally hid that the row type was missing a required column. A Kysely insert in the same place would have thrown.
+
+**Rule:** Never discard a supabase-js write result — bind it and check `.error`, even for a fire-and-forget link write. Treat `as any` on a `.from(...).insert(...)` as a defect in review: the cast exists precisely because the row object does not satisfy the generated type, which is the compiler telling you a required column is missing. When a "seeded" side table is mysteriously empty, check the writer's error handling before suspecting the read.
+
+**Applies to:** every `.from(...).insert(...)` / `.update(...)` whose result is not bound, especially in post-commit "also link X" tails; fixed for both writers in PR #1612 by moving them into a Kysely transaction under `lockIssueDispositions`.
diff --git a/.claude/rules/audit-log-system.md b/.claude/rules/audit-log-system.md
index 5ef3f9d4b6..1bc679c50e 100644
--- a/.claude/rules/audit-log-system.md
+++ b/.claude/rules/audit-log-system.md
@@ -23,7 +23,7 @@ The partition key *is the table name* — there is **no `companyId` column**. Co
- `entityId` TEXT — business entity PK the change rolls up to
- `recordId` TEXT — raw PK of the changed row; equals `entityId` for root tables, differs for children
- `operation` TEXT CHECK IN (`INSERT`,`UPDATE`,`DELETE`)
-- `actorId` TEXT | null — user who made the change; null = system/service-role (captured via `auth.uid()` in `dispatch_event_batch`)
+- `actorId` TEXT | null — user who made the change; null = system/service-role. Captured via `auth.uid()` in `dispatch_event_batch`, which is NULL on a direct Kysely connection (no `request.jwt.claims` GUC). The handler therefore falls back to the row's own audit columns — `record.actorId ?? new.updatedBy ?? new.createdBy ?? old.updatedBy ?? old.createdBy` (`packages/jobs/src/inngest/functions/events/audit.ts`) — so a Kysely write is still attributed, provided it stamps `updatedBy`/`createdBy`. A write that stamps neither logs as "System"
- `diff` JSONB | null — `{ field: { old, new, snapshot? } }`
- `metadata` JSONB | null — `ipAddress`, `userAgent`, `origin`, `requestId`
- `createdAt` TIMESTAMPTZ — original event time (handler passes `event.timestamp`; falls back to `clock_timestamp()` per row)
diff --git a/.claude/rules/inspection-system.md b/.claude/rules/inspection-system.md
index f75f0018ef..2d75933ec2 100644
--- a/.claude/rules/inspection-system.md
+++ b/.claude/rules/inspection-system.md
@@ -214,7 +214,8 @@ quality engine stays pure (verdicts only); orchestration lives in
(`getInspectionOutcomeState` — buckets recomputed fresh from the DB per POST;
`getSerialCompletionCandidates` / `postSerialCompletions` /
`postBulkCompletion`; `createInspectionRejectionIssue` — the NCR block lifted
-from the retired reject route).
+from the retired reject route; it passes `inspectionId` to `createQualityIssue` so the
+inspection link is written with the disposition row under the issue lock).
| Decision | Physical postings |
|---|---|
diff --git a/.claude/rules/issue-module.md b/.claude/rules/issue-module.md
index d19105d8ad..9dbf6fadf3 100644
--- a/.claude/rules/issue-module.md
+++ b/.claude/rules/issue-module.md
@@ -49,8 +49,27 @@ in the migrations — **newest wins**; core tables created in
(`Inventory` / `Non-Inventory`, e.g. a job-operation NCR from `apps/mes` or a
rejected non-tracked inbound-inspection lot) — they carry a `quantity` and no
`nonConformanceItemTrackedEntity` links. `AssociatedItemsList.tsx` renders these as
- a quantity + disposition `Select` (no entity chips; "Move entities" stays gated on
- `links.length > 0`). **Split** works for a non-tracked row as a pure quantity split
+ an inline-editable quantity + disposition `Select` (no entity chips; "Move entities"
+ stays gated on `links.length > 0`). The quantity saves through `item+/update.tsx`
+ (`field: "quantity"`) → `updateIssueItemQuantity` (`quality-disposition.server.ts`),
+ which refuses rows with entity links (their quantity is the link sum) and any NCR with
+ a `nonConformanceInspection` link (the reject already wrote off the lot, and
+ `closeIssue` restores `row.quantity` on Use As Is / Rework). The write is a
+ compare-and-set on `expectedQuantity` (the quantity the client last saw), so a stale
+ save matches no row and is refused. It is a Kysely write, so the audit actor comes
+ from `updatedBy` (the audit handler's fallback when `auth.uid()` is null).
+- **Issue disposition lock**: `lockIssueDispositions` (`@carbon/database/quality`)
+ takes `FOR NO KEY UPDATE` on the `nonConformance` row. Every writer that inserts
+ `nonConformanceItemTrackedEntity` / `nonConformanceInspection` rows or changes
+ `nonConformanceItem.quantity` takes it first, inside its transaction, before touching
+ any item row: the quantity edit, `assignEntitiesToIssueItem`, `splitIssueItem`, the
+ inspection association (`$id.association.new.tsx`), `new.tsx` job-operation
+ auto-link, the ERP inspection reject, sales-return escalation, and MES
+ `linkIssueDispositionContext` (which also writes the MES reject's inspection link, via
+ `createQualityIssue({ inspectionId })`). `linkEntitiesToIssueItemRow` is the shared
+ find-or-create-row + link + grow-quantity step. A new writer of those tables must take
+ the lock too, or the quantity edit's link / inspection checks can race it.
+- **Split** works for a non-tracked row as a pure quantity split
(`splitIssueItem` creates a new `Pending` row for the split-off quantity and shrinks
the original, no entity subdivision), so MRB can e.g. scrap N and use-as-is the
rest. `closeIssue` still requires every row (tracked or not) to be non-`Pending`.
diff --git a/apps/erp/app/modules/quality/AGENTS.md b/apps/erp/app/modules/quality/AGENTS.md
index 6afff7ce92..26c152c73b 100644
--- a/apps/erp/app/modules/quality/AGENTS.md
+++ b/apps/erp/app/modules/quality/AGENTS.md
@@ -18,6 +18,7 @@ Non-conformances (issues/NCRs), corrective/preventive actions (CAPAs), gauge man
- MUST check `isIssueLocked(status)` before allowing edits — Closed issues are locked.
- MUST use `deleteIssueAssociation` with the `type` parameter for managing NCR links — it handles 10+ association types via `nonConformanceAssociationType`.
- MUST scope all queries by `companyId`.
+- MUST take `lockIssueDispositions` (`@carbon/database/quality`) first, inside the transaction, before inserting `nonConformanceItemTrackedEntity` / `nonConformanceInspection` rows or changing `nonConformanceItem.quantity` — the inline quantity edit's link and inspection checks rely on every such writer holding it. See `.claude/rules/issue-module.md`.
- MUST use `saveInspectionDocumentAtomic` RPC for inspection document saves — it handles balloons and features atomically.
### Ask First
diff --git a/apps/erp/app/modules/quality/quality-disposition.server.test.ts b/apps/erp/app/modules/quality/quality-disposition.server.test.ts
new file mode 100644
index 0000000000..10c49f8a54
--- /dev/null
+++ b/apps/erp/app/modules/quality/quality-disposition.server.test.ts
@@ -0,0 +1,333 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// @carbon/glossary's terms.ts evaluates Lingui `msg` macros at module load,
+// which vitest doesn't transform; the module graph pulls it in transitively.
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+
+type Row = Record<string, unknown>;
+type Tables = Record<string, Row[]>;
+
+// An in-memory stand-in for the Kysely transaction: enough of the query
+// builder for these writers, plus an ordered log of reads, writes and locks so
+// the tests can assert the issue lock is taken before anything else.
+let tables: Tables;
+let log: string[];
+
+function matches(row: Row, filters: [string, string, unknown][]) {
+ return filters.every(([column, op, value]) =>
+ op === "in"
+ ? (value as unknown[]).includes(row[column])
+ : String(row[column]) === String(value)
+ );
+}
+
+function query(table: string, kind: "select" | "update" | "insert") {
+ const filters: [string, string, unknown][] = [];
+ const orders: string[] = [];
+ let patch: Row = {};
+ let values: Row[] = [];
+ let locked = false;
+
+ const run = (): Row[] => {
+ const rows = (tables[table] ??= []);
+ if (kind === "insert") {
+ log.push(`insert:${table}`);
+ const inserted = values.map((v, i) => ({
+ id: `${table}-${rows.length + i + 1}`,
+ ...v
+ }));
+ rows.push(...inserted);
+ return inserted;
+ }
+ const hit = rows.filter((r) => matches(r, filters));
+ // Real sorting, not a no-op: a row picked out of a split item's siblings is
+ // only deterministic if orderBy actually orders.
+ for (const column of [...orders].reverse()) {
+ hit.sort((a, b) =>
+ String(a[column] ?? "").localeCompare(String(b[column] ?? ""))
+ );
+ }
+ if (kind === "update") {
+ log.push(`update:${table}`);
+ for (const r of hit) Object.assign(r, patch);
+ return hit;
+ }
+ log.push(`${locked ? "lock" : "read"}:${table}`);
+ return hit;
+ };
+
+ const builder: any = {
+ select: () => builder,
+ returning: () => builder,
+ set: (value: Row) => {
+ patch = value;
+ return builder;
+ },
+ values: (value: Row | Row[]) => {
+ values = Array.isArray(value) ? value : [value];
+ return builder;
+ },
+ where: (column: string, op: string, value: unknown) => {
+ filters.push([column, op, value]);
+ return builder;
+ },
+ orderBy: (column: string) => {
+ orders.push(column);
+ return builder;
+ },
+ forNoKeyUpdate: () => {
+ locked = true;
+ return builder;
+ },
+ execute: async () => run(),
+ executeTakeFirst: async () => run()[0],
+ executeTakeFirstOrThrow: async () => {
+ const row = run()[0];
+ if (!row) throw new Error("no result");
+ return row;
+ }
+ };
+ return builder;
+}
+
+const trx = {
+ selectFrom: (table: string) => query(table, "select"),
+ updateTable: (table: string) => query(table, "update"),
+ insertInto: (table: string) => query(table, "insert")
+};
+
+vi.mock("~/services/database.server", () => ({
+ getDatabaseClient: () => ({
+ transaction: () => ({
+ execute: async (fn: (t: typeof trx) => unknown) => fn(trx)
+ })
+ })
+}));
+vi.mock("./quality.server", () => ({
+ errResult: (message: string) => ({ data: null, error: { message } })
+}));
+
+import {
+ linkEntitiesToIssueItemRow,
+ updateIssueItemQuantity
+} from "./quality-disposition.server";
+
+function seed(overrides: Partial<Tables> = {}) {
+ tables = {
+ nonConformance: [{ id: "nc-1", companyId: "c-1", status: "In Progress" }],
+ nonConformanceItem: [
+ {
+ id: "nci-1",
+ nonConformanceId: "nc-1",
+ itemId: "item-1",
+ quantity: 0,
+ companyId: "c-1"
+ }
+ ],
+ nonConformanceItemTrackedEntity: [],
+ nonConformanceInspection: [],
+ ...overrides
+ };
+ log = [];
+}
+
+const edit = (quantity: number, expectedQuantity: number) =>
+ updateIssueItemQuantity({
+ id: "nci-1",
+ companyId: "c-1",
+ userId: "u-1",
+ quantity,
+ expectedQuantity
+ });
+
+const itemRow = () => tables.nonConformanceItem[0];
+
+beforeEach(() => seed());
+
+describe("updateIssueItemQuantity", () => {
+ it("locks the issue before checking links and writing", async () => {
+ const result = await edit(5, 0);
+
+ expect(result.error).toBeNull();
+ expect(itemRow().quantity).toBe(5);
+ const lockAt = log.indexOf("lock:nonConformance");
+ expect(lockAt).toBeGreaterThan(-1);
+ expect(log.indexOf("read:nonConformanceItemTrackedEntity")).toBeGreaterThan(
+ lockAt
+ );
+ expect(log.indexOf("read:nonConformanceInspection")).toBeGreaterThan(
+ lockAt
+ );
+ expect(log.indexOf("update:nonConformanceItem")).toBeGreaterThan(lockAt);
+ });
+
+ it("refuses an older save that completes after a newer one", async () => {
+ const newer = await edit(7, 0);
+ const older = await edit(5, 0);
+
+ expect(newer.error).toBeNull();
+ expect(older.error?.message).toMatch(/changed since the page loaded/);
+ expect(itemRow().quantity).toBe(7);
+ });
+
+ it("refuses a row with linked tracked entities", async () => {
+ seed({
+ nonConformanceItemTrackedEntity: [
+ {
+ id: "l-1",
+ nonConformanceItemId: "nci-1",
+ nonConformanceId: "nc-1",
+ trackedEntityId: "te-1",
+ quantity: 1,
+ companyId: "c-1"
+ }
+ ]
+ });
+ const result = await edit(4, 0);
+
+ expect(result.error?.message).toMatch(/linked tracked entities/);
+ expect(itemRow().quantity).toBe(0);
+ });
+
+ it("refuses an issue with an inspection link", async () => {
+ seed({
+ nonConformanceInspection: [
+ { id: "i-1", nonConformanceId: "nc-1", companyId: "c-1" }
+ ]
+ });
+ const result = await edit(4, 0);
+
+ expect(result.error?.message).toMatch(/inspection lot/);
+ expect(itemRow().quantity).toBe(0);
+ });
+
+ it("refuses a closed issue", async () => {
+ seed({
+ nonConformance: [{ id: "nc-1", companyId: "c-1", status: "Closed" }]
+ });
+ const result = await edit(4, 0);
+
+ expect(result.error?.message).toMatch(/closed issue/);
+ expect(itemRow().quantity).toBe(0);
+ });
+});
+
+describe("linkEntitiesToIssueItemRow", () => {
+ const link = (
+ entities: { id: string; quantity: number }[],
+ fallbackQuantity?: number
+ ) =>
+ linkEntitiesToIssueItemRow(trx as any, {
+ nonConformanceId: "nc-1",
+ companyId: "c-1",
+ userId: "u-1",
+ itemId: "item-1",
+ entities,
+ fallbackQuantity
+ });
+
+ it("grows the row quantity by the linked entities", async () => {
+ await link([
+ { id: "te-1", quantity: 2 },
+ { id: "te-2", quantity: 3 }
+ ]);
+
+ expect(itemRow().quantity).toBe(5);
+ expect(tables.nonConformanceItemTrackedEntity).toHaveLength(2);
+ });
+
+ it("skips entities already linked on the issue", async () => {
+ seed({
+ nonConformanceItemTrackedEntity: [
+ {
+ id: "l-1",
+ nonConformanceItemId: "nci-other",
+ nonConformanceId: "nc-1",
+ trackedEntityId: "te-1",
+ quantity: 2,
+ companyId: "c-1"
+ }
+ ]
+ });
+ await link([
+ { id: "te-1", quantity: 2 },
+ { id: "te-2", quantity: 3 }
+ ]);
+
+ expect(itemRow().quantity).toBe(3);
+ expect(tables.nonConformanceItemTrackedEntity).toHaveLength(2);
+ });
+
+ it("creates the row when the item has none", async () => {
+ seed({ nonConformanceItem: [] });
+ await link([{ id: "te-1", quantity: 4 }]);
+
+ expect(tables.nonConformanceItem).toHaveLength(1);
+ expect(itemRow().quantity).toBe(4);
+ });
+
+ it("links onto the oldest row when the item has been split", async () => {
+ // splitIssueItem leaves two rows for one item. The split-off row is listed
+ // first here, so a bare executeTakeFirst grows the wrong one.
+ seed({
+ nonConformanceItem: [
+ {
+ id: "nci-split",
+ nonConformanceId: "nc-1",
+ itemId: "item-1",
+ quantity: 0,
+ companyId: "c-1",
+ createdAt: "2026-02-01T00:00:00.000Z"
+ },
+ {
+ id: "nci-1",
+ nonConformanceId: "nc-1",
+ itemId: "item-1",
+ quantity: 0,
+ companyId: "c-1",
+ createdAt: "2026-01-01T00:00:00.000Z"
+ }
+ ]
+ });
+ await link([{ id: "te-1", quantity: 4 }]);
+
+ const byId = (id: string) =>
+ tables.nonConformanceItem.find((r) => r.id === id)!;
+ expect(byId("nci-1").quantity).toBe(4);
+ expect(byId("nci-split").quantity).toBe(0);
+ expect(tables.nonConformanceItemTrackedEntity[0].nonConformanceItemId).toBe(
+ "nci-1"
+ );
+ });
+
+ it("uses the fallback quantity for an empty row with no entities", async () => {
+ await link([], 12);
+
+ expect(itemRow().quantity).toBe(12);
+ });
+
+ it("ignores the fallback when every entity is already linked", async () => {
+ seed({
+ nonConformanceItemTrackedEntity: [
+ {
+ id: "l-1",
+ nonConformanceItemId: "nci-other",
+ nonConformanceId: "nc-1",
+ trackedEntityId: "te-1",
+ quantity: 2,
+ companyId: "c-1"
+ }
+ ]
+ });
+ await link([{ id: "te-1", quantity: 2 }], 12);
+
+ expect(itemRow().quantity).toBe(0);
+ });
+});
diff --git a/apps/erp/app/modules/quality/quality-disposition.server.ts b/apps/erp/app/modules/quality/quality-disposition.server.ts
index 22653254d1..c55aa183eb 100644
--- a/apps/erp/app/modules/quality/quality-disposition.server.ts
+++ b/apps/erp/app/modules/quality/quality-disposition.server.ts
@@ -1,6 +1,7 @@
import type { Database, Json } from "@carbon/database";
import type { KyselyTx } from "@carbon/database/client";
-import { EPSILON } from "@carbon/utils";
+import { lockIssueDispositions } from "@carbon/database/quality";
+import { datetime, EPSILON, round } from "@carbon/utils";
import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import { getDatabaseClient } from "~/services/database.server";
@@ -43,6 +44,25 @@ export async function assignEntitiesToIssueItem(args: {
try {
const result = await db.transaction().execute(async (trx) => {
+ // Lock the issue before reading any quantity, so a concurrent quantity
+ // edit or link writer on the same issue waits for this move.
+ const owner = await trx
+ .selectFrom("nonConformanceItem")
+ .select(["nonConformanceId"])
+ .where("id", "=", nonConformanceItemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!owner) throw new Error("Source item association not found");
+ // Re-check the closed lock inside the transaction: the route check is a
+ // separate read and could race with a concurrent close.
+ const { status } = await lockIssueDispositions(trx, {
+ nonConformanceId: owner.nonConformanceId,
+ companyId
+ });
+ if (isIssueLocked(status)) {
+ throw new Error("Cannot modify a closed issue. Reopen it first.");
+ }
+
const source = await trx
.selectFrom("nonConformanceItem")
.select(["id", "nonConformanceId", "quantity"])
@@ -63,18 +83,6 @@ export async function assignEntitiesToIssueItem(args: {
throw new Error("Cannot move entities between different NCRs");
}
- // Re-check the lock inside the transaction: the route check is a separate
- // read and could race with a concurrent close.
- const parent = await trx
- .selectFrom("nonConformance")
- .select(["status"])
- .where("id", "=", source.nonConformanceId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (isIssueLocked(parent?.status)) {
- throw new Error("Cannot modify a closed issue. Reopen it first.");
- }
-
const existingLinks = await trx
.selectFrom("nonConformanceItemTrackedEntity")
.select(["quantity"])
@@ -146,6 +154,210 @@ export async function assignEntitiesToIssueItem(args: {
}
}
+// -------------------------------------------------------------
+// updateIssueItemQuantity
+// -------------------------------------------------------------
+// Writes:
+// - nonConformanceItem.quantity (compare-and-set on expectedQuantity)
+//
+// Only link-less rows on issues without an inspection link are editable: a
+// tracked row's quantity is the sum of its links, and an inspection-originated
+// issue already wrote off the lot, which closeIssue restores as row.quantity
+// on Use As Is / Rework. The checks and the update run under the issue lock,
+// which every link and inspection writer also takes, so a link cannot land
+// between the check and the write.
+
+export async function updateIssueItemQuantity(args: {
+ id: string;
+ companyId: string;
+ userId: string;
+ quantity: number;
+ expectedQuantity: number;
+}): Promise<Result<{ id: string }>> {
+ const { id, companyId, userId, quantity, expectedQuantity } = args;
+ const db = getDatabaseClient();
+
+ try {
+ return await db.transaction().execute(async (trx) => {
+ const owner = await trx
+ .selectFrom("nonConformanceItem")
+ .select(["nonConformanceId"])
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!owner) return errResult("Issue item not found");
+
+ const { status } = await lockIssueDispositions(trx, {
+ nonConformanceId: owner.nonConformanceId,
+ companyId
+ });
+ if (isIssueLocked(status)) {
+ return errResult("Cannot modify a closed issue. Reopen it first.");
+ }
+
+ const link = await trx
+ .selectFrom("nonConformanceItemTrackedEntity")
+ .select(["id"])
+ .where("nonConformanceItemId", "=", id)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (link) {
+ return errResult(
+ "This row's quantity comes from its linked tracked entities. Split or move entities instead."
+ );
+ }
+
+ const inspection = await trx
+ .selectFrom("nonConformanceInspection")
+ .select(["id"])
+ .where("nonConformanceId", "=", owner.nonConformanceId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (inspection) {
+ return errResult(
+ "Quantity is set by the rejected inspection lot and cannot be edited."
+ );
+ }
+
+ // Compare-and-set: a stale save (an older request finishing after a
+ // newer one) matches no row instead of overwriting it.
+ const updated = await trx
+ .updateTable("nonConformanceItem")
+ .set({
+ quantity: round(quantity),
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .where("quantity", "=", expectedQuantity)
+ .returning(["id"])
+ .executeTakeFirst();
+ if (!updated) {
+ return errResult(
+ "This quantity changed since the page loaded. Refresh and try again."
+ );
+ }
+ return { data: { id: updated.id }, error: null };
+ });
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to update quantity"
+ );
+ }
+}
+
+// -------------------------------------------------------------
+// linkEntitiesToIssueItemRow
+// -------------------------------------------------------------
+// Writes:
+// - nonConformanceItem (find-or-create the item's row, grow its quantity)
+// - nonConformanceItemTrackedEntity (one link per entity not yet on a row)
+//
+// The caller must hold lockIssueDispositions for the issue. Entities already
+// linked to any row of the issue are skipped (an entity sits on at most one
+// disposition row per issue). The row quantity grows by the linked entities'
+// quantities, so it stays equal to the link sum. With no entities at all, a
+// row still at 0 takes `fallbackQuantity` (e.g. an untracked inspection lot
+// size); entities that are all already linked change nothing.
+
+export async function linkEntitiesToIssueItemRow(
+ trx: KyselyTx,
+ args: {
+ nonConformanceId: string;
+ companyId: string;
+ userId: string;
+ itemId: string;
+ entities: { id: string; quantity: number }[];
+ fallbackQuantity?: number;
+ }
+): Promise<void> {
+ const { nonConformanceId, companyId, userId, itemId, entities } = args;
+ const nowIso = datetime.timestamp();
+
+ // splitIssueItem drops the old (nonConformanceId, itemId) unique constraint's
+ // guarantee: a split item has several rows. Link onto the oldest — the row the
+ // split shrank, which still holds the un-dispositioned remainder — rather than
+ // whichever row Postgres happens to return first.
+ let row = await trx
+ .selectFrom("nonConformanceItem")
+ .select(["id", "quantity"])
+ .where("nonConformanceId", "=", nonConformanceId)
+ .where("itemId", "=", itemId)
+ .where("companyId", "=", companyId)
+ .orderBy("createdAt")
+ .orderBy("id")
+ .executeTakeFirst();
+ if (!row) {
+ row = await trx
+ .insertInto("nonConformanceItem")
+ .values({
+ nonConformanceId,
+ itemId,
+ quantity: 0,
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id", "quantity"])
+ .executeTakeFirstOrThrow();
+ }
+ const currentQty = Number(row.quantity ?? 0);
+
+ if (entities.length === 0) {
+ const fallback = args.fallbackQuantity ?? 0;
+ if (currentQty === 0 && fallback > 0) {
+ await trx
+ .updateTable("nonConformanceItem")
+ .set({ quantity: fallback, updatedBy: userId, updatedAt: nowIso })
+ .where("id", "=", row.id)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ return;
+ }
+
+ const alreadyLinked = await trx
+ .selectFrom("nonConformanceItemTrackedEntity")
+ .select(["trackedEntityId"])
+ .where("nonConformanceId", "=", nonConformanceId)
+ .where(
+ "trackedEntityId",
+ "in",
+ entities.map((e) => e.id)
+ )
+ .where("companyId", "=", companyId)
+ .execute();
+ const alreadyLinkedIds = new Set(alreadyLinked.map((l) => l.trackedEntityId));
+ const toLink = entities.filter((e) => !alreadyLinkedIds.has(e.id));
+ if (toLink.length === 0) return;
+
+ await trx
+ .insertInto("nonConformanceItemTrackedEntity")
+ .values(
+ toLink.map((e) => ({
+ nonConformanceItemId: row.id,
+ nonConformanceId,
+ trackedEntityId: e.id,
+ quantity: e.quantity,
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+
+ const addedQty = toLink.reduce((acc, e) => acc + e.quantity, 0);
+ await trx
+ .updateTable("nonConformanceItem")
+ .set({
+ quantity: currentQty + addedQty,
+ updatedBy: userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", row.id)
+ .where("companyId", "=", companyId)
+ .execute();
+}
+
// -------------------------------------------------------------
// splitIssueItem
// -------------------------------------------------------------
@@ -368,6 +580,25 @@ export async function splitIssueItem(args: {
try {
const result = await db.transaction().execute(async (trx) => {
+ // Lock the issue before reading the row quantity, so a concurrent
+ // quantity edit or link writer on the same issue waits for this split.
+ const owner = await trx
+ .selectFrom("nonConformanceItem")
+ .select(["nonConformanceId"])
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!owner) throw new Error("Item association not found");
+ // Re-check inside the transaction: the route lock check is a separate read
+ // and could race with a concurrent close.
+ const { status } = await lockIssueDispositions(trx, {
+ nonConformanceId: owner.nonConformanceId,
+ companyId
+ });
+ if (isIssueLocked(status)) {
+ throw new Error("Cannot modify a closed issue. Reopen it first.");
+ }
+
const item = await trx
.selectFrom("nonConformanceItem")
.select(["id", "nonConformanceId", "itemId", "quantity"])
@@ -378,15 +609,10 @@ export async function splitIssueItem(args: {
const issue = await trx
.selectFrom("nonConformance")
- .select(["nonConformanceId", "status", "locationId"])
+ .select(["nonConformanceId", "locationId"])
.where("id", "=", item.nonConformanceId)
.where("companyId", "=", companyId)
.executeTakeFirst();
- // Re-check inside the transaction: the route lock check is a separate read
- // and could race with a concurrent close.
- if (isIssueLocked(issue?.status)) {
- throw new Error("Cannot modify a closed issue. Reopen it first.");
- }
const readableNc = issue?.nonConformanceId ?? item.nonConformanceId;
const locationId = issue?.locationId ?? null;
diff --git a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
index d79e2a2cc3..1149c9ff2c 100644
--- a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
@@ -29,9 +29,11 @@ import {
ModalFooter,
ModalHeader,
ModalTitle,
+ NumberField,
+ NumberInput as NumberFieldInput,
toast
} from "@carbon/react";
-import { EPSILON } from "@carbon/utils";
+import { EPSILON, INPUT_FORMAT } from "@carbon/utils";
import { Trans, useLingui } from "@lingui/react/macro";
import { useCallback, useEffect, useMemo, useState } from "react";
import {
@@ -60,8 +62,68 @@ import { DispositionStatus } from "./DispositionStatus";
type AssociatedItemsListProps = {
associatedItems: IssueAssociationNode["children"];
isDisabled?: boolean;
+ // True for an inspection-originated NCR: the reject already wrote off the
+ // lot quantity, which closeIssue restores on Use As Is / Rework.
+ isQuantityReadOnly?: boolean;
};
+function DispositionQuantityInput({
+ nonConformanceItemId,
+ quantity
+}: {
+ nonConformanceItemId: string;
+ quantity: number;
+}) {
+ const { t } = useLingui();
+ const fetcher = useFetcher<typeof action>();
+
+ useEffect(() => {
+ if (fetcher.data?.error) {
+ toast.error(fetcher.data.error.message);
+ }
+ }, [fetcher.data]);
+
+ // Show the submitted value while the save is in flight; once the fetcher is
+ // idle this falls back to the loader's quantity, which also resets the field
+ // when the server rejects the change.
+ const pending = fetcher.formData?.get("value");
+ const value = typeof pending === "string" ? Number(pending) : quantity;
+ // One save at a time: the next edit waits for the previous save and its
+ // revalidation, so it carries the fresh quantity as expectedQuantity.
+ const isSaving = fetcher.state !== "idle";
+
+ return (
+ <NumberField
+ aria-label={t`Quantity`}
+ value={value}
+ minValue={0}
+ formatOptions={INPUT_FORMAT.quantity}
+ isReadOnly={isSaving}
+ onChange={(next) => {
+ if (
+ isSaving ||
+ !Number.isFinite(next) ||
+ next < 0 ||
+ Math.abs(next - quantity) <= EPSILON
+ ) {
+ return;
+ }
+ const formData = new FormData();
+ formData.append("id", nonConformanceItemId);
+ formData.append("field", "quantity");
+ formData.append("value", String(next));
+ formData.append("expectedQuantity", String(quantity));
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.updateIssueItem
+ });
+ }}
+ >
+ <NumberFieldInput size="sm" className="pr-2 tabular-nums" />
+ </NumberField>
+ );
+}
+
type EntityLink = {
id: string;
quantity: number;
@@ -105,7 +167,8 @@ type MoveTarget = {
export function AssociatedItemsList({
associatedItems,
- isDisabled = false
+ isDisabled = false,
+ isQuantityReadOnly = false
}: AssociatedItemsListProps) {
const [items] = useItems();
const { t } = useLingui();
@@ -227,6 +290,9 @@ export function AssociatedItemsList({
}
const canEdit = permissions.can("update", "quality") && !isDisabled;
+ // Tracked rows (with entity links) derive their quantity from the links, so
+ // only link-less rows get the input; the update route enforces the same.
+ const canEditQuantity = canEdit && !isQuantityReadOnly;
const blockingRows = dispositionableRows.filter(
(r) => r.pending || r.sumMismatch
);
@@ -345,9 +411,16 @@ export function AssociatedItemsList({
<span className="text-xs font-medium text-muted-foreground">
<Trans>Quantity</Trans>
</span>
- <span className="h-8 flex items-center text-sm tabular-nums">
- {r.quantity}
- </span>
+ {canEditQuantity && r.links.length === 0 ? (
+ <DispositionQuantityInput
+ nonConformanceItemId={r.child.id as string}
+ quantity={r.quantity}
+ />
+ ) : (
+ <span className="h-8 flex items-center text-sm tabular-nums">
+ {r.quantity}
+ </span>
+ )}
</div>
<ValidatedForm
defaultValues={{
diff --git a/apps/erp/app/routes/x+/inspection+/$id.reject.tsx b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
index 8c842b7a25..96eb395ad4 100644
--- a/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
+++ b/apps/erp/app/routes/x+/inspection+/$id.reject.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, ERP_URL, error, success } 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 { lockIssueDispositions } from "@carbon/database/quality";
import { notifyIssueCreated } from "@carbon/ee/notifications";
import { getLogger } from "@carbon/logger";
import { datetime } from "@carbon/utils";
@@ -21,6 +22,7 @@ import { dispositionInspection } from "~/modules/quality/quality.server";
import { getCompanyIntegrations } from "~/modules/settings/settings.server";
import { getLocationTimeZone } from "~/modules/shared/timezone.server";
import { getUserDefaults } from "~/modules/users/users.server";
+import { getDatabaseClient } from "~/services/database.server";
import { path } from "~/utils/path";
const logger = getLogger("erp", "inspections-id-reject");
@@ -239,41 +241,121 @@ export async function action({ request, params }: ActionFunctionArgs) {
const ncrId = createResult.data.id;
+ // Every tracked entity in the lot: the sampled ones plus the un-sampled
+ // ones, which the cascade also Rejected.
+ const trackedEntityIds = ((insp.inspectionSample as any[]) ?? [])
+ .map((s) => s.trackedEntityId as string)
+ .filter(Boolean);
+ // A failed read would link only part of the lot and still report success,
+ // so roll the NCR back and let the operator retry the reject instead.
+ const failLotRead = async (err: unknown): Promise<never> => {
+ await deleteIssue(serviceRole, ncrId);
+ throw redirect(
+ path.to.inspection(id),
+ await flash(
+ request,
+ error(err, "Lot rejected, but failed to read the lot for the NCR")
+ )
+ );
+ };
+ const receiptLineEntities = await serviceRole
+ .from("trackedEntity")
+ .select("id")
+ .eq("attributes ->> Receipt Line", insp.sourceDocumentLineId ?? "")
+ .eq("companyId", companyId);
+ if (receiptLineEntities.error) await failLotRead(receiptLineEntities.error);
+ const allLotEntityIds = Array.from(
+ new Set([
+ ...trackedEntityIds,
+ ...(receiptLineEntities.data ?? []).map((r: any) => r.id as string)
+ ])
+ );
+ const entityQuantities =
+ allLotEntityIds.length > 0
+ ? await serviceRole
+ .from("trackedEntity")
+ .select("id, quantity")
+ .in("id", allLotEntityIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null };
+ if (entityQuantities.error) await failLotRead(entityQuantities.error);
+
// insertIssue inserted nonConformanceItem rows with default qty 0 and
// disposition 'Pending'. Now that we know the lot context, overwrite with
// the actual lot quantity and default the MRB's starting disposition to
// 'Scrap' (the most conservative outcome — they can downgrade to Rework /
- // Use As Is / split later).
- let scrapRowId: string | null = null;
- if (insp.itemId) {
- await serviceRole
- .from("nonConformanceItem")
- .update({
- quantity: Number(insp.lotSize ?? 0),
- disposition: "Scrap",
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("nonConformanceId", ncrId)
- .eq("itemId", insp.itemId);
+ // Use As Is / split later), link the source inspection, and seed the
+ // per-row entity links so the MRB can split / reassign specific entities.
+ // All of it runs under the issue lock shared by every disposition writer,
+ // so a quantity edit cannot land between the lot quantity and the
+ // inspection link.
+ try {
+ await getDatabaseClient()
+ .transaction()
+ .execute(async (trx) => {
+ await lockIssueDispositions(trx, {
+ nonConformanceId: ncrId,
+ companyId
+ });
- const scrapRow = await serviceRole
- .from("nonConformanceItem")
- .select("id")
- .eq("nonConformanceId", ncrId)
- .eq("itemId", insp.itemId)
- .single();
- scrapRowId = scrapRow.data?.id ?? null;
- }
+ let scrapRowId: string | null = null;
+ if (insp.itemId) {
+ const scrapRow = await trx
+ .updateTable("nonConformanceItem")
+ .set({
+ quantity: Number(insp.lotSize ?? 0),
+ disposition: "Scrap",
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("nonConformanceId", "=", ncrId)
+ .where("itemId", "=", insp.itemId)
+ .where("companyId", "=", companyId)
+ .returning(["id"])
+ .executeTakeFirst();
+ scrapRowId = scrapRow?.id ?? null;
+ }
- // Link the source inspection to the NCR so the issue explorer can surface
- // the origin and deep-link back to the inspection lot.
- await serviceRole.from("nonConformanceInspection").insert({
- nonConformanceId: ncrId,
- inspectionId: insp.id,
- companyId,
- createdBy: userId
- });
+ await trx
+ .insertInto("nonConformanceInspection")
+ .values({
+ nonConformanceId: ncrId,
+ inspectionId: insp.id,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+
+ const entityRows = (entityQuantities.data ?? []) as {
+ id: string;
+ quantity: number | null;
+ }[];
+ if (scrapRowId && entityRows.length > 0) {
+ await trx
+ .insertInto("nonConformanceItemTrackedEntity")
+ .values(
+ entityRows.map((e) => ({
+ nonConformanceItemId: scrapRowId!,
+ nonConformanceId: ncrId,
+ trackedEntityId: e.id,
+ quantity: Number(e.quantity ?? 1),
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+ }
+ });
+ } catch (err) {
+ await deleteIssue(serviceRole, ncrId);
+ throw redirect(
+ path.to.inspection(id),
+ await flash(
+ request,
+ error(err, "Lot rejected, but failed to link the NCR to the lot")
+ )
+ );
+ }
// Also link the receipt line — gives the explorer the supplier / receipt
// context through the existing "Receipt Lines" association branch.
@@ -293,22 +375,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
// Link every tracked entity in the lot to the NCR.
- const trackedEntityIds = ((insp.inspectionSample as any[]) ?? [])
- .map((s) => s.trackedEntityId as string)
- .filter(Boolean);
- // Include un-sampled entities too (they were also Rejected by the cascade).
- const receiptLineEntities = await client
- .from("trackedEntity")
- .select("id")
- .eq("attributes ->> Receipt Line", insp.sourceDocumentLineId ?? "")
- .eq("companyId", companyId);
- const allLotEntityIds = Array.from(
- new Set([
- ...trackedEntityIds,
- ...(receiptLineEntities.data ?? []).map((r: any) => r.id as string)
- ])
- );
-
if (allLotEntityIds.length > 0) {
await serviceRole.from("nonConformanceTrackedEntity").insert(
allLotEntityIds.map((trackedEntityId) => ({
@@ -318,29 +384,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
createdBy: userId
}))
);
-
- // Seed the per-row entity links on the default Scrap row so the MRB can
- // split / reassign specific entities to other dispositions. Each entity
- // contributes its own quantity to the row.
- if (scrapRowId) {
- const entityQuantities = await serviceRole
- .from("trackedEntity")
- .select("id, quantity")
- .in("id", allLotEntityIds)
- .eq("companyId", companyId);
- const rows = (entityQuantities.data ?? []).map((e: any) => ({
- nonConformanceItemId: scrapRowId!,
- trackedEntityId: e.id as string,
- quantity: Number(e.quantity ?? 1),
- companyId,
- createdBy: userId
- }));
- if (rows.length > 0) {
- await (serviceRole as any)
- .from("nonConformanceItemTrackedEntity")
- .insert(rows);
- }
- }
}
const tasks = await serviceRole.functions.invoke("create", {
diff --git a/apps/erp/app/routes/x+/issue+/$id.association.new.tsx b/apps/erp/app/routes/x+/issue+/$id.association.new.tsx
index 728b2e2ec8..0b16a84cd9 100644
--- a/apps/erp/app/routes/x+/issue+/$id.association.new.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.association.new.tsx
@@ -1,10 +1,13 @@
import { assertIsPost } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
+import { lockIssueDispositions } from "@carbon/database/quality";
import { validator } from "@carbon/form";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { getIssue, isIssueLocked } from "~/modules/quality";
import { issueAssociationValidator } from "~/modules/quality/quality.models";
+import { linkEntitiesToIssueItemRow } from "~/modules/quality/quality-disposition.server";
+import { getDatabaseClient } from "~/services/database.server";
import { requireUnlocked } from "~/utils/lockedGuard.server";
import { path } from "~/utils/path";
@@ -387,9 +390,11 @@ export async function action({ request, params }: ActionFunctionArgs) {
const inspection = await (client as any)
.from("inspection")
.select(
- "id, itemId, lotSize, receiptLineId, inspectionSample(trackedEntityId)"
+ "id, itemId, lotSize, sourceDocument, sourceDocumentLineId, inspectionSample(trackedEntityId)"
)
.eq("id", id)
+ // The link below is written through Kysely (no RLS), so scope here.
+ .eq("companyId", companyId)
.single();
if (inspection.error) {
logger.error("Failed to create association", {
@@ -401,24 +406,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
};
}
- const linkResult = await (client as any)
- .from("nonConformanceInspection")
- .insert({
- nonConformanceId,
- inspectionId: inspection.data.id,
- createdBy: userId,
- companyId: companyId
- });
- if (linkResult.error) {
- logger.error("Failed to create association", {
- error: linkResult.error
- });
- return {
- success: false,
- message: "Failed to create issue inbound inspection"
- };
- }
-
const sampledIds = (
(inspection.data.inspectionSample ?? []) as {
trackedEntityId: string;
@@ -429,12 +416,28 @@ export async function action({ request, params }: ActionFunctionArgs) {
// Pull the rest of the lot too — un-sampled entities are still part of
// the lot the MRB needs to disposition.
let lotEntityIds: string[] = sampledIds;
- if (inspection.data.receiptLineId) {
+ if (
+ inspection.data.sourceDocument === "Receipt" &&
+ inspection.data.sourceDocumentLineId
+ ) {
const receiptLineEntities = await client
.from("trackedEntity")
.select("id")
- .eq("attributes ->> Receipt Line", inspection.data.receiptLineId)
+ .eq(
+ "attributes ->> Receipt Line",
+ inspection.data.sourceDocumentLineId
+ )
.eq("companyId", companyId);
+ // A failed read would link only the sampled part of the lot.
+ if (receiptLineEntities.error) {
+ logger.error("Failed to create association", {
+ error: receiptLineEntities.error
+ });
+ return {
+ success: false,
+ message: "Failed to create issue inbound inspection"
+ };
+ }
lotEntityIds = Array.from(
new Set([
...sampledIds,
@@ -445,14 +448,21 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- await autoLinkInspectionContext(client, {
+ const linked = await linkInspection(client, {
nonConformanceId,
companyId,
userId,
+ inspectionId: inspection.data.id,
itemId: inspection.data.itemId ?? null,
lotSize: Number(inspection.data.lotSize ?? 0),
trackedEntityIds: lotEntityIds
});
+ if (!linked) {
+ return {
+ success: false,
+ message: "Failed to create issue inbound inspection"
+ };
+ }
break;
}
}
@@ -514,26 +524,49 @@ async function autoLinkJobOperationContext(
});
}
-async function autoLinkInspectionContext(
+// Links an inspection to the issue and seeds the item's disposition row with
+// the lot. The inspection link and the row writes share one transaction under
+// the issue lock, so a concurrent quantity edit either lands before (and the
+// row write overwrites it) or sees the inspection link and is refused.
+async function linkInspection(
client: Awaited<ReturnType<typeof requirePermissions>>["client"],
args: {
nonConformanceId: string;
companyId: string;
userId: string;
+ inspectionId: string;
itemId: string | null;
lotSize: number;
trackedEntityIds: string[];
}
-) {
+): Promise<boolean> {
const {
nonConformanceId,
companyId,
userId,
+ inspectionId,
itemId,
lotSize,
trackedEntityIds
} = args;
+ // Read before writing anything: a failed read would seed the row with
+ // wrong quantities and still report success.
+ const entityQuantities =
+ trackedEntityIds.length > 0
+ ? await client
+ .from("trackedEntity")
+ .select("id, quantity")
+ .in("id", trackedEntityIds)
+ .eq("companyId", companyId)
+ : { data: [], error: null };
+ if (entityQuantities.error) {
+ logger.error("Failed to create association", {
+ error: entityQuantities.error
+ });
+ return false;
+ }
+
await insertMissingTrackedEntities(client, {
nonConformanceId,
companyId,
@@ -541,113 +574,54 @@ async function autoLinkInspectionContext(
trackedEntityIds
});
- if (!itemId) return;
-
- // Find or create the disposition row for this item. New rows start at qty 0;
- // we'll bump the qty below by the sum of newly-attached entity quantities
- // so nonConformanceItem.quantity stays in sync with sum(links.quantity) and
- // the closure validator's link-sum check is satisfied.
- const existing = await client
- .from("nonConformanceItem")
- .select("id, quantity")
- .eq("nonConformanceId", nonConformanceId)
- .eq("itemId", itemId)
- .maybeSingle();
-
- let itemRowId: string;
- let currentQty: number;
- if (existing.data) {
- itemRowId = existing.data.id as string;
- currentQty = Number(existing.data.quantity ?? 0);
- } else {
- const insert = await (client as any)
- .from("nonConformanceItem")
- .insert({
- itemId,
- nonConformanceId,
- createdBy: userId,
- companyId,
- quantity: 0
- })
- .select("id, quantity")
- .single();
- if (insert.error || !insert.data) {
- logger.error("Failed to create association", { error: insert.error });
- return;
- }
- itemRowId = insert.data.id as string;
- currentQty = Number(insert.data.quantity ?? 0);
- }
-
- if (trackedEntityIds.length === 0) {
- // No entities to link — leave the row at its current qty (or fall back to
- // the lot size for a freshly-created empty row, so the user sees something
- // meaningful in the disposition list).
- if (currentQty === 0 && lotSize > 0) {
- await client
- .from("nonConformanceItem")
- .update({
- quantity: lotSize,
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("id", itemRowId)
- .eq("companyId", companyId);
- }
- return;
- }
-
- // An entity may only appear on one disposition row per NCR (DB ncUnique
- // constraint) — skip anything that's already linked anywhere on this NCR.
- const alreadyLinked = await (client as any)
- .from("nonConformanceItemTrackedEntity")
- .select("trackedEntityId")
- .eq("nonConformanceId", nonConformanceId)
- .in("trackedEntityId", trackedEntityIds);
- const alreadyLinkedSet = new Set(
- ((alreadyLinked.data ?? []) as { trackedEntityId: string }[]).map(
- (r) => r.trackedEntityId
- )
- );
- const toLink = trackedEntityIds.filter((id) => !alreadyLinkedSet.has(id));
- if (toLink.length === 0) return;
-
- const entityQuantities = await client
- .from("trackedEntity")
- .select("id, quantity")
- .in("id", toLink)
- .eq("companyId", companyId);
- const entityQtyById = new Map(
+ const quantityById = new Map(
(
(entityQuantities.data ?? []) as { id: string; quantity: number | null }[]
).map((e) => [e.id, Number(e.quantity ?? 1)])
);
-
- const linkRows = toLink.map((trackedEntityId) => ({
- nonConformanceItemId: itemRowId,
- trackedEntityId,
- quantity: entityQtyById.get(trackedEntityId) ?? 1,
- companyId,
- createdBy: userId
+ const entities = trackedEntityIds.map((id) => ({
+ id,
+ quantity: quantityById.get(id) ?? 1
}));
- const linkInsert = await (client as any)
- .from("nonConformanceItemTrackedEntity")
- .insert(linkRows);
- if (linkInsert.error) {
- logger.error("Failed to create association", { error: linkInsert.error });
- return;
- }
- const addedQty = linkRows.reduce((acc, r) => acc + r.quantity, 0);
- await client
- .from("nonConformanceItem")
- .update({
- quantity: currentQty + addedQty,
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("id", itemRowId)
- .eq("companyId", companyId);
+ try {
+ await getDatabaseClient()
+ .transaction()
+ .execute(async (trx) => {
+ const { status } = await lockIssueDispositions(trx, {
+ nonConformanceId,
+ companyId
+ });
+ if (isIssueLocked(status)) {
+ throw new Error("Cannot modify a closed issue. Reopen it first.");
+ }
+
+ await trx
+ .insertInto("nonConformanceInspection")
+ .values({
+ nonConformanceId,
+ inspectionId,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+
+ if (itemId) {
+ await linkEntitiesToIssueItemRow(trx, {
+ nonConformanceId,
+ companyId,
+ userId,
+ itemId,
+ entities,
+ fallbackQuantity: lotSize
+ });
+ }
+ });
+ return true;
+ } catch (err) {
+ logger.error("Failed to create association", { error: err });
+ return false;
+ }
}
async function insertMissingItem(
diff --git a/apps/erp/app/routes/x+/issue+/$id.details.tsx b/apps/erp/app/routes/x+/issue+/$id.details.tsx
index f4bdd16970..5dfea69181 100644
--- a/apps/erp/app/routes/x+/issue+/$id.details.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.details.tsx
@@ -136,7 +136,10 @@ export default function IssueDetailsRoute() {
const routeData = useRouteData<{
files: Promise<StorageItem[]>;
suppliers: { supplierId: string; externalLinkId: string | null }[];
- associations: Promise<{ items: IssueAssociationNode["children"] }>;
+ associations: Promise<{
+ items: IssueAssociationNode["children"];
+ inspections: IssueAssociationNode["children"];
+ }>;
}>(path.to.issue(id));
if (!routeData) throw new Error("Could not find issue data");
@@ -165,6 +168,9 @@ export default function IssueDetailsRoute() {
<AssociatedItemsList
associatedItems={resolvedAssociations?.items ?? []}
isDisabled={isIssueLocked(nonConformance?.status)}
+ isQuantityReadOnly={
+ (resolvedAssociations?.inspections ?? []).length > 0
+ }
/>
<CreateSupplierReturn
issueId={id}
diff --git a/apps/erp/app/routes/x+/issue+/item+/update.test.ts b/apps/erp/app/routes/x+/issue+/item+/update.test.ts
new file mode 100644
index 0000000000..5c2bfc3636
--- /dev/null
+++ b/apps/erp/app/routes/x+/issue+/item+/update.test.ts
@@ -0,0 +1,135 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// @carbon/glossary's terms.ts evaluates Lingui `msg` macros at module load,
+// which vitest doesn't transform; the route graph pulls it in transitively.
+vi.mock("@carbon/glossary", () => ({
+ terms: {},
+ getEntry: vi.fn(),
+ lookupEntry: vi.fn(),
+ hasEntry: vi.fn(),
+ termSlug: vi.fn(),
+ glossaryEntries: () => []
+}));
+vi.mock("@carbon/auth/auth.server", () => ({
+ requirePermissions: vi.fn()
+}));
+vi.mock("@carbon/auth/session.server", () => ({
+ flash: vi.fn(async () => ({}))
+}));
+vi.mock("~/modules/quality", () => ({
+ isIssueLocked: (status: string | null) => status === "Closed"
+}));
+vi.mock("~/modules/quality/quality.models", () => ({
+ disposition: ["Pending", "Scrap", "Use As Is"]
+}));
+// The locked compare-and-set lives in updateIssueItemQuantity and is covered
+// by quality-disposition.server.test.ts; this file covers the route's parsing.
+vi.mock("~/modules/quality/quality-disposition.server", () => ({
+ updateIssueItemQuantity: vi.fn(async () => ({
+ data: { id: "nci-1" },
+ error: null
+ }))
+}));
+
+import { updateIssueItemQuantity } from "~/modules/quality/quality-disposition.server";
+import { action } from "./update";
+
+// The item lookup the route runs before its field switch; `parentRow` null
+// simulates a missing (or other-company) item.
+let parentRow: { nonConformance: { status: string } } | null;
+const update = vi.fn();
+const client = {
+ from: () => {
+ const chain: any = {
+ select: () => chain,
+ eq: () => chain,
+ update: (value: unknown) => {
+ update(value);
+ return chain;
+ },
+ single: async () =>
+ parentRow
+ ? { data: parentRow, error: null }
+ : { data: null, error: { message: "No rows found" } },
+ then: (onFulfilled: (value: unknown) => unknown) =>
+ Promise.resolve({ data: null, error: null }).then(onFulfilled)
+ };
+ return chain;
+ }
+};
+
+function quantityRequest(fields: Record<string, string>) {
+ const body = new FormData();
+ body.set("id", "nci-1");
+ body.set("field", "quantity");
+ for (const [key, value] of Object.entries(fields)) body.set(key, value);
+ return new Request("http://localhost/x/issue/item/update", {
+ method: "POST",
+ body
+ });
+}
+
+async function run(request: Request) {
+ return (await action({ request, params: {}, context: {} } as any)) as {
+ error: { message: string } | null;
+ };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ parentRow = { nonConformance: { status: "In Progress" } };
+ vi.mocked(requirePermissions).mockResolvedValue({
+ client,
+ companyId: "company-1",
+ userId: "user-1"
+ } as any);
+});
+
+describe("issue item update — quantity", () => {
+ it("passes the parsed quantity and expected quantity to the locked update", async () => {
+ const result = await run(
+ quantityRequest({ value: "2.5", expectedQuantity: "0" })
+ );
+
+ expect(result.error).toBeNull();
+ expect(updateIssueItemQuantity).toHaveBeenCalledWith({
+ id: "nci-1",
+ companyId: "company-1",
+ userId: "user-1",
+ quantity: 2.5,
+ expectedQuantity: 0
+ });
+ });
+
+ it.each(["-3", "", "abc"])("refuses the quantity %j", async (value) => {
+ const result = await run(quantityRequest({ value, expectedQuantity: "0" }));
+
+ expect(result.error?.message).toBe("Quantity must be zero or more");
+ expect(updateIssueItemQuantity).not.toHaveBeenCalled();
+ });
+
+ it("refuses a missing expected quantity", async () => {
+ const result = await run(quantityRequest({ value: "5" }));
+
+ expect(result.error?.message).toBe("Invalid expected quantity");
+ expect(updateIssueItemQuantity).not.toHaveBeenCalled();
+ });
+
+ it("refuses a missing item before the field switch", async () => {
+ parentRow = null;
+ const body = new FormData();
+ body.set("id", "nci-missing");
+ body.set("field", "disposition");
+ body.set("value", "Scrap");
+ const result = await run(
+ new Request("http://localhost/x/issue/item/update", {
+ method: "POST",
+ body
+ })
+ );
+
+ expect(result.error?.message).toBe("Issue item not found");
+ expect(update).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/erp/app/routes/x+/issue+/item+/update.tsx b/apps/erp/app/routes/x+/issue+/item+/update.tsx
index 08cfe8f149..2cfb824c83 100644
--- a/apps/erp/app/routes/x+/issue+/item+/update.tsx
+++ b/apps/erp/app/routes/x+/issue+/item+/update.tsx
@@ -1,7 +1,9 @@
import { requirePermissions } from "@carbon/auth/auth.server";
+import { datetime } from "@carbon/utils";
import type { ActionFunctionArgs } from "react-router";
import { isIssueLocked } from "~/modules/quality";
import { disposition } from "~/modules/quality/quality.models";
+import { updateIssueItemQuantity } from "~/modules/quality/quality-disposition.server";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
@@ -34,6 +36,11 @@ export async function action({ request }: ActionFunctionArgs) {
.eq("id", id)
.eq("companyId", companyId)
.single();
+ // Without this, an update against a missing row matches nothing and still
+ // reports success.
+ if (parent.error || !parent.data) {
+ return { error: { message: "Issue item not found" }, data: null };
+ }
const lockedError = requireUnlockedBulk({
statuses: [(parent.data as any)?.nonConformance?.status ?? null],
checkFn: isIssueLocked,
@@ -57,9 +64,42 @@ export async function action({ request }: ActionFunctionArgs) {
.update({
[field]: value ? (value as (typeof disposition)[number]) : null,
updatedBy: userId,
- updatedAt: new Date().toISOString()
+ updatedAt: datetime.timestamp()
})
.eq("id", id);
+ case "quantity": {
+ const quantity = Number(value);
+ if (
+ value === null ||
+ value.trim() === "" ||
+ !Number.isFinite(quantity) ||
+ quantity < 0
+ ) {
+ return {
+ error: { message: "Quantity must be zero or more" },
+ data: null
+ };
+ }
+ const expected = formData.get("expectedQuantity");
+ const expectedQuantity = Number(expected);
+ if (
+ typeof expected !== "string" ||
+ expected.trim() === "" ||
+ !Number.isFinite(expectedQuantity)
+ ) {
+ return {
+ error: { message: "Invalid expected quantity" },
+ data: null
+ };
+ }
+ return await updateIssueItemQuantity({
+ id,
+ companyId,
+ userId,
+ quantity,
+ expectedQuantity
+ });
+ }
default:
return {
error: { message: `Invalid field: ${field}` },
diff --git a/apps/erp/app/routes/x+/issue+/new.tsx b/apps/erp/app/routes/x+/issue+/new.tsx
index 01935427df..758c31d745 100644
--- a/apps/erp/app/routes/x+/issue+/new.tsx
+++ b/apps/erp/app/routes/x+/issue+/new.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, ERP_URL, 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 { lockIssueDispositions } from "@carbon/database/quality";
import { notifyIssueCreated } from "@carbon/ee/notifications";
import { validationError, validator } from "@carbon/form";
import { getLogger } from "@carbon/logger";
@@ -19,8 +20,10 @@ import {
insertIssue,
issueValidator
} from "~/modules/quality";
+import { linkEntitiesToIssueItemRow } from "~/modules/quality/quality-disposition.server";
import IssueForm from "~/modules/quality/ui/Issue/IssueForm";
import { getCompanyIntegrations } from "~/modules/settings/settings.server";
+import { getDatabaseClient } from "~/services/database.server";
import { setCustomFields } from "~/utils/form";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -323,79 +326,26 @@ async function autoLinkJobOperationDisposition(
}
}
- // Disposition row: find or create. insertIssue may have already inserted
- // one for this item via the form's `items` array.
- const existingItem = await client
- .from("nonConformanceItem")
- .select("id, quantity")
- .eq("nonConformanceId", nonConformanceId)
- .eq("itemId", itemId)
- .maybeSingle();
-
- let itemRowId: string;
- let currentQty: number;
- if (existingItem.data) {
- itemRowId = existingItem.data.id as string;
- currentQty = Number(existingItem.data.quantity ?? 0);
- } else {
- const insert = await (client as any)
- .from("nonConformanceItem")
- .insert({
- itemId,
- nonConformanceId,
- createdBy: userId,
- companyId,
- quantity: 0
- })
- .select("id, quantity")
- .single();
- if (insert.error || !insert.data) {
- logger.error("Issue creation step failed", { error: insert.error });
- return;
- }
- itemRowId = insert.data.id as string;
- currentQty = Number(insert.data.quantity ?? 0);
- }
-
- // ncUnique: an entity may sit on at most one disposition row per NCR.
- const alreadyLinked = await (client as any)
- .from("nonConformanceItemTrackedEntity")
- .select("trackedEntityId")
- .eq("nonConformanceId", nonConformanceId)
- .in("trackedEntityId", entityIds);
- const alreadyLinkedSet = new Set(
- ((alreadyLinked.data ?? []) as { trackedEntityId: string }[]).map(
- (r) => r.trackedEntityId
- )
- );
-
- const linkRows = lotEntities
- .filter((e) => !alreadyLinkedSet.has(e.id))
- .map((e) => ({
- nonConformanceItemId: itemRowId,
- trackedEntityId: e.id,
- quantity: Number(e.quantity ?? 1),
- companyId,
- createdBy: userId
- }));
- if (linkRows.length === 0) return;
-
- const linkInsert = await (client as any)
- .from("nonConformanceItemTrackedEntity")
- .insert(linkRows);
- if (linkInsert.error) {
- logger.error("Issue creation step failed", { error: linkInsert.error });
- return;
+ // Disposition row: find or create (insertIssue may have already inserted
+ // one for this item via the form's `items` array), link the lot, and grow
+ // the row quantity — under the issue lock shared by every link writer.
+ try {
+ await getDatabaseClient()
+ .transaction()
+ .execute(async (trx) => {
+ await lockIssueDispositions(trx, { nonConformanceId, companyId });
+ await linkEntitiesToIssueItemRow(trx, {
+ nonConformanceId,
+ companyId,
+ userId,
+ itemId,
+ entities: lotEntities.map((e) => ({
+ id: e.id,
+ quantity: Number(e.quantity ?? 1)
+ }))
+ });
+ });
+ } catch (err) {
+ logger.error("Issue creation step failed", { error: err });
}
-
- const addedQty = linkRows.reduce((acc, r) => acc + r.quantity, 0);
- await client
- .from("nonConformanceItem")
- .update({
- quantity: currentQty + addedQty,
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("id", itemRowId)
- .eq("companyId", companyId);
}
diff --git a/apps/erp/app/routes/x+/sales-return-order+/$id.$lineId.issue.tsx b/apps/erp/app/routes/x+/sales-return-order+/$id.$lineId.issue.tsx
index 73659f87ef..70c6989df9 100644
--- a/apps/erp/app/routes/x+/sales-return-order+/$id.$lineId.issue.tsx
+++ b/apps/erp/app/routes/x+/sales-return-order+/$id.$lineId.issue.tsx
@@ -2,6 +2,7 @@ import { assertIsPost, error, notFound, success } 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 { lockIssueDispositions } from "@carbon/database/quality";
import { datetime } from "@carbon/utils";
import { FunctionRegion } from "@supabase/supabase-js";
import type { ActionFunctionArgs } from "react-router";
@@ -236,34 +237,6 @@ export async function action({ request, params }: ActionFunctionArgs) {
return failWith(err, message);
};
- // insertIssue seeded a nonConformanceItem row with default qty and Pending
- // disposition. Overwrite with the line's received quantity and the requested
- // disposition so MRB starts from the escalation's context.
- const itemUpdate = await serviceRole
- .from("nonConformanceItem")
- .update({
- quantity: quantityReceived,
- disposition,
- updatedBy: userId,
- updatedAt: datetime.timestamp()
- })
- .eq("nonConformanceId", ncrId)
- .eq("itemId", line.data.itemId);
- if (itemUpdate.error) {
- throw await failWithRollback(
- itemUpdate.error,
- "Failed to set the Issue's item"
- );
- }
-
- const itemRow = await serviceRole
- .from("nonConformanceItem")
- .select("id")
- .eq("nonConformanceId", ncrId)
- .eq("itemId", line.data.itemId)
- .single();
- const nonConformanceItemId = itemRow.data?.id ?? null;
-
// Link the RMA line so the issue explorer can surface the origin and
// deep-link back to the return order.
const lineLink = await serviceRole
@@ -283,8 +256,8 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- // Link the line's returned entities to the NCR, and seed the per-row entity
- // links on the item row so MRB can split / reassign specific entities.
+ // Link the line's returned entities to the NCR.
+ let entityRows: { id: string; quantity: number }[] = [];
if (entityIds.length > 0) {
const entityLinks = await serviceRole
.from("nonConformanceTrackedEntity")
@@ -303,32 +276,70 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- if (nonConformanceItemId) {
- const entityQuantities = await serviceRole
- .from("trackedEntity")
- .select("id, quantity")
- .in("id", entityIds)
- .eq("companyId", companyId);
- const rows = (entityQuantities.data ?? []).map((entity) => ({
- nonConformanceItemId,
- nonConformanceId: ncrId,
- trackedEntityId: entity.id,
- quantity: Number(entity.quantity ?? 1),
- companyId,
- createdBy: userId
- }));
- if (rows.length > 0) {
- const itemEntityLinks = await serviceRole
- .from("nonConformanceItemTrackedEntity")
- .insert(rows);
- if (itemEntityLinks.error) {
- throw await failWithRollback(
- itemEntityLinks.error,
- "Failed to link the returned entities to the Issue's item"
- );
- }
- }
+ const entityQuantities = await serviceRole
+ .from("trackedEntity")
+ .select("id, quantity")
+ .in("id", entityIds)
+ .eq("companyId", companyId);
+ if (entityQuantities.error) {
+ throw await failWithRollback(
+ entityQuantities.error,
+ "Failed to read the returned entities for the Issue"
+ );
}
+ entityRows = (entityQuantities.data ?? []).map((entity) => ({
+ id: entity.id,
+ quantity: Number(entity.quantity ?? 1)
+ }));
+ }
+
+ // insertIssue seeded a nonConformanceItem row with default qty and Pending
+ // disposition. Overwrite with the line's received quantity and the requested
+ // disposition so MRB starts from the escalation's context, and seed the
+ // per-row entity links so MRB can split / reassign specific entities. Both
+ // run under the issue lock shared by every disposition writer, so a quantity
+ // edit cannot land between the quantity and the links.
+ try {
+ await getDatabaseClient()
+ .transaction()
+ .execute(async (trx) => {
+ await lockIssueDispositions(trx, {
+ nonConformanceId: ncrId,
+ companyId
+ });
+
+ const itemRow = await trx
+ .updateTable("nonConformanceItem")
+ .set({
+ quantity: quantityReceived,
+ disposition,
+ updatedBy: userId,
+ updatedAt: datetime.timestamp()
+ })
+ .where("nonConformanceId", "=", ncrId)
+ .where("itemId", "=", line.data.itemId)
+ .where("companyId", "=", companyId)
+ .returning(["id"])
+ .executeTakeFirst();
+
+ if (itemRow && entityRows.length > 0) {
+ await trx
+ .insertInto("nonConformanceItemTrackedEntity")
+ .values(
+ entityRows.map((entity) => ({
+ nonConformanceItemId: itemRow.id,
+ nonConformanceId: ncrId,
+ trackedEntityId: entity.id,
+ quantity: entity.quantity,
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+ }
+ });
+ } catch (err) {
+ throw await failWithRollback(err, "Failed to set the Issue's item");
}
const tasks = await serviceRole.functions.invoke("create", {
diff --git a/apps/mes/app/services/quality.server.ts b/apps/mes/app/services/quality.server.ts
index 38652476de..e7c38f4fce 100644
--- a/apps/mes/app/services/quality.server.ts
+++ b/apps/mes/app/services/quality.server.ts
@@ -1,8 +1,10 @@
import type { getCarbonServiceRole } from "@carbon/auth/client.server";
import type { Database } from "@carbon/database";
import { getLocationTimeZone } from "@carbon/database";
+import { lockIssueDispositions } from "@carbon/database/quality";
import { datetime } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
+import { getDatabaseClient } from "~/services/database.server";
import {
getJobMakeMethod,
getTrackedEntitiesByMakeMethodId,
@@ -54,6 +56,9 @@ export type CreateQualityIssueArgs = {
nonConformanceTypeId?: string;
priority?: "Low" | "Medium" | "High" | "Critical";
quantity?: number;
+ // Links the source inspection in the same locked transaction as the
+ // disposition row, so the row is never visible without its inspection link.
+ inspectionId?: string;
};
// MES-owned NCR creation for a job operation: sequence, nonConformance insert,
@@ -153,7 +158,8 @@ export async function createQualityIssue(
itemId: context.itemId,
jobMakeMethodId: context.jobMakeMethodId,
trackedEntityId: args.trackedEntityId,
- quantity
+ quantity,
+ inspectionId: args.inspectionId
})
]);
const associationError =
@@ -563,6 +569,14 @@ export async function createInspectionRejectionIssue(
};
}
const insp = inspection.data as any;
+ // getInspection reads with the service role by id alone, and the issue this
+ // creates links the inspection — so the lot must belong to this company.
+ if (insp.companyId !== companyId) {
+ return {
+ error: new Error("Inspection is not in this company"),
+ message: "Failed to load the lot for the quality issue"
+ };
+ }
const jobOperationId = insp.sourceDocumentLineId as string | null;
if (!jobOperationId) {
return { error: null, message: "Lot has no job operation to link" };
@@ -630,7 +644,10 @@ export async function createInspectionRejectionIssue(
name: issueTitle,
description: `Auto-created from inspection ${inspectionReadableId}. Lot size ${insp.lotSize}, sample ${insp.sampleSize}, Ac ${insp.acceptanceNumber} / Re ${insp.rejectionNumber}.${failedFeaturesBlock}`,
priority: "Medium",
- quantity: Number(insp.lotSize ?? 1)
+ quantity: Number(insp.lotSize ?? 1),
+ // Link the source inspection to the issue so the ERP issue explorer can
+ // surface the origin and deep-link back to the inspection lot.
+ inspectionId
});
if (issue.error || !issue.data) {
@@ -640,21 +657,6 @@ export async function createInspectionRejectionIssue(
};
}
- // Link the source inspection to the issue so the ERP issue explorer can
- // surface the origin and deep-link back to the inspection lot.
- const link = await serviceRole.from("nonConformanceInspection").insert({
- nonConformanceId: issue.data.id,
- inspectionId,
- companyId,
- createdBy: userId
- });
- if (link.error) {
- return {
- error: link.error,
- message: "Quality issue created, but failed to link the inspection"
- };
- }
-
return { error: null, message: null };
}
@@ -759,6 +761,10 @@ async function getIssueContext(
};
}
+// Writes the issue's disposition row, its entity links and (optionally) the
+// source inspection link in one transaction under the issue lock shared by
+// every disposition writer, so a concurrent quantity edit in the ERP can never
+// see the row without its links or inspection.
async function linkIssueDispositionContext(
client: ServiceRole,
args: {
@@ -769,6 +775,7 @@ async function linkIssueDispositionContext(
jobMakeMethodId: string | null;
trackedEntityId?: string;
quantity: number;
+ inspectionId?: string;
}
): Promise<{ error: unknown | null }> {
const {
@@ -778,16 +785,19 @@ async function linkIssueDispositionContext(
itemId,
jobMakeMethodId,
trackedEntityId,
- quantity
+ quantity,
+ inspectionId
} = args;
- if (!itemId) return { error: null };
+ if (!itemId && !inspectionId) return { error: null };
- const trackedEntities = await getTrackedEntitiesForIssue(client, {
- companyId,
- jobMakeMethodId,
- trackedEntityId
- });
+ const trackedEntities = itemId
+ ? await getTrackedEntitiesForIssue(client, {
+ companyId,
+ jobMakeMethodId,
+ trackedEntityId
+ })
+ : { data: [], error: null };
if (trackedEntities.error) {
return { error: trackedEntities.error };
@@ -801,56 +811,72 @@ async function linkIssueDispositionContext(
)
: quantity;
- const item = await client
- .from("nonConformanceItem")
- .insert({
- nonConformanceId,
- itemId,
- quantity: itemQuantity,
- disposition: "Pending",
- companyId,
- createdBy: userId
- })
- .select("id")
- .single();
-
- if (item.error || !item.data?.id) {
- return { error: item.error ?? new Error("Failed to create issue item") };
- }
-
- if (trackedEntities.data.length === 0) {
- return { error: null };
- }
-
- const trackedEntityLinks = await client
- .from("nonConformanceTrackedEntity")
- .insert(
- trackedEntities.data.map((entity) => ({
- nonConformanceId,
- trackedEntityId: entity.id,
- companyId,
- createdBy: userId
- }))
- );
-
- if (trackedEntityLinks.error) {
- return { error: trackedEntityLinks.error };
- }
-
- const dispositionLinks = await client
- .from("nonConformanceItemTrackedEntity")
- .insert(
- trackedEntities.data.map((entity) => ({
- nonConformanceItemId: item.data.id,
- nonConformanceId,
- trackedEntityId: entity.id,
- quantity: Number(entity.quantity ?? quantity),
- companyId,
- createdBy: userId
- }))
- );
-
- return { error: dispositionLinks.error };
+ try {
+ await getDatabaseClient()
+ .transaction()
+ .execute(async (trx) => {
+ await lockIssueDispositions(trx, { nonConformanceId, companyId });
+
+ if (inspectionId) {
+ await trx
+ .insertInto("nonConformanceInspection")
+ .values({
+ nonConformanceId,
+ inspectionId,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+ }
+
+ if (!itemId) return;
+
+ const item = await trx
+ .insertInto("nonConformanceItem")
+ .values({
+ nonConformanceId,
+ itemId,
+ quantity: itemQuantity,
+ disposition: "Pending",
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ if (trackedEntities.data.length === 0) return;
+
+ await trx
+ .insertInto("nonConformanceTrackedEntity")
+ .values(
+ trackedEntities.data.map((entity) => ({
+ nonConformanceId,
+ trackedEntityId: entity.id,
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+
+ await trx
+ .insertInto("nonConformanceItemTrackedEntity")
+ .values(
+ trackedEntities.data.map((entity) => ({
+ nonConformanceItemId: item.id,
+ nonConformanceId,
+ trackedEntityId: entity.id,
+ quantity: Number(entity.quantity ?? quantity),
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+ });
+ } catch (err) {
+ return { error: err };
+ }
+
+ return { error: null };
}
async function getTrackedEntitiesForIssue(
diff --git a/packages/database/src/quality.ts b/packages/database/src/quality.ts
index 3a5d6cf72e..1d605fac42 100644
--- a/packages/database/src/quality.ts
+++ b/packages/database/src/quality.ts
@@ -1346,3 +1346,34 @@ export async function getOrCreateJobOperationInspection(
);
}
}
+
+// -------------------------------------------------------------
+// Issue disposition lock
+// -------------------------------------------------------------
+
+/**
+ * Serializes writes to an issue's disposition rows. Every writer that inserts
+ * `nonConformanceItemTrackedEntity` or `nonConformanceInspection` rows, or
+ * changes `nonConformanceItem.quantity`, takes this lock first inside its
+ * transaction — before touching any item row, so the lock order is always
+ * issue → item and writers cannot deadlock each other.
+ *
+ * It holds a `FOR NO KEY UPDATE` lock on the `nonConformance` row, which
+ * conflicts with other holders of the same lock but not with the FK checks of
+ * unrelated child inserts. Returns the issue status for the caller's
+ * locked-issue check; throws when the issue does not exist in the company.
+ */
+export async function lockIssueDispositions(
+ trx: Transaction<KyselyDatabase>,
+ args: { nonConformanceId: string; companyId: string }
+): Promise<{ status: string }> {
+ const issue = await trx
+ .selectFrom("nonConformance")
+ .select(["status"])
+ .where("id", "=", args.nonConformanceId)
+ .where("companyId", "=", args.companyId)
+ .forNoKeyUpdate()
+ .executeTakeFirst();
+ if (!issue) throw new Error("Issue not found");
+ return { status: issue.status };
+}
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index 4d096f73fb..049493d475 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20260911130000",
+ "schemaVersion": "20260914095239",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-09-11T12:46:13.101Z",
+ "exportedAt": "2026-09-15T18:44:34.921Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -849,14 +849,14 @@
"name": "gaugeType",
"rows": 0,
"columns": [
- "customFields",
- "companyId",
- "updatedAt",
- "createdAt",
+ "id",
+ "createdBy",
"name",
"updatedBy",
- "id",
- "createdBy"
+ "createdAt",
+ "customFields",
+ "companyId",
+ "updatedAt"
]
},
{
@@ -1269,7 +1269,7 @@
{
"name": "materialDimension",
"rows": 0,
- "columns": ["isMetric", "name", "companyId", "materialFormId", "id"]
+ "columns": ["name", "isMetric", "companyId", "materialFormId", "id"]
},
{
"name": "materialSubstance",
@@ -1290,23 +1290,23 @@
{
"name": "materialFinish",
"rows": 0,
- "columns": ["companyId", "materialSubstanceId", "id", "name"]
+ "columns": ["companyId", "materialSubstanceId", "name", "id"]
},
{
"name": "materialGrade",
"rows": 0,
- "columns": ["id", "materialSubstanceId", "companyId", "name"]
+ "columns": ["companyId", "name", "id", "materialSubstanceId"]
},
{
"name": "materialType",
"rows": 0,
"columns": [
- "id",
- "companyId",
- "name",
- "materialFormId",
"code",
- "materialSubstanceId"
+ "materialSubstanceId",
+ "materialFormId",
+ "name",
+ "id",
+ "companyId"
]
},
{
@@ -1388,13 +1388,13 @@
"rows": 0,
"columns": [
"createdBy",
+ "updatedAt",
"createdAt",
"companyId",
- "updatedAt",
- "id",
"updatedBy",
- "name",
- "customFields"
+ "id",
+ "customFields",
+ "name"
]
},
{
@@ -1402,80 +1402,80 @@
"rows": 0,
"columns": [
"createdAt",
- "updatedAt",
- "name",
"active",
- "createdBy",
- "systemType",
+ "name",
+ "updatedAt",
"id",
- "updatedBy",
- "companyId"
+ "systemType",
+ "createdBy",
+ "companyId",
+ "updatedBy"
]
},
{
"name": "nonConformanceType",
"rows": 0,
"columns": [
- "id",
- "updatedAt",
"name",
"customFields",
- "createdBy",
+ "id",
+ "updatedAt",
"createdAt",
"companyId",
- "updatedBy"
+ "updatedBy",
+ "createdBy"
]
},
{
"name": "nonConformanceWorkflow",
"rows": 0,
"columns": [
+ "createdBy",
+ "description",
+ "content",
+ "requiredActionIds",
"priority",
"companyId",
"updatedAt",
- "content",
- "description",
- "createdBy",
- "requiredActionIds",
- "id",
- "approvalRequirements",
- "tags",
- "source",
"updatedBy",
"createdAt",
"name",
- "active"
+ "active",
+ "approvalRequirements",
+ "id",
+ "tags",
+ "source"
]
},
{
"name": "nonConformance",
"rows": 0,
"columns": [
- "assignee",
- "content",
- "source",
- "tags",
- "updatedAt",
- "closeDate",
- "customFields",
- "openDate",
- "quantity",
- "description",
- "nonConformanceTypeId",
- "name",
- "companyId",
- "priority",
+ "locationId",
+ "nonConformanceId",
+ "dueDate",
+ "createdAt",
+ "approvalRequirements",
+ "requiredActionIds",
"updatedBy",
"nonConformanceWorkflowId",
"id",
"createdBy",
"status",
- "nonConformanceId",
- "locationId",
- "dueDate",
- "approvalRequirements",
- "createdAt",
- "requiredActionIds"
+ "quantity",
+ "description",
+ "name",
+ "nonConformanceTypeId",
+ "companyId",
+ "priority",
+ "source",
+ "assignee",
+ "content",
+ "tags",
+ "openDate",
+ "customFields",
+ "updatedAt",
+ "closeDate"
]
},
{
@@ -1534,39 +1534,39 @@
"name": "nonConformanceApprovalTask",
"rows": 0,
"columns": [
+ "updatedBy",
+ "dueDate",
+ "createdAt",
+ "assignee",
"status",
"updatedAt",
"approvalType",
- "assignee",
- "createdAt",
- "dueDate",
- "updatedBy",
- "nonConformanceId",
- "createdBy",
- "tags",
- "notes",
- "companyId",
+ "completedDate",
"id",
"sortOrder",
- "completedDate"
+ "companyId",
+ "notes",
+ "tags",
+ "createdBy",
+ "nonConformanceId"
]
},
{
"name": "nonConformanceReviewer",
"rows": 0,
"columns": [
+ "status",
+ "nonConformanceId",
+ "companyId",
+ "completedDate",
+ "notes",
"title",
"createdAt",
"updatedAt",
"createdBy",
"id",
"updatedBy",
- "assignee",
- "status",
- "nonConformanceId",
- "companyId",
- "notes",
- "completedDate"
+ "assignee"
]
},
{
@@ -1881,35 +1881,35 @@
"name": "procedure",
"rows": 0,
"columns": [
- "processId",
- "tags",
- "description",
- "content",
- "version",
- "updatedAt",
- "updatedBy",
+ "id",
+ "companyId",
+ "createdBy",
+ "status",
"name",
- "createdAt",
+ "updatedBy",
"assignee",
- "createdBy",
- "companyId",
- "id",
- "status"
+ "createdAt",
+ "updatedAt",
+ "version",
+ "description",
+ "processId",
+ "tags",
+ "content"
]
},
{
"name": "procedureParameter",
"rows": 0,
"columns": [
- "createdAt",
"id",
"updatedBy",
- "updatedAt",
+ "createdAt",
"procedureId",
+ "updatedAt",
"companyId",
- "createdBy",
"value",
- "key"
+ "key",
+ "createdBy"
]
},
{
@@ -1993,15 +1993,15 @@
"name": "returnReason",
"rows": 0,
"columns": [
- "createdBy",
- "inventoryValueZero",
- "companyId",
- "updatedBy",
- "customFields",
+ "name",
+ "updatedAt",
"id",
+ "customFields",
"createdAt",
- "name",
- "updatedAt"
+ "companyId",
+ "inventoryValueZero",
+ "updatedBy",
+ "createdBy"
]
},
{
@@ -2161,16 +2161,16 @@
"name": "slackDocumentThread",
"rows": 0,
"columns": [
- "updatedAt",
- "id",
- "threadTs",
- "companyId",
- "createdBy",
- "updatedBy",
- "channelId",
+ "createdAt",
"documentType",
"documentId",
- "createdAt"
+ "channelId",
+ "updatedBy",
+ "createdBy",
+ "companyId",
+ "threadTs",
+ "updatedAt",
+ "id"
]
},
{
@@ -2301,21 +2301,21 @@
"name": "tableView",
"rows": 0,
"columns": [
- "sortOrder",
- "columnVisibility",
- "id",
- "sorts",
- "columnPinning",
- "filters",
- "createdAt",
- "name",
"updatedBy",
"type",
"companyId",
"columnOrder",
"table",
"createdBy",
- "description"
+ "description",
+ "sortOrder",
+ "sorts",
+ "columnVisibility",
+ "id",
+ "filters",
+ "columnPinning",
+ "createdAt",
+ "name"
]
},
{
@@ -2378,16 +2378,16 @@
"name": "trackedActivity",
"rows": 0,
"columns": [
- "id",
- "createdBy",
- "attributes",
- "type",
- "createdAt",
- "updatedBy",
- "sourceDocumentReadableId",
+ "companyId",
"sourceDocumentId",
"sourceDocument",
- "companyId"
+ "sourceDocumentReadableId",
+ "updatedBy",
+ "createdAt",
+ "type",
+ "attributes",
+ "id",
+ "createdBy"
]
},
{
@@ -2665,17 +2665,17 @@
"name": "batchProperty",
"rows": 0,
"columns": [
+ "dataType",
+ "label",
+ "companyId",
+ "listOptions",
+ "itemId",
"createdAt",
"updatedAt",
- "itemId",
- "sortOrder",
- "createdBy",
"id",
+ "createdBy",
"updatedBy",
- "companyId",
- "label",
- "dataType",
- "listOptions"
+ "sortOrder"
]
},
{
@@ -2744,18 +2744,18 @@
"name": "demandForecast",
"rows": 0,
"columns": [
- "confidence",
+ "updatedBy",
+ "forecastMethod",
+ "periodId",
+ "forecastQuantity",
+ "notes",
"createdBy",
"itemId",
"updatedAt",
- "companyId",
- "createdAt",
+ "confidence",
"locationId",
- "updatedBy",
- "forecastMethod",
- "notes",
- "periodId",
- "forecastQuantity"
+ "companyId",
+ "createdAt"
]
},
{
@@ -3054,39 +3054,39 @@
"name": "nonConformanceItem",
"rows": 0,
"columns": [
- "itemId",
+ "createdAt",
"companyId",
+ "itemId",
"updatedAt",
- "createdAt",
+ "id",
+ "disposition",
+ "createdBy",
"nonConformanceId",
- "updatedBy",
"quantity",
- "disposition",
- "id",
- "createdBy"
+ "updatedBy"
]
},
{
"name": "procedureStep",
"rows": 0,
"columns": [
- "maxValue",
- "unitOfMeasureCode",
- "companyId",
- "procedureId",
- "updatedAt",
- "sortOrder",
- "listValues",
+ "fileTypes",
+ "required",
+ "updatedBy",
+ "createdBy",
+ "createdAt",
+ "name",
+ "description",
+ "type",
"minValue",
"id",
- "type",
- "description",
- "name",
- "createdAt",
- "createdBy",
- "updatedBy",
- "required",
- "fileTypes"
+ "listValues",
+ "sortOrder",
+ "updatedAt",
+ "procedureId",
+ "companyId",
+ "unitOfMeasureCode",
+ "maxValue"
]
},
{
@@ -3174,20 +3174,20 @@
"name": "trackedEntity",
"rows": 0,
"columns": [
- "attributes",
- "updatedBy",
"status",
+ "updatedBy",
"sourceDocument",
+ "attributes",
"itemId",
"sourceDocumentId",
- "createdBy",
- "companyId",
"quantity",
"expirationDate",
- "sourceDocumentReadableId",
+ "createdBy",
+ "companyId",
"readableId",
"createdAt",
- "id"
+ "id",
+ "sourceDocumentReadableId"
]
},
{
@@ -3215,8 +3215,8 @@
"createdBy",
"id",
"updatedAt",
- "companyId",
"trackedEntityId",
+ "companyId",
"createdAt"
]
},
@@ -3224,26 +3224,26 @@
"name": "trackedActivityInput",
"rows": 0,
"columns": [
- "companyId",
- "quantity",
- "createdBy",
- "trackedActivityId",
- "createdAt",
+ "updatedBy",
"trackedEntityId",
- "updatedBy"
+ "createdAt",
+ "trackedActivityId",
+ "createdBy",
+ "quantity",
+ "companyId"
]
},
{
"name": "trackedActivityOutput",
"rows": 0,
"columns": [
- "trackedEntityId",
- "createdBy",
- "trackedActivityId",
- "updatedBy",
- "companyId",
+ "createdAt",
"quantity",
- "createdAt"
+ "companyId",
+ "updatedBy",
+ "trackedActivityId",
+ "createdBy",
+ "trackedEntityId"
]
},
{
@@ -3342,22 +3342,22 @@
"name": "warehouseTransfer",
"rows": 0,
"columns": [
- "transferDate",
- "createdBy",
+ "tags",
+ "transferId",
+ "updatedBy",
+ "notes",
+ "companyId",
"id",
"reference",
- "companyId",
- "notes",
- "updatedBy",
- "transferId",
- "tags",
- "customFields",
- "status",
- "createdAt",
- "expectedReceiptDate",
+ "createdBy",
+ "transferDate",
"toLocationId",
"fromLocationId",
- "updatedAt"
+ "updatedAt",
+ "expectedReceiptDate",
+ "createdAt",
+ "status",
+ "customFields"
]
},
{
@@ -3391,19 +3391,19 @@
"name": "jobOperationBatch",
"rows": 0,
"columns": [
- "status",
"processId",
"companyId",
- "updatedBy",
+ "status",
"workCenterId",
- "notes",
- "createdBy",
- "readableId",
+ "updatedBy",
"updatedAt",
- "locationId",
+ "readableId",
+ "createdBy",
+ "notes",
+ "createdAt",
"id",
"customFields",
- "createdAt"
+ "locationId"
]
},
{
@@ -3666,24 +3666,24 @@
"name": "warehouseTransferLine",
"rows": 0,
"columns": [
- "quantity",
- "itemId",
- "createdBy",
- "customFields",
- "fromLocationId",
- "notes",
- "shippedQuantity",
- "updatedAt",
- "createdAt",
- "updatedBy",
- "transferId",
- "companyId",
- "fromStorageUnitId",
"toStorageUnitId",
+ "fromStorageUnitId",
+ "companyId",
+ "transferId",
+ "updatedBy",
+ "receivedQuantity",
+ "unitOfMeasureCode",
"id",
"toLocationId",
- "unitOfMeasureCode",
- "receivedQuantity"
+ "fromLocationId",
+ "customFields",
+ "quantity",
+ "createdBy",
+ "itemId",
+ "createdAt",
+ "updatedAt",
+ "shippedQuantity",
+ "notes"
]
},
{
@@ -3961,14 +3961,14 @@
"name": "nonConformanceCustomer",
"rows": 0,
"columns": [
- "updatedAt",
- "companyId",
"customerId",
+ "companyId",
+ "updatedAt",
"createdAt",
- "updatedBy",
"nonConformanceId",
- "createdBy",
- "id"
+ "updatedBy",
+ "id",
+ "createdBy"
]
},
{
@@ -4070,16 +4070,16 @@
"name": "nonConformanceSalesOrderLine",
"rows": 0,
"columns": [
+ "salesOrderReadableId",
+ "createdAt",
+ "salesOrderId",
+ "salesOrderLineId",
"companyId",
- "updatedAt",
"id",
+ "updatedAt",
"createdBy",
"updatedBy",
- "nonConformanceId",
- "salesOrderReadableId",
- "createdAt",
- "salesOrderLineId",
- "salesOrderId"
+ "nonConformanceId"
]
},
{
@@ -4155,29 +4155,29 @@
"name": "salesReturnOrder",
"rows": 0,
"columns": [
- "assignee",
- "internalNotes",
- "updatedBy",
- "updatedAt",
- "createdAt",
- "exchangeRate",
- "customerLocationId",
- "customFields",
"customerReference",
- "customerId",
+ "customFields",
+ "createdBy",
+ "companyId",
"expirationDate",
"status",
- "companyId",
- "createdBy",
- "customerContactId",
- "id",
- "salesOrderId",
- "currencyCode",
- "locationId",
+ "customerId",
+ "internalNotes",
+ "updatedBy",
+ "assignee",
+ "customerLocationId",
+ "exchangeRate",
+ "createdAt",
+ "updatedAt",
"replacementSalesOrderId",
- "externalNotes",
+ "locationId",
+ "orderDate",
"salesReturnOrderId",
- "orderDate"
+ "externalNotes",
+ "customerContactId",
+ "currencyCode",
+ "salesOrderId",
+ "id"
]
},
{
@@ -4346,15 +4346,15 @@
"name": "fulfillment",
"rows": 0,
"columns": [
- "salesOrderLineId",
- "createdBy",
- "id",
- "updatedBy",
"companyId",
- "quantity",
- "type",
+ "updatedBy",
+ "id",
+ "createdBy",
+ "salesOrderLineId",
+ "jobId",
"createdAt",
- "jobId"
+ "type",
+ "quantity"
]
},
{
@@ -4485,56 +4485,56 @@
"name": "gauge",
"rows": 0,
"columns": [
- "gaugeRole",
- "gaugeCalibrationStatus",
- "id",
- "description",
- "lastCalibrationDate",
- "gaugeId",
- "storageUnitId",
- "gaugeStatus",
- "gaugeTypeId",
+ "updatedBy",
"serialNumber",
"calibrationIntervalInMonths",
"createdBy",
- "updatedBy",
- "updatedAt",
"locationId",
+ "updatedAt",
"companyId",
- "createdAt",
- "customFields",
- "nextCalibrationDate",
"supplierId",
+ "nextCalibrationDate",
"modelNumber",
+ "createdAt",
+ "customFields",
"dateAcquired",
- "lastCalibrationStatus"
+ "lastCalibrationStatus",
+ "gaugeCalibrationStatus",
+ "id",
+ "gaugeRole",
+ "description",
+ "storageUnitId",
+ "lastCalibrationDate",
+ "gaugeId",
+ "gaugeTypeId",
+ "gaugeStatus"
]
},
{
"name": "gaugeCalibrationRecord",
"rows": 0,
"columns": [
- "calibrationAttempts",
- "createdBy",
- "requiresAction",
- "humidity",
- "supplierId",
- "inspectionStatus",
- "updatedBy",
- "dateCalibrated",
- "approvedBy",
- "measurementStandard",
- "requiresRepair",
- "id",
"customFields",
+ "id",
"createdAt",
"requiresAdjustment",
"temperature",
- "gaugeId",
"updatedAt",
+ "gaugeId",
"notes",
- "companyId"
- ]
+ "companyId",
+ "requiresAction",
+ "createdBy",
+ "calibrationAttempts",
+ "supplierId",
+ "humidity",
+ "dateCalibrated",
+ "updatedBy",
+ "inspectionStatus",
+ "measurementStandard",
+ "approvedBy",
+ "requiresRepair"
+ ]
},
{
"name": "inspection",
@@ -4830,26 +4830,26 @@
"name": "jobOperationDependency",
"rows": 0,
"columns": [
- "dependsOnId",
- "operationId",
+ "createdAt",
"jobId",
"companyId",
- "createdAt"
+ "operationId",
+ "dependsOnId"
]
},
{
"name": "jobOperationParameter",
"rows": 0,
"columns": [
- "updatedBy",
- "id",
- "createdAt",
+ "operationId",
+ "value",
+ "createdBy",
+ "companyId",
"key",
"updatedAt",
- "companyId",
- "value",
- "operationId",
- "createdBy"
+ "id",
+ "updatedBy",
+ "createdAt"
]
},
{
@@ -4871,16 +4871,16 @@
"name": "nonConformanceJobOperation",
"rows": 0,
"columns": [
- "jobReadableId",
- "jobId",
- "jobOperationId",
"createdAt",
- "id",
- "updatedAt",
- "companyId",
- "nonConformanceId",
+ "jobOperationId",
+ "jobId",
+ "jobReadableId",
+ "updatedBy",
"createdBy",
- "updatedBy"
+ "nonConformanceId",
+ "companyId",
+ "updatedAt",
+ "id"
]
},
{
@@ -4965,15 +4965,15 @@
"name": "jobOperationNote",
"rows": 0,
"columns": [
+ "createdAt",
"companyId",
"note",
"updatedBy",
- "createdAt",
- "jobOperationId",
- "updatedAt",
"id",
"productionQuantityId",
- "createdBy"
+ "createdBy",
+ "jobOperationId",
+ "updatedAt"
]
},
{
@@ -4997,44 +4997,44 @@
"name": "jobOperationStep",
"rows": 0,
"columns": [
+ "updatedAt",
+ "companyId",
+ "name",
+ "minValue",
+ "listValues",
+ "id",
+ "maxValue",
+ "fileTypes",
+ "type",
+ "required",
+ "createdAt",
+ "nonConformanceActionId",
+ "description",
+ "unitOfMeasureCode",
+ "sortOrder",
"nonConformanceInvestigationId",
"operationId",
- "sortOrder",
- "updatedBy",
"assemblyInstructionStepId",
"createdBy",
- "description",
- "nonConformanceActionId",
- "required",
- "createdAt",
- "unitOfMeasureCode",
- "fileTypes",
- "id",
- "maxValue",
- "type",
- "name",
- "companyId",
- "updatedAt",
- "listValues",
- "minValue"
+ "updatedBy"
]
},
{
"name": "jobOperationStepRecord",
"rows": 0,
"columns": [
- "createdBy",
- "updatedBy",
- "value",
- "companyId",
- "updatedAt",
+ "userValue",
+ "index",
+ "booleanValue",
+ "numericValue",
+ "createdAt",
"jobOperationStepId",
+ "updatedAt",
"id",
- "createdAt",
- "numericValue",
- "booleanValue",
- "userValue",
- "index"
+ "companyId",
+ "value",
+ "createdBy",
+ "updatedBy"
]
},
{
@@ -5065,25 +5065,25 @@
"name": "kanban",
"rows": 0,
"columns": [
- "companyId",
- "id",
- "conversionFactor",
- "storageUnitId",
- "createdBy",
- "itemId",
- "autoStartJob",
- "autoRelease",
- "purchaseUnitOfMeasureCode",
- "locationId",
- "createdAt",
"updatedBy",
"completedBarcodeOverride",
+ "locationId",
+ "createdAt",
+ "supplierId",
"fromStorageUnitId",
"jobId",
- "quantity",
- "updatedAt",
"replenishmentSystem",
- "supplierId"
+ "updatedAt",
+ "quantity",
+ "storageUnitId",
+ "companyId",
+ "conversionFactor",
+ "id",
+ "autoRelease",
+ "purchaseUnitOfMeasureCode",
+ "createdBy",
+ "itemId",
+ "autoStartJob"
]
},
{
@@ -5157,39 +5157,39 @@
"name": "methodOperationParameter",
"rows": 0,
"columns": [
+ "value",
+ "operationId",
+ "createdBy",
+ "companyId",
"key",
"updatedAt",
- "id",
"updatedBy",
- "createdAt",
- "operationId",
- "value",
- "createdBy",
- "companyId"
+ "id",
+ "createdAt"
]
},
{
"name": "methodOperationStep",
"rows": 0,
"columns": [
+ "sortOrder",
+ "operationId",
+ "createdBy",
+ "updatedBy",
"assemblyInstructionStepId",
"description",
"createdAt",
"required",
"unitOfMeasureCode",
- "sortOrder",
- "operationId",
- "createdBy",
- "updatedBy",
+ "fileTypes",
+ "maxValue",
+ "id",
+ "type",
"companyId",
"name",
"updatedAt",
"listValues",
- "minValue",
- "fileTypes",
- "maxValue",
- "id",
- "type"
+ "minValue"
]
},
{
@@ -5250,8 +5250,8 @@
"rows": 0,
"columns": [
"assignee",
- "updatedAt",
"status",
+ "updatedAt",
"supplierId",
"updatedBy",
"createdAt",
@@ -5263,24 +5263,24 @@
"actionTypeId",
"completedDate",
"companyId",
- "sortOrder",
- "id"
+ "id",
+ "sortOrder"
]
},
{
"name": "nonConformancePurchaseReturnOrderLine",
"rows": 0,
"columns": [
- "purchaseReturnOrderLineId",
"purchaseReturnOrderId",
+ "purchaseReturnOrderLineId",
"companyId",
"purchaseReturnOrderReadableId",
"nonConformanceId",
"updatedAt",
"createdAt",
"updatedBy",
- "createdBy",
"id",
+ "createdBy",
"quantity"
]
},
@@ -5289,15 +5289,15 @@
"rows": 0,
"columns": [
"salesReturnOrderReadableId",
- "createdAt",
"salesReturnOrderId",
"salesReturnOrderLineId",
- "companyId",
+ "createdAt",
"id",
"updatedAt",
+ "companyId",
+ "nonConformanceId",
"updatedBy",
- "createdBy",
- "nonConformanceId"
+ "createdBy"
]
},
{
@@ -5367,17 +5367,17 @@
"name": "purchaseInvoiceDelivery",
"rows": 0,
"columns": [
- "customFields",
- "id",
- "incotermLocation",
- "companyId",
- "locationId",
+ "updatedBy",
+ "shippingTermId",
+ "shippingMethodId",
+ "supplierShippingCost",
"updatedAt",
"incoterm",
- "supplierShippingCost",
- "shippingMethodId",
- "shippingTermId",
- "updatedBy"
+ "locationId",
+ "companyId",
+ "id",
+ "customFields",
+ "incotermLocation"
]
},
{
@@ -5470,15 +5470,15 @@
"rows": 0,
"columns": [
"companyId",
- "updatedAt",
"id",
- "updatedBy",
+ "updatedAt",
"createdBy",
+ "updatedBy",
"nonConformanceId",
"purchaseOrderReadableId",
"createdAt",
- "purchaseOrderLineId",
- "purchaseOrderId"
+ "purchaseOrderId",
+ "purchaseOrderLineId"
]
},
{
@@ -5511,13 +5511,13 @@
"rows": 0,
"columns": [
"createdBy",
- "updatedBy",
"companyId",
"quantity",
- "createdAt",
+ "updatedBy",
"purchaseReturnOrderLineId",
- "updatedAt",
- "trackedEntityId"
+ "createdAt",
+ "trackedEntityId",
+ "updatedAt"
]
},
{
@@ -5642,38 +5642,38 @@
"name": "quoteOperationParameter",
"rows": 0,
"columns": [
- "createdAt",
- "updatedBy",
- "id",
"updatedAt",
"key",
- "companyId",
+ "createdAt",
+ "id",
+ "updatedBy",
"createdBy",
+ "operationId",
"value",
- "operationId"
+ "companyId"
]
},
{
"name": "quoteOperationStep",
"rows": 0,
"columns": [
- "type",
- "fileTypes",
- "id",
- "maxValue",
+ "unitOfMeasureCode",
+ "description",
+ "required",
+ "createdAt",
+ "updatedBy",
+ "createdBy",
+ "operationId",
+ "sortOrder",
"listValues",
"minValue",
"name",
"companyId",
"updatedAt",
- "updatedBy",
- "createdBy",
- "operationId",
- "sortOrder",
- "unitOfMeasureCode",
- "description",
- "required",
- "createdAt"
+ "type",
+ "fileTypes",
+ "id",
+ "maxValue"
]
},
{
@@ -5760,170 +5760,170 @@
"name": "nonConformanceReceiptLine",
"rows": 0,
"columns": [
+ "createdAt",
"receiptLineId",
"receiptId",
- "createdAt",
"receiptReadableId",
- "nonConformanceId",
- "updatedBy",
"createdBy",
+ "updatedBy",
+ "nonConformanceId",
+ "companyId",
"updatedAt",
- "id",
- "companyId"
+ "id"
]
},
{
"name": "salesInvoice",
"rows": 0,
"columns": [
- "currencyCode",
- "exchangeRate",
- "companyId",
- "totalDiscount",
- "exchangeRateUpdatedAt",
- "customerReference",
- "createdAt",
- "dateDue",
- "opportunityId",
- "invoiceCustomerLocationId",
- "internalNotes",
- "createdBy",
- "customerId",
"locationId",
"status",
+ "customerId",
"totalTax",
"totalAmount",
- "invoiceCustomerId",
- "assignee",
- "id",
- "paymentTermId",
- "customFields",
- "dateIssued",
+ "invoiceCustomerLocationId",
+ "opportunityId",
+ "internalNotes",
+ "createdBy",
+ "exchangeRateUpdatedAt",
+ "customerReference",
+ "dateDue",
+ "createdAt",
+ "exchangeRate",
+ "currencyCode",
+ "totalDiscount",
+ "companyId",
+ "subtotal",
+ "datePaid",
+ "invoiceId",
+ "updatedBy",
+ "externalNotes",
"tags",
"invoiceCustomerContactId",
- "externalNotes",
"shipmentId",
- "updatedAt",
"postingDate",
- "subtotal",
- "datePaid",
- "invoiceId",
- "updatedBy"
+ "updatedAt",
+ "paymentTermId",
+ "id",
+ "dateIssued",
+ "customFields",
+ "invoiceCustomerId",
+ "assignee"
]
},
{
"name": "salesInvoiceLine",
"rows": 0,
"columns": [
- "nonTaxableAddOnCost",
- "opportunityId",
- "unitOfMeasureCode",
+ "methodType",
+ "internalNotes",
"id",
"assetId",
- "internalNotes",
- "methodType",
- "storageUnitId",
- "updatedAt",
- "invoiceId",
- "setupPrice",
- "externalNotes",
- "createdBy",
- "quantity",
+ "opportunityId",
+ "unitOfMeasureCode",
+ "nonTaxableAddOnCost",
"customFields",
"salesOrderLineId",
- "itemId",
- "companyId",
- "locationId",
- "unitPrice",
+ "quantity",
+ "createdBy",
+ "externalNotes",
+ "setupPrice",
+ "updatedAt",
+ "invoiceId",
+ "storageUnitId",
"modelUploadId",
"addOnCost",
- "taxPercent",
- "sortOrder",
- "shippingCost",
+ "unitPrice",
+ "locationId",
+ "companyId",
+ "itemId",
+ "salesOrderId",
+ "accountId",
+ "updatedBy",
+ "createdAt",
"description",
"invoiceLineType",
"exchangeRate",
- "createdAt",
- "accountId",
- "updatedBy",
- "salesOrderId"
+ "shippingCost",
+ "sortOrder",
+ "taxPercent"
]
},
{
"name": "salesInvoiceShipment",
"rows": 0,
"columns": [
- "shippingCost",
- "incotermLocation",
+ "companyId",
+ "locationId",
+ "shippingMethodId",
+ "incoterm",
+ "shippingTermId",
"createdAt",
"updatedAt",
+ "shippingCost",
+ "incotermLocation",
+ "customFields",
"createdBy",
"id",
- "updatedBy",
- "customFields",
- "locationId",
- "shippingMethodId",
- "companyId",
- "incoterm",
- "shippingTermId"
+ "updatedBy"
]
},
{
"name": "salesReturnOrderLine",
"rows": 0,
"columns": [
- "salesInvoiceLineId",
- "salesReturnOrderId",
- "companyId",
"returnReasonId",
"unitPrice",
+ "salesReturnOrderId",
+ "salesInvoiceLineId",
+ "companyId",
+ "quantityReceived",
"salesOrderLineId",
- "id",
"restockFeePercent",
- "quantityReceived",
- "updatedBy",
+ "id",
+ "unitOfMeasureCode",
"createdAt",
- "itemId",
- "disposition",
+ "updatedBy",
"lineNumber",
- "unitOfMeasureCode",
- "quantity",
- "updatedAt",
- "shipmentLineId",
- "closedComplete",
+ "disposition",
+ "itemId",
+ "createdBy",
"customFields",
- "createdBy"
+ "closedComplete",
+ "shipmentLineId",
+ "updatedAt",
+ "quantity"
]
},
{
"name": "salesReturnOrderLineTrackedEntity",
"rows": 0,
"columns": [
- "updatedAt",
- "trackedEntityId",
- "createdAt",
"salesReturnOrderLineId",
- "updatedBy",
- "companyId",
+ "createdAt",
+ "trackedEntityId",
+ "updatedAt",
+ "createdBy",
"quantity",
- "createdBy"
+ "companyId",
+ "updatedBy"
]
},
{
"name": "salesReturnOrderCreditLine",
"rows": 0,
"columns": [
- "companyId",
- "salesReturnOrderLineId",
- "quantity",
"unitPrice",
- "createdBy",
- "updatedBy",
- "memoId",
- "restockFee",
- "createdAt",
+ "quantity",
+ "salesReturnOrderLineId",
+ "companyId",
+ "updatedAt",
"id",
- "updatedAt"
+ "createdAt",
+ "restockFee",
+ "memoId",
+ "updatedBy",
+ "createdBy"
]
},
{
@@ -5946,41 +5946,41 @@
"name": "shipmentLine",
"rows": 0,
"columns": [
- "fulfillmentId",
- "unitPrice",
- "companyId",
- "createdBy",
- "itemId",
+ "shippedQuantity",
+ "storageUnitId",
+ "createdAt",
+ "requiresSerialTracking",
+ "shipmentId",
+ "orderQuantity",
+ "locationId",
+ "id",
+ "unitOfMeasure",
+ "outstandingQuantity",
"requiresBatchTracking",
"lineId",
+ "itemId",
"updatedBy",
"updatedAt",
- "outstandingQuantity",
- "id",
- "locationId",
- "unitOfMeasure",
- "orderQuantity",
- "createdAt",
- "requiresSerialTracking",
- "shipmentId",
- "shippedQuantity",
- "storageUnitId"
+ "companyId",
+ "createdBy",
+ "unitPrice",
+ "fulfillmentId"
]
},
{
"name": "nonConformanceShipmentLine",
"rows": 0,
"columns": [
- "shipmentReadableId",
- "shipmentLineId",
- "shipmentId",
- "createdAt",
- "updatedAt",
- "id",
- "companyId",
- "nonConformanceId",
+ "createdBy",
"updatedBy",
- "createdBy"
+ "nonConformanceId",
+ "companyId",
+ "id",
+ "updatedAt",
+ "createdAt",
+ "shipmentId",
+ "shipmentLineId",
+ "shipmentReadableId"
]
},
{
@@ -6055,33 +6055,33 @@
"name": "shipment",
"rows": 0,
"columns": [
- "shippingMethodId",
- "tags",
+ "customerId",
+ "id",
+ "postingDate",
+ "externalDocumentId",
+ "sourceDocumentReadableId",
+ "supplierId",
+ "externalNotes",
+ "invoiced",
+ "shipmentId",
+ "trackingNumber",
+ "customFields",
+ "status",
+ "updatedBy",
+ "sourceDocumentId",
+ "postedBy",
+ "createdBy",
+ "internalNotes",
+ "updatedAt",
+ "opportunityId",
+ "supplierInteractionId",
"locationId",
"assignee",
"sourceDocument",
- "companyId",
"createdAt",
- "opportunityId",
- "supplierInteractionId",
- "internalNotes",
- "updatedAt",
- "updatedBy",
- "postedBy",
- "createdBy",
- "sourceDocumentId",
- "trackingNumber",
- "status",
- "customFields",
- "externalNotes",
- "shipmentId",
- "invoiced",
- "sourceDocumentReadableId",
- "supplierId",
- "customerId",
- "id",
- "postingDate",
- "externalDocumentId"
+ "companyId",
+ "shippingMethodId",
+ "tags"
]
},
{
@@ -6275,29 +6275,29 @@
"name": "purchaseReturnOrder",
"rows": 0,
"columns": [
- "currencyCode",
- "id",
- "purchaseOrderId",
- "supplierContactId",
- "purchaseReturnOrderId",
- "orderDate",
- "externalNotes",
- "replacementPurchaseOrderId",
- "locationId",
- "createdAt",
- "exchangeRate",
- "supplierLocationId",
- "updatedAt",
- "assignee",
- "internalNotes",
"updatedBy",
- "companyId",
- "createdBy",
- "supplierId",
- "expirationDate",
- "status",
+ "internalNotes",
+ "assignee",
+ "updatedAt",
+ "supplierLocationId",
+ "exchangeRate",
+ "createdAt",
+ "supplierReference",
"customFields",
- "supplierReference"
+ "status",
+ "expirationDate",
+ "supplierId",
+ "createdBy",
+ "companyId",
+ "supplierContactId",
+ "purchaseOrderId",
+ "id",
+ "currencyCode",
+ "locationId",
+ "replacementPurchaseOrderId",
+ "externalNotes",
+ "orderDate",
+ "purchaseReturnOrderId"
]
},
{
@@ -6363,43 +6363,43 @@
"name": "purchaseReturnOrderLine",
"rows": 0,
"columns": [
- "companyId",
- "createdAt",
+ "id",
+ "restockFeePercent",
+ "purchaseOrderLineId",
+ "quantityShipped",
+ "createdBy",
+ "purchaseInvoiceLineId",
+ "purchaseReturnOrderId",
+ "unitPrice",
+ "returnReasonId",
"quantity",
"customFields",
"receiptLineId",
- "unitOfMeasureCode",
- "updatedAt",
- "updatedBy",
+ "companyId",
+ "createdAt",
"itemId",
- "lineNumber",
"closedComplete",
- "quantityShipped",
- "purchaseOrderLineId",
- "id",
- "restockFeePercent",
- "returnReasonId",
- "unitPrice",
- "purchaseInvoiceLineId",
- "purchaseReturnOrderId",
- "createdBy"
+ "lineNumber",
+ "updatedAt",
+ "updatedBy",
+ "unitOfMeasureCode"
]
},
{
"name": "purchaseReturnOrderCreditLine",
"rows": 0,
"columns": [
- "unitPrice",
"quantity",
"purchaseReturnOrderLineId",
"companyId",
+ "unitPrice",
+ "memoId",
+ "createdBy",
+ "updatedBy",
"id",
"createdAt",
"updatedAt",
- "restockFee",
- "memoId",
- "createdBy",
- "updatedBy"
+ "restockFee"
]
},
{