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.

refactor: merge job method route and job details route

Brad Barbin4ce54dea5cc6
diff --git a/apps/erp/app/modules/production/production.service.ts b/apps/erp/app/modules/production/production.service.ts
index 4713254d15..38b7b348fd 100644
--- a/apps/erp/app/modules/production/production.service.ts
+++ b/apps/erp/app/modules/production/production.service.ts
@@ -921,6 +921,20 @@ export async function getJobMakeMethodById(
.single();
}
+export async function getRootMakeMethod(
+ client: SupabaseClient<Database>,
+ jobId: string,
+ companyId: string
+) {
+ return client
+ .from("jobMakeMethod")
+ .select("*, ...item(itemType:type, methodRevision:revision)")
+ .eq("jobId", jobId)
+ .is("parentMaterialId", null)
+ .eq("companyId", companyId)
+ .single();
+}
+
export async function getJobMaterialsWithQuantityOnHand(
client: SupabaseClient<Database>,
jobId: string,
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
index e3fc43d333..1e0e16c472 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
@@ -104,9 +104,19 @@ const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {
const [searchParams, setSearchParams] = useSearchParams();
const selectedMaterialId = searchParams.get("materialId");
+ const isDetailsRoute =
+ jobId && location.pathname === path.to.jobDetails(jobId);
+
// biome-ignore lint/correctness/useExhaustiveDependencies: supress
useEffect(() => {
if (!selectedMaterialId) {
+ if (isDetailsRoute) {
+ const rootNode = method.find((m) => m.data.isRoot);
+ if (rootNode) {
+ selectNode(rootNode.id);
+ return;
+ }
+ }
deselectAllNodes();
return;
}
@@ -463,7 +473,7 @@ function NodePreview({ node }: { node: FlatTreeItem<JobMethod> }) {
function getNodePath(node: FlatTreeItem<JobMethod>) {
return node.data.isRoot
- ? path.to.jobMethod(node.data.jobId, node.data.jobMaterialMakeMethodId)
+ ? path.to.jobDetails(node.data.jobId)
: node.data.methodType === "Make"
? path.to.jobMakeMethod(
node.data.jobId,
diff --git a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
index 517dc60029..23a20f540b 100644
--- a/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
+++ b/apps/erp/app/modules/production/ui/Jobs/JobMakeMethodTools.tsx
@@ -114,7 +114,9 @@ const JobMakeMethodTools = ({ makeMethod }: { makeMethod?: JobMakeMethod }) => {
const getMethodModal = useDisclosure();
const saveMethodModal = useDisclosure();
- const isJobMethod = pathname === path.to.jobMethod(jobId, methodId!);
+ const isJobDetails = pathname === path.to.jobDetails(jobId);
+ const isJobMethod =
+ isJobDetails || pathname === path.to.jobMethod(jobId, methodId!);
const isJobMakeMethod =
methodId && pathname === path.to.jobMakeMethod(jobId, methodId);
diff --git a/apps/erp/app/routes/x+/job+/$jobId.details.tsx b/apps/erp/app/routes/x+/job+/$jobId.details.tsx
index 87c708ac9e..0bd8d7cfb8 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.details.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.details.tsx
@@ -30,31 +30,37 @@ import { usePermissions, useRealtime, useRouteData } from "~/hooks";
import type { Job, JobPurchaseOrderLine } from "~/modules/production";
import {
getJob,
+ getJobDocumentsWithItemId,
+ getJobMakeMethodById,
+ getJobMaterialsByMethodId,
+ getJobOperationsByMethodId,
getJobPurchaseOrderLines,
+ getProductionDataByOperations,
+ getRootMakeMethod,
jobValidator,
recalculateJobRequirements,
upsertJob
} from "~/modules/production";
import {
+ JobBillOfMaterial,
+ JobBillOfProcess,
JobDocuments,
+ JobEstimatesVsActuals,
JobNotes,
JobRiskRegister
} from "~/modules/production/ui/Jobs";
+import JobMakeMethodTools from "~/modules/production/ui/Jobs/JobMakeMethodTools";
import PurchasingStatus from "~/modules/purchasing/ui/PurchaseOrder/PurchasingStatus";
+import { getTagsList } from "~/modules/shared";
import { useItems } from "~/stores";
import type { StorageItem } from "~/types";
import { setCustomFields } from "~/utils/form";
-import { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
-export const handle: Handle = {
- breadcrumb: `Detail`,
- module: "production"
-};
-
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
- view: "production"
+ const { client, companyId } = await requirePermissions(request, {
+ view: "production",
+ bypassRls: true
});
const { jobId } = params;
@@ -68,9 +74,66 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
);
}
+ const rootMethod = await getRootMakeMethod(client, jobId, companyId);
+ if (rootMethod.error) {
+ return {
+ notes: (job.data?.notes ?? {}) as JSONContent,
+ purchaseOrderLines: getJobPurchaseOrderLines(client, jobId),
+ materials: [],
+ operations: [],
+ makeMethod: null,
+ files: Promise.resolve([] as StorageItem[]),
+ productionData: Promise.resolve({
+ quantities: [],
+ events: [],
+ notes: []
+ }),
+ tags: []
+ };
+ }
+
+ const methodId = rootMethod.data.id;
+
+ const [materials, operations, tags, makeMethod] = await Promise.all([
+ getJobMaterialsByMethodId(client, methodId),
+ getJobOperationsByMethodId(client, methodId),
+ getTagsList(client, companyId, "operation"),
+ getJobMakeMethodById(client, methodId, companyId)
+ ]);
+
return {
notes: (job.data?.notes ?? {}) as JSONContent,
- purchaseOrderLines: getJobPurchaseOrderLines(client, jobId)
+ purchaseOrderLines: getJobPurchaseOrderLines(client, jobId),
+ materials:
+ materials?.data?.map((m) => ({
+ ...m,
+ itemType: m.itemType as "Part",
+ unitOfMeasureCode: m.unitOfMeasureCode ?? "",
+ jobOperationId: m.jobOperationId ?? undefined
+ })) ?? [],
+ operations:
+ operations.data?.map((o) => ({
+ ...o,
+ description: o.description ?? "",
+ workCenterId: o.workCenterId ?? undefined,
+ laborRate: o.laborRate ?? 0,
+ machineRate: o.machineRate ?? 0,
+ operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,
+ jobMakeMethodId: o.jobMakeMethodId ?? methodId,
+ workInstruction: o.workInstruction as JSONContent
+ })) ?? [],
+ makeMethod: makeMethod.data ?? null,
+ files: getJobDocumentsWithItemId(
+ client,
+ companyId,
+ job.data,
+ rootMethod.data.itemId
+ ),
+ productionData: getProductionDataByOperations(
+ client,
+ operations?.data?.map((o) => o.id) ?? []
+ ),
+ tags: tags.data ?? []
};
}
@@ -126,15 +189,26 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
export default function JobDetailsRoute() {
- const { notes, purchaseOrderLines } = useLoaderData<typeof loader>();
+ const {
+ notes,
+ purchaseOrderLines,
+ materials,
+ operations,
+ makeMethod,
+ productionData,
+ tags,
+ files
+ } = useLoaderData<typeof loader>();
const { jobId } = useParams();
if (!jobId) throw new Error("Could not find jobId");
const permissions = usePermissions();
- const { setIsExplorerCollapsed } = usePanels();
+ const { setIsExplorerCollapsed, isExplorerCollapsed } = usePanels();
useMount(() => {
- setIsExplorerCollapsed(false);
+ if (isExplorerCollapsed) {
+ setIsExplorerCollapsed(false);
+ }
});
const jobData = useRouteData<{
@@ -146,55 +220,110 @@ export default function JobDetailsRoute() {
useRealtime("modelUpload", `modelPath=eq.(${jobData?.job.modelPath})`);
+ const methodId = makeMethod?.id;
+
return (
- <VStack spacing={2} className="p-2 h-full">
- <JobNotes
- id={jobId}
- title={jobData?.job.jobId ?? ""}
- subTitle={jobData?.job.itemReadableIdWithRevision ?? ""}
- notes={notes}
- />
-
- <Suspense
- fallback={
- <div className="flex w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center min-h-[420px] max-h-[70vh]">
- <Spinner className="h-10 w-10" />
- </div>
- }
- >
- <Await resolve={jobData.files}>
- {(files) => (
- <JobDocuments
- files={files}
- jobId={jobData.job.id ?? ""}
- itemId={jobData.job.itemId}
- modelUpload={{ ...jobData.job }}
+ <div className="h-[calc(100dvh-49px)] w-full items-start overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
+ <VStack spacing={2} className="p-2">
+ <JobMakeMethodTools makeMethod={makeMethod ?? undefined} />
+ <JobNotes
+ id={jobId}
+ title={jobData?.job.jobId ?? ""}
+ subTitle={jobData?.job.itemReadableIdWithRevision ?? ""}
+ notes={notes}
+ />
+
+ {methodId && (
+ <>
+ <JobBillOfMaterial
+ key={`bom:${methodId}`}
+ jobMakeMethodId={methodId}
+ // @ts-ignore
+ materials={materials}
+ // @ts-ignore
+ operations={operations}
/>
- )}
- </Await>
- </Suspense>
- <Suspense>
- <Await resolve={purchaseOrderLines}>
- {(purchaseOrderLines) => (
- <JobPurchaseOrderLines
- purchaseOrderLines={purchaseOrderLines.data ?? []}
+ <JobBillOfProcess
+ key={`bop:${methodId}`}
+ jobMakeMethodId={methodId}
+ // @ts-ignore
+ materials={materials}
+ // @ts-ignore
+ operations={operations}
+ locationId={jobData?.job?.locationId ?? ""}
+ tags={tags}
+ itemId={makeMethod.itemId}
+ salesOrderLineId={jobData?.job.salesOrderLineId ?? ""}
+ customerId={jobData?.job.customerId ?? ""}
/>
- )}
- </Await>
- </Suspense>
- <CadModel
- isReadOnly={!permissions.can("update", "production")}
- metadata={{
- jobId: jobData?.job?.id ?? undefined,
- itemId: jobData?.job?.itemId ?? undefined
- }}
- modelPath={jobData?.job?.modelPath ?? null}
- title="CAD Model"
- uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"
- viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"
- />
- <JobRiskRegister jobId={jobId} itemId={jobData?.job?.itemId ?? ""} />
- </VStack>
+ </>
+ )}
+
+ <Suspense
+ fallback={
+ <div className="flex w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center min-h-[200px]">
+ <Spinner className="h-10 w-10" />
+ </div>
+ }
+ >
+ <Await resolve={productionData}>
+ {(resolvedProductionData) => (
+ <JobEstimatesVsActuals
+ // @ts-ignore
+ materials={materials ?? []}
+ // @ts-ignore
+ operations={operations}
+ productionEvents={resolvedProductionData.events}
+ productionQuantities={resolvedProductionData.quantities}
+ notes={resolvedProductionData.notes}
+ />
+ )}
+ </Await>
+ </Suspense>
+
+ <Suspense
+ fallback={
+ <div className="flex w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center min-h-[420px] max-h-[70vh]">
+ <Spinner className="h-10 w-10" />
+ </div>
+ }
+ >
+ <Await resolve={files}>
+ {(resolvedFiles) => (
+ <JobDocuments
+ files={resolvedFiles}
+ jobId={jobData.job.id ?? ""}
+ bucket="parts"
+ itemId={makeMethod?.itemId ?? jobData.job.itemId}
+ modelUpload={{ ...jobData.job }}
+ />
+ )}
+ </Await>
+ </Suspense>
+
+ <Suspense>
+ <Await resolve={purchaseOrderLines}>
+ {(purchaseOrderLines) => (
+ <JobPurchaseOrderLines
+ purchaseOrderLines={purchaseOrderLines.data ?? []}
+ />
+ )}
+ </Await>
+ </Suspense>
+ <CadModel
+ isReadOnly={!permissions.can("update", "production")}
+ metadata={{
+ jobId: jobData?.job?.id ?? undefined,
+ itemId: jobData?.job?.itemId ?? undefined
+ }}
+ modelPath={jobData?.job?.modelPath ?? null}
+ title="CAD Model"
+ uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"
+ viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"
+ />
+ <JobRiskRegister jobId={jobId} itemId={jobData?.job?.itemId ?? ""} />
+ </VStack>
+ </div>
);
}
diff --git a/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx b/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
index 5eea52cfb6..ccf046a0c5 100644
--- a/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
+++ b/apps/erp/app/routes/x+/job+/$jobId.method.$methodId.tsx
@@ -1,211 +1,10 @@
-import { error } from "@carbon/auth";
-import { requirePermissions } from "@carbon/auth/auth.server";
-import { flash } from "@carbon/auth/session.server";
-import type { JSONContent } from "@carbon/react";
-import { Spinner, useMount, VStack } from "@carbon/react";
-import { Suspense } from "react";
import type { LoaderFunctionArgs } from "react-router";
-import { Await, redirect, useLoaderData, useParams } from "react-router";
-import { CadModel } from "~/components";
-import { usePanels } from "~/components/Layout";
-import { usePermissions, useRouteData } from "~/hooks";
-import type { Job } from "~/modules/production";
-import {
- getJob,
- getJobDocumentsWithItemId,
- getJobMakeMethodById,
- getJobMaterialsByMethodId,
- getJobOperationsByMethodId,
- getProductionDataByOperations
-} from "~/modules/production";
-import {
- JobBillOfMaterial,
- JobBillOfProcess,
- JobDocuments,
- JobEstimatesVsActuals
-} from "~/modules/production/ui/Jobs";
-import JobMakeMethodTools from "~/modules/production/ui/Jobs/JobMakeMethodTools";
-import { getTagsList } from "~/modules/shared";
+import { redirect } from "react-router";
import { path } from "~/utils/path";
-export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client, companyId } = await requirePermissions(request, {
- view: "production",
- bypassRls: true
- });
-
- const { jobId, methodId } = params;
- if (!jobId) throw new Error("Could not find jobId");
- if (!methodId) throw new Error("Could not find methodId");
-
- const [job, materials, operations, tags, makeMethod] = await Promise.all([
- getJob(client, jobId),
- getJobMaterialsByMethodId(client, methodId),
- getJobOperationsByMethodId(client, methodId),
- getTagsList(client, companyId, "operation"),
- getJobMakeMethodById(client, methodId, companyId)
- ]);
-
- if (job.error) {
- throw redirect(
- path.to.jobs,
- await flash(request, error(materials.error, "Failed to load job"))
- );
- }
-
- if (materials.error) {
- throw redirect(
- path.to.job(jobId),
- await flash(
- request,
- error(materials.error, "Failed to load job materials")
- )
- );
- }
-
- if (operations.error) {
- throw redirect(
- path.to.job(jobId),
- await flash(
- request,
- error(operations.error, "Failed to load job operations")
- )
- );
- }
-
- if (makeMethod.error) {
- throw redirect(
- path.to.job(jobId),
- await flash(
- request,
- error(makeMethod.error, "Failed to load make method")
- )
- );
- }
-
- return {
- job: job.data,
- materials:
- materials?.data.map((m) => ({
- ...m,
- itemType: m.itemType as "Part",
- unitOfMeasureCode: m.unitOfMeasureCode ?? "",
- jobOperationId: m.jobOperationId ?? undefined
- })) ?? [],
- operations:
- operations.data?.map((o) => ({
- ...o,
- description: o.description ?? "",
- workCenterId: o.workCenterId ?? undefined,
- laborRate: o.laborRate ?? 0,
- machineRate: o.machineRate ?? 0,
- operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,
- jobMakeMethodId: o.jobMakeMethodId ?? methodId,
- workInstruction: o.workInstruction as JSONContent
- })) ?? [],
- makeMethod: makeMethod.data,
- files: getJobDocumentsWithItemId(
- client,
- companyId,
- job.data,
- makeMethod.data.itemId
- ),
- productionData: getProductionDataByOperations(
- client,
- operations?.data?.map((o) => o.id)
- ),
- tags: tags.data ?? []
- };
-}
-
-export default function JobMakeMethodRoute() {
- const { makeMethod } = useLoaderData<typeof loader>();
- const permissions = usePermissions();
- const { methodId, jobId } = useParams();
- if (!methodId) throw new Error("Could not find methodId");
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { jobId } = params;
if (!jobId) throw new Error("Could not find jobId");
- const routeData = useRouteData<{ job: Job }>(path.to.job(jobId));
-
- const loaderData = useLoaderData<typeof loader>();
- const { job, materials, operations, productionData, tags, files } =
- loaderData;
-
- const { setIsExplorerCollapsed, isExplorerCollapsed } = usePanels();
-
- useMount(() => {
- if (isExplorerCollapsed) {
- setIsExplorerCollapsed(false);
- }
- });
-
- return (
- <div className="h-[calc(100dvh-49px)] w-full items-start overflow-y-auto scrollbar-thin scrollbar-track-transparent scrollbar-thumb-accent">
- <VStack spacing={2} className="p-2">
- <JobMakeMethodTools makeMethod={makeMethod} />
- <JobBillOfMaterial
- key={`bom:${methodId}`}
- jobMakeMethodId={methodId}
- materials={materials}
- // @ts-ignore
- operations={operations}
- />
- <JobBillOfProcess
- key={`bop:${methodId}`}
- jobMakeMethodId={methodId}
- materials={materials}
- // @ts-ignore
- operations={operations}
- locationId={routeData?.job?.locationId ?? ""}
- tags={tags}
- itemId={makeMethod.itemId}
- salesOrderLineId={job.salesOrderLineId ?? ""}
- customerId={job.customerId ?? ""}
- />
- <Suspense
- fallback={
- <div className="flex w-full h-full rounded bg-gradient-to-tr from-background to-card items-center justify-center min-h-[200px]">
- <Spinner className="h-10 w-10" />
- </div>
- }
- >
- <Await resolve={productionData}>
- {(resolvedProductionData) => (
- <JobEstimatesVsActuals
- // @ts-ignore
- materials={materials ?? []}
- // @ts-ignore
- operations={operations}
- productionEvents={resolvedProductionData.events}
- productionQuantities={resolvedProductionData.quantities}
- notes={resolvedProductionData.notes}
- />
- )}
- </Await>
- </Suspense>
- <Await resolve={files}>
- {(files) => (
- <JobDocuments
- files={files}
- jobId={jobId}
- bucket="parts"
- itemId={makeMethod.itemId}
- modelUpload={{ ...job }}
- />
- )}
- </Await>
- <CadModel
- isReadOnly={!permissions.can("update", "production")}
- metadata={{
- jobId: routeData?.job?.id ?? undefined,
- itemId: routeData?.job?.itemId ?? undefined
- }}
- modelPath={routeData?.job?.modelPath ?? null}
- title="CAD Model"
- uploadClassName="aspect-square min-h-[420px] max-h-[70vh]"
- viewerClassName="aspect-square min-h-[420px] max-h-[70vh]"
- />
- </VStack>
- </div>
- );
+ throw redirect(path.to.jobDetails(jobId));
}