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: quote quantities

Brad Barbine0c97059421b
diff --git a/apps/carbon/app/components/Editable/EditableNumber.tsx b/apps/carbon/app/components/Editable/EditableNumber.tsx
index c176eb4746..27c491f075 100644
--- a/apps/carbon/app/components/Editable/EditableNumber.tsx
+++ b/apps/carbon/app/components/Editable/EditableNumber.tsx
@@ -1,4 +1,5 @@
/* eslint-disable react/display-name */
+import type { NumberFieldProps } from "@carbon/react";
import { Input, NumberField } from "@carbon/react";
import type { PostgrestSingleResponse } from "@supabase/supabase-js";
import type { FocusEvent, KeyboardEvent } from "react";
@@ -10,7 +11,8 @@ const EditableNumber =
accessorKey: string,
newValue: string,
row: T
- ) => Promise<PostgrestSingleResponse<unknown>>
+ ) => Promise<PostgrestSingleResponse<unknown>>,
+ numberFieldProps?: NumberFieldProps
) =>
({
value,
@@ -56,10 +58,10 @@ const EditableNumber =
};
return (
- <NumberField defaultValue={value as number}>
+ <NumberField {...numberFieldProps} defaultValue={value as number}>
<Input
size="sm"
- className="w-full rounded-none"
+ className="w-full rounded-none ring-offset-0"
autoFocus
onKeyDown={onKeyDown}
onBlur={onBlur}
diff --git a/apps/carbon/app/components/Form/Submit.tsx b/apps/carbon/app/components/Form/Submit.tsx
index 2bc5ed63ff..b1b2f4cfe6 100644
--- a/apps/carbon/app/components/Form/Submit.tsx
+++ b/apps/carbon/app/components/Form/Submit.tsx
@@ -1,25 +1,26 @@
import type { ButtonProps } from "@carbon/react";
import { Button } from "@carbon/react";
-import type { PropsWithChildren } from "react";
+import { forwardRef } from "react";
import { useIsSubmitting } from "remix-validated-form";
-export const Submit = ({
- formId,
- children,
- ...props
-}: PropsWithChildren<ButtonProps & { formId?: string; text?: string }>) => {
- const isSubmitting = useIsSubmitting(formId);
- return (
- <Button
- form={formId}
- type="submit"
- isLoading={isSubmitting}
- isDisabled={isSubmitting}
- {...props}
- >
- {children}
- </Button>
- );
-};
+type SubmitProps = ButtonProps & { formId?: string; text?: string };
+export const Submit = forwardRef<HTMLButtonElement, SubmitProps>(
+ ({ formId, children, ...props }, ref) => {
+ const isSubmitting = useIsSubmitting(formId);
+ return (
+ <Button
+ ref={ref}
+ form={formId}
+ type="submit"
+ isLoading={isSubmitting}
+ isDisabled={isSubmitting}
+ {...props}
+ >
+ {children}
+ </Button>
+ );
+ }
+);
+Submit.displayName = "Submit";
export default Submit;
diff --git a/apps/carbon/app/components/Grid/components/Cell.tsx b/apps/carbon/app/components/Grid/components/Cell.tsx
index 765ca12b8b..46a410e3de 100644
--- a/apps/carbon/app/components/Grid/components/Cell.tsx
+++ b/apps/carbon/app/components/Grid/components/Cell.tsx
@@ -60,7 +60,7 @@ const Cell = <T extends object>({
onFocus={onFocus}
>
{isSelected && isEditing && hasEditableTableCellComponent ? (
- <div className="mx-[-1rem] my-[-0.5rem]">
+ <div className="mx-[-0.65rem] my-[-0.25rem]">
{hasEditableTableCellComponent
? flexRender(editableCell, {
accessorKey,
diff --git a/apps/carbon/app/components/Table/components/Cell.tsx b/apps/carbon/app/components/Table/components/Cell.tsx
index b5b45fe44a..55420cad00 100644
--- a/apps/carbon/app/components/Table/components/Cell.tsx
+++ b/apps/carbon/app/components/Table/components/Cell.tsx
@@ -64,7 +64,7 @@ const Cell = <T extends object>({
onFocus={onFocus}
>
{isSelected && isEditing && hasEditableTableCellComponent ? (
- <div className="mx-[-1rem] my-[-0.5rem]">
+ <div className="mx-[-0.65rem] my-[-0.25rem]">
{hasEditableTableCellComponent
? flexRender(editableCell, {
accessorKey,
diff --git a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
index 27472a529e..11ebab8149 100644
--- a/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
+++ b/apps/carbon/app/modules/parts/ui/Part/PartForm.tsx
@@ -141,7 +141,6 @@ const PartForm = ({ initialValues }: PartFormProps) => {
<Input name="id" label="Part ID" isReadOnly />
) : (
<InputControlled
- autoFocus
name="id"
label="Part ID"
helperText="Use ... to get the next part ID"
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index 509afadab8..f4f453b7c1 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -291,6 +291,16 @@ export async function getQuoteLines(
return client.from("quoteLine").select("*").eq("quoteId", quoteId);
}
+export async function getQuoteLineQuantities(
+ client: SupabaseClient<Database>,
+ quoteLineId: string
+) {
+ return client
+ .from("quoteLineQuantity")
+ .select("*")
+ .eq("quoteLineId", quoteLineId);
+}
+
export async function insertCustomer(
client: SupabaseClient<Database>,
customer:
@@ -378,6 +388,39 @@ export async function insertCustomerLocation(
.single();
}
+export async function insertQuoteLineQuantity(
+ client: SupabaseClient<Database>,
+ quoteLineQuantity: {
+ quoteLineId: string;
+ quantity?: number;
+ createdBy: string;
+ }
+) {
+ const quoteLine = await getQuoteLine(client, quoteLineQuantity.quoteLineId);
+ if (quoteLine.error) {
+ return quoteLine;
+ }
+
+ const partId = quoteLine.data?.partId;
+ const [partCost] = await Promise.all([
+ client.from("partCost").select("unitCost").eq("partId", partId).single(),
+ ]);
+
+ if (partCost.error) {
+ return partCost;
+ }
+
+ return client.from("quoteLineQuantity").insert([
+ {
+ ...quoteLineQuantity,
+ materialCost:
+ quoteLine.data.replenishmentSystem === "Make"
+ ? partCost.data?.unitCost
+ : 0,
+ },
+ ]);
+}
+
export async function updateCustomer(
client: SupabaseClient<Database>,
customer: Omit<TypeOfValidator<typeof customerValidator>, "id"> & {
diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.ts
index 89973fc9e6..f3b630bb91 100644
--- a/apps/carbon/app/modules/sales/types.ts
+++ b/apps/carbon/app/modules/sales/types.ts
@@ -7,6 +7,7 @@ import type {
getCustomerStatuses,
getCustomerTypes,
getQuoteExternalDocuments,
+ getQuoteLineQuantities,
getQuoteLines,
getQuotes,
} from "./sales.service";
@@ -47,4 +48,8 @@ export type QuotationLine = NonNullable<
Awaited<ReturnType<typeof getQuoteLines>>["data"]
>[number];
+export type QuotationLineQuantity = NonNullable<
+ Awaited<ReturnType<typeof getQuoteLineQuantities>>["data"]
+>[number];
+
export type QuotationStatusType = Database["public"]["Enums"]["quoteStatus"];
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationForm.tsx
index 1891831681..0464e0fbb3 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationForm.tsx
@@ -45,6 +45,7 @@ const QuotationForm = ({ initialValues }: QuotationFormProps) => {
method="post"
validator={quotationValidator}
defaultValues={initialValues}
+ className="w-full"
>
<Card className={cn(!isEditing && "mt-4")}>
<CardHeader>
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx
index 6b7fb5b31f..f6ecc68268 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLineForm.tsx
@@ -1,4 +1,5 @@
import {
+ Button,
Card,
CardContent,
CardFooter,
@@ -9,6 +10,7 @@ import {
import { useParams } from "@remix-run/react";
import { useState } from "react";
+import { BsDownload, BsUpload } from "react-icons/bs";
import { ValidatedForm } from "remix-validated-form";
import {
Hidden,
@@ -163,6 +165,26 @@ const QuotationLineForm = ({ initialValues }: QuotationLineFormProps) => {
}));
}}
/>
+ {isEditing && partData.replenishmentSystem === "Make" && (
+ <>
+ <Button
+ isDisabled
+ variant="secondary"
+ className="w-full"
+ leftIcon={<BsDownload />}
+ >
+ Get Part
+ </Button>
+ <Button
+ isDisabled
+ variant="secondary"
+ className="w-full"
+ leftIcon={<BsUpload />}
+ >
+ Set Part
+ </Button>
+ </>
+ )}
</VStack>
</div>
</VStack>
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLineQuantities.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLineQuantities.tsx
new file mode 100644
index 0000000000..dba0ea92f5
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLineQuantities.tsx
@@ -0,0 +1,248 @@
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+} from "@carbon/react";
+import { Form, Outlet, useNavigate, useParams } from "@remix-run/react";
+import type { ColumnDef } from "@tanstack/react-table";
+import { useMemo, useRef } from "react";
+import { IoMdTrash } from "react-icons/io";
+import { MdMoreHoriz } from "react-icons/md";
+import { EditableNumber } from "~/components/Editable";
+import Grid from "~/components/Grid";
+import { useRouteData } from "~/hooks";
+import type {
+ Quotation,
+ QuotationLine,
+ QuotationLineQuantity,
+} from "~/modules/sales";
+import { path } from "~/utils/path";
+import useQuotationQuantities from "./useQuotationQuantities";
+
+type QuotationLineQuantitiesProps = {
+ quotationLine: QuotationLine;
+ quotationLineQuantities: QuotationLineQuantity[];
+};
+
+const QuotationLineQuantities = ({
+ quotationLine,
+ quotationLineQuantities,
+}: QuotationLineQuantitiesProps) => {
+ const { id, lineId } = useParams();
+ if (!id) throw new Error("id not found");
+ if (!lineId) throw new Error("lineId not found");
+
+ const navigate = useNavigate();
+
+ const routeData = useRouteData<{
+ quotation: Quotation;
+ }>(path.to.quote(id));
+
+ // TODO: use the currency of the quote
+ const formatter = new Intl.NumberFormat("en-US", {
+ style: "currency",
+ currency: "USD",
+ });
+
+ const { canEdit, canDelete, onCellEdit } = useQuotationQuantities();
+
+ const isEditable = ["Draft"].includes(routeData?.quotation?.status ?? "");
+ const isMade = quotationLine.replenishmentSystem === "Make";
+
+ const columns = useMemo<ColumnDef<QuotationLineQuantity>[]>(() => {
+ const _columns: ColumnDef<QuotationLineQuantity>[] = [
+ {
+ header: "Line",
+ cell: ({ row }) => (
+ <HStack className="justify-between">
+ <span>{row.index + 1}</span>
+ <div className="relative w-6 h-5">
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="Edit quotation line"
+ icon={<MdMoreHoriz />}
+ size="md"
+ className="absolute right-[-1px] top-[-6px]"
+ variant="ghost"
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem
+ onClick={() => navigate(`delete/${row.original.id}`)}
+ disabled={!isEditable || !canDelete}
+ >
+ <DropdownMenuIcon icon={<IoMdTrash />} />
+ Delete Line
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </HStack>
+ ),
+ },
+
+ {
+ accessorKey: "quantity",
+ header: "Quantity",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "unitCostBase",
+ header: "Unit Cost",
+ cell: (item) => formatter.format(item.getValue<number>()),
+ },
+ {
+ accessorKey: "unitTaxAmount",
+ header: "Unit Tax",
+ cell: (item) => formatter.format(item.getValue<number>()),
+ },
+ {
+ header: "Extended Cost",
+ cell: ({ row }) =>
+ formatter.format(
+ row.original.quantity *
+ (row.original.unitCostBase + row.original.unitTaxAmount)
+ ),
+ },
+ {
+ accessorKey: "markupPercentage",
+ header: "Markup %",
+ cell: (item) => item.getValue() + "%",
+ },
+ {
+ accessorKey: "discountPercentage",
+ header: "Discount %",
+ cell: (item) => item.getValue() + "%",
+ },
+ {
+ header: "Extended Price",
+ cell: ({ row }) =>
+ formatter.format(
+ row.original.quantity *
+ (row.original.unitCostBase + row.original.unitTaxAmount) *
+ (1 - row.original.discountPercentage / 100) *
+ (1 + row.original.markupPercentage / 100)
+ ),
+ },
+ {
+ accessorKey: "leadTime",
+ header: "Lead Time",
+ cell: (item) => item.getValue(),
+ },
+ ];
+
+ if (isMade) {
+ _columns.push(
+ {
+ accessorKey: "scrapPercentage",
+ header: "Scrap Percentage",
+ cell: (item) => item.getValue() + "%",
+ },
+ {
+ accessorKey: "setupHours",
+ header: "Setup Hours",
+ cell: (item) => item.getValue(),
+ },
+ {
+ accessorKey: "productionHours",
+ header: "Production Hours",
+ cell: (item) => item.getValue(),
+ }
+ );
+ }
+
+ _columns.push({
+ accessorKey: "materialCost",
+ header: "Material Cost",
+ cell: (item) => formatter.format(item.getValue<number>()),
+ });
+
+ if (isMade) {
+ _columns.push(
+ {
+ accessorKey: "laborCost",
+ header: "Labor Cost",
+ cell: (item) => formatter.format(item.getValue<number>()),
+ },
+ {
+ accessorKey: "overheadCost",
+ header: "Overhead Cost",
+ cell: (item) => formatter.format(item.getValue<number>()),
+ },
+ {
+ accessorKey: "additionalCost",
+ header: "Additional Cost",
+ cell: (item) => formatter.format(item.getValue<number>()),
+ }
+ );
+ }
+
+ return _columns;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [navigate, quotationLine.replenishmentSystem, isEditable, canDelete]);
+
+ const editableComponents = useMemo(
+ () => ({
+ quantity: EditableNumber(onCellEdit),
+ scrapPercentage: EditableNumber(onCellEdit, {
+ minValue: 0,
+ maxValue: 1,
+ }),
+ setupHours: EditableNumber(onCellEdit, { minValue: 0 }),
+ productionHours: EditableNumber(onCellEdit, { minValue: 0 }),
+ materialCost: EditableNumber(onCellEdit, { minValue: 0 }),
+ laborCost: EditableNumber(onCellEdit, { minValue: 0 }),
+ overheadCost: EditableNumber(onCellEdit, { minValue: 0 }),
+ additionalCost: EditableNumber(onCellEdit, { minValue: 0 }),
+ discountPercentage: EditableNumber(onCellEdit, { minValue: 0 }),
+ markupPercentage: EditableNumber(onCellEdit, { minValue: 0 }),
+ unitTaxAmount: EditableNumber(onCellEdit, { minValue: 0 }),
+ leadTime: EditableNumber(onCellEdit, { minValue: 0 }),
+ }),
+ [onCellEdit]
+ );
+
+ const newRowButtonRef = useRef<HTMLButtonElement>(null);
+
+ return (
+ <>
+ <Card className="w-full h-[50vh]">
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Line Prices</CardTitle>
+ </CardHeader>
+ </HStack>
+
+ <CardContent>
+ <Grid<QuotationLineQuantity>
+ data={quotationLineQuantities}
+ columns={columns}
+ canEdit={canEdit && isEditable}
+ editableComponents={editableComponents}
+ onNewRow={
+ canEdit && isEditable
+ ? () => newRowButtonRef.current?.click()
+ : undefined
+ }
+ />
+ <Form method="post" action={path.to.newQuoteLineQuantity(id, lineId)}>
+ <button type="submit" ref={newRowButtonRef} className="sr-only" />
+ </Form>
+ </CardContent>
+ </Card>
+ <Outlet />
+ </>
+ );
+};
+
+export default QuotationLineQuantities;
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLines.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLines.tsx
deleted file mode 100644
index 1b3ce83b53..0000000000
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/QuotationLines.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-import {
- Card,
- CardAction,
- CardContent,
- CardHeader,
- CardTitle,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuIcon,
- DropdownMenuItem,
- DropdownMenuTrigger,
- HStack,
- IconButton,
-} from "@carbon/react";
-import { 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 { New } from "~/components";
-import { EditableNumber } from "~/components/Editable";
-import Grid from "~/components/Grid";
-import { useRouteData } from "~/hooks";
-import { type Quotation, type 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 }) => {
- return (
- <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: "customerPartId",
- header: "Customer Part",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "quantity",
- header: "Quantity",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "unitCost",
- header: "Unit Cost",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "unitPrice",
- header: "Unit Price",
- cell: (item) => item.getValue(),
- },
- {
- accessorKey: "leadTime",
- header: "Lead Time",
- cell: (item) => item.getValue(),
- },
- ];
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [navigate]);
-
- const editableComponents = useMemo(
- () => ({
- quantity: EditableNumber(onCellEdit),
- unitCost: EditableNumber(onCellEdit),
- unitPrice: EditableNumber(onCellEdit),
- leadTime: EditableNumber(onCellEdit),
- }),
- [onCellEdit]
- );
-
- return (
- <>
- <Card className="w-full h-full min-h-[50vh]">
- <HStack className="justify-between items-start">
- <CardHeader>
- <CardTitle>Line Prices</CardTitle>
- </CardHeader>
- <CardAction>{canEdit && isEditable && <New to="new" />}</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
index 6565135735..098338fb22 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/index.ts
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/index.ts
@@ -1,3 +1,3 @@
-import QuotationLines from "./QuotationLines";
+import QuotationLineQuantities from "./QuotationLineQuantities";
-export default QuotationLines;
+export default QuotationLineQuantities;
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationLines.tsx b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationQuantities.tsx
similarity index 92%
rename from apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationLines.tsx
rename to apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationQuantities.tsx
index 6a3f82cd09..ef4b3475a5 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationLines.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotation/QuotationLines/useQuotationQuantities.tsx
@@ -4,7 +4,7 @@ import { useSupabase } from "~/lib/supabase";
import type { QuotationLine } from "~/modules/sales";
import { useParts } from "~/stores/parts";
-export default function useQuotationLines() {
+export default function useQuotationQuantities() {
const { id: userId } = useUser();
const { supabase } = useSupabase();
const permissions = usePermissions();
@@ -26,7 +26,7 @@ export default function useQuotationLines() {
async (id: string, value: unknown, row: QuotationLine) => {
if (!supabase) throw new Error("Supabase client not found");
return await supabase
- .from("quoteLine")
+ .from("quoteLineQuantity")
.update({
[id]: value,
updatedBy: userId,
diff --git a/apps/carbon/app/modules/sales/ui/Quotation/index.ts b/apps/carbon/app/modules/sales/ui/Quotation/index.ts
index 10ebaa1ccc..8b19d82384 100644
--- a/apps/carbon/app/modules/sales/ui/Quotation/index.ts
+++ b/apps/carbon/app/modules/sales/ui/Quotation/index.ts
@@ -2,7 +2,10 @@ import QuotationDocuments from "./QuotationDocuments";
import QuotationForm from "./QuotationForm";
import QuotationHeader from "./QuotationHeader";
import QuotationLineForm from "./QuotationLineForm";
-import QuotationLines from "./QuotationLines";
+import {
+ default as QuotationLineQuantities,
+ default as QuotationLines,
+} from "./QuotationLines";
import QuotationSidebar from "./QuotationSidebar";
import QuotationStatus from "./QuotationStatus";
@@ -11,6 +14,7 @@ export {
QuotationForm,
QuotationHeader,
QuotationLineForm,
+ QuotationLineQuantities,
QuotationLines,
QuotationSidebar,
QuotationStatus,
diff --git a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.new.tsx b/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.new.tsx
new file mode 100644
index 0000000000..bc7b941c5d
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.new.tsx
@@ -0,0 +1,38 @@
+import { redirect, type ActionFunctionArgs } from "@remix-run/node";
+import { insertQuoteLineQuantity } from "~/modules/sales";
+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: "sales",
+ });
+
+ const { id, lineId } = params;
+ if (!id) throw new Error("Could not find id");
+ if (!lineId) throw new Error("Could not find lineId");
+
+ const createQuoteQuantity = await insertQuoteLineQuantity(client, {
+ quoteLineId: lineId,
+ createdBy: userId,
+ });
+
+ if (createQuoteQuantity.error) {
+ return redirect(
+ path.to.quoteLine(id, lineId),
+ await flash(
+ request,
+ error(
+ createQuoteQuantity.error,
+ "Failed to create quote line quantity."
+ )
+ )
+ );
+ }
+
+ return redirect(path.to.quoteLine(id, lineId));
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.tsx b/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.tsx
index 8516ef4fda..a5c8e4c9a4 100644
--- a/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$id.lines.$lineId.tsx
@@ -4,7 +4,9 @@ import { useLoaderData } from "@remix-run/react";
import { validationError } from "remix-validated-form";
import {
QuotationLineForm,
+ QuotationLineQuantities,
getQuoteLine,
+ getQuoteLineQuantities,
quotationLineValidator,
upsertQuoteLine,
} from "~/modules/sales";
@@ -23,10 +25,14 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const { lineId } = params;
if (!lineId) throw notFound("lineId not found");
- const quotationLine = await getQuoteLine(client, lineId);
+ const [quotationLine, quotationLineQuantities] = await Promise.all([
+ getQuoteLine(client, lineId),
+ getQuoteLineQuantities(client, lineId),
+ ]);
return json({
quotationLine: quotationLine?.data ?? null,
+ quotationLineQuantities: quotationLineQuantities?.data ?? [],
});
}
@@ -58,7 +64,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (updateQuotationLine.error) {
return redirect(
- path.to.quoteLines(quoteId),
+ path.to.quoteLine(quoteId, lineId),
await flash(
request,
error(updateQuotationLine.error, "Failed to update quote line")
@@ -66,24 +72,34 @@ export async function action({ request, params }: ActionFunctionArgs) {
);
}
- return redirect(path.to.quoteLines(quoteId));
+ return redirect(path.to.quoteLine(quoteId, lineId));
}
export default function EditQuotationLineRoute() {
- const { quotationLine } = useLoaderData<typeof loader>();
+ const { quotationLine, quotationLineQuantities } =
+ useLoaderData<typeof loader>();
+ if (!quotationLine) throw new Error("Could not find quotation line");
const initialValues = {
id: quotationLine?.id ?? undefined,
quoteId: quotationLine?.quoteId ?? "",
-
partId: quotationLine?.partId ?? "",
- customerPartId: quotationLine?.customerPartId ?? "",
description: quotationLine?.description ?? "",
- quantity: quotationLine?.quantity ?? 1,
- unitCost: quotationLine?.unitCost ?? 0,
- unitPrice: quotationLine?.unitPrice ?? 0,
- leadTime: quotationLine?.leadTime ?? undefined,
+ customerPartId: quotationLine?.customerPartId ?? "",
+ customerPartRevision: quotationLine?.customerPartRevision ?? "",
+ replenishmentSystem: (quotationLine?.replenishmentSystem ?? "") as
+ | "Buy"
+ | "Make",
+ unitOfMeasureCode: quotationLine?.unitOfMeasureCode ?? "",
};
- return <QuotationLineForm initialValues={initialValues} />;
+ return (
+ <>
+ <QuotationLineForm initialValues={initialValues} />
+ <QuotationLineQuantities
+ quotationLine={quotationLine}
+ quotationLineQuantities={quotationLineQuantities}
+ />
+ </>
+ );
}
diff --git a/apps/carbon/app/routes/x+/quote+/$id.new.tsx b/apps/carbon/app/routes/x+/quote+/$id.new.tsx
index c8b9553b09..7d6b7f0c6d 100644
--- a/apps/carbon/app/routes/x+/quote+/$id.new.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$id.new.tsx
@@ -4,6 +4,7 @@ import { useParams } from "@remix-run/react";
import { validationError } from "remix-validated-form";
import {
QuotationLineForm,
+ insertQuoteLineQuantity,
quotationLineValidator,
upsertQuoteLine,
} from "~/modules/sales";
@@ -49,6 +50,25 @@ export async function action({ request, params }: ActionFunctionArgs) {
const quoteLineId = createQuotationLine.data.id;
+ const createQuoteQuantity = await insertQuoteLineQuantity(client, {
+ quoteLineId,
+ quantity: 1,
+ createdBy: userId,
+ });
+
+ if (createQuoteQuantity.error) {
+ return redirect(
+ path.to.quoteLine(quoteId, quoteLineId),
+ await flash(
+ request,
+ error(
+ createQuoteQuantity.error,
+ "Failed to create quote line quantity."
+ )
+ )
+ );
+ }
+
return redirect(path.to.quoteLine(quoteId, quoteLineId));
}
diff --git a/apps/carbon/app/routes/x+/quote+/$id.tsx b/apps/carbon/app/routes/x+/quote+/$id.tsx
index ca26bd852b..12cd40dc27 100644
--- a/apps/carbon/app/routes/x+/quote+/$id.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$id.tsx
@@ -14,7 +14,7 @@ import {
} from "@carbon/react";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
-import { Outlet, useNavigate, useParams } from "@remix-run/react";
+import { Link, Outlet, useNavigate, useParams } from "@remix-run/react";
import { useState } from "react";
import { IoMdAdd } from "react-icons/io";
import { CollapsibleSidebar } from "~/components/Layout/Navigation/CollapsibleSidebar";
@@ -148,8 +148,7 @@ export default function QuotationRoute() {
type BillOfMaterialNodeType =
| "parent"
- | "part"
- | "part"
+ | "line"
| "assemblies"
| "operations"
| "materials"
@@ -171,106 +170,118 @@ const data: BillOfMaterialNode[] = [
type: "parent",
children: [
{
- id: "1",
- label: "P00001234",
- type: "part",
- },
- {
- id: "2",
- label: "P00001233",
- type: "part",
+ id: "cn8g57bau0l38ambhoeg",
+ label: "P000000002",
+ type: "line",
children: [
{
- id: "3",
+ id: "cn8g57bau0l38ambhoeg",
label: "Assemblies",
type: "assemblies",
- children: [
- {
- id: "4",
- label: "F5000123",
- type: "part",
- children: [
- {
- id: "5",
- label: "Assemblies",
- type: "assemblies",
- children: [],
- },
- {
- id: "6",
- label: "Operations",
- type: "operations",
- children: [
- {
- id: "7",
- label: "OP0003",
- type: "operation",
- children: [
- {
- id: "8",
- label: "Materials",
- type: "materials",
- children: [
- {
- id: "9",
- label: "RAW000001",
- type: "material",
- },
- {
- id: "10",
- label: "FAS000002",
- type: "material",
- },
- ],
- },
- ],
- },
- ],
- },
- ],
- },
- ],
},
{
- id: "11",
+ id: "cn8g57bau0l38ambhoeg",
label: "Operations",
type: "operations",
- children: [
- {
- id: "12",
- label: "OP0001",
- type: "operation",
- children: [
- {
- id: "13",
- label: "Materials",
- type: "materials",
- children: [
- {
- id: "14",
- label: "RAW000003",
- type: "material",
- },
- ],
- },
- ],
- },
- {
- id: "13",
- label: "OP0002",
- type: "operation",
- children: [
- {
- id: "13",
- label: "Materials",
- type: "materials",
- },
- ],
- },
- ],
},
],
},
+ // {
+ // id: "2",
+ // label: "P00001233",
+ // type: "line",
+ // children: [
+ // {
+ // id: "3",
+ // label: "Assemblies",
+ // type: "assemblies",
+ // children: [
+ // {
+ // id: "4",
+ // label: "F5000123",
+ // type: "assembly",
+ // children: [
+ // {
+ // id: "5",
+ // label: "Assemblies",
+ // type: "assemblies",
+ // children: [],
+ // },
+ // {
+ // id: "6",
+ // label: "Operations",
+ // type: "operations",
+ // children: [
+ // {
+ // id: "7",
+ // label: "OP0003",
+ // type: "operation",
+ // children: [
+ // {
+ // id: "8",
+ // label: "Materials",
+ // type: "materials",
+ // children: [
+ // {
+ // id: "9",
+ // label: "RAW000001",
+ // type: "material",
+ // },
+ // {
+ // id: "10",
+ // label: "FAS000002",
+ // type: "material",
+ // },
+ // ],
+ // },
+ // ],
+ // },
+ // ],
+ // },
+ // ],
+ // },
+ // ],
+ // },
+ // {
+ // id: "11",
+ // label: "Operations",
+ // type: "operations",
+ // children: [
+ // {
+ // id: "12",
+ // label: "OP0001",
+ // type: "operation",
+ // children: [
+ // {
+ // id: "13",
+ // label: "Materials",
+ // type: "materials",
+ // children: [
+ // {
+ // id: "14",
+ // label: "RAW000003",
+ // type: "material",
+ // },
+ // ],
+ // },
+ // ],
+ // },
+ // {
+ // id: "13",
+ // label: "OP0002",
+ // type: "operation",
+ // children: [
+ // {
+ // id: "13",
+ // label: "Materials",
+ // type: "materials",
+ // },
+ // ],
+ // },
+ // ],
+ // },
+ // ],
+ // },
],
},
];
@@ -280,6 +291,9 @@ const BillOfMaterialItem = ({
id,
label,
}: Omit<BillOfMaterialNode, "children">) => {
+ const { id: quoteId } = useParams();
+ if (!quoteId) throw new Error("id not found");
+
switch (type) {
case "assemblies":
return (
@@ -311,7 +325,19 @@ const BillOfMaterialItem = ({
<IoMdAdd />
</Button>
);
- case "part":
+ case "line":
+ return (
+ <Button
+ variant="ghost"
+ className="flex-1 justify-start"
+ leftIcon={<AiOutlinePartition />}
+ asChild
+ >
+ <Link to={path.to.quoteLine(quoteId, id)} prefetch="intent">
+ {label}
+ </Link>
+ </Button>
+ );
case "assembly":
return (
<Button
@@ -343,12 +369,15 @@ const BillOfMaterialItem = ({
</Button>
);
case "parent":
- default:
return (
- <Button variant="ghost" className="flex-1 justify-start">
- {label}
+ <Button variant="ghost" className="flex-1 justify-start" asChild>
+ <Link to={path.to.quote(quoteId)} prefetch="intent">
+ {label}
+ </Link>
</Button>
);
+ default:
+ throw new Error(`unknown type: ${type}`);
}
};
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 9ea0f6f5ce..68a7e3a965 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -277,6 +277,8 @@ export const path = {
generatePath(`${x}/purchase-order/${id}/lines/new`),
newQuote: `${x}/quote/new`,
newQuoteLine: (id: string) => generatePath(`${x}/quote/${id}/new`),
+ newQuoteLineQuantity: (id: string, lineId: string) =>
+ generatePath(`${x}/quote/${id}/lines/${lineId}/new`),
newReceipt: `${x}/inventory/receipts/new`,
newRequestForQuote: `${x}/rfq/new`,
newShift: `${x}/resources/shifts/new`,
@@ -366,10 +368,10 @@ export const path = {
quoteFavorite: `${x}/purchasing/orders/favorite`,
quoteInternalDocuments: (id: string) =>
generatePath(`${x}/quote/${id}/internal`),
- quoteLines: (orderId: string) =>
- generatePath(`${x}/quote/${orderId}/lines`),
- quoteLine: (orderId: string, id: string) =>
- generatePath(`${x}/quote/${orderId}/lines/${id}`),
+ quoteLines: (quoteId: string) =>
+ generatePath(`${x}/quote/${quoteId}/lines`),
+ quoteLine: (quoteId: string, id: string) =>
+ generatePath(`${x}/quote/${quoteId}/lines/${id}`),
quoteRelease: (id: string) => generatePath(`${x}/quote/${id}/release`),
quotes: `${x}/sales/quotes`,
receipt: (id: string) => generatePath(`${x}/inventory/receipts/${id}`),
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 198674b51e..9ef36f7dfa 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -7143,7 +7143,7 @@ export interface Database {
}
];
};
- quoteLineQuantities: {
+ quoteLineQuantity: {
Row: {
additionalCost: number;
createdAt: string;
@@ -7212,43 +7212,43 @@ export interface Database {
};
Relationships: [
{
- foreignKeyName: "quoteLineQuantities_createdBy_fkey";
+ foreignKeyName: "quoteLineQuantity_createdBy_fkey";
columns: ["createdBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
{
- foreignKeyName: "quoteLineQuantities_createdBy_fkey";
+ foreignKeyName: "quoteLineQuantity_createdBy_fkey";
columns: ["createdBy"];
referencedRelation: "employeeSummary";
referencedColumns: ["id"];
},
{
- foreignKeyName: "quoteLineQuantities_createdBy_fkey";
+ foreignKeyName: "quoteLineQuantity_createdBy_fkey";
columns: ["createdBy"];
referencedRelation: "userDefaults";
referencedColumns: ["userId"];
},
{
- foreignKeyName: "quoteLineQuantities_quoteLineId_fkey";
+ foreignKeyName: "quoteLineQuantity_quoteLineId_fkey";
columns: ["quoteLineId"];
referencedRelation: "quoteLine";
referencedColumns: ["id"];
},
{
- foreignKeyName: "quoteLineQuantities_updatedBy_fkey";
+ foreignKeyName: "quoteLineQuantity_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "user";
referencedColumns: ["id"];
},
{
- foreignKeyName: "quoteLineQuantities_updatedBy_fkey";
+ foreignKeyName: "quoteLineQuantity_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "employeeSummary";
referencedColumns: ["id"];
},
{
- foreignKeyName: "quoteLineQuantities_updatedBy_fkey";
+ foreignKeyName: "quoteLineQuantity_updatedBy_fkey";
columns: ["updatedBy"];
referencedRelation: "userDefaults";
referencedColumns: ["userId"];
diff --git a/packages/database/supabase/migrations/20240206224405_quotes.sql b/packages/database/supabase/migrations/20240206224405_quotes.sql
index e3777c3526..0ebaab30af 100644
--- a/packages/database/supabase/migrations/20240206224405_quotes.sql
+++ b/packages/database/supabase/migrations/20240206224405_quotes.sql
@@ -66,7 +66,7 @@ CREATE TABLE "quoteLine" (
CREATE INDEX "quoteLine_quoteId_idx" ON "quoteLine" ("quoteId");
-CREATE TABLE "quoteLineQuantities" (
+CREATE TABLE "quoteLineQuantity" (
"id" TEXT NOT NULL DEFAULT xid(),
"quoteLineId" TEXT NOT NULL,
"quantity" NUMERIC(10, 2) NOT NULL DEFAULT 0,
@@ -88,13 +88,13 @@ CREATE TABLE "quoteLineQuantities" (
"updatedAt" TIMESTAMP WITH TIME ZONE,
"updatedBy" TEXT,
- CONSTRAINT "quoteLineQuantities_pkey" PRIMARY KEY ("id"),
- CONSTRAINT "quoteLineQuantities_quoteLineId_fkey" FOREIGN KEY ("quoteLineId") REFERENCES "quoteLine" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
- CONSTRAINT "quoteLineQuantities_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
- CONSTRAINT "quoteLineQuantities_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
+ CONSTRAINT "quoteLineQuantity_pkey" PRIMARY KEY ("id"),
+ CONSTRAINT "quoteLineQuantity_quoteLineId_fkey" FOREIGN KEY ("quoteLineId") REFERENCES "quoteLine" ("id") ON DELETE CASCADE ON UPDATE CASCADE,
+ CONSTRAINT "quoteLineQuantity_createdBy_fkey" FOREIGN KEY ("createdBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE,
+ CONSTRAINT "quoteLineQuantity_updatedBy_fkey" FOREIGN KEY ("updatedBy") REFERENCES "user" ("id") ON DELETE RESTRICT ON UPDATE CASCADE
);
-CREATE INDEX "quoteLineQuantities_quoteLineId_idx" ON "quoteLineQuantities" ("quoteLineId");
+CREATE INDEX "quoteLineQuantity_quoteLineId_idx" ON "quoteLineQuantity" ("quoteLineId");
CREATE TABLE "quoteAssembly" (
"id" TEXT NOT NULL DEFAULT xid(),