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.

bug fix: subdivide batch lots when splitting disposition rows (#1153)

Anshul sharmad79824edb437
diff --git a/apps/erp/app/modules/quality/quality-disposition.server.ts b/apps/erp/app/modules/quality/quality-disposition.server.ts
new file mode 100644
index 0000000000..91e4c2d338
--- /dev/null
+++ b/apps/erp/app/modules/quality/quality-disposition.server.ts
@@ -0,0 +1,903 @@
+import type { Database } from "@carbon/database";
+import type { KyselyTx } from "@carbon/database/client";
+import type { SupabaseClient } from "@supabase/supabase-js";
+
+import { getDatabaseClient } from "~/services/database.server";
+import { isIssueLocked } from "./quality.models";
+import { errResult, type Result } from "./quality.server";
+
+type TrackedEntityRow = Database["public"]["Tables"]["trackedEntity"]["Row"];
+
+// -------------------------------------------------------------
+// assignEntitiesToIssueItem
+// -------------------------------------------------------------
+// Writes:
+// - nonConformanceItemTrackedEntity (delete moved links, re-insert against target)
+// - nonConformanceItem (decrement source qty, increment target qty)
+
+export async function assignEntitiesToIssueItem(args: {
+ nonConformanceItemId: string;
+ targetItemId: string;
+ assignments: { trackedEntityId: string; quantity: number }[];
+ companyId: string;
+ userId: string;
+}): Promise<Result<{ moved: number }>> {
+ const { nonConformanceItemId, targetItemId, assignments, companyId, userId } =
+ args;
+
+ if (assignments.length === 0) {
+ return errResult("No assignments provided");
+ }
+
+ // Same source and target would decrement then re-inflate the same row off a
+ // stale read, corrupting its quantity.
+ if (nonConformanceItemId === targetItemId) {
+ return errResult("Cannot move entities onto the same row");
+ }
+
+ const db = getDatabaseClient();
+ const nowIso = new Date().toISOString();
+ const entityIds = assignments.map((a) => a.trackedEntityId);
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const source = await trx
+ .selectFrom("nonConformanceItem")
+ .select(["id", "nonConformanceId", "quantity"])
+ .where("id", "=", nonConformanceItemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!source) throw new Error("Source item association not found");
+
+ const target = await trx
+ .selectFrom("nonConformanceItem")
+ .select(["id", "nonConformanceId", "quantity"])
+ .where("id", "=", targetItemId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!target) throw new Error("Target item association not found");
+
+ if (source.nonConformanceId !== target.nonConformanceId) {
+ 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"])
+ .where("nonConformanceItemId", "=", nonConformanceItemId)
+ .where("trackedEntityId", "in", entityIds)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ const existingQty = existingLinks.reduce(
+ (acc, l) => acc + Number(l.quantity ?? 0),
+ 0
+ );
+ const movingQty = assignments.reduce(
+ (acc, a) => acc + Number(a.quantity),
+ 0
+ );
+
+ await trx
+ .deleteFrom("nonConformanceItemTrackedEntity")
+ .where("nonConformanceItemId", "=", nonConformanceItemId)
+ .where("trackedEntityId", "in", entityIds)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ await trx
+ .insertInto("nonConformanceItemTrackedEntity")
+ .values(
+ assignments.map((a) => ({
+ nonConformanceItemId: targetItemId,
+ nonConformanceId: target.nonConformanceId,
+ trackedEntityId: a.trackedEntityId,
+ quantity: Number(a.quantity),
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+
+ await trx
+ .updateTable("nonConformanceItem")
+ .set({
+ quantity: Math.max(0, Number(source.quantity ?? 0) - existingQty),
+ updatedBy: userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", nonConformanceItemId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ await trx
+ .updateTable("nonConformanceItem")
+ .set({
+ quantity: Number(target.quantity ?? 0) + movingQty,
+ updatedBy: userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", targetItemId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ return { moved: assignments.length };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to move entities"
+ );
+ }
+}
+
+// -------------------------------------------------------------
+// splitIssueItem
+// -------------------------------------------------------------
+// Splits a disposition row into a new row so portions can get different
+// dispositions. Whole linked lots are re-pointed to the new row; a quantity
+// split that lands mid-lot subdivides the batch entity via subdivideBatchEntity.
+
+// Physically subdivides a batch tracked entity, mirroring the MES issue split:
+// creates a new lot for `moveQty` linked to `newRowId`, decrements the original
+// lot to `keepQty` (kept on its existing row), and writes split genealogy
+// (trackedActivity "Split" + inputs/outputs + net-zero "Batch Split" itemLedger,
+// which leaves on-hand unchanged).
+//
+// NOTE: the same lot-subdivision + genealogy also lives in the MES issue edge
+// function (packages/database/supabase/functions/issue/index.ts, case
+// "trackedEntitiesToOperation"). They can't share code across the app/Deno
+// boundary today — keep the two in sync if the genealogy shape changes.
+
+// The storage unit a tracked entity currently holds stock in, derived from its
+// item-ledger rows by net on-hand per bin. Batch-split ledger entries MUST be
+// booked against this bin (not NULL), or per-storage-unit on-hand views (picking,
+// available-tracked-entities) won't net to zero. Mirrors the MES helper
+// packages/database/supabase/functions/issue/resolve-tracked-entity-bin.ts —
+// keep the two in sync. Returns the bin with the highest positive net; falls
+// back to any bin the entity appears in when nothing nets positive.
+function resolveHoldingStorageUnit(
+ rows: { storageUnitId: string | null; quantity: number | string | null }[]
+): string | null {
+ const netByBin = new Map<string, number>();
+ for (const row of rows) {
+ if (!row.storageUnitId) continue;
+ netByBin.set(
+ row.storageUnitId,
+ (netByBin.get(row.storageUnitId) ?? 0) + Number(row.quantity ?? 0)
+ );
+ }
+ let bestBin: string | null = null;
+ let bestQty = 0;
+ for (const [bin, qty] of netByBin) {
+ if (qty > bestQty) {
+ bestQty = qty;
+ bestBin = bin;
+ }
+ }
+ if (bestBin) return bestBin;
+ return rows.find((row) => row.storageUnitId)?.storageUnitId ?? null;
+}
+
+async function subdivideBatchEntity(
+ trx: KyselyTx,
+ args: {
+ source: Pick<
+ TrackedEntityRow,
+ | "id"
+ | "readableId"
+ | "sourceDocumentId"
+ | "sourceDocumentReadableId"
+ | "status"
+ | "attributes"
+ | "itemId"
+ | "expirationDate"
+ >;
+ linkId: string;
+ newRowId: string;
+ nonConformanceId: string;
+ itemId: string;
+ readableNc: string;
+ locationId: string | null;
+ entityQty: number;
+ moveQty: number;
+ keepQty: number;
+ companyId: string;
+ userId: string;
+ nowIso: string;
+ }
+): Promise<void> {
+ const {
+ source,
+ linkId,
+ newRowId,
+ nonConformanceId,
+ itemId,
+ readableNc,
+ locationId,
+ entityQty,
+ moveQty,
+ keepQty,
+ companyId,
+ userId,
+ nowIso
+ } = args;
+
+ const newEntity = await trx
+ .insertInto("trackedEntity")
+ .values({
+ readableId: source.readableId,
+ sourceDocumentId: source.sourceDocumentId,
+ sourceDocument: "Item",
+ sourceDocumentReadableId: source.sourceDocumentReadableId,
+ quantity: moveQty,
+ status: source.status ?? "Available",
+ attributes: source.attributes,
+ itemId: source.itemId ?? source.sourceDocumentId,
+ expirationDate: source.expirationDate ?? null,
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ await trx
+ .updateTable("trackedEntity")
+ .set({
+ quantity: keepQty,
+ attributes: {
+ ...((source.attributes as Record<string, unknown>) ?? {}),
+ "Split Entity ID": newEntity.id
+ }
+ })
+ .where("id", "=", source.id)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ await trx
+ .updateTable("nonConformanceItemTrackedEntity")
+ .set({ quantity: keepQty, updatedBy: userId, updatedAt: nowIso })
+ .where("id", "=", linkId)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ await trx
+ .insertInto("nonConformanceItemTrackedEntity")
+ .values({
+ nonConformanceItemId: newRowId,
+ nonConformanceId,
+ trackedEntityId: newEntity.id,
+ quantity: moveQty,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+
+ const activity = await trx
+ .insertInto("trackedActivity")
+ .values({
+ type: "Split",
+ sourceDocument: "Non-Conformance",
+ sourceDocumentId: nonConformanceId,
+ sourceDocumentReadableId: readableNc,
+ attributes: {
+ "Non-Conformance": nonConformanceId,
+ "Original Quantity": entityQty,
+ "Split Quantity": moveQty,
+ "Remaining Quantity": keepQty,
+ "Split Entity ID": newEntity.id,
+ Employee: userId
+ },
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ await trx
+ .insertInto("trackedActivityInput")
+ .values({
+ trackedActivityId: activity.id,
+ trackedEntityId: source.id,
+ quantity: entityQty,
+ companyId,
+ createdBy: userId
+ })
+ .execute();
+
+ await trx
+ .insertInto("trackedActivityOutput")
+ .values([
+ {
+ trackedActivityId: activity.id,
+ trackedEntityId: source.id,
+ quantity: keepQty,
+ companyId,
+ createdBy: userId
+ },
+ {
+ trackedActivityId: activity.id,
+ trackedEntityId: newEntity.id,
+ quantity: moveQty,
+ companyId,
+ createdBy: userId
+ }
+ ])
+ .execute();
+
+ // The bin the source lot actually holds stock in — split ledger entries book
+ // against it so per-storage-unit on-hand stays consistent (see helper note).
+ const sourceLedgerRows = await trx
+ .selectFrom("itemLedger")
+ .select(["storageUnitId", "quantity"])
+ .where("trackedEntityId", "=", source.id)
+ .where("companyId", "=", companyId)
+ .execute();
+ const storageUnitId = resolveHoldingStorageUnit(sourceLedgerRows);
+
+ await trx
+ .insertInto("itemLedger")
+ .values([
+ {
+ itemId,
+ locationId,
+ storageUnitId,
+ entryType: "Negative Adjmt." as const,
+ documentType: "Batch Split" as const,
+ documentId: activity.id,
+ quantity: -entityQty,
+ trackedEntityId: source.id,
+ companyId,
+ createdBy: userId,
+ comment: `NC ${readableNc} batch split`
+ },
+ {
+ itemId,
+ locationId,
+ storageUnitId,
+ entryType: "Positive Adjmt." as const,
+ documentType: "Batch Split" as const,
+ documentId: activity.id,
+ quantity: keepQty,
+ trackedEntityId: source.id,
+ companyId,
+ createdBy: userId,
+ comment: `NC ${readableNc} batch split`
+ },
+ {
+ itemId,
+ locationId,
+ storageUnitId,
+ entryType: "Positive Adjmt." as const,
+ documentType: "Batch Split" as const,
+ documentId: activity.id,
+ quantity: moveQty,
+ trackedEntityId: newEntity.id,
+ companyId,
+ createdBy: userId,
+ comment: `NC ${readableNc} batch split`
+ }
+ ])
+ .execute();
+}
+
+export async function splitIssueItem(args: {
+ id: string;
+ companyId: string;
+ userId: string;
+ splitQuantity?: number;
+ entityAssignments?: { trackedEntityId: string; quantity: number }[];
+}): Promise<Result<{ id: string }>> {
+ const { id, companyId, userId, splitQuantity, entityAssignments } = args;
+ const db = getDatabaseClient();
+ const nowIso = new Date().toISOString();
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const item = await trx
+ .selectFrom("nonConformanceItem")
+ .select(["id", "nonConformanceId", "itemId", "quantity"])
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!item) throw new Error("Item association not found");
+
+ const issue = await trx
+ .selectFrom("nonConformance")
+ .select(["nonConformanceId", "status", "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;
+
+ // Each NCR link owns a full lot, so a link's quantity always equals its
+ // tracked entity's quantity — the greedy fill below relies on that.
+ const links = await trx
+ .selectFrom("nonConformanceItemTrackedEntity as link")
+ .innerJoin("trackedEntity as te", "te.id", "link.trackedEntityId")
+ .select([
+ "link.id as linkId",
+ "link.quantity as linkQuantity",
+ "te.id as entityId",
+ "te.quantity as entityQuantity",
+ "te.status as entityStatus",
+ "te.attributes as entityAttributes",
+ "te.readableId as entityReadableId",
+ "te.sourceDocumentId as entitySourceDocumentId",
+ "te.sourceDocumentReadableId as entitySourceDocumentReadableId",
+ "te.itemId as entityItemId",
+ "te.expirationDate as entityExpirationDate"
+ ])
+ .where("link.nonConformanceItemId", "=", id)
+ .where("link.companyId", "=", companyId)
+ .where("te.companyId", "=", companyId)
+ .orderBy("te.quantity", "asc")
+ .execute();
+
+ if (links.length === 0) throw new Error("No linked entities to split");
+
+ // entityAssignments are whole-lot picks from the multi-entity checkbox UI;
+ // splitQuantity fills greedily from the smallest lots, subdividing the
+ // last one if it overshoots.
+ type Move = { link: (typeof links)[number]; moveQty: number };
+ const moves: Move[] = [];
+
+ if (entityAssignments && entityAssignments.length > 0) {
+ // Whole-lot picks: trust only the server-side link, not the client's
+ // quantity, and reject unknown or duplicated entities.
+ const seen = new Set<string>();
+ for (const a of entityAssignments) {
+ if (seen.has(a.trackedEntityId)) {
+ throw new Error("Duplicate entity in split selection");
+ }
+ seen.add(a.trackedEntityId);
+ const link = links.find((l) => l.entityId === a.trackedEntityId);
+ if (!link) {
+ throw new Error("Selected entity is not linked to this row");
+ }
+ moves.push({ link, moveQty: Number(link.linkQuantity ?? 0) });
+ }
+ } else if (typeof splitQuantity === "number" && splitQuantity > 0) {
+ let remaining = splitQuantity;
+ for (const link of links) {
+ if (remaining <= 1e-6) break;
+ const q = Number(link.linkQuantity ?? 0);
+ if (q <= remaining + 1e-6) {
+ moves.push({ link, moveQty: q });
+ remaining -= q;
+ } else {
+ moves.push({ link, moveQty: remaining });
+ remaining = 0;
+ break;
+ }
+ }
+ if (remaining > 1e-6) {
+ throw new Error("Split quantity exceeds the linked entity quantity");
+ }
+ } else {
+ throw new Error("Missing split parameters");
+ }
+
+ const effectiveSplitQty = moves.reduce((acc, m) => acc + m.moveQty, 0);
+ const current = Number(item.quantity ?? 0);
+ if (effectiveSplitQty >= current) {
+ throw new Error(
+ `Split quantity (${effectiveSplitQty}) must be less than the current quantity (${current})`
+ );
+ }
+
+ // New disposition row that receives the split-off portion.
+ const newRow = await trx
+ .insertInto("nonConformanceItem")
+ .values({
+ nonConformanceId: item.nonConformanceId,
+ itemId: item.itemId,
+ quantity: effectiveSplitQty,
+ disposition: "Pending",
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ for (const { link, moveQty } of moves) {
+ const entityQty = Number(link.entityQuantity ?? 0);
+
+ if (moveQty >= entityQty - 1e-6) {
+ // Whole lot moving — re-point the link, no physical change.
+ await trx
+ .updateTable("nonConformanceItemTrackedEntity")
+ .set({
+ nonConformanceItemId: newRow.id,
+ updatedBy: userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", link.linkId)
+ .where("companyId", "=", companyId)
+ .execute();
+ continue;
+ }
+
+ await subdivideBatchEntity(trx, {
+ source: {
+ id: link.entityId,
+ readableId: link.entityReadableId,
+ sourceDocumentId: link.entitySourceDocumentId,
+ sourceDocumentReadableId: link.entitySourceDocumentReadableId,
+ status: link.entityStatus,
+ attributes: link.entityAttributes,
+ itemId: link.entityItemId,
+ expirationDate: link.entityExpirationDate
+ },
+ linkId: link.linkId,
+ newRowId: newRow.id,
+ nonConformanceId: item.nonConformanceId,
+ itemId: item.itemId,
+ readableNc,
+ locationId,
+ entityQty,
+ moveQty,
+ keepQty: entityQty - moveQty,
+ companyId,
+ userId,
+ nowIso
+ });
+ }
+
+ // Shrink the original row by whatever moved out.
+ await trx
+ .updateTable("nonConformanceItem")
+ .set({
+ quantity: current - effectiveSplitQty,
+ updatedBy: userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .execute();
+
+ return { id: newRow.id };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to split line"
+ );
+ }
+}
+
+// -------------------------------------------------------------
+// closeIssue
+// -------------------------------------------------------------
+// Validates disposition plan (qty sums, no Pending rows, no Consumed entities),
+// then for each row with linked entities:
+// - insert trackedActivity + trackedActivityInput
+// - flip trackedEntity status (Use As Is / Rework → Available;
+// Scrap / Return to Supplier → Rejected and write a Negative Adjmt. ledger)
+// Finally sets nonConformance.status = Closed.
+
+type DispositionLink = {
+ id: string;
+ trackedEntityId: string;
+ quantity: number;
+ trackedEntityStatus: string | null;
+};
+
+type DispositionRow = {
+ id: string;
+ itemId: string;
+ disposition: string | null;
+ quantity: number;
+ links: DispositionLink[];
+};
+
+type IssueClosureBlocker = { nonConformanceItemId: string; reason: string };
+
+export async function closeIssue(
+ client: SupabaseClient<Database>,
+ args: { nonConformanceId: string; companyId: string; userId: string }
+): Promise<Result<{ id: string }>> {
+ const { nonConformanceId, companyId, userId } = args;
+ const db = getDatabaseClient();
+
+ // Preflight reads via Supabase (uses nested selects / RLS-aware service role)
+ const planResult = await (client as any)
+ .from("nonConformanceItem")
+ .select(
+ `
+ id,
+ itemId,
+ disposition,
+ quantity,
+ links:nonConformanceItemTrackedEntity(
+ id,
+ quantity,
+ trackedEntityId,
+ trackedEntity(
+ id,
+ status
+ )
+ )
+ `
+ )
+ .eq("nonConformanceId", nonConformanceId)
+ .eq("companyId", companyId)
+ .order("createdAt", { ascending: true });
+
+ if (planResult.error || !planResult.data) {
+ return errResult("Failed to load disposition plan");
+ }
+
+ const plan: DispositionRow[] = (planResult.data as any[]).map((row) => ({
+ id: row.id,
+ itemId: row.itemId,
+ disposition: row.disposition,
+ quantity: Number(row.quantity ?? 0),
+ links: (row.links ?? []).map((link: any) => ({
+ id: link.id,
+ trackedEntityId: link.trackedEntityId,
+ quantity: Number(link.quantity ?? 0),
+ trackedEntityStatus: link.trackedEntity?.status ?? null
+ }))
+ }));
+
+ const blockers: IssueClosureBlocker[] = [];
+ for (const row of plan) {
+ if (row.links.length === 0) continue;
+ if (!row.disposition || row.disposition === "Pending") {
+ blockers.push({
+ nonConformanceItemId: row.id,
+ reason: "Disposition is still Pending"
+ });
+ continue;
+ }
+ const sum = row.links.reduce((acc, l) => acc + l.quantity, 0);
+ if (Math.abs(sum - row.quantity) > 1e-6) {
+ blockers.push({
+ nonConformanceItemId: row.id,
+ reason: `Linked entity quantity (${sum}) does not match row quantity (${row.quantity})`
+ });
+ }
+ for (const link of row.links) {
+ if (!link.trackedEntityStatus) {
+ blockers.push({
+ nonConformanceItemId: row.id,
+ reason: "Linked tracked entity is missing"
+ });
+ } else if (link.trackedEntityStatus === "Consumed") {
+ blockers.push({
+ nonConformanceItemId: row.id,
+ reason: `Tracked entity ${link.trackedEntityId} is already Consumed`
+ });
+ }
+ }
+ }
+
+ if (blockers.length > 0) {
+ return errResult(
+ `Cannot close: ${blockers.map((b) => b.reason).join("; ")}`,
+ blockers
+ );
+ }
+
+ try {
+ const result = await db.transaction().execute(async (trx) => {
+ const issue = await trx
+ .selectFrom("nonConformance")
+ .select(["id", "nonConformanceId", "status", "locationId"])
+ .where("id", "=", nonConformanceId)
+ .where("companyId", "=", companyId)
+ .executeTakeFirst();
+ if (!issue) throw new Error("Issue not found");
+ if (issue.status === "Closed") return { id: issue.id };
+
+ const nowIso = new Date().toISOString();
+ const today = nowIso.slice(0, 10);
+ const readableNc = issue.nonConformanceId ?? nonConformanceId;
+ const locationId = issue.locationId;
+
+ // The preflight plan above was read outside this transaction and can be
+ // stale (a concurrent split/move changes rows and link quantities). Re-read
+ // the plan under a row lock and re-validate the correctness-critical
+ // invariants before posting, so a race rolls back instead of posting a
+ // ledger off stale quantities. `forUpdate` on the item rows serializes
+ // against split/move, which update the same rows.
+ const itemRows = await trx
+ .selectFrom("nonConformanceItem")
+ .select(["id", "itemId", "disposition", "quantity"])
+ .where("nonConformanceId", "=", nonConformanceId)
+ .where("companyId", "=", companyId)
+ .orderBy("createdAt", "asc")
+ .forUpdate()
+ .execute();
+
+ const linkRows = await trx
+ .selectFrom("nonConformanceItemTrackedEntity as link")
+ .innerJoin("trackedEntity as te", (join) =>
+ join
+ .onRef("te.id", "=", "link.trackedEntityId")
+ .onRef("te.companyId", "=", "link.companyId")
+ )
+ .select([
+ "link.nonConformanceItemId as nonConformanceItemId",
+ "link.id as id",
+ "link.trackedEntityId as trackedEntityId",
+ "link.quantity as quantity",
+ "te.status as trackedEntityStatus"
+ ])
+ .where("link.nonConformanceId", "=", nonConformanceId)
+ .where("link.companyId", "=", companyId)
+ .execute();
+
+ const linksByItem = new Map<string, DispositionLink[]>();
+ for (const link of linkRows) {
+ const arr = linksByItem.get(link.nonConformanceItemId) ?? [];
+ arr.push({
+ id: link.id,
+ trackedEntityId: link.trackedEntityId,
+ quantity: Number(link.quantity ?? 0),
+ trackedEntityStatus: link.trackedEntityStatus ?? null
+ });
+ linksByItem.set(link.nonConformanceItemId, arr);
+ }
+
+ const freshPlan: DispositionRow[] = itemRows.map((row) => ({
+ id: row.id,
+ itemId: row.itemId,
+ disposition: row.disposition,
+ quantity: Number(row.quantity ?? 0),
+ links: linksByItem.get(row.id) ?? []
+ }));
+
+ for (const row of freshPlan) {
+ if (row.links.length === 0) continue;
+ if (!row.disposition || row.disposition === "Pending") {
+ throw new Error("Disposition changed while closing; please retry.");
+ }
+ const sum = row.links.reduce((acc, l) => acc + l.quantity, 0);
+ if (Math.abs(sum - row.quantity) > 1e-6) {
+ throw new Error("Quantities changed while closing; please retry.");
+ }
+ for (const link of row.links) {
+ if (
+ !link.trackedEntityStatus ||
+ link.trackedEntityStatus === "Consumed"
+ ) {
+ throw new Error(
+ "A tracked entity changed while closing; please retry."
+ );
+ }
+ }
+ }
+
+ for (const row of freshPlan) {
+ if (row.links.length === 0) continue;
+
+ const activity = await trx
+ .insertInto("trackedActivity")
+ .values({
+ type: "Disposition",
+ sourceDocument: "Non-Conformance",
+ sourceDocumentId: nonConformanceId,
+ sourceDocumentReadableId: readableNc,
+ attributes: {
+ "Non-Conformance": nonConformanceId,
+ Disposition: row.disposition ?? "",
+ Employee: userId
+ },
+ companyId,
+ createdBy: userId
+ })
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ await trx
+ .insertInto("trackedActivityInput")
+ .values(
+ row.links.map((link) => ({
+ trackedActivityId: activity.id,
+ trackedEntityId: link.trackedEntityId,
+ quantity: link.quantity,
+ companyId,
+ createdBy: userId
+ }))
+ )
+ .execute();
+
+ if (row.disposition === "Use As Is" || row.disposition === "Rework") {
+ const idsToFlip = row.links
+ .filter((l) => l.trackedEntityStatus !== "Available")
+ .map((l) => l.trackedEntityId);
+ if (idsToFlip.length > 0) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ status: "Available" })
+ .where("id", "in", idsToFlip)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ continue;
+ }
+
+ if (
+ row.disposition === "Scrap" ||
+ row.disposition === "Return to Supplier"
+ ) {
+ const commentSuffix =
+ row.disposition === "Scrap" ? "scrap" : "return to supplier";
+
+ await trx
+ .insertInto("itemLedger")
+ .values(
+ row.links.map((link) => ({
+ itemId: row.itemId,
+ locationId,
+ entryType: "Negative Adjmt." as const,
+ documentType: "Non-Conformance" as const,
+ documentId: nonConformanceId,
+ quantity: -link.quantity,
+ trackedEntityId: link.trackedEntityId,
+ companyId,
+ createdBy: userId,
+ comment: `NC ${readableNc} ${commentSuffix}`
+ }))
+ )
+ .execute();
+
+ const idsToFlip = row.links
+ .filter((l) => l.trackedEntityStatus !== "Rejected")
+ .map((l) => l.trackedEntityId);
+ if (idsToFlip.length > 0) {
+ await trx
+ .updateTable("trackedEntity")
+ .set({ status: "Rejected" })
+ .where("id", "in", idsToFlip)
+ .where("companyId", "=", companyId)
+ .execute();
+ }
+ }
+ }
+
+ const updated = await trx
+ .updateTable("nonConformance")
+ .set({
+ status: "Closed",
+ closeDate: today,
+ updatedBy: userId,
+ updatedAt: nowIso
+ })
+ .where("id", "=", nonConformanceId)
+ .where("companyId", "=", companyId)
+ .returning(["id"])
+ .executeTakeFirstOrThrow();
+
+ return { id: updated.id };
+ });
+
+ return { data: result, error: null };
+ } catch (err) {
+ return errResult(
+ err instanceof Error ? err.message : "Failed to close NCR"
+ );
+ }
+}
diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.ts
index fecafc9dfc..90c1b1c3f2 100644
--- a/apps/erp/app/modules/quality/quality.models.ts
+++ b/apps/erp/app/modules/quality/quality.models.ts
@@ -526,10 +526,6 @@ export const issueWorkflowValidator = z.object({
.optional()
});
-export const itemQuantityValidator = z.object({
- quantity: zfd.numeric(z.number().min(0))
-});
-
const entityAssignmentItem = z.object({
trackedEntityId: z.string().min(1, { message: "Tracked entity is required" }),
quantity: z
diff --git a/apps/erp/app/modules/quality/quality.server.ts b/apps/erp/app/modules/quality/quality.server.ts
index f7f1e8b9cd..1bd74d9c57 100644
--- a/apps/erp/app/modules/quality/quality.server.ts
+++ b/apps/erp/app/modules/quality/quality.server.ts
@@ -1,5 +1,3 @@
-import type { Database } from "@carbon/database";
-import type { SupabaseClient } from "@supabase/supabase-js";
import { sql } from "kysely";
import type { z } from "zod";
@@ -11,9 +9,9 @@ import type {
type Ok<T> = { data: T; error: null };
type Err = { data: null; error: { message: string; blockers?: unknown } };
-type Result<T> = Ok<T> | Err;
+export type Result<T> = Ok<T> | Err;
-function errResult(message: string, blockers?: unknown): Err {
+export function errResult(message: string, blockers?: unknown): Err {
return { data: null, error: { message, ...(blockers ? { blockers } : {}) } };
}
@@ -376,363 +374,3 @@ export async function dispositionInboundInspection(
);
}
}
-
-// -------------------------------------------------------------
-// 3. assignEntitiesToIssueItem
-// -------------------------------------------------------------
-// Writes:
-// - nonConformanceItemTrackedEntity (delete moved links, re-insert against target)
-// - nonConformanceItem (decrement source qty, increment target qty)
-
-export async function assignEntitiesToIssueItem(args: {
- nonConformanceItemId: string;
- targetItemId: string;
- assignments: { trackedEntityId: string; quantity: number }[];
- companyId: string;
- userId: string;
-}): Promise<Result<{ moved: number }>> {
- const { nonConformanceItemId, targetItemId, assignments, companyId, userId } =
- args;
-
- if (assignments.length === 0) {
- return errResult("No assignments provided");
- }
-
- const db = getDatabaseClient();
- const nowIso = new Date().toISOString();
- const entityIds = assignments.map((a) => a.trackedEntityId);
-
- try {
- const result = await db.transaction().execute(async (trx) => {
- const source = await trx
- .selectFrom("nonConformanceItem")
- .select(["id", "nonConformanceId", "quantity"])
- .where("id", "=", nonConformanceItemId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (!source) throw new Error("Source item association not found");
-
- const target = await trx
- .selectFrom("nonConformanceItem")
- .select(["id", "nonConformanceId", "quantity"])
- .where("id", "=", targetItemId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (!target) throw new Error("Target item association not found");
-
- if (source.nonConformanceId !== target.nonConformanceId) {
- throw new Error("Cannot move entities between different NCRs");
- }
-
- const existingLinks = await trx
- .selectFrom("nonConformanceItemTrackedEntity")
- .select(["quantity"])
- .where("nonConformanceItemId", "=", nonConformanceItemId)
- .where("trackedEntityId", "in", entityIds)
- .where("companyId", "=", companyId)
- .execute();
-
- const existingQty = existingLinks.reduce(
- (acc, l) => acc + Number(l.quantity ?? 0),
- 0
- );
- const movingQty = assignments.reduce(
- (acc, a) => acc + Number(a.quantity),
- 0
- );
-
- await trx
- .deleteFrom("nonConformanceItemTrackedEntity")
- .where("nonConformanceItemId", "=", nonConformanceItemId)
- .where("trackedEntityId", "in", entityIds)
- .where("companyId", "=", companyId)
- .execute();
-
- await trx
- .insertInto("nonConformanceItemTrackedEntity")
- .values(
- assignments.map((a) => ({
- nonConformanceItemId: targetItemId,
- nonConformanceId: target.nonConformanceId,
- trackedEntityId: a.trackedEntityId,
- quantity: Number(a.quantity),
- companyId,
- createdBy: userId
- }))
- )
- .execute();
-
- await trx
- .updateTable("nonConformanceItem")
- .set({
- quantity: Math.max(0, Number(source.quantity ?? 0) - existingQty),
- updatedBy: userId,
- updatedAt: nowIso
- })
- .where("id", "=", nonConformanceItemId)
- .where("companyId", "=", companyId)
- .execute();
-
- await trx
- .updateTable("nonConformanceItem")
- .set({
- quantity: Number(target.quantity ?? 0) + movingQty,
- updatedBy: userId,
- updatedAt: nowIso
- })
- .where("id", "=", targetItemId)
- .where("companyId", "=", companyId)
- .execute();
-
- return { moved: assignments.length };
- });
-
- return { data: result, error: null };
- } catch (err) {
- return errResult(
- err instanceof Error ? err.message : "Failed to move entities"
- );
- }
-}
-
-// -------------------------------------------------------------
-// 4. closeIssue
-// -------------------------------------------------------------
-// Validates disposition plan (qty sums, no Pending rows, no Consumed entities),
-// then for each row with linked entities:
-// - insert trackedActivity + trackedActivityInput
-// - flip trackedEntity status (Use As Is / Rework → Available;
-// Scrap / Return to Supplier → Rejected and write a Negative Adjmt. ledger)
-// Finally sets nonConformance.status = Closed.
-
-type DispositionLink = {
- id: string;
- trackedEntityId: string;
- quantity: number;
- trackedEntityStatus: string | null;
-};
-
-type DispositionRow = {
- id: string;
- itemId: string;
- disposition: string | null;
- quantity: number;
- links: DispositionLink[];
-};
-
-type IssueClosureBlocker = { nonConformanceItemId: string; reason: string };
-
-export async function closeIssue(
- client: SupabaseClient<Database>,
- args: { nonConformanceId: string; companyId: string; userId: string }
-): Promise<Result<{ id: string }>> {
- const { nonConformanceId, companyId, userId } = args;
- const db = getDatabaseClient();
-
- // Preflight reads via Supabase (uses nested selects / RLS-aware service role)
- const planResult = await (client as any)
- .from("nonConformanceItem")
- .select(
- `
- id,
- itemId,
- disposition,
- quantity,
- links:nonConformanceItemTrackedEntity(
- id,
- quantity,
- trackedEntityId,
- trackedEntity(
- id,
- status
- )
- )
- `
- )
- .eq("nonConformanceId", nonConformanceId)
- .eq("companyId", companyId)
- .order("createdAt", { ascending: true });
-
- if (planResult.error || !planResult.data) {
- return errResult("Failed to load disposition plan");
- }
-
- const plan: DispositionRow[] = (planResult.data as any[]).map((row) => ({
- id: row.id,
- itemId: row.itemId,
- disposition: row.disposition,
- quantity: Number(row.quantity ?? 0),
- links: (row.links ?? []).map((link: any) => ({
- id: link.id,
- trackedEntityId: link.trackedEntityId,
- quantity: Number(link.quantity ?? 0),
- trackedEntityStatus: link.trackedEntity?.status ?? null
- }))
- }));
-
- const blockers: IssueClosureBlocker[] = [];
- for (const row of plan) {
- if (row.links.length === 0) continue;
- if (!row.disposition || row.disposition === "Pending") {
- blockers.push({
- nonConformanceItemId: row.id,
- reason: "Disposition is still Pending"
- });
- continue;
- }
- const sum = row.links.reduce((acc, l) => acc + l.quantity, 0);
- if (Math.abs(sum - row.quantity) > 1e-6) {
- blockers.push({
- nonConformanceItemId: row.id,
- reason: `Linked entity quantity (${sum}) does not match row quantity (${row.quantity})`
- });
- }
- for (const link of row.links) {
- if (!link.trackedEntityStatus) {
- blockers.push({
- nonConformanceItemId: row.id,
- reason: "Linked tracked entity is missing"
- });
- } else if (link.trackedEntityStatus === "Consumed") {
- blockers.push({
- nonConformanceItemId: row.id,
- reason: `Tracked entity ${link.trackedEntityId} is already Consumed`
- });
- }
- }
- }
-
- if (blockers.length > 0) {
- return errResult(
- `Cannot close: ${blockers.map((b) => b.reason).join("; ")}`,
- blockers
- );
- }
-
- try {
- const result = await db.transaction().execute(async (trx) => {
- const issue = await trx
- .selectFrom("nonConformance")
- .select(["id", "nonConformanceId", "status", "locationId"])
- .where("id", "=", nonConformanceId)
- .where("companyId", "=", companyId)
- .executeTakeFirst();
- if (!issue) throw new Error("Issue not found");
- if (issue.status === "Closed") return { id: issue.id };
-
- const nowIso = new Date().toISOString();
- const today = nowIso.slice(0, 10);
- const readableNc = issue.nonConformanceId ?? nonConformanceId;
- const locationId = issue.locationId;
-
- for (const row of plan) {
- if (row.links.length === 0) continue;
-
- const activity = await trx
- .insertInto("trackedActivity")
- .values({
- type: "Disposition",
- sourceDocument: "Non-Conformance",
- sourceDocumentId: nonConformanceId,
- sourceDocumentReadableId: readableNc,
- attributes: {
- "Non-Conformance": nonConformanceId,
- Disposition: row.disposition ?? "",
- Employee: userId
- },
- companyId,
- createdBy: userId
- })
- .returning(["id"])
- .executeTakeFirstOrThrow();
-
- await trx
- .insertInto("trackedActivityInput")
- .values(
- row.links.map((link) => ({
- trackedActivityId: activity.id,
- trackedEntityId: link.trackedEntityId,
- quantity: link.quantity,
- companyId,
- createdBy: userId
- }))
- )
- .execute();
-
- if (row.disposition === "Use As Is" || row.disposition === "Rework") {
- const idsToFlip = row.links
- .filter((l) => l.trackedEntityStatus !== "Available")
- .map((l) => l.trackedEntityId);
- if (idsToFlip.length > 0) {
- await trx
- .updateTable("trackedEntity")
- .set({ status: "Available" })
- .where("id", "in", idsToFlip)
- .where("companyId", "=", companyId)
- .execute();
- }
- continue;
- }
-
- if (
- row.disposition === "Scrap" ||
- row.disposition === "Return to Supplier"
- ) {
- const commentSuffix =
- row.disposition === "Scrap" ? "scrap" : "return to supplier";
-
- await trx
- .insertInto("itemLedger")
- .values(
- row.links.map((link) => ({
- itemId: row.itemId,
- locationId,
- entryType: "Negative Adjmt." as const,
- documentType: "Non-Conformance" as const,
- documentId: nonConformanceId,
- quantity: -link.quantity,
- trackedEntityId: link.trackedEntityId,
- companyId,
- createdBy: userId,
- comment: `NC ${readableNc} ${commentSuffix}`
- }))
- )
- .execute();
-
- const idsToFlip = row.links
- .filter((l) => l.trackedEntityStatus !== "Rejected")
- .map((l) => l.trackedEntityId);
- if (idsToFlip.length > 0) {
- await trx
- .updateTable("trackedEntity")
- .set({ status: "Rejected" })
- .where("id", "in", idsToFlip)
- .where("companyId", "=", companyId)
- .execute();
- }
- }
- }
-
- const updated = await trx
- .updateTable("nonConformance")
- .set({
- status: "Closed",
- closeDate: today,
- updatedBy: userId,
- updatedAt: nowIso
- })
- .where("id", "=", nonConformanceId)
- .where("companyId", "=", companyId)
- .returning(["id"])
- .executeTakeFirstOrThrow();
-
- return { id: updated.id };
- });
-
- return { data: result, error: null };
- } catch (err) {
- return errResult(
- err instanceof Error ? err.message : "Failed to close NCR"
- );
- }
-}
diff --git a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
index 7efc76ea0f..268f37bf53 100644
--- a/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/AssociatedItemsList.tsx
@@ -51,7 +51,6 @@ import { path } from "~/utils/path";
import {
assignIssueItemEntitiesValidator,
disposition,
- itemQuantityValidator,
splitIssueItemValidator
} from "../../quality.models";
import type { IssueAssociationNode } from "../../types";
@@ -167,21 +166,6 @@ export function AssociatedItemsList({
[fetcher]
);
- const onUpdateQuantity = useCallback(
- (nonConformanceItemId: string, quantityValue: number | null) => {
- const formData = new FormData();
- formData.append("id", nonConformanceItemId);
- formData.append("field", "quantity");
- formData.append("value", quantityValue?.toString() ?? "0");
-
- fetcher.submit(formData, {
- method: "post",
- action: path.to.updateIssueItem
- });
- },
- [fetcher]
- );
-
const onMoveEntity = useCallback(
(
sourceRowId: string,
@@ -283,6 +267,12 @@ export function AssociatedItemsList({
disposition: (s.disposition ?? "Pending") as string,
itemReadableId: item.readableIdWithRevision
}));
+ // Split breaks a portion of the row onto a new disposition row.
+ // A single batch lot is subdivided server-side (a new tracked
+ // entity is created for the split-off quantity), so any row with
+ // quantity > 1 is splittable, even when it's one indivisible lot.
+ const canSplit = r.quantity > 1;
+ const hasRowActions = canSplit || siblings.length > 0;
const isDropTarget =
canEdit &&
sameItemSiblings.length > 0 &&
@@ -335,7 +325,7 @@ export function AssociatedItemsList({
}
}}
>
- <div className="flex items-center w-full gap-4">
+ <div className="flex items-start w-full gap-4">
<div className="flex flex-col min-w-0 flex-1">
<h3 className="font-semibold truncate">
{item.readableIdWithRevision}
@@ -344,27 +334,14 @@ export function AssociatedItemsList({
{item.name}
</p>
</div>
- <ValidatedForm
- key={`${r.child.id}-${r.quantity}`}
- defaultValues={{
- quantity: r.quantity
- }}
- validator={itemQuantityValidator}
- className="w-24 shrink-0"
- >
- <NumberInput
- label={t`Quantity`}
- name="quantity"
- isReadOnly={!canEdit || r.links.length > 0}
- minValue={0}
- size="sm"
- onBlur={(e) => {
- const target = e.target as HTMLInputElement;
- const numValue = parseFloat(target.value) || 0;
- onUpdateQuantity(r.child.id, numValue);
- }}
- />
- </ValidatedForm>
+ <div className="w-20 shrink-0 flex flex-col gap-1">
+ <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>
+ </div>
<ValidatedForm
defaultValues={{
disposition: r.disposition ?? "Pending"
@@ -372,7 +349,7 @@ export function AssociatedItemsList({
validator={z.object({
disposition: z.string()
})}
- className="w-[120px] shrink-0 items-center"
+ className="w-[150px] shrink-0 items-center"
>
<Select
options={disposition.map((d) => ({
@@ -384,7 +361,7 @@ export function AssociatedItemsList({
name="disposition"
inline={(value) => {
return (
- <div className="h-8 flex items-center">
+ <div className="h-8 flex items-center min-w-0 max-w-full">
<DispositionStatus disposition={value} />
</div>
);
@@ -396,8 +373,8 @@ export function AssociatedItemsList({
}}
/>
</ValidatedForm>
- <div className="w-10 shrink-0 flex items-end justify-end">
- {canEdit && r.links.length > 0 && (
+ <div className="w-10 shrink-0 flex items-start justify-end">
+ {canEdit && r.links.length > 0 && hasRowActions && (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<IconButton
@@ -408,7 +385,7 @@ export function AssociatedItemsList({
/>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
- {r.quantity > 1 && (
+ {canSplit && (
<DropdownMenuItem
onClick={() =>
setSplitTarget({
@@ -532,6 +509,7 @@ function SplitLineModal({
const hasMultipleEntities = target.links.length > 1;
const [selected, setSelected] = useState<Record<string, boolean>>({});
+ const [splitQty, setSplitQty] = useState(1);
const selectedAssignments = target.links
.filter((l) => selected[l.trackedEntityId])
@@ -544,11 +522,15 @@ function SplitLineModal({
(acc, a) => acc + a.quantity,
0
);
+ // The split-off portion must leave something on the original row, so it has
+ // to be a whole positive quantity strictly less than the current quantity.
+ const splitQtyValid =
+ Number.isFinite(splitQty) && splitQty >= 1 && splitQty < target.maxQuantity;
const canSubmit = hasMultipleEntities
? selectedAssignments.length > 0 &&
selectedSum > 0 &&
selectedSum < target.maxQuantity
- : true;
+ : splitQtyValid;
return (
<Modal
@@ -581,16 +563,16 @@ function SplitLineModal({
}}
>
<ModalBody>
+ <Hidden name="id" />
+ <Hidden name="itemId" />
+ <input
+ type="hidden"
+ name="entityAssignments"
+ value={
+ hasMultipleEntities ? JSON.stringify(selectedAssignments) : ""
+ }
+ />
<div className="flex flex-col gap-4 w-full">
- <Hidden name="id" />
- <Hidden name="itemId" />
- <input
- type="hidden"
- name="entityAssignments"
- value={
- hasMultipleEntities ? JSON.stringify(selectedAssignments) : ""
- }
- />
<Input
name="currentQuantity"
label={t`Current quantity`}
@@ -639,9 +621,17 @@ function SplitLineModal({
label={t`Split off quantity`}
minValue={1}
maxValue={target.maxQuantity - 1}
+ onChange={setSplitQty}
helperText={t`Remaining after split stays on the original row.`}
/>
)}
+ {!hasMultipleEntities && !splitQtyValid && (
+ <p className="text-xs text-destructive-foreground">
+ <Trans>
+ Enter a quantity between 1 and {target.maxQuantity - 1}.
+ </Trans>
+ </p>
+ )}
</div>
</ModalBody>
<ModalFooter>
diff --git a/apps/erp/app/modules/quality/ui/Issue/DispositionStatus.tsx b/apps/erp/app/modules/quality/ui/Issue/DispositionStatus.tsx
index d97ada9792..58508530d4 100644
--- a/apps/erp/app/modules/quality/ui/Issue/DispositionStatus.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/DispositionStatus.tsx
@@ -1,30 +1,36 @@
-import { Status } from "@carbon/react";
+import { cn, Status } from "@carbon/react";
+import type { ComponentProps } from "react";
-export function DispositionStatus({ disposition }: { disposition: string }) {
- switch (disposition) {
- case "Conditional Acceptance":
- return <Status color="blue">Conditional Acceptance</Status>;
- case "Deviation Accepted":
- return <Status color="green">Deviation Accepted</Status>;
- case "Hold":
- return <Status color="yellow">Hold</Status>;
- case "No Action Required":
- return <Status color="blue">No Action Required</Status>;
- case "Pending":
- return <Status color="orange">Pending</Status>;
- case "Quarantine":
- return <Status color="red">Quarantine</Status>;
- case "Repair":
- return <Status color="yellow">Repair</Status>;
- case "Return to Supplier":
- return <Status color="red">Return to Supplier</Status>;
- case "Rework":
- return <Status color="yellow">Rework</Status>;
- case "Scrap":
- return <Status color="red">Scrap</Status>;
- case "Use As Is":
- return <Status color="green">Use As Is</Status>;
- default:
- return <Status color="gray">{disposition}</Status>;
- }
+type StatusColor = ComponentProps<typeof Status>["color"];
+
+const dispositionColors: Record<string, StatusColor> = {
+ "Conditional Acceptance": "blue",
+ "Deviation Accepted": "green",
+ Hold: "yellow",
+ "No Action Required": "blue",
+ Pending: "orange",
+ Quarantine: "red",
+ Repair: "yellow",
+ "Return to Supplier": "red",
+ Rework: "yellow",
+ Scrap: "red",
+ "Use As Is": "green"
+};
+
+export function DispositionStatus({
+ disposition,
+ className
+}: {
+ disposition: string;
+ className?: string;
+}) {
+ const color = dispositionColors[disposition] ?? "gray";
+ return (
+ <Status
+ color={color}
+ className={cn("max-w-full [&>svg]:shrink-0", className)}
+ >
+ <span className="min-w-0 truncate">{disposition}</span>
+ </Status>
+ );
}
diff --git a/apps/erp/app/routes/x+/issue+/$id.close.tsx b/apps/erp/app/routes/x+/issue+/$id.close.tsx
index 910d8097c8..51502490a0 100644
--- a/apps/erp/app/routes/x+/issue+/$id.close.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.close.tsx
@@ -6,7 +6,7 @@ import { notifyIssueStatusChanged } from "@carbon/ee/notifications";
import { getLogger } from "@carbon/logger";
import type { ActionFunctionArgs } from "react-router";
import { redirect } from "react-router";
-import { closeIssue } from "~/modules/quality/quality.server";
+import { closeIssue } from "~/modules/quality/quality-disposition.server";
import { getCompanyIntegrations } from "~/modules/settings/settings.server";
import { path, requestReferrer } from "~/utils/path";
diff --git a/apps/erp/app/routes/x+/issue+/item+/assign-entities.tsx b/apps/erp/app/routes/x+/issue+/item+/assign-entities.tsx
index 0087c14517..a450e76f5b 100644
--- a/apps/erp/app/routes/x+/issue+/item+/assign-entities.tsx
+++ b/apps/erp/app/routes/x+/issue+/item+/assign-entities.tsx
@@ -8,7 +8,7 @@ import {
assignIssueItemEntitiesValidator,
isIssueLocked
} from "~/modules/quality";
-import { assignEntitiesToIssueItem } from "~/modules/quality/quality.server";
+import { assignEntitiesToIssueItem } from "~/modules/quality/quality-disposition.server";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
diff --git a/apps/erp/app/routes/x+/issue+/item+/split.tsx b/apps/erp/app/routes/x+/issue+/item+/split.tsx
index d2b4300db1..e41c876c97 100644
--- a/apps/erp/app/routes/x+/issue+/item+/split.tsx
+++ b/apps/erp/app/routes/x+/issue+/item+/split.tsx
@@ -5,6 +5,7 @@ import { validationError, validator } from "@carbon/form";
import type { ActionFunctionArgs } from "react-router";
import { data } from "react-router";
import { isIssueLocked, splitIssueItemValidator } from "~/modules/quality";
+import { splitIssueItem } from "~/modules/quality/quality-disposition.server";
import { requireUnlockedBulk } from "~/utils/lockedGuard.server";
export async function action({ request }: ActionFunctionArgs) {
@@ -23,7 +24,7 @@ export async function action({ request }: ActionFunctionArgs) {
const existing = await client
.from("nonConformanceItem")
- .select("*, nonConformance(status)")
+ .select("nonConformance(status)")
.eq("id", id)
.eq("companyId", companyId)
.single();
@@ -42,138 +43,18 @@ export async function action({ request }: ActionFunctionArgs) {
});
if (lockedError) return lockedError;
- const current = Number(existing.data.quantity ?? 0);
- const nowIso = new Date().toISOString();
-
- let effectiveSplitQty: number;
- let entitiesToMove: { trackedEntityId: string; quantity: number }[] = [];
-
- if (entityAssignments && entityAssignments.length > 0) {
- effectiveSplitQty = entityAssignments.reduce(
- (acc, a) => acc + Number(a.quantity),
- 0
- );
- entitiesToMove = entityAssignments;
- } else if (typeof splitQuantity === "number" && splitQuantity > 0) {
- const links = await (client as any)
- .from("nonConformanceItemTrackedEntity")
- .select("trackedEntityId, quantity")
- .eq("nonConformanceItemId", id)
- .eq("companyId", companyId)
- .order("quantity", { ascending: true });
- if (links.error) {
- return data(
- { error: links.error },
- await flash(request, error(links.error, "Failed to load entity links"))
- );
- }
-
- let remaining = splitQuantity;
- for (const link of (links.data ?? []) as any[]) {
- const qty = Number(link.quantity ?? 0);
- if (qty <= remaining + 1e-6) {
- entitiesToMove.push({
- trackedEntityId: link.trackedEntityId,
- quantity: qty
- });
- remaining -= qty;
- if (remaining <= 1e-6) break;
- }
- }
-
- if (Math.abs(remaining) > 1e-6) {
- return data(
- {
- error: {
- message:
- "Cannot split by quantity alone — mixed batch sizes require explicit entity selection"
- }
- },
- await flash(
- request,
- error(null, "Use the entity picker to split this row")
- )
- );
- }
-
- effectiveSplitQty = splitQuantity;
- } else {
- return data(
- { error: { message: "Missing split parameters" } },
- await flash(request, error(null, "Invalid split request"))
- );
- }
-
- if (effectiveSplitQty >= current) {
- return data(
- {
- error: {
- message: `Split quantity (${effectiveSplitQty}) must be less than the current quantity (${current})`
- }
- },
- await flash(request, error(null, "Split quantity too large"))
- );
- }
-
- const insert = await client
- .from("nonConformanceItem")
- .insert({
- nonConformanceId: existing.data.nonConformanceId,
- itemId: existing.data.itemId,
- quantity: effectiveSplitQty,
- disposition: "Pending",
- companyId,
- createdBy: userId
- })
- .select("id")
- .single();
-
- if (insert.error || !insert.data) {
- return data(
- { error: insert.error },
- await flash(request, error(insert.error, "Failed to split line"))
- );
- }
-
- const newRowId = (insert.data as { id: string }).id;
-
- if (entitiesToMove.length > 0) {
- const entityIds = entitiesToMove.map((e) => e.trackedEntityId);
- const move = await (client as any)
- .from("nonConformanceItemTrackedEntity")
- .update({
- nonConformanceItemId: newRowId,
- updatedBy: userId,
- updatedAt: nowIso
- })
- .eq("nonConformanceItemId", id)
- .in("trackedEntityId", entityIds)
- .eq("companyId", companyId);
- if (move.error) {
- return data(
- { error: move.error },
- await flash(
- request,
- error(move.error, "Failed to reassign tracked entities")
- )
- );
- }
- }
-
- const update = await client
- .from("nonConformanceItem")
- .update({
- quantity: current - effectiveSplitQty,
- updatedBy: userId,
- updatedAt: nowIso
- })
- .eq("id", id)
- .eq("companyId", companyId);
+ const result = await splitIssueItem({
+ id,
+ companyId,
+ userId,
+ splitQuantity,
+ entityAssignments: entityAssignments ?? undefined
+ });
- if (update.error) {
+ if (result.error) {
return data(
- { error: update.error },
- await flash(request, error(update.error, "Failed to update original"))
+ { error: result.error },
+ await flash(request, error(result.error, result.error.message))
);
}
diff --git a/apps/erp/app/routes/x+/issue+/item+/update.tsx b/apps/erp/app/routes/x+/issue+/item+/update.tsx
index 6d89f534d3..08cfe8f149 100644
--- a/apps/erp/app/routes/x+/issue+/item+/update.tsx
+++ b/apps/erp/app/routes/x+/issue+/item+/update.tsx
@@ -60,22 +60,6 @@ export async function action({ request }: ActionFunctionArgs) {
updatedAt: new Date().toISOString()
})
.eq("id", id);
- case "quantity":
- const quantity = parseFloat(value || "0");
- if (isNaN(quantity) || quantity < 0) {
- return {
- error: { message: "Invalid quantity" },
- data: null
- };
- }
- return await client
- .from("nonConformanceItem")
- .update({
- quantity,
- updatedBy: userId,
- updatedAt: new Date().toISOString()
- })
- .eq("id", id);
default:
return {
error: { message: `Invalid field: ${field}` },
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 43274589d5..09dc2bf0fe 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Dieses Unternehmen im Implementierungs-Hub registrieren"
msgid "Enter a batch number before setting the expiration date"
msgstr "Geben Sie eine Chargennummer ein, bevor Sie das Ablaufdatum festlegen"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "Geben Sie eine Menge zwischen 1 und {0} ein."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Lieferantenrechnungen gegen eine Bestellung eingeben und genehmigen (dreigliedriger Abgleich)"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 9d259a9f19..a174a6a94f 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Enroll this company in the Implementation Hub"
msgid "Enter a batch number before setting the expiration date"
msgstr "Enter a batch number before setting the expiration date"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "Enter a quantity between 1 and {0}."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Enter and approve vendor bills against a PO (three-way match)"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index 76b045431d..a43c3bf3a5 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Inscribir esta empresa en el centro de implementación"
msgid "Enter a batch number before setting the expiration date"
msgstr "Ingrese un número de lote antes de establecer la fecha de vencimiento"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "Ingrese una cantidad entre 1 y {0}."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Ingresar y aprobar facturas de proveedores contra una OC (coincidencia de tres vías)"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 3bb2074148..286a234d21 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Inscrire cette entreprise au hub d'implémentation"
msgid "Enter a batch number before setting the expiration date"
msgstr "Entrez un numéro de lot avant de définir la date d'expiration"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "Entrez une quantité entre 1 et {0}."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Entrer et approuver les factures fournisseurs par rapport à un bon de commande (rapprochement à trois voies)"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 23e650c09b..a6e64c3ecf 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -4731,6 +4731,10 @@ msgstr "इस कंपनी को कार्यान्वयन हब
msgid "Enter a batch number before setting the expiration date"
msgstr "समाप्ति तारीख सेट करने से पहले एक बैच नंबर दर्ज करें"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "1 और {0} के बीच मात्रा दर्ज करें।"
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "विक्रेता बिलों को PO के विरुद्ध दर्ज करें और अनुमोदित करें (तीन-तरफा मिलान)"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index 2390a73736..28b5ecce00 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Iscrivi questa azienda all'hub di implementazione"
msgid "Enter a batch number before setting the expiration date"
msgstr "Inserisci un numero di lotto prima di impostare la data di scadenza"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "Inserisci una quantità tra 1 e {0}."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Inserisci e approva fatture fornitori rispetto a un ordine di acquisto (verifica a tre vie)"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 5b8d5361c4..736a204833 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -4731,6 +4731,10 @@ msgstr "この会社を実装ハブに登録する"
msgid "Enter a batch number before setting the expiration date"
msgstr "有効期限を設定する前にバッチ番号を入力してください"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "1~{0}の数量を入力してください。"
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "ベンダー請求書をPOに対して入力および承認する(3者間照合)"
diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.po
index 55d464c513..b319981af8 100644
--- a/packages/locale/locales/ko/erp.po
+++ b/packages/locale/locales/ko/erp.po
@@ -4731,6 +4731,10 @@ msgstr "이 회사를 구현 허브에 등록"
msgid "Enter a batch number before setting the expiration date"
msgstr "유효기한을 설정하기 전에 배치 번호를 입력하세요"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "1과 {0} 사이의 수량을 입력하세요."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "구매주문(PO)에 대한 공급업체 청구서를 입력하고 승인하세요(3자 대조)"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 93733606f6..506ae9ab36 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Zarejestruj tę firmę w centrum wdrażania"
msgid "Enter a batch number before setting the expiration date"
msgstr "Wprowadź numer partii przed ustawieniem daty wygaśnięcia"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "Wprowadź ilość między 1 a {0}."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Wprowadź i zatwierdź faktury od dostawców względem PO (trójstronna weryfikacja)"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index f202213fc1..8d73de925f 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Inscrever esta empresa no hub de implementação"
msgid "Enter a batch number before setting the expiration date"
msgstr "Insira um número de lote antes de definir a data de expiração"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "Digite uma quantidade entre 1 e {0}."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Inserir e aprovar faturas de fornecedores contra uma PO (correspondência de três vias)"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index 75920e687d..ba2435bfff 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Зарегистрировать эту компанию в центре
msgid "Enter a batch number before setting the expiration date"
msgstr "Введите номер партии перед установкой даты истечения"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "Введите количество от 1 до {0}."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Ввести и утвердить счета поставщиков по сравнению с ПО (трёхсторонняя сверка)"
diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.po
index 013c7e27a2..ffc5dd015d 100644
--- a/packages/locale/locales/tr/erp.po
+++ b/packages/locale/locales/tr/erp.po
@@ -4731,6 +4731,10 @@ msgstr "Bu şirketi Uygulama merkezine kaydedin"
msgid "Enter a batch number before setting the expiration date"
msgstr "Son kullanma tarihini ayarlamadan önce bir parti numarası girin"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "1 ile {0} arasında bir miktar girin."
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "Satıcı faturalarını bir PO'ya karşı girin ve onaylayın (üç yönlü eşleştirme)"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index b741fef0b5..07ce258087 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -4731,6 +4731,10 @@ msgstr "将此公司注册到实施中心"
msgid "Enter a batch number before setting the expiration date"
msgstr "在设置过期日期前请输入批号"
+#. placeholder {0}: target.maxQuantity - 1
+msgid "Enter a quantity between 1 and {0}."
+msgstr "请输入 1 至 {0} 之间的数量。"
+
msgid "Enter and approve vendor bills against a PO (three-way match)"
msgstr "输入并批准针对采购订单的供应商账单(三方匹配)"