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: add crud for tools to quote and job bill of process

Brad Barbin92500a32ec4a
diff --git a/apps/carbon/app/modules/items/items.service.ts b/apps/carbon/app/modules/items/items.service.ts
index 2dffc6676b..7f21091c70 100644
--- a/apps/carbon/app/modules/items/items.service.ts
+++ b/apps/carbon/app/modules/items/items.service.ts
@@ -631,22 +631,6 @@ export async function getMethodOperationsByMakeMethodId(
.order("order", { ascending: true });
}
-export async function getMethodOperationToolsByOperationIds(
- client: SupabaseClient<Database>,
- operationIds: string[]
-) {
- if (operationIds.length === 0) {
- return {
- data: [],
- error: null,
- };
- }
- return client
- .from("methodOperationTool")
- .select("*")
- .in("operationId", operationIds);
-}
-
type Method = NonNullable<
Awaited<ReturnType<typeof getMethodTreeArray>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 345db4735d..d711829b8b 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -72,6 +72,7 @@ import {
operationToolValidator,
operationTypes,
} from "~/modules/shared";
+import type { action as editMethodOperationToolAction } from "~/routes/x+/items+/methods+/operation.tool.$id";
import type { action as newMethodOperationToolAction } from "~/routes/x+/items+/methods+/operation.tool.new";
import { useTools } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
@@ -1035,7 +1036,7 @@ function ToolsListItem({
const disclosure = useDisclosure();
const deleteModalDisclosure = useDisclosure();
const submitted = useRef(false);
- const fetcher = useFetcher<typeof newMethodOperationToolAction>();
+ const fetcher = useFetcher<typeof editMethodOperationToolAction>();
useEffect(() => {
if (submitted.current && fetcher.state === "idle") {
diff --git a/apps/carbon/app/modules/production/production.service.ts b/apps/carbon/app/modules/production/production.service.ts
index 949b485ed3..6f49da8936 100644
--- a/apps/carbon/app/modules/production/production.service.ts
+++ b/apps/carbon/app/modules/production/production.service.ts
@@ -5,6 +5,7 @@ import type { StorageItem } from "~/types";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
+import type { operationToolValidator } from "../shared";
import type {
jobMaterialValidator,
jobOperationStatus,
@@ -42,6 +43,13 @@ export async function deleteJobOperation(
return client.from("jobOperation").delete().eq("id", jobOperationId);
}
+export async function deleteJobOperationTool(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("jobOperationTool").delete().eq("id", id);
+}
+
export async function deleteProductionEvent(
client: SupabaseClient<Database>,
productionEventId: string
@@ -331,7 +339,9 @@ export async function getJobOperationsByMethodId(
) {
return client
.from("jobOperation")
- .select("*")
+ .select(
+ "*, jobOperationTool(id, operationId, toolId, quantity, createdBy, createdAt, updatedBy, updatedAt)"
+ )
.eq("jobMakeMethodId", jobMakeMethodId)
.order("order", { ascending: true });
}
@@ -782,6 +792,35 @@ export async function upsertJobOperation(
.single();
}
+export async function upsertJobOperationTool(
+ client: SupabaseClient<Database>,
+ jobOperationTool:
+ | (Omit<z.infer<typeof operationToolValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof operationToolValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ updatedAt: string;
+ })
+) {
+ if ("createdBy" in jobOperationTool) {
+ return client
+ .from("jobOperationTool")
+ .insert(jobOperationTool)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("jobOperationTool")
+ .update(sanitize(jobOperationTool))
+ .eq("id", jobOperationTool.id)
+ .select("id")
+ .single();
+}
+
export async function upsertJobMethod(
client: SupabaseClient<Database>,
type: "itemToJob" | "quoteLineToJob",
diff --git a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
index 8d18bb794a..2970dd096d 100644
--- a/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
+++ b/apps/carbon/app/modules/production/ui/Jobs/JobBillOfProcess.tsx
@@ -4,6 +4,9 @@ import type { Database } from "@carbon/database";
import { ValidatedForm } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Badge,
Button,
Card,
@@ -11,15 +14,25 @@ import {
CardContent,
CardHeader,
CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
Editor,
HStack,
IconButton,
Label,
+ VStack,
cn,
generateHTML,
useDebounce,
+ useDisclosure,
} from "@carbon/react";
-import { formatDateTime, formatDurationMilliseconds } from "@carbon/utils";
+import {
+ formatDateTime,
+ formatDurationMilliseconds,
+ formatRelativeTime,
+} from "@carbon/utils";
import { getLocalTimeZone, today } from "@internationalized/date";
import { useFetcher, useParams } from "@remix-run/react";
import type { RealtimeChannel } from "@supabase/supabase-js";
@@ -28,13 +41,23 @@ import { nanoid } from "nanoid";
import type { Dispatch, SetStateAction } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
import { flushSync } from "react-dom";
-import { LuChevronDown, LuDollarSign, LuSettings2, LuX } from "react-icons/lu";
+import {
+ LuAlertTriangle,
+ LuChevronDown,
+ LuDollarSign,
+ LuHammer,
+ LuMoreVertical,
+ LuPlusCircle,
+ LuSettings2,
+ LuX,
+} from "react-icons/lu";
import type { z } from "zod";
-import { DirectionAwareTabs, TimeTypeIcon } from "~/components";
+import { DirectionAwareTabs, EmployeeAvatar, TimeTypeIcon } from "~/components";
import Activity from "~/components/Activity";
import {
Hidden,
InputControlled,
+ Number,
NumberControlled,
Process,
Select,
@@ -42,16 +65,26 @@ import {
StandardFactor,
Submit,
SupplierProcess,
+ Tool,
UnitHint,
WorkCenter,
getUnitHint,
} from "~/components/Form";
import { OperationStatusIcon } from "~/components/Icons";
import InfiniteScroll from "~/components/InfiniteScroll";
+import { ConfirmDelete } from "~/components/Modals";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUrlParams, useUser } from "~/hooks";
-import { methodOperationOrders, operationTypes } from "~/modules/shared";
+import type { OperationTool } from "~/modules/shared";
+import {
+ methodOperationOrders,
+ operationToolValidator,
+ operationTypes,
+} from "~/modules/shared";
+import type { action as editJobOperationToolAction } from "~/routes/x+/job+/methods+/operation.tool.$id";
+import type { action as newJobOperationToolAction } from "~/routes/x+/job+/methods+/operation.tool.new";
+import { useTools } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
import { jobOperationValidator } from "../../production.models";
import { getProductionEventsPage } from "../../production.service";
@@ -69,7 +102,9 @@ type ItemWithData = Item & {
type JobBillOfProcessProps = {
jobMakeMethodId: string;
locationId: string;
- operations: Operation[];
+ operations: (Operation & {
+ jobOperationTool: OperationTool[];
+ })[];
};
function makeItems(operations: Operation[]): ItemWithData[] {
@@ -122,7 +157,10 @@ function makeItem(operation: Operation): ItemWithData {
};
}
-const initialOperation: Omit<Operation, "jobMakeMethodId" | "order"> = {
+const initialOperation: Omit<
+ Operation,
+ "jobMakeMethodId" | "order" | "jobOperationTool"
+> = {
description: "",
laborRate: 0,
laborTime: 0,
@@ -474,6 +512,23 @@ const JobBillOfProcess = ({
},
{
id: 2,
+ label: "Tools",
+ content: (
+ <div className="flex w-full flex-col py-4">
+ <ToolsForm
+ tools={
+ operations.find((o) => o.id === item.id)?.jobOperationTool ?? []
+ }
+ operationId={item.id!}
+ isDisabled={
+ selectedItemId === null || isTemporaryId(selectedItemId!)
+ }
+ />
+ </div>
+ ),
+ },
+ {
+ id: 3,
label: "Realtime Events",
content: (
<div className="flex w-full flex-col pr-2 py-6 min-h-[300px]">
@@ -1389,3 +1444,212 @@ const ProductionEventActivity = ({ item }: ProductionEventActivityProps) => {
/>
);
};
+
+function ToolsListItem({
+ tool: { toolId, quantity, id, updatedBy, updatedAt, createdBy, createdAt },
+ operationId,
+ className,
+}: {
+ tool: OperationTool;
+ operationId: string;
+ className?: string;
+}) {
+ const disclosure = useDisclosure();
+ const deleteModalDisclosure = useDisclosure();
+ const submitted = useRef(false);
+ const fetcher = useFetcher<typeof editJobOperationToolAction>();
+
+ useEffect(() => {
+ if (submitted.current && fetcher.state === "idle") {
+ disclosure.onClose();
+ submitted.current = false;
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.state]);
+
+ const tools = useTools();
+ const tool = tools.find((t) => t.id === toolId);
+ if (!tool || !id) return null;
+
+ const isUpdated = updatedBy !== null;
+ const person = isUpdated ? updatedBy : createdBy;
+ const date = updatedAt ?? createdAt;
+
+ return (
+ <div className={cn("border-b p-6", className)}>
+ {disclosure.isOpen ? (
+ <ValidatedForm
+ action={path.to.jobOperationTool(id)}
+ method="post"
+ validator={operationToolValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ onSubmit={() => {
+ disclosure.onClose();
+ }}
+ defaultValues={{
+ id: id,
+ toolId: toolId ?? "",
+ quantity: quantity ?? 1,
+ operationId,
+ }}
+ className="w-full"
+ >
+ <Hidden name="operationId" />
+ <VStack spacing={4}>
+ <div className="w-full grid grid-cols-1 lg:grid-cols-[1fr_1fr] gap-4 items-start">
+ <Tool name="toolId" label="Tool" autoFocus />
+ <Number name="quantity" label="Quantity" />
+ </div>
+ <HStack className="w-full justify-end" spacing={2}>
+ <Button variant="secondary" onClick={disclosure.onClose}>
+ Cancel
+ </Button>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Save
+ </Submit>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ ) : (
+ <div className="flex flex-1 justify-between items-center w-full">
+ <HStack spacing={4} className="w-1/2">
+ <HStack spacing={4} className="flex-1">
+ <div className="bg-muted border rounded-full flex items-center justify-center p-2">
+ <LuHammer className="size-4" />
+ </div>
+ <VStack spacing={0}>
+ <span className="text-sm font-medium">{tool.readableId}</span>
+ <span className="text-xs text-muted-foreground">
+ {tool.name}
+ </span>
+ </VStack>
+ <span className="text-base text-muted-foreground text-right">
+ {quantity}
+ </span>
+ </HStack>
+ </HStack>
+ <div className="flex items-center justify-end gap-2">
+ <HStack spacing={2}>
+ <span className="text-xs text-muted-foreground">
+ {isUpdated ? "Updated" : "Created"} {formatRelativeTime(date)}
+ </span>
+ <EmployeeAvatar employeeId={person} withName={false} />
+ </HStack>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Open menu"
+ icon={<LuMoreVertical />}
+ variant="ghost"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={disclosure.onOpen}>
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className="text-destructive"
+ onClick={deleteModalDisclosure.onOpen}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ )}
+ {deleteModalDisclosure.isOpen && (
+ <ConfirmDelete
+ action={path.to.deleteJobOperationTool(id)}
+ isOpen={deleteModalDisclosure.isOpen}
+ name={tool.readableId}
+ text={`Are you sure you want to delete ${tool.readableId} from this operation? This cannot be undone.`}
+ onCancel={() => {
+ deleteModalDisclosure.onClose();
+ }}
+ onSubmit={() => {
+ deleteModalDisclosure.onClose();
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function ToolsForm({
+ operationId,
+ isDisabled,
+ tools,
+}: {
+ operationId: string;
+ isDisabled: boolean;
+ tools: OperationTool[];
+}) {
+ const fetcher = useFetcher<typeof newJobOperationToolAction>();
+
+ if (isDisabled && isTemporaryId(operationId)) {
+ return (
+ <Alert className="max-w-[420px] mx-auto my-8">
+ <LuAlertTriangle />
+ <AlertTitle>Cannot add tools to unsaved operation</AlertTitle>
+ <AlertDescription>
+ Please save the operation before adding tools.
+ </AlertDescription>
+ </Alert>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="p-6 border rounded-lg">
+ <ValidatedForm
+ action={path.to.newJobOperationTool}
+ method="post"
+ validator={operationToolValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ defaultValues={{
+ id: undefined,
+ toolId: "",
+ quantity: 1,
+ operationId,
+ }}
+ className="w-full"
+ >
+ <Hidden name="operationId" />
+ <VStack spacing={4}>
+ <div className="w-full grid grid-cols-1 lg:grid-cols-[1fr_1fr] gap-4 items-start">
+ <Tool name="toolId" label="Tool" autoFocus />
+ <Number name="quantity" label="Quantity" />
+ </div>
+
+ <Submit
+ leftIcon={<LuPlusCircle />}
+ isDisabled={isDisabled || fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Add New
+ </Submit>
+ </VStack>
+ </ValidatedForm>
+ </div>
+
+ {tools.length > 0 && (
+ <div className="border rounded-lg">
+ {tools.map((t, index) => (
+ <ToolsListItem
+ key={t.id}
+ tool={t}
+ operationId={operationId}
+ className={index === tools.length - 1 ? "border-none" : ""}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 1f878890fb..ef5a3eae49 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -7,6 +7,7 @@ import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
import { sanitize } from "~/utils/supabase";
import { getCurrencyByCode } from "../accounting";
+import type { operationToolValidator } from "../shared";
import { upsertExternalLink } from "../shared/shared.service";
import type {
customerAccountingValidator,
@@ -194,6 +195,13 @@ export async function deleteQuoteOperation(
return client.from("quoteOperation").delete().eq("id", quoteOperationId);
}
+export async function deleteQuoteOperationTool(
+ client: SupabaseClient<Database>,
+ id: string
+) {
+ return client.from("quoteOperationTool").delete().eq("id", id);
+}
+
export async function deleteSalesOrder(
client: SupabaseClient<Database>,
salesOrderId: string
@@ -800,7 +808,9 @@ export async function getQuoteOperationsByMethodId(
) {
return client
.from("quoteOperation")
- .select("*")
+ .select(
+ "*, quoteOperationTool(id, operationId, toolId, quantity, createdBy, createdAt, updatedBy, updatedAt)"
+ )
.eq("quoteMakeMethodId", quoteMakeMethodId)
.order("order", { ascending: true });
}
@@ -1869,6 +1879,35 @@ export async function upsertQuoteOperation(
.single();
}
+export async function upsertQuoteOperationTool(
+ client: SupabaseClient<Database>,
+ quoteOperationTool:
+ | (Omit<z.infer<typeof operationToolValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ })
+ | (Omit<z.infer<typeof operationToolValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ updatedAt: string;
+ })
+) {
+ if ("createdBy" in quoteOperationTool) {
+ return client
+ .from("quoteOperationTool")
+ .insert(quoteOperationTool)
+ .select("id")
+ .single();
+ }
+
+ return client
+ .from("quoteOperationTool")
+ .update(sanitize(quoteOperationTool))
+ .eq("id", quoteOperationTool.id)
+ .select("id")
+ .single();
+}
+
export async function upsertQuotePayment(
client: SupabaseClient<Database>,
quotePayment:
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 2b6eeed110..25aefa94d0 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -3,6 +3,9 @@ import { useCarbon } from "@carbon/auth";
import { ValidatedForm } from "@carbon/form";
import type { JSONContent } from "@carbon/react";
import {
+ Alert,
+ AlertDescription,
+ AlertTitle,
Badge,
Button,
Card,
@@ -10,27 +13,44 @@ import {
CardContent,
CardHeader,
CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
Editor,
HStack,
IconButton,
Label,
+ VStack,
cn,
generateHTML,
useDebounce,
+ useDisclosure,
} from "@carbon/react";
+import { formatRelativeTime } from "@carbon/utils";
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 { useCallback, useEffect, useRef, useState } from "react";
import { flushSync } from "react-dom";
-import { LuChevronDown, LuDollarSign, LuSettings2, LuX } from "react-icons/lu";
+import {
+ LuAlertTriangle,
+ LuChevronDown,
+ LuDollarSign,
+ LuHammer,
+ LuMoreVertical,
+ LuPlusCircle,
+ LuSettings2,
+ LuX,
+} from "react-icons/lu";
import type { z } from "zod";
-import { DirectionAwareTabs, TimeTypeIcon } from "~/components";
+import { DirectionAwareTabs, EmployeeAvatar, TimeTypeIcon } from "~/components";
import {
Hidden,
InputControlled,
+ Number,
NumberControlled,
Process,
Select,
@@ -38,14 +58,24 @@ import {
StandardFactor,
Submit,
SupplierProcess,
+ Tool,
UnitHint,
WorkCenter,
getUnitHint,
} from "~/components/Form";
+import { ConfirmDelete } from "~/components/Modals";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { methodOperationOrders, operationTypes } from "~/modules/shared";
+import type { OperationTool } from "~/modules/shared";
+import {
+ methodOperationOrders,
+ operationToolValidator,
+ operationTypes,
+} from "~/modules/shared";
+import type { action as editQuoteOperationToolAction } from "~/routes/x+/quote+/methods+/operation.tool.$id";
+import type { action as newQuoteOperationToolAction } from "~/routes/x+/quote+/methods+/operation.tool.new";
+import { useTools } from "~/stores";
import { getPrivateUrl, path } from "~/utils/path";
import { quoteOperationValidator } from "../../sales.models";
import type { Quotation } from "../../types";
@@ -60,7 +90,9 @@ type ItemWithData = Item & {
type QuoteBillOfProcessProps = {
quoteMakeMethodId: string;
- operations: Operation[];
+ operations: (Operation & {
+ quoteOperationTool: OperationTool[];
+ })[];
};
function makeItems(operations: Operation[]): ItemWithData[] {
@@ -110,7 +142,10 @@ function makeItem(operation: Operation): ItemWithData {
};
}
-const initialOperation: Omit<Operation, "quoteMakeMethodId" | "order"> = {
+const initialOperation: Omit<
+ Operation,
+ "quoteMakeMethodId" | "order" | "quoteOperationTool"
+> = {
description: "",
laborRate: 0,
laborTime: 0,
@@ -366,6 +401,24 @@ const QuoteBillOfProcess = ({
</div>
),
},
+ {
+ id: 2,
+ label: "Tools",
+ content: (
+ <div className="flex w-full flex-col py-4">
+ <ToolsForm
+ tools={
+ operations.find((o) => o.id === item.id)?.quoteOperationTool ??
+ []
+ }
+ operationId={item.id!}
+ isDisabled={
+ selectedItemId === null || isTemporaryId(selectedItemId!)
+ }
+ />
+ </div>
+ ),
+ },
];
return (
@@ -1206,3 +1259,212 @@ function OperationForm({
</ValidatedForm>
);
}
+
+function ToolsListItem({
+ tool: { toolId, quantity, id, updatedBy, updatedAt, createdBy, createdAt },
+ operationId,
+ className,
+}: {
+ tool: OperationTool;
+ operationId: string;
+ className?: string;
+}) {
+ const disclosure = useDisclosure();
+ const deleteModalDisclosure = useDisclosure();
+ const submitted = useRef(false);
+ const fetcher = useFetcher<typeof editQuoteOperationToolAction>();
+
+ useEffect(() => {
+ if (submitted.current && fetcher.state === "idle") {
+ disclosure.onClose();
+ submitted.current = false;
+ }
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [fetcher.state]);
+
+ const tools = useTools();
+ const tool = tools.find((t) => t.id === toolId);
+ if (!tool || !id) return null;
+
+ const isUpdated = updatedBy !== null;
+ const person = isUpdated ? updatedBy : createdBy;
+ const date = updatedAt ?? createdAt;
+
+ return (
+ <div className={cn("border-b p-6", className)}>
+ {disclosure.isOpen ? (
+ <ValidatedForm
+ action={path.to.quoteOperationTool(id)}
+ method="post"
+ validator={operationToolValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ onSubmit={() => {
+ disclosure.onClose();
+ }}
+ defaultValues={{
+ id: id,
+ toolId: toolId ?? "",
+ quantity: quantity ?? 1,
+ operationId,
+ }}
+ className="w-full"
+ >
+ <Hidden name="operationId" />
+ <VStack spacing={4}>
+ <div className="w-full grid grid-cols-1 lg:grid-cols-[1fr_1fr] gap-4 items-start">
+ <Tool name="toolId" label="Tool" autoFocus />
+ <Number name="quantity" label="Quantity" />
+ </div>
+ <HStack className="w-full justify-end" spacing={2}>
+ <Button variant="secondary" onClick={disclosure.onClose}>
+ Cancel
+ </Button>
+ <Submit
+ isDisabled={fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Save
+ </Submit>
+ </HStack>
+ </VStack>
+ </ValidatedForm>
+ ) : (
+ <div className="flex flex-1 justify-between items-center w-full">
+ <HStack spacing={4} className="w-1/2">
+ <HStack spacing={4} className="flex-1">
+ <div className="bg-muted border rounded-full flex items-center justify-center p-2">
+ <LuHammer className="size-4" />
+ </div>
+ <VStack spacing={0}>
+ <span className="text-sm font-medium">{tool.readableId}</span>
+ <span className="text-xs text-muted-foreground">
+ {tool.name}
+ </span>
+ </VStack>
+ <span className="text-base text-muted-foreground text-right">
+ {quantity}
+ </span>
+ </HStack>
+ </HStack>
+ <div className="flex items-center justify-end gap-2">
+ <HStack spacing={2}>
+ <span className="text-xs text-muted-foreground">
+ {isUpdated ? "Updated" : "Created"} {formatRelativeTime(date)}
+ </span>
+ <EmployeeAvatar employeeId={person} withName={false} />
+ </HStack>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Open menu"
+ icon={<LuMoreVertical />}
+ variant="ghost"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={disclosure.onOpen}>
+ Edit
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ className="text-destructive"
+ onClick={deleteModalDisclosure.onOpen}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </div>
+ )}
+ {deleteModalDisclosure.isOpen && (
+ <ConfirmDelete
+ action={path.to.deleteQuoteOperationTool(id)}
+ isOpen={deleteModalDisclosure.isOpen}
+ name={tool.readableId}
+ text={`Are you sure you want to delete ${tool.readableId} from this operation? This cannot be undone.`}
+ onCancel={() => {
+ deleteModalDisclosure.onClose();
+ }}
+ onSubmit={() => {
+ deleteModalDisclosure.onClose();
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function ToolsForm({
+ operationId,
+ isDisabled,
+ tools,
+}: {
+ operationId: string;
+ isDisabled: boolean;
+ tools: OperationTool[];
+}) {
+ const fetcher = useFetcher<typeof newQuoteOperationToolAction>();
+
+ if (isDisabled && isTemporaryId(operationId)) {
+ return (
+ <Alert className="max-w-[420px] mx-auto my-8">
+ <LuAlertTriangle />
+ <AlertTitle>Cannot add tools to unsaved operation</AlertTitle>
+ <AlertDescription>
+ Please save the operation before adding tools.
+ </AlertDescription>
+ </Alert>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-6">
+ <div className="p-6 border rounded-lg">
+ <ValidatedForm
+ action={path.to.newQuoteOperationTool}
+ method="post"
+ validator={operationToolValidator}
+ fetcher={fetcher}
+ resetAfterSubmit
+ defaultValues={{
+ id: undefined,
+ toolId: "",
+ quantity: 1,
+ operationId,
+ }}
+ className="w-full"
+ >
+ <Hidden name="operationId" />
+ <VStack spacing={4}>
+ <div className="w-full grid grid-cols-1 lg:grid-cols-[1fr_1fr] gap-4 items-start">
+ <Tool name="toolId" label="Tool" autoFocus />
+ <Number name="quantity" label="Quantity" />
+ </div>
+
+ <Submit
+ leftIcon={<LuPlusCircle />}
+ isDisabled={isDisabled || fetcher.state !== "idle"}
+ isLoading={fetcher.state !== "idle"}
+ >
+ Add New
+ </Submit>
+ </VStack>
+ </ValidatedForm>
+ </div>
+
+ {tools.length > 0 && (
+ <div className="border rounded-lg">
+ {tools.map((t, index) => (
+ <ToolsListItem
+ key={t.id}
+ tool={t}
+ operationId={operationId}
+ className={index === tools.length - 1 ? "border-none" : ""}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/items+/methods+/operation.tool.$id.tsx b/apps/carbon/app/routes/x+/items+/methods+/operation.tool.$id.tsx
index 356070f402..2e9c07c1ec 100644
--- a/apps/carbon/app/routes/x+/items+/methods+/operation.tool.$id.tsx
+++ b/apps/carbon/app/routes/x+/items+/methods+/operation.tool.$id.tsx
@@ -9,7 +9,7 @@ import { operationToolValidator } from "~/modules/shared";
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, companyId, userId } = await requirePermissions(request, {
- create: "parts",
+ update: "parts",
});
const { id } = params;
diff --git a/apps/carbon/app/routes/x+/job+/methods+/operation.tool.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/operation.tool.$id.tsx
new file mode 100644
index 0000000000..10ab21f66f
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/operation.tool.$id.tsx
@@ -0,0 +1,65 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { upsertJobOperationTool } from "~/modules/production";
+import { operationToolValidator } from "~/modules/shared";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "production",
+ });
+
+ const { id } = params;
+ if (!id) {
+ return json({ success: false, message: "Invalid operation tool id" });
+ }
+
+ const formData = await request.formData();
+ const validation = await validator(operationToolValidator).validate(formData);
+
+ if (validation.error) {
+ return json({ success: false, message: "Invalid form data" });
+ }
+
+ const { id: _id, ...data } = validation.data;
+
+ const update = await upsertJobOperationTool(client, {
+ id,
+ ...data,
+ companyId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ });
+ if (update.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(update.error, "Failed to update job operation tool")
+ )
+ );
+ }
+
+ const operationToolId = update.data?.id;
+ if (!operationToolId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(update.error, "Failed to update job operation tool")
+ )
+ );
+ }
+
+ return json(
+ { id: operationToolId },
+ await flash(request, success("Job operation tool updated"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/operation.tool.delete.$id.tsx b/apps/carbon/app/routes/x+/job+/methods+/operation.tool.delete.$id.tsx
new file mode 100644
index 0000000000..0be85a7299
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/operation.tool.delete.$id.tsx
@@ -0,0 +1,32 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { deleteJobOperationTool } from "~/modules/production";
+
+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 deleteOperationTool = await deleteJobOperationTool(client, id);
+ if (deleteOperationTool.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(deleteOperationTool.error, "Failed to delete job operation tool")
+ )
+ );
+ }
+
+ return json({});
+}
diff --git a/apps/carbon/app/routes/x+/job+/methods+/operation.tool.new.tsx b/apps/carbon/app/routes/x+/job+/methods+/operation.tool.new.tsx
new file mode 100644
index 0000000000..2ee1e6fabe
--- /dev/null
+++ b/apps/carbon/app/routes/x+/job+/methods+/operation.tool.new.tsx
@@ -0,0 +1,53 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { upsertJobOperationTool } from "~/modules/production";
+import { operationToolValidator } from "~/modules/shared";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "production",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(operationToolValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const insert = await upsertJobOperationTool(client, {
+ ...validation.data,
+ companyId,
+ createdBy: userId,
+ });
+ if (insert.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insert.error, "Failed to insert job operation tool")
+ )
+ );
+ }
+
+ const jobOperationToolId = insert.data?.id;
+ if (!jobOperationToolId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insert.error, "Failed to insert job operation tool")
+ )
+ );
+ }
+
+ return json({ id: jobOperationToolId });
+}
diff --git a/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.$id.tsx b/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.$id.tsx
new file mode 100644
index 0000000000..8f298ca772
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.$id.tsx
@@ -0,0 +1,65 @@
+import { assertIsPost, error, success } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { upsertQuoteOperationTool } from "~/modules/sales";
+import { operationToolValidator } from "~/modules/shared";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { id } = params;
+ if (!id) {
+ return json({ success: false, message: "Invalid operation tool id" });
+ }
+
+ const formData = await request.formData();
+ const validation = await validator(operationToolValidator).validate(formData);
+
+ if (validation.error) {
+ return json({ success: false, message: "Invalid form data" });
+ }
+
+ const { id: _id, ...data } = validation.data;
+
+ const update = await upsertQuoteOperationTool(client, {
+ id,
+ ...data,
+ companyId,
+ updatedBy: userId,
+ updatedAt: new Date().toISOString(),
+ });
+ if (update.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(update.error, "Failed to update operation tool")
+ )
+ );
+ }
+
+ const operationToolId = update.data?.id;
+ if (!operationToolId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(update.error, "Failed to update operation tool")
+ )
+ );
+ }
+
+ return json(
+ { id: operationToolId },
+ await flash(request, success("Quote operation tool updated"))
+ );
+}
diff --git a/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.delete.$id.tsx b/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.delete.$id.tsx
new file mode 100644
index 0000000000..ac3b8e0f04
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.delete.$id.tsx
@@ -0,0 +1,35 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { deleteQuoteOperationTool } from "~/modules/sales";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "sales",
+ });
+
+ const { id } = params;
+ if (!id) {
+ throw new Error("id not found");
+ }
+
+ const deleteOperationTool = await deleteQuoteOperationTool(client, id);
+ if (deleteOperationTool.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(
+ deleteOperationTool.error,
+ "Failed to delete quote operation tool"
+ )
+ )
+ );
+ }
+
+ return json({});
+}
diff --git a/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.new.tsx b/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.new.tsx
new file mode 100644
index 0000000000..318370843d
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/methods+/operation.tool.new.tsx
@@ -0,0 +1,53 @@
+import { assertIsPost, error } from "@carbon/auth";
+import { requirePermissions } from "@carbon/auth/auth.server";
+import { flash } from "@carbon/auth/session.server";
+import { validationError, validator } from "@carbon/form";
+import { json, type ActionFunctionArgs } from "@vercel/remix";
+import { upsertQuoteOperationTool } from "~/modules/sales";
+import { operationToolValidator } from "~/modules/shared";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(operationToolValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const insert = await upsertQuoteOperationTool(client, {
+ ...validation.data,
+ companyId,
+ createdBy: userId,
+ });
+ if (insert.error) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insert.error, "Failed to insert quote operation tool")
+ )
+ );
+ }
+
+ const quoteOperationToolId = insert.data?.id;
+ if (!quoteOperationToolId) {
+ return json(
+ {
+ id: null,
+ },
+ await flash(
+ request,
+ error(insert.error, "Failed to insert quote operation tool")
+ )
+ );
+ }
+
+ return json({ id: quoteOperationToolId });
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 4cd3690ed8..4d38e6330d 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -254,6 +254,8 @@ export const path = {
deleteJob: (id: string) => generatePath(`${x}/job/${id}/delete`),
deleteJobMaterial: (jobId: string, id: string) =>
generatePath(`${x}/job/methods/${jobId}/material/delete/${id}`),
+ deleteJobOperationTool: (id: string) =>
+ generatePath(`${x}/job/methods/operation/tool/delete/${id}`),
deleteMaterialForm: (id: string) =>
generatePath(`${x}/items/forms/delete/${id}`),
deleteMaterialSubstance: (id: string) =>
@@ -290,6 +292,9 @@ export const path = {
generatePath(
`${x}/quote/methods/${quoteId}/${lineId}/material/delete/${id}`
),
+ deleteQuoteOperationTool: (id: string) =>
+ generatePath(`${x}/quote/methods/operation/tool/delete/${id}`),
+
deleteReceipt: (id: string) => generatePath(`${x}/receipt/delete/${id}`),
deleteSalesOrder: (id: string) =>
generatePath(`${x}/sales-order/${id}/delete`),
@@ -389,6 +394,8 @@ export const path = {
generatePath(`${x}/job/methods/${jobId}/operation/${id}`),
jobOperations: (id: string) => generatePath(`${x}/job/${id}/operations`),
jobOperationsOrder: `${x}/job/methods/operation/order`,
+ jobOperationTool: (id: string) =>
+ generatePath(`${x}/job/methods/operation/tool/${id}`),
jobOperationStatus: `${x}/job/methods/operation/status`,
jobProductionEvents: (id: string) => generatePath(`${x}/job/${id}/events`),
jobProductionQuantities: (id: string) =>
@@ -486,6 +493,7 @@ export const path = {
generatePath(`${x}/job/methods/${jobId}/material/new`),
newJobOperation: (jobId: string) =>
generatePath(`${x}/job/methods/${jobId}/operation/new`),
+ newJobOperationTool: `${x}/job/methods/operation/tool/new`,
newLocation: `${x}/resources/locations/new`,
newMaterial: `${x}/material/new`,
newMethodMaterial: `${x}/items/methods/material/new`,
@@ -515,6 +523,7 @@ export const path = {
generatePath(`${x}/quote/${id}/${lineId}/cost/new`),
newQuoteOperation: (quoteId: string, lineId: string) =>
generatePath(`${x}/quote/methods/${quoteId}/${lineId}/operation/new`),
+ newQuoteOperationTool: `${x}/quote/methods/operation/tool/new`,
newQuoteMaterial: (quoteId: string, lineId: string) =>
generatePath(`${x}/quote/methods/${quoteId}/${lineId}/material/new`),
newReceipt: `${x}/receipt/new`,
@@ -672,6 +681,8 @@ export const path = {
quoteOperation: (quoteId: string, lineId: string, id: string) =>
generatePath(`${x}/quote/methods/${quoteId}/${lineId}/operation/${id}`),
quoteOperationsOrder: `${x}/quote/methods/operation/order`,
+ quoteOperationTool: (id: string) =>
+ generatePath(`${x}/quote/methods/operation/tool/${id}`),
quotePayment: (id: string) => generatePath(`${x}/quote/${id}/payment`),
quoteShipment: (id: string) => generatePath(`${x}/quote/${id}/shipment`),
quoteStatus: (id: string) => generatePath(`${x}/quote/${id}/status`),