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: get method and save method for jobs

Brad Barbin8fe938b00e07
diff --git a/apps/carbon/app/modules/production/production.models.ts b/apps/carbon/app/modules/production/production.models.ts
index 8f270693e0..73980e22b4 100644
--- a/apps/carbon/app/modules/production/production.models.ts
+++ b/apps/carbon/app/modules/production/production.models.ts
@@ -353,7 +353,7 @@ export const getJobMethodValidator = z.object({
targetId: z.string().min(1, { message: "Please select a source method" }),
});
-export const getJobMaterialMethodValidator = z.object({
- jobMaterialId: z.string().min(1, { message: "Quote Material is required" }),
- itemId: z.string().min(1, { message: "Please select a source method" }),
-});
+// export const getJobMaterialMethodValidator = z.object({
+// jobMaterialId: z.string().min(1, { message: "Quote Material is required" }),
+// itemId: z.string().min(1, { message: "Please select a source method" }),
+// });
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index fa227f3480..4ba1c1bbb2 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -6,7 +6,6 @@ import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import type {
- getJobMaterialMethodValidator,
jobMaterialValidator,
jobOperationValidator,
jobValidator,
@@ -24,6 +23,20 @@ export async function getJob(client: SupabaseClient<Database>, id: string) {
return client.from("jobs").select("*").eq("id", id).single();
}
+export async function deleteJobMaterial(
+ client: SupabaseClient<Database>,
+ jobMaterialId: string
+) {
+ return client.from("jobMaterial").delete().eq("id", jobMaterialId);
+}
+
+export async function deleteJobOperation(
+ client: SupabaseClient<Database>,
+ jobOperationId: string
+) {
+ return client.from("jobOperation").delete().eq("id", jobOperationId);
+}
+
export async function getJobDocuments(
client: SupabaseClient<Database>,
companyId: string,
@@ -163,34 +176,6 @@ type JobMethodTreeItem = {
children: JobMethodTreeItem[];
};
-export async function upsertJob(
- client: SupabaseClient<Database>,
- job:
- | (Omit<z.infer<typeof jobValidator>, "id" | "jobId"> & {
- jobId: string;
- companyId: string;
- createdBy: string;
- customFields?: Json;
- })
- | (Omit<z.infer<typeof jobValidator>, "id" | "jobId"> & {
- id: string;
- jobId: string;
- updatedBy: string;
- customFields?: Json;
- })
-) {
- if ("updatedBy" in job) {
- return client
- .from("job")
- .update(sanitize(job))
- .eq("id", job.id)
- .select("id")
- .single();
- } else {
- return client.from("job").insert([job]).select("id").single();
- }
-}
-
export async function getJobMaterial(
client: SupabaseClient<Database>,
materialId: string
@@ -263,6 +248,34 @@ export async function updateJobOperationOrder(
return Promise.all(updatePromises);
}
+export async function upsertJob(
+ client: SupabaseClient<Database>,
+ job:
+ | (Omit<z.infer<typeof jobValidator>, "id" | "jobId"> & {
+ jobId: string;
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof jobValidator>, "id" | "jobId"> & {
+ id: string;
+ jobId: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("updatedBy" in job) {
+ return client
+ .from("job")
+ .update(sanitize(job))
+ .eq("id", job.id)
+ .select("id")
+ .single();
+ } else {
+ return client.from("job").insert([job]).select("id").single();
+ }
+}
+
export async function upsertJobMaterial(
client: SupabaseClient<Database>,
jobMaterial:
@@ -347,15 +360,17 @@ export async function upsertJobMethod(
export async function upsertJobMaterialMakeMethod(
client: SupabaseClient<Database>,
- jobMaterial: z.infer<typeof getJobMaterialMethodValidator> & {
+ jobMaterial: {
+ sourceId: string;
+ targetId: string;
companyId: string;
- createdBy: string;
+ userId: string;
}
) {
const makeMethod = await client
.from("jobMakeMethod")
.select("id")
- .eq("parentMaterialId", jobMaterial.jobMaterialId)
+ .eq("parentMaterialId", jobMaterial.targetId)
.single();
if (makeMethod.error) {
return makeMethod;
@@ -364,10 +379,10 @@ export async function upsertJobMaterialMakeMethod(
const { error } = await client.functions.invoke("get-method", {
body: {
type: "itemToJobMakeMethod",
- sourceId: jobMaterial.itemId,
+ sourceId: jobMaterial.sourceId,
targetId: makeMethod.data.id,
companyId: jobMaterial.companyId,
- userId: jobMaterial.createdBy,
+ userId: jobMaterial.userId,
},
});
@@ -381,9 +396,60 @@ export async function upsertJobMaterialMakeMethod(
return { data: null, error: null };
}
-export async function deleteJobMaterial(
+export async function upsertMakeMethodFromJob(
client: SupabaseClient<Database>,
- jobMaterialId: string
+ jobMethod: {
+ sourceId: string;
+ targetId: string;
+ companyId: string;
+ userId: string;
+ }
) {
- return client.from("jobMaterial").delete().eq("id", jobMaterialId);
+ return client.functions.invoke("get-method", {
+ body: {
+ type: "jobToItem",
+ sourceId: jobMethod.sourceId,
+ targetId: jobMethod.targetId,
+ companyId: jobMethod.companyId,
+ userId: jobMethod.userId,
+ },
+ });
+}
+
+export async function upsertMakeMethodFromJobMethod(
+ client: SupabaseClient<Database>,
+ jobMethod: {
+ sourceId: string;
+ targetId: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ const makeMethod = await client
+ .from("jobMakeMethod")
+ .select("id")
+ .eq("parentMaterialId", jobMethod.sourceId)
+ .single();
+ if (makeMethod.error) {
+ return makeMethod;
+ }
+
+ const { error } = await client.functions.invoke("get-method", {
+ body: {
+ type: "jobMakeMethodToItem",
+ sourceId: makeMethod.data.id,
+ targetId: jobMethod.targetId,
+ companyId: jobMethod.companyId,
+ userId: jobMethod.userId,
+ },
+ });
+
+ if (error) {
+ return {
+ data: null,
+ error: { message: "Failed to save method" } as PostgrestError,
+ };
+ }
+
+ return { data: null, error: null };
}
diff --git a/apps/carbon/app/modules/production/types.ts b/apps/carbon/app/modules/production/types.ts
index ad31f3ebb9..b931f59130 100644
--- a/apps/carbon/app/modules/production/types.ts
+++ b/apps/carbon/app/modules/production/types.ts
@@ -1,3 +1,7 @@
-import type { getJob } from "./production.service";
+import type { getJob, getJobMethodTree } from "./production.service";
export type Job = NonNullable<Awaited<ReturnType<typeof getJob>>["data"]>;
+
+export type JobMethod = NonNullable<
+ Awaited<ReturnType<typeof getJobMethodTree>>["data"]
+>[number]["data"];
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
new file mode 100644
index 0000000000..1600c6443e
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBreadcrumbs.tsx
@@ -0,0 +1,283 @@
+import { ValidatedForm } from "@carbon/form";
+import {
+ Alert,
+ AlertTitle,
+ Button,
+ Checkbox,
+ HStack,
+ Menubar,
+ MenubarItem,
+ Modal,
+ ModalBody,
+ ModalContent,
+ ModalDescription,
+ ModalFooter,
+ ModalHeader,
+ ModalTitle,
+ toast,
+ useDisclosure,
+ VStack,
+} from "@carbon/react";
+import { Link, useFetcher, useLocation, useParams } from "@remix-run/react";
+import { useEffect, useState } from "react";
+import {
+ LuAlertTriangle,
+ LuDownload,
+ LuHardHat,
+ LuUpload,
+} from "react-icons/lu";
+import { BreadcrumbItem, Breadcrumbs } from "~/components";
+import { Hidden, Item, Submit } from "~/components/Form";
+import type { Tree } from "~/components/TreeView";
+import { usePermissions, useRouteData } from "~/hooks";
+import { path } from "~/utils/path";
+import { getJobMethodValidator } from "../../production.models";
+import type { Job, JobMethod } from "../../types";
+
+const JobBreadcrumbs = () => {
+ const permissions = usePermissions();
+ const { jobId, methodId, materialId } = useParams();
+ if (!jobId) throw new Error("jobId not found");
+
+ const fetcher = useFetcher<{ error: string | null }>();
+ const routeData = useRouteData<{
+ job: Job;
+ method: Tree<JobMethod>;
+ }>(path.to.job(jobId));
+
+ const { pathname } = useLocation();
+
+ const methodTree = routeData?.method;
+ const hasMethods = methodTree?.children && methodTree.children.length > 0;
+
+ const isGetMethodLoading =
+ fetcher.state !== "idle" && fetcher.formAction === path.to.jobMethodGet;
+ const isSaveMethodLoading =
+ fetcher.state !== "idle" && fetcher.formAction === path.to.jobMethodSave;
+
+ useEffect(() => {
+ if (fetcher.data?.error) {
+ toast.error(fetcher.data.error);
+ }
+ }, [fetcher.data?.error]);
+
+ const [includeInactive, setIncludeInactive] = useState<
+ boolean | "indeterminate"
+ >(true);
+
+ const getMethodModal = useDisclosure();
+ const saveMethodModal = useDisclosure();
+
+ const isJobMethod = pathname === path.to.jobMethod(jobId, methodId!);
+ const isJobMakeMethod =
+ methodId &&
+ materialId &&
+ pathname === path.to.jobMakeMethod(jobId, methodId, materialId);
+
+ return isJobMethod || isJobMakeMethod ? (
+ <>
+ <Menubar>
+ <HStack className="w-full justify-between">
+ <Breadcrumbs>
+ <BreadcrumbItem>
+ <Button leftIcon={<LuHardHat />} variant="ghost" asChild>
+ <Link to={path.to.jobDetails(jobId)}>
+ {routeData?.job?.jobId}
+ </Link>
+ </Button>
+ </BreadcrumbItem>
+ </Breadcrumbs>
+ {permissions.can("update", "production") &&
+ (isJobMethod || isJobMakeMethod) && (
+ <HStack spacing={0}>
+ <MenubarItem
+ isDisabled={
+ !permissions.can("update", "parts") || isSaveMethodLoading
+ }
+ isLoading={isSaveMethodLoading}
+ leftIcon={<LuUpload />}
+ onClick={saveMethodModal.onOpen}
+ >
+ Save Method
+ </MenubarItem>
+ <MenubarItem
+ isLoading={isGetMethodLoading}
+ isDisabled={isGetMethodLoading}
+ leftIcon={<LuDownload />}
+ onClick={getMethodModal.onOpen}
+ >
+ Get Method
+ </MenubarItem>
+ </HStack>
+ )}
+ </HStack>
+ </Menubar>
+ {getMethodModal.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ getMethodModal.onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ fetcher={fetcher}
+ action={path.to.jobMethodGet}
+ validator={getJobMethodValidator}
+ onSubmit={getMethodModal.onClose}
+ >
+ <ModalHeader>
+ <ModalTitle>Get Method</ModalTitle>
+ <ModalDescription>
+ Overwrite the job method with the source method
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ {isJobMethod ? (
+ <>
+ <Hidden name="type" value="item" />
+ <Hidden name="targetId" value={jobId} />
+ </>
+ ) : (
+ <>
+ <Hidden name="type" value="method" />
+ <Hidden name="targetId" value={materialId!} />
+ </>
+ )}
+
+ <VStack spacing={4}>
+ <Item
+ name="sourceId"
+ label="Source Method"
+ type={(routeData?.job.itemType ?? "Part") as "Part"}
+ includeInactive={includeInactive === true}
+ replenishmentSystem="Make"
+ />
+ <div className="flex items-center space-x-2">
+ <Checkbox
+ id="include-inactive"
+ checked={includeInactive}
+ onCheckedChange={setIncludeInactive}
+ />
+ <label
+ htmlFor="include-inactive"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Include Inactive
+ </label>
+ </div>
+ {hasMethods && (
+ <Alert variant="destructive">
+ <LuAlertTriangle className="h-4 w-4" />
+ <AlertTitle>
+ This will overwrite the existing job method
+ </AlertTitle>
+ </Alert>
+ )}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button onClick={getMethodModal.onClose} variant="secondary">
+ Cancel
+ </Button>
+ <Submit variant={hasMethods ? "destructive" : "primary"}>
+ Confirm
+ </Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
+
+ {saveMethodModal.isOpen && (
+ <Modal
+ open
+ onOpenChange={(open) => {
+ if (!open) {
+ saveMethodModal.onClose();
+ }
+ }}
+ >
+ <ModalContent>
+ <ValidatedForm
+ method="post"
+ fetcher={fetcher}
+ action={path.to.jobMethodSave}
+ validator={getJobMethodValidator}
+ defaultValues={{
+ targetId: isJobMethod
+ ? routeData?.job?.itemId ?? undefined
+ : undefined,
+ }}
+ onSubmit={saveMethodModal.onClose}
+ >
+ <ModalHeader>
+ <ModalTitle>Save Method</ModalTitle>
+ <ModalDescription>
+ Overwrite the target manufacturing method with the job method
+ </ModalDescription>
+ </ModalHeader>
+ <ModalBody>
+ {isJobMethod ? (
+ <>
+ <Hidden name="type" value="job" />
+ <Hidden name="sourceId" value={jobId} />
+ </>
+ ) : (
+ <>
+ <Hidden name="type" value="method" />
+ <Hidden name="sourceId" value={materialId!} />
+ </>
+ )}
+
+ <VStack spacing={4}>
+ <Item
+ name="targetId"
+ label="Target Method"
+ type={(routeData?.job?.itemType ?? "Part") as "Part"}
+ includeInactive={includeInactive === true}
+ replenishmentSystem="Make"
+ />
+ <div className="flex items-center space-x-2">
+ <Checkbox
+ id="include-inactive"
+ checked={includeInactive}
+ onCheckedChange={setIncludeInactive}
+ />
+ <label
+ htmlFor="include-inactive"
+ className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
+ >
+ Include Inactive
+ </label>
+ </div>
+ {hasMethods && (
+ <Alert variant="destructive">
+ <LuAlertTriangle className="h-4 w-4" />
+ <AlertTitle>
+ This will overwrite the existing manufacturing method
+ </AlertTitle>
+ </Alert>
+ )}
+ </VStack>
+ </ModalBody>
+ <ModalFooter>
+ <Button onClick={saveMethodModal.onClose} variant="secondary">
+ Cancel
+ </Button>
+ <Submit variant={hasMethods ? "destructive" : "primary"}>
+ Confirm
+ </Submit>
+ </ModalFooter>
+ </ValidatedForm>
+ </ModalContent>
+ </Modal>
+ )}
+ </>
+ ) : null;
+};
+
+export default JobBreadcrumbs;
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
index 16290eb7b8..05a109a81c 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
@@ -176,13 +176,13 @@ function getNodePath(node: FlatTreeItem<QuoteMethod>) {
node.data.quoteMaterialMakeMethodId
)
: node.data.methodType === "Make"
- ? path.to.quoteLineMaterialMake(
+ ? path.to.quoteLineMakeMethod(
node.data.quoteId,
node.data.quoteLineId,
node.data.quoteMaterialMakeMethodId,
node.data.methodMaterialId
)
- : path.to.quoteLineMaterial(
+ : path.to.quoteLineMethodMaterial(
node.data.quoteId,
node.data.quoteLineId,
node.data.methodType.toLowerCase(),
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx
index d0025a662a..70a670a5bf 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx
@@ -73,7 +73,7 @@ const QuoteBreadcrumbs = () => {
methodId &&
materialId &&
pathname ===
- path.to.quoteLineMaterialMake(quoteId, lineId!, methodId, materialId);
+ path.to.quoteLineMakeMethod(quoteId, lineId!, methodId, materialId);
return (
<>
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
index 8cc98875b6..1fd4d8f144 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteMaterialForm.tsx
@@ -126,13 +126,13 @@ const QuoteMaterialForm = ({
useEffect(() => {
const newPath =
initialValues.methodType === "Make"
- ? path.to.quoteLineMaterialMake(
+ ? path.to.quoteLineMakeMethod(
quoteId,
lineId,
initialValues.quoteMaterialMakeMethodId!,
initialValues.id!
)
- : path.to.quoteLineMaterial(
+ : path.to.quoteLineMethodMaterial(
quoteId,
lineId,
initialValues.methodType.toLowerCase(),
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.tsx
index c0fe513dd6..942fb1407d 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.tsx
@@ -22,6 +22,7 @@ import {
JobBoMExplorer,
JobHeader,
} from "~/modules/production";
+import JobBreadcrumbs from "~/modules/production/ui/Jobs/JobBreadcrumbs";
import {} from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
@@ -102,6 +103,7 @@ export default function JobRoute() {
<ResizablePanel order={2}>
<ScrollArea className="h-[calc(100vh-99px)]">
<VStack spacing={2} className="p-2">
+ <JobBreadcrumbs />
<Outlet />
</VStack>
</ScrollArea>
diff --git a/apps/carbon/app/routes/x+/job+/methods+/get.tsx b/apps/carbon/app/routes/x+/job+/methods+/get.tsx
index ca86a3446d..a3254da4f4 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/get.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/get.tsx
@@ -2,7 +2,6 @@ import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";
import { getSupabaseServiceRole } from "~/lib/supabase";
import {
- getJobMaterialMethodValidator,
getJobMethodValidator,
upsertJobMaterialMakeMethod,
upsertJobMethod,
@@ -19,14 +18,13 @@ export async function action({ request }: ActionFunctionArgs) {
const type = formData.get("type") as string;
const serviceRole = getSupabaseServiceRole();
- if (["item", "quoteLine"].includes(type)) {
- const validation = await validator(getJobMethodValidator).validate(
- formData
- );
- if (validation.error) {
- return validationError(validation.error);
- }
+ const validation = await validator(getJobMethodValidator).validate(formData);
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ if (["item", "quoteLine"].includes(type)) {
const jobMethod = await upsertJobMethod(
serviceRole,
type === "item" ? "itemToJob" : "quoteLineToJob",
@@ -42,18 +40,11 @@ export async function action({ request }: ActionFunctionArgs) {
});
}
- if (type === "material") {
- const validation = await validator(getJobMaterialMethodValidator).validate(
- formData
- );
- if (validation.error) {
- return validationError(validation.error);
- }
-
+ if (type === "method") {
const makeMethod = await upsertJobMaterialMakeMethod(serviceRole, {
...validation.data,
companyId,
- createdBy: userId,
+ userId,
});
if (makeMethod.error) {
diff --git a/apps/carbon/app/routes/x+/job+/methods+/save.tsx b/apps/carbon/app/routes/x+/job+/methods+/save.tsx
index 3130c9022d..51310535a0 100644
--- a/apps/carbon/app/routes/x+/job+/methods+/save.tsx
+++ b/apps/carbon/app/routes/x+/job+/methods+/save.tsx
@@ -2,11 +2,10 @@ import { validationError, validator } from "@carbon/form";
import { json, redirect, type ActionFunctionArgs } from "@remix-run/node";
import { getSupabaseServiceRole } from "~/lib/supabase";
import {
- getLineMethodValidator,
- getMethodValidator,
- upsertMakeMethodFromQuoteLine,
- upsertMakeMethodFromQuoteMethod,
-} from "~/modules/sales";
+ getJobMethodValidator,
+ upsertMakeMethodFromJob,
+ upsertMakeMethodFromJobMethod,
+} from "~/modules/production";
import { requirePermissions } from "~/services/auth/auth.server";
import { path, requestReferrer } from "~/utils/path";
@@ -19,48 +18,41 @@ export async function action({ request }: ActionFunctionArgs) {
const type = formData.get("type") as string;
const serviceRole = getSupabaseServiceRole();
- if (type === "line") {
- const validation = await validator(getLineMethodValidator).validate(
- formData
- );
- if (validation.error) {
- return validationError(validation.error);
- }
+ const validation = await validator(getJobMethodValidator).validate(formData);
+ if (validation.error) {
+ return validationError(validation.error);
+ }
- const lineMethod = await upsertMakeMethodFromQuoteLine(serviceRole, {
+ if (type === "job") {
+ const jobMethod = await upsertMakeMethodFromJob(serviceRole, {
...validation.data,
companyId,
userId,
});
return json({
- error: lineMethod.error
- ? "Failed to save quote method to make method"
+ error: jobMethod.error
+ ? "Failed to save job method to make method"
: null,
});
}
if (type === "method") {
- const validation = await validator(getMethodValidator).validate(formData);
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const makeMethod = await upsertMakeMethodFromQuoteMethod(serviceRole, {
+ const makeMethod = await upsertMakeMethodFromJobMethod(serviceRole, {
...validation.data,
companyId,
- createdBy: userId,
+ userId,
});
if (makeMethod.error) {
return json({
error: makeMethod.error
- ? "Failed to save quote method to make method"
+ ? "Failed to save job method to make method"
: null,
});
}
- throw redirect(requestReferrer(request) ?? path.to.quotes);
+ throw redirect(requestReferrer(request) ?? path.to.jobs);
}
return json({ error: "Invalid type" }, { status: 400 });
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 7df237f4aa..9c983ff029 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -373,6 +373,7 @@ export const path = {
),
jobMaterialsOrder: `${x}/job/methods/material/order`,
jobMethodGet: `${x}/job/methods/get`,
+ jobMethodSave: `${x}/job/methods/save`,
jobOperation: (jobId: string, id: string) =>
generatePath(`${x}/job/methods/${jobId}/operation/${id}`),
jobOperationsOrder: `${x}/job/methods/operation/order`,
@@ -607,7 +608,7 @@ export const path = {
generatePath(`${x}/quote/${quoteId}/${id}/details`),
quoteLineCost: (quoteId: string, lineId: string) =>
generatePath(`${x}/quote/${quoteId}/${lineId}/cost/update`),
- quoteLineMaterial: (
+ quoteLineMethodMaterial: (
quoteId: string,
lineId: string,
methodType: string,
@@ -617,7 +618,7 @@ export const path = {
generatePath(
`${x}/quote/${quoteId}/${lineId}/${methodType}/${methodId}/${id}`
),
- quoteLineMaterialMake: (
+ quoteLineMakeMethod: (
quoteId: string,
lineId: string,
makeMethodId: string,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 6455970fc8..eceb778ca4 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -33557,6 +33557,63 @@ export default {
tags: ["(rpc) _xid_machine_id"],
},
},
+ "/rpc/get_job_methods_by_method_id": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "mid",
+ required: true,
+ type: "string",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_job_methods_by_method_id"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ mid: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["mid"],
+ type: "object",
+ },
+ },
+ {
+ $ref: "#/parameters/preferParams",
+ },
+ ],
+ produces: [
+ "application/json",
+ "application/vnd.pgrst.object+json;nulls=stripped",
+ "application/vnd.pgrst.object+json",
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ },
+ },
+ tags: ["(rpc) get_job_methods_by_method_id"],
+ },
+ },
"/rpc/xid_encode": {
get: {
parameters: [
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 86b30a960e..e2f354d554 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -28790,6 +28790,28 @@ export type Database = {
isRoot: boolean
}[]
}
+ get_job_methods_by_method_id: {
+ Args: {
+ mid: string
+ }
+ Returns: {
+ jobId: string
+ methodMaterialId: string
+ jobMakeMethodId: string
+ jobMaterialMakeMethodId: string
+ itemId: string
+ itemReadableId: string
+ description: string
+ unitOfMeasureCode: string
+ itemType: string
+ quantity: number
+ unitCost: number
+ methodType: Database["public"]["Enums"]["methodType"]
+ parentMaterialId: string
+ order: number
+ isRoot: boolean
+ }[]
+ }
get_method_tree: {
Args: {
uid: string
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 333480e92c..5586ac3a4b 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -23,6 +23,8 @@ const payloadValidator = z.object({
"itemToJobMakeMethod",
"itemToQuoteMakeMethod",
"itemToQuoteLine",
+ "jobToItem",
+ "jobMakeMethodToItem",
"quoteLineToItem",
"quoteLineToJob",
"quoteMakeMethodToItem",
@@ -928,6 +930,374 @@ serve(async (req: Request) => {
});
break;
}
+ case "jobMakeMethodToItem": {
+ const jobMakeMethodId = sourceId;
+ const itemId = targetId;
+
+ const [makeMethod, jobMakeMethod] = await Promise.all([
+ client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("jobMakeMethod")
+ .select("*")
+ .eq("id", jobMakeMethodId)
+ .single(),
+ ]);
+
+ if (makeMethod.error) {
+ throw new Error("Failed to get make method");
+ }
+
+ if (jobMakeMethod.error) {
+ throw new Error("Failed to get job make method");
+ }
+
+ const [jobOperations, jobParentMakeMethod] = await Promise.all([
+ client
+ .from("jobOperationsWithMakeMethods")
+ .select("*")
+ .eq("jobId", jobMakeMethod.data.jobId),
+ client
+ .from("jobMakeMethod")
+ .select("*")
+ .eq("jobId", jobMakeMethod.data.jobId)
+ .is("parentMaterialId", null)
+ .single(),
+ ]);
+
+ if (jobOperations.error) {
+ throw new Error("Failed to get job operations");
+ }
+
+ if (jobParentMakeMethod.error) {
+ throw new Error("Failed to get parent make method");
+ }
+
+ const [jobMethodTrees] = await Promise.all([
+ getJobMethodTree(client, jobParentMakeMethod.data.id),
+ ]);
+
+ if (jobMethodTrees.error) {
+ throw new Error("Failed to get method tree");
+ }
+
+ const fullJobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;
+ if (!fullJobMethodTree) throw new Error("Method tree not found");
+
+ let jobMethodTree: JobMethodTreeItem | null = null;
+
+ traverseJobMethod(fullJobMethodTree, (node: JobMethodTreeItem) => {
+ if (node.data.jobMaterialMakeMethodId === jobMakeMethodId) {
+ jobMethodTree = node;
+ return;
+ }
+ });
+ if (!jobMethodTree) throw new Error("Job method tree not found");
+
+ const madeItemIds: string[] = [];
+
+ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {
+ if (node.data.itemId && node.data.methodType === "Make") {
+ madeItemIds.push(node.data.itemId);
+ }
+ });
+
+ const makeMethods = await client
+ .from("makeMethod")
+ .select("*")
+ .in("itemId", madeItemIds);
+ if (makeMethods.error) {
+ throw new Error("Failed to get make methods");
+ }
+
+ const makeMethodByItemId: Record<string, string> = {};
+ makeMethods.data?.forEach((m) => {
+ makeMethodByItemId[m.itemId] = m.id;
+ });
+
+ await db.transaction().execute(async (trx) => {
+ let makeMethodsToDelete: string[] = [];
+ const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =
+ [];
+ const operationInserts: Database["public"]["Tables"]["methodOperation"]["Insert"][] =
+ [];
+
+ traverseJobMethod(jobMethodTree!, (node: JobMethodTreeItem) => {
+ if (node.data.itemId && node.data.methodType === "Make") {
+ makeMethodsToDelete.push(makeMethodByItemId[node.data.itemId]);
+ }
+
+ node.children.forEach((child) => {
+ materialInserts.push({
+ makeMethodId: makeMethodByItemId[node.data.itemId],
+ materialMakeMethodId: makeMethodByItemId[child.data.itemId],
+ itemId: child.data.itemId,
+ itemReadableId: child.data.itemReadableId,
+ itemType: child.data.itemType,
+ methodType: child.data.methodType,
+ order: child.data.order,
+ quantity: child.data.quantity,
+ unitOfMeasureCode: child.data.unitOfMeasureCode,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ });
+ });
+ });
+
+ if (makeMethodsToDelete.length > 0) {
+ makeMethodsToDelete = makeMethodsToDelete.map((mm) =>
+ mm === makeMethodByItemId[jobMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : mm
+ );
+ await Promise.all([
+ trx
+ .deleteFrom("methodMaterial")
+ .where("makeMethodId", "in", makeMethodsToDelete)
+ .execute(),
+ trx
+ .deleteFrom("methodOperation")
+ .where("makeMethodId", "in", makeMethodsToDelete)
+ .execute(),
+ ]);
+ }
+
+ if (materialInserts.length > 0) {
+ await trx
+ .insertInto("methodMaterial")
+ .values(
+ materialInserts.map((insert) => ({
+ ...insert,
+ makeMethodId:
+ insert.makeMethodId ===
+ makeMethodByItemId[jobMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : insert.makeMethodId,
+ itemId:
+ insert.itemId === jobMakeMethod.data.itemId
+ ? itemId
+ : insert.itemId,
+ }))
+ )
+ .execute();
+ }
+
+ jobOperations.data?.forEach((op) => {
+ operationInserts.push({
+ makeMethodId: op.makeMethodId!,
+ processId: op.processId!,
+ workCenterId: op.workCenterId,
+ description: op.description ?? "",
+ setupTime: op.setupTime ?? 0,
+ setupUnit: op.setupUnit ?? "Total Minutes",
+ laborTime: op.laborTime ?? 0,
+ laborUnit: op.laborUnit ?? "Minutes/Piece",
+ machineTime: op.machineTime ?? 0,
+ machineUnit: op.machineUnit ?? "Minutes/Piece",
+ order: op.order ?? 1,
+ operationOrder: op.operationOrder ?? "After Previous",
+ operationType: op.operationType ?? "Inside",
+ workInstruction: op.workInstruction,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ });
+ });
+
+ if (operationInserts.length > 0) {
+ await trx
+ .insertInto("methodOperation")
+ .values(
+ operationInserts.map((insert) => ({
+ ...insert,
+ makeMethodId:
+ insert.makeMethodId ===
+ makeMethodByItemId[jobMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : insert.makeMethodId,
+ }))
+ )
+ .execute();
+ }
+ });
+
+ break;
+ }
+ case "jobToItem": {
+ const jobId = sourceId;
+ if (!jobId) {
+ throw new Error("Invalid sourceId");
+ }
+ const itemId = targetId;
+
+ const [makeMethod, jobMakeMethod, jobOperations] = await Promise.all([
+ client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("jobMakeMethod")
+ .select("*")
+ .eq("jobId", jobId)
+ .is("parentMaterialId", null)
+ .single(),
+ client
+ .from("jobOperationsWithMakeMethods")
+ .select("*")
+ .eq("jobId", jobId),
+ ]);
+
+ if (makeMethod.error) {
+ throw new Error("Failed to get make method");
+ }
+
+ if (jobMakeMethod.error) {
+ throw new Error("Failed to get job make method");
+ }
+
+ if (jobOperations.error) {
+ throw new Error("Failed to get job operations");
+ }
+
+ const [jobMethodTrees] = await Promise.all([
+ getJobMethodTree(client, jobMakeMethod.data.id),
+ ]);
+
+ if (jobMethodTrees.error) {
+ throw new Error("Failed to get method tree");
+ }
+
+ const jobMethodTree = jobMethodTrees.data?.[0] as JobMethodTreeItem;
+ if (!jobMethodTree) throw new Error("Method tree not found");
+
+ const madeItemIds: string[] = [];
+
+ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {
+ if (node.data.itemId && node.data.methodType === "Make") {
+ madeItemIds.push(node.data.itemId);
+ }
+ });
+
+ const makeMethods = await client
+ .from("makeMethod")
+ .select("*")
+ .in("itemId", madeItemIds);
+ if (makeMethods.error) {
+ throw new Error("Failed to get make methods");
+ }
+
+ const makeMethodByItemId: Record<string, string> = {};
+ makeMethods.data?.forEach((m) => {
+ makeMethodByItemId[m.itemId] = m.id;
+ });
+
+ await db.transaction().execute(async (trx) => {
+ let makeMethodsToDelete: string[] = [];
+ const materialInserts: Database["public"]["Tables"]["methodMaterial"]["Insert"][] =
+ [];
+ const operationInserts: Database["public"]["Tables"]["methodOperation"]["Insert"][] =
+ [];
+
+ traverseJobMethod(jobMethodTree, (node: JobMethodTreeItem) => {
+ if (node.data.itemId && node.data.methodType === "Make") {
+ makeMethodsToDelete.push(makeMethodByItemId[node.data.itemId]);
+ }
+
+ node.children.forEach((child) => {
+ materialInserts.push({
+ makeMethodId: makeMethodByItemId[node.data.itemId],
+ materialMakeMethodId: makeMethodByItemId[child.data.itemId],
+ itemId: child.data.itemId,
+ itemReadableId: child.data.itemReadableId,
+ itemType: child.data.itemType,
+ methodType: child.data.methodType,
+ order: child.data.order,
+ quantity: child.data.quantity,
+ unitOfMeasureCode: child.data.unitOfMeasureCode,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ });
+ });
+ });
+
+ if (makeMethodsToDelete.length > 0) {
+ makeMethodsToDelete = makeMethodsToDelete.map((mm) =>
+ mm === makeMethodByItemId[jobMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : mm
+ );
+ await Promise.all([
+ trx
+ .deleteFrom("methodMaterial")
+ .where("makeMethodId", "in", makeMethodsToDelete)
+ .execute(),
+ trx
+ .deleteFrom("methodOperation")
+ .where("makeMethodId", "in", makeMethodsToDelete)
+ .execute(),
+ ]);
+ }
+
+ if (materialInserts.length > 0) {
+ await trx
+ .insertInto("methodMaterial")
+ .values(
+ materialInserts.map((insert) => ({
+ ...insert,
+ makeMethodId:
+ insert.makeMethodId ===
+ makeMethodByItemId[jobMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : insert.makeMethodId,
+ itemId:
+ insert.itemId === jobMakeMethod.data.itemId
+ ? itemId
+ : insert.itemId,
+ }))
+ )
+ .execute();
+ }
+
+ jobOperations.data?.forEach((op) => {
+ operationInserts.push({
+ makeMethodId: op.makeMethodId!,
+ processId: op.processId!,
+ workCenterId: op.workCenterId,
+ description: op.description ?? "",
+ setupTime: op.setupTime ?? 0,
+ setupUnit: op.setupUnit ?? "Total Minutes",
+ laborTime: op.laborTime ?? 0,
+ laborUnit: op.laborUnit ?? "Minutes/Piece",
+ machineTime: op.machineTime ?? 0,
+ machineUnit: op.machineUnit ?? "Minutes/Piece",
+ order: op.order ?? 1,
+ operationOrder: op.operationOrder ?? "After Previous",
+ operationType: op.operationType ?? "Inside",
+ operationSupplierProcessId: op.operationSupplierProcessId,
+ workInstruction: op.workInstruction,
+ companyId,
+ createdBy: userId,
+ customFields: {},
+ });
+ });
+
+ if (operationInserts.length > 0) {
+ await trx
+ .insertInto("methodOperation")
+ .values(
+ operationInserts.map((insert) => ({
+ ...insert,
+ makeMethodId:
+ insert.makeMethodId ===
+ makeMethodByItemId[jobMakeMethod.data.itemId]
+ ? makeMethod.data.id
+ : insert.makeMethodId,
+ }))
+ )
+ .execute();
+ }
+ });
+
+ break;
+ }
case "quoteLineToItem": {
const [quoteId, quoteLineId] = (sourceId as string).split(":");
if (!quoteId || !quoteLineId) {
@@ -1638,6 +2008,90 @@ function traverseQuoteMethod(
}
}
+type JobMethod = NonNullable<
+ Awaited<ReturnType<typeof getJobMethodTreeArray>>["data"]
+>[number];
+type JobMethodTreeItem = {
+ id: string;
+ data: JobMethod;
+ children: JobMethodTreeItem[];
+};
+
+export async function getJobMethodTree(
+ client: SupabaseClient<Database>,
+ methodId: string
+) {
+ const items = await getJobMethodTreeArray(client, methodId);
+ if (items.error) return items;
+
+ const tree = getJobMethodTreeArrayToTree(items.data);
+
+ return {
+ data: tree,
+ error: null,
+ };
+}
+
+export function getJobMethodTreeArray(
+ client: SupabaseClient<Database>,
+ methodId: string
+) {
+ return client.rpc("get_job_methods_by_method_id", {
+ mid: methodId,
+ });
+}
+
+function getJobMethodTreeArrayToTree(items: JobMethod[]): JobMethodTreeItem[] {
+ // function traverseAndRenameIds(node: JobMethodTreeItem) {
+ // const clone = structuredClone(node);
+ // clone.id = `node-${Math.random().toString(16).slice(2)}`;
+ // clone.children = clone.children.map((n) => traverseAndRenameIds(n));
+ // return clone;
+ // }
+
+ const rootItems: JobMethodTreeItem[] = [];
+ const lookup: { [id: string]: JobMethodTreeItem } = {};
+
+ for (const item of items) {
+ const itemId = item.methodMaterialId;
+ const parentId = item.parentMaterialId;
+
+ if (!Object.prototype.hasOwnProperty.call(lookup, itemId)) {
+ // @ts-ignore - we don't add data here
+ lookup[itemId] = { id: itemId, children: [] };
+ }
+
+ lookup[itemId]["data"] = item;
+
+ const treeItem = lookup[itemId];
+
+ if (parentId === null || parentId === undefined) {
+ rootItems.push(treeItem);
+ } else {
+ if (!Object.prototype.hasOwnProperty.call(lookup, parentId)) {
+ // @ts-ignore - we don't add data here
+ lookup[parentId] = { id: parentId, children: [] };
+ }
+
+ lookup[parentId]["children"].push(treeItem);
+ }
+ }
+ return rootItems;
+}
+
+function traverseJobMethod(
+ node: JobMethodTreeItem,
+ callback: (node: JobMethodTreeItem) => void
+) {
+ callback(node);
+
+ if (node.children) {
+ for (const child of node.children) {
+ traverseJobMethod(child, callback);
+ }
+ }
+}
+
const getRatesFromWorkCenters =
(workCenters: Database["public"]["Views"]["workCenters"]["Row"][] | null) =>
(
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 86b30a960e..e2f354d554 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -28790,6 +28790,28 @@ export type Database = {
isRoot: boolean
}[]
}
+ get_job_methods_by_method_id: {
+ Args: {
+ mid: string
+ }
+ Returns: {
+ jobId: string
+ methodMaterialId: string
+ jobMakeMethodId: string
+ jobMaterialMakeMethodId: string
+ itemId: string
+ itemReadableId: string
+ description: string
+ unitOfMeasureCode: string
+ itemType: string
+ quantity: number
+ unitCost: number
+ methodType: Database["public"]["Enums"]["methodType"]
+ parentMaterialId: string
+ order: number
+ isRoot: boolean
+ }[]
+ }
get_method_tree: {
Args: {
uid: string
diff --git a/packages/database/supabase/migrations/20240915192542_job-methods.sql b/packages/database/supabase/migrations/20240915192542_job-methods.sql
index 07b8ac2c1a..a96b7759ac 100644
--- a/packages/database/supabase/migrations/20240915192542_job-methods.sql
+++ b/packages/database/supabase/migrations/20240915192542_job-methods.sql
@@ -204,6 +204,16 @@ CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true)
LEFT JOIN "jobMakeMethod" jmm
ON jmm."parentMaterialId" = jm."id";
+CREATE OR REPLACE VIEW "jobOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ jo.*
+ FROM "jobOperation" jo
+ INNER JOIN "jobMakeMethod" jmm
+ ON jo."jobMakeMethodId" = jmm.id
+ LEFT JOIN "makeMethod" mm
+ ON jmm."itemId" = mm."itemId";
+
CREATE OR REPLACE FUNCTION get_job_method(jid TEXT)
RETURNS TABLE (
"jobId" TEXT,
@@ -423,3 +433,78 @@ CREATE POLICY "Customers with production_view can view their own job make method
)
)
);
+
+CREATE OR REPLACE FUNCTION get_job_methods_by_method_id(mid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" TEXT,
+ "description" TEXT,
+ "unitOfMeasureCode" TEXT,
+ "itemType" TEXT,
+ "quantity" NUMERIC,
+ "unitCost" NUMERIC,
+ "methodType" "methodType",
+ "parentMaterialId" TEXT,
+ "order" DOUBLE PRECISION,
+ "isRoot" BOOLEAN
+) AS $$
+WITH RECURSIVE material AS (
+ SELECT
+ "jobId",
+ "id",
+ "id" AS "jobMakeMethodId",
+ 'Make'::"methodType" AS "methodType",
+ "id" AS "jobMaterialMakeMethodId",
+ "itemId",
+ 'Part' AS "itemType",
+ 1::NUMERIC(10,4) AS "quantity",
+ 0::NUMERIC(10,4) AS "unitCost",
+ "parentMaterialId",
+ CAST(1 AS DOUBLE PRECISION) AS "order",
+ TRUE AS "isRoot"
+ FROM
+ "jobMakeMethod"
+ WHERE
+ "id" = mid
+ UNION
+ SELECT
+ child."jobId",
+ child."id",
+ child."jobMakeMethodId",
+ child."methodType",
+ child."jobMaterialMakeMethodId",
+ child."itemId",
+ child."itemType",
+ child."quantity",
+ child."unitCost",
+ parent."id" AS "parentMaterialId",
+ child."order",
+ FALSE AS "isRoot"
+ FROM
+ "jobMaterialWithMakeMethodId" child
+ INNER JOIN material parent ON parent."jobMaterialMakeMethodId" = child."jobMakeMethodId"
+)
+SELECT
+ material."jobId",
+ material.id as "methodMaterialId",
+ material."jobMakeMethodId",
+ material."jobMaterialMakeMethodId",
+ material."itemId",
+ item."readableId" AS "itemReadableId",
+ item."name" AS "description",
+ item."unitOfMeasureCode",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
\ No newline at end of file