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.

feat: support multiple items per issues (rawdogged no llm)

Brad Barbin48d49b95e9bc
diff --git a/apps/erp/app/modules/quality/quality.models.ts b/apps/erp/app/modules/quality/quality.models.ts
index 8e64bf0601..15984e1683 100644
--- a/apps/erp/app/modules/quality/quality.models.ts
+++ b/apps/erp/app/modules/quality/quality.models.ts
@@ -34,6 +34,7 @@ export const nonConformancePriority = [
] as const;
export const nonConformanceAssociationType = [
+ "items",
"customers",
"suppliers",
"jobOperations",
diff --git a/apps/erp/app/modules/quality/quality.service.ts b/apps/erp/app/modules/quality/quality.service.ts
index 43c3eab155..ee695ad9a7 100644
--- a/apps/erp/app/modules/quality/quality.service.ts
+++ b/apps/erp/app/modules/quality/quality.service.ts
@@ -76,6 +76,11 @@ export async function deleteIssueAssociation(
associationId: string
) {
switch (type) {
+ case "items":
+ return await client
+ .from("nonConformanceItem")
+ .delete()
+ .eq("id", associationId);
case "customers":
return await client
.from("nonConformanceCustomer")
@@ -302,7 +307,7 @@ export async function getIssues(
args?: GenericQueryFilters & { search: string | null }
) {
let query = client
- .from("nonConformance")
+ .from("issues")
.select("*", { count: "exact" })
.eq("companyId", companyId);
@@ -400,6 +405,7 @@ export async function getIssueAssociations(
companyId: string
) {
const [
+ items,
jobOperations,
purchaseOrderLines,
salesOrderLines,
@@ -409,6 +415,20 @@ export async function getIssueAssociations(
customers,
suppliers,
] = await Promise.all([
+ // Items
+ client
+ .from("nonConformanceItem")
+ .select(
+ `
+ id,
+ itemId
+ ...item(
+ redableIdWithRevision
+ )
+ `
+ )
+ .eq("nonConformanceId", nonConformanceId)
+ .eq("companyId", companyId),
// Job Operations
client
.from("nonConformanceJobOperation")
@@ -525,6 +545,14 @@ export async function getIssueAssociations(
]);
return {
+ items:
+ items.data?.map((item) => ({
+ type: "items",
+ id: item.id,
+ documentId: item.itemId,
+ documentReadableId: item.readableIdWithRevision || "",
+ documentLineId: "",
+ })) || [],
jobOperations:
jobOperations.data?.map((item) => ({
type: "jobOperations",
@@ -1000,17 +1028,33 @@ export async function upsertIssue(
})
) {
if ("createdBy" in nonConformance) {
+ const { itemId, ...data } = nonConformance;
const result = await client
.from("nonConformance")
- .insert([nonConformance])
+ .insert([data])
.select("id")
.single();
+ if (result.data?.id && itemId) {
+ const itemInsert = await client.from("nonConformanceItem").insert([
+ {
+ nonConformanceId: result.data.id,
+ itemId,
+ companyId: nonConformance.companyId,
+ },
+ ]);
+
+ if (itemInsert.error) {
+ console.error(itemInsert);
+ }
+ }
+
return result;
} else {
+ const { itemId, ...data } = nonConformance;
return client
.from("nonConformance")
- .update(sanitize(nonConformance))
+ .update(sanitize(data))
.eq("id", nonConformance.id);
}
}
diff --git a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
index 9df3d14050..da3e6e5ae5 100644
--- a/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Actions/ActionsTable.tsx
@@ -9,6 +9,7 @@ import {
LuFileText,
LuOctagonX,
LuPencil,
+ LuSquareStack,
LuUser,
} from "react-icons/lu";
import { EmployeeAvatar, Hyperlink, Table } from "~/components";
@@ -16,6 +17,8 @@ import { EmployeeAvatar, Hyperlink, Table } from "~/components";
import { formatDate } from "@carbon/utils";
import { Enumerable } from "~/components/Enumerable";
import { usePermissions } from "~/hooks";
+import { getLinkToItemDetails } from "~/modules/items/ui/Item/ItemForm";
+import { useItems } from "~/stores";
import { usePeople } from "~/stores/people";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
@@ -36,6 +39,7 @@ const ActionsTable = memo(
const permissions = usePermissions();
const [people] = usePeople();
+ const [items] = useItems();
const columns = useMemo<ColumnDef<QualityAction>[]>(() => {
const defaultColumns: ColumnDef<QualityAction>[] = [
@@ -107,6 +111,40 @@ const ActionsTable = memo(
icon: <LuUser />,
},
},
+ {
+ id: "items",
+ header: "Items",
+ cell: ({ row }) => (
+ <span className="flex gap-2 items-center flex-wrap py-2">
+ {((row.original.items ?? []) as Array<string>).map((i) => {
+ const item = items.find((x) => x.id === i);
+ if (!item) return null;
+ return (
+ <Enumerable
+ key={item?.id}
+ value={item?.readableIdWithRevision ?? null}
+ onClick={() =>
+ // @ts-ignore
+ navigate(getLinkToItemDetails(item.type, item.id))
+ }
+ className="cursor-pointer"
+ />
+ );
+ })}
+ </span>
+ ),
+ meta: {
+ icon: <LuSquareStack />,
+ filter: {
+ type: "static",
+ options: items.map((item) => ({
+ value: item.id,
+ label: <Enumerable value={item.readableIdWithRevision} />,
+ })),
+ isArray: true,
+ },
+ },
+ },
{
accessorKey: "dueDate",
header: "Due Date",
@@ -170,7 +208,7 @@ const ActionsTable = memo(
},
];
return defaultColumns;
- }, [requiredActions, people, issueTypes]);
+ }, [requiredActions, people, items, issueTypes, navigate]);
const renderContextMenu = useCallback(
(row: QualityAction) => {
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx b/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
index 5ac1c247d0..c11088585a 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssueAssociations.tsx
@@ -70,11 +70,11 @@ export function IssueAssociationsSkeleton() {
export function IssueAssociationsTree({
tree,
nonConformanceId,
- itemId,
+ items,
}: {
tree: IssueAssociationNode[];
nonConformanceId: string;
- itemId?: string;
+ items?: string[];
}) {
const [filterText, setFilterText] = useState("");
const deleteDisclosure = useDisclosure();
@@ -113,7 +113,10 @@ export function IssueAssociationsTree({
{tree
.sort((a, b) => a.name.localeCompare(b.name))
.filter((node) => {
- if (node.key === "trackedEntities" && !itemId) {
+ if (
+ node.key === "trackedEntities" &&
+ (!Array.isArray(items) || items.length == 0)
+ ) {
return false;
}
@@ -123,7 +126,7 @@ export function IssueAssociationsTree({
<IssueAssociationItem
key={node.key}
filterText={filterText}
- itemId={itemId}
+ items={items}
node={node}
nonConformanceId={nonConformanceId}
onDelete={onDelete}
@@ -153,13 +156,13 @@ export function IssueAssociationItem({
node,
filterText,
nonConformanceId,
- itemId,
+ items,
onDelete,
}: {
node: IssueAssociationNode;
filterText: string;
nonConformanceId: string;
- itemId?: string;
+ items?: string[];
onDelete: (child: IssueAssociationNode["children"][number]) => void;
}) {
const newAssociationModal = useDisclosure();
@@ -270,7 +273,7 @@ export function IssueAssociationItem({
onClose={newAssociationModal.onClose}
type={node.key}
name={node.name}
- itemId={itemId}
+ items={items}
/>
)}
</>
@@ -316,7 +319,7 @@ function NewSupplierAssociation() {
);
}
-function NewJobOperationAssociation({ itemId }: { itemId?: string }) {
+function NewJobOperationAssociation({ items }: { items?: string[] }) {
const [jobs, setJobs] = useState<{ label: string; value: string }[]>([]);
const [jobsAreLoading, setJobsAreLoading] = useState(true);
@@ -393,7 +396,7 @@ function NewJobOperationAssociation({ itemId }: { itemId?: string }) {
);
}
-function NewPurchaseOrderLineAssociation({ itemId }: { itemId?: string }) {
+function NewPurchaseOrderLineAssociation({ items }: { items?: string[] }) {
const [purchaseOrders, setPurchaseOrders] = useState<
{ label: string; value: string }[]
>([]);
@@ -446,8 +449,8 @@ function NewPurchaseOrderLineAssociation({ itemId }: { itemId?: string }) {
.select("id, itemId, item(name)")
.eq("purchaseOrderId", purchaseOrderId);
- if (itemId) {
- query = query.eq("itemId", itemId);
+ if (items) {
+ query = query.in("itemId", items);
}
const { data, error } = await query;
@@ -497,7 +500,7 @@ function NewPurchaseOrderLineAssociation({ itemId }: { itemId?: string }) {
);
}
-function NewSalesOrderLineAssociation({ itemId }: { itemId?: string }) {
+function NewSalesOrderLineAssociation({ items }: { items?: string[] }) {
const { carbon } = useCarbon();
const [salesOrders, setSalesOrders] = useState<
{ label: string; value: string }[]
@@ -548,8 +551,8 @@ function NewSalesOrderLineAssociation({ itemId }: { itemId?: string }) {
.select("id, itemId, item(name)")
.eq("salesOrderId", salesOrderId);
- if (itemId) {
- query = query.eq("itemId", itemId);
+ if (items) {
+ query = query.in("itemId", items);
}
const { data, error } = await query;
@@ -599,9 +602,9 @@ function NewSalesOrderLineAssociation({ itemId }: { itemId?: string }) {
);
}
-function NewShipmentLineAssociation({ itemId }: { itemId?: string }) {
+function NewShipmentLineAssociation({ items }: { items?: string[] }) {
const { carbon } = useCarbon();
- const [items] = useItems();
+ const [storedItems] = useItems();
const [shipments, setShipments] = useState<
{ label: string; value: string }[]
>([]);
@@ -644,8 +647,8 @@ function NewShipmentLineAssociation({ itemId }: { itemId?: string }) {
.select("id, itemId")
.eq("shipmentId", shipmentId);
- if (itemId) {
- query = query.eq("itemId", itemId);
+ if (items) {
+ query = query.in("itemId", items);
}
const { data, error } = await query;
@@ -656,7 +659,7 @@ function NewShipmentLineAssociation({ itemId }: { itemId?: string }) {
setShipmentLines(
data?.map((line) => ({
- label: getItemReadableId(items, line.itemId) ?? `Line ${line.id}`,
+ label: getItemReadableId(storedItems, line.itemId) ?? `Line ${line.id}`,
value: line.id,
})) ?? []
);
@@ -695,9 +698,9 @@ function NewShipmentLineAssociation({ itemId }: { itemId?: string }) {
);
}
-function NewReceiptLineAssociation({ itemId }: { itemId?: string }) {
+function NewReceiptLineAssociation({ items }: { items?: string[] }) {
const { carbon } = useCarbon();
- const [items] = useItems();
+ const [storedItems] = useItems();
const [receipts, setReceipts] = useState<{ label: string; value: string }[]>(
[]
);
@@ -740,8 +743,8 @@ function NewReceiptLineAssociation({ itemId }: { itemId?: string }) {
.select("id, itemId")
.eq("receiptId", receiptId);
- if (itemId) {
- query = query.eq("itemId", itemId);
+ if (items) {
+ query = query.in("itemId", items);
}
const { data, error } = await query;
@@ -752,7 +755,7 @@ function NewReceiptLineAssociation({ itemId }: { itemId?: string }) {
setReceiptLines(
data?.map((line) => ({
- label: getItemReadableId(items, line.itemId) ?? `Line ${line.id}`,
+ label: getItemReadableId(storedItems, line.itemId) ?? `Line ${line.id}`,
value: line.id,
})) ?? []
);
@@ -791,7 +794,7 @@ function NewReceiptLineAssociation({ itemId }: { itemId?: string }) {
);
}
-function NewTrackedEntityAssociation({ itemId }: { itemId?: string }) {
+function NewTrackedEntityAssociation({ items }: { items?: string[] }) {
const { carbon } = useCarbon();
const [trackedEntities, setTrackedEntities] = useState<
{ label: string; value: string }[]
@@ -804,7 +807,7 @@ function NewTrackedEntityAssociation({ itemId }: { itemId?: string }) {
});
async function fetchTrackedEntities() {
- if (!carbon || !itemId) {
+ if (!carbon || !items) {
toast.error("Failed to load data");
return;
}
@@ -813,7 +816,7 @@ function NewTrackedEntityAssociation({ itemId }: { itemId?: string }) {
.from("trackedEntity")
.select("id")
.eq("sourceDocument", "Item")
- .eq("sourceDocumentId", itemId!);
+ .in("sourceDocumentId", items!);
if (error) {
toast.error("Failed to load tracked entities");
@@ -843,13 +846,13 @@ function NewAssociationModal({
onClose,
type,
name,
- itemId,
+ items,
}: {
open: boolean;
onClose: () => void;
type: IssueAssociationKey;
name: string;
- itemId?: string;
+ items?: string[];
}) {
const { id } = useParams();
if (!id) throw new Error("No issue ID found");
@@ -873,17 +876,17 @@ function NewAssociationModal({
case "suppliers":
return <NewSupplierAssociation />;
case "jobOperations":
- return <NewJobOperationAssociation itemId={itemId} />;
+ return <NewJobOperationAssociation items={items} />;
case "purchaseOrderLines":
- return <NewPurchaseOrderLineAssociation itemId={itemId} />;
+ return <NewPurchaseOrderLineAssociation items={items} />;
case "salesOrderLines":
- return <NewSalesOrderLineAssociation itemId={itemId} />;
+ return <NewSalesOrderLineAssociation items={items} />;
case "shipmentLines":
- return <NewShipmentLineAssociation itemId={itemId} />;
+ return <NewShipmentLineAssociation items={items} />;
case "receiptLines":
- return <NewReceiptLineAssociation itemId={itemId} />;
+ return <NewReceiptLineAssociation items={items} />;
case "trackedEntities":
- return <NewTrackedEntityAssociation itemId={itemId} />;
+ return <NewTrackedEntityAssociation items={items} />;
default:
return null;
}
diff --git a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx
index 56bdd63857..fef4e3f34d 100644
--- a/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx
+++ b/apps/erp/app/modules/quality/ui/Issue/IssuesTable.tsx
@@ -222,6 +222,40 @@ const IssuesTable = memo(({ data, types, count }: IssuesTableProps) => {
icon: <LuUser />,
},
},
+ {
+ id: "items",
+ header: "Items",
+ cell: ({ row }) => (
+ <span className="flex gap-2 items-center flex-wrap py-2">
+ {((row.original.items ?? []) as Array<string>).map((i) => {
+ const item = items.find((x) => x.id === i);
+ if (!item) return null;
+ return (
+ <Enumerable
+ key={item?.id}
+ value={item?.readableIdWithRevision ?? null}
+ onClick={() =>
+ // @ts-ignore
+ navigate(getLinkToItemDetails(item.type, item.id))
+ }
+ className="cursor-pointer"
+ />
+ );
+ })}
+ </span>
+ ),
+ meta: {
+ icon: <LuSquareStack />,
+ filter: {
+ type: "static",
+ options: items.map((item) => ({
+ value: item.id,
+ label: <Enumerable value={item.readableIdWithRevision} />,
+ })),
+ isArray: true,
+ },
+ },
+ },
{
accessorKey: "openDate",
header: "Open Date",
@@ -240,7 +274,7 @@ const IssuesTable = memo(({ data, types, count }: IssuesTableProps) => {
},
];
return [...defaultColumns, ...customColumns];
- }, [customColumns, items, locations, people, types]);
+ }, [customColumns, items, locations, navigate, people, types]);
const renderContextMenu = useCallback(
(row: Issue) => {
diff --git a/apps/erp/app/routes/x+/issue+/$id.tsx b/apps/erp/app/routes/x+/issue+/$id.tsx
index fd879173e9..6f3b10fe4f 100644
--- a/apps/erp/app/routes/x+/issue+/$id.tsx
+++ b/apps/erp/app/routes/x+/issue+/$id.tsx
@@ -41,7 +41,13 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { id } = params;
if (!id) throw new Error("Could not find id");
- const [nonConformance, nonConformanceTypes, investigationTypes, requiredActions, tags] = await Promise.all([
+ const [
+ nonConformance,
+ nonConformanceTypes,
+ investigationTypes,
+ requiredActions,
+ tags,
+ ] = await Promise.all([
getIssue(client, id),
getIssueTypesList(client, companyId),
getInvestigationTypesList(client, companyId),
@@ -68,7 +74,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
}
export default function IssueRoute() {
- const { associations, nonConformance } = useLoaderData<typeof loader>();
+ const { associations } = useLoaderData<typeof loader>();
const { id } = useParams();
if (!id) throw new Error("Could not find id");
@@ -85,6 +91,13 @@ export default function IssueRoute() {
{(resolvedAssociations) => {
// Transform the raw associations data into the tree structure expected by IssueAssociationsTree
const tree: IssueAssociationNode[] = [
+ {
+ key: "items",
+ name: "Item",
+ pluralName: "Items",
+ module: "parts",
+ children: resolvedAssociations.items,
+ },
{
key: "jobOperations",
name: "Job Operation",
@@ -146,7 +159,11 @@ export default function IssueRoute() {
<IssueAssociationsTree
tree={tree}
nonConformanceId={id}
- itemId={nonConformance.itemId ?? undefined}
+ items={
+ resolvedAssociations.items?.map(
+ (i) => i.documentId
+ ) ?? undefined
+ }
/>
);
}}
diff --git a/packages/database/supabase/migrations/20250905122922_multi-item-issues.sql b/packages/database/supabase/migrations/20250905122922_multi-item-issues.sql
new file mode 100644
index 0000000000..7c9d7384ec
--- /dev/null
+++ b/packages/database/supabase/migrations/20250905122922_multi-item-issues.sql
@@ -0,0 +1,112 @@
+
+
+
+CREATE TABLE "nonConformanceItem" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "nonConformanceId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE DEFAULT NOW() NOT NULL,
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "nonConformanceItem_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "nonConformanceItem_nonConformanceId_fkey" FOREIGN KEY ("nonConformanceId") REFERENCES "nonConformance"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "nonConformanceItem_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item"("id") ON UPDATE CASCADE ON DELETE CASCADE,
+ CONSTRAINT "nonConformanceItem_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company"("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "nonConformanceItem_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE,
+ CONSTRAINT "nonConformanceItem_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE
+);
+
+
+CREATE POLICY "SELECT" ON "public"."nonConformanceItem"
+FOR SELECT USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('quality_view')
+ )::text[]
+ )
+);
+
+CREATE POLICY "INSERT" ON "public"."nonConformanceItem"
+FOR INSERT WITH CHECK (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('quality_create')
+ )::text[]
+ )
+);
+
+CREATE POLICY "UPDATE" ON "public"."nonConformanceItem"
+FOR UPDATE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('quality_update')
+ )::text[]
+ )
+);
+
+CREATE POLICY "DELETE" ON "public"."nonConformanceItem"
+FOR DELETE USING (
+ "companyId" = ANY (
+ (
+ SELECT
+ get_companies_with_employee_permission ('quality_delete')
+ )::text[]
+ )
+);
+
+INSERT INTO "nonConformanceItem" ("nonConformanceId", "itemId", "companyId")
+SELECT
+ ncr."id",
+ ncr."itemId",
+ ncr."companyId"
+FROM "nonConformance" ncr
+WHERE ncr."itemId" IS NOT NULL
+AND ncr."companyId" IS NOT NULL;
+
+DROP VIEW IF EXISTS "qualityActions";
+
+ALTER TABLE "nonConformance" DROP COLUMN "itemId";
+
+DROP VIEW IF EXISTS "qualityActions";
+CREATE OR REPLACE VIEW "qualityActions" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ ncat.*,
+ ncra."name" AS "actionType",
+ ncr."nonConformanceId" AS "readableNonConformanceId",
+ ncr."name" AS "nonConformanceName",
+ ncr."status" AS "nonConformanceStatus",
+ ncr."openDate" AS "nonConformanceOpenDate",
+ ncr."dueDate" AS "nonConformanceDueDate",
+ ncr."closeDate" AS "nonConformanceCloseDate",
+ nct."name" AS "nonConformanceTypeName",
+ nci."items"
+ FROM "nonConformanceActionTask" ncat
+ INNER JOIN "nonConformance" ncr ON ncat."nonConformanceId" = ncr."id"
+ LEFT JOIN "nonConformanceRequiredAction" ncra ON ncra."id" = ncat."actionTypeId"
+ LEFT JOIN "nonConformanceType" nct ON ncr."nonConformanceTypeId" = nct."id"
+ LEFT JOIN (
+ SELECT
+ "nonConformanceId",
+ array_agg("itemId"::text) as items
+ FROM "nonConformanceItem" nci
+ GROUP BY "nonConformanceId"
+ ) nci ON nci."nonConformanceId" = ncr."id";
+
+CREATE OR REPLACE VIEW "issues" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ ncr.*,
+ nci."items"
+ FROM "nonConformance" ncr
+ LEFT JOIN (
+ SELECT
+ "nonConformanceId",
+ array_agg("itemId"::text) as items
+ FROM "nonConformanceItem" nci
+ GROUP BY "nonConformanceId"
+ ) nci ON nci."nonConformanceId" = ncr."id";
\ No newline at end of file