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: create quote lines

Brad Barbinfc9275693dca
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index 06dbe7ad72..877ceace92 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -2,6 +2,7 @@ import { z } from "zod";
import { zfd } from "zod-form-data";
import { address, contact } from "~/types/validators";
import { currencyCodes } from "../accounting";
+import { methodType } from "../items";
import { standardFactorType } from "../shared/types";
export const salesRFQStatusType = [
@@ -90,6 +91,27 @@ export const quoteValidator = z.object({
expirationDate: zfd.text(z.string().optional()),
});
+export const quoteLineValidator = z.object({
+ id: zfd.text(z.string().optional()),
+ quoteId: z.string(),
+ itemId: z.string().min(1, { message: "Part is required" }),
+ itemReadableId: zfd.text(z.string().optional()),
+ status: z.enum(quoteLineStatusType, {
+ errorMap: () => ({ message: "Status is required" }),
+ }),
+ estimatorId: zfd.text(z.string().optional()),
+ description: z.string().min(1, { message: "Description is required" }),
+ methodType: z.enum(methodType, {
+ errorMap: () => ({ message: "Method is required" }),
+ }),
+ customerPartId: zfd.text(z.string().optional()),
+ customerPartRevision: zfd.text(z.string().optional()),
+ unitOfMeasureCode: zfd.text(
+ z.string().min(1, { message: "Unit of measure is required" })
+ ),
+ modelUploadId: zfd.text(z.string().optional()),
+});
+
export const quotationValidator = z.object({
id: zfd.text(z.string().optional()),
quoteId: zfd.text(z.string().optional()),
diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.ts
index ec0cbc38ac..fe0a856ec2 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -15,11 +15,11 @@ import type {
customerTypeValidator,
customerValidator,
quotationAssemblyValidator,
- quotationLineValidator,
quotationMaterialValidator,
quotationOperationValidator,
quotationPricingValidator,
- quotationValidator,
+ quoteLineValidator,
+ quoteValidator,
salesOrderLineValidator,
salesOrderPaymentValidator,
salesOrderShipmentValidator,
@@ -496,7 +496,7 @@ export async function getQuoteLine(
client: SupabaseClient<Database>,
quoteLineId: string
) {
- return client.from("quoteLine").select("*").eq("id", quoteLineId).single();
+ return client.from("quoteLines").select("*").eq("id", quoteLineId).single();
}
export async function getQuoteLines(
@@ -1153,13 +1153,13 @@ export async function updateQuoteFavorite(
export async function upsertQuote(
client: SupabaseClient<Database>,
quote:
- | (Omit<z.infer<typeof quotationValidator>, "id" | "quoteId"> & {
+ | (Omit<z.infer<typeof quoteValidator>, "id" | "quoteId"> & {
quoteId: string;
companyId: string;
createdBy: string;
customFields?: Json;
})
- | (Omit<z.infer<typeof quotationValidator>, "id" | "quoteId"> & {
+ | (Omit<z.infer<typeof quoteValidator>, "id" | "quoteId"> & {
id: string;
quoteId: string;
updatedBy: string;
@@ -1215,12 +1215,12 @@ export async function upsertQuoteMakeMethod(
export async function upsertQuoteLine(
client: SupabaseClient<Database>,
quotationLine:
- | (Omit<z.infer<typeof quotationLineValidator>, "id"> & {
+ | (Omit<z.infer<typeof quoteLineValidator>, "id"> & {
companyId: string;
createdBy: string;
customFields?: Json;
})
- | (Omit<z.infer<typeof quotationLineValidator>, "id"> & {
+ | (Omit<z.infer<typeof quoteLineValidator>, "id"> & {
id: string;
updatedBy: string;
customFields?: Json;
diff --git a/apps/carbon/app/modules/sales/types.ts b/apps/carbon/app/modules/sales/types.ts
index 24a03e94e6..602c21f15e 100644
--- a/apps/carbon/app/modules/sales/types.ts
+++ b/apps/carbon/app/modules/sales/types.ts
@@ -6,9 +6,9 @@ import type {
getCustomers,
getCustomerStatuses,
getCustomerTypes,
- getQuoteAssembly,
getQuoteExternalDocuments,
getQuoteLines,
+ getQuoteMakeMethod,
getQuoteMaterials,
getQuoteOperation,
getQuotes,
@@ -47,8 +47,8 @@ export type CustomerType = NonNullable<
Awaited<ReturnType<typeof getCustomerTypes>>["data"]
>[number];
-export type QuotationAssembly = NonNullable<
- Awaited<ReturnType<typeof getQuoteAssembly>>["data"]
+export type QuotationMakeMethod = NonNullable<
+ Awaited<ReturnType<typeof getQuoteMakeMethod>>["data"]
>;
export type QuotationAttachment = NonNullable<
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/useQuoteDocuments.ts b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/useQuoteDocuments.ts
index b43c02986b..e4d5164ba2 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/useQuoteDocuments.ts
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/useQuoteDocuments.ts
@@ -1,5 +1,5 @@
import { toast } from "@carbon/react";
-import { useFetcher } from "@remix-run/react";
+import { useRevalidator } from "@remix-run/react";
import { useCallback } from "react";
import { usePermissions, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
@@ -11,18 +11,13 @@ type Props = {
};
export const useQuoteDocuments = ({ isExternal, id }: Props) => {
- const fetcher = useFetcher<{}>();
const permissions = usePermissions();
const { company } = useUser();
const { supabase } = useSupabase();
+ const revalidator = useRevalidator();
const canDelete = permissions.can("delete", "sales"); // TODO: or is document owner
- const refresh = useCallback(
- () => fetcher.submit(null, { method: "post" }),
- [fetcher]
- );
-
const getPath = useCallback(
(attachment: QuotationAttachment) => {
return `${company.id}/quote/${
@@ -44,9 +39,9 @@ export const useQuoteDocuments = ({ isExternal, id }: Props) => {
}
toast.success("File deleted successfully");
- refresh();
+ revalidator.revalidate();
},
- [supabase?.storage, getPath, refresh]
+ [supabase?.storage, getPath, revalidator]
);
const download = useCallback(
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
new file mode 100644
index 0000000000..cf1c0877fc
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx
@@ -0,0 +1,257 @@
+import {
+ CardAction,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ ModalCard,
+ ModalCardBody,
+ ModalCardContent,
+ ModalCardDescription,
+ ModalCardFooter,
+ ModalCardHeader,
+ ModalCardProvider,
+ ModalCardTitle,
+ VStack,
+ cn,
+} from "@carbon/react";
+
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useNavigate, useParams } from "@remix-run/react";
+import { useState } from "react";
+import { BsDownload, BsThreeDotsVertical, BsUpload } from "react-icons/bs";
+import { LuTrash } from "react-icons/lu";
+import type { z } from "zod";
+import {
+ CustomFormFields,
+ Hidden,
+ Input,
+ InputControlled,
+ Item,
+ Select,
+ SelectControlled,
+ Submit,
+} from "~/components/Form";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import { methodType } from "~/modules/items";
+import type { Quotation } from "~/modules/sales";
+import { quoteLineStatusType, quoteLineValidator } from "~/modules/sales";
+import { path } from "~/utils/path";
+
+type QuoteLineFormProps = {
+ initialValues: z.infer<typeof quoteLineValidator>;
+ type?: "card" | "modal";
+ onClose?: () => void;
+};
+
+const QuoteLineForm = ({
+ initialValues,
+ type,
+ onClose,
+}: QuoteLineFormProps) => {
+ const navigate = useNavigate();
+ const permissions = usePermissions();
+ const { company } = useUser();
+ const { supabase } = useSupabase();
+
+ const { quoteId } = useParams();
+
+ if (!quoteId) throw new Error("quoteId not found");
+
+ const routeData = useRouteData<{
+ quotation: Quotation;
+ }>(path.to.quote(quoteId));
+
+ const isEditable = ["Draft", "To Review"].includes(
+ routeData?.quotation?.status ?? ""
+ );
+
+ const isEditing = initialValues.id !== undefined;
+
+ const [itemData, setItemData] = useState<{
+ itemId: string;
+ itemReadableId: string;
+ description: string;
+ methodType: string;
+ uom: string;
+ modelUploadId: string | null;
+ }>({
+ itemId: initialValues.itemId ?? "",
+ itemReadableId: initialValues.itemReadableId ?? "",
+ description: initialValues.description ?? "",
+ methodType: initialValues.methodType ?? "",
+ uom: initialValues.unitOfMeasureCode ?? "",
+ modelUploadId: initialValues.modelUploadId ?? null,
+ });
+
+ const onItemChange = async (itemId: string) => {
+ if (!supabase || !company.id) return;
+ const [item] = await Promise.all([
+ supabase
+ .from("item")
+ .select(
+ "name, readableId, defaultMethodType, unitOfMeasureCode, modelUploadId"
+ )
+ .eq("id", itemId)
+ .single(),
+ ]);
+
+ setItemData({
+ itemId,
+ itemReadableId: item.data?.readableId ?? "",
+ description: item.data?.name ?? "",
+ methodType: item.data?.defaultMethodType ?? "",
+ uom: item.data?.unitOfMeasureCode ?? "",
+ modelUploadId: item.data?.modelUploadId ?? null,
+ });
+ };
+
+ return (
+ <ModalCardProvider type={type}>
+ <ModalCard onClose={onClose}>
+ <ModalCardContent>
+ <ValidatedForm
+ defaultValues={initialValues}
+ validator={quoteLineValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.quoteLine(quoteId, initialValues.id!)
+ : path.to.newQuoteLine(quoteId)
+ }
+ className="w-full"
+ onSubmit={() => {
+ if (type === "modal") onClose?.();
+ }}
+ >
+ <HStack className="w-full justify-between items-start">
+ <ModalCardHeader>
+ <ModalCardTitle>
+ {isEditing ? "Quote Line" : "New Quote Line"}
+ </ModalCardTitle>
+ <ModalCardDescription>
+ {isEditing
+ ? itemData?.description
+ : "A quote line contains pricing and lead times for a particular part"}
+ </ModalCardDescription>
+ </ModalCardHeader>
+ {isEditing && (
+ <CardAction>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ icon={<BsThreeDotsVertical />}
+ aria-label="More"
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem onClick={() => navigate("delete")}>
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Line
+ </DropdownMenuItem>
+ <DropdownMenuItem disabled>
+ <DropdownMenuIcon icon={<BsDownload />} />
+ Get Part
+ </DropdownMenuItem>
+ <DropdownMenuItem disabled>
+ <DropdownMenuIcon icon={<BsUpload />} />
+ Save Part
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </CardAction>
+ )}
+ </HStack>
+ <ModalCardBody>
+ <Hidden name="intent" value="line" />
+ <Hidden name="id" />
+ <Hidden name="quoteId" />
+ <Hidden name="itemReadableId" value={itemData?.itemReadableId} />
+ <Hidden name="unitOfMeasureCode" value={itemData?.uom} />
+ <Hidden
+ name="modelUploadId"
+ value={itemData?.modelUploadId ?? undefined}
+ />
+ <VStack>
+ <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
+ <Item
+ name="itemId"
+ type="Part"
+ label="Part"
+ onChange={(value) => {
+ onItemChange(value?.value as string);
+ }}
+ />
+
+ <InputControlled
+ name="description"
+ label="Description"
+ value={itemData.description}
+ onChange={(newValue) =>
+ setItemData((d) => ({ ...d, description: newValue }))
+ }
+ />
+
+ <SelectControlled
+ name="methodType"
+ label="Method"
+ options={
+ methodType.map((m) => ({
+ label: m,
+ value: m,
+ })) ?? []
+ }
+ value={itemData.methodType}
+ onChange={(newValue) => {
+ if (newValue)
+ setItemData((d) => ({
+ ...d,
+ methodType: newValue?.value,
+ }));
+ }}
+ />
+
+ <Input name="customerPartId" label="Customer Part ID" />
+ <Input
+ name="customerPartRevision"
+ label="Customer Part Revision"
+ />
+
+ <Select
+ name="status"
+ label="Line Status"
+ options={quoteLineStatusType.map((s) => ({
+ label: s,
+ value: s,
+ }))}
+ className={cn(!isEditing && "sr-only")}
+ />
+
+ <CustomFormFields table="quoteLine" />
+ </div>
+ </VStack>
+ </ModalCardBody>
+ <ModalCardFooter>
+ <Submit
+ isDisabled={
+ !isEditable || isEditing
+ ? !permissions.can("update", "sales")
+ : !permissions.can("create", "sales")
+ }
+ >
+ Save
+ </Submit>
+ </ModalCardFooter>
+ </ValidatedForm>
+ </ModalCardContent>
+ </ModalCard>
+ </ModalCardProvider>
+ );
+};
+
+export default QuoteLineForm;
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/index.ts b/apps/carbon/app/modules/sales/ui/Quotes/index.ts
index 09a7c8f559..ac91321f74 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/index.ts
+++ b/apps/carbon/app/modules/sales/ui/Quotes/index.ts
@@ -2,6 +2,7 @@ import QuoteBoMExplorer from "./QuoteBoMExplorer";
import QuoteDocuments from "./QuoteDocuments";
import QuoteForm from "./QuoteForm";
import QuoteHeader from "./QuoteHeader";
+import QuoteLineForm from "./QuoteLineForm";
import QuotesTable from "./QuotesTable";
export {
@@ -9,5 +10,6 @@ export {
QuoteDocuments,
QuoteForm,
QuoteHeader,
+ QuoteLineForm,
QuotesTable,
};
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
new file mode 100644
index 0000000000..7f1ecf36f5
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx
@@ -0,0 +1,56 @@
+import { VStack } from "@carbon/react";
+import { json, redirect, type LoaderFunctionArgs } from "@remix-run/node";
+import { useLoaderData } from "@remix-run/react";
+import { getQuoteLine, QuoteLineForm } from "~/modules/sales";
+import { requirePermissions } from "~/services/auth/auth.server";
+import { flash } from "~/services/session.server";
+import { path } from "~/utils/path";
+import { error } from "~/utils/result";
+
+export const loader = async ({ request, params }: LoaderFunctionArgs) => {
+ const { client } = await requirePermissions(request, {
+ view: "sales",
+ });
+
+ const { quoteId, lineId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+ if (!lineId) throw new Error("Could not find lineId");
+
+ const [line] = await Promise.all([getQuoteLine(client, lineId)]);
+
+ if (line.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(request, error(line.error, "Failed to load line"))
+ );
+ }
+
+ return json({
+ line: line.data,
+ });
+};
+
+export default function QuoteLine() {
+ const { line } = useLoaderData<typeof loader>();
+ const initialValues = {
+ ...line,
+ id: line.id ?? undefined,
+ quoteId: line.quoteId ?? "",
+ estimatorId: line.estimatorId ?? "",
+ customerPartId: line.customerPartId ?? "",
+ customerPartRevision: line.customerPartRevision ?? "",
+ status: line.status ?? "Draft",
+ itemId: line.itemId ?? "",
+ itemReadableId: line.itemReadableId ?? "",
+ description: line.description ?? "",
+ methodType: line.methodType ?? "Make",
+ unitOfMeasureCode: line.unitOfMeasureCode ?? "",
+ modelUploadId: line.modelUploadId ?? undefined,
+ };
+
+ return (
+ <VStack spacing={2} className="p-2">
+ <QuoteLineForm initialValues={initialValues} />
+ </VStack>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId._index.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId._index.tsx
new file mode 100644
index 0000000000..2d50ac46e9
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId._index.tsx
@@ -0,0 +1,9 @@
+import type { LoaderFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { path } from "~/utils/path";
+
+export async function loader({ params }: LoaderFunctionArgs) {
+ const { quoteId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+ throw redirect(path.to.quoteDetails(quoteId));
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
index 8b85368f5f..bea771512a 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx
@@ -1,18 +1,95 @@
import { VStack } from "@carbon/react";
+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 { QuoteDocuments, QuoteForm } from "~/modules/sales";
+import type { FileObject } from "@supabase/storage-js";
+import { useRouteData } from "~/hooks";
+import type { Quotation } from "~/modules/sales";
+import {
+ QuoteDocuments,
+ QuoteForm,
+ quoteValidator,
+ upsertQuote,
+} from "~/modules/sales";
+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, success } from "~/utils/result";
+
+export async function action({ request, params }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, userId } = await requirePermissions(request, {
+ update: "sales",
+ });
+
+ const { quoteId: id } = params;
+ if (!id) throw new Error("Could not find id");
+
+ const formData = await request.formData();
+ const validation = await validator(quoteValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { quoteId, ...data } = validation.data;
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ const update = await upsertQuote(client, {
+ id,
+ quoteId,
+ ...data,
+ customFields: setCustomFields(formData),
+ updatedBy: userId,
+ });
+ if (update.error) {
+ throw redirect(
+ path.to.quote(id),
+ await flash(request, error(update.error, "Failed to update quote"))
+ );
+ }
+
+ throw redirect(
+ path.to.quote(id),
+ await flash(request, success("Updated quote"))
+ );
+}
export default function QuoteDetailsRoute() {
const { quoteId } = useParams();
if (!quoteId) throw new Error("Could not find quoteId");
+
+ const quoteData = useRouteData<{
+ quote: Quotation;
+ files: (FileObject & { quoteLineId: string | null })[];
+ }>(path.to.quote(quoteId));
+
+ if (!quoteData) throw new Error("Could not find quote data");
const initialValues = {
- id: "1",
+ id: quoteData?.quote?.id ?? "",
+ customerId: quoteData?.quote?.customerId ?? "",
+ customerContactId: quoteData?.quote?.customerContactId ?? "",
+ customerReference: quoteData?.quote?.customerReference ?? "",
+ dueDate: quoteData?.quote?.dueDate ?? "",
+ estimatorId: quoteData?.quote?.estimatorId ?? "",
+ expirationDate: quoteData?.quote?.expirationDate ?? "",
+ locationId: quoteData?.quote?.locationId ?? "",
+ quoteId: quoteData?.quote?.quoteId ?? "",
+ salesPersonId: quoteData?.quote?.salesPersonId ?? "",
+ status: quoteData?.quote?.status ?? "Draft",
};
return (
<VStack spacing={2} className="p-2">
<QuoteForm key={initialValues.id} initialValues={initialValues} />
- <QuoteDocuments id={quoteId} attachments={[]} isExternal={false} />
+ <QuoteDocuments
+ id={quoteId}
+ attachments={quoteData?.files ?? []}
+ isExternal={false}
+ />
</VStack>
);
}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx
new file mode 100644
index 0000000000..4de3f5cdb4
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.new.tsx
@@ -0,0 +1,62 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import {
+ insertQuoteLinePrice,
+ quoteLineValidator,
+ upsertQuoteLine,
+} from "~/modules/sales";
+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: "sales",
+ });
+
+ const { quoteId } = params;
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ const formData = await request.formData();
+ const validation = await validator(quoteLineValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const { id, ...data } = validation.data;
+
+ const createQuotationLine = await upsertQuoteLine(client, {
+ ...data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createQuotationLine.error) {
+ throw redirect(
+ path.to.quote(quoteId),
+ await flash(
+ request,
+ error(createQuotationLine.error, "Failed to create quote line.")
+ )
+ );
+ }
+
+ const quoteLineId = createQuotationLine.data.id;
+
+ await insertQuoteLinePrice(client, {
+ quoteId,
+ quoteLineId,
+ quantity: 1,
+ markupPercent: 15,
+ createdBy: userId,
+ });
+
+ throw redirect(path.to.quoteLine(quoteId, quoteLineId));
+}
diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
index 58e998b34d..c17501d41f 100644
--- a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx
@@ -2,6 +2,10 @@ import {
Button,
ClientOnly,
cn,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
HStack,
IconButton,
ResizableHandle,
@@ -13,11 +17,20 @@ import {
} from "@carbon/react";
import type { LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
-import { Outlet, useParams } from "@remix-run/react";
-import { LuGhost, LuPlus } from "react-icons/lu";
+import { Outlet, useNavigate, useParams } from "@remix-run/react";
+import { LuGhost, LuImage, LuPlus } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
import type { FlatTree } from "~/components/TreeView/TreeView";
-import { getQuote, QuoteBoMExplorer, QuoteHeader } from "~/modules/sales";
+import { useRouteData, useUser } from "~/hooks";
+import type { QuotationLine } from "~/modules/sales";
+import {
+ getQuote,
+ getQuoteInternalDocuments,
+ getQuoteLines,
+ QuoteBoMExplorer,
+ QuoteHeader,
+ QuoteLineForm,
+} from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
import type { Handle } from "~/utils/handle";
@@ -31,14 +44,18 @@ export const handle: Handle = {
};
export async function loader({ request, params }: LoaderFunctionArgs) {
- const { client } = await requirePermissions(request, {
+ const { client, companyId } = await requirePermissions(request, {
view: "sales",
});
const { quoteId } = params;
if (!quoteId) throw new Error("Could not find quoteId");
- const [quote] = await Promise.all([getQuote(client, quoteId)]);
+ const [quote, lines, files] = await Promise.all([
+ getQuote(client, quoteId),
+ getQuoteLines(client, quoteId),
+ getQuoteInternalDocuments(client, companyId, quoteId),
+ ]);
if (quote.error) {
throw redirect(
@@ -49,6 +66,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
return json({
quote: quote.data,
+ lines: lines.data ?? [],
+ files: files.data ?? [],
});
}
@@ -95,27 +114,63 @@ export default function QuoteRoute() {
}
function QuoteExplorer() {
+ const { quoteId } = useParams();
+ if (!quoteId) throw new Error("Could not find quoteId");
+ const quoteData = useRouteData<{ lines: QuotationLine[] }>(
+ path.to.quote(quoteId)
+ );
+
+ const { id: userId } = useUser();
+ const quoteLineInitialValues = {
+ quoteId,
+ itemId: "",
+ itemReadableId: "",
+ status: "Draft" as const,
+ estimatorId: userId,
+ description: "",
+ methodType: "Make" as const,
+ unitOfMeasureCode: "",
+ };
+
+ const newQuoteLineDisclosure = useDisclosure();
+
return (
- <VStack className="w-full h-[calc(100vh-99px)] justify-between">
- <VStack className="flex-1 overflow-y-auto" spacing={0}>
- <QuoteLineItem />
- <QuoteLineItem />
- <QuoteLineItem />
- {/* <EmptyQuote /> */}
+ <>
+ <VStack className="w-full h-[calc(100vh-99px)] justify-between">
+ <VStack className="flex-1 overflow-y-auto" spacing={0}>
+ {quoteData?.lines && quoteData?.lines?.length > 0 ? (
+ quoteData?.lines.map((line) => (
+ <QuoteLineItem key={line.id} line={line} />
+ ))
+ ) : (
+ <EmptyQuote onAdd={newQuoteLineDisclosure.onOpen} />
+ )}
+ </VStack>
+ <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
+ <Button leftIcon={<LuPlus />} onClick={newQuoteLineDisclosure.onOpen}>
+ Add Line Item
+ </Button>
+ </div>
</VStack>
- <div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
- <Button leftIcon={<LuPlus />}>Add Line Item</Button>
- </div>
- </VStack>
+ {newQuoteLineDisclosure.isOpen && (
+ <QuoteLineForm
+ initialValues={quoteLineInitialValues}
+ type="modal"
+ onClose={newQuoteLineDisclosure.onClose}
+ />
+ )}
+ </>
);
}
-function EmptyQuote() {
+function EmptyQuote({ onAdd }: { onAdd: () => void }) {
return (
<VStack className="w-full h-full justify-center items-center">
<LuGhost className="w-12 h-12" />
<h3 className="font-semibold text-lg">Pretty empty around here</h3>
- <Button leftIcon={<LuPlus />}>Add Line Item</Button>
+ <Button leftIcon={<LuPlus />} onClick={onAdd}>
+ Add Line Item
+ </Button>
</VStack>
);
}
@@ -215,46 +270,82 @@ const methods: FlatTree<{
},
];
-function QuoteLineItem() {
- const isSelected = false;
+function QuoteLineItem({ line }: { line: QuotationLine }) {
+ const { quoteId, lineId } = useParams();
+ const navigate = useNavigate();
const disclosure = useDisclosure();
- const onParentClick = () => {
- disclosure.onToggle();
+
+ if (!quoteId) throw new Error("Could not find quoteId");
+
+ const isSelected = lineId === line.id;
+ const onLineClick = (line: QuotationLine) => {
+ if (line.methodType === "Make") {
+ disclosure.onToggle();
+ }
+
+ if (!isSelected) {
+ // navigate to line
+ navigate(path.to.quoteLine(quoteId, line.id!));
+ }
};
+
return (
<VStack spacing={0}>
<HStack
className={cn(
- "w-full p-2 items-center justify-between hover:bg-accent cursor-pointer",
+ "w-full p-2 items-center justify-between hover:bg-accent/60 cursor-pointer",
!disclosure.isOpen && "border-b border-border",
- isSelected && "bg-accent"
+ isSelected && "bg-accent/60"
)}
- onClick={onParentClick}
+ onClick={() => onLineClick(line)}
>
<HStack spacing={2}>
- <img
- alt="P2392303"
- className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border border-border"
- src="/file/preview/private/<thumbnailPath>"
- />
- {/* <div className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border border-border p-2">
- <LuImage className="w-6 h-6 text-muted-foreground" />
- </div> */}
+ {line.thumbnailPath ? (
+ <img
+ alt="P2392303"
+ className={cn(
+ "w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border border-border",
+ line.status === "Complete" && "border-green-500",
+ line.status === "In Progress" && "border-yellow-500"
+ )}
+ src={`/file/preview/private/${line.thumbnailPath}`}
+ />
+ ) : (
+ <div
+ className={cn(
+ "w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border border-border p-2",
+ line.status === "Complete" && "border-green-500",
+ line.status === "In Progress" && "border-yellow-500"
+ )}
+ >
+ <LuImage className="w-6 h-6 text-muted-foreground" />
+ </div>
+ )}
+
<VStack spacing={0}>
- <span className="font-mono font-semibold">A932023</span>
+ <span className="font-mono font-semibold">
+ {line.itemReadableId}
+ </span>
<span className="font-mono text-muted-foreground text-xs">
- Rev 0
+ {line.customerPartId}
+ {line.customerPartRevision && ` (${line.customerPartRevision})`}
</span>
</VStack>
</HStack>
- {/* <HStack spacing={1}>
- {false ? (
- <EmployeeAvatar employeeId={null} className="flex-shrink-0" />
- ) : (
- <Avatar className="flex-shrink-0" size="xs" />
- )} */}
- <IconButton aria-label="More" icon={<MdMoreVert />} variant="ghost" />
- {/* </HStack> */}
+
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ aria-label="More"
+ icon={<MdMoreVert />}
+ variant="ghost"
+ onClick={(e) => e.stopPropagation()}
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent>
+ <DropdownMenuItem>Delete Line</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
</HStack>
{disclosure.isOpen && (
<VStack className="border-b border-border">
diff --git a/apps/carbon/app/routes/x+/quote+/new.tsx b/apps/carbon/app/routes/x+/quote+/new.tsx
new file mode 100644
index 0000000000..bb2ffb5a73
--- /dev/null
+++ b/apps/carbon/app/routes/x+/quote+/new.tsx
@@ -0,0 +1,81 @@
+import { validationError, validator } from "@carbon/remix-validated-form";
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { redirect } from "@remix-run/node";
+import { useUrlParams, useUser } from "~/hooks";
+import type { QuotationStatusType } from "~/modules/sales";
+import { QuoteForm, quoteValidator, upsertQuote } from "~/modules/sales";
+import { getNextSequence, rollbackNextSequence } from "~/modules/settings";
+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 }: ActionFunctionArgs) {
+ assertIsPost(request);
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: "sales",
+ });
+
+ const formData = await request.formData();
+ const validation = await validator(quoteValidator).validate(formData);
+
+ if (validation.error) {
+ return validationError(validation.error);
+ }
+
+ const nextSequence = await getNextSequence(client, "quote", companyId);
+ if (nextSequence.error) {
+ throw redirect(
+ path.to.newQuote,
+ await flash(
+ request,
+ error(nextSequence.error, "Failed to get next sequence")
+ )
+ );
+ }
+
+ const createQuote = await upsertQuote(client, {
+ ...validation.data,
+ quoteId: nextSequence.data,
+ companyId,
+ createdBy: userId,
+ customFields: setCustomFields(formData),
+ });
+
+ if (createQuote.error || !createQuote.data?.[0]) {
+ // TODO: this should be done as a transaction
+ await rollbackNextSequence(client, "quote", companyId);
+ throw redirect(
+ path.to.quotes,
+ await flash(request, error(createQuote.error, "Failed to insert quote"))
+ );
+ }
+
+ const order = createQuote.data?.[0];
+
+ throw redirect(path.to.quote(order.id!));
+}
+
+export default function QuoteNewRoute() {
+ const { defaults } = useUser();
+ const [params] = useUrlParams();
+ const customerId = params.get("customerId");
+ const initialValues = {
+ customerContactId: "",
+ customerId: customerId ?? "",
+ customerReference: "",
+ expirationDate: "",
+ dueDate: "",
+ locationId: defaults?.locationId ?? "",
+ quoteId: undefined,
+ status: "Draft" as QuotationStatusType,
+ };
+
+ return (
+ <div className="w-1/2 max-w-[600px] min-w-[420px] mx-auto mt-8">
+ <QuoteForm initialValues={initialValues} />
+ </div>
+ );
+}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
index 1d98c0e3f7..1a99501eef 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
@@ -57,7 +57,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export async function action({ request, params }: ActionFunctionArgs) {
assertIsPost(request);
const { client, userId } = await requirePermissions(request, {
- update: "parts",
+ update: "sales",
});
const { rfqId: id } = params;
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index 911b948f16..d4dcf70bb7 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -573,7 +573,7 @@ export const path = {
quoteInternalDocuments: (id: string) =>
generatePath(`${x}/quote/${id}/internal`),
quoteLine: (quoteId: string, id: string) =>
- generatePath(`${x}/quote/${quoteId}/lines/${id}/details`),
+ generatePath(`${x}/quote/${quoteId}/${id}/details`),
quoteMaterial: (
quoteId: string,
lineId: string,
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 2cfe7f963d..2d3f550e27 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -12826,10 +12826,10 @@ export type Database = {
id: string
itemId: string
itemReadableId: string | null
+ methodType: Database["public"]["Enums"]["methodType"]
modelUploadId: string | null
quoteId: string
quoteRevisionId: number
- replenishmentSystem: string | null
status: Database["public"]["Enums"]["quoteLineStatus"]
unitOfMeasureCode: string | null
updatedAt: string | null
@@ -12846,10 +12846,10 @@ export type Database = {
id?: string
itemId: string
itemReadableId?: string | null
+ methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
quoteId: string
quoteRevisionId?: number
- replenishmentSystem?: string | null
status?: Database["public"]["Enums"]["quoteLineStatus"]
unitOfMeasureCode?: string | null
updatedAt?: string | null
@@ -12866,10 +12866,10 @@ export type Database = {
id?: string
itemId?: string
itemReadableId?: string | null
+ methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
quoteId?: string
quoteRevisionId?: number
- replenishmentSystem?: string | null
status?: Database["public"]["Enums"]["quoteLineStatus"]
unitOfMeasureCode?: string | null
updatedAt?: string | null
@@ -22868,6 +22868,7 @@ export type Database = {
}
quoteLines: {
Row: {
+ autodeskUrn: string | null
companyId: string | null
createdBy: string | null
customerPartId: string | null
@@ -22878,6 +22879,12 @@ export type Database = {
id: string | null
itemId: string | null
itemReadableId: string | null
+ methodType: Database["public"]["Enums"]["methodType"] | null
+ modelId: string | null
+ modelName: string | null
+ modelPath: string | null
+ modelSize: number | null
+ modelUploadId: string | null
pricingDiscountPercent: number | null
pricingExtendedPrice: number | null
pricingLeadTime: number | null
@@ -22886,8 +22893,8 @@ export type Database = {
pricingUnitCost: number | null
quoteId: string | null
quoteRevisionId: number | null
- replenishmentSystem: string | null
status: Database["public"]["Enums"]["quoteLineStatus"] | null
+ thumbnailPath: string | null
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
diff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.ts
index 2cfe7f963d..2d3f550e27 100644
--- a/packages/database/supabase/functions/lib/types.ts
+++ b/packages/database/supabase/functions/lib/types.ts
@@ -12826,10 +12826,10 @@ export type Database = {
id: string
itemId: string
itemReadableId: string | null
+ methodType: Database["public"]["Enums"]["methodType"]
modelUploadId: string | null
quoteId: string
quoteRevisionId: number
- replenishmentSystem: string | null
status: Database["public"]["Enums"]["quoteLineStatus"]
unitOfMeasureCode: string | null
updatedAt: string | null
@@ -12846,10 +12846,10 @@ export type Database = {
id?: string
itemId: string
itemReadableId?: string | null
+ methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
quoteId: string
quoteRevisionId?: number
- replenishmentSystem?: string | null
status?: Database["public"]["Enums"]["quoteLineStatus"]
unitOfMeasureCode?: string | null
updatedAt?: string | null
@@ -12866,10 +12866,10 @@ export type Database = {
id?: string
itemId?: string
itemReadableId?: string | null
+ methodType?: Database["public"]["Enums"]["methodType"]
modelUploadId?: string | null
quoteId?: string
quoteRevisionId?: number
- replenishmentSystem?: string | null
status?: Database["public"]["Enums"]["quoteLineStatus"]
unitOfMeasureCode?: string | null
updatedAt?: string | null
@@ -22868,6 +22868,7 @@ export type Database = {
}
quoteLines: {
Row: {
+ autodeskUrn: string | null
companyId: string | null
createdBy: string | null
customerPartId: string | null
@@ -22878,6 +22879,12 @@ export type Database = {
id: string | null
itemId: string | null
itemReadableId: string | null
+ methodType: Database["public"]["Enums"]["methodType"] | null
+ modelId: string | null
+ modelName: string | null
+ modelPath: string | null
+ modelSize: number | null
+ modelUploadId: string | null
pricingDiscountPercent: number | null
pricingExtendedPrice: number | null
pricingLeadTime: number | null
@@ -22886,8 +22893,8 @@ export type Database = {
pricingUnitCost: number | null
quoteId: string | null
quoteRevisionId: number | null
- replenishmentSystem: string | null
status: Database["public"]["Enums"]["quoteLineStatus"] | null
+ thumbnailPath: string | null
unitOfMeasureCode: string | null
updatedAt: string | null
updatedBy: string | null
diff --git a/packages/database/supabase/migrations/20240715024405_quotes.sql b/packages/database/supabase/migrations/20240715024405_quotes.sql
index 974e2ec568..da39090916 100644
--- a/packages/database/supabase/migrations/20240715024405_quotes.sql
+++ b/packages/database/supabase/migrations/20240715024405_quotes.sql
@@ -71,7 +71,7 @@ CREATE TABLE "quoteLine" (
"description" TEXT NOT NULL,
"customerPartId" TEXT,
"customerPartRevision" TEXT,
- "replenishmentSystem" TEXT,
+ "methodType" "methodType" NOT NULL DEFAULT 'Make',
"unitOfMeasureCode" TEXT,
"companyId" TEXT NOT NULL,
"createdBy" TEXT NOT NULL,
diff --git a/packages/database/supabase/migrations/20240715134816_quote-pricing.sql b/packages/database/supabase/migrations/20240715134816_quote-pricing.sql
index 513bb634cf..b687a1d2d5 100644
--- a/packages/database/supabase/migrations/20240715134816_quote-pricing.sql
+++ b/packages/database/supabase/migrations/20240715134816_quote-pricing.sql
@@ -22,18 +22,6 @@ CREATE TABLE "quoteLinePrice" (
CREATE INDEX "quoteLinePrice_quoteId_idx" ON "quoteLinePrice" ("quoteId");
-CREATE OR REPLACE VIEW "quoteLines" WITH(SECURITY_INVOKER=true) AS (
- SELECT
- ql.*,
- qlp."quantity" AS "pricingQuantity",
- qlp."unitCost" AS "pricingUnitCost",
- qlp."leadTime" AS "pricingLeadTime",
- qlp."discountPercent" AS "pricingDiscountPercent",
- qlp."markupPercent" AS "pricingMarkupPercent",
- qlp."extendedPrice" AS "pricingExtendedPrice"
- FROM "quoteLine" ql
- LEFT JOIN "quoteLinePrice" qlp ON ql."id" = qlp."quoteLineId"
-);
ALTER TABLE "quoteLinePrice" ENABLE ROW LEVEL SECURITY;
diff --git a/packages/database/supabase/migrations/20240719014956_model-uploads-thumbnail.sql b/packages/database/supabase/migrations/20240719014956_model-uploads-thumbnail.sql
index bb948daada..089e652e9a 100644
--- a/packages/database/supabase/migrations/20240719014956_model-uploads-thumbnail.sql
+++ b/packages/database/supabase/migrations/20240719014956_model-uploads-thumbnail.sql
@@ -90,4 +90,28 @@ CREATE OR REPLACE VIEW "salesRfqLines" WITH(SECURITY_INVOKER=true) AS
i.name as "itemName"
FROM "salesRfqLine" srl
LEFT JOIN "item" i ON i.id = srl."itemId"
- LEFT JOIN "modelUpload" mu ON mu.id = srl."modelUploadId";
\ No newline at end of file
+ LEFT JOIN "modelUpload" mu ON mu.id = srl."modelUploadId";
+
+
+DROP VIEW "quoteLines";
+CREATE OR REPLACE VIEW "quoteLines" WITH(SECURITY_INVOKER=true) AS (
+ SELECT
+ ql.*,
+ qlp."quantity" AS "pricingQuantity",
+ qlp."unitCost" AS "pricingUnitCost",
+ qlp."leadTime" AS "pricingLeadTime",
+ qlp."discountPercent" AS "pricingDiscountPercent",
+ qlp."markupPercent" AS "pricingMarkupPercent",
+ qlp."extendedPrice" AS "pricingExtendedPrice",
+ COALESCE(mu.id, imu.id) as "modelId",
+ COALESCE(mu."autodeskUrn", imu."autodeskUrn") as "autodeskUrn",
+ COALESCE(mu."modelPath", imu."modelPath") as "modelPath",
+ COALESCE(mu."thumbnailPath", imu."thumbnailPath") as "thumbnailPath",
+ COALESCE(mu."name", imu."name") as "modelName",
+ COALESCE(mu."size", imu."size") as "modelSize"
+ FROM "quoteLine" ql
+ LEFT JOIN "quoteLinePrice" qlp ON ql."id" = qlp."quoteLineId"
+ LEFT JOIN "modelUpload" mu ON ql."modelUploadId" = mu."id"
+ INNER JOIN "item" i ON i.id = ql."itemId"
+ LEFT JOIN "modelUpload" imu ON imu.id = i."modelUploadId"
+);
\ No newline at end of file
diff --git a/packages/utils/src/color.ts b/packages/utils/src/color.ts
index 526fc36cf1..b9dafbe62d 100644
--- a/packages/utils/src/color.ts
+++ b/packages/utils/src/color.ts
@@ -18,7 +18,7 @@ const colors = [
{ background: "#4f46e5", color: "#ffffff" },
{ background: "#caffbf", color: "#000000" },
{ background: "#e2eeff", color: "#3671c7" },
- { background: "#ffc6ff", color: "#7f47b3" },
+ { color: "#c6c9ff", background: "#474ab3" },
{ background: "#cdbef5", color: "#5b3baf" },
{ background: "#5d4037", color: "#ffffff" },
];