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: refactor quote bill of process to use process/work center/work instructions

Brad Barbin2e8a679363a7
diff --git a/apps/carbon/app/components/Form/UnitHint.tsx b/apps/carbon/app/components/Form/UnitHint.tsx
index 5b5ef04159..e7b6055f6e 100644
--- a/apps/carbon/app/components/Form/UnitHint.tsx
+++ b/apps/carbon/app/components/Form/UnitHint.tsx
@@ -4,8 +4,6 @@ import { Select } from "~/components";
import type { SelectProps } from "~/components/Select";
import type { StandardFactor } from "~/modules/shared";
-type UnitHints = "Per Unit" | "Fixed";
-
export type UnitHintProps = Omit<SelectProps, "onChange" | "options"> & {
defaultUnit?: StandardFactor;
label?: string;
@@ -25,7 +23,7 @@ const UnitHint = ({
value = getUnitHint(defaultUnit),
...props
}: UnitHintProps) => {
- const onChange = (value: UnitHints) => {
+ const onChange = (value: string) => {
props?.onChange?.(value);
};
diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.ts
index 6ec4d2f8f5..49d8193db7 100644
--- a/apps/carbon/app/components/Form/index.ts
+++ b/apps/carbon/app/components/Form/index.ts
@@ -53,6 +53,7 @@ import SupplierType from "./SupplierType";
import TextArea from "./Textarea";
import TimePicker from "./TimePicker";
import Timezone from "./Timezone";
+import UnitHint, { getUnitHint } from "./UnitHint";
import UnitOfMeasure from "./UnitOfMeasure";
import User from "./User";
import Users from "./Users";
@@ -74,17 +75,18 @@ export {
ConversionFactor,
CreatableCombobox,
Currency,
- CustomFormFields,
Customer,
CustomerContact,
CustomerLocation,
CustomerStatus,
CustomerType,
+ CustomFormFields,
DatePicker,
DefaultMethodType,
Department,
Employee,
Employees,
+ getUnitHint,
Hidden,
Input,
InputControlled,
@@ -115,6 +117,7 @@ export {
TextArea,
TimePicker,
Timezone,
+ UnitHint,
UnitOfMeasure,
User,
Users,
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index 5abbf7eec2..a1a2f2f580 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -13,6 +13,7 @@ import {
cn,
generateHTML,
useDebounce,
+ useThrottle,
} from "@carbon/react";
import { ValidatedForm } from "@carbon/remix-validated-form";
import { getLocalTimeZone, today } from "@internationalized/date";
@@ -33,9 +34,10 @@ import {
Select,
StandardFactor,
Submit,
+ UnitHint,
WorkCenter,
+ getUnitHint,
} from "~/components/Form";
-import UnitHint, { getUnitHint } from "~/components/Form/UnitHint";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
import { usePermissions, useUser } from "~/hooks";
@@ -219,7 +221,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
});
}, []);
- const onUpdateWorkInstruction = useDebounce(async (content: JSONContent) => {
+ const onUpdateWorkInstruction = useThrottle(async (content: JSONContent) => {
if (!permissions.can("update", "parts")) return;
setItems((prevItems) =>
prevItems.map((item) =>
@@ -244,7 +246,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
updatedBy: userId,
})
.eq("methodOperationId", selectedItemId!);
- }, 3000);
+ }, 2000);
const onUploadImage = async (file: File) => {
const fileType = file.name.split(".").pop();
diff --git a/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx b/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
index f1ea01e5b1..b3f565c988 100644
--- a/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
+++ b/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
@@ -55,10 +55,10 @@ const WorkCenterForm = ({
if (fetcher.state === "loading" && fetcher.data?.data) {
onClose?.();
- toast.success(`Created work cell type`);
+ toast.success(`Created work center`);
} else if (fetcher.state === "idle" && fetcher.data?.error) {
toast.error(
- `Failed to create work cell type: ${fetcher.data.error.message}`
+ `Failed to create work center: ${fetcher.data.error.message}`
);
}
}, [fetcher.data, fetcher.state, onClose, type]);
diff --git a/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx b/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
index b01547a0bc..3e803ae12f 100644
--- a/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx
@@ -192,7 +192,7 @@ const WorkCentersTable = memo(
<ConfirmDelete
action={path.to.deleteWorkCenter(selectedWorkCenter.id)}
name={selectedWorkCenter?.name ?? ""}
- text={`Are you sure you want to deactivate the ${selectedWorkCenter?.name} work cell type?`}
+ text={`Are you sure you want to deactivate the ${selectedWorkCenter?.name} work center?`}
isOpen={deleteModal.isOpen}
onCancel={onDeleteCancel}
onSubmit={onDeleteCancel}
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index a78c018c31..cd648fc9b9 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -245,12 +245,14 @@ export const quoteOperationValidator = z.object({
quoteMakeMethodId: z
.string()
.min(1, { message: "Quote Make Method is required" }),
+ order: zfd.numeric(z.number().min(0)),
operationOrder: z.enum(methodOperationOrders, {
- errorMap: () => ({ message: "Operation Order is required" }),
+ errorMap: (issue, ctx) => ({
+ message: "Operation order is required",
+ }),
}),
- order: zfd.numeric(z.number().min(0)),
- workCellTypeId: z.string().min(20, { message: "Work cell is required" }),
- equipmentTypeId: zfd.text(z.string().optional()),
+ 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" })
),
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index b8efd2f57d..ebdbce4e00 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -677,7 +677,7 @@ export async function getQuoteOperation(
) {
return client
.from("quoteOperation")
- .select("*")
+ .select("*, quoteOperationWorkInstruction(content)")
.eq("id", quoteOperationId)
.single();
}
@@ -698,7 +698,7 @@ export async function getQuoteOperationsByMethodId(
) {
return client
.from("quoteOperation")
- .select("*")
+ .select("*, quoteOperationWorkInstruction(content)")
.eq("quoteMakeMethodId", quoteMakeMethodId)
.order("order", { ascending: true });
}
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 7da99ac789..ce2f53ac82 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -1,4 +1,5 @@
"use client";
+import type { JSONContent } from "@carbon/react";
import {
Badge,
Button,
@@ -7,38 +8,51 @@ import {
CardContent,
CardHeader,
CardTitle,
+ Editor,
HStack,
cn,
+ generateHTML,
useDebounce,
+ useThrottle,
} from "@carbon/react";
import { ValidatedForm } from "@carbon/remix-validated-form";
+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 { LuSettings2, LuX } from "react-icons/lu";
+import { LuHammer, LuHardHat, LuSettings2, LuX } from "react-icons/lu";
import type { z } from "zod";
+import { DirectionAwareTabs } from "~/components/DirectionAwareTabs";
import {
Hidden,
InputControlled,
Number,
NumberControlled,
+ Process,
Select,
StandardFactor,
Submit,
+ UnitHint,
WorkCenter,
+ getUnitHint,
} from "~/components/Form";
import type { Item, SortableItemRenderProps } from "~/components/SortableList";
import { SortableList, SortableListItem } from "~/components/SortableList";
-import { usePermissions, useRouteData } from "~/hooks";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import { methodOperationOrders } from "~/modules/shared";
import { path } from "~/utils/path";
import { quoteOperationValidator } from "../../sales.models";
import type { Quotation } from "../../types";
-type Operation = z.infer<typeof quoteOperationValidator>;
+type Operation = z.infer<typeof quoteOperationValidator> & {
+ quoteOperationWorkInstruction: {
+ content: JSONContent | null;
+ };
+};
type ItemWithData = Item & {
data: Operation;
@@ -61,10 +75,19 @@ function makeItem(operation: Operation): ItemWithData {
order: operation.operationOrder,
details: (
<HStack spacing={1}>
- <Badge variant="secondary">
- {operation.productionStandard} {operation.standardFactor}
- </Badge>
- <Badge variant="secondary">{operation.operationOrder}</Badge>
+ {operation.laborTime > 0 && (
+ <Badge variant="secondary">
+ <LuHardHat className="h-3 w-3 mr-1" />
+ {operation.laborTime} {operation.laborUnit}
+ </Badge>
+ )}
+
+ {operation.machineTime > 0 && (
+ <Badge variant="secondary">
+ <LuHammer className="h-3 w-3 mr-1" />
+ {operation.machineTime} {operation.machineUnit}
+ </Badge>
+ )}
</HStack>
),
data: operation,
@@ -73,15 +96,20 @@ function makeItem(operation: Operation): ItemWithData {
const initialMethodOperation: Omit<Operation, "quoteMakeMethodId" | "order"> = {
description: "",
- workCellTypeId: "",
- equipmentTypeId: "",
- setupHours: 0,
- productionStandard: 0,
- standardFactor: "Hours/Piece",
+ processId: "",
+ workCenterId: "",
+ setupTime: 0,
+ setupUnit: "Total Minutes",
+ laborTime: 0,
+ laborUnit: "Minutes/Piece",
+ machineTime: 0,
+ machineUnit: "Minutes/Piece",
operationOrder: "After Previous",
- quotingRate: 0,
laborRate: 0,
- overheadRate: 0,
+ quotingRate: 0,
+ quoteOperationWorkInstruction: {
+ content: {},
+ },
};
const QuoteBillOfProcess = ({
@@ -91,6 +119,10 @@ const QuoteBillOfProcess = ({
const { supabase } = useSupabase();
const sortOrderFetcher = useFetcher<{}>();
const permissions = usePermissions();
+ const {
+ id: userId,
+ company: { id: companyId },
+ } = useUser();
const [items, setItems] = useState<ItemWithData[]>(
makeItems(operations ?? [])
@@ -203,6 +235,52 @@ const QuoteBillOfProcess = ({
});
}, []);
+ const onUpdateWorkInstruction = useThrottle(async (content: JSONContent) => {
+ if (!permissions.can("update", "parts")) return;
+ setItems((prevItems) =>
+ prevItems.map((item) =>
+ item.id === selectedItemId
+ ? {
+ ...item,
+ data: {
+ ...item.data,
+ quoteOperationWorkInstruction: {
+ content,
+ },
+ },
+ }
+ : item
+ )
+ );
+ await supabase
+ ?.from("quoteOperationWorkInstruction")
+ .update({
+ content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("quoteOperationId", selectedItemId!);
+ }, 2500);
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/quote-line/${selectedItemId}/${nanoid()}.${fileType}`;
+ const result = await supabase?.storage
+ .from("private")
+ .upload(fileName, file);
+
+ 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,
@@ -211,6 +289,73 @@ const QuoteBillOfProcess = ({
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",
+ disabled: isTemporaryId(item.id),
+ 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.quoteOperationWorkInstruction?.content ??
+ ({} as JSONContent)
+ }
+ onUpload={onUploadImage}
+ onChange={onUpdateWorkInstruction}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(
+ item.data.quoteOperationWorkInstruction?.content ??
+ ({} as JSONContent)
+ ),
+ }}
+ />
+ )}
+ </motion.div>
+ </div>
+ ),
+ },
+ ];
return (
<SortableListItem<Operation>
@@ -304,25 +449,13 @@ const QuoteBillOfProcess = ({
layout
className="w-full "
>
- <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>
+ <DirectionAwareTabs
+ className="mr-auto"
+ tabs={tabs}
+ onChange={() =>
+ setTabChangeRerender(tabChangeRerender + 1)
+ }
+ />
</motion.div>
</div>
</motion.div>
@@ -390,22 +523,22 @@ function OperationForm({
if (!quoteId) throw new Error("quoteId not found");
if (!lineId) throw new Error("lineId not found");
- const methodOperationFetcher = useFetcher<{ id: string }>();
+ const fetcher = useFetcher<{ id: string }>();
const { supabase } = useSupabase();
useEffect(() => {
// replace the temporary id with the actual id
- if (methodOperationFetcher.data && methodOperationFetcher.data.id) {
+ if (fetcher.data && fetcher.data.id) {
flushSync(() => {
setItems((prevItems) =>
prevItems.map((i) =>
i.id === item.id
? {
...i,
- id: methodOperationFetcher.data!.id!,
+ id: fetcher.data!.id!,
data: {
...i.data,
- ...methodOperationFetcher.data,
+ ...fetcher.data,
},
}
: i
@@ -414,52 +547,96 @@ function OperationForm({
});
setSelectedItemId(null);
}
- }, [item.id, methodOperationFetcher.data, setItems, setSelectedItemId]);
+ }, [item.id, fetcher.data, setItems, setSelectedItemId]);
- const [workCellData, setWorkCellData] = useState<{
- workCellTypeId: string;
+ const [processData, setProcessData] = useState<{
+ processId: string;
description: string;
- standardFactor: string;
- quotingRate: number;
+ setupUnitHint: string;
+ setupUnit: string;
+ laborUnitHint: string;
+ laborUnit: string;
+ machineUnitHint: string;
+ machineUnit: string;
laborRate: number;
- overheadRate: number;
+ quotingRate: number;
}>({
- workCellTypeId: item.data.workCellTypeId ?? "",
+ processId: item.data.processId ?? "",
description: item.data.description ?? "",
- standardFactor: item.data.standardFactor ?? "Hours/Piece",
- quotingRate: item.data.quotingRate ?? 0,
+ setupUnitHint: getUnitHint(item.data.setupUnit),
+ setupUnit: item.data.setupUnit ?? "Total Minutes",
+ laborUnitHint: getUnitHint(item.data.laborUnit),
+ laborUnit: item.data.laborUnit ?? "Hours/Piece",
+ machineUnitHint: getUnitHint(item.data.machineUnit),
+ machineUnit: item.data.machineUnit ?? "Hours/Piece",
laborRate: item.data.laborRate ?? 0,
- overheadRate: item.data.overheadRate ?? 0,
+ quotingRate: item.data.quotingRate ?? 0,
});
- const onWorkCellChange = async (workCellTypeId: string) => {
- if (!supabase || !workCellTypeId) return;
+ const onProcessChange = async (processId: string) => {
+ if (!supabase || !processId) return;
+ const [process, workCenters] = await Promise.all([
+ supabase.from("process").select("*").eq("id", processId).single(),
+ supabase
+ .from("workCenterProcess")
+ .select("workCenter(*)")
+ .eq("processId", processId),
+ ]);
+
+ 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),
+ machineUnit: process.data?.defaultStandardFactor ?? "Hours/Piece",
+ machineUnitHint: getUnitHint(process.data?.defaultStandardFactor),
+ laborRate:
+ // get the average labor rate from the work centers
+ workCenters?.data && workCenters.data.length
+ ? workCenters?.data?.reduce((acc, workCenter) => {
+ return (acc += workCenter.workCenter?.laborRate ?? 0);
+ }, 0) / workCenters?.data.length
+ : p.laborRate,
+ // get the average quoting rate from the work centers
+ quotingRate:
+ workCenters?.data && workCenters.data.length
+ ? workCenters?.data?.reduce((acc, workCenter) => {
+ return (acc += workCenter.workCenter?.quotingRate ?? 0);
+ }, 0) / workCenters?.data.length
+ : p.laborRate,
+ }));
+ };
+
+ 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("workCellType")
+ .from("workCenter")
.select("*")
- .eq("id", workCellTypeId)
+ .eq("id", workCenterId)
.single();
if (error) throw new Error(error.message);
- setWorkCellData({
- workCellTypeId,
- description: data?.name ?? "",
- standardFactor: data?.defaultStandardFactor ?? "Hours/Piece",
+ setProcessData((d) => ({
+ ...d,
+ laborUnit: data?.defaultStandardFactor ?? "Hours/Piece",
+ laborUnitHint: getUnitHint(data?.defaultStandardFactor),
+ machineUnit: data?.defaultStandardFactor ?? "Hours/Piece",
+ machineUnitHint: getUnitHint(data?.defaultStandardFactor),
quotingRate: data?.quotingRate ?? 0,
laborRate: data?.laborRate ?? 0,
- overheadRate: data?.overheadRate ?? 0,
- });
+ }));
};
- const [equipmentData, setEquipmentData] = useState<{
- equipmentTypeId: string;
- setupHours: number;
- }>({
- equipmentTypeId: item.data.equipmentTypeId ?? "",
- setupHours: item.data.setupHours ?? 0,
- });
-
return (
<ValidatedForm
action={
@@ -471,13 +648,18 @@ function OperationForm({
defaultValues={item.data}
validator={quoteOperationValidator}
className="w-full flex flex-col gap-y-4"
- fetcher={methodOperationFetcher}
+ fetcher={fetcher}
onSubmit={(values) => {
setItems((prevItems) =>
prevItems.map((i) =>
i.id === item.id
? {
- ...makeItem(values),
+ ...makeItem({
+ ...values,
+ quoteOperationWorkInstruction: {
+ content: i.data.quoteOperationWorkInstruction?.content,
+ },
+ }),
id: item.id,
}
: i
@@ -488,12 +670,11 @@ function OperationForm({
<Hidden name="quoteMakeMethodId" />
<Hidden name="order" />
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <WorkCenter
- name="workCellTypeId"
- label="Work Cell"
- isReadOnly={isDisabled}
+ <Process
+ name="processId"
+ label="Process"
onChange={(value) => {
- onWorkCellChange(value?.value as string);
+ onProcessChange(value?.value as string);
}}
/>
<Select
@@ -505,38 +686,97 @@ function OperationForm({
label: o,
}))}
/>
+ <WorkCenter
+ name="workCenterId"
+ label="Work Center"
+ isOptional
+ processId={processData.processId}
+ onChange={(value) => {
+ onWorkCenterChange(value?.value ?? null);
+ }}
+ />
</div>
<InputControlled
name="description"
label="Description"
- value={workCellData.description}
+ value={processData.description}
onChange={(newValue) => {
- setWorkCellData((d) => ({ ...d, description: newValue }));
+ setProcessData((d) => ({ ...d, description: newValue }));
}}
/>
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <NumberControlled
- name="setupHours"
- label="Setup Time"
- minValue={0}
- value={equipmentData.setupHours}
+ <UnitHint
+ name="setupHint"
+ label="Setup"
+ value={processData.setupUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ setupUnitHint: hint,
+ setupUnit: hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
+ }));
+ }}
+ />
+ <Number name="setupTime" label="Setup Time" minValue={0} />
+ <StandardFactor
+ name="setupUnit"
+ label="Setup Unit"
+ hint={processData.setupUnitHint}
+ value={processData.setupUnit}
onChange={(newValue) => {
- setEquipmentData((d) => ({ ...d, setupHours: newValue }));
+ setProcessData((d) => ({
+ ...d,
+ setupUnit: newValue?.value ?? "Total Minutes",
+ }));
}}
/>
- <Number
- name="productionStandard"
- label="Production Standard"
- minValue={0}
+ <UnitHint
+ name="laborHint"
+ label="Labor"
+ value={processData.laborUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ laborUnitHint: hint,
+ laborUnit: hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
+ }));
+ }}
/>
+ <Number name="laborTime" label="Labor Time" minValue={0} />
<StandardFactor
- name="standardFactor"
- label="Standard Factor"
- value={workCellData.standardFactor}
+ name="laborUnit"
+ label="Labor Unit"
+ hint={processData.laborUnitHint}
+ value={processData.laborUnit}
onChange={(newValue) => {
- setWorkCellData((d) => ({
+ setProcessData((d) => ({
...d,
- standardFactor: newValue?.value ?? "Hours/Piece",
+ laborUnit: newValue?.value ?? "Hours/Piece",
+ }));
+ }}
+ />
+ <UnitHint
+ name="machineHint"
+ label="Machine"
+ value={processData.machineUnitHint}
+ onChange={(hint) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnitHint: hint,
+ machineUnit: hint === "Fixed" ? "Total Minutes" : "Minutes/Piece",
+ }));
+ }}
+ />
+ <Number name="machineTime" label="Machine Time" minValue={0} />
+ <StandardFactor
+ name="machineUnit"
+ label="Machine Unit"
+ hint={processData.machineUnitHint}
+ value={processData.machineUnit}
+ onChange={(newValue) => {
+ setProcessData((d) => ({
+ ...d,
+ machineUnit: newValue?.value ?? "Hours/Piece",
}));
}}
/>
@@ -544,9 +784,13 @@ function OperationForm({
name="quotingRate"
label="Quoting Rate"
minValue={0}
- value={workCellData.quotingRate}
+ value={processData.quotingRate}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
onChange={(newValue) =>
- setWorkCellData((d) => ({
+ setProcessData((d) => ({
...d,
quotingRate: newValue,
}))
@@ -556,26 +800,18 @@ function OperationForm({
name="laborRate"
label="Labor Rate"
minValue={0}
- value={workCellData.laborRate}
+ value={processData.laborRate}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
onChange={(newValue) =>
- setWorkCellData((d) => ({
+ setProcessData((d) => ({
...d,
laborRate: newValue,
}))
}
/>
- <NumberControlled
- name="overheadRate"
- label="Overhead Rate"
- minValue={0}
- value={workCellData.overheadRate}
- onChange={(newValue) =>
- setWorkCellData((d) => ({
- ...d,
- overheadRate: newValue,
- }))
- }
- />
</div>
<motion.div
className="flex w-full items-center justify-end p-2"
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
index c1e005c2f5..cead835398 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -253,6 +253,7 @@ const QuoteLineForm = ({
<div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
<div className="col-span-2 grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-2 auto-rows-min">
<Item
+ autoFocus
name="itemId"
label="Part"
type="Part"
@@ -311,7 +312,6 @@ const QuoteLineForm = ({
}));
}}
onBlur={(e) => onCustomerPartChange(e.target.value)}
- autoFocus
/>
<InputControlled
name="customerPartRevision"
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx
index f6697f5bc4..771938ca87 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineNotes.tsx
@@ -7,7 +7,7 @@ import {
Editor,
generateHTML,
toast,
- useDebounce,
+ useThrottle,
} from "@carbon/react";
import { getLocalTimeZone, today } from "@internationalized/date";
import { nanoid } from "nanoid";
@@ -44,7 +44,7 @@ const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {
return `/file/preview/private/${result.data.path}`;
};
- const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {
+ const onUpdateInternalNotes = useThrottle(async (content: JSONContent) => {
await supabase
?.from("quoteLine")
.update({
@@ -53,7 +53,7 @@ const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {
updatedBy: userId,
})
.eq("id", line.id!);
- }, 3000);
+ }, 2500);
return (
<Card>
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx
index 075cfa3ada..1b3f14da83 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx
@@ -7,7 +7,7 @@ import {
Editor,
generateHTML,
toast,
- useDebounce,
+ useThrottle,
} from "@carbon/react";
import { getLocalTimeZone, today } from "@internationalized/date";
import { nanoid } from "nanoid";
@@ -44,7 +44,7 @@ const SalesRFQLineNotes = ({ line }: { line: SalesRFQLine }) => {
return `/file/preview/private/${result.data.path}`;
};
- const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {
+ const onUpdateInternalNotes = useThrottle(async (content: JSONContent) => {
await supabase
?.from("salesRfqLine")
.update({
@@ -53,7 +53,7 @@ const SalesRFQLineNotes = ({ line }: { line: SalesRFQLine }) => {
updatedBy: userId,
})
.eq("id", line.id!);
- }, 3000);
+ }, 2500);
return (
<Card>
diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
index 718d6099f2..d5ec5ddc16 100644
--- a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.$makeMethodId.$materialId.tsx
@@ -86,7 +86,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
methodOperations:
methodOperations.data?.map((operation) => ({
...operation,
- equipmentTypeId: operation.equipmentTypeId ?? undefined,
+ workCenterId: operation.workCenterId ?? undefined,
methodOperationWorkInstruction:
operation.methodOperationWorkInstruction as {
content: JSONContent | null;
diff --git a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.tsx b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.tsx
index 5f27c1b3de..f0dfc334df 100644
--- a/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.tsx
+++ b/apps/carbon/app/routes/x+/fixture+/$itemId.manufacturing.tsx
@@ -97,7 +97,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
methodOperations:
methodOperations.data?.map((operation) => ({
...operation,
- equipmentTypeId: operation.equipmentTypeId ?? undefined,
+ workCenterId: operation.workCenterId ?? undefined,
methodOperationWorkInstruction:
operation.methodOperationWorkInstruction as {
content: JSONContent | null;
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx
index ac1e0decd3..cd8673466a 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.make.$methodId.$materialId.tsx
@@ -1,3 +1,4 @@
+import type { JSONContent } from "@carbon/react";
import { VStack } from "@carbon/react";
import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
@@ -90,8 +91,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
operations.data?.map((o) => ({
...o,
description: o.description ?? "",
- equipmentTypeId: o.equipmentTypeId ?? undefined,
+ workCenterId: o.workCenterId ?? undefined,
quoteMakeMethodId: o.quoteMakeMethodId ?? methodId,
+ quoteOperationWorkInstruction: {
+ content: (o.quoteOperationWorkInstruction?.content ??
+ {}) as JSONContent,
+ },
})) ?? [],
});
}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx
index c5d3debc1d..6801328f67 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.method.$methodId.tsx
@@ -1,3 +1,4 @@
+import type { JSONContent } from "@carbon/react";
import { VStack } from "@carbon/react";
import { json, redirect, useLoaderData, useParams } from "@remix-run/react";
@@ -61,8 +62,12 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
operations.data?.map((o) => ({
...o,
description: o.description ?? "",
- equipmentTypeId: o.equipmentTypeId ?? undefined,
+ workCenterId: o.workCenterId ?? undefined,
quoteMakeMethodId: o.quoteMakeMethodId ?? methodId,
+ quoteOperationWorkInstruction: {
+ content: (o.quoteOperationWorkInstruction?.content ??
+ {}) as JSONContent,
+ },
})) ?? [],
});
}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.pick.$methodId.$materialId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.pick.$methodId.$materialId.tsx
index 1cbcd2df25..2bb4ce971b 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.pick.$methodId.$materialId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.pick.$methodId.$materialId.tsx
@@ -58,7 +58,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
operations.data?.map((o) => ({
...o,
description: o.description ?? "",
- equipmentTypeId: o.equipmentTypeId ?? undefined,
+ workCenterId: o.workCenterId ?? undefined,
quoteMakeMethodId: o.quoteMakeMethodId ?? methodId,
})) ?? [],
});
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
index c63f114a72..6ff8f71491 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
@@ -7,7 +7,7 @@ import {
Editor,
generateHTML,
toast,
- useDebounce,
+ useThrottle,
} from "@carbon/react";
import { validationError, validator } from "@carbon/remix-validated-form";
import { getLocalTimeZone, today } from "@internationalized/date";
@@ -131,7 +131,7 @@ const QuoteNotes = ({ quote }: { quote: Quotation }) => {
return `/file/preview/private/${result.data.path}`;
};
- const onUpdateExternalNotes = useDebounce(async (content: JSONContent) => {
+ const onUpdateExternalNotes = useThrottle(async (content: JSONContent) => {
await supabase
?.from("quote")
.update({
@@ -140,7 +140,7 @@ const QuoteNotes = ({ quote }: { quote: Quotation }) => {
updatedBy: userId,
})
.eq("id", quote.id!);
- }, 3000);
+ }, 2500);
return (
<Card>
diff --git a/apps/carbon/app/routes/x+/resources+/work-centers.new.tsx b/apps/carbon/app/routes/x+/resources+/work-centers.new.tsx
index 99b37e8b3f..a893fa998c 100644
--- a/apps/carbon/app/routes/x+/resources+/work-centers.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/work-centers.new.tsx
@@ -45,7 +45,7 @@ export async function action({ request }: ActionFunctionArgs) {
path.to.workCenters,
await flash(
request,
- error(createWorkCenter.error, "Failed to create work cell type")
+ error(createWorkCenter.error, "Failed to create work center")
)
);
}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
index c735825725..3e3d72f7c0 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
@@ -7,7 +7,7 @@ import {
Editor,
generateHTML,
toast,
- useDebounce,
+ useThrottle,
VStack,
} from "@carbon/react";
import { validationError, validator } from "@carbon/remix-validated-form";
@@ -143,7 +143,7 @@ const SalesRFQNotes = ({ salesRfq }: { salesRfq: SalesRFQ }) => {
return `/file/preview/private/${result.data.path}`;
};
- const onUpdateExternalNotes = useDebounce(async (content: JSONContent) => {
+ const onUpdateExternalNotes = useThrottle(async (content: JSONContent) => {
await supabase
?.from("salesRfq")
.update({
@@ -152,7 +152,7 @@ const SalesRFQNotes = ({ salesRfq }: { salesRfq: SalesRFQ }) => {
updatedBy: userId,
})
.eq("id", salesRfq.id!);
- }, 3000);
+ }, 2500);
return (
<Card>
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index cdcfb1dc90..f6ded91f88 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -13696,6 +13696,121 @@ export type Database = {
},
]
}
+ quoteOperationWorkInstruction: {
+ Row: {
+ companyId: string
+ content: Json | null
+ createdAt: string
+ createdBy: string
+ quoteOperationId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ content?: Json | null
+ createdAt?: string
+ createdBy: string
+ quoteOperationId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ content?: Json | null
+ createdAt?: string
+ createdBy?: string
+ quoteOperationId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_quoteOperationId_fkey"
+ columns: ["quoteOperationId"]
+ isOneToOne: true
+ referencedRelation: "quoteOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_quoteOperationId_fkey"
+ columns: ["quoteOperationId"]
+ isOneToOne: true
+ referencedRelation: "quoteOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
receipt: {
Row: {
assignee: string | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index cdcfb1dc90..f6ded91f88 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -13696,6 +13696,121 @@ export type Database = {
},
]
}
+ quoteOperationWorkInstruction: {
+ Row: {
+ companyId: string
+ content: Json | null
+ createdAt: string
+ createdBy: string
+ quoteOperationId: string
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Insert: {
+ companyId: string
+ content?: Json | null
+ createdAt?: string
+ createdBy: string
+ quoteOperationId: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Update: {
+ companyId?: string
+ content?: Json | null
+ createdAt?: string
+ createdBy?: string
+ quoteOperationId?: string
+ updatedAt?: string | null
+ updatedBy?: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_quoteOperationId_fkey"
+ columns: ["quoteOperationId"]
+ isOneToOne: true
+ referencedRelation: "quoteOperation"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_quoteOperationId_fkey"
+ columns: ["quoteOperationId"]
+ isOneToOne: true
+ referencedRelation: "quoteOperationsWithMakeMethods"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperationWorkInstruction_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
receipt: {
Row: {
assignee: string | null
diff --git a/packages/database/supabase/migrations/20240819115702_work-centers.sql b/packages/database/supabase/migrations/20240819115702_work-centers.sql
index 05ca64d694..4eb7bcf654 100644
--- a/packages/database/supabase/migrations/20240819115702_work-centers.sql
+++ b/packages/database/supabase/migrations/20240819115702_work-centers.sql
@@ -261,4 +261,66 @@ CREATE OR REPLACE VIEW "quoteOperationsWithMakeMethods" WITH(SECURITY_INVOKER=tr
INNER JOIN "quoteMakeMethod" qmm
ON qo."quoteMakeMethodId" = qmm.id
LEFT JOIN "makeMethod" mm
- ON qmm."itemId" = mm."itemId";
\ No newline at end of file
+ ON qmm."itemId" = mm."itemId";
+
+CREATE TABLE "quoteOperationWorkInstruction" (
+ "quoteOperationId" TEXT NOT NULL,
+ "content" JSON DEFAULT '{"type": "doc","content": [{"type": "heading","attrs": {"level": 2},"content": [{"type": "text","text": "Work Instructions"}]},{"type": "paragraph"}]}'::json,
+ "companyId" TEXT NOT NULL,
+ "createdAt" TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
+ "createdBy" TEXT NOT NULL,
+ "updatedAt" TIMESTAMP WITH TIME ZONE,
+ "updatedBy" TEXT,
+
+ CONSTRAINT "quoteOperationWorkInstruction_pkey" PRIMARY KEY ("quoteOperationId"),
+ CONSTRAINT "quoteOperationWorkInstruction_quoteOperationId_fkey" FOREIGN KEY ("quoteOperationId") REFERENCES "quoteOperation" ("id") ON DELETE CASCADE,
+ CONSTRAINT "quoteOperationWorkInstruction_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE SET NULL,
+ CONSTRAINT "quoteOperationWorkInstruction_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user"("id") ON UPDATE CASCADE ON DELETE RESTRICT
+);
+
+CREATE FUNCTION public.create_quote_operation_work_instruction()
+RETURNS TRIGGER AS $$
+BEGIN
+ INSERT INTO public."quoteOperationWorkInstruction"("quoteOperationId", "createdBy", "companyId")
+ VALUES (new."id", new."createdBy", new."companyId");
+
+
+ RETURN new;
+END;
+$$ LANGUAGE plpgsql SECURITY DEFINER;
+
+CREATE TRIGGER create_quote_operation_related_records
+ AFTER INSERT on public."quoteOperation"
+ FOR EACH ROW EXECUTE PROCEDURE public.create_quote_operation_work_instruction();
+
+ALTER TABLE "quoteOperationWorkInstruction" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees can view quote work instructions" ON "quoteOperationWorkInstruction"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId") AND
+ "companyId" = ANY(
+ select "companyId" from "userToCompany" where "userId" = auth.uid()::text
+ )
+ );
+
+CREATE POLICY "Employees with sales_create can create quote work instructions" ON "quoteOperationWorkInstruction"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId") AND
+ has_company_permission('sales_create', "companyId")
+ );
+
+CREATE POLICY "Employees with sales_update can update quote work instructions" ON "quoteOperationWorkInstruction"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('sales_update', "companyId")
+ );
+
+CREATE POLICY "Employees with sales_delete can delete quote work instructions" ON "quoteOperationWorkInstruction"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId") AND
+ has_company_permission('sales_delete', "companyId")
+ );
\ No newline at end of file
diff --git a/packages/react/src/hooks/index.ts b/packages/react/src/hooks/index.ts
index 6e213757e8..7783205750 100644
--- a/packages/react/src/hooks/index.ts
+++ b/packages/react/src/hooks/index.ts
@@ -8,6 +8,7 @@ import useKeyboardShortcuts from "./useKeyboardShortcuts";
import useLocalStorage from "./useLocalStorage";
import useMount from "./useMount";
import useOutsideClick from "./useOutsideClick";
+import useThrottle from "./useThrottle";
import useWindowSize from "./useWindowSize";
export {
@@ -21,5 +22,6 @@ export {
useLocalStorage,
useMount,
useOutsideClick,
+ useThrottle,
useWindowSize,
};
diff --git a/packages/react/src/hooks/useThrottle.ts b/packages/react/src/hooks/useThrottle.ts
new file mode 100644
index 0000000000..1444fd7277
--- /dev/null
+++ b/packages/react/src/hooks/useThrottle.ts
@@ -0,0 +1,28 @@
+import { useRef } from "react";
+
+/**
+ * A function that you call with a throttle delay, the function will be called at most once per delay
+ *
+ * @param fn The function to throttle
+ * @param delay In ms
+ */
+export default function useThrottle<T extends (...args: any[]) => any>(
+ fn: T,
+ delay: number
+) {
+ const timeout = useRef<ReturnType<typeof setTimeout>>();
+ const lastArgs = useRef<Parameters<T>>();
+
+ return (...args: Parameters<T>) => {
+ lastArgs.current = args;
+
+ if (timeout.current) {
+ return;
+ }
+
+ timeout.current = setTimeout(() => {
+ fn(...lastArgs.current);
+ timeout.current = undefined;
+ }, delay);
+ };
+}