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: job bill of material and bill of process

Brad Barbin95a7976ce3a4
diff --git a/apps/carbon/app/modules/production/production.models.ts b/apps/carbon/app/modules/production/production.models.ts
index efc7834b9f..c197e89363 100644
--- a/apps/carbon/app/modules/production/production.models.ts
+++ b/apps/carbon/app/modules/production/production.models.ts
@@ -1,5 +1,12 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
+import {
+ methodItemType,
+ methodOperationOrders,
+ methodType,
+ operationTypes,
+ standardFactorType,
+} from "../shared";
export const deadlineTypes = [
"ASAP",
@@ -50,3 +57,303 @@ export const jobValidator = z
path: ["dueDate"],
}
);
+
+export const jobOperationValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ jobMakeMethodId: z
+ .string()
+ .min(1, { message: "Quote Make Method is required" }),
+ order: zfd.numeric(z.number().min(0)),
+ operationOrder: z.enum(methodOperationOrders, {
+ errorMap: (issue, ctx) => ({
+ message: "Operation order is required",
+ }),
+ }),
+ operationType: z.enum(operationTypes, {
+ errorMap: (issue, ctx) => ({
+ message: "Operation type is required",
+ }),
+ }),
+ processId: z.string().min(20, { message: "Process is required" }),
+ workCenterId: zfd.text(z.string().optional()),
+ description: zfd.text(
+ z.string().min(0, { message: "Description is required" })
+ ),
+ setupUnit: z
+ .enum(standardFactorType, {
+ errorMap: () => ({ message: "Setup unit is required" }),
+ })
+ .optional(),
+ setupTime: zfd.numeric(z.number().min(0).optional()),
+ laborUnit: z
+ .enum(standardFactorType, {
+ errorMap: () => ({ message: "Labor unit is required" }),
+ })
+ .optional(),
+ laborTime: zfd.numeric(z.number().min(0).optional()),
+ machineUnit: z
+ .enum(standardFactorType, {
+ errorMap: () => ({ message: "Machine unit is required" }),
+ })
+ .optional(),
+ machineTime: zfd.numeric(z.number().min(0).optional()),
+ machineRate: zfd.numeric(z.number().min(0).optional()),
+ overheadRate: zfd.numeric(z.number().min(0).optional()),
+ laborRate: zfd.numeric(z.number().min(0).optional()),
+ operationSupplierProcessId: zfd.text(z.string().optional()),
+ operationMinimumCost: zfd.numeric(z.number().min(0).optional()),
+ operationUnitCost: zfd.numeric(z.number().min(0).optional()),
+ operationLeadTime: zfd.numeric(z.number().min(0).optional()),
+ })
+ .refine(
+ (data) => {
+ if (data.operationType === "Outside") {
+ return Number.isFinite(data.operationMinimumCost);
+ }
+ return true;
+ },
+ {
+ message: "Minimum is required",
+ path: ["operationMinimumCost"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Outside") {
+ return Number.isFinite(data.operationUnitCost);
+ }
+ return true;
+ },
+ {
+ message: "Unit cost is required",
+ path: ["operationUnitCost"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Outside") {
+ return Number.isFinite(data.operationLeadTime);
+ }
+ return true;
+ },
+ {
+ message: "Lead time is required",
+ path: ["operationLeadTime"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return !!data.setupUnit;
+ }
+ return true;
+ },
+ {
+ message: "Setup unit is required",
+ path: ["setupUnit"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return !!data.laborUnit;
+ }
+ return true;
+ },
+ {
+ message: "Labor unit is required",
+ path: ["laborUnit"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return !!data.laborUnit;
+ }
+ return true;
+ },
+ {
+ message: "Machine unit is required",
+ path: ["machineUnit"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return Number.isFinite(data.setupTime);
+ }
+ return true;
+ },
+ {
+ message: "Setup time is required",
+ path: ["setupTime"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return Number.isFinite(data.laborTime);
+ }
+ return true;
+ },
+ {
+ message: "Labor time is required",
+ path: ["laborTime"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return Number.isFinite(data.machineTime);
+ }
+ return true;
+ },
+ {
+ message: "Machine time is required",
+ path: ["machineTime"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return Number.isFinite(data.machineRate);
+ }
+ return true;
+ },
+ {
+ message: "Machine rate is required",
+ path: ["machineRate"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return Number.isFinite(data.overheadRate);
+ }
+ return true;
+ },
+ {
+ message: "Overhead rate is required",
+ path: ["overheadRate"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.operationType === "Inside") {
+ return Number.isFinite(data.laborRate);
+ }
+ return true;
+ },
+ {
+ message: "Labor rate is required",
+ path: ["laborRate"],
+ }
+ );
+export const jobMaterialValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ jobMakeMethodId: z.string().min(20, { message: "Make method is required" }),
+ order: zfd.numeric(z.number().min(0)),
+ itemType: z.enum(methodItemType, {
+ errorMap: (issue, ctx) => ({
+ message: "Item type is required",
+ }),
+ }),
+ methodType: z.enum(methodType, {
+ errorMap: (issue, ctx) => ({
+ message: "Method type is required",
+ }),
+ }),
+ itemId: z.string().min(1, { message: "Item is required" }),
+ itemReadableId: z.string().min(1, { message: "Item ID is required" }),
+ description: z.string().min(1, { message: "Description is required" }),
+ quoteOperationId: zfd.text(z.string().optional()),
+ quantity: zfd.numeric(z.number().min(0)),
+ unitCost: zfd.numeric(z.number().min(0)),
+ unitOfMeasureCode: z
+ .string()
+ .min(1, { message: "Unit of Measure is required" }),
+ })
+ .refine(
+ (data) => {
+ if (data.itemType === "Part") {
+ return !!data.itemReadableId;
+ }
+ return true;
+ },
+ {
+ message: "Part ID is required",
+ path: ["itemId"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.itemType === "Material") {
+ return !!data.itemReadableId;
+ }
+ return true;
+ },
+ {
+ message: "Material ID is required",
+ path: ["itemId"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.itemType === "Fixture") {
+ return !!data.itemReadableId;
+ }
+ return true;
+ },
+ {
+ message: "Fixture ID is required",
+ path: ["itemId"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.itemType === "Tool") {
+ return !!data.itemReadableId;
+ }
+ return true;
+ },
+ {
+ message: "Tool ID is required",
+ path: ["itemId"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.itemType === "Consumable") {
+ return !!data.itemReadableId;
+ }
+ return true;
+ },
+ {
+ message: "Consumable ID is required",
+ path: ["itemId"],
+ }
+ )
+ .refine(
+ (data) => {
+ if (data.itemType === "Service") {
+ return !!data.itemReadableId;
+ }
+ return true;
+ },
+ {
+ message: "Service ID is required",
+ path: ["itemId"],
+ }
+ );
+
+export const getJobMethodValidator = z.object({
+ jobId: z.string().min(1, { message: "Job ID 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 dd3f7f1803..15ce226d04 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -1,11 +1,16 @@
import type { Database, Json } from "@carbon/database";
-import type { SupabaseClient } from "@supabase/supabase-js";
+import type { PostgrestError, SupabaseClient } from "@supabase/supabase-js";
import type { z } from "zod";
import type { StorageItem } from "~/types";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
-import type { jobValidator } from "./production.models";
+import type {
+ getJobMaterialMethodValidator,
+ jobMaterialValidator,
+ jobOperationValidator,
+ jobValidator,
+} from "./production.models";
import type { Job } from "./types";
export async function deleteJob(
@@ -86,6 +91,78 @@ export async function getJobsList(
.order("jobId");
}
+export async function getJobMethodTree(
+ client: SupabaseClient<Database>,
+ jobId: string
+) {
+ const items = await getJobMethodTreeArray(client, jobId);
+ if (items.error) return items;
+
+ const tree = getJobMethodTreeArrayToTree(items.data);
+
+ return {
+ data: tree,
+ error: null,
+ };
+}
+
+export async function getJobMethodTreeArray(
+ client: SupabaseClient<Database>,
+ jobId: string
+) {
+ return client.rpc("get_job_method", {
+ jid: jobId,
+ });
+}
+
+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
+ 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
+ lookup[parentId] = { id: parentId, children: [] };
+ }
+
+ lookup[parentId]["children"].push(treeItem);
+ }
+ }
+ return rootItems;
+ // return rootItems.map((item) => traverseAndRenameIds(item));
+}
+
+export type JobMethod = NonNullable<
+ Awaited<ReturnType<typeof getJobMethodTreeArray>>["data"]
+>[number];
+type JobMethodTreeItem = {
+ id: string;
+ data: JobMethod;
+ children: JobMethodTreeItem[];
+};
+
export async function upsertJob(
client: SupabaseClient<Database>,
job:
@@ -113,3 +190,202 @@ export async function upsertJob(
return client.from("job").insert([job]).select("id").single();
}
}
+
+export async function getJobMaterial(
+ client: SupabaseClient<Database>,
+ materialId: string
+) {
+ return client
+ .from("jobMaterialWithMakeMethodId")
+ .select("*")
+ .eq("id", materialId)
+ .single();
+}
+
+export async function getJobMaterialsByMethodId(
+ client: SupabaseClient<Database>,
+ jobMakeMethodId: string
+) {
+ return client
+ .from("jobMaterial")
+ .select("*")
+ .eq("jobMakeMethodId", jobMakeMethodId)
+ .order("order", { ascending: true });
+}
+
+export async function getJobOperation(
+ client: SupabaseClient<Database>,
+ jobOperationId: string
+) {
+ return client
+ .from("jobOperation")
+ .select("*")
+ .eq("id", jobOperationId)
+ .single();
+}
+
+export async function getJobOperationsByMethodId(
+ client: SupabaseClient<Database>,
+ jobMakeMethodId: string
+) {
+ return client
+ .from("jobOperation")
+ .select("*")
+ .eq("jobMakeMethodId", jobMakeMethodId)
+ .order("order", { ascending: true });
+}
+
+export async function updateJobMaterialOrder(
+ client: SupabaseClient<Database>,
+ updates: {
+ id: string;
+ order: number;
+ updatedBy: string;
+ }[]
+) {
+ const updatePromises = updates.map(({ id, order, updatedBy }) =>
+ client.from("jobMaterial").update({ order, updatedBy }).eq("id", id)
+ );
+ return Promise.all(updatePromises);
+}
+
+export async function updateJobOperationOrder(
+ client: SupabaseClient<Database>,
+ updates: {
+ id: string;
+ order: number;
+ updatedBy: string;
+ }[]
+) {
+ const updatePromises = updates.map(({ id, order, updatedBy }) =>
+ client.from("jobOperation").update({ order, updatedBy }).eq("id", id)
+ );
+ return Promise.all(updatePromises);
+}
+
+export async function upsertJobMaterial(
+ client: SupabaseClient<Database>,
+ jobMaterial:
+ | (Omit<z.infer<typeof jobMaterialValidator>, "id"> & {
+ jobId: string;
+ jobOperationId?: string;
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof jobMaterialValidator>, "id"> & {
+ id: string;
+ jobId: string;
+ jobOperationId?: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("id" in jobMaterial) {
+ return client
+ .from("jobMaterial")
+ .update(sanitize(jobMaterial))
+ .eq("id", jobMaterial.id)
+ .select("id, methodType")
+ .single();
+ }
+ return client
+ .from("jobMaterial")
+ .insert([jobMaterial])
+ .select("id, methodType")
+ .single();
+}
+
+export async function upsertJobOperation(
+ client: SupabaseClient<Database>,
+ jobOperation:
+ | (Omit<z.infer<typeof jobOperationValidator>, "id"> & {
+ jobId: string;
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof jobOperationValidator>, "id"> & {
+ id: string;
+ jobId: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("id" in jobOperation) {
+ return client
+ .from("jobOperation")
+ .update(sanitize(jobOperation))
+ .eq("id", jobOperation.id)
+ .select("id")
+ .single();
+ }
+ return client
+ .from("jobOperation")
+ .insert([jobOperation])
+ .select("id")
+ .single();
+}
+
+export async function upsertJobMethod(
+ client: SupabaseClient<Database>,
+ jobMethod: {
+ itemId: string;
+ jobId: string;
+ companyId: string;
+ userId: string;
+ }
+) {
+ return client.functions.invoke("get-method", {
+ body: {
+ type: "itemToJob",
+ sourceId: jobMethod.itemId,
+ targetId: jobMethod.jobId,
+ companyId: jobMethod.companyId,
+ userId: jobMethod.userId,
+ },
+ });
+}
+
+export async function upsertJobMaterialMakeMethod(
+ client: SupabaseClient<Database>,
+ jobMaterial: z.infer<typeof getJobMaterialMethodValidator> & {
+ companyId: string;
+ createdBy: string;
+ }
+) {
+ const makeMethod = await client
+ .from("jobMakeMethod")
+ .select("id")
+ .eq("parentMaterialId", jobMaterial.jobMaterialId)
+ .single();
+ if (makeMethod.error) {
+ return makeMethod;
+ }
+
+ const { error } = await client.functions.invoke("get-method", {
+ body: {
+ type: "itemToJobMakeMethod",
+ sourceId: jobMaterial.itemId,
+ targetId: makeMethod.data.id,
+ companyId: jobMaterial.companyId,
+ userId: jobMaterial.createdBy,
+ },
+ });
+
+ if (error) {
+ return {
+ data: null,
+ error: { message: "Failed to pull method" } as PostgrestError,
+ };
+ }
+
+ return { data: null, error: null };
+}
+
+export async function deleteJobMaterial(
+ client: SupabaseClient<Database>,
+ jobMaterialId: string
+) {
+ return client.from("jobMaterial").delete().eq("id", jobMaterialId);
+}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
new file mode 100644
index 0000000000..adee5ae761
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfMaterial.tsx
@@ -0,0 +1,616 @@
+"use client";
+import { ValidatedForm } from "@carbon/form";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ cn,
+ HStack,
+ toast,
+ useDebounce,
+ VStack,
+} from "@carbon/react";
+import { useFetcher, useParams } from "@remix-run/react";
+import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
+import type { Dispatch, SetStateAction } from "react";
+import { useCallback, useEffect, useState } from "react";
+import { flushSync } from "react-dom";
+import { LuSettings2, LuX } from "react-icons/lu";
+import type { z } from "zod";
+import { MethodIcon, MethodItemTypeIcon } from "~/components";
+import {
+ DefaultMethodType,
+ Hidden,
+ InputControlled,
+ Item,
+ Number,
+ NumberControlled,
+ Select,
+ Submit,
+ UnitOfMeasure,
+} from "~/components/Form";
+import type {
+ Item as SortableItem,
+ SortableItemRenderProps,
+} from "~/components/SortableList";
+import { SortableList, SortableListItem } from "~/components/SortableList";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { MethodItemType, MethodType } from "~/modules/shared";
+import { path } from "~/utils/path";
+import type { jobOperationValidator } from "../../production.models";
+import { jobMaterialValidator } from "../../production.models";
+import type { Job } from "../../types";
+
+type Material = z.infer<typeof jobMaterialValidator>;
+
+type Operation = z.infer<typeof jobOperationValidator>;
+
+type ItemWithData = SortableItem & {
+ data: Material;
+};
+
+type JobBillOfMaterialProps = {
+ jobMakeMethodId: string;
+ materials: Material[];
+ operations: Operation[];
+};
+
+function makeItems(materials: Material[]): ItemWithData[] {
+ return materials.map(makeItem);
+}
+
+function makeItem(material: Material): ItemWithData {
+ return {
+ id: material.id!,
+ title: (
+ <VStack spacing={0} className="py-2.5">
+ <h4 className="flex tracking-tighter text-base md:text-lg truncate">
+ {material.itemReadableId}
+ </h4>
+ {material?.description && (
+ <span className="text-xs text-muted-foreground">
+ {material.description}{" "}
+ </span>
+ )}
+ </VStack>
+ ),
+ checked: false,
+ details: (
+ <HStack spacing={2}>
+ <Badge variant="secondary">
+ <MethodIcon type={material.methodType} />
+ </Badge>
+
+ <Badge variant="secondary">{material.quantity}</Badge>
+ <Badge variant="secondary">
+ <MethodItemTypeIcon type={material.itemType} />
+ </Badge>
+ </HStack>
+ ),
+ data: material,
+ };
+}
+
+const initialMethodMaterial: Omit<Material, "jobMakeMethodId" | "order"> & {
+ description: string;
+} = {
+ itemId: "",
+ itemReadableId: "",
+ itemType: "Part" as const,
+ methodType: "Buy" as const,
+ description: "",
+ quantity: 1,
+ unitCost: 0,
+ unitOfMeasureCode: "EA",
+};
+
+const JobBillOfMaterial = ({
+ jobMakeMethodId,
+ materials,
+ operations,
+}: JobBillOfMaterialProps) => {
+ const { jobId } = useParams();
+ if (!jobId) throw new Error("jobId not found");
+
+ const fetcher = useFetcher<{}>();
+ const permissions = usePermissions();
+
+ const [items, setItems] = useState<ItemWithData[]>(
+ makeItems(materials ?? [])
+ );
+ const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
+
+ const jobData = useRouteData<{ job: Job }>(path.to.job(jobId));
+ const isDisabled = jobData?.job?.status !== "Draft";
+
+ const onToggleItem = (id: string) => {
+ if (!permissions.can("update", "production") || isDisabled) return;
+ setItems((prevItems) =>
+ prevItems.map((item) =>
+ item.id === id ? { ...item, checked: !item.checked } : item
+ )
+ );
+ };
+
+ // we create a temporary item and append it to the list
+ const onAddItem = () => {
+ if (!permissions.can("update", "production") || isDisabled) return;
+ const temporaryId = Math.random().toString(16).slice(2);
+ setSelectedItemId(temporaryId);
+ setItems((prevItems) => {
+ let newOrder = 1;
+ if (prevItems.length) {
+ newOrder = prevItems[prevItems.length - 1].data.order + 1;
+ }
+
+ return [
+ ...prevItems,
+ {
+ title: "",
+ checked: false,
+ id: temporaryId,
+ data: {
+ ...initialMethodMaterial,
+ order: newOrder,
+ jobMakeMethodId,
+ },
+ },
+ ];
+ });
+ };
+
+ const onRemoveItem = async (id: string) => {
+ if (!permissions.can("update", "production") || isDisabled) return;
+ // get the item and it's order in the list
+ const itemIndex = items.findIndex((i) => i.id === id);
+ const item = items[itemIndex];
+
+ setItems((prevItems) => prevItems.filter((item) => item.id !== id));
+
+ fetcher.submit(new FormData(), {
+ method: "post",
+ action: path.to.deleteJobMaterial(jobId, item.id),
+ });
+ };
+
+ const onReorder = (reorderedItems: ItemWithData[]) => {
+ if (!permissions.can("update", "production") || isDisabled) return;
+ const newItems = reorderedItems.map((item, index) => ({
+ ...item,
+ data: {
+ ...item.data,
+ order: index + 1,
+ },
+ }));
+ const updates = newItems.reduce<Record<string, number>>((acc, item) => {
+ if (!isTemporaryId(item.id)) {
+ acc[item.id] = item.data.order;
+ }
+ return acc;
+ }, {});
+
+ setItems(reorderedItems);
+ updateSortOrder(updates);
+ };
+
+ const updateSortOrder = useDebounce((updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ fetcher.submit(formData, {
+ method: "post",
+ action: path.to.jobMaterialsOrder,
+ });
+ }, 1000);
+
+ const onCloseOnDrag = useCallback(() => {
+ setItems((prevItems) => {
+ const updatedItems = prevItems.map((item) =>
+ item.checked ? { ...item, checked: false } : item
+ );
+ return updatedItems.some(
+ (item, index) => item.checked !== prevItems[index].checked
+ )
+ ? updatedItems
+ : prevItems;
+ });
+ }, []);
+
+ const renderListItem = ({
+ item,
+ items,
+ order,
+ onToggleItem,
+ onRemoveItem,
+ }: SortableItemRenderProps<ItemWithData>) => {
+ const isOpen = item.id === selectedItemId;
+
+ return (
+ <SortableListItem<Material>
+ item={item}
+ items={items}
+ order={order}
+ key={item.id}
+ isExpanded={isOpen}
+ onSelectItem={setSelectedItemId}
+ onToggleItem={onToggleItem}
+ onRemoveItem={onRemoveItem}
+ handleDrag={onCloseOnDrag}
+ className="my-2 "
+ renderExtra={(item) => (
+ <div
+ key={`${isOpen}`}
+ className={cn(
+ "flex h-full flex-col items-center justify-center pl-2",
+ isOpen ? "py-1" : "py-3 "
+ )}
+ >
+ <motion.button
+ layout
+ onClick={
+ isOpen
+ ? () => {
+ if (isTemporaryId(item.id)) {
+ setItems((prevItems) =>
+ prevItems.filter((i) => i.id !== item.id)
+ );
+ }
+ setSelectedItemId(null);
+ }
+ : () => {
+ setSelectedItemId(item.id);
+ }
+ }
+ key="collapse"
+ className={cn(
+ isOpen
+ ? "absolute right-3 top-3 z-10 "
+ : "relative z-10 ml-auto mr-3 "
+ )}
+ >
+ {isOpen ? (
+ <motion.span
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ exit={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ duration: 1.95,
+ }}
+ >
+ <LuX className="h-5 w-5 text-foreground" />
+ </motion.span>
+ ) : (
+ <motion.span
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ exit={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ duration: 0.95,
+ }}
+ >
+ <LuSettings2 className="stroke-1 h-5 w-5 text-foreground/80 hover:stroke-primary/70 " />
+ </motion.span>
+ )}
+ </motion.button>
+
+ <LayoutGroup id={`${item.id}`}>
+ <AnimatePresence mode="popLayout">
+ {isOpen ? (
+ <motion.div className="flex w-full flex-col ">
+ <div className=" w-full p-2">
+ <motion.div
+ initial={{
+ y: 0,
+ opacity: 0,
+ filter: "blur(4px)",
+ }}
+ animate={{
+ y: 0,
+ opacity: 1,
+ filter: "blur(0px)",
+ }}
+ transition={{
+ type: "spring",
+ duration: 0.15,
+ }}
+ layout
+ className="w-full "
+ >
+ <motion.div
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ bounce: 0.2,
+ duration: 0.75,
+ delay: 0.15,
+ }}
+ >
+ <MaterialForm
+ item={item}
+ isDisabled={isDisabled}
+ setItems={setItems}
+ setSelectedItemId={setSelectedItemId}
+ jobOperations={operations}
+ />
+ </motion.div>
+ </motion.div>
+ </div>
+ </motion.div>
+ ) : null}
+ </AnimatePresence>
+ </LayoutGroup>
+ </div>
+ )}
+ />
+ );
+ };
+
+ return (
+ <Card>
+ <HStack className="justify-between">
+ <CardHeader>
+ <CardTitle>Bill of Material</CardTitle>
+ </CardHeader>
+
+ <CardAction>
+ <Button
+ variant="secondary"
+ isDisabled={
+ isDisabled ||
+ !permissions.can("update", "production") ||
+ selectedItemId !== null
+ }
+ onClick={onAddItem}
+ >
+ Add Material
+ </Button>
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <SortableList
+ items={items}
+ onReorder={onReorder}
+ onToggleItem={onToggleItem}
+ onRemoveItem={onRemoveItem}
+ renderItem={renderListItem}
+ />
+ </CardContent>
+ </Card>
+ );
+};
+
+export default JobBillOfMaterial;
+
+function isTemporaryId(id: string) {
+ return id.length < 20;
+}
+
+function MaterialForm({
+ item,
+ isDisabled,
+ setItems,
+ setSelectedItemId,
+ jobOperations,
+}: {
+ item: ItemWithData;
+ isDisabled: boolean;
+ setItems: Dispatch<SetStateAction<ItemWithData[]>>;
+ setSelectedItemId: Dispatch<SetStateAction<string | null>>;
+ jobOperations: Operation[];
+}) {
+ const { jobId } = useParams();
+ if (!jobId) throw new Error("jobId not found");
+
+ const { supabase } = useSupabase();
+ const methodMaterialFetcher = useFetcher<{ id: string }>();
+ const params = useParams();
+ const { company } = useUser();
+
+ useEffect(() => {
+ // replace the temporary id with the actual id
+ if (methodMaterialFetcher.data && methodMaterialFetcher.data.id) {
+ flushSync(() => {
+ setItems((prevItems) =>
+ prevItems.map((i) =>
+ i.id === item.id
+ ? {
+ ...i,
+ id: methodMaterialFetcher.data!.id!,
+ data: {
+ ...i.data,
+ ...methodMaterialFetcher.data,
+ },
+ }
+ : i
+ )
+ );
+ });
+ setSelectedItemId(null);
+ }
+ }, [item.id, methodMaterialFetcher.data, setItems, setSelectedItemId]);
+
+ const [itemType, setItemType] = useState<MethodItemType>(item.data.itemType);
+ const [itemData, setItemData] = useState<{
+ itemId: string;
+ itemReadableId: string;
+ methodType: MethodType;
+ description: string;
+ unitCost: number;
+ unitOfMeasureCode: string;
+ quantity: number;
+ }>({
+ itemId: item.data.itemId ?? "",
+ itemReadableId: item.data.itemReadableId ?? "",
+ methodType: item.data.methodType ?? "Buy",
+ description: item.data.description ?? "",
+ unitCost: item.data.unitCost ?? 0,
+ unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",
+ quantity: item.data.quantity ?? 1,
+ });
+
+ const onTypeChange = (value: MethodItemType) => {
+ setItemType(value);
+ setItemData({
+ itemId: "",
+ itemReadableId: "",
+ methodType: "" as "Buy",
+ quantity: 1,
+ unitCost: 0,
+ description: "",
+ unitOfMeasureCode: "EA",
+ });
+ };
+
+ const onItemChange = async (itemId: string) => {
+ if (!supabase) return;
+ if (itemId === params.itemId) {
+ toast.error("An item cannot be added to itself.");
+ return;
+ }
+
+ const [item, itemCost] = await await Promise.all([
+ supabase
+ .from("item")
+ .select("name, readableId, unitOfMeasureCode, defaultMethodType")
+ .eq("id", itemId)
+ .eq("companyId", company.id)
+ .single(),
+ supabase
+ .from("itemCost")
+ .select("unitCost")
+ .eq("itemId", itemId)
+ .single(),
+ ]);
+
+ if (item.error) {
+ toast.error("Failed to load item details");
+ return;
+ }
+
+ setItemData((d) => ({
+ ...d,
+ itemId,
+ itemReadableId: item.data?.readableId ?? "",
+ description: item.data?.name ?? "",
+ unitCost: itemCost.data?.unitCost ?? 0,
+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
+ methodType: item.data?.defaultMethodType ?? "Buy",
+ }));
+ };
+
+ return (
+ <ValidatedForm
+ action={
+ isTemporaryId(item.id)
+ ? path.to.newJobMaterial(jobId)
+ : path.to.jobMaterial(jobId, item.id!)
+ }
+ method="post"
+ defaultValues={item.data}
+ validator={jobMaterialValidator}
+ className="w-full"
+ fetcher={methodMaterialFetcher}
+ onSubmit={(values) => {
+ setItems((prevItems) =>
+ prevItems.map((i) =>
+ i.id === item.id
+ ? {
+ ...makeItem({ ...values, description: itemData.description }),
+ id: item.id,
+ }
+ : i
+ )
+ );
+ }}
+ >
+ <Hidden name="jobMakeMethodId" />
+ <Hidden name="itemReadableId" value={itemData.itemReadableId} />
+ <Hidden name="order" />
+ {itemData.methodType === "Make" && (
+ <Hidden name="unitCost" value={itemData.unitCost} />
+ )}
+ <VStack className="pt-4">
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <Item
+ disabledItems={[params.itemId!]}
+ isReadOnly={isDisabled}
+ name="itemId"
+ label={itemType}
+ includeInactive
+ type={itemType}
+ onChange={(value) => {
+ onItemChange(value?.value as string);
+ }}
+ onTypeChange={onTypeChange}
+ />
+ <InputControlled
+ className="col-span-2"
+ name="description"
+ label="Description"
+ value={itemData.description}
+ onChange={(newValue) => {
+ setItemData((d) => ({ ...d, description: newValue }));
+ }}
+ />
+
+ <DefaultMethodType
+ name="methodType"
+ label="Method Type"
+ value={itemData.methodType}
+ replenishmentSystem="Buy and Make"
+ />
+ <Number name="quantity" label="Quantity per Parent" />
+ <UnitOfMeasure
+ name="unitOfMeasureCode"
+ value={itemData.unitOfMeasureCode}
+ onChange={(newValue) =>
+ setItemData((d) => ({
+ ...d,
+ unitOfMeasureCode: newValue?.value ?? "EA",
+ }))
+ }
+ />
+ <Select
+ name="jobOperationId"
+ label="Operation"
+ isClearable
+ options={jobOperations.map((o) => ({
+ value: o.id!,
+ label: o.description,
+ }))}
+ />
+ {itemData.methodType !== "Make" && (
+ <NumberControlled
+ name="unitCost"
+ label="Unit Cost"
+ value={itemData.unitCost}
+ minValue={0}
+ />
+ )}
+ </div>
+
+ <motion.div
+ className="flex w-full items-center justify-end p-2"
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ bounce: 0,
+ duration: 0.55,
+ }}
+ >
+ <motion.div layout className="ml-auto mr-1 pt-2">
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ </motion.div>
+ </motion.div>
+ </VStack>
+ </ValidatedForm>
+ );
+}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
new file mode 100644
index 0000000000..1546d833a6
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -0,0 +1,1163 @@
+"use client";
+import { ValidatedForm } from "@carbon/form";
+import type { JSONContent } from "@carbon/react";
+import {
+ Badge,
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Editor,
+ HStack,
+ Label,
+ cn,
+ generateHTML,
+ useDebounce,
+ useThrottle,
+} from "@carbon/react";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import { useFetcher, useParams } from "@remix-run/react";
+import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
+import { nanoid } from "nanoid";
+import type { Dispatch, SetStateAction } from "react";
+import { useCallback, useEffect, useState } from "react";
+import { flushSync } from "react-dom";
+import { LuChevronDown, LuDollarSign, LuSettings2, LuX } from "react-icons/lu";
+import type { z } from "zod";
+import { DirectionAwareTabs, TimeTypeIcon } from "~/components";
+import {
+ Hidden,
+ InputControlled,
+ NumberControlled,
+ Process,
+ Select,
+ SelectControlled,
+ StandardFactor,
+ Submit,
+ SupplierProcess,
+ UnitHint,
+ WorkCenter,
+ getUnitHint,
+} from "~/components/Form";
+import type { Item, SortableItemRenderProps } from "~/components/SortableList";
+import { SortableList, SortableListItem } from "~/components/SortableList";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import { methodOperationOrders, operationTypes } from "~/modules/shared";
+import { path } from "~/utils/path";
+import { jobOperationValidator } from "../../production.models";
+import type { Job } from "../../types";
+
+type Operation = z.infer<typeof jobOperationValidator> & {
+ workInstruction: JSONContent | null;
+};
+
+type ItemWithData = Item & {
+ data: Operation;
+};
+
+type JobBillOfProcessProps = {
+ jobMakeMethodId: string;
+ operations: Operation[];
+};
+
+function makeItems(operations: Operation[]): ItemWithData[] {
+ return operations.map(makeItem);
+}
+
+function makeItem(operation: Operation): ItemWithData {
+ return {
+ id: operation.id!,
+ title: operation.description ?? "",
+ checked: false,
+ order: operation.operationOrder,
+ details: (
+ <HStack spacing={1}>
+ {operation.operationType === "Outside" ? (
+ <Badge>Outside</Badge>
+ ) : (
+ <>
+ {(operation?.laborTime ?? 0) > 0 && (
+ <Badge variant="secondary">
+ <TimeTypeIcon type="Labor" className="h-3 w-3 mr-1" />
+ {operation.laborTime} {operation.laborUnit}
+ </Badge>
+ )}
+
+ {(operation?.machineTime ?? 0) > 0 && (
+ <Badge variant="secondary">
+ <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
+ {operation.machineTime} {operation.machineUnit}
+ </Badge>
+ )}
+ </>
+ )}
+ </HStack>
+ ),
+ data: operation,
+ };
+}
+
+const initialOperation: Omit<Operation, "jobMakeMethodId" | "order"> = {
+ description: "",
+ laborRate: 0,
+ laborTime: 0,
+ laborUnit: "Minutes/Piece",
+ machineRate: 0,
+ machineTime: 0,
+ machineUnit: "Minutes/Piece",
+ operationUnitCost: 0,
+ operationLeadTime: 0,
+ operationOrder: "After Previous",
+ operationType: "Inside",
+ overheadRate: 0,
+ processId: "",
+ setupTime: 0,
+ setupUnit: "Total Minutes",
+ workCenterId: "",
+ workInstruction: {},
+};
+
+const JobBillOfProcess = ({
+ jobMakeMethodId,
+ operations,
+}: JobBillOfProcessProps) => {
+ const { supabase } = useSupabase();
+ const sortOrderFetcher = useFetcher<{}>();
+ const permissions = usePermissions();
+ const {
+ id: userId,
+ company: { id: companyId },
+ } = useUser();
+
+ const [items, setItems] = useState<ItemWithData[]>(
+ makeItems(operations ?? [])
+ );
+ const [selectedItemId, setSelectedItemId] = useState<string | null>(null);
+
+ const { jobId } = useParams();
+ if (!jobId) throw new Error("jobId not found");
+ const jobData = useRouteData<{ job: Job }>(path.to.job(jobId));
+
+ const isDisabled = jobData?.job?.status !== "Draft";
+
+ const onToggleItem = (id: string) => {
+ if (!permissions.can("update", "sales") || isDisabled) return;
+ setItems((prevItems) =>
+ prevItems.map((item) =>
+ item.id === id ? { ...item, checked: !item.checked } : item
+ )
+ );
+ };
+
+ // we create a temporary item and append it to the list
+ const onAddItem = () => {
+ if (!permissions.can("update", "sales") || isDisabled) return;
+ const temporaryId = Math.random().toString(16).slice(2);
+ setSelectedItemId(temporaryId);
+ setItems((prevItems) => {
+ let newOrder = 1;
+ if (prevItems.length) {
+ newOrder = prevItems[prevItems.length - 1].data.order + 1;
+ }
+
+ return [
+ ...prevItems,
+ {
+ title: "",
+ checked: false,
+ id: temporaryId,
+ data: {
+ ...initialOperation,
+ order: newOrder,
+ jobMakeMethodId,
+ },
+ },
+ ];
+ });
+ };
+
+ const onRemoveItem = async (id: string) => {
+ if (!permissions.can("update", "sales") || isDisabled) return;
+ // get the item and it's order in the list
+ const itemIndex = items.findIndex((i) => i.id === id);
+ const item = items[itemIndex];
+
+ setItems((prevItems) => prevItems.filter((item) => item.id !== id));
+
+ const response = await supabase?.from("jobOperation").delete().eq("id", id);
+ if (response?.error) {
+ // add the item back to the list if there was an error
+ setItems((prevItems) => {
+ const updatedItems = [...prevItems];
+ updatedItems.splice(itemIndex, 0, item);
+ return updatedItems;
+ });
+ }
+ };
+
+ const onReorder = (items: ItemWithData[]) => {
+ if (!permissions.can("update", "sales") || isDisabled) return;
+ const newItems = items.map((item, index) => ({
+ ...item,
+ data: {
+ ...item.data,
+ order: index + 1,
+ },
+ }));
+ const updates = newItems.reduce<Record<string, number>>((acc, item) => {
+ if (!isTemporaryId(item.id)) {
+ acc[item.id] = item.data.order;
+ }
+ return acc;
+ }, {});
+
+ setItems(newItems);
+ updateSortOrder(updates);
+ };
+
+ const updateSortOrder = useDebounce((updates: Record<string, number>) => {
+ let formData = new FormData();
+ formData.append("updates", JSON.stringify(updates));
+ sortOrderFetcher.submit(formData, {
+ method: "post",
+ action: path.to.jobOperationsOrder,
+ });
+ }, 1000);
+
+ const onCloseOnDrag = useCallback(() => {
+ setItems((prevItems) => {
+ const updatedItems = prevItems.map((item) =>
+ item.checked ? { ...item, checked: false } : item
+ );
+ return updatedItems.some(
+ (item, index) => item.checked !== prevItems[index].checked
+ )
+ ? updatedItems
+ : prevItems;
+ });
+ }, []);
+
+ const onUpdateWorkInstruction = useThrottle(async (content: JSONContent) => {
+ if (!permissions.can("update", "parts")) return;
+ setItems((prevItems) =>
+ prevItems.map((item) =>
+ item.id === selectedItemId
+ ? {
+ ...item,
+ data: {
+ ...item.data,
+ workInstruction: content,
+ },
+ }
+ : item
+ )
+ );
+ if (selectedItemId !== null && !isTemporaryId(selectedItemId))
+ await supabase
+ ?.from("jobOperation")
+ .update({
+ workInstruction: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", selectedItemId!);
+ }, 2500);
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/parts/${selectedItemId}/${nanoid()}.${fileType}`;
+ const result = await supabase?.storage
+ .from("private")
+ .upload(fileName, file, { upsert: true });
+
+ if (result?.error) {
+ throw new Error(result.error.message);
+ }
+
+ if (!result?.data) {
+ throw new Error("Failed to upload image");
+ }
+
+ return `/file/preview/private/${result.data.path}`;
+ };
+
+ const [tabChangeRerender, setTabChangeRerender] = useState<number>(1);
+ const renderListItem = ({
+ item,
+ items,
+ order,
+ onToggleItem,
+ onRemoveItem,
+ }: SortableItemRenderProps<ItemWithData>) => {
+ const isOpen = item.id === selectedItemId;
+ const tabs = [
+ {
+ id: 0,
+ label: "Details",
+ content: (
+ <div className="flex w-full flex-col pr-2 py-2">
+ <motion.div
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ bounce: 0.2,
+ duration: 0.75,
+ delay: 0.15,
+ }}
+ >
+ <OperationForm
+ item={item}
+ isDisabled={isDisabled}
+ setItems={setItems}
+ setSelectedItemId={setSelectedItemId}
+ />
+ </motion.div>
+ </div>
+ ),
+ },
+ {
+ id: 1,
+ label: "Work Instructions",
+ content: (
+ <div className="flex flex-col">
+ <motion.div
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ bounce: 0.2,
+ duration: 0.75,
+ delay: 0.15,
+ }}
+ >
+ {permissions.can("update", "parts") ? (
+ <Editor
+ initialValue={
+ item.data.workInstruction ?? ({} as JSONContent)
+ }
+ onUpload={onUploadImage}
+ onChange={onUpdateWorkInstruction}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(
+ item.data.workInstruction ?? ({} as JSONContent)
+ ),
+ }}
+ />
+ )}
+ </motion.div>
+ </div>
+ ),
+ },
+ ];
+
+ return (
+ <SortableListItem<Operation>
+ item={item}
+ items={items}
+ order={order}
+ key={item.id}
+ isExpanded={isOpen}
+ onSelectItem={setSelectedItemId}
+ onToggleItem={onToggleItem}
+ onRemoveItem={onRemoveItem}
+ handleDrag={onCloseOnDrag}
+ className="my-2 "
+ renderExtra={(item) => (
+ <div
+ key={`${isOpen}`}
+ className={cn(
+ "flex h-full flex-col items-center justify-center gap-2 pl-2",
+ isOpen ? "py-1" : "py-3 "
+ )}
+ >
+ <motion.button
+ layout
+ onClick={
+ isOpen
+ ? () => {
+ if (isTemporaryId(item.id)) {
+ setItems((prevItems) =>
+ prevItems.filter((i) => i.id !== item.id)
+ );
+ }
+ setSelectedItemId(null);
+ }
+ : () => {
+ setSelectedItemId(item.id);
+ }
+ }
+ key="collapse"
+ className={cn(
+ isOpen
+ ? "absolute right-3 top-3 z-10 "
+ : "relative z-10 ml-auto mr-3 "
+ )}
+ >
+ {isOpen ? (
+ <motion.span
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ exit={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ duration: 1.95,
+ }}
+ >
+ <LuX className="h-5 w-5 text-foreground" />
+ </motion.span>
+ ) : (
+ <motion.span
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ exit={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ duration: 0.95,
+ }}
+ >
+ <LuSettings2 className="stroke-1 h-5 w-5 text-foreground/80 hover:stroke-primary/70 " />
+ </motion.span>
+ )}
+ </motion.button>
+
+ <LayoutGroup id={`${item.id}`}>
+ <AnimatePresence mode="popLayout">
+ {isOpen ? (
+ <motion.div className="flex w-full flex-col ">
+ <div className=" w-full p-2">
+ <motion.div
+ initial={{
+ y: 0,
+ opacity: 0,
+ filter: "blur(4px)",
+ }}
+ animate={{
+ y: 0,
+ opacity: 1,
+ filter: "blur(0px)",
+ }}
+ transition={{
+ type: "spring",
+ duration: 0.15,
+ }}
+ layout
+ className="w-full "
+ >
+ <DirectionAwareTabs
+ className="mr-auto"
+ tabs={tabs}
+ onChange={() =>
+ setTabChangeRerender(tabChangeRerender + 1)
+ }
+ />
+ </motion.div>
+ </div>
+ </motion.div>
+ ) : null}
+ </AnimatePresence>
+ </LayoutGroup>
+ </div>
+ )}
+ />
+ );
+ };
+
+ return (
+ <Card>
+ <HStack className="justify-between">
+ <CardHeader>
+ <CardTitle>Bill of Process</CardTitle>
+ </CardHeader>
+
+ <CardAction>
+ <Button
+ variant="secondary"
+ isDisabled={
+ !permissions.can("update", "sales") ||
+ selectedItemId !== null ||
+ isDisabled
+ }
+ onClick={onAddItem}
+ >
+ Add Operation
+ </Button>
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <SortableList
+ items={items}
+ onReorder={onReorder}
+ onToggleItem={onToggleItem}
+ onRemoveItem={onRemoveItem}
+ renderItem={renderListItem}
+ />
+ </CardContent>
+ </Card>
+ );
+};
+
+export default JobBillOfProcess;
+
+function isTemporaryId(id: string) {
+ return id.length < 20;
+}
+
+function OperationForm({
+ item,
+ isDisabled,
+ setItems,
+ setSelectedItemId,
+}: {
+ item: ItemWithData;
+ isDisabled: boolean;
+ setItems: Dispatch<SetStateAction<ItemWithData[]>>;
+ setSelectedItemId: Dispatch<SetStateAction<string | null>>;
+}) {
+ const { jobId } = useParams();
+ const { id: userId } = useUser();
+ if (!jobId) throw new Error("jobId not found");
+
+ const fetcher = useFetcher<{ id: string }>();
+ const { supabase } = useSupabase();
+
+ useEffect(() => {
+ // replace the temporary id with the actual id
+ if (fetcher.data && fetcher.data.id) {
+ flushSync(() => {
+ setItems((prevItems) =>
+ prevItems.map((i) =>
+ i.id === item.id
+ ? {
+ ...i,
+ id: fetcher.data!.id!,
+ data: {
+ ...i.data,
+ ...fetcher.data,
+ },
+ }
+ : i
+ )
+ );
+ });
+
+ // save the work instructions
+ if (isTemporaryId(item.id) && supabase) {
+ supabase
+ .from("jobOperation")
+ .update({
+ workInstruction: item.data.workInstruction,
+ createdAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("jobOperationId", fetcher.data.id)
+ .then(() => {
+ setSelectedItemId(null);
+ });
+ } else {
+ setSelectedItemId(null);
+ }
+ }
+ }, [
+ item.id,
+ fetcher.data,
+ setItems,
+ setSelectedItemId,
+ item.data.workInstruction,
+ supabase,
+ userId,
+ ]);
+
+ const [showMachine, setShowMachine] = useState(
+ (item.data.machineTime ?? 0) > 0
+ );
+ const [showLabor, setShowLabor] = useState((item.data.laborTime ?? 0) > 0);
+ const [showSetup, setShowSetup] = useState(
+ (item.data.setupTime ?? 0) > 0 ||
+ (showLabor === false && showMachine === false)
+ );
+
+ const [showCost, setShowCost] = useState(false);
+
+ const [processData, setProcessData] = useState<{
+ description: string;
+ laborRate: number;
+ laborTime: number;
+ laborUnit: string;
+ laborUnitHint: string;
+ machineRate: number;
+ machineTime: number;
+ machineUnit: string;
+ machineUnitHint: string;
+ operationMinimumCost: number;
+ operationLeadTime: number;
+ operationType: string;
+ operationUnitCost: number;
+ overheadRate: number;
+ processId: string;
+ setupTime: number;
+ setupUnit: string;
+ setupUnitHint: string;
+ }>({
+ description: item.data.description ?? "",
+ laborRate: item.data.laborRate ?? 0,
+ laborTime: item.data.laborTime ?? 0,
+ laborUnit: item.data.laborUnit ?? "Hours/Piece",
+ laborUnitHint: getUnitHint(item.data.laborUnit),
+ machineRate: item.data.machineRate ?? 0,
+ machineTime: item.data.machineTime ?? 0,
+ machineUnit: item.data.machineUnit ?? "Hours/Piece",
+ machineUnitHint: getUnitHint(item.data.machineUnit),
+ operationMinimumCost: item.data.operationMinimumCost ?? 0,
+ operationLeadTime: item.data.operationLeadTime ?? 0,
+ operationType: item.data.operationType ?? "Inside",
+ operationUnitCost: item.data.operationUnitCost ?? 0,
+ overheadRate: item.data.overheadRate ?? 0,
+ processId: item.data.processId ?? "",
+ setupTime: item.data.setupTime ?? 0,
+ setupUnit: item.data.setupUnit ?? "Total Minutes",
+ setupUnitHint: getUnitHint(item.data.setupUnit),
+ });
+
+ const onProcessChange = async (processId: string) => {
+ if (!supabase || !processId) return;
+ const [process, workCenters, supplierProcesses] = await Promise.all([
+ supabase.from("process").select("*").eq("id", processId).single(),
+ supabase
+ .from("workCenterProcess")
+ .select("workCenter(*)")
+ .eq("processId", processId)
+ .eq("workCenter.active", true),
+ supabase.from("supplierProcess").select("*").eq("processId", processId),
+ ]);
+
+ const activeWorkCenters =
+ workCenters?.data?.filter((wc) => Boolean(wc.workCenter)) ?? [];
+
+ if (process.error) throw new Error(process.error.message);
+
+ setProcessData((p) => ({
+ ...p,
+ processId,
+ description: process.data?.name ?? "",
+ laborUnit: process.data?.defaultStandardFactor ?? "Hours/Piece",
+ laborUnitHint: getUnitHint(process.data?.defaultStandardFactor),
+ laborRate:
+ // get the average labor rate from the work centers
+ activeWorkCenters.length
+ ? activeWorkCenters.reduce((acc, workCenter) => {
+ return (acc += workCenter.workCenter?.laborRate ?? 0);
+ }, 0) / activeWorkCenters.length
+ : p.laborRate,
+ machineUnit: process.data?.defaultStandardFactor ?? "Hours/Piece",
+ machineUnitHint: getUnitHint(process.data?.defaultStandardFactor),
+ machineRate:
+ // get the average labor rate from the work centers
+ activeWorkCenters.length
+ ? activeWorkCenters.reduce((acc, workCenter) => {
+ return (acc += workCenter.workCenter?.machineRate ?? 0);
+ }, 0) / activeWorkCenters.length
+ : p.machineRate,
+ // get the average quoting rate from the work centers
+ overheadRate: activeWorkCenters.length
+ ? activeWorkCenters?.reduce((acc, workCenter) => {
+ return (acc += workCenter.workCenter?.overheadRate ?? 0);
+ }, 0) / activeWorkCenters.length
+ : p.overheadRate,
+ operationMinimumCost:
+ supplierProcesses.data && supplierProcesses.data.length > 0
+ ? supplierProcesses.data.reduce((acc, sp) => {
+ return (acc += sp.minimumCost ?? 0);
+ }, 0) / supplierProcesses.data.length
+ : p.operationMinimumCost,
+ operationUnitCost:
+ supplierProcesses.data && supplierProcesses.data.length > 0
+ ? supplierProcesses.data.reduce((acc, sp) => {
+ return (acc += sp.unitCost ?? 0);
+ }, 0) / supplierProcesses.data.length
+ : p.operationUnitCost,
+ operationLeadTime:
+ supplierProcesses.data && supplierProcesses.data.length > 0
+ ? supplierProcesses.data.reduce((acc, sp) => {
+ return (acc += sp.leadTime ?? 0);
+ }, 0) / supplierProcesses.data.length
+ : p.operationLeadTime,
+ operationType:
+ process.data?.processType === "Outside" ? "Outside" : "Inside",
+ }));
+ };
+
+ const onWorkCenterChange = async (workCenterId: string | null) => {
+ if (!supabase) return;
+ if (!workCenterId) {
+ // get the average costs
+ await onProcessChange(processData.processId);
+ return;
+ }
+
+ const { data, error } = await supabase
+ .from("workCenter")
+ .select("*")
+ .eq("id", workCenterId)
+ .single();
+
+ if (error) throw new Error(error.message);
+
+ setProcessData((d) => ({
+ ...d,
+ laborRate: data?.laborRate ?? 0,
+ laborUnit: data?.defaultStandardFactor ?? "Hours/Piece",
+ laborUnitHint: getUnitHint(data?.defaultStandardFactor),
+ machineRate: data?.machineRate ?? 0,
+ machineUnit: data?.defaultStandardFactor ?? "Hours/Piece",
+ machineUnitHint: getUnitHint(data?.defaultStandardFactor),
+ overheadRate: data?.overheadRate ?? 0,
+ }));
+ };
+
+ const onSupplierProcessChange = async (supplierProcessId: string) => {
+ if (!supabase) return;
+ const { data, error } = await supabase
+ .from("supplierProcess")
+ .select("*")
+ .eq("id", supplierProcessId)
+ .single();
+
+ if (error) throw new Error(error.message);
+
+ setProcessData((d) => ({
+ ...d,
+ operationMinimumCost: data?.minimumCost ?? 0,
+ operationUnitCost: data?.unitCost ?? 0,
+ operationLeadTime: data?.leadTime ?? 0,
+ }));
+ };
+
+ return (
+ <ValidatedForm
+ action={
+ isTemporaryId(item.id)
+ ? path.to.newJobOperation(jobId)
+ : path.to.jobOperation(jobId, item.id!)
+ }
+ method="post"
+ defaultValues={item.data}
+ validator={jobOperationValidator}
+ className="w-full flex flex-col gap-y-4"
+ fetcher={fetcher}
+ onSubmit={async (values) => {
+ setItems((prevItems) =>
+ prevItems.map((i) =>
+ i.id === item.id
+ ? {
+ ...makeItem({
+ ...values,
+ workInstruction: i.data.workInstruction,
+ }),
+ id: item.id,
+ }
+ : i
+ )
+ );
+ }}
+ >
+ <Hidden name="jobMakeMethodId" />
+ <Hidden name="order" />
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <Process
+ name="processId"
+ label="Process"
+ onChange={(value) => {
+ onProcessChange(value?.value as string);
+ }}
+ />
+ <Select
+ name="operationOrder"
+ label="Operation Order"
+ placeholder="Operation Order"
+ options={methodOperationOrders.map((o) => ({
+ value: o,
+ label: o,
+ }))}
+ />
+ <SelectControlled
+ name="operationType"
+ label="Operation Type"
+ placeholder="Operation Type"
+ options={operationTypes.map((o) => ({
+ value: o,
+ label: o,
+ }))}
+ value={processData.operationType}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+
+ setupUnit: "Total Minutes",
+ laborUnit: "Minutes/Piece",
+ machineUnit: "Minutes/Piece",
+ operationType: value?.value as string,
+ }));
+ }}
+ />
+
+ <InputControlled
+ name="description"
+ label="Description"
+ value={processData.description}
+ onChange={(newValue) => {
+ setProcessData((d) => ({ ...d, description: newValue }));
+ }}
+ className="col-span-2"
+ />
+
+ {processData.operationType === "Outside" ? (
+ <>
+ <SupplierProcess
+ name="operationSupplierProcessId"
+ label="Supplier"
+ processId={processData.processId}
+ isOptional
+ onChange={(value) => {
+ if (value) {
+ onSupplierProcessChange(value?.value as string);
+ }
+ }}
+ />
+ <NumberControlled
+ name="operationMinimumCost"
+ label="Minimum Cost"
+ minValue={0}
+ value={processData.operationMinimumCost}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ operationMinimumCost: newValue,
+ }))
+ }
+ />
+ <NumberControlled
+ name="operationUnitCost"
+ label="Unit Cost"
+ minValue={0}
+ value={processData.operationUnitCost}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ operationUnitCost: newValue,
+ }))
+ }
+ />
+ <NumberControlled
+ name="operationLeadTime"
+ label="Lead Time"
+ minValue={0}
+ value={processData.operationLeadTime}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ operationLeadTime: newValue,
+ }))
+ }
+ />
+ </>
+ ) : (
+ <WorkCenter
+ name="workCenterId"
+ label="Work Center"
+ isOptional
+ processId={processData.processId}
+ onChange={(value) => {
+ if (value) {
+ onWorkCenterChange(value?.value as string);
+ }
+ }}
+ />
+ )}
+ </div>
+
+ {processData.operationType === "Inside" && (
+ <>
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={() => setShowSetup(!showSetup)}
+ >
+ <HStack>
+ <TimeTypeIcon type="Setup" />
+ <Label>Setup</Label>
+ </HStack>
+ <LuChevronDown
+ className={`transition-transform ${
+ showSetup ? "rotate-180" : ""
+ }`}
+ />
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
+ showSetup ? "" : "hidden"
+ }`}
+ >
+ <UnitHint
+ name="setupHint"
+ label="Setup"
+ value={processData.setupUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ setupUnitHint: hint,
+ setupUnit:
+ hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
+ }));
+ }}
+ />
+ <NumberControlled
+ name="setupTime"
+ label="Setup Time"
+ minValue={0}
+ value={processData.setupTime}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ setupTime: newValue,
+ }))
+ }
+ />
+ <StandardFactor
+ name="setupUnit"
+ label="Setup Unit"
+ hint={processData.setupUnitHint}
+ value={processData.setupUnit}
+ onChange={(newValue) => {
+ setProcessData((d) => ({
+ ...d,
+ setupUnit: newValue?.value ?? "Total Minutes",
+ }));
+ }}
+ />
+ </div>
+ </div>
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={() => setShowLabor(!showLabor)}
+ >
+ <HStack>
+ <TimeTypeIcon type="Labor" />
+ <Label>Labor</Label>
+ </HStack>
+ <LuChevronDown
+ className={`transition-transform ${
+ showLabor ? "rotate-180" : ""
+ }`}
+ />
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
+ showLabor ? "" : "hidden"
+ }`}
+ >
+ <UnitHint
+ name="laborHint"
+ label="Labor"
+ value={processData.laborUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ laborUnitHint: hint,
+ laborUnit:
+ hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
+ }));
+ }}
+ />
+ <NumberControlled
+ name="laborTime"
+ label="Labor Time"
+ minValue={0}
+ value={processData.laborTime}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ laborTime: newValue,
+ }))
+ }
+ />
+ <StandardFactor
+ name="laborUnit"
+ label="Labor Unit"
+ hint={processData.laborUnitHint}
+ value={processData.laborUnit}
+ onChange={(newValue) => {
+ setProcessData((d) => ({
+ ...d,
+ laborUnit: newValue?.value ?? "Total Minutes",
+ }));
+ }}
+ />
+ </div>
+ </div>
+
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={() => setShowMachine(!showMachine)}
+ >
+ <HStack>
+ <TimeTypeIcon type="Machine" />
+ <Label>Machine</Label>
+ </HStack>
+ <LuChevronDown
+ className={`transition-transform ${
+ showMachine ? "rotate-180" : ""
+ }`}
+ />
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
+ showMachine ? "" : "hidden"
+ }`}
+ >
+ <UnitHint
+ name="machineHint"
+ label="Machine"
+ value={processData.machineUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnitHint: hint,
+ machineUnit:
+ hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
+ }));
+ }}
+ />
+ <NumberControlled
+ name="machineTime"
+ label="Machine Time"
+ minValue={0}
+ value={processData.machineTime}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ machineTime: newValue,
+ }))
+ }
+ />
+ <StandardFactor
+ name="machineUnit"
+ label="Machine Unit"
+ hint={processData.machineUnitHint}
+ value={processData.machineUnit}
+ onChange={(newValue) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnit: newValue?.value ?? "Total Minutes",
+ }));
+ }}
+ />
+ </div>
+ </div>
+
+ <div className="border border-border rounded-md shadow-sm p-4 flex flex-col gap-4">
+ <HStack
+ className="w-full justify-between cursor-pointer"
+ onClick={() => setShowCost(!showCost)}
+ >
+ <HStack>
+ <LuDollarSign />
+ <Label>Costing</Label>
+ </HStack>
+ <LuChevronDown
+ className={`transition-transform ${
+ showCost ? "rotate-180" : ""
+ }`}
+ />
+ </HStack>
+ <div
+ className={`grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3 pb-4 ${
+ showCost ? "" : "hidden"
+ }`}
+ >
+ <NumberControlled
+ name="laborRate"
+ label="Labor Rate"
+ minValue={0}
+ value={processData.laborRate}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ laborRate: newValue,
+ }))
+ }
+ />
+ <NumberControlled
+ name="machineRate"
+ label="Machine Rate"
+ minValue={0}
+ value={processData.machineRate}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ machineRate: newValue,
+ }))
+ }
+ />
+ <NumberControlled
+ name="overheadRate"
+ label="Overhead Rate"
+ minValue={0}
+ value={processData.overheadRate}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ overheadRate: newValue,
+ }))
+ }
+ />
+ </div>
+ </div>
+ </>
+ )}
+ <motion.div
+ className="flex w-full items-center justify-end p-2"
+ initial={{ opacity: 0, filter: "blur(4px)" }}
+ animate={{ opacity: 1, filter: "blur(0px)" }}
+ transition={{
+ type: "spring",
+ bounce: 0,
+ duration: 0.55,
+ }}
+ >
+ <motion.div layout className="ml-auto mr-1 pt-2">
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ </motion.div>
+ </motion.div>
+ </ValidatedForm>
+ );
+}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBoMExplorer.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
new file mode 100644
index 0000000000..b8305f1c4f
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBoMExplorer.tsx
@@ -0,0 +1,183 @@
+import { Badge, HStack, Spinner, VStack, cn } from "@carbon/react";
+import { useFetchers, useNavigate } from "@remix-run/react";
+import { useRef } from "react";
+import { LuChevronDown, LuChevronUp } from "react-icons/lu";
+import { MethodIcon, MethodItemTypeIcon } from "~/components";
+import type { FlatTree, FlatTreeItem } from "~/components/TreeView";
+import { LevelLine, TreeView, useTree } from "~/components/TreeView";
+import { useOptimisticLocation } from "~/hooks";
+import { path } from "~/utils/path";
+import type { JobMethod } from "../../production.service";
+
+type JobBoMExplorerProps = {
+ method: FlatTree<JobMethod>;
+};
+
+const JobBoMExplorer = ({ method }: JobBoMExplorerProps) => {
+ const parentRef = useRef<HTMLDivElement>(null);
+ const navigate = useNavigate();
+ const location = useOptimisticLocation();
+
+ const fetchers = useFetchers();
+ const getMethodFetcher = fetchers.find(
+ (f) => f.formAction === path.to.jobMethodGet
+ );
+
+ const isLoading = getMethodFetcher?.state === "loading";
+
+ const {
+ nodes,
+ getTreeProps,
+ getNodeProps,
+ // toggleNodeSelection,
+ toggleExpandNode,
+ expandAllBelowDepth,
+ // toggleExpandLevel,
+ collapseAllBelowDepth,
+ scrollToNode,
+ virtualizer,
+ } = useTree({
+ tree: method,
+ // selectedId,
+ // collapsedIds,
+ onSelectedIdChanged: () => {},
+ estimatedRowHeight: () => 32,
+ parentRef,
+ isEager: true,
+ });
+
+ return (
+ <VStack>
+ {isLoading ? (
+ <div className="flex items-center justify-center py-8 w-full">
+ <Spinner className="w-4 h-4" />
+ </div>
+ ) : (
+ <TreeView
+ parentRef={parentRef}
+ virtualizer={virtualizer}
+ autoFocus
+ tree={method}
+ nodes={nodes}
+ getNodeProps={getNodeProps}
+ getTreeProps={getTreeProps}
+ renderNode={({ node, state }) => (
+ <div
+ key={node.id}
+ className={cn(
+ "flex h-8 cursor-pointer items-center overflow-hidden rounded-sm pr-2",
+ getNodePath(node) === location.pathname
+ ? "bg-muted hover:bg-muted/90"
+ : "bg-transparent hover:bg-muted/90"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ navigate(getNodePath(node));
+ }}
+ >
+ <div className="flex h-8 items-center">
+ {Array.from({ length: node.level }).map((_, index) => (
+ <LevelLine
+ key={index}
+ isSelected={getNodePath(node) === location.pathname}
+ />
+ ))}
+ <div
+ className={cn(
+ "flex h-8 w-4 items-center",
+ node.hasChildren && "hover:bg-accent"
+ )}
+ onClick={(e) => {
+ e.stopPropagation();
+ if (e.altKey) {
+ if (state.expanded) {
+ collapseAllBelowDepth(node.level);
+ } else {
+ expandAllBelowDepth(node.level);
+ }
+ } else {
+ toggleExpandNode(node.id);
+ }
+ scrollToNode(node.id);
+ }}
+ >
+ {node.hasChildren ? (
+ state.expanded ? (
+ <LuChevronDown className="h-4 w-4 text-gray-400" />
+ ) : (
+ <LuChevronUp className="h-4 w-4 text-gray-400" />
+ )
+ ) : (
+ <div className="h-8 w-4" />
+ )}
+ </div>
+ </div>
+
+ <div className="flex w-full items-center justify-between gap-2">
+ <div className="flex items-center gap-2 overflow-x-hidden">
+ <MethodIcon
+ type={
+ // node.data.isRoot ? "Method" :
+ node.data.methodType
+ }
+ className="h-4 min-h-4 w-4 min-w-4 flex-shrink-0"
+ />
+ <NodeText node={node} />
+ </div>
+ <div className="flex items-center gap-1">
+ {node.data.isRoot ? (
+ <Badge variant="outline" className="text-xs">
+ Method
+ </Badge>
+ ) : (
+ <NodeData node={node} />
+ )}
+ </div>
+ </div>
+ </div>
+ )}
+ />
+ )}
+ </VStack>
+ );
+};
+
+export default JobBoMExplorer;
+
+function NodeText({ node }: { node: FlatTreeItem<JobMethod> }) {
+ return (
+ <div className="flex items-center gap-1">
+ <span className="text-sm font-mono">{node.data.itemReadableId}</span>
+ </div>
+ );
+}
+
+function NodeData({ node }: { node: FlatTreeItem<JobMethod> }) {
+ return (
+ <HStack spacing={1}>
+ <Badge className="text-xs" variant="outline">
+ {node.data.quantity}
+ </Badge>
+ <Badge variant="secondary">
+ <MethodItemTypeIcon type={node.data.itemType} />
+ </Badge>
+ </HStack>
+ );
+}
+
+function getNodePath(node: FlatTreeItem<JobMethod>) {
+ return node.data.isRoot
+ ? path.to.jobMethod(node.data.jobId, node.data.jobMaterialMakeMethodId)
+ : node.data.methodType === "Make"
+ ? path.to.jobMakeMethod(
+ node.data.jobId,
+ node.data.jobMaterialMakeMethodId,
+ node.data.methodMaterialId
+ )
+ : path.to.jobMethodMaterial(
+ node.data.jobId,
+ node.data.methodType.toLowerCase(),
+ node.data.jobMakeMethodId,
+ node.data.methodMaterialId
+ );
+}
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx
new file mode 100644
index 0000000000..16b6ea9a49
--- /dev/null
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobMaterialForm.tsx
@@ -0,0 +1,258 @@
+import {
+ Card,
+ CardContent,
+ CardFooter,
+ CardHeader,
+ CardTitle,
+ toast,
+ VStack,
+} from "@carbon/react";
+import {
+ useFetcher,
+ useLocation,
+ useNavigate,
+ useParams,
+} from "@remix-run/react";
+
+import { ValidatedForm } from "@carbon/form";
+import { useEffect, useState } from "react";
+import type { z } from "zod";
+import {
+ DefaultMethodType,
+ Hidden,
+ InputControlled,
+ Item,
+ Number,
+ NumberControlled,
+ Select,
+ Submit,
+ UnitOfMeasure,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { jobOperationValidator } from "~/modules/production";
+import { jobMaterialValidator } from "~/modules/production";
+import type { MethodItemType, MethodType } from "~/modules/shared";
+import { path } from "~/utils/path";
+
+type JobMaterialFormProps = {
+ initialValues: z.infer<typeof jobMaterialValidator> & {
+ jobMaterialMakeMethodId: string | null;
+ };
+ operations: z.infer<typeof jobOperationValidator>[];
+};
+
+const JobMaterialForm = ({
+ initialValues,
+ operations,
+}: JobMaterialFormProps) => {
+ const fetcher = useFetcher<{ id: string; methodType: MethodType }>();
+ const { supabase } = useSupabase();
+ const permissions = usePermissions();
+ const navigate = useNavigate();
+ const location = useLocation();
+
+ const { jobId, materialId } = useParams();
+ if (!jobId) throw new Error("jobId not found");
+ if (!materialId) throw new Error("materialId not found");
+
+ const [itemType, setItemType] = useState<MethodItemType>(
+ initialValues.itemType
+ );
+ const [itemData, setItemData] = useState<{
+ itemId: string;
+ itemReadableId: string;
+ methodType: MethodType;
+ description: string;
+ unitCost: number;
+ unitOfMeasureCode: string;
+ quantity: number;
+ }>({
+ itemId: initialValues.itemId ?? "",
+ itemReadableId: initialValues.itemReadableId ?? "",
+ methodType: initialValues.methodType ?? "Buy",
+ description: initialValues.description ?? "",
+ unitCost: initialValues.unitCost ?? 0,
+ unitOfMeasureCode: initialValues.unitOfMeasureCode ?? "EA",
+ quantity: initialValues.quantity ?? 1,
+ });
+
+ const onTypeChange = (value: MethodItemType) => {
+ setItemType(value);
+ setItemData({
+ itemId: "",
+ itemReadableId: "",
+ methodType: "" as "Buy",
+ quantity: 1,
+ description: "",
+ unitCost: 0,
+ unitOfMeasureCode: "EA",
+ });
+ };
+
+ const onItemChange = async (itemId: string) => {
+ if (!supabase) return;
+
+ const [item, itemCost] = await await Promise.all([
+ supabase
+ .from("item")
+ .select("name, readableId, unitOfMeasureCode, defaultMethodType")
+ .eq("id", itemId)
+ .single(),
+ supabase
+ .from("itemCost")
+ .select("unitCost")
+ .eq("itemId", itemId)
+ .single(),
+ ]);
+
+ if (item.error) {
+ toast.error("Failed to load item details");
+ return;
+ }
+
+ setItemData((d) => ({
+ ...d,
+ itemId,
+ itemReadableId: item.data?.readableId ?? "",
+ description: item.data?.name ?? "",
+ unitCost: itemCost.data?.unitCost ?? 0,
+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
+ methodType: item.data?.defaultMethodType ?? "Buy",
+ }));
+ };
+
+ useEffect(() => {
+ const newPath =
+ initialValues.methodType === "Make"
+ ? path.to.jobMakeMethod(
+ jobId,
+ initialValues.jobMaterialMakeMethodId!,
+ initialValues.id!
+ )
+ : path.to.jobMethodMaterial(
+ jobId,
+ initialValues.methodType.toLowerCase(),
+ initialValues.jobMakeMethodId,
+ initialValues.id!
+ );
+ if (
+ fetcher.data?.methodType === "Make" &&
+ !location.pathname.includes("make")
+ ) {
+ navigate(newPath);
+ }
+
+ if (
+ fetcher.data?.methodType === "Buy" &&
+ !location.pathname.includes("buy")
+ ) {
+ navigate(newPath);
+ }
+
+ if (
+ fetcher.data?.methodType === "Pick" &&
+ !location.pathname.includes("pick")
+ ) {
+ navigate(newPath);
+ }
+ }, [
+ fetcher.data,
+ initialValues,
+ initialValues.id,
+ initialValues.methodType,
+ initialValues.jobMaterialMakeMethodId,
+ jobId,
+ location.pathname,
+ navigate,
+ ]);
+
+ return (
+ <Card>
+ <ValidatedForm
+ method="post"
+ action={path.to.jobMaterial(jobId, initialValues?.id!)}
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ validator={jobMaterialValidator}
+ >
+ <CardHeader>
+ <CardTitle>{itemData.itemReadableId}</CardTitle>
+ </CardHeader>
+ <CardContent>
+ <Hidden name="jobMakeMethodId" />
+ <Hidden name="itemReadableId" value={itemData.itemReadableId} />
+ {itemData.methodType === "Make" && (
+ <Hidden name="unitCost" value={itemData.unitCost} />
+ )}
+ <Hidden name="order" />
+ <VStack className="pt-4">
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <Item
+ name="itemId"
+ label={itemType}
+ type={itemType}
+ includeInactive
+ onChange={(value) => {
+ onItemChange(value?.value as string);
+ }}
+ onTypeChange={onTypeChange}
+ />
+ <Select
+ name="jobOperationId"
+ label="Operation"
+ isClearable
+ options={operations.map((o) => ({
+ value: o.id!,
+ label: o.description,
+ }))}
+ />
+ </div>
+ <InputControlled
+ name="description"
+ label="Description"
+ value={itemData.description}
+ onChange={(newValue) => {
+ setItemData((d) => ({ ...d, description: newValue }));
+ }}
+ />
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <DefaultMethodType
+ name="methodType"
+ label="Method Type"
+ value={itemData.methodType}
+ replenishmentSystem="Buy and Make"
+ />
+ <Number name="quantity" label="Quantity per Parent" />
+ <UnitOfMeasure
+ name="unitOfMeasureCode"
+ value={itemData.unitOfMeasureCode}
+ onChange={(newValue) =>
+ setItemData((d) => ({
+ ...d,
+ unitOfMeasureCode: newValue?.value ?? "EA",
+ }))
+ }
+ />
+ {itemData.methodType !== "Make" && (
+ <NumberControlled
+ name="unitCost"
+ label="Unit Cost"
+ value={itemData.unitCost}
+ minValue={0}
+ />
+ )}
+ </div>
+ </VStack>
+ </CardContent>
+ <CardFooter>
+ <Submit isDisabled={!permissions.can("update", "production")}>
+ Save
+ </Submit>
+ </CardFooter>
+ </ValidatedForm>
+ </Card>
+ );
+};
+
+export default JobMaterialForm;
diff --git a/apps/carbon/app/modules/production/ui/Jobs/index.ts b/apps/carbon/app/modules/production/ui/Jobs/index.ts
index 14a13f1373..7dc4909957 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/index.ts
+++ b/apps/carbon/app/modules/production/ui/Jobs/index.ts
@@ -1,14 +1,22 @@
import { getDeadlineIcon, getDeadlineText } from "./Deadline";
+import JobBillOfMaterial from "./JobBillOfMaterial";
+import JobBillOfProcess from "./JobBillOfProcess";
+import JobBoMExplorer from "./JobBoMExplorer";
import JobForm from "./JobForm";
import JobHeader from "./JobHeader";
+import JobMaterialForm from "./JobMaterialForm";
import JobsTable from "./JobsTable";
import JobStatus from "./JobStatus";
export {
getDeadlineIcon,
getDeadlineText,
+ JobBillOfMaterial,
+ JobBillOfProcess,
+ JobBoMExplorer,
JobForm,
JobHeader,
+ JobMaterialForm,
JobsTable,
JobStatus,
};
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
index b88872394d..16290eb7b8 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBoMExplorer.tsx
@@ -50,7 +50,7 @@ const QuoteBoMExplorer = ({ methods }: QuoteBoMExplorerProps) => {
});
return (
- <VStack className="p-2">
+ <VStack>
{isLoading ? (
<div className="flex items-center justify-center py-8 w-full">
<Spinner className="w-4 h-4" />
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index 7a113b5d2b..e28833378e 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -256,7 +256,7 @@ function QuoteLineItem({ line, isDisabled, onDelete }: QuoteLineItemProps) {
{disclosure.isOpen &&
line.methodType === "Make" &&
permissions.can("update", "sales") && (
- <VStack className="border-b border-border">
+ <VStack className="border-b border-border p-1">
<QuoteBoMExplorer methods={methods} />
</VStack>
)}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.buy.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.buy.$methodId.$materialId.tsx
new file mode 100644
index 0000000000..57e8deb572
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.buy.$methodId.$materialId.tsx
@@ -0,0 +1,82 @@
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
+
+import {
+ getJobMaterial,
+ getJobOperationsByMethodId,
+ JobMaterialForm,
+} from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { jobId, methodId, materialId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+ if (!methodId) throw new Error("Could not find methodId");
+ if (!materialId) throw new Error("Could not find materialId");
+
+ const [material, operations] = await Promise.all([
+ getJobMaterial(client, materialId),
+ getJobOperationsByMethodId(client, methodId),
+ ]);
+
+ if (material.error) {
+ throw redirect(
+ path.to.job(jobId),
+ await flash(request, error(material.error, "Failed to load job material"))
+ );
+ }
+
+ return json({
+ material: {
+ ...material.data,
+ id: material.data.id ?? "",
+ description: material.data.description ?? "",
+ itemId: material.data.itemId ?? "",
+ itemReadableId: material.data.itemReadableId ?? "",
+ itemType: material.data.itemType as "Part",
+ methodType: material.data.methodType ?? "Make",
+ order: material.data.order ?? 1,
+ quantity: material.data.quantity ?? 0,
+ jobMakeMethodId: material.data.jobMakeMethodId ?? "",
+ jobMaterialMakeMethodId: material.data.jobMaterialMakeMethodId,
+ jobOperationId: material.data.jobOperationId ?? undefined,
+ unitCost: material.data.unitCost ?? 0,
+ unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
+ },
+ operations:
+ operations.data?.map((o) => ({
+ ...o,
+ description: o.description ?? "",
+ laborRate: o.laborRate ?? 0,
+ machineRate: o.machineRate ?? 0,
+ operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,
+ jobMakeMethodId: o.jobMakeMethodId ?? methodId,
+ workCenterId: o.workCenterId ?? undefined,
+ })) ?? [],
+ });
+}
+
+export default function JobMaterialBuyPage() {
+ const { material, operations } = useLoaderData<typeof loader>();
+
+ const { materialId } = useParams();
+ if (!materialId) throw new Error("Could not find materialId");
+
+ return (
+ <VStack spacing={2}>
+ <JobMaterialForm
+ key={materialId}
+ initialValues={material}
+ operations={operations}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
new file mode 100644
index 0000000000..7cfbd97f75
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.make.$methodId.$materialId.tsx
@@ -0,0 +1,118 @@
+import type { JSONContent } from "@carbon/react";
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
+
+import {
+ getJobMaterial,
+ getJobMaterialsByMethodId,
+ getJobOperationsByMethodId,
+ JobBillOfMaterial,
+ JobBillOfProcess,
+ JobMaterialForm,
+} from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { jobId, methodId, materialId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+ if (!methodId) throw new Error("Could not find methodId");
+ if (!materialId) throw new Error("Could not find materialId");
+
+ const [material, materials, operations] = await Promise.all([
+ getJobMaterial(client, materialId),
+ getJobMaterialsByMethodId(client, methodId),
+ getJobOperationsByMethodId(client, methodId),
+ ]);
+
+ if (material.error) {
+ throw redirect(
+ path.to.job(jobId),
+ await flash(request, error(material.error, "Failed to load job material"))
+ );
+ }
+
+ 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")
+ )
+ );
+ }
+
+ return json({
+ material: {
+ ...material.data,
+ id: material.data.id ?? "",
+ description: material.data.description ?? "",
+ itemId: material.data.itemId ?? "",
+ itemReadableId: material.data.itemReadableId ?? "",
+ itemType: material.data.itemType as "Part",
+ methodType: material.data.methodType ?? "Make",
+ order: material.data.order ?? 1,
+ quantity: material.data.quantity ?? 0,
+ jobMakeMethodId: material.data.jobMakeMethodId ?? "",
+ jobMaterialMakeMethodId: material.data.jobMaterialMakeMethodId,
+ jobOperationId: material.data.jobOperationId ?? undefined,
+ unitCost: material.data.unitCost ?? 0,
+ unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
+ },
+ 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 | null,
+ })) ?? [],
+ });
+}
+
+export default function JobMakeMethodRoute() {
+ const { methodId } = useParams();
+ if (!methodId) throw new Error("Could not find methodId");
+
+ const loaderData = useLoaderData<typeof loader>();
+ const { material, materials, operations } = loaderData;
+
+ return (
+ <VStack spacing={2} key={JSON.stringify(loaderData)}>
+ <JobMaterialForm initialValues={material} operations={operations} />
+ <JobBillOfProcess jobMakeMethodId={methodId} operations={operations} />
+ <JobBillOfMaterial
+ jobMakeMethodId={methodId}
+ materials={materials}
+ operations={operations}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx
new file mode 100644
index 0000000000..4af8c236f2
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.method.$methodId.tsx
@@ -0,0 +1,91 @@
+import type { JSONContent } from "@carbon/react";
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
+
+import {
+ getJobMaterialsByMethodId,
+ getJobOperationsByMethodId,
+ JobBillOfMaterial,
+ JobBillOfProcess,
+} from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { jobId, methodId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+ if (!methodId) throw new Error("Could not find methodId");
+
+ const [materials, operations] = await Promise.all([
+ getJobMaterialsByMethodId(client, methodId),
+ getJobOperationsByMethodId(client, methodId),
+ ]);
+
+ 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")
+ )
+ );
+ }
+
+ return json({
+ 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,
+ })) ?? [],
+ });
+}
+
+export default function JobMakeMethodRoute() {
+ const { jobId, methodId } = useParams();
+ if (!jobId) throw new Error("Could not find jobId");
+ if (!methodId) throw new Error("Could not find methodId");
+
+ const loaderData = useLoaderData<typeof loader>();
+ const { materials, operations } = loaderData;
+
+ return (
+ <VStack spacing={2} key={JSON.stringify(loaderData)}>
+ <JobBillOfProcess jobMakeMethodId={methodId} operations={operations} />
+ <JobBillOfMaterial
+ jobMakeMethodId={methodId}
+ materials={materials}
+ operations={operations}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.pick.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.pick.$methodId.$materialId.tsx
new file mode 100644
index 0000000000..74ebb4d430
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/$jobId.pick.$methodId.$materialId.tsx
@@ -0,0 +1,82 @@
+import { VStack } from "@carbon/react";
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
+
+import {
+ getJobMaterial,
+ getJobOperationsByMethodId,
+ JobMaterialForm,
+} from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "production",
+ });
+
+ const { jobId, methodId, materialId } = params;
+ if (!jobId) throw new Error("Could not find jobId");
+ if (!methodId) throw new Error("Could not find methodId");
+ if (!materialId) throw new Error("Could not find materialId");
+
+ const [material, operations] = await Promise.all([
+ getJobMaterial(client, materialId),
+ getJobOperationsByMethodId(client, methodId),
+ ]);
+
+ if (material.error) {
+ throw redirect(
+ path.to.job(jobId),
+ await flash(request, error(material.error, "Failed to load job material"))
+ );
+ }
+
+ return json({
+ material: {
+ ...material.data,
+ id: material.data.id ?? "",
+ description: material.data.description ?? "",
+ itemId: material.data.itemId ?? "",
+ itemReadableId: material.data.itemReadableId ?? "",
+ itemType: material.data.itemType as "Part",
+ methodType: material.data.methodType ?? "Make",
+ order: material.data.order ?? 1,
+ quantity: material.data.quantity ?? 0,
+ jobMakeMethodId: material.data.jobMakeMethodId ?? "",
+ jobMaterialMakeMethodId: material.data.jobMaterialMakeMethodId,
+ jobOperationId: material.data.jobOperationId ?? undefined,
+ unitCost: material.data.unitCost ?? 0,
+ unitOfMeasureCode: material.data.unitOfMeasureCode ?? "",
+ },
+ operations:
+ operations.data?.map((o) => ({
+ ...o,
+ description: o.description ?? "",
+ laborRate: o.laborRate ?? 0,
+ machineRate: o.machineRate ?? 0,
+ operationSupplierProcessId: o.operationSupplierProcessId ?? undefined,
+ jobMakeMethodId: o.jobMakeMethodId ?? methodId,
+ workCenterId: o.workCenterId ?? undefined,
+ })) ?? [],
+ });
+}
+
+export default function JobMaterialPickPage() {
+ const { material, operations } = useLoaderData<typeof loader>();
+
+ const { materialId } = useParams();
+ if (!materialId) throw new Error("Could not find materialId");
+
+ return (
+ <VStack spacing={2}>
+ <JobMaterialForm
+ key={materialId}
+ initialValues={material}
+ operations={operations}
+ />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/$jobId.tsx b/apps/carbon/app/routes/x+/job+/$jobId.tsx
index 67f33a9ea7..c0fe513dd6 100644
--- a/apps/carbon/app/routes/x+/job+/$jobId.tsx
+++ b/apps/carbon/app/routes/x+/job+/$jobId.tsx
@@ -7,8 +7,21 @@ import {
VStack,
} from "@carbon/react";
import type { LoaderFunctionArgs } from "@remix-run/node";
-import { json, Outlet, redirect, useParams } from "@remix-run/react";
-import { getJob, getJobDocuments, JobHeader } from "~/modules/production";
+import {
+ json,
+ Outlet,
+ redirect,
+ useLoaderData,
+ useParams,
+} from "@remix-run/react";
+import { flattenTree } from "~/components/TreeView";
+import {
+ getJob,
+ getJobDocuments,
+ getJobMethodTree,
+ JobBoMExplorer,
+ JobHeader,
+} from "~/modules/production";
import {} from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
@@ -40,19 +53,19 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const files = await getJobDocuments(client, companyId, job.data);
- // const methods = await getJobMethodTrees(client, jobId);
+ const method = await getJobMethodTree(client, jobId);
- // if (methods.error) {
- // throw redirect(
- // path.to.jobs,
- // await flash(request, error(methods.error, "Failed to load job method"))
- // );
- // }
+ if (method.error) {
+ throw redirect(
+ path.to.jobs,
+ await flash(request, error(method.error, "Failed to load job method"))
+ );
+ }
return json({
job: job.data,
files: files,
- // methods: methods.data ?? [],
+ method: method.data ?? [],
});
}
@@ -61,6 +74,9 @@ export default function JobRoute() {
const { jobId } = params;
if (!jobId) throw new Error("Could not find jobId");
+ const { method } = useLoaderData<typeof loader>();
+ const flattenedTree = method.length > 0 ? flattenTree(method[0]) : [];
+
return (
<div className="flex flex-col h-[calc(100vh-49px)] w-full">
<JobHeader />
@@ -77,8 +93,8 @@ export default function JobRoute() {
className="bg-card h-full"
>
<ScrollArea className="h-[calc(100vh-99px)]">
- <div className="grid w-full h-full overflow-hidden">
- {/* <JobExplorer /> */}
+ <div className="grid w-full h-full overflow-hidden p-2">
+ <JobBoMExplorer method={flattenedTree} />
</div>
</ScrollArea>
</ResizablePanel>
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
new file mode 100644
index 0000000000..94a5a58fc8
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.$id.tsx
@@ -0,0 +1,71 @@
+import { validationError, validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@remix-run/node";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import { jobMaterialValidator, upsertJobMaterial } from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ create: "production",
+ });
+
+ const { jobId, id } = params;
+ if (!jobId) {
+ throw new Error("jobId not found");
+ }
+
+ if (!id) {
+ throw new Error("id not found");
+ }
+
+ const formData = await request.formData();
+ const validation = await validator(jobMaterialValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const serviceRole = getSupabaseServiceRole();
+ const updateJobMaterial = await upsertJobMaterial(serviceRole, {
+ jobId,
+ ...validation.data,
+ id: id,
+ companyId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (updateJobMaterial.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(updateJobMaterial.error, "Failed to update job material")
+ )
+ );
+ }
+
+ const jobMaterialId = updateJobMaterial.data?.id;
+ if (!jobMaterialId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(updateJobMaterial, "Failed to update job material")
+ )
+ );
+ }
+
+ return json({
+ id: jobMaterialId,
+ methodType: updateJobMaterial.data.methodType,
+ });
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
new file mode 100644
index 0000000000..5dbaf648d2
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.delete.$id.tsx
@@ -0,0 +1,33 @@
+import { json, type ActionFunctionArgs } from "@remix-run/node";
+import { deleteJobMaterial } from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "production",
+ });
+
+ const { id } = params;
+ if (!id) {
+ throw new Error("id not found");
+ }
+
+ const deleteMaterial = await deleteJobMaterial(client, id);
+ if (deleteMaterial.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(deleteMaterial.error, "Failed to delete job material")
+ )
+ );
+ }
+
+ return json({});
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx
new file mode 100644
index 0000000000..c737e48fe1
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.material.new.tsx
@@ -0,0 +1,90 @@
+import { validationError, validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@remix-run/node";
+import { getSupabaseServiceRole } from "~/lib/supabase";
+import {
+ jobMaterialValidator,
+ upsertJobMaterial,
+ upsertJobMaterialMakeMethod,
+} from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { companyId, userId } = await requirePermissions(request, {
+ create: "production",
+ });
+
+ const { jobId } = params;
+ if (!jobId) {
+ throw new Error("jobId not found");
+ }
+
+ const formData = await request.formData();
+ const validation = await validator(jobMaterialValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const serviceRole = getSupabaseServiceRole();
+ const insertJobMaterial = await upsertJobMaterial(serviceRole, {
+ ...data,
+ jobId,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (insertJobMaterial.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insertJobMaterial.error, "Failed to insert job material")
+ )
+ );
+ }
+
+ const jobMaterialId = insertJobMaterial.data?.id;
+ if (!jobMaterialId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insertJobMaterial, "Failed to insert job material")
+ )
+ );
+ }
+
+ if (data.methodType === "Make") {
+ const makeMethod = await upsertJobMaterialMakeMethod(serviceRole, {
+ ...data,
+ jobMaterialId,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (makeMethod.error) {
+ return json(
+ {
+ id: jobMaterialId,
+ },
+ await flash(
+ request,
+ error(makeMethod.error, "Failed to insert job material make method")
+ )
+ );
+ }
+ }
+
+ return json({ id: jobMaterialId });
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.$id.tsx
new file mode 100644
index 0000000000..4f55b49875
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.$id.tsx
@@ -0,0 +1,68 @@
+import { validationError, validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@remix-run/node";
+import {
+ jobOperationValidator,
+ upsertJobOperation,
+} from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production",
+ });
+
+ const { jobId, id } = params;
+ if (!jobId) {
+ throw new Error("jobId not found");
+ }
+ if (!id) {
+ throw new Error("id not found");
+ }
+
+ const formData = await request.formData();
+ const validation = await validator(jobOperationValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const updateJobOperation = await upsertJobOperation(client, {
+ jobId,
+ ...validation.data,
+ id: id,
+ companyId,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (updateJobOperation.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(updateJobOperation.error, "Failed to update job operation")
+ )
+ );
+ }
+
+ const jobOperationId = updateJobOperation.data?.id;
+ if (!jobOperationId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(updateJobOperation, "Failed to update job operation")
+ )
+ );
+ }
+
+ return json({ id: jobOperationId });
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx b/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
new file mode 100644
index 0000000000..e785102356
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/$jobId.operation.new.tsx
@@ -0,0 +1,66 @@
+import { validationError, validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@remix-run/node";
+import {
+ jobOperationValidator,
+ upsertJobOperation,
+} from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production",
+ });
+
+ const { jobId } = params;
+ if (!jobId) {
+ throw new Error("jobId not found");
+ }
+
+ const formData = await request.formData();
+ const validation = await validator(jobOperationValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const insertJobOperation = await upsertJobOperation(client, {
+ ...data,
+ jobId,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+ if (insertJobOperation.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insertJobOperation.error, "Failed to insert job operation")
+ )
+ );
+ }
+
+ const jobOperationId = insertJobOperation.data?.id;
+ if (!jobOperationId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insertJobOperation, "Failed to insert job operation")
+ )
+ );
+ }
+
+ return json({ id: jobOperationId });
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/get.tsx b/apps/carbon/app/routes/x+/job+/methods+/get.tsx
new file mode 100644
index 0000000000..ba7ba9aa8d
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/get.tsx
@@ -0,0 +1,67 @@
+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,
+} from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "production",
+ });
+
+ const formData = await request.formData();
+ const type = formData.get("type") as string;
+
+ const serviceRole = getSupabaseServiceRole();
+ if (type === "method") {
+ const validation = await validator(getJobMethodValidator).validate(
+ formData
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const jobMethod = await upsertJobMethod(serviceRole, {
+ ...validation.data,
+ companyId,
+ userId,
+ });
+
+ return json({
+ error: jobMethod.error ? "Failed to get job method" : null,
+ });
+ }
+
+ if (type === "material") {
+ const validation = await validator(getJobMaterialMethodValidator).validate(
+ formData
+ );
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const makeMethod = await upsertJobMaterialMakeMethod(serviceRole, {
+ ...validation.data,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (makeMethod.error) {
+ return json({
+ error: makeMethod.error
+ ? "Failed to insert job material make method"
+ : null,
+ });
+ }
+
+ throw redirect(requestReferrer(request) ?? path.to.jobs);
+ }
+
+ return json({ error: "Invalid type" }, { status: 400 });
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/material.order.tsx b/apps/carbon/app/routes/x+/job+/methods+/material.order.tsx
new file mode 100644
index 0000000000..99def21c82
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/material.order.tsx
@@ -0,0 +1,42 @@
+import { json, type ActionFunctionArgs } from "@remix-run/node";
+
+import { updateJobMaterialOrder } from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production",
+ });
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return json(
+ {},
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, orderString]) => ({
+ id,
+ order: Number(orderString),
+ updatedBy: userId,
+ })
+ );
+
+ const updateSortOrders = await updateJobMaterialOrder(client, updates);
+ if (updateSortOrders.some((update) => update.error))
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateSortOrders, "Failed to update sort order")
+ )
+ );
+
+ return null;
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/operation.order.tsx b/apps/carbon/app/routes/x+/job+/methods+/operation.order.tsx
new file mode 100644
index 0000000000..02edb4f633
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/operation.order.tsx
@@ -0,0 +1,42 @@
+import { json, type ActionFunctionArgs } from "@remix-run/node";
+
+import { updateJobOperationOrder } from "~/modules/production";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { error } from "~/utils/result";
+
+export async function action({ request }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "production",
+ });
+
+ const updateMap = (await request.formData()).get("updates") as string;
+ if (!updateMap) {
+ return json(
+ {},
+ await flash(request, error(null, "Failed to receive a new sort order"))
+ );
+ }
+
+ const updates = Object.entries(JSON.parse(updateMap)).map(
+ ([id, orderString]) => ({
+ id,
+ order: Number(orderString),
+ updatedBy: userId,
+ })
+ );
+
+ const updateSortOrders = await updateJobOperationOrder(client, updates);
+ if (updateSortOrders.some((update) => update.error))
+ return json(
+ {},
+ await flash(
+ request,
+ error(updateSortOrders, "Failed to update sort order")
+ )
+ );
+
+ return null;
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/save.tsx b/apps/carbon/app/routes/x+/job+/methods+/save.tsx
new file mode 100644
index 0000000000..3130c9022d
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/save.tsx
@@ -0,0 +1,67 @@
+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";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { path, requestReferrer } from "~/utils/path";
+
+export async function action({ request }: ActionFunctionArgs) {
+ const { companyId, userId } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const formData = await request.formData();
+ 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 lineMethod = await upsertMakeMethodFromQuoteLine(serviceRole, {
+ ...validation.data,
+ companyId,
+ userId,
+ });
+
+ return json({
+ error: lineMethod.error
+ ? "Failed to save quote 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, {
+ ...validation.data,
+ companyId,
+ createdBy: userId,
+ });
+
+ if (makeMethod.error) {
+ return json({
+ error: makeMethod.error
+ ? "Failed to save quote method to make method"
+ : null,
+ });
+ }
+
+ throw redirect(requestReferrer(request) ?? path.to.quotes);
+ }
+
+ return json({ error: "Invalid type" }, { status: 400 });
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index f351843fc0..7df237f4aa 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -232,6 +232,8 @@ export const path = {
deleteItemPostingGroup: (id: string) =>
generatePath(`${x}/items/groups/delete/${id}`),
deleteJob: (id: string) => generatePath(`${x}/job/${id}/delete`),
+ deleteJobMaterial: (jobId: string, id: string) =>
+ generatePath(`${x}/job/methods/${jobId}/material/delete/${id}`),
deleteMaterialForm: (id: string) =>
generatePath(`${x}/items/forms/delete/${id}`),
deleteMaterialSubstance: (id: string) =>
@@ -354,6 +356,26 @@ export const path = {
itemPostingGroups: `${x}/items/groups`,
job: (id: string) => generatePath(`${x}/job/${id}`),
jobDetails: (id: string) => generatePath(`${x}/job/${id}/details`),
+ jobMaterial: (jobId: string, id: string) =>
+ generatePath(`${x}/job/methods/${jobId}/material/${id}`),
+ jobMethod: (jobId: string, methodId: string) =>
+ generatePath(`${x}/job/${jobId}/method/${methodId}`),
+ jobMakeMethod: (jobId: string, makeMethodId: string, materialId: string) =>
+ generatePath(`${x}/job/${jobId}/make/${makeMethodId}/${materialId}`),
+ jobMethodMaterial: (
+ jobId: string,
+ methodType: string,
+ makeMethodId: string,
+ materialId: string
+ ) =>
+ generatePath(
+ `${x}/job/${jobId}/${methodType}/${makeMethodId}/${materialId}`
+ ),
+ jobMaterialsOrder: `${x}/job/methods/material/order`,
+ jobMethodGet: `${x}/job/methods/get`,
+ jobOperation: (jobId: string, id: string) =>
+ generatePath(`${x}/job/methods/${jobId}/operation/${id}`),
+ jobOperationsOrder: `${x}/job/methods/operation/order`,
jobs: `${x}/production/jobs`,
location: (id: string) => generatePath(`${x}/resources/locations/${id}`),
locations: `${x}/resources/locations`,
@@ -435,6 +457,10 @@ export const path = {
newGroup: `${x}/users/groups/new`,
newHoliday: `${x}/people/holidays/new`,
newJob: `${x}/job/new`,
+ newJobMaterial: (jobId: string) =>
+ generatePath(`${x}/job/methods/${jobId}/material/new`),
+ newJobOperation: (jobId: string) =>
+ generatePath(`${x}/job/methods/${jobId}/operation/new`),
newLocation: `${x}/resources/locations/new`,
newMaterial: `${x}/material/new`,
newMethodMaterial: `${x}/items/methods/material/new`,
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 28937c3ef7..6455970fc8 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -4416,6 +4416,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.jobId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.jobMakeMethodId",
+ },
{
$ref: "#/parameters/rowFilter.jobOperation.order",
},
@@ -4449,15 +4452,33 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.operationOrder",
},
- {
- $ref: "#/parameters/rowFilter.jobOperation.quotingRate",
- },
{
$ref: "#/parameters/rowFilter.jobOperation.laborRate",
},
{
$ref: "#/parameters/rowFilter.jobOperation.overheadRate",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.machineRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationMinimumCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationLeadTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationUnitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationSupplierProcessId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.workInstruction",
+ },
{
$ref: "#/parameters/rowFilter.jobOperation.companyId",
},
@@ -4476,9 +4497,6 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.customFields",
},
- {
- $ref: "#/parameters/rowFilter.jobOperation.workInstruction",
- },
{
$ref: "#/parameters/select",
},
@@ -4515,7 +4533,6 @@ export default {
description: "Partial Content",
},
},
- summary: "Stores information about operations performed in jobs",
tags: ["jobOperation"],
},
post: {
@@ -4535,7 +4552,6 @@ export default {
description: "Created",
},
},
- summary: "Stores information about operations performed in jobs",
tags: ["jobOperation"],
},
delete: {
@@ -4546,6 +4562,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.jobId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.jobMakeMethodId",
+ },
{
$ref: "#/parameters/rowFilter.jobOperation.order",
},
@@ -4579,15 +4598,33 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.operationOrder",
},
- {
- $ref: "#/parameters/rowFilter.jobOperation.quotingRate",
- },
{
$ref: "#/parameters/rowFilter.jobOperation.laborRate",
},
{
$ref: "#/parameters/rowFilter.jobOperation.overheadRate",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.machineRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationMinimumCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationLeadTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationUnitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationSupplierProcessId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.workInstruction",
+ },
{
$ref: "#/parameters/rowFilter.jobOperation.companyId",
},
@@ -4606,9 +4643,6 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.customFields",
},
- {
- $ref: "#/parameters/rowFilter.jobOperation.workInstruction",
- },
{
$ref: "#/parameters/preferReturn",
},
@@ -4618,7 +4652,6 @@ export default {
description: "No Content",
},
},
- summary: "Stores information about operations performed in jobs",
tags: ["jobOperation"],
},
patch: {
@@ -4629,6 +4662,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.jobId",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.jobMakeMethodId",
+ },
{
$ref: "#/parameters/rowFilter.jobOperation.order",
},
@@ -4662,15 +4698,33 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.operationOrder",
},
- {
- $ref: "#/parameters/rowFilter.jobOperation.quotingRate",
- },
{
$ref: "#/parameters/rowFilter.jobOperation.laborRate",
},
{
$ref: "#/parameters/rowFilter.jobOperation.overheadRate",
},
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.machineRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationMinimumCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationLeadTime",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationUnitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.operationSupplierProcessId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobOperation.workInstruction",
+ },
{
$ref: "#/parameters/rowFilter.jobOperation.companyId",
},
@@ -4689,9 +4743,6 @@ export default {
{
$ref: "#/parameters/rowFilter.jobOperation.customFields",
},
- {
- $ref: "#/parameters/rowFilter.jobOperation.workInstruction",
- },
{
$ref: "#/parameters/body.jobOperation",
},
@@ -4704,7 +4755,6 @@ export default {
description: "No Content",
},
},
- summary: "Stores information about operations performed in jobs",
tags: ["jobOperation"],
},
},
@@ -9298,44 +9348,41 @@ export default {
tags: ["country"],
},
},
- "/contact": {
+ "/jobMakeMethod": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.contact.id",
- },
- {
- $ref: "#/parameters/rowFilter.contact.firstName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.id",
},
{
- $ref: "#/parameters/rowFilter.contact.lastName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.jobId",
},
{
- $ref: "#/parameters/rowFilter.contact.fullName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.parentMaterialId",
},
{
- $ref: "#/parameters/rowFilter.contact.email",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.itemId",
},
{
- $ref: "#/parameters/rowFilter.contact.title",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.quantityPerParent",
},
{
- $ref: "#/parameters/rowFilter.contact.mobilePhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.companyId",
},
{
- $ref: "#/parameters/rowFilter.contact.homePhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.createdAt",
},
{
- $ref: "#/parameters/rowFilter.contact.workPhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.createdBy",
},
{
- $ref: "#/parameters/rowFilter.contact.fax",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.contact.notes",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.updatedBy",
},
{
- $ref: "#/parameters/rowFilter.contact.companyId",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.customFields",
},
{
$ref: "#/parameters/select",
@@ -9364,7 +9411,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/contact",
+ $ref: "#/definitions/jobMakeMethod",
},
type: "array",
},
@@ -9373,12 +9420,12 @@ export default {
description: "Partial Content",
},
},
- tags: ["contact"],
+ tags: ["jobMakeMethod"],
},
post: {
parameters: [
{
- $ref: "#/parameters/body.contact",
+ $ref: "#/parameters/body.jobMakeMethod",
},
{
$ref: "#/parameters/select",
@@ -9392,45 +9439,42 @@ export default {
description: "Created",
},
},
- tags: ["contact"],
+ tags: ["jobMakeMethod"],
},
delete: {
parameters: [
{
- $ref: "#/parameters/rowFilter.contact.id",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.id",
},
{
- $ref: "#/parameters/rowFilter.contact.firstName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.jobId",
},
{
- $ref: "#/parameters/rowFilter.contact.lastName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.parentMaterialId",
},
{
- $ref: "#/parameters/rowFilter.contact.fullName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.itemId",
},
{
- $ref: "#/parameters/rowFilter.contact.email",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.quantityPerParent",
},
{
- $ref: "#/parameters/rowFilter.contact.title",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.companyId",
},
{
- $ref: "#/parameters/rowFilter.contact.mobilePhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.createdAt",
},
{
- $ref: "#/parameters/rowFilter.contact.homePhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.createdBy",
},
{
- $ref: "#/parameters/rowFilter.contact.workPhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.contact.fax",
- },
- {
- $ref: "#/parameters/rowFilter.contact.notes",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.updatedBy",
},
{
- $ref: "#/parameters/rowFilter.contact.companyId",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.customFields",
},
{
$ref: "#/parameters/preferReturn",
@@ -9441,48 +9485,45 @@ export default {
description: "No Content",
},
},
- tags: ["contact"],
+ tags: ["jobMakeMethod"],
},
patch: {
parameters: [
{
- $ref: "#/parameters/rowFilter.contact.id",
- },
- {
- $ref: "#/parameters/rowFilter.contact.firstName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.id",
},
{
- $ref: "#/parameters/rowFilter.contact.lastName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.jobId",
},
{
- $ref: "#/parameters/rowFilter.contact.fullName",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.parentMaterialId",
},
{
- $ref: "#/parameters/rowFilter.contact.email",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.itemId",
},
{
- $ref: "#/parameters/rowFilter.contact.title",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.quantityPerParent",
},
{
- $ref: "#/parameters/rowFilter.contact.mobilePhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.companyId",
},
{
- $ref: "#/parameters/rowFilter.contact.homePhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.createdAt",
},
{
- $ref: "#/parameters/rowFilter.contact.workPhone",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.createdBy",
},
{
- $ref: "#/parameters/rowFilter.contact.fax",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.updatedAt",
},
{
- $ref: "#/parameters/rowFilter.contact.notes",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.updatedBy",
},
{
- $ref: "#/parameters/rowFilter.contact.companyId",
+ $ref: "#/parameters/rowFilter.jobMakeMethod.customFields",
},
{
- $ref: "#/parameters/body.contact",
+ $ref: "#/parameters/body.jobMakeMethod",
},
{
$ref: "#/parameters/preferReturn",
@@ -9493,20 +9534,47 @@ export default {
description: "No Content",
},
},
- tags: ["contact"],
+ tags: ["jobMakeMethod"],
},
},
- "/userDefaults": {
+ "/contact": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.userDefaults.userId",
+ $ref: "#/parameters/rowFilter.contact.id",
},
{
- $ref: "#/parameters/rowFilter.userDefaults.companyId",
+ $ref: "#/parameters/rowFilter.contact.firstName",
},
{
- $ref: "#/parameters/rowFilter.userDefaults.locationId",
+ $ref: "#/parameters/rowFilter.contact.lastName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.fullName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.email",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.title",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.mobilePhone",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.homePhone",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.workPhone",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.fax",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.notes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.companyId",
},
{
$ref: "#/parameters/select",
@@ -9535,7 +9603,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/userDefaults",
+ $ref: "#/definitions/contact",
},
type: "array",
},
@@ -9544,65 +9612,245 @@ export default {
description: "Partial Content",
},
},
- tags: ["userDefaults"],
+ tags: ["contact"],
},
- },
- "/jobMaterial": {
- get: {
+ post: {
parameters: [
{
- $ref: "#/parameters/rowFilter.jobMaterial.id",
+ $ref: "#/parameters/body.contact",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.jobId",
+ $ref: "#/parameters/select",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.itemId",
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
},
+ },
+ tags: ["contact"],
+ },
+ delete: {
+ parameters: [
{
- $ref: "#/parameters/rowFilter.jobMaterial.itemReadableId",
+ $ref: "#/parameters/rowFilter.contact.id",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.itemType",
+ $ref: "#/parameters/rowFilter.contact.firstName",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.methodType",
+ $ref: "#/parameters/rowFilter.contact.lastName",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.order",
+ $ref: "#/parameters/rowFilter.contact.fullName",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.description",
+ $ref: "#/parameters/rowFilter.contact.email",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.quantity",
+ $ref: "#/parameters/rowFilter.contact.title",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.unitOfMeasureCode",
+ $ref: "#/parameters/rowFilter.contact.mobilePhone",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.unitCost",
+ $ref: "#/parameters/rowFilter.contact.homePhone",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.companyId",
+ $ref: "#/parameters/rowFilter.contact.workPhone",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.createdAt",
+ $ref: "#/parameters/rowFilter.contact.fax",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.createdBy",
+ $ref: "#/parameters/rowFilter.contact.notes",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.updatedAt",
+ $ref: "#/parameters/rowFilter.contact.companyId",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.updatedBy",
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
},
+ },
+ tags: ["contact"],
+ },
+ patch: {
+ parameters: [
{
- $ref: "#/parameters/rowFilter.jobMaterial.customFields",
+ $ref: "#/parameters/rowFilter.contact.id",
},
{
- $ref: "#/parameters/rowFilter.jobMaterial.jobOperationId",
+ $ref: "#/parameters/rowFilter.contact.firstName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.lastName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.fullName",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.email",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.title",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.mobilePhone",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.homePhone",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.workPhone",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.fax",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.notes",
+ },
+ {
+ $ref: "#/parameters/rowFilter.contact.companyId",
+ },
+ {
+ $ref: "#/parameters/body.contact",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["contact"],
+ },
+ },
+ "/userDefaults": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.userDefaults.userId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.userDefaults.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.userDefaults.locationId",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/userDefaults",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["userDefaults"],
+ },
+ },
+ "/jobMaterial": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.itemId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.itemReadableId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.itemType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.methodType",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.order",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.description",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.quantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.scrapQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.productionQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.unitOfMeasureCode",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.unitCost",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.jobMakeMethodId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.jobOperationId",
},
{
$ref: "#/parameters/select",
@@ -9640,7 +9888,6 @@ export default {
description: "Partial Content",
},
},
- summary: "Stores information about materials used in jobs",
tags: ["jobMaterial"],
},
post: {
@@ -9660,7 +9907,6 @@ export default {
description: "Created",
},
},
- summary: "Stores information about materials used in jobs",
tags: ["jobMaterial"],
},
delete: {
@@ -9692,6 +9938,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.quantity",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.scrapQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.productionQuantity",
+ },
{
$ref: "#/parameters/rowFilter.jobMaterial.unitOfMeasureCode",
},
@@ -9716,6 +9968,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.customFields",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.jobMakeMethodId",
+ },
{
$ref: "#/parameters/rowFilter.jobMaterial.jobOperationId",
},
@@ -9728,7 +9983,6 @@ export default {
description: "No Content",
},
},
- summary: "Stores information about materials used in jobs",
tags: ["jobMaterial"],
},
patch: {
@@ -9760,6 +10014,12 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.quantity",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.scrapQuantity",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.productionQuantity",
+ },
{
$ref: "#/parameters/rowFilter.jobMaterial.unitOfMeasureCode",
},
@@ -9784,6 +10044,9 @@ export default {
{
$ref: "#/parameters/rowFilter.jobMaterial.customFields",
},
+ {
+ $ref: "#/parameters/rowFilter.jobMaterial.jobMakeMethodId",
+ },
{
$ref: "#/parameters/rowFilter.jobMaterial.jobOperationId",
},
@@ -9799,7 +10062,6 @@ export default {
description: "No Content",
},
},
- summary: "Stores information about materials used in jobs",
tags: ["jobMaterial"],
},
},
@@ -22733,6 +22995,114 @@ export default {
tags: ["salesRfqLines"],
},
},
+ "/jobFavorite": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobFavorite.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobFavorite.userId",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/jobFavorite",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["jobFavorite"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.jobFavorite",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["jobFavorite"],
+ },
+ delete: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobFavorite.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobFavorite.userId",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["jobFavorite"],
+ },
+ patch: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.jobFavorite.jobId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobFavorite.userId",
+ },
+ {
+ $ref: "#/parameters/body.jobFavorite",
+ },
+ {
+ $ref: "#/parameters/preferReturn",
+ },
+ ],
+ responses: {
+ "204": {
+ description: "No Content",
+ },
+ },
+ tags: ["jobFavorite"],
+ },
+ },
"/documentTransaction": {
get: {
parameters: [
@@ -30077,50 +30447,74 @@ export default {
tags: ["quoteLine"],
},
},
- "/currency": {
+ "/jobMaterialWithMakeMethodId": {
get: {
parameters: [
{
- $ref: "#/parameters/rowFilter.currency.id",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.id",
},
{
- $ref: "#/parameters/rowFilter.currency.name",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.jobId",
},
{
- $ref: "#/parameters/rowFilter.currency.code",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.itemId",
},
{
- $ref: "#/parameters/rowFilter.currency.symbol",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.itemReadableId",
},
{
- $ref: "#/parameters/rowFilter.currency.exchangeRate",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.itemType",
},
{
- $ref: "#/parameters/rowFilter.currency.decimalPlaces",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.methodType",
},
{
- $ref: "#/parameters/rowFilter.currency.isBaseCurrency",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.order",
},
{
- $ref: "#/parameters/rowFilter.currency.active",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.description",
},
{
- $ref: "#/parameters/rowFilter.currency.companyId",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.quantity",
},
{
- $ref: "#/parameters/rowFilter.currency.createdBy",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.scrapQuantity",
},
{
- $ref: "#/parameters/rowFilter.currency.createdAt",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.productionQuantity",
},
{
- $ref: "#/parameters/rowFilter.currency.updatedBy",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.unitOfMeasureCode",
},
{
- $ref: "#/parameters/rowFilter.currency.updatedAt",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.unitCost",
},
{
- $ref: "#/parameters/rowFilter.currency.customFields",
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.customFields",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.jobMakeMethodId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.jobOperationId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.jobMaterialWithMakeMethodId.jobMaterialMakeMethodId",
},
{
$ref: "#/parameters/select",
@@ -30149,7 +30543,7 @@ export default {
description: "OK",
schema: {
items: {
- $ref: "#/definitions/currency",
+ $ref: "#/definitions/jobMaterialWithMakeMethodId",
},
type: "array",
},
@@ -30158,28 +30552,112 @@ export default {
description: "Partial Content",
},
},
- tags: ["currency"],
+ tags: ["jobMaterialWithMakeMethodId"],
},
- post: {
- parameters: [
- {
- $ref: "#/parameters/body.currency",
- },
- {
- $ref: "#/parameters/select",
- },
- {
- $ref: "#/parameters/preferPost",
- },
- ],
- responses: {
- "201": {
- description: "Created",
- },
- },
- tags: ["currency"],
- },
- delete: {
+ },
+ "/currency": {
+ get: {
+ parameters: [
+ {
+ $ref: "#/parameters/rowFilter.currency.id",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.name",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.code",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.symbol",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.exchangeRate",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.decimalPlaces",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.isBaseCurrency",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.active",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.companyId",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.createdBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.createdAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.updatedBy",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.updatedAt",
+ },
+ {
+ $ref: "#/parameters/rowFilter.currency.customFields",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/order",
+ },
+ {
+ $ref: "#/parameters/range",
+ },
+ {
+ $ref: "#/parameters/rangeUnit",
+ },
+ {
+ $ref: "#/parameters/offset",
+ },
+ {
+ $ref: "#/parameters/limit",
+ },
+ {
+ $ref: "#/parameters/preferCount",
+ },
+ ],
+ responses: {
+ "200": {
+ description: "OK",
+ schema: {
+ items: {
+ $ref: "#/definitions/currency",
+ },
+ type: "array",
+ },
+ },
+ "206": {
+ description: "Partial Content",
+ },
+ },
+ tags: ["currency"],
+ },
+ post: {
+ parameters: [
+ {
+ $ref: "#/parameters/body.currency",
+ },
+ {
+ $ref: "#/parameters/select",
+ },
+ {
+ $ref: "#/parameters/preferPost",
+ },
+ ],
+ responses: {
+ "201": {
+ description: "Created",
+ },
+ },
+ tags: ["currency"],
+ },
+ delete: {
parameters: [
{
$ref: "#/parameters/rowFilter.currency.id",
@@ -33823,6 +34301,63 @@ export default {
tags: ["(rpc) is_claims_admin"],
},
},
+ "/rpc/get_job_method": {
+ get: {
+ parameters: [
+ {
+ format: "text",
+ in: "query",
+ name: "jid",
+ 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_method"],
+ },
+ post: {
+ parameters: [
+ {
+ in: "body",
+ name: "args",
+ required: true,
+ schema: {
+ properties: {
+ jid: {
+ format: "text",
+ type: "string",
+ },
+ },
+ required: ["jid"],
+ 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_method"],
+ },
+ },
"/rpc/get_quote_methods_by_method_id": {
get: {
parameters: [
@@ -35968,7 +36503,6 @@ export default {
type: "object",
},
jobOperation: {
- description: "Stores information about operations performed in jobs",
required: [
"id",
"jobId",
@@ -35981,13 +36515,16 @@ export default {
"machineTime",
"machineUnit",
"operationOrder",
- "quotingRate",
"laborRate",
"overheadRate",
+ "operationType",
+ "operationMinimumCost",
+ "operationLeadTime",
+ "operationUnitCost",
+ "workInstruction",
"companyId",
"createdAt",
"createdBy",
- "workInstruction",
],
properties: {
id: {
@@ -36002,6 +36539,12 @@ export default {
format: "text",
type: "string",
},
+ jobMakeMethodId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobMakeMethod.id`.<fk table='jobMakeMethod' column='id'/>",
+ format: "text",
+ type: "string",
+ },
order: {
default: 1,
format: "double precision",
@@ -36098,21 +36641,49 @@ export default {
format: 'public."methodOperationOrder"',
type: "string",
},
- quotingRate: {
+ laborRate: {
default: 0,
format: "numeric",
type: "number",
},
- laborRate: {
+ overheadRate: {
default: 0,
format: "numeric",
type: "number",
},
- overheadRate: {
+ machineRate: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ operationType: {
+ default: "Inside",
+ enum: ["Inside", "Outside"],
+ format: 'public."operationType"',
+ type: "string",
+ },
+ operationMinimumCost: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ operationLeadTime: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ operationUnitCost: {
default: 0,
format: "numeric",
type: "number",
},
+ operationSupplierProcessId: {
+ format: "text",
+ type: "string",
+ },
+ workInstruction: {
+ format: "json",
+ },
companyId: {
description:
"Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
@@ -36143,9 +36714,6 @@ export default {
customFields: {
format: "jsonb",
},
- workInstruction: {
- format: "json",
- },
},
type: "object",
},
@@ -38183,6 +38751,79 @@ export default {
},
type: "object",
},
+ jobMakeMethod: {
+ required: [
+ "id",
+ "jobId",
+ "itemId",
+ "quantityPerParent",
+ "companyId",
+ "createdAt",
+ "createdBy",
+ ],
+ properties: {
+ id: {
+ default: "public.xid()",
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ jobId: {
+ description:
+ "Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ parentMaterialId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobMaterial.id`.<fk table='jobMaterial' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ quantityPerParent: {
+ default: 1,
+ format: "numeric",
+ type: "number",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ default: "now()",
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ customFields: {
+ format: "jsonb",
+ },
+ },
+ type: "object",
+ },
contact: {
required: ["id", "firstName", "lastName", "email", "companyId"],
properties: {
@@ -38264,7 +38905,6 @@ export default {
type: "object",
},
jobMaterial: {
- description: "Stores information about materials used in jobs",
required: [
"id",
"jobId",
@@ -38275,10 +38915,12 @@ export default {
"order",
"description",
"quantity",
+ "scrapQuantity",
"unitCost",
"companyId",
"createdAt",
"createdBy",
+ "jobMakeMethodId",
],
properties: {
id: {
@@ -38328,6 +38970,15 @@ export default {
format: "numeric",
type: "number",
},
+ scrapQuantity: {
+ default: 0,
+ format: "numeric",
+ type: "number",
+ },
+ productionQuantity: {
+ format: "numeric",
+ type: "number",
+ },
unitOfMeasureCode: {
format: "text",
type: "string",
@@ -38367,6 +39018,12 @@ export default {
customFields: {
format: "jsonb",
},
+ jobMakeMethodId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobMakeMethod.id`.<fk table='jobMakeMethod' column='id'/>",
+ format: "text",
+ type: "string",
+ },
jobOperationId: {
description:
"Note:\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",
@@ -44426,6 +45083,24 @@ export default {
},
type: "object",
},
+ jobFavorite: {
+ required: ["jobId", "userId"],
+ properties: {
+ jobId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ userId: {
+ description:
+ "Note:\nThis is a Primary Key.<pk/>\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
documentTransaction: {
required: ["id", "documentId", "type", "userId", "createdAt"],
properties: {
@@ -47779,6 +48454,115 @@ export default {
},
type: "object",
},
+ jobMaterialWithMakeMethodId: {
+ properties: {
+ id: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ jobId: {
+ description:
+ "Note:\nThis is a Foreign Key to `job.id`.<fk table='job' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ itemId: {
+ description:
+ "Note:\nThis is a Foreign Key to `item.id`.<fk table='item' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ itemReadableId: {
+ format: "text",
+ type: "string",
+ },
+ itemType: {
+ format: "text",
+ type: "string",
+ },
+ methodType: {
+ enum: ["Buy", "Make", "Pick"],
+ format: 'public."methodType"',
+ type: "string",
+ },
+ order: {
+ format: "double precision",
+ type: "number",
+ },
+ description: {
+ format: "text",
+ type: "string",
+ },
+ quantity: {
+ format: "numeric",
+ type: "number",
+ },
+ scrapQuantity: {
+ format: "numeric",
+ type: "number",
+ },
+ productionQuantity: {
+ format: "numeric",
+ type: "number",
+ },
+ unitOfMeasureCode: {
+ format: "text",
+ type: "string",
+ },
+ unitCost: {
+ format: "numeric",
+ type: "number",
+ },
+ companyId: {
+ description:
+ "Note:\nThis is a Foreign Key to `company.id`.<fk table='company' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ createdAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ createdBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ updatedAt: {
+ format: "timestamp with time zone",
+ type: "string",
+ },
+ updatedBy: {
+ description:
+ "Note:\nThis is a Foreign Key to `user.id`.<fk table='user' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ customFields: {
+ format: "jsonb",
+ },
+ jobMakeMethodId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobMakeMethod.id`.<fk table='jobMakeMethod' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ jobOperationId: {
+ description:
+ "Note:\nThis is a Foreign Key to `jobOperation.id`.<fk table='jobOperation' column='id'/>",
+ format: "text",
+ type: "string",
+ },
+ jobMaterialMakeMethodId: {
+ description: "Note:\nThis is a Primary Key.<pk/>",
+ format: "text",
+ type: "string",
+ },
+ },
+ type: "object",
+ },
currency: {
required: [
"id",
@@ -51333,6 +52117,13 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobOperation.jobMakeMethodId": {
+ name: "jobMakeMethodId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"rowFilter.jobOperation.order": {
name: "order",
required: false,
@@ -51410,27 +52201,69 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.jobOperation.quotingRate": {
- name: "quotingRate",
+ "rowFilter.jobOperation.laborRate": {
+ name: "laborRate",
required: false,
format: "numeric",
in: "query",
type: "string",
},
- "rowFilter.jobOperation.laborRate": {
- name: "laborRate",
+ "rowFilter.jobOperation.overheadRate": {
+ name: "overheadRate",
required: false,
format: "numeric",
in: "query",
type: "string",
},
- "rowFilter.jobOperation.overheadRate": {
- name: "overheadRate",
+ "rowFilter.jobOperation.machineRate": {
+ name: "machineRate",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.operationType": {
+ name: "operationType",
+ required: false,
+ format: 'public."operationType"',
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.operationMinimumCost": {
+ name: "operationMinimumCost",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.operationLeadTime": {
+ name: "operationLeadTime",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.operationUnitCost": {
+ name: "operationUnitCost",
required: false,
format: "numeric",
in: "query",
type: "string",
},
+ "rowFilter.jobOperation.operationSupplierProcessId": {
+ name: "operationSupplierProcessId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobOperation.workInstruction": {
+ name: "workInstruction",
+ required: false,
+ format: "json",
+ in: "query",
+ type: "string",
+ },
"rowFilter.jobOperation.companyId": {
name: "companyId",
required: false,
@@ -51473,13 +52306,6 @@ export default {
in: "query",
type: "string",
},
- "rowFilter.jobOperation.workInstruction": {
- name: "workInstruction",
- required: false,
- format: "json",
- in: "query",
- type: "string",
- },
"body.journalLine": {
name: "journalLine",
description: "journalLine",
@@ -54126,6 +54952,92 @@ export default {
in: "query",
type: "string",
},
+ "body.jobMakeMethod": {
+ name: "jobMakeMethod",
+ description: "jobMakeMethod",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/jobMakeMethod",
+ },
+ },
+ "rowFilter.jobMakeMethod.id": {
+ name: "id",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.jobId": {
+ name: "jobId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.parentMaterialId": {
+ name: "parentMaterialId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.itemId": {
+ name: "itemId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.quantityPerParent": {
+ name: "quantityPerParent",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.companyId": {
+ name: "companyId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.createdAt": {
+ name: "createdAt",
+ required: false,
+ format: "timestamp with time zone",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.createdBy": {
+ name: "createdBy",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ format: "timestamp with time zone",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMakeMethod.customFields": {
+ name: "customFields",
+ required: false,
+ format: "jsonb",
+ in: "query",
+ type: "string",
+ },
"body.contact": {
name: "contact",
description: "contact",
@@ -54321,6 +55233,20 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobMaterial.scrapQuantity": {
+ name: "scrapQuantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterial.productionQuantity": {
+ name: "productionQuantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
"rowFilter.jobMaterial.unitOfMeasureCode": {
name: "unitOfMeasureCode",
required: false,
@@ -54377,6 +55303,13 @@ export default {
in: "query",
type: "string",
},
+ "rowFilter.jobMaterial.jobMakeMethodId": {
+ name: "jobMakeMethodId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"rowFilter.jobMaterial.jobOperationId": {
name: "jobOperationId",
required: false,
@@ -62371,6 +63304,29 @@ export default {
in: "query",
type: "string",
},
+ "body.jobFavorite": {
+ name: "jobFavorite",
+ description: "jobFavorite",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/jobFavorite",
+ },
+ },
+ "rowFilter.jobFavorite.jobId": {
+ name: "jobId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobFavorite.userId": {
+ name: "userId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"body.documentTransaction": {
name: "documentTransaction",
description: "documentTransaction",
@@ -66733,6 +67689,169 @@ export default {
in: "query",
type: "string",
},
+ "body.jobMaterialWithMakeMethodId": {
+ name: "jobMaterialWithMakeMethodId",
+ description: "jobMaterialWithMakeMethodId",
+ required: false,
+ in: "body",
+ schema: {
+ $ref: "#/definitions/jobMaterialWithMakeMethodId",
+ },
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.id": {
+ name: "id",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.jobId": {
+ name: "jobId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.itemId": {
+ name: "itemId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.itemReadableId": {
+ name: "itemReadableId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.itemType": {
+ name: "itemType",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.methodType": {
+ name: "methodType",
+ required: false,
+ format: 'public."methodType"',
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.order": {
+ name: "order",
+ required: false,
+ format: "double precision",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.description": {
+ name: "description",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.quantity": {
+ name: "quantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.scrapQuantity": {
+ name: "scrapQuantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.productionQuantity": {
+ name: "productionQuantity",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.unitOfMeasureCode": {
+ name: "unitOfMeasureCode",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.unitCost": {
+ name: "unitCost",
+ required: false,
+ format: "numeric",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.companyId": {
+ name: "companyId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.createdAt": {
+ name: "createdAt",
+ required: false,
+ format: "timestamp with time zone",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.createdBy": {
+ name: "createdBy",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.updatedAt": {
+ name: "updatedAt",
+ required: false,
+ format: "timestamp with time zone",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.updatedBy": {
+ name: "updatedBy",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.customFields": {
+ name: "customFields",
+ required: false,
+ format: "jsonb",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.jobMakeMethodId": {
+ name: "jobMakeMethodId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.jobOperationId": {
+ name: "jobOperationId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
+ "rowFilter.jobMaterialWithMakeMethodId.jobMaterialMakeMethodId": {
+ name: "jobMaterialMakeMethodId",
+ required: false,
+ format: "text",
+ in: "query",
+ type: "string",
+ },
"body.currency": {
name: "currency",
description: "currency",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index b5e9ac6807..86b30a960e 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -7221,6 +7221,254 @@ export type Database = {
},
]
}
+ jobFavorite: {
+ Row: {
+ jobId: string
+ userId: string
+ }
+ Insert: {
+ jobId: string
+ userId: string
+ }
+ Update: {
+ jobId?: string
+ userId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobFavorites_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ jobMakeMethod: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ customFields: Json | null
+ id: string
+ itemId: string
+ jobId: string
+ parentMaterialId: string | null
+ quantityPerParent: number
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ customFields?: Json | null
+ id?: string
+ itemId: string
+ jobId: string
+ parentMaterialId?: string | null
+ quantityPerParent?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ customFields?: Json | null
+ id?: string
+ itemId?: string
+ jobId?: string
+ parentMaterialId?: string | null
+ quantityPerParent?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobMakeMethod_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "itemQuantities"
+ referencedColumns: ["itemId"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"
+ columns: ["parentMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"
+ columns: ["parentMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
jobMaterial: {
Row: {
companyId: string
@@ -7233,10 +7481,13 @@ export type Database = {
itemReadableId: string
itemType: string
jobId: string
+ jobMakeMethodId: string
jobOperationId: string | null
methodType: Database["public"]["Enums"]["methodType"]
order: number
+ productionQuantity: number | null
quantity: number
+ scrapQuantity: number
unitCost: number
unitOfMeasureCode: string | null
updatedAt: string | null
@@ -7253,10 +7504,13 @@ export type Database = {
itemReadableId: string
itemType?: string
jobId: string
+ jobMakeMethodId: string
jobOperationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
order?: number
+ productionQuantity?: number | null
quantity?: number
+ scrapQuantity?: number
unitCost?: number
unitOfMeasureCode?: string | null
updatedAt?: string | null
@@ -7273,10 +7527,13 @@ export type Database = {
itemReadableId?: string
itemType?: string
jobId?: string
+ jobMakeMethodId?: string
jobOperationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
order?: number
+ productionQuantity?: number | null
quantity?: number
+ scrapQuantity?: number
unitCost?: number
unitOfMeasureCode?: string | null
updatedAt?: string | null
@@ -7374,6 +7631,20 @@ export type Database = {
referencedRelation: "jobs"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMakeMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["jobMaterialMakeMethodId"]
+ },
{
foreignKeyName: "jobMaterial_jobOperationId_fkey"
columns: ["jobOperationId"]
@@ -7434,16 +7705,22 @@ export type Database = {
description: string | null
id: string
jobId: string
+ jobMakeMethodId: string | null
laborRate: number
laborTime: number
laborUnit: Database["public"]["Enums"]["factor"]
+ machineRate: number | null
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
+ operationLeadTime: number
+ operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
+ operationSupplierProcessId: string | null
+ operationType: Database["public"]["Enums"]["operationType"]
+ operationUnitCost: number
order: number
overheadRate: number
processId: string
- quotingRate: number
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
updatedAt: string | null
@@ -7459,16 +7736,22 @@ export type Database = {
description?: string | null
id?: string
jobId: string
+ jobMakeMethodId?: string | null
laborRate?: number
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
+ machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
+ operationLeadTime?: number
+ operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
+ operationSupplierProcessId?: string | null
+ operationType?: Database["public"]["Enums"]["operationType"]
+ operationUnitCost?: number
order?: number
overheadRate?: number
processId: string
- quotingRate?: number
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
updatedAt?: string | null
@@ -7484,16 +7767,22 @@ export type Database = {
description?: string | null
id?: string
jobId?: string
+ jobMakeMethodId?: string | null
laborRate?: number
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
+ machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
+ operationLeadTime?: number
+ operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
+ operationSupplierProcessId?: string | null
+ operationType?: Database["public"]["Enums"]["operationType"]
+ operationUnitCost?: number
order?: number
overheadRate?: number
processId?: string
- quotingRate?: number
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
updatedAt?: string | null
@@ -7579,6 +7868,20 @@ export type Database = {
referencedRelation: "jobs"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMakeMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["jobMaterialMakeMethodId"]
+ },
{
foreignKeyName: "jobOperation_processId_fkey"
columns: ["processId"]
@@ -23050,6 +23353,188 @@ export type Database = {
},
]
}
+ jobMaterialWithMakeMethodId: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ description: string | null
+ id: string | null
+ itemId: string | null
+ itemReadableId: string | null
+ itemType: string | null
+ jobId: string | null
+ jobMakeMethodId: string | null
+ jobMaterialMakeMethodId: string | null
+ jobOperationId: string | null
+ methodType: Database["public"]["Enums"]["methodType"] | null
+ order: number | null
+ productionQuantity: number | null
+ quantity: number | null
+ scrapQuantity: number | null
+ unitCost: number | null
+ unitOfMeasureCode: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "itemQuantities"
+ referencedColumns: ["itemId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMakeMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["jobMaterialMakeMethodId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_unitOfMeasureCode_fkey"
+ columns: ["unitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
jobs: {
Row: {
active: boolean | null
@@ -23707,14 +24192,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -24586,14 +25071,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
@@ -28285,6 +28770,26 @@ export type Database = {
}
Returns: string
}
+ get_job_method: {
+ Args: {
+ jid: string
+ }
+ Returns: {
+ jobId: string
+ methodMaterialId: string
+ jobMakeMethodId: string
+ jobMaterialMakeMethodId: string
+ itemId: string
+ itemReadableId: 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/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index b5e9ac6807..86b30a960e 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -7221,6 +7221,254 @@ export type Database = {
},
]
}
+ jobFavorite: {
+ Row: {
+ jobId: string
+ userId: string
+ }
+ Insert: {
+ jobId: string
+ userId: string
+ }
+ Update: {
+ jobId?: string
+ userId?: string
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobFavorites_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobFavorites_userId_fkey"
+ columns: ["userId"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
+ jobMakeMethod: {
+ Row: {
+ companyId: string
+ createdAt: string
+ createdBy: string
+ customFields: Json | null
+ id: string
+ itemId: string
+ jobId: string
+ parentMaterialId: string | null
+ quantityPerParent: number
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ createdAt?: string
+ createdBy: string
+ customFields?: Json | null
+ id?: string
+ itemId: string
+ jobId: string
+ parentMaterialId?: string | null
+ quantityPerParent?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ createdAt?: string
+ createdBy?: string
+ customFields?: Json | null
+ id?: string
+ itemId?: string
+ jobId?: string
+ parentMaterialId?: string | null
+ quantityPerParent?: number
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobMakeMethod_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "itemQuantities"
+ referencedColumns: ["itemId"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"
+ columns: ["parentMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterial"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_parentMaterialId_fkey"
+ columns: ["parentMaterialId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMakeMethod_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
jobMaterial: {
Row: {
companyId: string
@@ -7233,10 +7481,13 @@ export type Database = {
itemReadableId: string
itemType: string
jobId: string
+ jobMakeMethodId: string
jobOperationId: string | null
methodType: Database["public"]["Enums"]["methodType"]
order: number
+ productionQuantity: number | null
quantity: number
+ scrapQuantity: number
unitCost: number
unitOfMeasureCode: string | null
updatedAt: string | null
@@ -7253,10 +7504,13 @@ export type Database = {
itemReadableId: string
itemType?: string
jobId: string
+ jobMakeMethodId: string
jobOperationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
order?: number
+ productionQuantity?: number | null
quantity?: number
+ scrapQuantity?: number
unitCost?: number
unitOfMeasureCode?: string | null
updatedAt?: string | null
@@ -7273,10 +7527,13 @@ export type Database = {
itemReadableId?: string
itemType?: string
jobId?: string
+ jobMakeMethodId?: string
jobOperationId?: string | null
methodType?: Database["public"]["Enums"]["methodType"]
order?: number
+ productionQuantity?: number | null
quantity?: number
+ scrapQuantity?: number
unitCost?: number
unitOfMeasureCode?: string | null
updatedAt?: string | null
@@ -7374,6 +7631,20 @@ export type Database = {
referencedRelation: "jobs"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMakeMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["jobMaterialMakeMethodId"]
+ },
{
foreignKeyName: "jobMaterial_jobOperationId_fkey"
columns: ["jobOperationId"]
@@ -7434,16 +7705,22 @@ export type Database = {
description: string | null
id: string
jobId: string
+ jobMakeMethodId: string | null
laborRate: number
laborTime: number
laborUnit: Database["public"]["Enums"]["factor"]
+ machineRate: number | null
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
+ operationLeadTime: number
+ operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
+ operationSupplierProcessId: string | null
+ operationType: Database["public"]["Enums"]["operationType"]
+ operationUnitCost: number
order: number
overheadRate: number
processId: string
- quotingRate: number
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
updatedAt: string | null
@@ -7459,16 +7736,22 @@ export type Database = {
description?: string | null
id?: string
jobId: string
+ jobMakeMethodId?: string | null
laborRate?: number
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
+ machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
+ operationLeadTime?: number
+ operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
+ operationSupplierProcessId?: string | null
+ operationType?: Database["public"]["Enums"]["operationType"]
+ operationUnitCost?: number
order?: number
overheadRate?: number
processId: string
- quotingRate?: number
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
updatedAt?: string | null
@@ -7484,16 +7767,22 @@ export type Database = {
description?: string | null
id?: string
jobId?: string
+ jobMakeMethodId?: string | null
laborRate?: number
laborTime?: number
laborUnit?: Database["public"]["Enums"]["factor"]
+ machineRate?: number | null
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
+ operationLeadTime?: number
+ operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
+ operationSupplierProcessId?: string | null
+ operationType?: Database["public"]["Enums"]["operationType"]
+ operationUnitCost?: number
order?: number
overheadRate?: number
processId?: string
- quotingRate?: number
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
updatedAt?: string | null
@@ -7579,6 +7868,20 @@ export type Database = {
referencedRelation: "jobs"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMakeMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobOperation_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["jobMaterialMakeMethodId"]
+ },
{
foreignKeyName: "jobOperation_processId_fkey"
columns: ["processId"]
@@ -23050,6 +23353,188 @@ export type Database = {
},
]
}
+ jobMaterialWithMakeMethodId: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ description: string | null
+ id: string | null
+ itemId: string | null
+ itemReadableId: string | null
+ itemType: string | null
+ jobId: string | null
+ jobMakeMethodId: string | null
+ jobMaterialMakeMethodId: string | null
+ jobOperationId: string | null
+ methodType: Database["public"]["Enums"]["methodType"] | null
+ order: number | null
+ productionQuantity: number | null
+ quantity: number | null
+ scrapQuantity: number | null
+ unitCost: number | null
+ unitOfMeasureCode: string | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "jobMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "item"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_itemId_fkey"
+ columns: ["itemId"]
+ isOneToOne: false
+ referencedRelation: "itemQuantities"
+ referencedColumns: ["itemId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "job"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobId_fkey"
+ columns: ["jobId"]
+ isOneToOne: false
+ referencedRelation: "jobs"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMakeMethod"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobMakeMethodId_fkey"
+ columns: ["jobMakeMethodId"]
+ isOneToOne: false
+ referencedRelation: "jobMaterialWithMakeMethodId"
+ referencedColumns: ["jobMaterialMakeMethodId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_jobOperationId_fkey"
+ columns: ["jobOperationId"]
+ isOneToOne: false
+ referencedRelation: "jobOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_unitOfMeasureCode_fkey"
+ columns: ["unitOfMeasureCode", "companyId"]
+ isOneToOne: false
+ referencedRelation: "unitOfMeasure"
+ referencedColumns: ["code", "companyId"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "jobMaterial_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
jobs: {
Row: {
active: boolean | null
@@ -23707,14 +24192,14 @@ export type Database = {
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["supplierLocationId"]
+ columns: ["id"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
},
{
foreignKeyName: "partner_id_fkey"
- columns: ["id"]
+ columns: ["supplierLocationId"]
isOneToOne: false
referencedRelation: "supplierLocation"
referencedColumns: ["id"]
@@ -24586,14 +25071,14 @@ export type Database = {
Relationships: [
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["supplierCountryCode"]
+ columns: ["customerCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
},
{
foreignKeyName: "address_countryCode_fkey"
- columns: ["customerCountryCode"]
+ columns: ["supplierCountryCode"]
isOneToOne: false
referencedRelation: "country"
referencedColumns: ["id"]
@@ -28285,6 +28770,26 @@ export type Database = {
}
Returns: string
}
+ get_job_method: {
+ Args: {
+ jid: string
+ }
+ Returns: {
+ jobId: string
+ methodMaterialId: string
+ jobMakeMethodId: string
+ jobMaterialMakeMethodId: string
+ itemId: string
+ itemReadableId: 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
new file mode 100644
index 0000000000..07b8ac2c1a
--- /dev/null
+++ b/packages/database/supabase/migrations/20240915192542_job-methods.sql
@@ -0,0 +1,425 @@
+DROP TABLE "jobMaterial";
+DROP TABLE "jobOperation";
+
+CREATE TABLE "jobMaterial" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "jobId" TEXT NOT NULL,
+ "itemId" TEXT NOT NULL,
+ "itemReadableId" TEXT NOT NULL,
+ "itemType" TEXT NOT NULL DEFAULT 'Part',
+ "methodType" "methodType" NOT NULL DEFAULT 'Make',
+ "order" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "description" TEXT NOT NULL,
+ "quantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
+ "scrapQuantity" NUMERIC(10, 4) NOT NULL DEFAULT 0,
+ "productionQuantity" NUMERIC(10, 4) GENERATED ALWAYS AS ("quantity" + "scrapQuantity") STORED,
+ "unitOfMeasureCode" TEXT,
+ "unitCost" NUMERIC(10, 4) NOT NULL DEFAULT 0,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "customFields" JSONB,
+
+ CONSTRAINT "jobMaterial_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "jobMaterial_jobId_fkey" FOREIGN KEY ("jobId") REFERENCES "job" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "jobMaterial_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobMaterial_unitOfMeasureCode_fkey" FOREIGN KEY ("unitOfMeasureCode", "companyId") REFERENCES "unitOfMeasure" ("code", "companyId") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobMaterial_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobMaterial_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobMaterial_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "jobMaterial_jobId_idx" ON "jobMaterial" ("jobId");
+
+CREATE TABLE "jobMakeMethod" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "jobId" TEXT NOT NULL,
+ "parentMaterialId" TEXT,
+ "itemId" TEXT NOT NULL,
+ "quantityPerParent" NUMERIC(10, 4) NOT NULL DEFAULT 1,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "customFields" JSONB,
+
+ CONSTRAINT "jobMakeMethod_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "jobMakeMethod_jobId_fkey" FOREIGN KEY ("jobId") REFERENCES "job" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "jobMakeMethod_parentMaterialId_fkey" FOREIGN KEY ("parentMaterialId") REFERENCES "jobMaterial" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "jobMakeMethod_itemId_fkey" FOREIGN KEY ("itemId") REFERENCES "item" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobMakeMethod_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobMakeMethod_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobMakeMethod_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE OR REPLACE FUNCTION insert_job_make_method()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO "jobMakeMethod" ("jobId", "itemId", "companyId", "createdBy")
+ VALUES (NEW."id", NEW."itemId", NEW."companyId", NEW."createdBy");
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER insert_job_make_method_trigger
+AFTER INSERT ON "job"
+FOR EACH ROW
+EXECUTE FUNCTION insert_job_make_method();
+
+CREATE INDEX "jobMakeMethod_jobId_idx" ON "jobMakeMethod" ("jobId");
+CREATE INDEX "jobMakeMethod_parentMaterialId_idx" ON "jobMakeMethod" ("parentMaterialId");
+
+ALTER TABLE "jobMaterial" ADD COLUMN "jobMakeMethodId" TEXT NOT NULL,
+ ADD CONSTRAINT "jobMaterial_jobMakeMethodId_fkey" FOREIGN KEY ("jobMakeMethodId") REFERENCES "jobMakeMethod" ("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+CREATE OR REPLACE FUNCTION insert_job_material_make_method()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO "jobMakeMethod" ("jobId", "parentMaterialId", "itemId", "companyId", "createdBy")
+ VALUES (NEW."jobId", NEW."id", NEW."itemId", NEW."companyId", NEW."createdBy");
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER insert_job_material_make_method_trigger
+ AFTER INSERT ON "jobMaterial"
+ FOR EACH ROW
+ WHEN (NEW."methodType" = 'Make')
+ EXECUTE FUNCTION insert_job_material_make_method();
+
+CREATE OR REPLACE FUNCTION update_job_material_make_method_item_id()
+ RETURNS TRIGGER AS $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM "jobMakeMethod"
+ WHERE "jobId" = NEW."jobId" AND "parentMaterialId" = NEW."id"
+ ) THEN
+ INSERT INTO "jobMakeMethod" ("jobId", "parentMaterialId", "itemId", "companyId", "createdBy")
+ VALUES (NEW."jobId", NEW."id", NEW."itemId", NEW."companyId", NEW."createdBy");
+ ELSE
+ UPDATE "jobMakeMethod"
+ SET "itemId" = NEW."itemId"
+ WHERE "jobId" = NEW."jobId" AND "parentMaterialId" = NEW."id";
+ END IF;
+ RETURN NEW;
+END;
+$$ LANGUAGE plpgsql;
+
+CREATE TRIGGER update_job_material_make_method_item_id_trigger
+ AFTER UPDATE OF "itemId", "methodType" ON "jobMaterial"
+ FOR EACH ROW
+ WHEN (
+ (OLD."methodType" = 'Make' AND OLD."itemId" IS DISTINCT FROM NEW."itemId") OR
+ (NEW."methodType" = 'Make' AND OLD."methodType" <> 'Make')
+ )
+ EXECUTE FUNCTION update_job_material_make_method_item_id();
+
+CREATE TABLE "jobOperation" (
+ "id" TEXT NOT NULL DEFAULT xid(),
+ "jobId" TEXT NOT NULL,
+ "jobMakeMethodId" TEXT,
+ "order" DOUBLE PRECISION NOT NULL DEFAULT 1,
+ "processId" TEXT NOT NULL,
+ "workCenterId" TEXT,
+ "description" TEXT,
+ "setupTime" NUMERIC(10,2) NOT NULL DEFAULT 0,
+ "setupUnit" factor NOT NULL DEFAULT 'Total Hours',
+ "laborTime" NUMERIC(10,2) NOT NULL DEFAULT 0,
+ "laborUnit" factor NOT NULL DEFAULT 'Hours/Piece',
+ "machineTime" NUMERIC(10,2) NOT NULL DEFAULT 0,
+ "machineUnit" factor NOT NULL DEFAULT 'Hours/Piece',
+ "operationOrder" "methodOperationOrder" NOT NULL DEFAULT 'After Previous',
+ "laborRate" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ "overheadRate" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ "machineRate" NUMERIC(10,4) DEFAULT 0,
+ "operationType" "operationType" NOT NULL DEFAULT 'Inside',
+ "operationMinimumCost" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ "operationLeadTime" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ "operationUnitCost" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ "operationSupplierProcessId" TEXT,
+ "workInstruction" JSON NOT NULL DEFAULT '{}',
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+ "customFields" JSONB,
+
+ CONSTRAINT "jobOperation_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "jobOperation_jobId_fkey" FOREIGN KEY ("jobId") REFERENCES "job" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "jobOperation_jobMakeMethodId_fkey" FOREIGN KEY ("jobMakeMethodId") REFERENCES "jobMakeMethod" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "jobOperation_processId_fkey" FOREIGN KEY ("processId") REFERENCES "process" ("id") ON DELETE RESTRICT,
+ CONSTRAINT "jobOperation_workCenterId_fkey" FOREIGN KEY ("workCenterId") REFERENCES "workCenter" ("id") ON DELETE RESTRICT,
+ CONSTRAINT "jobOperation_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobOperation_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "jobOperation_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+);
+
+CREATE INDEX "jobOperation_jobId_idx" ON "jobOperation" ("jobId");
+CREATE INDEX "jobOperation_jobMakeMethodId_idx" ON "jobOperation" ("jobMakeMethodId");
+
+ALTER TABLE "jobMaterial" ADD COLUMN "jobOperationId" TEXT,
+ ADD CONSTRAINT "jobMaterial_jobOperationId_fkey" FOREIGN KEY ("jobOperationId") REFERENCES "jobOperation" ("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+COMMIT;
+CREATE INDEX "jobMaterial_jobOperationId_idx" ON "jobMaterial" ("jobOperationId");
+
+CREATE TABLE "jobFavorite" (
+ "jobId" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+
+ CONSTRAINT "jobFavorites_pkey" PRIMARY KEY ("jobId", "userId"),
+ CONSTRAINT "jobFavorites_jobId_fkey" FOREIGN KEY ("jobId") REFERENCES "job"("id") ON DELETE CASCADE,
+ CONSTRAINT "jobFavorites_userId_fkey" FOREIGN KEY ("userId") REFERENCES "user"("id") ON DELETE CASCADE
+);
+
+CREATE INDEX "jobFavorites_userId_idx" ON "jobFavorite" ("userId");
+CREATE INDEX "jobFavorites_jobId_idx" ON "jobFavorite" ("jobId");
+
+ALTER TABLE "jobFavorite" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Users can view their own job favorites" ON "jobFavorite"
+ FOR SELECT USING (
+ auth.uid()::text = "userId"
+ );
+
+CREATE POLICY "Users can create their own job favorites" ON "jobFavorite"
+ FOR INSERT WITH CHECK (
+ auth.uid()::text = "userId"
+ );
+
+CREATE POLICY "Users can delete their own job favorites" ON "jobFavorite"
+ FOR DELETE USING (
+ auth.uid()::text = "userId"
+ );
+
+CREATE OR REPLACE VIEW "jobMaterialWithMakeMethodId" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ jm.*,
+ jmm."id" AS "jobMaterialMakeMethodId"
+ FROM "jobMaterial" jm
+ LEFT JOIN "jobMakeMethod" jmm
+ ON jmm."parentMaterialId" = jm."id";
+
+CREATE OR REPLACE FUNCTION get_job_method(jid TEXT)
+RETURNS TABLE (
+ "jobId" TEXT,
+ "methodMaterialId" TEXT,
+ "jobMakeMethodId" TEXT,
+ "jobMaterialMakeMethodId" TEXT,
+ "itemId" TEXT,
+ "itemReadableId" 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
+ "jobId" = jid
+ AND "parentMaterialId" IS NULL
+ 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",
+ material."itemType",
+ material."quantity",
+ material."unitCost",
+ material."methodType",
+ material."parentMaterialId",
+ material."order",
+ material."isRoot"
+FROM material
+INNER JOIN item ON material."itemId" = item.id
+WHERE material."jobId" = jid
+ORDER BY "order"
+$$ LANGUAGE sql STABLE;
+
+ALTER TABLE "jobMaterial" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "jobOperation" ENABLE ROW LEVEL SECURITY;
+ALTER TABLE "jobMakeMethod" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Requests with an API key can access jobs" ON "jobMaterial"
+FOR ALL USING (
+ has_valid_api_key_for_company("companyId")
+);
+
+CREATE POLICY "Requests with an API key can access jobs" ON "jobOperation"
+FOR ALL USING (
+ has_valid_api_key_for_company("companyId")
+);
+
+CREATE POLICY "Requests with an API key can access jobs" ON "jobMakeMethod"
+FOR ALL USING (
+ has_valid_api_key_for_company("companyId")
+);
+
+-- Policies for jobMaterial
+CREATE POLICY "Employees can view job materials" ON "jobMaterial"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
+ )
+ );
+
+CREATE POLICY "Employees with production_create can insert job materials" ON "jobMaterial"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_create', "companyId")
+ );
+
+CREATE POLICY "Employees with production_update can update job materials" ON "jobMaterial"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_update', "companyId")
+ );
+
+CREATE POLICY "Employees with production_delete can delete job materials" ON "jobMaterial"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_delete', "companyId")
+ );
+
+CREATE POLICY "Customers with production_view can view their own job materials" ON "jobMaterial"
+ FOR SELECT
+ USING (
+ has_role('customer', "companyId") AND
+ has_company_permission('production_view', "companyId") AND
+ "jobId" IN (
+ SELECT "id" FROM "job" WHERE "customerId" IN (
+ SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ );
+
+-- Policies for jobOperation
+CREATE POLICY "Employees can view job operations" ON "jobOperation"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
+ )
+ );
+
+CREATE POLICY "Employees with production_create can insert job operations" ON "jobOperation"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_create', "companyId")
+ );
+
+CREATE POLICY "Employees with production_update can update job operations" ON "jobOperation"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_update', "companyId")
+ );
+
+CREATE POLICY "Employees with production_delete can delete job operations" ON "jobOperation"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_delete', "companyId")
+ );
+
+CREATE POLICY "Customers with production_view can view their own job operations" ON "jobOperation"
+ FOR SELECT
+ USING (
+ has_role('customer', "companyId") AND
+ has_company_permission('production_view', "companyId") AND
+ "jobId" IN (
+ SELECT "id" FROM "job" WHERE "customerId" IN (
+ SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ );
+
+CREATE POLICY "Employees can view job make methods" ON "jobMakeMethod"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId")
+ AND "companyId" = ANY(
+ SELECT "companyId" from "userToCompany" where "userId" = auth.uid()::text
+ )
+ );
+
+CREATE POLICY "Employees with production_create can insert job make methods" ON "jobMakeMethod"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_create', "companyId")
+ );
+
+CREATE POLICY "Employees with production_update can update job make methods" ON "jobMakeMethod"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_update', "companyId")
+ );
+
+CREATE POLICY "Employees with production_delete can delete job make methods" ON "jobMakeMethod"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId")
+ AND has_company_permission('production_delete', "companyId")
+ );
+
+CREATE POLICY "Customers with production_view can view their own job make methods" ON "jobMakeMethod"
+ FOR SELECT
+ USING (
+ has_role('customer', "companyId") AND
+ has_company_permission('production_view', "companyId") AND
+ "jobId" IN (
+ SELECT "id" FROM "job" WHERE "customerId" IN (
+ SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
+ )
+ )
+ );