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 outside processing to suppliers and bill of processes

Brad Barbin2a5e250e1a12
diff --git a/apps/carbon/app/components/Assignee.tsx b/apps/carbon/app/components/Assignee.tsx
index 44d3cd9c21..13dc062198 100644
--- a/apps/carbon/app/components/Assignee.tsx
+++ b/apps/carbon/app/components/Assignee.tsx
@@ -84,7 +84,7 @@ const Assign = forwardRef<HTMLButtonElement, ComboboxProps>(
<PopoverTrigger asChild>
<button
className={cn(
- "rounded-md px-2.5 py-0.5 text-sm transition-colors cursor-pointer bg-background hover:bg-accent hover:text-accent-foreground border border-input",
+ "rounded-md px-2.5 py-0.5 text-sm transition-colors cursor-pointer bg-background hover:bg-accent hover:text-accent-foreground border border-input font-normal",
className
)}
role="combobox"
diff --git a/apps/carbon/app/components/CreateableMultiSelect.tsx b/apps/carbon/app/components/CreateableMultiSelect.tsx
index dce5384a0a..0649199d8a 100644
--- a/apps/carbon/app/components/CreateableMultiSelect.tsx
+++ b/apps/carbon/app/components/CreateableMultiSelect.tsx
@@ -91,9 +91,12 @@ const CreatableMultiSelect = forwardRef<
"bg-transparent px-2",
className
)}
- onClick={() => setOpen(!open)}
+ isDisabled={isReadOnly}
+ onClick={() => {
+ if (!isReadOnly) setOpen(!open);
+ }}
onKeyDown={(e) => {
- if (e.key === "Enter" || e.key === " ") {
+ if ((e.key === "Enter" || e.key === " ") && !isReadOnly) {
setOpen(!open);
}
}}
@@ -188,10 +191,12 @@ CreatableMultiSelect.displayName = "CreatableMultiSelect";
export default CreatableMultiSelect;
function SelectedOption({
+ isReadOnly,
item,
options,
onUnselect,
}: {
+ isReadOnly?: boolean;
item: string;
options: CreatableMultiSelectProps["options"];
onUnselect: (item: string) => void;
@@ -204,9 +209,10 @@ function SelectedOption({
{options.find((option) => option.value === item)?.label}
<BadgeCloseButton
tabIndex={-1}
+ disabled={isReadOnly}
style={{ color: colors.color }}
onKeyDown={(e) => {
- if (e.key === "Enter") {
+ if (e.key === "Enter" && !isReadOnly) {
onUnselect(item);
}
}}
@@ -217,7 +223,7 @@ function SelectedOption({
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
- onUnselect(item);
+ if (!isReadOnly) onUnselect(item);
}}
/>
</Badge>
diff --git a/apps/carbon/app/components/Form/Process.tsx b/apps/carbon/app/components/Form/Process.tsx
index 50af113be7..594641dede 100644
--- a/apps/carbon/app/components/Form/Process.tsx
+++ b/apps/carbon/app/components/Form/Process.tsx
@@ -38,7 +38,8 @@ const Process = (props: ProcessSelectProps) => {
}}
initialValues={{
name: created,
- defaultStandardFactor: "Minutes/Piece" as "Total Hours",
+ processType: "Inside",
+ defaultStandardFactor: "Minutes/Piece",
}}
/>
)}
diff --git a/apps/carbon/app/components/Form/Processes.tsx b/apps/carbon/app/components/Form/Processes.tsx
index 060ace4e00..8fdc1df751 100644
--- a/apps/carbon/app/components/Form/Processes.tsx
+++ b/apps/carbon/app/components/Form/Processes.tsx
@@ -38,7 +38,8 @@ const Processes = (props: ProcessSelectProps) => {
}}
initialValues={{
name: created,
- defaultStandardFactor: "Minutes/Piece" as "Total Hours",
+ defaultStandardFactor: "Minutes/Piece",
+ processType: "Inside",
workCenters: [],
}}
/>
diff --git a/apps/carbon/app/components/Form/SupplierProcess.tsx b/apps/carbon/app/components/Form/SupplierProcess.tsx
new file mode 100644
index 0000000000..0c3c123b5f
--- /dev/null
+++ b/apps/carbon/app/components/Form/SupplierProcess.tsx
@@ -0,0 +1,85 @@
+import { useDisclosure, useMount } from "@carbon/react";
+import { useFetcher } from "@remix-run/react";
+import { useMemo, useRef } from "react";
+import type { getSupplierProcessesByProcess } from "~/modules/purchasing";
+import { SupplierProcessForm } from "~/modules/purchasing";
+import { useSuppliers } from "~/stores";
+import { path } from "~/utils/path";
+import type { ComboboxProps } from "./Combobox";
+import CreatableCombobox from "./CreatableCombobox";
+
+type SupplierProcessSelectProps = Omit<ComboboxProps, "options"> & {
+ processId?: string;
+};
+
+const SupplierProcess = ({
+ processId,
+ ...props
+}: SupplierProcessSelectProps) => {
+ const newSupplierProcessModal = useDisclosure();
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ const [suppliers] = useSuppliers();
+ const options = useSupplierProcesses({
+ processId,
+ }).map((supplierProcess) => {
+ const supplier = suppliers.find(
+ (supplier) => supplier.id === supplierProcess.supplierId
+ );
+ return {
+ label: supplier?.name ?? "Unknown Supplier",
+ value: supplierProcess.id!,
+ };
+ });
+
+ return (
+ <>
+ <CreatableCombobox
+ ref={triggerRef}
+ options={options}
+ {...props}
+ label={props?.label ?? "Work Center"}
+ onCreateOption={(option) => {
+ newSupplierProcessModal.onOpen();
+ }}
+ />
+ {newSupplierProcessModal.isOpen && processId && (
+ <SupplierProcessForm
+ type="modal"
+ onClose={() => {
+ newSupplierProcessModal.onClose();
+ triggerRef.current?.click();
+ }}
+ initialValues={{
+ processId,
+ supplierId: "",
+ minimumCost: 0,
+ unitCost: 0,
+ leadTime: 0,
+ }}
+ />
+ )}
+ </>
+ );
+};
+
+SupplierProcess.displayName = "SupplierProcess";
+
+export default SupplierProcess;
+
+export const useSupplierProcesses = (args: { processId?: string }) => {
+ const { processId } = args;
+ const fetcher =
+ useFetcher<Awaited<ReturnType<typeof getSupplierProcessesByProcess>>>();
+
+ useMount(() => {
+ fetcher.load(path.to.api.supplierProcesses(processId));
+ });
+
+ const supplierProcesses = useMemo(
+ () => (fetcher.data?.data ? fetcher.data?.data : []),
+ [fetcher.data]
+ );
+
+ return supplierProcesses;
+};
diff --git a/apps/carbon/app/components/Form/Suppliers.tsx b/apps/carbon/app/components/Form/Suppliers.tsx
new file mode 100644
index 0000000000..5ccc5b516d
--- /dev/null
+++ b/apps/carbon/app/components/Form/Suppliers.tsx
@@ -0,0 +1,59 @@
+import { useDisclosure } from "@carbon/react";
+import { useMemo, useRef, useState } from "react";
+import { SupplierForm } from "~/modules/purchasing";
+import { useSuppliers } from "~/stores";
+import type { CreatableMultiSelectProps } from "./CreatableMultiSelect";
+import CreatableMultiSelect from "./CreatableMultiSelect";
+
+type SupplierSelectProps = Omit<CreatableMultiSelectProps, "options"> & {
+ processId?: string;
+};
+
+const Suppliers = (props: SupplierSelectProps) => {
+ const newSupplierModal = useDisclosure();
+
+ const [created, setCreated] = useState<string>("");
+ const triggerRef = useRef<HTMLButtonElement>(null);
+
+ const [suppliers] = useSuppliers();
+ const options = useMemo(() => {
+ return (
+ suppliers.map((c) => ({
+ value: c.id,
+ label: c.name,
+ })) ?? []
+ );
+ }, [suppliers]);
+
+ return (
+ <>
+ <CreatableMultiSelect
+ ref={triggerRef}
+ options={options}
+ {...props}
+ label={props?.label ?? "Work Center"}
+ onCreateOption={(option) => {
+ newSupplierModal.onOpen();
+ setCreated(option);
+ }}
+ />
+ {newSupplierModal.isOpen && (
+ <SupplierForm
+ type="modal"
+ onClose={() => {
+ setCreated("");
+ newSupplierModal.onClose();
+ triggerRef.current?.click();
+ }}
+ initialValues={{
+ name: created,
+ }}
+ />
+ )}
+ </>
+ );
+};
+
+Suppliers.displayName = "Supplier";
+
+export default Suppliers;
diff --git a/apps/carbon/app/components/Form/WorkCenter.tsx b/apps/carbon/app/components/Form/WorkCenter.tsx
index c3ff2de47e..5cbc2fd275 100644
--- a/apps/carbon/app/components/Form/WorkCenter.tsx
+++ b/apps/carbon/app/components/Form/WorkCenter.tsx
@@ -47,7 +47,7 @@ const WorkCenter = (props: WorkCenterSelectProps) => {
initialValues={{
name: created,
description: "",
- quotingRate: 0,
+ overheadRate: 0,
laborRate: 0,
locationId: props?.locationId ?? defaults?.locationId ?? "",
processes: props?.processId ? [props.processId] : [],
diff --git a/apps/carbon/app/components/Form/WorkCenters.tsx b/apps/carbon/app/components/Form/WorkCenters.tsx
index 6251ca2be5..a93c943786 100644
--- a/apps/carbon/app/components/Form/WorkCenters.tsx
+++ b/apps/carbon/app/components/Form/WorkCenters.tsx
@@ -44,7 +44,7 @@ const WorkCenters = (props: WorkCenterSelectProps) => {
initialValues={{
name: created,
description: "",
- quotingRate: 0,
+ overheadRate: 0,
laborRate: 0,
locationId: defaults?.locationId ?? "",
processes: props?.processId ? [props.processId] : [],
diff --git a/apps/carbon/app/components/Form/index.ts b/apps/carbon/app/components/Form/index.ts
index 49d8193db7..65a85612a9 100644
--- a/apps/carbon/app/components/Form/index.ts
+++ b/apps/carbon/app/components/Form/index.ts
@@ -48,8 +48,10 @@ import Submit from "./Submit";
import Supplier from "./Supplier";
import SupplierContact from "./SupplierContact";
import SupplierLocation from "./SupplierLocation";
+import SupplierProcess from "./SupplierProcess";
import SupplierStatus from "./SupplierStatus";
import SupplierType from "./SupplierType";
+import Suppliers from "./Suppliers";
import TextArea from "./Textarea";
import TimePicker from "./TimePicker";
import Timezone from "./Timezone";
@@ -112,6 +114,8 @@ export {
Supplier,
SupplierContact,
SupplierLocation,
+ SupplierProcess,
+ Suppliers,
SupplierStatus,
SupplierType,
TextArea,
diff --git a/apps/carbon/app/modules/items/items.models.ts b/apps/carbon/app/modules/items/items.models.ts
index e2bcb49181..66953b89ad 100644
--- a/apps/carbon/app/modules/items/items.models.ts
+++ b/apps/carbon/app/modules/items/items.models.ts
@@ -245,33 +245,8 @@ export const methodOperationValidator = z
})
.optional(),
machineTime: zfd.numeric(z.number().min(0).optional()),
- operationCost: zfd.numeric(z.number().min(0).optional()),
- operationLeadTime: zfd.numeric(z.number().min(0).optional()),
+ operationSupplierProcessId: zfd.text(z.string().optional()),
})
- .refine(
- (data) => {
- if (data.operationType === "Outside") {
- return Number.isFinite(data.operationCost);
- }
- return true;
- },
- {
- message: "Operation cost is required",
- path: ["operationCost"],
- }
- )
- .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") {
diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
index c6f9d9f252..dea7100ee1 100644
--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx
@@ -28,14 +28,15 @@ import { LuSettings2, LuX } from "react-icons/lu";
import type { z } from "zod";
import { DirectionAwareTabs } from "~/components/DirectionAwareTabs";
import {
- Combobox,
Hidden,
InputControlled,
Number,
Process,
Select,
+ SelectControlled,
StandardFactor,
Submit,
+ SupplierProcess,
UnitHint,
WorkCenter,
getUnitHint,
@@ -104,20 +105,18 @@ function makeItem(operation: Operation): ItemWithData {
};
}
-const initialMethodOperation: Omit<Operation, "makeMethodId" | "order"> = {
+const initialOperation: Omit<Operation, "makeMethodId" | "order"> = {
description: "",
- processId: "",
- workCenterId: "",
- setupTime: 0,
- setupUnit: "Total Minutes",
laborTime: 0,
laborUnit: "Minutes/Piece",
machineTime: 0,
machineUnit: "Minutes/Piece",
operationOrder: "After Previous",
operationType: "Inside",
- operationCost: 0,
- operationLeadTime: 0,
+ processId: "",
+ setupTime: 0,
+ setupUnit: "Total Minutes",
+ workCenterId: "",
methodOperationWorkInstruction: {
content: {},
},
@@ -163,7 +162,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {
checked: false,
id: temporaryId,
data: {
- ...initialMethodOperation,
+ ...initialOperation,
order: newOrder,
makeMethodId,
},
@@ -544,25 +543,25 @@ function OperationForm({
}, [item.id, methodOperationFetcher.data, setItems, setSelectedItemId]);
const [processData, setProcessData] = useState<{
- processId: string;
- operationType: string;
description: string;
- setupUnitHint: string;
- setupUnit: string;
- laborUnitHint: string;
laborUnit: string;
- machineUnitHint: string;
+ laborUnitHint: string;
machineUnit: string;
+ machineUnitHint: string;
+ operationType: string;
+ processId: string;
+ setupUnit: string;
+ setupUnitHint: string;
}>({
- processId: item.data.processId ?? "",
- operationType: item.data.operationType ?? "Inside",
description: item.data.description ?? "",
- 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),
+ laborUnitHint: getUnitHint(item.data.laborUnit),
machineUnit: item.data.machineUnit ?? "Hours/Piece",
+ machineUnitHint: getUnitHint(item.data.machineUnit),
+ operationType: item.data.operationType ?? "Inside",
+ processId: item.data.processId ?? "",
+ setupUnit: item.data.setupUnit ?? "Total Minutes",
+ setupUnitHint: getUnitHint(item.data.setupUnit),
});
const onProcessChange = async (processId: string) => {
@@ -583,6 +582,7 @@ function OperationForm({
laborUnitHint: getUnitHint(data?.defaultStandardFactor),
machineUnit: data?.defaultStandardFactor ?? "Hours/Piece",
machineUnitHint: getUnitHint(data?.defaultStandardFactor),
+ operationType: data?.processType === "Outside" ? "Outside" : "Inside",
}));
};
@@ -654,9 +654,15 @@ function OperationForm({
value: o,
label: o,
}))}
+ onChange={(value) => {
+ setProcessData((d) => ({
+ ...d,
+ operationOrder: value?.value as string,
+ }));
+ }}
/>
- <Select
+ <SelectControlled
name="operationType"
label="Operation Type"
placeholder="Operation Type"
@@ -664,6 +670,7 @@ function OperationForm({
value: o,
label: o,
}))}
+ value={processData.operationType}
onChange={(value) => {
setProcessData((d) => ({
...d,
@@ -688,22 +695,12 @@ function OperationForm({
{processData.operationType === "Outside" ? (
<>
- <Combobox
- isOptional
- name="operationSupplierId"
+ <SupplierProcess
+ name="operationSupplierProcessId"
label="Supplier"
- options={[]}
- />
- <Number
- name="operationCost"
- label="Cost per Unit"
- minValue={0}
- formatOptions={{
- style: "currency",
- currency: "USD",
- }}
+ processId={processData.processId}
+ isOptional
/>
- <Number name="operationLeadTime" label="Lead Time" minValue={0} />
</>
) : (
<>
diff --git a/apps/carbon/app/modules/purchasing/purchasing.models.ts b/apps/carbon/app/modules/purchasing/purchasing.models.ts
index 9da62ae753..842cdf2916 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.models.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.models.ts
@@ -196,6 +196,15 @@ export const supplierPaymentValidator = z.object({
currencyCode: zfd.text(z.string().optional()),
});
+export const supplierProcessValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ supplierId: z.string().min(36, { message: "Supplier is required" }),
+ processId: z.string().min(1, { message: "Process is required" }),
+ minimumCost: zfd.numeric(z.number().min(0)),
+ unitCost: zfd.numeric(z.number().min(0)),
+ leadTime: zfd.numeric(z.number().min(0)),
+});
+
export const supplierShippingValidator = z.object({
supplierId: z.string().min(36, { message: "Supplier is required" }),
shippingSupplierId: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/purchasing/purchasing.service.ts b/apps/carbon/app/modules/purchasing/purchasing.service.ts
index 1d25d80a14..0bc50ef8dc 100644
--- a/apps/carbon/app/modules/purchasing/purchasing.service.ts
+++ b/apps/carbon/app/modules/purchasing/purchasing.service.ts
@@ -14,6 +14,7 @@ import type {
supplierAccountingValidator,
supplierContactValidator,
supplierPaymentValidator,
+ supplierProcessValidator,
supplierShippingValidator,
supplierStatusValidator,
supplierTypeValidator,
@@ -78,6 +79,17 @@ export async function deleteSupplierLocation(
.eq("id", supplierLocationId);
}
+export async function deleteSupplierProcess(
+ client: SupabaseClient<Database>,
+ supplierProcessId: string
+) {
+ return client
+ .from("supplierProcess")
+ .delete()
+ .eq("id", supplierProcessId)
+ .single();
+}
+
export async function deleteSupplierStatus(
client: SupabaseClient<Database>,
supplierStatusId: string
@@ -289,6 +301,26 @@ export async function getSupplierPayment(
.single();
}
+export async function getSupplierProcessesByProcess(
+ client: SupabaseClient<Database>,
+ processId: string
+) {
+ return client
+ .from("supplierProcesses")
+ .select("*")
+ .eq("processId", processId);
+}
+
+export async function getSupplierProcessesBySupplier(
+ client: SupabaseClient<Database>,
+ supplierId: string
+) {
+ return client
+ .from("supplierProcesses")
+ .select("*")
+ .eq("supplierId", supplierId);
+}
+
export async function getSupplierShipping(
client: SupabaseClient<Database>,
supplierId: string
@@ -599,6 +631,35 @@ export async function upsertSupplier(
.single();
}
+export async function upsertSupplierProcess(
+ client: SupabaseClient<Database>,
+ supplierProcess:
+ | (Omit<z.infer<typeof supplierProcessValidator>, "id"> & {
+ companyId: string;
+ createdBy: string;
+ customFields?: Json;
+ })
+ | (Omit<z.infer<typeof supplierProcessValidator>, "id"> & {
+ id: string;
+ updatedBy: string;
+ customFields?: Json;
+ })
+) {
+ if ("createdBy" in supplierProcess) {
+ return client
+ .from("supplierProcess")
+ .insert([supplierProcess])
+ .select("id")
+ .single();
+ }
+ return client
+ .from("supplierProcess")
+ .update(sanitize(supplierProcess))
+ .eq("id", supplierProcess.id)
+ .select("id")
+ .single();
+}
+
export async function updateSupplierAccounting(
client: SupabaseClient<Database>,
supplierAccounting: z.infer<typeof supplierAccountingValidator> & {
diff --git a/apps/carbon/app/modules/purchasing/types.ts b/apps/carbon/app/modules/purchasing/types.ts
index a8e05f6b07..b4cedc14ed 100644
--- a/apps/carbon/app/modules/purchasing/types.ts
+++ b/apps/carbon/app/modules/purchasing/types.ts
@@ -6,6 +6,7 @@ import type {
getSupplier,
getSupplierContacts,
getSupplierLocations,
+ getSupplierProcessesBySupplier,
getSuppliers,
getSupplierStatuses,
getSupplierTypes,
@@ -52,6 +53,10 @@ export type SupplierLocation = NonNullable<
Awaited<ReturnType<typeof getSupplierLocations>>["data"]
>[number];
+export type SupplierProcess = NonNullable<
+ Awaited<ReturnType<typeof getSupplierProcessesBySupplier>>["data"]
+>[number];
+
export type SupplierStatus = NonNullable<
Awaited<ReturnType<typeof getSupplierStatuses>>["data"]
>[number];
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
index 93d2da4dfd..52e08c28ef 100644
--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierForm.tsx
@@ -61,58 +61,64 @@ const SupplierForm = ({
: !permissions.can("create", "purchasing");
return (
- <ModalCardProvider type={type}>
- <ModalCard onClose={onClose}>
- <ModalCardContent>
- <ValidatedForm
- method="post"
- action={isEditing ? undefined : path.to.newSupplier}
- validator={supplierValidator}
- defaultValues={initialValues}
- fetcher={fetcher}
- >
- <ModalCardHeader>
- <ModalCardTitle>
- {isEditing ? "Supplier Overview" : "New Supplier"}
- </ModalCardTitle>
- {!isEditing && (
- <ModalCardDescription>
- A supplier is a business or person who sells you parts or
- services.
- </ModalCardDescription>
- )}
- </ModalCardHeader>
- <ModalCardBody>
- <Hidden name="id" />
- <Hidden name="type" value={type} />
- <div
- className={cn(
- "grid w-full gap-x-8 gap-y-4",
- isEditing ? "grid-cols-1 lg:grid-cols-3" : "grid-cols-2"
+ <div>
+ <ModalCardProvider type={type}>
+ <ModalCard onClose={onClose}>
+ <ModalCardContent>
+ <ValidatedForm
+ method="post"
+ action={isEditing ? undefined : path.to.newSupplier}
+ validator={supplierValidator}
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ >
+ <ModalCardHeader>
+ <ModalCardTitle>
+ {isEditing ? "Supplier Overview" : "New Supplier"}
+ </ModalCardTitle>
+ {!isEditing && (
+ <ModalCardDescription>
+ A supplier is a business or person who sells you parts or
+ services.
+ </ModalCardDescription>
)}
- >
- <Input autoFocus={!isEditing} name="name" label="Name" />
+ </ModalCardHeader>
+ <ModalCardBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <div
+ className={cn(
+ "grid w-full gap-x-8 gap-y-4",
+ type === "modal"
+ ? "grid-cols-1"
+ : isEditing
+ ? "grid-cols-1 lg:grid-cols-3"
+ : "grid-cols-2"
+ )}
+ >
+ <Input autoFocus={!isEditing} name="name" label="Name" />
- <SupplierStatus
- name="supplierStatusId"
- label="Supplier Status"
- placeholder="Select Supplier Status"
- />
+ <SupplierStatus
+ name="supplierStatusId"
+ label="Supplier Status"
+ placeholder="Select Supplier Status"
+ />
- <Employee name="accountManagerId" label="Account Manager" />
+ <Employee name="accountManagerId" label="Account Manager" />
- <CustomFormFields table="supplier" />
- </div>
- </ModalCardBody>
- <ModalCardFooter>
- <HStack>
- <Submit isDisabled={isDisabled}>Save</Submit>
- </HStack>
- </ModalCardFooter>
- </ValidatedForm>
- </ModalCardContent>
- </ModalCard>
- </ModalCardProvider>
+ <CustomFormFields table="supplier" />
+ </div>
+ </ModalCardBody>
+ <ModalCardFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ </HStack>
+ </ModalCardFooter>
+ </ValidatedForm>
+ </ModalCardContent>
+ </ModalCard>
+ </ModalCardProvider>
+ </div>
);
};
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcessForm.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcessForm.tsx
new file mode 100644
index 0000000000..c8e554cac7
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcessForm.tsx
@@ -0,0 +1,144 @@
+import {
+ Button,
+ HStack,
+ ModalDrawer,
+ ModalDrawerBody,
+ ModalDrawerContent,
+ ModalDrawerFooter,
+ ModalDrawerHeader,
+ ModalDrawerProvider,
+ ModalDrawerTitle,
+ toast,
+ VStack,
+} from "@carbon/react";
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useFetcher, useParams } from "@remix-run/react";
+import type { PostgrestResponse } from "@supabase/supabase-js";
+import { useEffect, useState } from "react";
+import type { z } from "zod";
+import {
+ CustomFormFields,
+ Hidden,
+ Number,
+ Process,
+ Submit,
+ Supplier,
+} from "~/components/Form";
+import { usePermissions } from "~/hooks";
+import type { SupplierProcess } from "~/modules/purchasing";
+import { supplierProcessValidator } from "~/modules/purchasing";
+import { path } from "~/utils/path";
+
+type SupplierProcessFormProps = {
+ initialValues: z.infer<typeof supplierProcessValidator>;
+ type?: "drawer" | "modal";
+ open?: boolean;
+ onClose?: () => void;
+};
+
+const SupplierProcessForm = ({
+ initialValues,
+ type = "drawer",
+ open = true,
+ onClose,
+}: SupplierProcessFormProps) => {
+ const permissions = usePermissions();
+ const fetcher = useFetcher<PostgrestResponse<SupplierProcess>>();
+ const { supplierId } = useParams();
+ const [supplier, setSupplier] = useState<string | undefined>(supplierId);
+
+ useEffect(() => {
+ if (type !== "modal") return;
+
+ if (fetcher.state === "loading" && fetcher.data?.data) {
+ onClose?.();
+ // @ts-ignore
+ toast.success(`Created supplier process`);
+ } else if (fetcher.state === "idle" && fetcher.data?.error) {
+ toast.error(`Failed to create supplier process`);
+ }
+ }, [fetcher.data, fetcher.state, onClose, type]);
+
+ const isEditing = initialValues.id !== undefined;
+ const isDisabled = isEditing
+ ? !permissions.can("update", "purchasing")
+ : !permissions.can("create", "purchasing");
+
+ return (
+ <ModalDrawerProvider type={type}>
+ <ModalDrawer
+ open={open}
+ onOpenChange={(isOpen) => {
+ if (!isOpen) onClose?.();
+ }}
+ >
+ <ModalDrawerContent>
+ <ValidatedForm
+ validator={supplierProcessValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.supplierProcess(supplier!, initialValues.id!)
+ : path.to.newSupplierProcess(supplier!)
+ }
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ className="flex flex-col h-full"
+ >
+ <ModalDrawerHeader>
+ <ModalDrawerTitle>
+ {isEditing ? "Edit" : "New"} Supplier Process
+ </ModalDrawerTitle>
+ </ModalDrawerHeader>
+ <ModalDrawerBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ {supplierId && <Hidden name="supplierId" value={supplierId} />}
+ <VStack spacing={4}>
+ {supplierId === undefined && (
+ <Supplier
+ name="supplierId"
+ label="Supplier"
+ onChange={(newValue) => setSupplier(newValue?.value)}
+ />
+ )}
+ <Process name="processId" label="Process" />
+ <Number
+ name="minimumCost"
+ label="Minimum Cost"
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ minValue={0}
+ />
+ <Number
+ name="unitCost"
+ label="Unit Cost"
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ minValue={0}
+ />
+ <Number name="leadTime" label="Lead Time" minValue={0} />
+
+ <CustomFormFields table="supplierProcess" />
+ </VStack>
+ </ModalDrawerBody>
+ <ModalDrawerFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ <Button size="md" variant="solid" onClick={() => onClose?.()}>
+ Cancel
+ </Button>
+ </HStack>
+ </ModalDrawerFooter>
+ </ValidatedForm>
+ </ModalDrawerContent>
+ </ModalDrawer>
+ </ModalDrawerProvider>
+ );
+};
+
+export default SupplierProcessForm;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx
new file mode 100644
index 0000000000..96b430107f
--- /dev/null
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierProcesses.tsx
@@ -0,0 +1,179 @@
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+} from "@carbon/react";
+import { useLocale } from "@react-aria/i18n";
+import { Outlet, useNavigate, useParams } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useCallback, useMemo } from "react";
+import { LuPencil, LuTrash } from "react-icons/lu";
+import { MdMoreHoriz } from "react-icons/md";
+import { New } from "~/components";
+import { EditableNumber } from "~/components/Editable";
+import Grid from "~/components/Grid";
+import { usePermissions, useUser } from "~/hooks";
+import { useCustomColumns } from "~/hooks/useCustomColumns";
+import { useSupabase } from "~/lib/supabase";
+import type { SupplierProcess } from "~/modules/purchasing";
+import { path } from "~/utils/path";
+
+type SupplierProccessesProps = {
+ processes: SupplierProcess[];
+};
+
+const SupplierProccesses = ({ processes }: SupplierProccessesProps) => {
+ const { supplierId } = useParams();
+ if (!supplierId) throw new Error("supplierId not found");
+ const { id: userId } = useUser();
+
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+
+ const canEdit = permissions.can("update", "purchasing");
+ const canDelete = permissions.can("delete", "purchasing");
+ const { supabase } = useSupabase();
+
+ const onCellEdit = useCallback(
+ async (id: string, value: unknown, row: SupplierProcess) => {
+ if (!supabase) throw new Error("Supabase client not found");
+ return await supabase
+ .from("supplierProcess")
+ .update({
+ [id]: value,
+ updatedBy: userId,
+ })
+ .eq("id", row.id!);
+ },
+ [supabase, userId]
+ );
+
+ const customColumns = useCustomColumns<SupplierProcess>("supplierProcess");
+
+ // TODO: factor in default currency or quote currency
+ const { locale } = useLocale();
+ const formatter = useMemo(
+ () => new Intl.NumberFormat(locale, { style: "currency", currency: "USD" }),
+ [locale]
+ );
+
+ const columns = useMemo<ColumnDef<SupplierProcess>[]>(() => {
+ const defaultColumns: ColumnDef<SupplierProcess>[] = [
+ {
+ accessorKey: "proccessName",
+ header: "Process",
+ cell: ({ row }) => (
+ <HStack className="justify-between min-w-[100px]">
+ <span>{row.original.processName}</span>
+ <div className="relative w-6 h-5">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Edit supplier process"
+ icon={<MdMoreHoriz />}
+ size="md"
+ className="absolute right-[-1px] top-[-6px]"
+ variant="ghost"
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ onClick={() =>
+ navigate(
+ path.to.supplierProcess(supplierId, row.original.id!)
+ )
+ }
+ disabled={!canEdit}
+ >
+ <DropdownMenuIcon icon={<LuPencil />} />
+ Edit Process
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ navigate(
+ path.to.deleteSupplierProcess(
+ supplierId,
+ row.original.id!
+ )
+ )
+ }
+ disabled={!canDelete}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Process
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </HStack>
+ ),
+ },
+
+ {
+ accessorKey: "minimumCost",
+ header: "Minimum Cost",
+ cell: ({ row }) => formatter.format(row.original.minimumCost ?? 0),
+ },
+ {
+ accessorKey: "unitCost",
+ header: "Unit Cost",
+ cell: ({ row }) => formatter.format(row.original.unitCost ?? 0),
+ },
+ {
+ accessorKey: "leadTime",
+ header: "Lead Time",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ return [...defaultColumns, ...customColumns];
+ }, [customColumns, canEdit, canDelete, navigate, supplierId, formatter]);
+
+ const editableComponents = useMemo(
+ () => ({
+ minimumCost: EditableNumber(onCellEdit, {
+ formatOptions: { style: "currency", currency: "USD" },
+ }),
+ unitCost: EditableNumber(onCellEdit, {
+ formatOptions: { style: "currency", currency: "USD" },
+ }),
+ leadTime: EditableNumber(onCellEdit),
+ }),
+ [onCellEdit]
+ );
+
+ return (
+ <>
+ <Card className="w-full h-full min-h-[50vh]">
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Supplier Processes</CardTitle>
+ </CardHeader>
+ <CardAction>{canEdit && <New to="new" />}</CardAction>
+ </HStack>
+
+ <CardContent>
+ <Grid<SupplierProcess>
+ data={processes ?? []}
+ columns={columns}
+ canEdit={canEdit}
+ editableComponents={editableComponents}
+ onNewRow={canEdit ? () => navigate("new") : undefined}
+ />
+ </CardContent>
+ </Card>
+ <Outlet />
+ </>
+ );
+};
+
+export default SupplierProccesses;
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx
index cc78f11869..9b9e2c2cc5 100644
--- a/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/SupplierSidebar/useSupplierSidebar.tsx
@@ -7,6 +7,7 @@ import {
LuMapPin,
LuTruck,
} from "react-icons/lu";
+import { TbRoute } from "react-icons/tb";
import { usePermissions } from "~/hooks";
import type { Role } from "~/types";
import { path } from "~/utils/path";
@@ -51,6 +52,13 @@ export function useSupplierSidebar({ contacts, locations }: Props) {
icon: LuCreditCard,
shortcut: "Command+Shift+p",
},
+ {
+ name: "Processes",
+ to: path.to.supplierProcesses(supplierId),
+ role: ["employee"],
+ icon: TbRoute,
+ shortcut: "Command+Shift+r",
+ },
{
name: "Shipping",
to: path.to.supplierShipping(supplierId),
diff --git a/apps/carbon/app/modules/purchasing/ui/Supplier/index.ts b/apps/carbon/app/modules/purchasing/ui/Supplier/index.ts
index 7e651241e0..af856c2239 100644
--- a/apps/carbon/app/modules/purchasing/ui/Supplier/index.ts
+++ b/apps/carbon/app/modules/purchasing/ui/Supplier/index.ts
@@ -5,6 +5,8 @@ import SupplierHeader from "./SupplierHeader";
import SupplierLocationForm from "./SupplierLocationForm";
import SupplierLocations from "./SupplierLocations";
import SupplierPaymentForm from "./SupplierPaymentForm";
+import SupplierProcessForm from "./SupplierProcessForm";
+import SupplierProcesses from "./SupplierProcesses";
import SupplierShippingForm from "./SupplierShippingForm";
import SupplierSidebar from "./SupplierSidebar";
@@ -16,6 +18,8 @@ export {
SupplierLocationForm,
SupplierLocations,
SupplierPaymentForm,
+ SupplierProcessForm,
+ SupplierProcesses,
SupplierShippingForm,
SupplierSidebar,
};
diff --git a/apps/carbon/app/modules/resources/resources.models.ts b/apps/carbon/app/modules/resources/resources.models.ts
index 8c1e161fa0..76f26244d9 100644
--- a/apps/carbon/app/modules/resources/resources.models.ts
+++ b/apps/carbon/app/modules/resources/resources.models.ts
@@ -1,19 +1,6 @@
import { z } from "zod";
import { zfd } from "zod-form-data";
-
-export const standardFactorType = [
- "Hours/Piece",
- "Hours/100 Pieces",
- "Hours/1000 Pieces",
- "Minutes/Piece",
- "Minutes/100 Pieces",
- "Minutes/1000 Pieces",
- "Pieces/Hour",
- "Pieces/Minute",
- "Seconds/Piece",
- "Total Hours",
- "Total Minutes",
-] as const;
+import { processTypes, standardFactorType } from "../shared";
export const abilityValidator = z
.object({
@@ -99,16 +86,34 @@ export const partnerValidator = z.object({
abilityId: z.string().min(20, { message: "Invalid ability" }),
});
-export const processValidator = z.object({
- id: zfd.text(z.string().optional()),
- name: z.string().min(1, { message: "Process name is required" }),
- defaultStandardFactor: z.enum(standardFactorType, {
- errorMap: () => ({ message: "Standard factor is required" }),
- }),
- workCenters: z
- .array(z.string().min(20, { message: "Invalid work center" }))
- .optional(),
-});
+export const processValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ name: z.string().min(1, { message: "Process name is required" }),
+ processType: z.enum(processTypes, {
+ errorMap: () => ({ message: "Process type is required" }),
+ }),
+ defaultStandardFactor: z
+ .enum(standardFactorType, {
+ errorMap: () => ({ message: "Standard factor is required" }),
+ })
+ .optional(),
+ workCenters: z
+ .array(z.string().min(20, { message: "Invalid work center" }))
+ .optional(),
+ })
+ .refine((data) => {
+ if (data.processType !== "Outside" && !data.workCenters) {
+ return { workCenters: ["Work center is required for inside process"] };
+ }
+ return true;
+ })
+ .refine((data) => {
+ if (data.processType !== "Outside" && !data.defaultStandardFactor) {
+ return { defaultStandardFactor: ["Standard factor is required"] };
+ }
+ return true;
+ });
export const workCenterValidator = z.object({
id: zfd.text(z.string().optional()),
@@ -119,9 +124,9 @@ export const workCenterValidator = z.object({
}),
laborRate: zfd.numeric(z.number().min(0)),
locationId: z.string().min(20, { message: "Location is required" }),
+ overheadRate: zfd.numeric(z.number().min(0)),
processes: z
.array(z.string().min(20, { message: "Invalid process" }))
.optional(),
- quotingRate: zfd.numeric(z.number().min(0)),
requiredAbilityId: zfd.text(z.string().optional()),
});
diff --git a/apps/carbon/app/modules/resources/resources.service.ts b/apps/carbon/app/modules/resources/resources.service.ts
index 442a20468f..ce1eb481d3 100644
--- a/apps/carbon/app/modules/resources/resources.service.ts
+++ b/apps/carbon/app/modules/resources/resources.service.ts
@@ -559,7 +559,13 @@ export async function upsertProcess(
const { workCenters, ...insert } = process;
const processInsert = await client
.from("process")
- .insert([insert])
+ .insert([
+ {
+ ...insert,
+ defaultStandardFactor:
+ insert.defaultStandardFactor ?? "Minutes/Piece",
+ },
+ ])
.select("id")
.single();
if (processInsert.error) {
diff --git a/apps/carbon/app/modules/resources/ui/Abilities/AbilitiesTable.tsx b/apps/carbon/app/modules/resources/ui/Abilities/AbilitiesTable.tsx
index 7d93dfea8b..f08ad848cb 100644
--- a/apps/carbon/app/modules/resources/ui/Abilities/AbilitiesTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/Abilities/AbilitiesTable.tsx
@@ -81,6 +81,7 @@ const AbilitiesTable = memo(({ data, count }: AbilitiesTableProps) => {
cell: ({ row }) => (
<AvatarGroup limit={5}>
<AvatarGroupList>
+ {/* @ts-ignore */}
{row.original.employees.map((employee, index: number) => (
<Avatar
key={index}
diff --git a/apps/carbon/app/modules/resources/ui/Processes/ProcessForm.tsx b/apps/carbon/app/modules/resources/ui/Processes/ProcessForm.tsx
index cfcd282bd8..49cdb10f53 100644
--- a/apps/carbon/app/modules/resources/ui/Processes/ProcessForm.tsx
+++ b/apps/carbon/app/modules/resources/ui/Processes/ProcessForm.tsx
@@ -1,6 +1,12 @@
import {
Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
HStack,
+ IconButton,
ModalDrawer,
ModalDrawerBody,
ModalDrawerContent,
@@ -10,22 +16,30 @@ import {
ModalDrawerTitle,
VStack,
toast,
+ useDisclosure,
} from "@carbon/react";
import { ValidatedForm } from "@carbon/remix-validated-form";
-import { useFetcher } from "@remix-run/react";
+import { useFetcher, useNavigate } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
-import { useEffect } from "react";
+import { useEffect, useState } from "react";
+import { LuPencil, LuPlus, LuTrash } from "react-icons/lu";
+import { MdMoreHoriz } from "react-icons/md";
import type { z } from "zod";
+import { SupplierAvatar } from "~/components";
import {
CustomFormFields,
Hidden,
Input,
+ Select,
StandardFactor,
Submit,
} from "~/components/Form";
+import { useSupplierProcesses } from "~/components/Form/SupplierProcess";
import WorkCenters from "~/components/Form/WorkCenters";
import { usePermissions } from "~/hooks";
+import { SupplierProcessForm } from "~/modules/purchasing";
import { processValidator } from "~/modules/resources";
+import { processTypes } from "~/modules/shared";
import { path } from "~/utils/path";
type ProcessFormProps = {
@@ -60,6 +74,8 @@ const ProcessForm = ({
? !permissions.can("update", "resources")
: !permissions.can("create", "resources");
+ const [processType, setProcessType] = useState(initialValues.processType);
+
return (
<ModalDrawerProvider type={type}>
<ModalDrawer
@@ -91,12 +107,32 @@ const ProcessForm = ({
<Hidden name="type" value={type} />
<VStack spacing={4}>
<Input name="name" label="Process Name" />
- <StandardFactor
- name="defaultStandardFactor"
- label="Default Unit"
- value={initialValues.defaultStandardFactor}
+ <Select
+ name="processType"
+ label="Process Type"
+ options={processTypes.map((pt) => ({
+ value: pt,
+ label: pt,
+ }))}
+ onChange={(newValue) => {
+ setProcessType(
+ newValue?.value as (typeof processTypes)[number]
+ );
+ }}
/>
- <WorkCenters name="workCenters" label="Work Centers" />
+ {processType !== "Outside" && (
+ <>
+ <StandardFactor
+ name="defaultStandardFactor"
+ label="Default Unit"
+ value={initialValues.defaultStandardFactor}
+ />
+ <WorkCenters name="workCenters" label="Work Centers" />
+ </>
+ )}
+ {processType !== "Inside" && (
+ <SupplierProcesses processId={initialValues.id} />
+ )}
<CustomFormFields table="process" />
</VStack>
</ModalDrawerBody>
@@ -116,3 +152,89 @@ const ProcessForm = ({
};
export default ProcessForm;
+
+function SupplierProcesses({ processId }: { processId?: string }) {
+ const permissions = usePermissions();
+ const processes = useSupplierProcesses({ processId });
+ const navigate = useNavigate();
+ const isEditing = processId !== undefined;
+ const newSupplierProcessModal = useDisclosure();
+
+ return (
+ <>
+ <div className="flex flex-col gap-2 w-full">
+ {processes.length > 0 && (
+ <>
+ <label className="text-muted-foreground text-xs">Suppliers</label>
+ {processes.map((sp) => (
+ <HStack
+ key={sp.id}
+ className="w-full justify-between rounded-md border border-border p-2"
+ >
+ <SupplierAvatar supplierId={sp.supplierId} />
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Edit supplier process"
+ icon={<MdMoreHoriz />}
+ size="md"
+ variant="ghost"
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ onClick={() =>
+ navigate(
+ path.to.supplierProcess(sp.supplierId!, sp.id!)
+ )
+ }
+ disabled={!permissions.can("update", "purchasing")}
+ >
+ <DropdownMenuIcon icon={<LuPencil />} />
+ Edit Process
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() =>
+ navigate(
+ path.to.deleteSupplierProcess(sp.supplierId!, sp.id!)
+ )
+ }
+ disabled={!permissions.can("delete", "purchasing")}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Process
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </HStack>
+ ))}
+ </>
+ )}
+ <Button
+ isDisabled={!isEditing}
+ leftIcon={<LuPlus />}
+ variant="secondary"
+ onClick={newSupplierProcessModal.onOpen}
+ >
+ Add Supplier
+ </Button>
+ </div>
+ {newSupplierProcessModal.isOpen && processId && (
+ <SupplierProcessForm
+ type="modal"
+ onClose={() => {
+ newSupplierProcessModal.onClose();
+ }}
+ initialValues={{
+ processId: processId,
+ supplierId: "",
+ minimumCost: 0,
+ unitCost: 0,
+ leadTime: 0,
+ }}
+ />
+ )}
+ </>
+ );
+}
diff --git a/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
index 3888b60f13..848ce3b843 100644
--- a/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
+++ b/apps/carbon/app/modules/resources/ui/Processes/ProcessesTable.tsx
@@ -1,4 +1,13 @@
-import { Enumerable, MenuIcon, MenuItem } from "@carbon/react";
+import {
+ Avatar,
+ AvatarGroup,
+ AvatarGroupList,
+ AvatarOverflowIndicator,
+ Badge,
+ Enumerable,
+ MenuIcon,
+ MenuItem,
+} from "@carbon/react";
import { useNavigate } from "@remix-run/react";
import type { ColumnDef } from "@tanstack/react-table";
import { memo, useCallback, useMemo } from "react";
@@ -6,7 +15,8 @@ import { LuPencil, LuTrash } from "react-icons/lu";
import { EmployeeAvatar, New, Table } from "~/components";
import { usePermissions, useUrlParams } from "~/hooks";
import { useCustomColumns } from "~/hooks/useCustomColumns";
-import { standardFactorType, type Process } from "~/modules/resources";
+import { type Process } from "~/modules/resources";
+import { standardFactorType } from "~/modules/shared";
import { usePeople } from "~/stores";
import { path } from "~/utils/path";
@@ -42,6 +52,16 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {
/>
),
},
+ {
+ accessorKey: "processType",
+ header: "Process Type",
+ cell: (item) =>
+ item.getValue() === "Outside" ? (
+ <Enumerable value={item.getValue<string>()} />
+ ) : (
+ <Badge variant="secondary">{item.getValue<string>()}</Badge>
+ ),
+ },
{
id: "workCenters",
header: "Work Centers",
@@ -69,6 +89,22 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {
},
},
},
+ {
+ id: "suppliers",
+ header: "Suppliers",
+ cell: ({ row }) => (
+ <AvatarGroup limit={5}>
+ <AvatarGroupList>
+ {((row.original.suppliers ?? []) as Array<{ name: string }>).map(
+ (s) => (
+ <Avatar key={s.name} name={s.name} />
+ )
+ )}
+ </AvatarGroupList>
+ <AvatarOverflowIndicator />
+ </AvatarGroup>
+ ),
+ },
{
id: "createdBy",
header: "Created By",
diff --git a/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx b/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
index b3f565c988..5653804b0e 100644
--- a/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
+++ b/apps/carbon/app/modules/resources/ui/WorkCenters/WorkCenterForm.tsx
@@ -105,8 +105,8 @@ const WorkCenterForm = ({
<TextArea name="description" label="Description" />
<Location name="locationId" label="Location" />
<Number
- name="quotingRate"
- label="Quoting Rate"
+ name="overheadRate"
+ label="Overhead Rate"
formatOptions={{
style: "currency",
currency: "USD",
@@ -131,7 +131,7 @@ const WorkCenterForm = ({
label="Required Ability"
isClearable
/>
- <CustomFormFields table="workCellType" />
+ <CustomFormFields table="workCenter" />
</VStack>
</ModalDrawerBody>
<ModalDrawerFooter>
diff --git a/apps/carbon/app/modules/resources/ui/useResourcesSubmodules.tsx b/apps/carbon/app/modules/resources/ui/useResourcesSubmodules.tsx
index 7c83b039fa..e8ed4102fa 100644
--- a/apps/carbon/app/modules/resources/ui/useResourcesSubmodules.tsx
+++ b/apps/carbon/app/modules/resources/ui/useResourcesSubmodules.tsx
@@ -12,16 +12,6 @@ const resourcesRoutes: RouteGroup[] = [
to: path.to.abilities,
icon: <LuHammer />,
},
- {
- name: "Work Centers",
- to: path.to.workCenters,
- icon: <LuGroup />,
- },
- ],
- },
- {
- name: "Configure",
- routes: [
{
name: "Locations",
to: path.to.locations,
@@ -32,6 +22,11 @@ const resourcesRoutes: RouteGroup[] = [
to: path.to.processes,
icon: <TbRoute />,
},
+ {
+ name: "Work Centers",
+ to: path.to.workCenters,
+ icon: <LuGroup />,
+ },
],
},
];
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index 16c675e44e..edf09d031e 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -2,7 +2,12 @@ import { z } from "zod";
import { zfd } from "zod-form-data";
import { address, contact } from "~/types/validators";
import { currencyCodes } from "../accounting";
-import { methodItemType, methodOperationOrders, methodType } from "../shared";
+import {
+ methodItemType,
+ methodOperationOrders,
+ methodType,
+ operationTypes,
+} from "../shared";
import { standardFactorType } from "../shared/types";
export const salesRFQStatusType = [
@@ -240,37 +245,185 @@ export const quoteMaterialValidator = z
}
);
-export const quoteOperationValidator = z.object({
- id: zfd.text(z.string().optional()),
- quoteMakeMethodId: 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",
+export const quoteOperationValidator = z
+ .object({
+ id: zfd.text(z.string().optional()),
+ quoteMakeMethodId: 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",
+ }),
}),
- }),
- 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" }),
- }),
- setupTime: zfd.numeric(z.number().min(0)),
- laborUnit: z.enum(standardFactorType, {
- errorMap: () => ({ message: "Labor unit is required" }),
- }),
- laborTime: zfd.numeric(z.number().min(0)),
- machineUnit: z.enum(standardFactorType, {
- errorMap: () => ({ message: "Machine unit is required" }),
- }),
- machineTime: zfd.numeric(z.number().min(0)),
- quotingRate: zfd.numeric(z.number().min(0)),
- laborRate: zfd.numeric(z.number().min(0)),
-});
+ 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()),
+ 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.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 quoteFinalizeValidator = z
.object({
diff --git a/apps/carbon/app/modules/sales/ui/Customer/CustomerForm.tsx b/apps/carbon/app/modules/sales/ui/Customer/CustomerForm.tsx
index 3d0ea693f7..508a74aada 100644
--- a/apps/carbon/app/modules/sales/ui/Customer/CustomerForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Customer/CustomerForm.tsx
@@ -61,58 +61,64 @@ const CustomerForm = ({
: !permissions.can("create", "sales");
return (
- <ModalCardProvider type={type}>
- <ModalCard onClose={onClose}>
- <ModalCardContent>
- <ValidatedForm
- method="post"
- action={isEditing ? undefined : path.to.newCustomer}
- validator={customerValidator}
- defaultValues={initialValues}
- fetcher={fetcher}
- >
- <ModalCardHeader>
- <ModalCardTitle>
- {isEditing ? "Customer Overview" : "New Customer"}
- </ModalCardTitle>
- {!isEditing && (
- <ModalCardDescription>
- A customer is a business or person who buys your parts or
- services.
- </ModalCardDescription>
- )}
- </ModalCardHeader>
- <ModalCardBody>
- <Hidden name="id" />
- <Hidden name="type" value={type} />
- <div
- className={cn(
- "grid w-full gap-x-8 gap-y-4",
- isEditing ? "grid-cols-1 lg:grid-cols-3" : "grid-cols-2"
+ <div>
+ <ModalCardProvider type={type}>
+ <ModalCard onClose={onClose}>
+ <ModalCardContent>
+ <ValidatedForm
+ method="post"
+ action={isEditing ? undefined : path.to.newCustomer}
+ validator={customerValidator}
+ defaultValues={initialValues}
+ fetcher={fetcher}
+ >
+ <ModalCardHeader>
+ <ModalCardTitle>
+ {isEditing ? "Customer Overview" : "New Customer"}
+ </ModalCardTitle>
+ {!isEditing && (
+ <ModalCardDescription>
+ A customer is a business or person who buys your parts or
+ services.
+ </ModalCardDescription>
)}
- >
- <Input name="name" label="Name" autoFocus={!isEditing} />
+ </ModalCardHeader>
+ <ModalCardBody>
+ <Hidden name="id" />
+ <Hidden name="type" value={type} />
+ <div
+ className={cn(
+ "grid w-full gap-x-8 gap-y-4",
+ type === "modal"
+ ? "grid-cols-1"
+ : isEditing
+ ? "grid-cols-1 lg:grid-cols-3"
+ : "grid-cols-2"
+ )}
+ >
+ <Input name="name" label="Name" autoFocus={!isEditing} />
- <CustomerStatus
- name="customerStatusId"
- label="Customer Status"
- placeholder="Select Customer Status"
- />
+ <CustomerStatus
+ name="customerStatusId"
+ label="Customer Status"
+ placeholder="Select Customer Status"
+ />
- <Employee name="accountManagerId" label="Account Manager" />
+ <Employee name="accountManagerId" label="Account Manager" />
- <CustomFormFields table="customer" />
- </div>
- </ModalCardBody>
- <ModalCardFooter>
- <HStack>
- <Submit isDisabled={isDisabled}>Save</Submit>
- </HStack>
- </ModalCardFooter>
- </ValidatedForm>
- </ModalCardContent>
- </ModalCard>
- </ModalCardProvider>
+ <CustomFormFields table="customer" />
+ </div>
+ </ModalCardBody>
+ <ModalCardFooter>
+ <HStack>
+ <Submit isDisabled={isDisabled}>Save</Submit>
+ </HStack>
+ </ModalCardFooter>
+ </ValidatedForm>
+ </ModalCardContent>
+ </ModalCard>
+ </ModalCardProvider>
+ </div>
);
};
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
index 6b218079ae..c36d09d6f6 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBillOfProcess.tsx
@@ -9,6 +9,7 @@ import {
CardHeader,
CardTitle,
Editor,
+ Enumerable,
HStack,
cn,
generateHTML,
@@ -33,8 +34,10 @@ import {
NumberControlled,
Process,
Select,
+ SelectControlled,
StandardFactor,
Submit,
+ SupplierProcess,
UnitHint,
WorkCenter,
getUnitHint,
@@ -43,7 +46,11 @@ 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 { TimeTypeIcon, methodOperationOrders } from "~/modules/shared";
+import {
+ TimeTypeIcon,
+ methodOperationOrders,
+ operationTypes,
+} from "~/modules/shared";
import { path } from "~/utils/path";
import { quoteOperationValidator } from "../../sales.models";
import type { Quotation } from "../../types";
@@ -75,18 +82,24 @@ function makeItem(operation: Operation): ItemWithData {
order: operation.operationOrder,
details: (
<HStack spacing={1}>
- {operation.laborTime > 0 && (
- <Badge variant="secondary">
- <TimeTypeIcon type="Labor" className="h-3 w-3 mr-1" />
- {operation.laborTime} {operation.laborUnit}
- </Badge>
- )}
+ {operation.operationType === "Outside" ? (
+ <Enumerable value="Outside" />
+ ) : (
+ <>
+ {(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 && (
- <Badge variant="secondary">
- <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
- {operation.machineTime} {operation.machineUnit}
- </Badge>
+ {(operation?.machineTime ?? 0) > 0 && (
+ <Badge variant="secondary">
+ <TimeTypeIcon type="Machine" className="h-3 w-3 mr-1" />
+ {operation.machineTime} {operation.machineUnit}
+ </Badge>
+ )}
+ </>
)}
</HStack>
),
@@ -94,19 +107,22 @@ function makeItem(operation: Operation): ItemWithData {
};
}
-const initialMethodOperation: Omit<Operation, "quoteMakeMethodId" | "order"> = {
+const initialOperation: Omit<Operation, "quoteMakeMethodId" | "order"> = {
description: "",
- processId: "",
- workCenterId: "",
- setupTime: 0,
- setupUnit: "Total Minutes",
+ laborRate: 0,
laborTime: 0,
laborUnit: "Minutes/Piece",
machineTime: 0,
machineUnit: "Minutes/Piece",
+ operationUnitCost: 0,
+ operationLeadTime: 0,
operationOrder: "After Previous",
- laborRate: 0,
- quotingRate: 0,
+ operationType: "Inside",
+ overheadRate: 0,
+ processId: "",
+ setupTime: 0,
+ setupUnit: "Total Minutes",
+ workCenterId: "",
quoteOperationWorkInstruction: {
content: {},
},
@@ -162,7 +178,7 @@ const QuoteBillOfProcess = ({
checked: false,
id: temporaryId,
data: {
- ...initialMethodOperation,
+ ...initialOperation,
order: newOrder,
quoteMakeMethodId,
},
@@ -550,38 +566,47 @@ function OperationForm({
}, [item.id, fetcher.data, setItems, setSelectedItemId]);
const [processData, setProcessData] = useState<{
- processId: string;
description: string;
- setupUnitHint: string;
- setupUnit: string;
- laborUnitHint: string;
+ laborRate: number;
laborUnit: string;
- machineUnitHint: string;
+ laborUnitHint: string;
machineUnit: string;
- laborRate: number;
- quotingRate: number;
+ machineUnitHint: string;
+ operationMinimumCost: number;
+ operationLeadTime: number;
+ operationType: string;
+ operationUnitCost: number;
+ overheadRate: number;
+ processId: string;
+ setupUnit: string;
+ setupUnitHint: string;
}>({
- processId: item.data.processId ?? "",
description: item.data.description ?? "",
- setupUnitHint: getUnitHint(item.data.setupUnit),
- setupUnit: item.data.setupUnit ?? "Total Minutes",
- laborUnitHint: getUnitHint(item.data.laborUnit),
+ laborRate: item.data.laborRate ?? 0,
laborUnit: item.data.laborUnit ?? "Hours/Piece",
- machineUnitHint: getUnitHint(item.data.machineUnit),
+ laborUnitHint: getUnitHint(item.data.laborUnit),
machineUnit: item.data.machineUnit ?? "Hours/Piece",
- laborRate: item.data.laborRate ?? 0,
- quotingRate: item.data.quotingRate ?? 0,
+ 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 ?? "",
+ setupUnit: item.data.setupUnit ?? "Total Minutes",
+ setupUnitHint: getUnitHint(item.data.setupUnit),
});
const onProcessChange = async (processId: string) => {
if (!supabase || !processId) return;
- const [process, workCenters] = await Promise.all([
+ 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 =
@@ -605,11 +630,31 @@ function OperationForm({
}, 0) / activeWorkCenters.length
: p.laborRate,
// get the average quoting rate from the work centers
- quotingRate: activeWorkCenters.length
+ overheadRate: activeWorkCenters.length
? activeWorkCenters?.reduce((acc, workCenter) => {
- return (acc += workCenter.workCenter?.quotingRate ?? 0);
+ return (acc += workCenter.workCenter?.overheadRate ?? 0);
}, 0) / activeWorkCenters.length
: p.laborRate,
+ 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",
}));
};
@@ -635,11 +680,29 @@ function OperationForm({
laborUnitHint: getUnitHint(data?.defaultStandardFactor),
machineUnit: data?.defaultStandardFactor ?? "Hours/Piece",
machineUnitHint: getUnitHint(data?.defaultStandardFactor),
- quotingRate: data?.quotingRate ?? 0,
+ overheadRate: data?.overheadRate ?? 0,
laborRate: data?.laborRate ?? 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={
@@ -689,132 +752,221 @@ function OperationForm({
label: o,
}))}
/>
- <WorkCenter
- name="workCenterId"
- label="Work Center"
- isOptional
- processId={processData.processId}
+ <SelectControlled
+ name="operationType"
+ label="Operation Type"
+ placeholder="Operation Type"
+ options={operationTypes.map((o) => ({
+ value: o,
+ label: o,
+ }))}
+ value={processData.operationType}
onChange={(value) => {
- onWorkCenterChange(value?.value ?? null);
- }}
- />
- </div>
- <InputControlled
- name="description"
- label="Description"
- value={processData.description}
- onChange={(newValue) => {
- setProcessData((d) => ({ ...d, description: newValue }));
- }}
- />
- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <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) => {
setProcessData((d) => ({
...d,
- setupUnit: newValue?.value ?? "Total Minutes",
- }));
- }}
- />
- <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="laborUnit"
- label="Labor Unit"
- hint={processData.laborUnitHint}
- value={processData.laborUnit}
- onChange={(newValue) => {
- setProcessData((d) => ({
- ...d,
- 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",
+
+ setupUnit: "Total Minutes",
+ laborUnit: "Minutes/Piece",
+ machineUnit: "Minutes/Piece",
+ operationType: value?.value as string,
}));
}}
/>
- <Number name="machineTime" label="Machine Time" minValue={0} />
- <StandardFactor
- name="machineUnit"
- label="Machine Unit"
- hint={processData.machineUnitHint}
- value={processData.machineUnit}
+
+ <InputControlled
+ name="description"
+ label="Description"
+ value={processData.description}
onChange={(newValue) => {
- setProcessData((d) => ({
- ...d,
- machineUnit: newValue?.value ?? "Hours/Piece",
- }));
+ setProcessData((d) => ({ ...d, description: newValue }));
}}
+ className="col-span-2"
/>
- <NumberControlled
- name="quotingRate"
- label="Quoting Rate"
- minValue={0}
- value={processData.quotingRate}
- formatOptions={{
- style: "currency",
- currency: "USD",
- }}
- onChange={(newValue) =>
- setProcessData((d) => ({
- ...d,
- quotingRate: newValue,
- }))
- }
- />
- <NumberControlled
- name="laborRate"
- label="Labor Rate"
- minValue={0}
- value={processData.laborRate}
- formatOptions={{
- style: "currency",
- currency: "USD",
- }}
- onChange={(newValue) =>
- setProcessData((d) => ({
- ...d,
- laborRate: newValue,
- }))
- }
- />
+
+ {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);
+ }
+ }}
+ />
+ <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) => {
+ setProcessData((d) => ({
+ ...d,
+ setupUnit: newValue?.value ?? "Total Minutes",
+ }));
+ }}
+ />
+ <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="laborUnit"
+ label="Labor Unit"
+ hint={processData.laborUnitHint}
+ value={processData.laborUnit}
+ onChange={(newValue) => {
+ setProcessData((d) => ({
+ ...d,
+ 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",
+ }));
+ }}
+ />
+
+ <NumberControlled
+ name="overheadRate"
+ label="Overhead Rate"
+ minValue={0}
+ value={processData.overheadRate}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ overheadRate: newValue,
+ }))
+ }
+ />
+ <NumberControlled
+ name="laborRate"
+ label="Labor Rate"
+ minValue={0}
+ value={processData.laborRate}
+ formatOptions={{
+ style: "currency",
+ currency: "USD",
+ }}
+ onChange={(newValue) =>
+ setProcessData((d) => ({
+ ...d,
+ laborRate: newValue,
+ }))
+ }
+ />
+ </>
+ )}
</div>
<motion.div
className="flex w-full items-center justify-end p-2"
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx
index 6e3224238f..fd9cb2b89e 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx
@@ -103,9 +103,7 @@ const QuoteBreadcrumbs = () => {
<HStack spacing={0}>
<MenubarItem
isDisabled={
- !hasMethods ||
- !permissions.can("update", "parts") ||
- isSaveMethodLoading
+ !permissions.can("update", "parts") || isSaveMethodLoading
}
isLoading={isSaveMethodLoading}
leftIcon={<LuUpload />}
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
index 7f028fad29..342cc9d7d1 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteExplorer.tsx
@@ -3,6 +3,7 @@ import {
cn,
DropdownMenu,
DropdownMenuContent,
+ DropdownMenuIcon,
DropdownMenuItem,
DropdownMenuTrigger,
HStack,
@@ -19,7 +20,7 @@ import {
import { prettifyKeyboardShortcut } from "@carbon/utils";
import { useNavigate, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
-import { LuChevronsUpDown, LuImage, LuPlus } from "react-icons/lu";
+import { LuChevronsUpDown, LuImage, LuPlus, LuTrash } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
import { Empty } from "~/components";
import type { Tree } from "~/components/TreeView";
@@ -256,6 +257,7 @@ function QuoteLineItem({ line, isDisabled, onDelete }: QuoteLineItemProps) {
onDelete(line);
}}
>
+ <DropdownMenuIcon icon={<LuTrash />} />
Delete Line
</DropdownMenuItem>
</DropdownMenuContent>
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
index 1b797b7cd9..4570d9528a 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
@@ -3,6 +3,7 @@ import {
cn,
DropdownMenu,
DropdownMenuContent,
+ DropdownMenuIcon,
DropdownMenuItem,
DropdownMenuTrigger,
HStack,
@@ -18,7 +19,7 @@ import {
import { prettifyKeyboardShortcut } from "@carbon/utils";
import { useNavigate, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
-import { LuImage, LuPlus } from "react-icons/lu";
+import { LuImage, LuPlus, LuTrash } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
import { Empty } from "~/components";
import { useOptimisticLocation, usePermissions, useRouteData } from "~/hooks";
@@ -217,6 +218,7 @@ function SalesRFQLineItem({
onDelete(line);
}}
>
+ <DropdownMenuIcon icon={<LuTrash />} />
Delete Line
</DropdownMenuItem>
</DropdownMenuContent>
diff --git a/apps/carbon/app/modules/shared/shared.models.ts b/apps/carbon/app/modules/shared/shared.models.ts
index 32537d2966..eb49485e53 100644
--- a/apps/carbon/app/modules/shared/shared.models.ts
+++ b/apps/carbon/app/modules/shared/shared.models.ts
@@ -39,3 +39,9 @@ export const noteValidator = z.object({
});
export const operationTypes = ["Inside", "Outside"] as const;
+
+export const processTypes = [
+ "Inside",
+ "Outside",
+ "Inside and Outside",
+] as const;
diff --git a/apps/carbon/app/routes/api+/purchasing.supplier-processes.ts b/apps/carbon/app/routes/api+/purchasing.supplier-processes.ts
new file mode 100644
index 0000000000..a702aa1990
--- /dev/null
+++ b/apps/carbon/app/routes/api+/purchasing.supplier-processes.ts
@@ -0,0 +1,37 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json } from "@remix-run/node";
+import { getSupplierProcessesByProcess } from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { error } from "~/utils/result";
+
+export async function loader({ request }: LoaderFunctionArgs) {
+ const authorized = await requirePermissions(request, {
+ view: "purchasing",
+ });
+
+ const url = new URL(request.url);
+ const searchParams = new URLSearchParams(url.search);
+ const processId = searchParams.get("processId") as string;
+
+ if (!processId || processId === "undefined")
+ return json({
+ data: [],
+ });
+
+ const processes = await getSupplierProcessesByProcess(
+ authorized.client,
+ processId
+ );
+ if (processes.error) {
+ return json(
+ processes,
+ await flash(
+ request,
+ error(processes.error, "Failed to get supplier processes")
+ )
+ );
+ }
+
+ return json(processes);
+}
diff --git a/apps/carbon/app/routes/x+/resources+/processes.$processId.tsx b/apps/carbon/app/routes/x+/resources+/processes.$processId.tsx
index 1c92ec48f2..9720d62b00 100644
--- a/apps/carbon/app/routes/x+/resources+/processes.$processId.tsx
+++ b/apps/carbon/app/routes/x+/resources+/processes.$processId.tsx
@@ -83,9 +83,12 @@ export default function ProcessRoute() {
const initialValues = {
id: process.id!,
name: process.name!,
+ processType: process.processType ?? "Inside",
defaultStandardFactor: process.defaultStandardFactor ?? "Minutes/Piece",
// @ts-ignore
workCenters: (process.workCenters ?? []).map((wc) => wc.id) ?? [],
+ // @ts-ignore
+ suppliers: (process.suppliers ?? []).map((s) => s.id) ?? [],
...getCustomFields(process.customFields),
};
diff --git a/apps/carbon/app/routes/x+/resources+/processes.delete.$processId.tsx b/apps/carbon/app/routes/x+/resources+/processes.delete.$processId.tsx
index 44b73ed76c..8bab9db3b3 100644
--- a/apps/carbon/app/routes/x+/resources+/processes.delete.$processId.tsx
+++ b/apps/carbon/app/routes/x+/resources+/processes.delete.$processId.tsx
@@ -74,7 +74,7 @@ export default function DeleteProcessRoute() {
return (
<ConfirmDelete
action={path.to.deleteProcess(processId)}
- name={process.name}
+ name={process.name!}
text={`Are you sure you want to delete the process: ${process.name}? This cannot be undone.`}
onCancel={onCancel}
/>
diff --git a/apps/carbon/app/routes/x+/resources+/processes.new.tsx b/apps/carbon/app/routes/x+/resources+/processes.new.tsx
index 1a84e0c1fd..1ba6cee29c 100644
--- a/apps/carbon/app/routes/x+/resources+/processes.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/processes.new.tsx
@@ -64,6 +64,7 @@ export default function NewProcessRoute() {
const initialValues = {
name: "",
+ processType: "Inside" as const,
defaultStandardFactor: "Minutes/Piece" as const,
};
diff --git a/apps/carbon/app/routes/x+/resources+/work-centers.$id.tsx b/apps/carbon/app/routes/x+/resources+/work-centers.$id.tsx
index f00a479063..e2adffe7cf 100644
--- a/apps/carbon/app/routes/x+/resources+/work-centers.$id.tsx
+++ b/apps/carbon/app/routes/x+/resources+/work-centers.$id.tsx
@@ -87,7 +87,6 @@ export default function WorkCenterRoute() {
name: workCenter?.name ?? "",
description: workCenter?.description ?? "",
requiredAbilityId: workCenter?.requiredAbilityId ?? undefined,
- quotingRate: workCenter?.quotingRate ?? 0,
laborRate: workCenter?.laborRate ?? 0,
overheadRate: workCenter?.overheadRate ?? 0,
defaultStandardFactor: workCenter?.defaultStandardFactor ?? "Minutes/Piece",
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 a893fa998c..3e857a2088 100644
--- a/apps/carbon/app/routes/x+/resources+/work-centers.new.tsx
+++ b/apps/carbon/app/routes/x+/resources+/work-centers.new.tsx
@@ -61,7 +61,6 @@ export default function NewWorkCenterRoute() {
const initialValues = {
name: "",
description: "",
- quotingRate: 0,
laborRate: 0,
overheadRate: 0,
defaultStandardFactor: "Minutes/Piece" as "Minutes/Piece",
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.$id.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.$id.tsx
new file mode 100644
index 0000000000..7b4f6c2117
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.$id.tsx
@@ -0,0 +1,82 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useParams } from "@remix-run/react";
+import { useRouteData } from "~/hooks";
+import type { SupplierProcess } from "~/modules/purchasing";
+import {
+ SupplierProcessForm,
+ supplierProcessValidator,
+ upsertSupplierProcess,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw new Error("Could not find supplierId");
+
+ const formData = await request.formData();
+
+ const validation = await validator(supplierProcessValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+ if (!id) throw new Error("Could not find id");
+
+ const createSupplierProcess = await upsertSupplierProcess(client, {
+ id,
+ ...data,
+ updatedBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createSupplierProcess.error) {
+ throw redirect(
+ path.to.supplierProcesses(supplierId),
+ await flash(
+ request,
+ error(createSupplierProcess.error, "Failed to update supplier process")
+ )
+ );
+ }
+
+ return redirect(path.to.supplierProcesses(supplierId));
+}
+
+export default function SupplierProcessRoute() {
+ const { supplierId, id } = useParams();
+ if (!supplierId) throw new Error("Could not find supplier id");
+ if (!id) throw new Error("Could not find id");
+ const routeData = useRouteData<{ processes: SupplierProcess[] }>(
+ path.to.supplierProcesses(supplierId)
+ );
+
+ const process = routeData?.processes.find((process) => process.id === id);
+ if (!process) throw new Error("Could not find process");
+
+ const initialValues = {
+ id: process.id ?? undefined,
+ supplierId: process.supplierId ?? "",
+ processId: process.processId ?? "",
+ minimumCost: process.minimumCost ?? 0,
+ unitCost: process.unitCost ?? 0,
+ leadTime: process.leadTime ?? 0,
+ };
+
+ return <SupplierProcessForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx
new file mode 100644
index 0000000000..b3f5e38d24
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.delete.$id.tsx
@@ -0,0 +1,64 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import { useRouteData } from "~/hooks";
+import {
+ deleteSupplierProcess,
+ type SupplierProcess,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+
+ const { supplierId, id } = params;
+ if (!supplierId) throw new Error("Could not find supplierId");
+ if (!id) throw new Error("Could not find id");
+
+ const update = await deleteSupplierProcess(client, id);
+
+ if (update.error) {
+ throw redirect(
+ path.to.supplierProcesses(supplierId),
+ await flash(
+ request,
+ error(update.error, "Failed to delete supplier process")
+ )
+ );
+ }
+
+ return redirect(path.to.supplierProcesses(supplierId));
+}
+
+export default function DeleteSupplierProcessRoute() {
+ const navigate = useNavigate();
+ const { supplierId, id } = useParams();
+ if (!supplierId) throw new Error("Could not find supplier id");
+ if (!id) throw new Error("Could not find id");
+ const routeData = useRouteData<{ processes: SupplierProcess[] }>(
+ path.to.supplierProcesses(supplierId)
+ );
+
+ const process = routeData?.processes.find((process) => process.id === id);
+ if (!process) throw new Error("Could not find process");
+
+ return (
+ <ConfirmDelete
+ action={path.to.deleteSupplierProcess(supplierId, id)}
+ isOpen
+ name={process.processName!}
+ text={`Are you sure you want to permanently delete the supplier process?`}
+ onCancel={() => {
+ navigate(-1);
+ }}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.new.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.new.tsx
new file mode 100644
index 0000000000..c06e8a5375
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.new.tsx
@@ -0,0 +1,75 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useParams } from "@remix-run/react";
+import {
+ SupplierProcessForm,
+ supplierProcessValidator,
+ upsertSupplierProcess,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { setCustomFields } from "~/utils/form";
+import { assertIsPost } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw new Error("Could not find supplierId");
+
+ const formData = await request.formData();
+ const modal = formData.get("type") === "modal";
+
+ const validation = await validator(supplierProcessValidator).validate(
+ formData
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createSupplierProcess = await upsertSupplierProcess(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createSupplierProcess.error) {
+ throw redirect(
+ path.to.supplierProcesses(supplierId),
+ await flash(
+ request,
+ error(createSupplierProcess.error, "Failed to create supplier process")
+ )
+ );
+ }
+
+ return modal
+ ? json(createSupplierProcess)
+ : redirect(path.to.supplierProcesses(supplierId));
+}
+
+export default function NewSupplierProcessRoute() {
+ const { supplierId } = useParams();
+
+ if (!supplierId) throw new Error("Could not find supplier id");
+
+ const initialValues = {
+ supplierId: supplierId,
+ processId: "",
+ minimumCost: 0,
+ unitCost: 0,
+ leadTime: 0,
+ };
+
+ return <SupplierProcessForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.tsx b/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.tsx
new file mode 100644
index 0000000000..94e9e99706
--- /dev/null
+++ b/apps/carbon/app/routes/x+/supplier+/$supplierId.processes.tsx
@@ -0,0 +1,48 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { Outlet, useLoaderData } from "@remix-run/react";
+import {
+ SupplierProcesses,
+ getSupplierProcessesBySupplier,
+} from "~/modules/purchasing";
+
+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: "purchasing",
+ });
+
+ const { supplierId } = params;
+ if (!supplierId) throw new Error("Could not find supplierId");
+
+ const processes = await getSupplierProcessesBySupplier(client, supplierId);
+
+ if (processes.error || !processes.data) {
+ throw redirect(
+ path.to.supplier(supplierId),
+ await flash(
+ request,
+ error(processes.error, "Failed to load supplier payment")
+ )
+ );
+ }
+
+ return json({
+ processes: processes.data,
+ });
+}
+
+export default function SupplierPaymentRoute() {
+ const { processes } = useLoaderData<typeof loader>();
+
+ return (
+ <>
+ <SupplierProcesses processes={processes} />
+ <Outlet />
+ </>
+ );
+}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index a55b28e885..126cc7ed8f 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -49,6 +49,8 @@ export const path = {
generatePath(`${api}/purchasing/supplier-contacts?supplierId=${id}`),
supplierLocations: (id: string) =>
generatePath(`${api}/purchasing/supplier-locations?supplierId=${id}`),
+ supplierProcesses: (id?: string) =>
+ generatePath(`${api}/purchasing/supplier-processes?processId=${id}`),
supplierStatuses: `${api}/purchasing/supplier-statuses`,
supplierTypes: `${api}/purchasing/supplier-types`,
unitOfMeasures: `${api}/items/uoms`,
@@ -265,6 +267,8 @@ export const path = {
generatePath(`${x}/supplier/${supplierId}/contacts/delete/${id}`),
deleteSupplierLocation: (supplierId: string, id: string) =>
generatePath(`${x}/supplier/${supplierId}/locations/delete/${id}`),
+ deleteSupplierProcess: (supplierId: string, id: string) =>
+ generatePath(`${x}/supplier/${supplierId}/processes/delete/${id}`),
deleteSupplierStatus: (id: string) =>
generatePath(`${x}/purchasing/supplier-statuses/delete/${id}`),
deleteSupplierType: (id: string) =>
@@ -461,6 +465,8 @@ export const path = {
generatePath(`${x}/supplier/${id}/contacts/new`),
newSupplierLocation: (id: string) =>
generatePath(`${x}/supplier/${id}/locations/new`),
+ newSupplierProcess: (id: string) =>
+ generatePath(`${x}/supplier/${id}/processes/new`),
newSupplierStatus: `${x}/purchasing/supplier-statuses/new`,
newSupplierType: `${x}/purchasing/supplier-types/new`,
newTool: `${x}/tool/new`,
@@ -673,6 +679,10 @@ export const path = {
generatePath(`${x}/supplier/${id}/locations`),
supplierPayment: (id: string) =>
generatePath(`${x}/supplier/${id}/payments`),
+ supplierProcess: (supplierId: string, id: string) =>
+ generatePath(`${x}/supplier/${supplierId}/processes/${id}`),
+ supplierProcesses: (id: string) =>
+ generatePath(`${x}/supplier/${id}/processes`),
supplierShipping: (id: string) =>
generatePath(`${x}/supplier/${id}/shipping`),
supplierRoot: `${x}/supplier`,
diff --git a/apps/docs/pages/core-concepts/permissions.mdx b/apps/docs/pages/core-concepts/permissions.mdx
index 32035889a0..af1fcc5edb 100644
--- a/apps/docs/pages/core-concepts/permissions.mdx
+++ b/apps/docs/pages/core-concepts/permissions.mdx
@@ -72,14 +72,14 @@ CREATE POLICY "Employees with sales_view can view customer" ON "customer"
FOR SELECT
USING (
has_role('employee', "companyId") AND
- has_company_permissions('sales_view', "companyId")
+ has_company_permission('sales_view', "companyId")
);
CREATE POLICY "Customers with sales_view can their own organization" ON "customer"
FOR SELECT
USING (
has_role('customer', "companyId") AND
- has_company_permissions('sales_view', "companyId")
+ has_company_permission('sales_view', "companyId")
AND id IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
)
@@ -89,21 +89,21 @@ CREATE POLICY "Employees with sales_create can create customers" ON "customer"
FOR INSERT
WITH CHECK (
has_role('employee', "companyId") AND
- has_company_permissions('sales_create', "companyId")
+ has_company_permission('sales_create', "companyId")
);
CREATE POLICY "Employees with sales_update can update customers" ON "customer"
FOR UPDATE
USING (
has_role('employee', "companyId") AND
- has_company_permissions('sales_update', "companyId")
+ has_company_permission('sales_update', "companyId")
);
CREATE POLICY "Customers with sales_update can their own organization" ON "customer"
FOR UPDATE
USING (
has_role('customer', "companyId") AND
- has_company_permissions('sales_update', "companyId")
+ has_company_permission('sales_update', "companyId")
AND id IN (
SELECT "customerId" FROM "customerAccount" WHERE id::uuid = auth.uid()
)
@@ -113,7 +113,7 @@ CREATE POLICY "Employees with sales_delete can delete customers" ON "customer"
FOR DELETE
USING (
has_role('employee', "companyId") AND
- has_company_permissions('sales_delete', "companyId")
+ has_company_permission('sales_delete', "companyId")
);
```
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 1c35c03d1d..0da9fa2eac 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -7908,12 +7908,11 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
makeMethodId: string
- operationCost: number
- operationLeadTime: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId: string | null
+ operationSupplierProcessId: string | null
operationType: Database["public"]["Enums"]["operationType"]
order: number
+ overheadRate: number
processId: string
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
@@ -7933,12 +7932,11 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId: string
- operationCost?: number
- operationLeadTime?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId?: string | null
+ operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
order?: number
+ overheadRate?: number
processId: string
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
@@ -7958,12 +7956,11 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId?: string
- operationCost?: number
- operationLeadTime?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId?: string | null
+ operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
order?: number
+ overheadRate?: number
processId?: string
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
@@ -8049,41 +8046,6 @@ export type Database = {
referencedRelation: "quoteOperationsWithMakeMethods"
referencedColumns: ["makeMethodId"]
},
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "methodOperation_processId_fkey"
columns: ["processId"]
@@ -8147,6 +8109,20 @@ export type Database = {
referencedRelation: "workCenters"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
+ isOneToOne: false
+ referencedRelation: "supplierProcess"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
+ isOneToOne: false
+ referencedRelation: "supplierProcesses"
+ referencedColumns: ["id"]
+ },
]
}
methodOperationWorkInstruction: {
@@ -10026,6 +10002,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"]
id: string
name: string
+ processType: Database["public"]["Enums"]["processType"]
updatedAt: string | null
updatedBy: string | null
}
@@ -10037,6 +10014,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"]
id?: string
name: string
+ processType?: Database["public"]["Enums"]["processType"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -10048,6 +10026,7 @@ export type Database = {
defaultStandardFactor?: Database["public"]["Enums"]["factor"]
id?: string
name?: string
+ processType?: Database["public"]["Enums"]["processType"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -13499,11 +13478,12 @@ export type Database = {
laborUnit: Database["public"]["Enums"]["factor"]
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
- operationCost: number
operationLeadTime: number
+ operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId: string | null
+ operationSupplierProcessId: string | null
operationType: Database["public"]["Enums"]["operationType"]
+ operationUnitCost: number
order: number
overheadRate: number
processId: string
@@ -13529,11 +13509,12 @@ export type Database = {
laborUnit?: Database["public"]["Enums"]["factor"]
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
- operationCost?: number
operationLeadTime?: number
+ operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId?: string | null
+ operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
+ operationUnitCost?: number
order?: number
overheadRate?: number
processId: string
@@ -13559,11 +13540,12 @@ export type Database = {
laborUnit?: Database["public"]["Enums"]["factor"]
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
- operationCost?: number
operationLeadTime?: number
+ operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId?: string | null
+ operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
+ operationUnitCost?: number
order?: number
overheadRate?: number
processId?: string
@@ -13642,38 +13624,17 @@ export type Database = {
referencedColumns: ["userId"]
},
{
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
+ referencedRelation: "supplierProcess"
referencedColumns: ["id"]
},
{
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
+ referencedRelation: "supplierProcesses"
referencedColumns: ["id"]
},
{
@@ -17904,8 +17865,13 @@ export type Database = {
companyId: string
createdAt: string
createdBy: string
+ customFields: Json | null
+ id: string
+ leadTime: number
+ minimumCost: number
processId: string
supplierId: string
+ unitCost: number
updatedAt: string | null
updatedBy: string | null
}
@@ -17913,8 +17879,13 @@ export type Database = {
companyId: string
createdAt?: string
createdBy: string
+ customFields?: Json | null
+ id?: string
+ leadTime?: number
+ minimumCost?: number
processId: string
supplierId: string
+ unitCost?: number
updatedAt?: string | null
updatedBy?: string | null
}
@@ -17922,8 +17893,13 @@ export type Database = {
companyId?: string
createdAt?: string
createdBy?: string
+ customFields?: Json | null
+ id?: string
+ leadTime?: number
+ minimumCost?: number
processId?: string
supplierId?: string
+ unitCost?: number
updatedAt?: string | null
updatedBy?: string | null
}
@@ -19694,8 +19670,7 @@ export type Database = {
laborRate: number
locationId: string | null
name: string
- overheadRate: number | null
- quotingRate: number
+ overheadRate: number
requiredAbilityId: string | null
updatedAt: string | null
updatedBy: string | null
@@ -19712,8 +19687,7 @@ export type Database = {
laborRate?: number
locationId?: string | null
name: string
- overheadRate?: number | null
- quotingRate?: number
+ overheadRate?: number
requiredAbilityId?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -19730,8 +19704,7 @@ export type Database = {
laborRate?: number
locationId?: string | null
name?: string
- overheadRate?: number | null
- quotingRate?: number
+ overheadRate?: number
requiredAbilityId?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -22279,6 +22252,8 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"] | null
id: string | null
name: string | null
+ processType: Database["public"]["Enums"]["processType"] | null
+ suppliers: Json | null
updatedAt: string | null
updatedBy: string | null
workCenters: Json | null
@@ -23635,9 +23610,14 @@ export type Database = {
machineTime: number | null
machineUnit: Database["public"]["Enums"]["factor"] | null
makeMethodId: string | null
+ operationLeadTime: number | null
+ operationMinimumCost: number | null
operationOrder:
| Database["public"]["Enums"]["methodOperationOrder"]
| null
+ operationSupplierProcessId: string | null
+ operationType: Database["public"]["Enums"]["operationType"] | null
+ operationUnitCost: number | null
order: number | null
overheadRate: number | null
processId: string | null
@@ -23715,6 +23695,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
+ isOneToOne: false
+ referencedRelation: "supplierProcess"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
+ isOneToOne: false
+ referencedRelation: "supplierProcesses"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_processId_fkey"
columns: ["processId"]
@@ -25679,6 +25673,172 @@ export type Database = {
},
]
}
+ supplierProcesses: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ id: string | null
+ leadTime: number | null
+ minimumCost: number | null
+ processId: string | null
+ processName: string | null
+ supplierId: string | null
+ unitCost: number | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "supplierProcess_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_processId_fkey"
+ columns: ["processId"]
+ isOneToOne: false
+ referencedRelation: "process"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_processId_fkey"
+ columns: ["processId"]
+ isOneToOne: false
+ referencedRelation: "processes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "supplier"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "contractors"
+ referencedColumns: ["supplierId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "partners"
+ referencedColumns: ["supplierId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrderSuppliers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "suppliers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
suppliers: {
Row: {
accountManagerId: string | null
@@ -26178,7 +26338,6 @@ export type Database = {
name: string | null
overheadRate: number | null
processes: Json | null
- quotingRate: number | null
requiredAbilityId: string | null
updatedAt: string | null
updatedBy: string | null
@@ -26712,6 +26871,7 @@ export type Database = {
| "Consumable"
| "Fixture"
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"
+ processType: "Inside" | "Outside" | "Inside and Outside"
purchaseInvoiceStatus:
| "Draft"
| "Pending"
diff --git a/packages/database/supabase/functions/get-method/index.ts b/packages/database/supabase/functions/get-method/index.ts
index 5bac43bd43..6f0752edee 100644
--- a/packages/database/supabase/functions/get-method/index.ts
+++ b/packages/database/supabase/functions/get-method/index.ts
@@ -58,16 +58,21 @@ serve(async (req: Request) => {
}
const itemId = sourceId;
- const [makeMethod, quoteMakeMethod, workCenters] = await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
- client
- .from("quoteMakeMethod")
- .select("*")
- .eq("quoteLineId", quoteLineId)
- .is("parentMaterialId", null)
- .single(),
- client.from("workCenters").select("*").eq("companyId", companyId),
- ]);
+ const [makeMethod, quoteMakeMethod, workCenters, supplierProcesses] =
+ await Promise.all([
+ client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("quoteMakeMethod")
+ .select("*")
+ .eq("quoteLineId", quoteLineId)
+ .is("parentMaterialId", null)
+ .single(),
+ client.from("workCenters").select("*").eq("companyId", companyId),
+ client
+ .from("supplierProcess")
+ .select("*")
+ .eq("companyId", companyId),
+ ]);
if (makeMethod.error) {
throw new Error("Failed to get make method");
@@ -92,7 +97,12 @@ serve(async (req: Request) => {
const methodTree = methodTrees.data?.[0] as MethodTreeItem;
if (!methodTree) throw new Error("Method tree not found");
- const getRates = getRatesFromWorkCenters(workCenters?.data);
+ const getLaborAndOverheadRates = getRatesFromWorkCenters(
+ workCenters?.data
+ );
+ const getOutsideOperationRates = getRatesFromSupplierProcesses(
+ supplierProcesses?.data
+ );
await db.transaction().execute(async (trx) => {
// Delete existing quoteMakeMethod, quoteMakeMethodOperation, quoteMakeMethodMaterial
@@ -143,9 +153,15 @@ serve(async (req: Request) => {
laborUnit: op.laborUnit,
machineTime: op.machineTime,
machineUnit: op.machineUnit,
- ...getRates(op.processId, op.workCenterId),
+ ...getLaborAndOverheadRates(op.processId, op.workCenterId),
order: op.order,
operationOrder: op.operationOrder,
+ operationType: op.operationType,
+ operationSupplierProcessId: op.operationSupplierProcessId,
+ ...getOutsideOperationRates(
+ op.processId,
+ op.operationSupplierProcessId
+ ),
companyId,
createdBy: userId,
customFields: {},
@@ -253,15 +269,20 @@ serve(async (req: Request) => {
}
const itemId = sourceId;
- const [makeMethod, quoteMakeMethod, workCenters] = await Promise.all([
- client.from("makeMethod").select("*").eq("itemId", itemId).single(),
- client
- .from("quoteMakeMethod")
- .select("*")
- .eq("id", quoteMakeMethodId)
- .single(),
- client.from("workCenters").select("*").eq("companyId", companyId),
- ]);
+ const [makeMethod, quoteMakeMethod, workCenters, supplierProcesses] =
+ await Promise.all([
+ client.from("makeMethod").select("*").eq("itemId", itemId).single(),
+ client
+ .from("quoteMakeMethod")
+ .select("*")
+ .eq("id", quoteMakeMethodId)
+ .single(),
+ client.from("workCenters").select("*").eq("companyId", companyId),
+ client
+ .from("supplierProcess")
+ .select("*")
+ .eq("companyId", companyId),
+ ]);
if (makeMethod.error) {
throw new Error("Failed to get make method");
@@ -282,7 +303,12 @@ serve(async (req: Request) => {
const methodTree = methodTrees.data?.[0] as MethodTreeItem;
if (!methodTree) throw new Error("Method tree not found");
- const getRates = getRatesFromWorkCenters(workCenters?.data);
+ const getLaborAndOverheadRates = getRatesFromWorkCenters(
+ workCenters?.data
+ );
+ const getOutsideOperationRates = getRatesFromSupplierProcesses(
+ supplierProcesses?.data
+ );
await db.transaction().execute(async (trx) => {
// Delete existing quoteMakeMethodOperation, quoteMakeMethodMaterial
@@ -324,10 +350,15 @@ serve(async (req: Request) => {
laborUnit: op.laborUnit,
machineTime: op.machineTime,
machineUnit: op.machineUnit,
- ...getRates(op.processId, op.workCenterId),
-
+ ...getLaborAndOverheadRates(op.processId, op.workCenterId),
order: op.order,
operationOrder: op.operationOrder,
+ operationType: op.operationType,
+ operationSupplierProcessId: op.operationSupplierProcessId,
+ ...getOutsideOperationRates(
+ op.processId,
+ op.operationSupplierProcessId
+ ),
companyId,
createdBy: userId,
customFields: {},
@@ -575,6 +606,8 @@ serve(async (req: Request) => {
machineUnit: op.machineUnit ?? "Minutes/Piece",
order: op.order ?? 1,
operationOrder: op.operationOrder ?? "After Previous",
+ operationType: op.operationType ?? "Inside",
+ operationSupplierProcessId: op.operationSupplierProcessId,
companyId,
createdBy: userId,
customFields: {},
@@ -772,6 +805,8 @@ serve(async (req: Request) => {
machineUnit: op.machineUnit ?? "Minutes/Piece",
order: op.order ?? 1,
operationOrder: op.operationOrder ?? "After Previous",
+ operationType: op.operationType ?? "Inside",
+
companyId,
createdBy: userId,
customFields: {},
@@ -982,10 +1017,10 @@ const getRatesFromWorkCenters =
(
processId: string,
workCenterId: string | null
- ): { quotingRate: number; laborRate: number } => {
+ ): { overheadRate: number; laborRate: number } => {
if (!workCenters) {
return {
- quotingRate: 0,
+ overheadRate: 0,
laborRate: 0,
};
}
@@ -997,7 +1032,7 @@ const getRatesFromWorkCenters =
if (workCenter) {
return {
- quotingRate: workCenter.quotingRate ?? 0,
+ overheadRate: workCenter.overheadRate ?? 0,
laborRate: workCenter.laborRate ?? 0,
};
}
@@ -1009,9 +1044,9 @@ const getRatesFromWorkCenters =
});
if (relatedWorkCenters.length > 0) {
- const quotingRate =
+ const overheadRate =
relatedWorkCenters.reduce((acc, workCenter) => {
- return (acc += workCenter.quotingRate ?? 0);
+ return (acc += workCenter.overheadRate ?? 0);
}, 0) / relatedWorkCenters.length;
const laborRate =
relatedWorkCenters.reduce((acc, workCenter) => {
@@ -1019,13 +1054,77 @@ const getRatesFromWorkCenters =
}, 0) / relatedWorkCenters.length;
return {
- quotingRate,
+ overheadRate,
laborRate,
};
}
return {
- quotingRate: 0,
+ overheadRate: 0,
laborRate: 0,
};
};
+
+const getRatesFromSupplierProcesses =
+ (
+ processes: Database["public"]["Tables"]["supplierProcess"]["Row"][] | null
+ ) =>
+ (
+ processId: string,
+ supplierProcessId: string | null
+ ): {
+ operationMinimumCost: number;
+ operationUnitCost: number;
+ operationLeadTime: number;
+ } => {
+ if (!processes) {
+ return {
+ operationMinimumCost: 0,
+ operationUnitCost: 0,
+ operationLeadTime: 0,
+ };
+ }
+
+ if (supplierProcessId) {
+ const supplierProcess = processes?.find(
+ (sp) => sp.id === supplierProcessId
+ );
+
+ if (supplierProcess) {
+ return {
+ operationMinimumCost: supplierProcess.minimumCost,
+ operationUnitCost: supplierProcess.unitCost,
+ operationLeadTime: supplierProcess.leadTime,
+ };
+ }
+ }
+
+ const relatedProcesses = processes.filter((p) => p.processId === processId);
+
+ if (relatedProcesses.length > 0) {
+ const operationMinimumCost =
+ relatedProcesses.reduce((acc, process) => {
+ return (acc += process.minimumCost ?? 0);
+ }, 0) / relatedProcesses.length;
+ const operationUnitCost =
+ relatedProcesses.reduce((acc, process) => {
+ return (acc += process.unitCost ?? 0);
+ }, 0) / relatedProcesses.length;
+ const operationLeadTime =
+ relatedProcesses.reduce((acc, process) => {
+ return (acc += process.leadTime ?? 0);
+ }, 0) / relatedProcesses.length;
+
+ return {
+ operationMinimumCost,
+ operationUnitCost,
+ operationLeadTime,
+ };
+ }
+
+ return {
+ operationMinimumCost: 0,
+ operationUnitCost: 0,
+ operationLeadTime: 0,
+ };
+ };
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 1c35c03d1d..0da9fa2eac 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -7908,12 +7908,11 @@ export type Database = {
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
makeMethodId: string
- operationCost: number
- operationLeadTime: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId: string | null
+ operationSupplierProcessId: string | null
operationType: Database["public"]["Enums"]["operationType"]
order: number
+ overheadRate: number
processId: string
setupTime: number
setupUnit: Database["public"]["Enums"]["factor"]
@@ -7933,12 +7932,11 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId: string
- operationCost?: number
- operationLeadTime?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId?: string | null
+ operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
order?: number
+ overheadRate?: number
processId: string
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
@@ -7958,12 +7956,11 @@ export type Database = {
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
makeMethodId?: string
- operationCost?: number
- operationLeadTime?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId?: string | null
+ operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
order?: number
+ overheadRate?: number
processId?: string
setupTime?: number
setupUnit?: Database["public"]["Enums"]["factor"]
@@ -8049,41 +8046,6 @@ export type Database = {
referencedRelation: "quoteOperationsWithMakeMethods"
referencedColumns: ["makeMethodId"]
},
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "methodOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
- referencedColumns: ["id"]
- },
{
foreignKeyName: "methodOperation_processId_fkey"
columns: ["processId"]
@@ -8147,6 +8109,20 @@ export type Database = {
referencedRelation: "workCenters"
referencedColumns: ["id"]
},
+ {
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
+ isOneToOne: false
+ referencedRelation: "supplierProcess"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
+ isOneToOne: false
+ referencedRelation: "supplierProcesses"
+ referencedColumns: ["id"]
+ },
]
}
methodOperationWorkInstruction: {
@@ -10026,6 +10002,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"]
id: string
name: string
+ processType: Database["public"]["Enums"]["processType"]
updatedAt: string | null
updatedBy: string | null
}
@@ -10037,6 +10014,7 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"]
id?: string
name: string
+ processType?: Database["public"]["Enums"]["processType"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -10048,6 +10026,7 @@ export type Database = {
defaultStandardFactor?: Database["public"]["Enums"]["factor"]
id?: string
name?: string
+ processType?: Database["public"]["Enums"]["processType"]
updatedAt?: string | null
updatedBy?: string | null
}
@@ -13499,11 +13478,12 @@ export type Database = {
laborUnit: Database["public"]["Enums"]["factor"]
machineTime: number
machineUnit: Database["public"]["Enums"]["factor"]
- operationCost: number
operationLeadTime: number
+ operationMinimumCost: number
operationOrder: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId: string | null
+ operationSupplierProcessId: string | null
operationType: Database["public"]["Enums"]["operationType"]
+ operationUnitCost: number
order: number
overheadRate: number
processId: string
@@ -13529,11 +13509,12 @@ export type Database = {
laborUnit?: Database["public"]["Enums"]["factor"]
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
- operationCost?: number
operationLeadTime?: number
+ operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId?: string | null
+ operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
+ operationUnitCost?: number
order?: number
overheadRate?: number
processId: string
@@ -13559,11 +13540,12 @@ export type Database = {
laborUnit?: Database["public"]["Enums"]["factor"]
machineTime?: number
machineUnit?: Database["public"]["Enums"]["factor"]
- operationCost?: number
operationLeadTime?: number
+ operationMinimumCost?: number
operationOrder?: Database["public"]["Enums"]["methodOperationOrder"]
- operationSupplierId?: string | null
+ operationSupplierProcessId?: string | null
operationType?: Database["public"]["Enums"]["operationType"]
+ operationUnitCost?: number
order?: number
overheadRate?: number
processId?: string
@@ -13642,38 +13624,17 @@ export type Database = {
referencedColumns: ["userId"]
},
{
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
isOneToOne: false
- referencedRelation: "contractors"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "partners"
- referencedColumns: ["supplierId"]
- },
- {
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "purchaseOrderSuppliers"
+ referencedRelation: "supplierProcess"
referencedColumns: ["id"]
},
{
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
isOneToOne: false
- referencedRelation: "supplier"
- referencedColumns: ["id"]
- },
- {
- foreignKeyName: "quoteOperation_operationSupplierId_fkey"
- columns: ["operationSupplierId"]
- isOneToOne: false
- referencedRelation: "suppliers"
+ referencedRelation: "supplierProcesses"
referencedColumns: ["id"]
},
{
@@ -17904,8 +17865,13 @@ export type Database = {
companyId: string
createdAt: string
createdBy: string
+ customFields: Json | null
+ id: string
+ leadTime: number
+ minimumCost: number
processId: string
supplierId: string
+ unitCost: number
updatedAt: string | null
updatedBy: string | null
}
@@ -17913,8 +17879,13 @@ export type Database = {
companyId: string
createdAt?: string
createdBy: string
+ customFields?: Json | null
+ id?: string
+ leadTime?: number
+ minimumCost?: number
processId: string
supplierId: string
+ unitCost?: number
updatedAt?: string | null
updatedBy?: string | null
}
@@ -17922,8 +17893,13 @@ export type Database = {
companyId?: string
createdAt?: string
createdBy?: string
+ customFields?: Json | null
+ id?: string
+ leadTime?: number
+ minimumCost?: number
processId?: string
supplierId?: string
+ unitCost?: number
updatedAt?: string | null
updatedBy?: string | null
}
@@ -19694,8 +19670,7 @@ export type Database = {
laborRate: number
locationId: string | null
name: string
- overheadRate: number | null
- quotingRate: number
+ overheadRate: number
requiredAbilityId: string | null
updatedAt: string | null
updatedBy: string | null
@@ -19712,8 +19687,7 @@ export type Database = {
laborRate?: number
locationId?: string | null
name: string
- overheadRate?: number | null
- quotingRate?: number
+ overheadRate?: number
requiredAbilityId?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -19730,8 +19704,7 @@ export type Database = {
laborRate?: number
locationId?: string | null
name?: string
- overheadRate?: number | null
- quotingRate?: number
+ overheadRate?: number
requiredAbilityId?: string | null
updatedAt?: string | null
updatedBy?: string | null
@@ -22279,6 +22252,8 @@ export type Database = {
defaultStandardFactor: Database["public"]["Enums"]["factor"] | null
id: string | null
name: string | null
+ processType: Database["public"]["Enums"]["processType"] | null
+ suppliers: Json | null
updatedAt: string | null
updatedBy: string | null
workCenters: Json | null
@@ -23635,9 +23610,14 @@ export type Database = {
machineTime: number | null
machineUnit: Database["public"]["Enums"]["factor"] | null
makeMethodId: string | null
+ operationLeadTime: number | null
+ operationMinimumCost: number | null
operationOrder:
| Database["public"]["Enums"]["methodOperationOrder"]
| null
+ operationSupplierProcessId: string | null
+ operationType: Database["public"]["Enums"]["operationType"] | null
+ operationUnitCost: number | null
order: number | null
overheadRate: number | null
processId: string | null
@@ -23715,6 +23695,20 @@ export type Database = {
referencedRelation: "userDefaults"
referencedColumns: ["userId"]
},
+ {
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
+ isOneToOne: false
+ referencedRelation: "supplierProcess"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "quoteOperation_operationSupplierProcessId_fkey"
+ columns: ["operationSupplierProcessId"]
+ isOneToOne: false
+ referencedRelation: "supplierProcesses"
+ referencedColumns: ["id"]
+ },
{
foreignKeyName: "quoteOperation_processId_fkey"
columns: ["processId"]
@@ -25679,6 +25673,172 @@ export type Database = {
},
]
}
+ supplierProcesses: {
+ Row: {
+ companyId: string | null
+ createdAt: string | null
+ createdBy: string | null
+ customFields: Json | null
+ id: string | null
+ leadTime: number | null
+ minimumCost: number | null
+ processId: string | null
+ processName: string | null
+ supplierId: string | null
+ unitCost: number | null
+ updatedAt: string | null
+ updatedBy: string | null
+ }
+ Relationships: [
+ {
+ foreignKeyName: "supplierProcess_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "company"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "companies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "customFieldTables"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_companyId_fkey"
+ columns: ["companyId"]
+ isOneToOne: false
+ referencedRelation: "integrations"
+ referencedColumns: ["companyId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_createdBy_fkey"
+ columns: ["createdBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_processId_fkey"
+ columns: ["processId"]
+ isOneToOne: false
+ referencedRelation: "process"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_processId_fkey"
+ columns: ["processId"]
+ isOneToOne: false
+ referencedRelation: "processes"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "supplier"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "contractors"
+ referencedColumns: ["supplierId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "partners"
+ referencedColumns: ["supplierId"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "purchaseOrderSuppliers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_supplierId_fkey"
+ columns: ["supplierId"]
+ isOneToOne: false
+ referencedRelation: "suppliers"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "user"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeeSummary"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employees"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "employeesAcrossCompanies"
+ referencedColumns: ["id"]
+ },
+ {
+ foreignKeyName: "supplierProcess_updatedBy_fkey"
+ columns: ["updatedBy"]
+ isOneToOne: false
+ referencedRelation: "userDefaults"
+ referencedColumns: ["userId"]
+ },
+ ]
+ }
suppliers: {
Row: {
accountManagerId: string | null
@@ -26178,7 +26338,6 @@ export type Database = {
name: string | null
overheadRate: number | null
processes: Json | null
- quotingRate: number | null
requiredAbilityId: string | null
updatedAt: string | null
updatedBy: string | null
@@ -26712,6 +26871,7 @@ export type Database = {
| "Consumable"
| "Fixture"
paymentTermCalculationMethod: "Net" | "End of Month" | "Day of Month"
+ processType: "Inside" | "Outside" | "Inside and Outside"
purchaseInvoiceStatus:
| "Draft"
| "Pending"
diff --git a/packages/database/supabase/migrations/20240823024502_outside-operations.sql b/packages/database/supabase/migrations/20240823024502_outside-operations.sql
index 6f13368d55..22d91f1394 100644
--- a/packages/database/supabase/migrations/20240823024502_outside-operations.sql
+++ b/packages/database/supabase/migrations/20240823024502_outside-operations.sql
@@ -1,35 +1,165 @@
+
CREATE TYPE "operationType" AS ENUM (
'Inside',
'Outside'
);
-ALTER TABLE "methodOperation"
- ADD COLUMN "operationType" "operationType" NOT NULL DEFAULT 'Inside',
- ADD COLUMN "operationLeadTime" INTEGER NOT NULL DEFAULT 0,
- ADD COLUMN "operationCost" NUMERIC(10,4) NOT NULL DEFAULT 0,
- ADD COLUMN "operationSupplierId" TEXT,
- ADD CONSTRAINT "methodOperation_operationSupplierId_fkey" FOREIGN KEY ("operationSupplierId") REFERENCES "supplier" ("id") ON DELETE SET NULL;
+DROP VIEW "workCenters";
+DROP VIEW "processes";
+DROP VIEW "quoteOperationsWithMakeMethods";
+
+COMMIT;
+
+ALTER TABLE "workCenter"
+ DROP COLUMN "quotingRate" CASCADE,
+ ADD COLUMN "overheadRate" NUMERIC(10,4) NOT NULL DEFAULT 0;
+
-ALTER TABLE "quoteOperation"
- ADD COLUMN "operationType" "operationType" NOT NULL DEFAULT 'Inside',
- ADD COLUMN "operationLeadTime" INTEGER NOT NULL DEFAULT 0,
- ADD COLUMN "operationCost" NUMERIC(10,4) NOT NULL DEFAULT 0,
- ADD COLUMN "operationSupplierId" TEXT,
- ADD CONSTRAINT "quoteOperation_operationSupplierId_fkey" FOREIGN KEY ("operationSupplierId") REFERENCES "supplier" ("id") ON DELETE SET NULL;
CREATE TABLE "supplierProcess" (
+ "id" TEXT NOT NULL DEFAULT xid(),
"supplierId" TEXT NOT NULL,
"processId" TEXT NOT NULL,
+ "minimumCost" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ "unitCost" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ "leadTime" NUMERIC(10,4) NOT NULL DEFAULT 0,
"companyId" TEXT NOT NULL,
+ "customFields" JSONB,
"createdBy" TEXT NOT NULL,
"createdAt" TIMESTAMPTZ NOT NULL DEFAULT now(),
"updatedBy" TEXT,
"updatedAt" TIMESTAMPTZ,
- CONSTRAINT "supplierProcess_pkey" PRIMARY KEY ("supplierId", "processId"),
+ CONSTRAINT "supplierProcess_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "supplierProcess_supplierId_processId_key" UNIQUE ("supplierId", "processId"),
CONSTRAINT "supplierProcess_supplierId_fkey" FOREIGN KEY ("supplierId") REFERENCES "supplier" ("id") ON DELETE CASCADE,
CONSTRAINT "supplierProcess_processId_fkey" FOREIGN KEY ("processId") REFERENCES "process" ("id") ON DELETE CASCADE,
CONSTRAINT "supplierProcess_companyId_fkey" FOREIGN KEY ("companyId") REFERENCES "company" ("id") ON DELETE CASCADE,
CONSTRAINT "supplierProcess_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT,
CONSTRAINT "supplierProcess_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE SET NULL
-);
\ No newline at end of file
+);
+
+ALTER TABLE "supplierProcess" ENABLE ROW LEVEL SECURITY;
+
+CREATE POLICY "Employees with purchasing, resources, or sales can read supplier processes"
+ ON "supplierProcess"
+ FOR SELECT
+ USING (
+ has_role('employee', "companyId") AND (
+ has_company_permission('purchasing_view', "companyId") OR
+ has_company_permission('resources_view', "companyId") OR
+ has_company_permission('sales_view', "companyId")
+ )
+ );
+
+CREATE POLICY "Employees with resources and purchasing can create supplier processes"
+ ON "supplierProcess"
+ FOR INSERT
+ WITH CHECK (
+ has_role('employee', "companyId") AND (
+ has_company_permission('purchasing_update', "companyId") OR
+ has_company_permission('resources_update', "companyId")
+ )
+ );
+
+CREATE POLICY "Employees with resources can update supplier processes"
+ ON "supplierProcess"
+ FOR UPDATE
+ USING (
+ has_role('employee', "companyId") AND has_company_permission('resources_update', "companyId")
+ );
+
+CREATE POLICY "Employees with resources or purchasing can delete supplier processes"
+ ON "supplierProcess"
+ FOR DELETE
+ USING (
+ has_role('employee', "companyId") AND (
+ has_company_permission('purchasing_delete', "companyId") OR
+ has_company_permission('resources_delete', "companyId")
+ )
+ );
+
+INSERT INTO "customFieldTable" ("table", "name", "module")
+VALUES ('supplierProcess', 'Supplier Process', 'Purchasing');
+
+CREATE VIEW "supplierProcesses" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ sp.*,
+ p.name as "processName"
+ FROM "supplierProcess" sp
+ INNER JOIN "process" p ON sp."processId" = p.id;
+
+
+
+ALTER TABLE "methodOperation"
+ ADD COLUMN "overheadRate" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ ADD COLUMN "operationType" "operationType" NOT NULL DEFAULT 'Inside',
+ ADD COLUMN "operationSupplierProcessId" TEXT,
+ ADD CONSTRAINT "quoteOperation_operationSupplierProcessId_fkey" FOREIGN KEY ("operationSupplierProcessId") REFERENCES "supplierProcess" ("id") ON DELETE SET NULL;;
+
+
+ALTER TABLE "quoteOperation"
+ ADD COLUMN "operationType" "operationType" NOT NULL DEFAULT 'Inside',
+ ADD COLUMN "operationMinimumCost" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ ADD COLUMN "operationLeadTime" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ ADD COLUMN "operationUnitCost" NUMERIC(10,4) NOT NULL DEFAULT 0,
+ ADD COLUMN "operationSupplierProcessId" TEXT,
+ ADD CONSTRAINT "quoteOperation_operationSupplierProcessId_fkey" FOREIGN KEY ("operationSupplierProcessId") REFERENCES "supplierProcess" ("id") ON DELETE SET NULL;
+
+
+CREATE TYPE "processType" AS ENUM ('Inside', 'Outside', 'Inside and Outside');
+
+ALTER TABLE "process"
+ ADD COLUMN "processType" "processType" NOT NULL DEFAULT 'Inside';
+
+CREATE OR REPLACE VIEW "workCenters" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ wc.*,
+ l.name as "locationName",
+ wcp.processes
+ FROM "workCenter" wc
+ LEFT JOIN location l
+ ON wc."locationId" = l.id
+ LEFT JOIN (
+ SELECT
+ "workCenterId",
+ jsonb_agg(jsonb_build_object('id', "processId", 'name', p.name)) as processes
+ FROM "workCenterProcess" wcp
+ INNER JOIN "process" p ON wcp."processId" = p.id
+ GROUP BY "workCenterId"
+ ) wcp ON wc.id = wcp."workCenterId";
+
+CREATE OR REPLACE VIEW "processes" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ p.*,
+ wcp."workCenters",
+ sp."suppliers"
+ FROM "process" p
+ LEFT JOIN (
+ SELECT
+ "processId",
+ jsonb_agg(jsonb_build_object('id', "workCenterId", 'name', wc.name)) as "workCenters"
+ FROM "workCenterProcess" wcp
+ INNER JOIN "workCenter" wc ON wcp."workCenterId" = wc.id
+ GROUP BY "processId"
+ ) wcp ON p.id = wcp."processId"
+ LEFT JOIN (
+ SELECT
+ "processId",
+ jsonb_agg(jsonb_build_object('id', sp."id", 'name', s.name)) as "suppliers"
+ FROM "supplierProcess" sp
+ INNER JOIN "supplier" s ON sp."supplierId" = s.id
+ GROUP BY "processId"
+ ) sp ON p.id = sp."processId";
+
+CREATE OR REPLACE VIEW "quoteOperationsWithMakeMethods" WITH(SECURITY_INVOKER=true) AS
+ SELECT
+ mm.id AS "makeMethodId",
+ qo.*
+ FROM "quoteOperation" qo
+ INNER JOIN "quoteMakeMethod" qmm
+ ON qo."quoteMakeMethodId" = qmm.id
+ LEFT JOIN "makeMethod" mm
+ ON qmm."itemId" = mm."itemId";
+
+
diff --git a/packages/utils/src/date.ts b/packages/utils/src/date.ts
index b78aaae250..87e5806acc 100644
--- a/packages/utils/src/date.ts
+++ b/packages/utils/src/date.ts
@@ -27,13 +27,25 @@ export function formatDate(
options?: Intl.DateTimeFormatOptions
) {
if (!dateString) return "";
- // @ts-expect-error
- const date = parseAbsolute(dateString);
+ try {
+ // @ts-expect-error
+ const date = parseAbsolute(dateString);
- return new Intl.DateTimeFormat(
- undefined,
- options || defaultFormatOptions
- ).format(date.toDate());
+ return new Intl.DateTimeFormat(
+ undefined,
+ options || defaultFormatOptions
+ ).format(date.toDate());
+ } catch {
+ try {
+ const date = new Date(dateString);
+ return new Intl.DateTimeFormat(
+ undefined,
+ options || defaultFormatOptions
+ ).format(date);
+ } catch {
+ return dateString;
+ }
+ }
}
export function formatRelativeTime(isoString: string) {