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.

refactor: batch updates for grid and table

Brad Barbinc464fc6f28c1
diff --git a/apps/carbon/app/components/Editable/EditableList.tsx b/apps/carbon/app/components/Editable/EditableList.tsx
index c7cd50868c..12f1c4e32b 100644
--- a/apps/carbon/app/components/Editable/EditableList.tsx
+++ b/apps/carbon/app/components/Editable/EditableList.tsx
@@ -19,21 +19,21 @@ const EditableList =
onError,
onUpdate,
}: EditableTableCellComponentProps<T>) => {
- const onChange = async (value: string) => {
+ const onChange = async (newValue: string) => {
// this is the optimistic update on the FE
- onUpdate(accessorKey, value);
+ onUpdate({ [accessorKey]: newValue });
// the is the actual update on the BE
- mutation(accessorKey, value, row)
+ mutation(accessorKey, newValue, row)
.then(({ error }) => {
if (error) {
onError();
- onUpdate(accessorKey, value);
+ onUpdate({ [accessorKey]: value });
}
})
.catch(() => {
onError();
- onUpdate(accessorKey, value);
+ onUpdate({ [accessorKey]: value });
});
};
diff --git a/apps/carbon/app/components/Editable/EditableNumber.tsx b/apps/carbon/app/components/Editable/EditableNumber.tsx
index 5d63656f40..c176eb4746 100644
--- a/apps/carbon/app/components/Editable/EditableNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditableNumber.tsx
@@ -22,7 +22,7 @@ const EditableNumber =
const updateNumber = async (newValue: string) => {
const numberValue = Number(newValue);
// this is the optimistic update on the FE
- onUpdate(accessorKey, numberValue);
+ onUpdate({ [accessorKey]: numberValue });
// the is the actual update on the BE
// @ts-ignore
@@ -30,12 +30,12 @@ const EditableNumber =
.then(({ error }) => {
if (error) {
onError();
- onUpdate(accessorKey, numberValue);
+ onUpdate({ [accessorKey]: value });
}
})
.catch(() => {
onError();
- onUpdate(accessorKey, numberValue);
+ onUpdate({ [accessorKey]: value });
});
};
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
index bf65bbd342..bc01bb54b8 100644
--- a/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditablePurchaseInvoiceLineNumber.tsx
@@ -50,8 +50,10 @@ const EditablePurchaseInvoiceLineNumber =
.eq("number", accountNumber)
.single();
- onUpdate("description", account.data?.name ?? "");
- onUpdate("accountNumber", accountNumber);
+ onUpdate({
+ description: account.data?.name ?? "",
+ accountNumber: accountNumber,
+ });
try {
const { error } = await client
@@ -96,12 +98,14 @@ const EditablePurchaseInvoiceLineNumber =
return;
}
- onUpdate("partId", partId);
- onUpdate("description", part.data?.name);
- onUpdate("unitOfMeasureCode", part.data?.unitOfMeasureCode ?? null);
- onUpdate("locationId", options.defaultLocationId);
- onUpdate("shelfId", shelf.data?.defaultShelfId ?? null);
- onUpdate("unitPrice", cost.data?.unitCost ?? null);
+ onUpdate({
+ partId,
+ description: part.data?.name,
+ unitOfMeasureCode: part.data?.unitOfMeasureCode ?? null,
+ locationId: options.defaultLocationId!,
+ shelfId: shelf.data?.defaultShelfId ?? null,
+ unitPrice: cost.data?.unitCost ?? null,
+ });
try {
const { error } = await client
@@ -139,8 +143,10 @@ const EditablePurchaseInvoiceLineNumber =
return;
}
- onUpdate("serviceId", serviceId);
- onUpdate("description", service.data?.name);
+ onUpdate({
+ serviceId,
+ description: service.data?.name,
+ });
try {
const { error } = await client
diff --git a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
index 90c56a589a..f24a951736 100644
--- a/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditablePurchaseOrderLineNumber.tsx
@@ -50,8 +50,10 @@ const EditablePurchaseOrderLineNumber =
.eq("number", accountNumber)
.single();
- onUpdate("description", account.data?.name ?? "");
- onUpdate("accountNumber", accountNumber);
+ onUpdate({
+ description: account.data?.name ?? "",
+ accountNumber: accountNumber,
+ });
try {
const { error } = await client
@@ -96,12 +98,14 @@ const EditablePurchaseOrderLineNumber =
return;
}
- onUpdate("partId", partId);
- onUpdate("description", part.data?.name);
- onUpdate("unitOfMeasureCode", part.data?.unitOfMeasureCode ?? null);
- onUpdate("locationId", options.defaultLocationId);
- onUpdate("shelfId", shelf.data?.defaultShelfId ?? null);
- onUpdate("unitPrice", cost.data?.unitCost ?? null);
+ onUpdate({
+ partId: partId,
+ description: part.data?.name,
+ unitOfMeasureCode: part.data?.unitOfMeasureCode ?? null,
+ locationId: options.defaultLocationId,
+ shelfId: shelf.data?.defaultShelfId ?? null,
+ unitPrice: cost.data?.unitCost ?? null,
+ });
try {
const { error } = await client
@@ -139,8 +143,10 @@ const EditablePurchaseOrderLineNumber =
return;
}
- onUpdate("serviceId", serviceId);
- onUpdate("description", service.data?.name);
+ onUpdate({
+ serviceId: serviceId,
+ description: service.data?.name,
+ });
try {
const { error } = await client
diff --git a/apps/carbon/app/components/Editable/EditableText.tsx b/apps/carbon/app/components/Editable/EditableText.tsx
index 089d078017..35f402f108 100644
--- a/apps/carbon/app/components/Editable/EditableText.tsx
+++ b/apps/carbon/app/components/Editable/EditableText.tsx
@@ -21,19 +21,19 @@ const EditableText =
}: EditableTableCellComponentProps<T>) => {
const updateText = async (newValue: string) => {
// this is the optimistic update on the FE
- onUpdate(accessorKey, newValue);
+ onUpdate({ [accessorKey]: newValue });
// the is the actual update on the BE
mutation(accessorKey, newValue, row)
.then(({ error }) => {
if (error) {
onError();
- onUpdate(accessorKey, value);
+ onUpdate({ [accessorKey]: value });
}
})
.catch(() => {
onError();
- onUpdate(accessorKey, value);
+ onUpdate({ [accessorKey]: value });
});
};
diff --git a/apps/carbon/app/components/Editable/types.ts b/apps/carbon/app/components/Editable/types.ts
index 848313fd18..180c6cf05e 100644
--- a/apps/carbon/app/components/Editable/types.ts
+++ b/apps/carbon/app/components/Editable/types.ts
@@ -6,7 +6,7 @@ export type EditableTableCellComponentProps<T> = {
value: unknown;
row: T;
accessorKey: string;
- onUpdate: (columnId: string, value: unknown) => void;
+ onUpdate: (updates: Record<string, unknown>) => void;
onError: () => void;
};
@@ -15,6 +15,6 @@ export type Position = null | { row: number; column: number };
declare module "@tanstack/react-table" {
interface TableMeta<TData> {
editableComponents?: Record<string, EditableTableCellComponent<TData>>;
- updateData?: (rowIndex: number, columnId: string, value: unknown) => void;
+ updateData?: (rowIndex: number, updates: Record<string, unknown>) => void;
}
}
diff --git a/apps/carbon/app/components/Grid/Grid.tsx b/apps/carbon/app/components/Grid/Grid.tsx
index 1744eb9fb1..9e349dc89c 100644
--- a/apps/carbon/app/components/Grid/Grid.tsx
+++ b/apps/carbon/app/components/Grid/Grid.tsx
@@ -75,28 +75,6 @@ const Grid = <T extends object>({
defaultColumnOrder ?? []
);
- /* Sorting */
- // const { isSorted, toggleSortBy } = useSort();
-
- // const columnAccessors = useMemo(
- // () =>
- // columns.reduce<Record<string, string>>((acc, column) => {
- // const accessorKey: string | undefined = getAccessorKey(column);
- // if (accessorKey?.includes("_"))
- // throw new Error(
- // `Invalid accessorKey ${accessorKey}. Cannot contain '_'`
- // );
- // if (accessorKey && column.header && typeof column.header === "string") {
- // return {
- // ...acc,
- // [accessorKey]: column.header,
- // };
- // }
- // return acc;
- // }, {}),
- // [columns]
- // );
-
const table = useReactTable({
data: internalData,
columns: columns,
@@ -110,22 +88,28 @@ const Grid = <T extends object>({
meta: {
// These are not part of the standard API, but are accessible via table.options.meta
editableComponents,
- updateData: (rowIndex, columnId, value) => {
+ updateData: (rowIndex, updates) => {
setInternalData((previousData) => {
const newData = previousData.map((row, index) => {
if (index === rowIndex) {
- if (columnId.includes("_") && !(columnId in row)) {
- updateNestedProperty(row, columnId, value);
- return row;
- } else {
- return {
- ...row,
- [columnId]: value,
- };
- }
+ return Object.entries(updates).reduce(
+ (newRow, [columnId, value]) => {
+ if (columnId.includes("_") && !(columnId in newRow)) {
+ updateNestedProperty(newRow, columnId, value);
+ return newRow;
+ } else {
+ return {
+ ...newRow,
+ [columnId]: value,
+ };
+ }
+ },
+ row
+ );
}
return row;
});
+
onDataChange?.(newData);
return newData;
@@ -201,9 +185,9 @@ const Grid = <T extends object>({
);
const onCellUpdate = useCallback(
- (rowIndex: number) => (columnId: string, value: unknown) =>
+ (rowIndex: number) => (updates: Record<string, unknown>) =>
table.options.meta?.updateData
- ? table.options.meta?.updateData(rowIndex, columnId, value)
+ ? table.options.meta?.updateData(rowIndex, updates)
: undefined,
[table]
);
diff --git a/apps/carbon/app/components/Grid/components/Cell.tsx b/apps/carbon/app/components/Grid/components/Cell.tsx
index 0359ccc3d4..0296d3d29a 100644
--- a/apps/carbon/app/components/Grid/components/Cell.tsx
+++ b/apps/carbon/app/components/Grid/components/Cell.tsx
@@ -14,7 +14,7 @@ type CellProps<T> = {
isEditing: boolean;
isSelected: boolean;
onClick?: () => void;
- onUpdate?: (columnId: string, value: unknown) => void;
+ onUpdate?: (updates: Record<string, unknown>) => void;
};
const Cell = <T extends object>({
diff --git a/apps/carbon/app/components/Grid/components/Row.tsx b/apps/carbon/app/components/Grid/components/Row.tsx
index 147c5b2acd..eae7171ee2 100644
--- a/apps/carbon/app/components/Grid/components/Row.tsx
+++ b/apps/carbon/app/components/Grid/components/Row.tsx
@@ -18,7 +18,7 @@ type RowProps<T> = {
rowIsSelected: boolean;
rowRef?: MutableRefObject<HTMLTableRowElement | null>;
onCellClick: (row: number, column: number) => void;
- onCellUpdate: (row: number) => (columnId: string, value: unknown) => void;
+ onCellUpdate: (row: number) => (updates: Record<string, unknown>) => void;
onEditRow?: (row: T) => void;
};
@@ -34,6 +34,8 @@ const Row = <T extends object>({
onCellClick,
onCellUpdate,
}: RowProps<T>) => {
+ const onUpdate = onCellUpdate(row.index);
+
return (
<Tr
key={row.id}
@@ -56,7 +58,7 @@ const Row = <T extends object>({
isSelected={isSelected}
isEditing={isEditing}
onClick={() => onCellClick(cell.row.index, columnIndex)}
- onUpdate={onCellUpdate(cell.row.index)}
+ onUpdate={onUpdate}
/>
);
})}
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index cc4c869fe2..876f02d3a2 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -160,19 +160,23 @@ const Table = <T extends object>({
meta: {
// These are not part of the standard API, but are accessible via table.options.meta
editableComponents,
- updateData: (rowIndex, columnId, value) => {
+ updateData: (rowIndex, updates) => {
setInternalData((previousData) =>
previousData.map((row, index) => {
if (index === rowIndex) {
- if (columnId.includes("_") && !(columnId in row)) {
- updateNestedProperty(row, columnId, value);
- return row;
- } else {
- return {
- ...row,
- [columnId]: value,
- };
- }
+ let newRow = { ...row };
+ Object.entries(updates).forEach(([columnId, value]) => {
+ if (columnId.includes("_") && !(columnId in newRow)) {
+ updateNestedProperty(newRow, columnId, value);
+ return newRow;
+ } else {
+ return {
+ ...newRow,
+ [columnId]: value,
+ };
+ }
+ });
+ return newRow;
}
return row;
})
@@ -263,11 +267,10 @@ const Table = <T extends object>({
);
const onCellUpdate = useCallback(
- (rowIndex: number) => (columnId: string, value: unknown) => {
- return table.options.meta?.updateData
- ? table.options.meta?.updateData(rowIndex, columnId, value)
- : undefined;
- },
+ (rowIndex: number) => (updates: Record<string, unknown>) =>
+ table.options.meta?.updateData
+ ? table.options.meta?.updateData(rowIndex, updates)
+ : undefined,
[table]
);
diff --git a/apps/carbon/app/components/Table/components/Cell.tsx b/apps/carbon/app/components/Table/components/Cell.tsx
index 05fa18077f..84a7624c69 100644
--- a/apps/carbon/app/components/Table/components/Cell.tsx
+++ b/apps/carbon/app/components/Table/components/Cell.tsx
@@ -16,7 +16,7 @@ type CellProps<T> = {
isRowSelected: boolean;
isSelected: boolean;
onClick?: () => void;
- onUpdate?: (columnId: string, value: unknown) => void;
+ onUpdate?: (updates: Record<string, unknown>) => void;
};
const Cell = <T extends object>({
diff --git a/apps/carbon/app/components/Table/components/Row.tsx b/apps/carbon/app/components/Table/components/Row.tsx
index f6a3a9a310..bb072945f6 100644
--- a/apps/carbon/app/components/Table/components/Row.tsx
+++ b/apps/carbon/app/components/Table/components/Row.tsx
@@ -21,7 +21,7 @@ type RowProps<T> = ComponentProps<typeof Tr> & {
rowIsSelected: boolean;
withColumnOrdering: boolean;
onCellClick: (row: number, column: number) => void;
- onCellUpdate: (row: number) => (columnId: string, value: unknown) => void;
+ onCellUpdate: (row: number) => (updates: Record<string, unknown>) => void;
};
const Row = <T extends object>({
@@ -40,6 +40,8 @@ const Row = <T extends object>({
onCellUpdate,
...props
}: RowProps<T>) => {
+ const onUpdate = isEditMode ? onCellUpdate(row.index) : undefined;
+
return (
<Tr
key={row.id}
@@ -84,7 +86,7 @@ const Row = <T extends object>({
)
: undefined
}
- onUpdate={isEditMode ? onCellUpdate(cell.row.index) : undefined}
+ onUpdate={onUpdate}
/>
);
})}
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLines.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLines.tsx
new file mode 100644
index 0000000000..f0bf1793fa
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLines.tsx
@@ -0,0 +1,153 @@
+import {
+ Button,
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+} from "@carbon/react";
+import { Link, Outlet, useNavigate, useParams } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useMemo } from "react";
+import { BsFillPenFill } from "react-icons/bs";
+import { IoMdTrash } from "react-icons/io";
+import { MdMoreHoriz } from "react-icons/md";
+import {
+ EditableNumber,
+ // EditableQuotationPart,
+ EditableText,
+} from "~/components/Editable";
+import Grid from "~/components/Grid";
+import { useRouteData } from "~/hooks";
+import type { Quotation, QuotationLine } from "~/modules/sales";
+import type { ListItem } from "~/types";
+import { path } from "~/utils/path";
+import useQuotationLines from "./useQuotationLines";
+
+const QuotationLines = () => {
+ const { id } = useParams();
+ if (!id) throw new Error("id not found");
+
+ const navigate = useNavigate();
+
+ const routeData = useRouteData<{
+ quotation: Quotation;
+ quotationLines: QuotationLine[];
+ locations: ListItem[];
+ }>(path.to.quote(id));
+
+ const { canEdit, canDelete, onCellEdit } = useQuotationLines();
+
+ const isEditable = ["Draft"].includes(routeData?.quotation?.status ?? "");
+
+ const columns = useMemo<ColumnDef<QuotationLine>[]>(() => {
+ return [
+ {
+ header: "Line",
+ cell: ({ row }) => row.index + 1,
+ },
+ {
+ accessorKey: "partId",
+ header: "Part",
+ cell: ({ row }) => {
+ <HStack className="justify-between min-w-[100px]">
+ <span>{row.original.partId}</span>
+ <div className="relative w-6 h-5">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Edit quote line"
+ icon={<MdMoreHoriz />}
+ size="md"
+ className="absolute right-[-1px] top-[-6px]"
+ variant="ghost"
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ onClick={() => navigate(row.original.id!)}
+ disabled={!isEditable || !canEdit}
+ >
+ <DropdownMenuIcon icon={<BsFillPenFill />} />
+ Edit Line
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ onClick={() => navigate(`delete/${row.original.id}`)}
+ disabled={!isEditable || !canDelete}
+ >
+ <DropdownMenuIcon icon={<IoMdTrash />} />
+ Delete Line
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </HStack>;
+ },
+ },
+ {
+ accessorKey: "description",
+ header: "Description",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "quantity",
+ header: "Quantity",
+ cell: (item) => item.getValue(),
+ },
+ ];
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [navigate]);
+
+ const editableComponents = useMemo(
+ () => ({
+ description: EditableText(onCellEdit),
+ quantity: EditableNumber(onCellEdit),
+ unitPrice: EditableNumber(onCellEdit),
+ // partId: EditableQuotationPart(onCellEdit, {
+ // client: supabase,
+ // parts: partOptions,
+ // }),
+ }),
+ [onCellEdit]
+ );
+
+ return (
+ <>
+ <Card className="w-full h-full min-h-[50vh]">
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Quotation Lines</CardTitle>
+ </CardHeader>
+ <CardAction>
+ {canEdit && isEditable && (
+ <Button asChild>
+ <Link to="new">New</Link>
+ </Button>
+ )}
+ </CardAction>
+ </HStack>
+
+ <CardContent>
+ <Grid<QuotationLine>
+ data={routeData?.quotationLines ?? []}
+ columns={columns}
+ canEdit={canEdit && isEditable}
+ editableComponents={editableComponents}
+ onNewRow={canEdit && isEditable ? () => navigate("new") : undefined}
+ />
+ </CardContent>
+ </Card>
+ <Outlet />
+ </>
+ );
+};
+
+export default QuotationLines;
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/index.ts b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/index.ts
new file mode 100644
index 0000000000..6565135735
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/index.ts
@@ -0,0 +1,3 @@
+import QuotationLines from "./QuotationLines";
+
+export default QuotationLines;
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationLines.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationLines.tsx
new file mode 100644
index 0000000000..6a3f82cd09
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationLines.tsx
@@ -0,0 +1,46 @@
+import { useCallback, useMemo } from "react";
+import { usePermissions, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { QuotationLine } from "~/modules/sales";
+import { useParts } from "~/stores/parts";
+
+export default function useQuotationLines() {
+ const { id: userId } = useUser();
+ const { supabase } = useSupabase();
+ const permissions = usePermissions();
+
+ const canEdit = permissions.can("update", "sales");
+ const canDelete = permissions.can("delete", "sales");
+
+ const [parts] = useParts();
+ const partOptions = useMemo(
+ () =>
+ parts.map((p) => ({
+ value: p.id,
+ label: p.id,
+ })),
+ [parts]
+ );
+
+ const onCellEdit = useCallback(
+ async (id: string, value: unknown, row: QuotationLine) => {
+ if (!supabase) throw new Error("Supabase client not found");
+ return await supabase
+ .from("quoteLine")
+ .update({
+ [id]: value,
+ updatedBy: userId,
+ })
+ .eq("id", row.id!);
+ },
+ [supabase, userId]
+ );
+
+ return {
+ canDelete,
+ canEdit,
+ partOptions,
+ supabase,
+ onCellEdit,
+ };
+}
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/index.ts b/apps/carbon/app/modules/sales/ui/Quotation/index.ts
index ece229b2a8..01496b611d 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/index.ts
+++ b/apps/carbon/app/modules/sales/ui/Quotation/index.ts
@@ -1,6 +1,7 @@
import QuotationDocuments from "./QuotationDocuments";
import QuotationForm from "./QuotationForm";
import QuotationHeader from "./QuotationHeader";
+import QuotationLines from "./QuotationLines";
import QuotationSidebar from "./QuotationSidebar";
import QuotationStatus from "./QuotationStatus";
import { useQuotationTotals } from "./useQuotationTotals";
@@ -9,6 +10,7 @@ export {
QuotationDocuments,
QuotationForm,
QuotationHeader,
+ QuotationLines,
QuotationSidebar,
QuotationStatus,
useQuotationTotals,
diff --git a/apps/carbon/app/routes/x+/quote+/$id.lines.tsx b/apps/carbon/app/routes/x+/quote+/$id.lines.tsx
new file mode 100644
index 0000000000..b0c132e5a9
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$id.lines.tsx
@@ -0,0 +1,11 @@
+import { Outlet } from "@remix-run/react";
+import { QuotationLines } from "~/modules/sales";
+
+export default function QuotationLinesRoute() {
+ return (
+ <div className="flex flex-col w-full space-x-4 space-y-4">
+ <QuotationLines />
+ <Outlet />
+ </div>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$orderId.lines.$lineId.tsx b/apps/carbon/app/routes/x+/quote+/$orderId.lines.$lineId.tsx
new file mode 100644
index 0000000000..3647b65312
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$orderId.lines.$lineId.tsx
@@ -0,0 +1,121 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import type { PurchaseOrderLineType } from "~/modules/purchasing";
+import {
+ PurchaseOrderLineForm,
+ getPurchaseOrderLine,
+ purchaseOrderLineValidator,
+ upsertPurchaseOrderLine,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { assertIsPost, notFound } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ view: "parts",
+ role: "employee",
+ });
+
+ const { lineId } = params;
+ if (!lineId) throw notFound("lineId not found");
+
+ const purchaseOrderLine = await getPurchaseOrderLine(client, lineId);
+
+ return json({
+ purchaseOrderLine: purchaseOrderLine?.data ?? null,
+ });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const { orderId, lineId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+ if (!lineId) throw new Error("Could not find lineId");
+
+ const validation = await purchaseOrderLineValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ if (data.purchaseOrderLineType === "Part") {
+ data.accountNumber = undefined;
+ data.assetId = undefined;
+ data.serviceId = undefined;
+ } else if (data.purchaseOrderLineType === "Service") {
+ data.accountNumber = undefined;
+ data.assetId = undefined;
+ data.partId = undefined;
+ } else if (data.purchaseOrderLineType === "G/L Account") {
+ data.assetId = undefined;
+ data.partId = undefined;
+ data.serviceId = undefined;
+ } else if (data.purchaseOrderLineType === "Fixed Asset") {
+ data.accountNumber = undefined;
+ data.partId = undefined;
+ data.serviceId = undefined;
+ } else if (data.purchaseOrderLineType === "Comment") {
+ data.accountNumber = undefined;
+ data.assetId = undefined;
+ data.partId = undefined;
+ data.serviceId = undefined;
+ }
+
+ const updatePurchaseOrderLine = await upsertPurchaseOrderLine(client, {
+ id: lineId,
+ ...data,
+ updatedBy: userId,
+ });
+
+ if (updatePurchaseOrderLine.error) {
+ return redirect(
+ path.to.purchaseOrderLines(orderId),
+ await flash(
+ request,
+ error(
+ updatePurchaseOrderLine.error,
+ "Failed to update purchase order line"
+ )
+ )
+ );
+ }
+
+ return redirect(path.to.purchaseOrderLines(orderId));
+}
+
+export default function EditPurchaseOrderLineRoute() {
+ const { purchaseOrderLine } = useLoaderData<typeof loader>();
+
+ const initialValues = {
+ id: purchaseOrderLine?.id ?? undefined,
+ purchaseOrderId: purchaseOrderLine?.purchaseOrderId ?? "",
+ purchaseOrderLineType:
+ purchaseOrderLine?.purchaseOrderLineType ??
+ ("Part" as PurchaseOrderLineType),
+ partId: purchaseOrderLine?.partId ?? "",
+ serviceId: purchaseOrderLine?.serviceId ?? "",
+ accountNumber: purchaseOrderLine?.accountNumber ?? "",
+ assetId: purchaseOrderLine?.assetId ?? "",
+ description: purchaseOrderLine?.description ?? "",
+ purchaseQuantity: purchaseOrderLine?.purchaseQuantity ?? 1,
+ unitPrice: purchaseOrderLine?.unitPrice ?? 0,
+ setupPrice: purchaseOrderLine?.setupPrice ?? 0,
+ unitOfMeasureCode: purchaseOrderLine?.unitOfMeasureCode ?? "",
+ shelfId: purchaseOrderLine?.shelfId ?? "",
+ };
+
+ return <PurchaseOrderLineForm initialValues={initialValues} />;
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$orderId.lines.delete.$lineId.tsx b/apps/carbon/app/routes/x+/quote+/$orderId.lines.delete.$lineId.tsx
new file mode 100644
index 0000000000..b7c86bf169
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$orderId.lines.delete.$lineId.tsx
@@ -0,0 +1,87 @@
+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
+import { json, redirect } from "@remix-run/node";
+import { useLoaderData, useNavigate, useParams } from "@remix-run/react";
+import { ConfirmDelete } from "~/components/Modals";
+import {
+ deletePurchaseOrderLine,
+ getPurchaseOrderLine,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+import { flash } from "~/services/session.server";
+import { notFound } from "~/utils/http";
+import { path } from "~/utils/path";
+import { error, success } from "~/utils/result";
+
+export async function loader({ request, params }: LoaderFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+ const { lineId, orderId } = params;
+ if (!lineId) throw notFound("lineId not found");
+ if (!orderId) throw notFound("orderId not found");
+
+ const purchaseOrderLine = await getPurchaseOrderLine(client, lineId);
+ if (purchaseOrderLine.error) {
+ return redirect(
+ path.to.purchaseOrderLines(orderId),
+ await flash(
+ request,
+ error(purchaseOrderLine.error, "Failed to get purchase order line")
+ )
+ );
+ }
+
+ return json({ purchaseOrderLine: purchaseOrderLine.data });
+}
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ const { client } = await requirePermissions(request, {
+ delete: "purchasing",
+ });
+
+ const { lineId, orderId } = params;
+ if (!lineId) throw notFound("Could not find lineId");
+ if (!orderId) throw notFound("Could not find orderId");
+
+ const { error: deleteTypeError } = await deletePurchaseOrderLine(
+ client,
+ lineId
+ );
+ if (deleteTypeError) {
+ return redirect(
+ path.to.purchaseOrderLines(orderId),
+ await flash(
+ request,
+ error(deleteTypeError, "Failed to delete purchase order line")
+ )
+ );
+ }
+
+ return redirect(
+ path.to.purchaseOrderLines(orderId),
+ await flash(request, success("Successfully deleted purchase order line"))
+ );
+}
+
+export default function DeletePurchaseOrderLineRoute() {
+ const { lineId, orderId } = useParams();
+ const { purchaseOrderLine } = useLoaderData<typeof loader>();
+ const navigate = useNavigate();
+
+ if (!purchaseOrderLine) return null;
+ if (!lineId) throw notFound("Could not find lineId");
+ if (!orderId) throw notFound("Could not find orderId");
+
+ const onCancel = () => navigate(path.to.purchaseOrderLines(orderId));
+
+ return (
+ <ConfirmDelete
+ action={path.to.deletePurchaseOrderLine(orderId, lineId)}
+ name="Purchase Order Line"
+ text={`Are you sure you want to delete the purchase order line for ${
+ purchaseOrderLine.purchaseQuantity ?? 0
+ } ${purchaseOrderLine.description ?? ""}? This cannot be undone.`}
+ onCancel={onCancel}
+ />
+ );
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$orderId.lines.new.tsx b/apps/carbon/app/routes/x+/quote+/$orderId.lines.new.tsx
new file mode 100644
index 0000000000..90b961ef88
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$orderId.lines.new.tsx
@@ -0,0 +1,74 @@
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useParams } from "@remix-run/react";
+import { validationError } from "remix-validated-form";
+import type { PurchaseOrderLineType } from "~/modules/purchasing";
+import {
+ PurchaseOrderLineForm,
+ purchaseOrderLineValidator,
+ upsertPurchaseOrderLine,
+} from "~/modules/purchasing";
+import { requirePermissions } from "~/services/auth";
+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, userId } = await requirePermissions(request, {
+ create: "purchasing",
+ });
+
+ const { orderId } = params;
+ if (!orderId) throw new Error("Could not find orderId");
+
+ const validation = await purchaseOrderLineValidator.validate(
+ await request.formData()
+ );
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createPurchaseOrderLine = await upsertPurchaseOrderLine(client, {
+ ...data,
+ createdBy: userId,
+ });
+
+ if (createPurchaseOrderLine.error) {
+ return redirect(
+ path.to.purchaseOrderLines(orderId),
+ await flash(
+ request,
+ error(
+ createPurchaseOrderLine.error,
+ "Failed to create purchase order line."
+ )
+ )
+ );
+ }
+
+ return redirect(path.to.purchaseOrderLines(orderId));
+}
+
+export default function NewPurchaseOrderLineRoute() {
+ const { orderId } = useParams();
+
+ if (!orderId) throw new Error("Could not find purchase order id");
+
+ const initialValues = {
+ purchaseOrderId: orderId,
+ purchaseOrderLineType: "Part" as PurchaseOrderLineType,
+ partId: "",
+ purchaseQuantity: 1,
+ unitPrice: 0,
+ setupPrice: 0,
+ unitOfMeasureCode: "",
+ shelfId: "",
+ };
+
+ return <PurchaseOrderLineForm initialValues={initialValues} />;
+}