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.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: crud for quote lines
Brad Barbinf770077c4081
diff --git a/apps/carbon/app/components/Assignee.tsx b/apps/carbon/app/components/Assignee.tsxindex 74302c2d64..682eb3d70b 100644--- a/apps/carbon/app/components/Assignee.tsx+++ b/apps/carbon/app/components/Assignee.tsx@@ -33,7 +33,17 @@ export type ComboboxProps = Omit<const Assign = forwardRef<HTMLButtonElement, ComboboxProps>((- { id, table, size, value, isReadOnly, placeholder, onChange, ...props },+ {+ id,+ table,+ size,+ value,+ isReadOnly,+ placeholder,+ onChange,+ className,+ ...props+ },ref) => {const [open, setOpen] = useState(false);@@ -73,7 +83,10 @@ const Assign = forwardRef<HTMLButtonElement, ComboboxProps>(<Popover open={open} onOpenChange={setOpen}><PopoverTrigger asChild><button- className="rounded-md px-2.5 py-0.5 text-sm hover:bg-muted/50 transition-colors cursor-pointer border border-border"+ className={cn(+ "rounded-md px-2.5 py-0.5 text-sm hover:bg-muted/50 transition-colors cursor-pointer border border-border",+ className+ )}role="combobox"aria-expanded={open}ref={ref}diff --git a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsxindex 8f1565129f..fe6ce9c3da 100644--- a/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx+++ b/apps/carbon/app/modules/items/ui/Item/BillOfProcess.tsx@@ -228,7 +228,7 @@ const BillOfProcess = ({ makeMethodId, operations }: BillOfProcessProps) => {updatedBy: userId,}).eq("methodOperationId", selectedItemId!);- }, 1000);+ }, 3000);const onUploadImage = async (file: File) => {const fileName = `${companyId}/parts/${selectedItemId}/${Math.random()diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocuments.tsx b/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocuments.tsxindex c2becdf909..347dc7af40 100644--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocuments.tsx+++ b/apps/carbon/app/modules/items/ui/Item/ItemDocuments/ItemDocuments.tsx@@ -138,7 +138,7 @@ const ItemDocuments = ({</Hyperlink></HStack></Td>- <Td>+ <Td className="text-xs font-mono">{convertKbToString(Math.floor((file.metadata?.size ?? 0) / 1024))}diff --git a/apps/carbon/app/modules/sales/sales.service.ts b/apps/carbon/app/modules/sales/sales.service.tsindex fe0a856ec2..48dcb0c293 100644--- a/apps/carbon/app/modules/sales/sales.service.ts+++ b/apps/carbon/app/modules/sales/sales.service.ts@@ -412,6 +412,16 @@ export async function getFilesByRfqId(};}+export async function getFilesByQuoteLineId(+ client: SupabaseClient<Database>,+ companyId: string,+ quoteLineId: string+) {+ return client.storage+ .from("private")+ .list(`${companyId}/quote-line/${quoteLineId}`);+}+export async function getQuote(client: SupabaseClient<Database>,quoteId: string@@ -472,24 +482,12 @@ export async function getQuoteAssemblies(return client.from("quoteMakeMethod").select("*").eq("quoteId", quoteId);}-export async function getQuoteExternalDocuments(+export async function getQuoteDocuments(client: SupabaseClient<Database>,companyId: string,quoteId: string) {- return client.storage- .from("private")- .list(`${companyId}/quote/external/${quoteId}`);-}--export async function getQuoteInternalDocuments(- client: SupabaseClient<Database>,- companyId: string,- quoteId: string-) {- return client.storage- .from("private")- .list(`${companyId}/quote/internal/${quoteId}`);+ return client.storage.from("private").list(`${companyId}/quote/${quoteId}`);}export async function getQuoteLine(@@ -856,8 +854,11 @@ export async function insertQuoteLinePrice(let unitCost = 0;- if (quoteLine.data?.replenishmentSystem === "Buy") {+ if (quoteLine.data?.methodType !== "Make") {const itemId = quoteLine.data?.itemId;+ if (!itemId) {+ throw new Error("itemId not found");+ }const [itemCost] = await Promise.all([client.from("itemCost").select("unitCost").eq("itemId", itemId).single(),]);diff --git a/apps/carbon/app/modules/sales/ui/Quotes/DeleteQuoteLine.tsx b/apps/carbon/app/modules/sales/ui/Quotes/DeleteQuoteLine.tsxnew file mode 100644index 0000000000..bf6b9e96cc--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/DeleteQuoteLine.tsx@@ -0,0 +1,26 @@+import { useParams } from "@remix-run/react";+import { ConfirmDelete } from "~/components/Modals";+import { path } from "~/utils/path";+import type { QuotationLine } from "../../types";++export default function DeleteQuoteLine({+ line,+ onCancel,+}: {+ line: QuotationLine;+ onCancel: () => void;+}) {+ const { quoteId } = useParams();+ if (!quoteId) throw new Error("id not found");+ if (!line.id) return null;++ return (+ <ConfirmDelete+ action={path.to.deleteQuoteLine(quoteId, line.id)}+ name={line.itemReadableId ?? "this line"}+ text={`Are you sure you want to delete the line: ${line.itemReadableId}? This cannot be undone.`}+ onCancel={onCancel}+ onSubmit={onCancel}+ />+ );+}diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsxnew file mode 100644index 0000000000..5e6ac1f046--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteBreadcrumbs.tsx@@ -0,0 +1,40 @@+import { Button } from "@carbon/react";+import { Link, useParams } from "@remix-run/react";+import { RiProgress4Line } from "react-icons/ri";+import { BreadcrumbItem, Breadcrumbs } from "~/components";+import { useRouteData } from "~/hooks";+import { path } from "~/utils/path";+import type { Quotation, QuotationLine } from "../../types";++const QuoteBreadcrumbs = () => {+ const { quoteId, lineId, makeMethodId } = useParams();+ if (!quoteId) throw new Error("quoteId not found");++ const routeData = useRouteData<{ quote: Quotation; lines: QuotationLine[] }>(+ path.to.quote(quoteId)+ );+ const line = routeData?.lines.find((line) => line.id === lineId);++ return (+ <Breadcrumbs className="my-1">+ <BreadcrumbItem>+ <Button leftIcon={<RiProgress4Line />} variant="ghost" asChild>+ <Link to={path.to.quoteDetails(quoteId)}>+ {routeData?.quote?.quoteId}+ </Link>+ </Button>+ </BreadcrumbItem>+ {line && (+ <BreadcrumbItem>+ <Button variant="ghost" asChild>+ <Link to={path.to.quoteLine(quoteId, line.id!)}>+ {line.itemReadableId}+ </Link>+ </Button>+ </BreadcrumbItem>+ )}+ </Breadcrumbs>+ );+};++export default QuoteBreadcrumbs;diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocumentForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocumentForm.tsxindex e49b3bcc9a..c18b55d5ca 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocumentForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocumentForm.tsx@@ -8,10 +8,9 @@ import { path } from "~/utils/path";type QuoteDocumentFormProps = {id: string;- isExternal: boolean;};-const QuoteDocumentForm = ({ id, isExternal }: QuoteDocumentFormProps) => {+const QuoteDocumentForm = ({ id }: QuoteDocumentFormProps) => {const submit = useSubmit();const { company } = useUser();const { supabase } = useSupabase();@@ -19,9 +18,7 @@ const QuoteDocumentForm = ({ id, isExternal }: QuoteDocumentFormProps) => {const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {if (e.target.files && supabase && company) {const file = e.target.files[0];- const fileName = `${company.id}/quote/${- isExternal ? "external" : "internal"- }/${id}/${file.name}`;+ const fileName = `${company.id}/quote/${id}/${file.name}`;const fileUpload = await supabase.storage.from("private")diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocuments.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocuments.tsxindex ed6699b6ab..700dd70fe4 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocuments.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/QuoteDocuments.tsx@@ -28,17 +28,11 @@ import { useQuoteDocuments } from "./useQuoteDocuments";type QuoteDocumentsProps = {attachments: QuotationAttachment[];- isExternal: boolean;id: string;};-const QuoteDocuments = ({- attachments,- isExternal,- id,-}: QuoteDocumentsProps) => {+const QuoteDocuments = ({ attachments, id }: QuoteDocumentsProps) => {const { canDelete, download, deleteAttachment, getPath } = useQuoteDocuments({- isExternal,id,});@@ -50,7 +44,7 @@ const QuoteDocuments = ({<CardTitle>Documents</CardTitle></CardHeader><CardAction>- <QuoteDocumentForm isExternal={false} id={id} />+ <QuoteDocumentForm id={id} /></CardAction></HStack><CardContent>@@ -88,7 +82,7 @@ const QuoteDocuments = ({</Hyperlink></HStack></Td>- <Td>+ <Td className="text-xs font-mono">{convertKbToString(Math.floor((attachment.metadata?.size ?? 0) / 1024))}@@ -128,7 +122,7 @@ const QuoteDocuments = ({colSpan={24}className="py-8 text-muted-foreground text-center">- No {isExternal ? "external" : "internal"} attachments+ No files uploaded</Td></Tr>)}diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/useQuoteDocuments.ts b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/useQuoteDocuments.tsindex e4d5164ba2..f95db000e9 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/useQuoteDocuments.ts+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteDocuments/useQuoteDocuments.ts@@ -6,11 +6,10 @@ import { useSupabase } from "~/lib/supabase";import type { QuotationAttachment } from "~/modules/sales/types";type Props = {- isExternal: boolean;id: string;};-export const useQuoteDocuments = ({ isExternal, id }: Props) => {+export const useQuoteDocuments = ({ id }: Props) => {const permissions = usePermissions();const { company } = useUser();const { supabase } = useSupabase();@@ -20,11 +19,9 @@ export const useQuoteDocuments = ({ isExternal, id }: Props) => {const getPath = useCallback((attachment: QuotationAttachment) => {- return `${company.id}/quote/${- isExternal ? "external" : "internal"- }/${id}/${attachment.name}`;+ return `${company.id}/quote/${id}/${attachment.name}`;},- [company.id, isExternal, id]+ [company.id, id]);const deleteAttachment = useCallback(diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsxindex aca30b9b44..a5a9022f85 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteHeader.tsx@@ -12,6 +12,7 @@ import {import { useParams } from "@remix-run/react";import { LuCheckCheck, LuChevronDown, LuEye } from "react-icons/lu";import { RiProgress4Line } from "react-icons/ri";+import { Assignee, useOptimisticAssignment } from "~/components";import { useRouteData } from "~/hooks";import type { Quotation } from "~/modules/sales";@@ -23,6 +24,15 @@ const QuoteHeader = () => {const routeData = useRouteData<{ quote: Quotation }>(path.to.quote(quoteId));+ const optimisticAssignment = useOptimisticAssignment({+ id: quoteId,+ table: "quote",+ });+ const assignee =+ optimisticAssignment !== undefined+ ? optimisticAssignment+ : routeData?.quote?.assignee;+return (<div className="flex flex-shrink-0 items-center justify-between px-4 py-2 bg-card border-b border-border"><HStack className="w-full justify-between">@@ -35,6 +45,12 @@ const QuoteHeader = () => {</Badge></HStack><HStack>+ <Assignee+ id={quoteId}+ table="quote"+ value={assignee ?? ""}+ className="h-8"+ /><Button leftIcon={<LuEye />} variant="secondary">Preview</Button>diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsxnew file mode 100644index 0000000000..4d3466efbe--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx@@ -0,0 +1,370 @@+import {+ Card,+ CardAction,+ CardContent,+ CardHeader,+ CardTitle,+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+ File,+ HStack,+ IconButton,+ Table,+ Tbody,+ Td,+ Th,+ Thead,+ Tr,+ toast,+} from "@carbon/react";+import { convertKbToString } from "@carbon/utils";+import type { FileObject } from "@supabase/storage-js";+import { LuAxis3D, LuUpload } from "react-icons/lu";+import { MdMoreVert } from "react-icons/md";+import { DocumentPreview, Hyperlink } from "~/components";+import { DocumentIcon, getDocumentType } from "~/modules/documents";+import type { ItemFile, ModelUpload } from "~/modules/items";++import { useNavigate, useRevalidator, useSubmit } from "@remix-run/react";+import type { ChangeEvent } from "react";+import { usePermissions, useUser } from "~/hooks";+import { useSupabase } from "~/lib/supabase";+import { path } from "~/utils/path";++import { useCallback } from "react";++const useQuoteLineDocuments = ({+ quoteId,+ quoteLineId,+}: {+ quoteId: string;+ quoteLineId: string;+}) => {+ const navigate = useNavigate();+ const permissions = usePermissions();+ const revalidator = useRevalidator();+ const { supabase } = useSupabase();+ const { company } = useUser();++ const canDelete = permissions.can("delete", "sales");+ const getPath = useCallback(+ (file: ItemFile) => {+ return `${company.id}/quote-line/${quoteLineId}/${file.name}`;+ },+ [company.id, quoteLineId]+ );++ const deleteFile = useCallback(+ async (file: ItemFile) => {+ const fileDelete = await supabase?.storage+ .from("private")+ .remove([getPath(file)]);++ if (!fileDelete || fileDelete.error) {+ toast.error(fileDelete?.error?.message || "Error deleting file");+ return;+ }++ toast.success("File deleted successfully");+ revalidator.revalidate();+ },+ [getPath, supabase?.storage, revalidator]+ );++ const deleteModel = useCallback(+ async (quoteLineId: string) => {+ if (!quoteLineId || !supabase) return;++ const { error } = await supabase+ .from("quoteLine")+ .update({ modelUploadId: null })+ .eq("id", quoteLineId);+ if (error) {+ toast.error("Error removing model from line");+ return;+ }+ toast.success("Model removed from line");+ revalidator.revalidate();+ },+ [supabase, revalidator]+ );++ const download = useCallback(+ async (file: ItemFile) => {+ const result = await supabase?.storage+ .from("private")+ .download(getPath(file));++ if (!result || result.error) {+ toast.error(result?.error?.message || "Error downloading file");+ return;+ }++ const a = document.createElement("a");+ document.body.appendChild(a);+ const url = window.URL.createObjectURL(result.data);+ a.href = url;+ a.download = file.name;+ a.click();++ setTimeout(() => {+ window.URL.revokeObjectURL(url);+ document.body.removeChild(a);+ }, 0);+ },+ [supabase?.storage, getPath]+ );++ const viewModel = useCallback(+ (model: ModelUpload) => {+ if (!model?.autodeskUrn) {+ toast.error("Autodesk URN not found");+ return;+ }+ navigate(path.to.file.cadModel(model?.autodeskUrn));+ },+ [navigate]+ );++ return {+ canDelete,+ deleteFile,+ deleteModel,+ download,+ getPath,+ viewModel,+ };+};++type QuoteLineDocumentsProps = {+ files: FileObject[];+ quoteId: string;+ quoteLineId: string;+ modelUpload?: ModelUpload;+};++const QuoteLineDocuments = ({+ files,+ quoteId,+ quoteLineId,+ modelUpload,+}: QuoteLineDocumentsProps) => {+ const { canDelete, download, deleteFile, deleteModel, getPath, viewModel } =+ useQuoteLineDocuments({+ quoteId,+ quoteLineId,+ });++ return (+ <Card className="flex-grow">+ <HStack className="justify-between items-start">+ <CardHeader>+ <CardTitle>Files</CardTitle>+ </CardHeader>+ <CardAction>+ <QuoteLineDocumentForm quoteId={quoteId} quoteLineId={quoteLineId} />+ </CardAction>+ </HStack>+ <CardContent>+ <Table>+ <Thead>+ <Tr>+ <Th>Name</Th>+ <Th>Size</Th>+ <Th />+ </Tr>+ </Thead>+ <Tbody>+ {modelUpload?.autodeskUrn && (+ <Tr>+ <Td>+ <HStack>+ <LuAxis3D className="text-green-500 w-6 h-6" />+ <Hyperlink+ target="_blank"+ onClick={() => viewModel(modelUpload)}+ >+ {modelUpload?.autodeskUrn+ ? modelUpload.modelName+ : "Uploading..."}+ </Hyperlink>+ </HStack>+ </Td>+ <Td>+ {modelUpload.modelSize+ ? convertKbToString(+ Math.floor((modelUpload.modelSize ?? 0) / 1024)+ )+ : "--"}+ </Td>+ <Td>+ <div className="flex justify-end w-full">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="More"+ icon={<MdMoreVert />}+ variant="secondary"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ onClick={() => viewModel(modelUpload)}+ >+ View+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={!canDelete}+ onClick={() => deleteModel(quoteLineId)}+ >+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </Td>+ </Tr>+ )}+ {files.map((file) => {+ const type = getDocumentType(file.name);+ return (+ <Tr key={file.id}>+ <Td>+ <HStack>+ <DocumentIcon type={type} />+ <Hyperlink onClick={() => download(file)}>+ {["PDF", "Image"].includes(type) ? (+ <DocumentPreview+ bucket="private"+ pathToFile={getPath(file)}+ // @ts-ignore+ type={type}+ >+ {file.name}+ </DocumentPreview>+ ) : (+ file.name+ )}+ </Hyperlink>+ </HStack>+ </Td>+ <Td>+ {convertKbToString(+ Math.floor((file.metadata?.size ?? 0) / 1024)+ )}+ </Td>+ <Td>+ <div className="flex justify-end w-full">+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="More"+ icon={<MdMoreVert />}+ variant="secondary"+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem onClick={() => download(file)}>+ Download+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={!canDelete}+ onClick={() => deleteFile(file)}+ >+ Delete+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>+ </Td>+ </Tr>+ );+ })}+ {files.length === 0 && !modelUpload && (+ <Tr>+ <Td+ colSpan={24}+ className="py-8 text-muted-foreground text-center"+ >+ No files+ </Td>+ </Tr>+ )}+ </Tbody>+ </Table>+ </CardContent>+ </Card>+ );+};++export default QuoteLineDocuments;++type QuoteLineDocumentFormProps = {+ quoteId: string;+ quoteLineId: string;+};++const QuoteLineDocumentForm = ({+ quoteId,+ quoteLineId,+}: QuoteLineDocumentFormProps) => {+ const submit = useSubmit();+ const { company } = useUser();+ const { supabase } = useSupabase();++ const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {+ if (e.target.files && supabase && company) {+ const file = e.target.files[0];+ const fileName = `${company.id}/quote-line/${quoteLineId}/${file.name}`;++ const fileUpload = await supabase.storage+ .from("private")+ .upload(fileName, file, {+ cacheControl: `${12 * 60 * 60}`,+ });++ if (fileUpload.error) {+ toast.error("Failed to upload file");+ }++ if (fileUpload.data?.path) {+ toast.success("File uploaded");+ submitFileData({+ path: fileUpload.data.path,+ name: file.name,+ size: file.size,+ });+ }+ }+ };++ const submitFileData = ({+ path: filePath,+ name,+ size,+ }: {+ path: string;+ name: string;+ size: number;+ }) => {+ const formData = new FormData();+ formData.append("path", filePath);+ formData.append("name", name);+ formData.append("size", Math.round(size / 1024).toString());+ formData.append("sourceDocument", "Quote");+ formData.append("sourceDocumentId", quoteId);++ submit(formData, {+ method: "post",+ action: path.to.newDocument,+ });+ };++ return (+ <File leftIcon={<LuUpload />} onChange={uploadFile}>+ New+ </File>+ );+};diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsxindex cf1c0877fc..87d2a81c5e 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineForm.tsx@@ -15,15 +15,15 @@ import {ModalCardHeader,ModalCardProvider,ModalCardTitle,+ useDisclosure,VStack,- cn,} from "@carbon/react";import { ValidatedForm } from "@carbon/remix-validated-form";-import { useNavigate, useParams } from "@remix-run/react";+import { useParams } from "@remix-run/react";import { useState } from "react";-import { BsDownload, BsThreeDotsVertical, BsUpload } from "react-icons/bs";-import { LuTrash } from "react-icons/lu";+import { BsThreeDotsVertical } from "react-icons/bs";+import { LuDownload, LuTrash, LuUpload } from "react-icons/lu";import type { z } from "zod";import {CustomFormFields,@@ -38,8 +38,12 @@ import {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 type { Quotation, QuotationLine } from "~/modules/sales";+import {+ DeleteQuoteLine,+ quoteLineStatusType,+ quoteLineValidator,+} from "~/modules/sales";import { path } from "~/utils/path";type QuoteLineFormProps = {@@ -53,7 +57,6 @@ const QuoteLineForm = ({type,onClose,}: QuoteLineFormProps) => {- const navigate = useNavigate();const permissions = usePermissions();const { company } = useUser();const { supabase } = useSupabase();@@ -110,147 +113,165 @@ const QuoteLineForm = ({});};+ const deleteDisclosure = useDisclosure();+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);- }}- />+ <>+ <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+ ? itemData?.itemReadableId ?? "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={deleteDisclosure.onOpen}>+ <DropdownMenuIcon icon={<LuTrash />} />+ Delete Line+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={itemData.methodType !== "Make"}+ >+ <DropdownMenuIcon icon={<LuDownload />} />+ Get Method+ </DropdownMenuItem>+ <DropdownMenuItem+ disabled={itemData.methodType !== "Make"}+ >+ <DropdownMenuIcon icon={<LuUpload />} />+ Save Method+ </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 }))- }- />+ <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,- }));- }}- />+ <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"- />+ <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")}- />+ <Select+ name="status"+ label="Line Status"+ options={quoteLineStatusType.map((s) => ({+ label: s,+ value: s,+ }))}+ />- <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>+ <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>+ {isEditing && deleteDisclosure.isOpen && (+ <DeleteQuoteLine+ line={initialValues as QuotationLine}+ onCancel={deleteDisclosure.onClose}+ />+ )}+ </>);};diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsxindex 2e148a7ae6..7662550014 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx@@ -3,6 +3,7 @@ import {HStack,MenuIcon,MenuItem,+ Progress,useDisclosure,} from "@carbon/react";import { formatDate } from "@carbon/utils";@@ -129,29 +130,17 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {},},{- accessorKey: "name",- header: "Name",- cell: (item) => {- if (item.getValue<string>()) {- return item.getValue<string>().substring(0, 50);- }- return null;- },- },- {- id: "itemIds",- header: "Parts",- cell: ({ row }) => row.original.itemIds?.length ?? 0,- meta: {- filter: {- type: "static",- options: items.map((item) => ({- value: item.id,- label: item.id,- helperText: item.name,- })),- isArray: true,- },+ header: "Progress",+ cell: ({ row }) => {+ const lines = row.original.lines ?? 0;+ const completedLines = row.original.completedLines ?? 0;+ return (+ <Progress+ leftLabel={completedLines.toString()}+ rightLabel={lines.toString()}+ value={lines === 0 ? 0 : (completedLines / lines) * 100}+ />+ );},},{@@ -287,7 +276,7 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {];return [...defaultColumns, ...customColumns];- }, [customers, items, people, customColumns, fetcher]);+ }, [customers, people, customColumns, fetcher]);const renderContextMenu = useMemo(() => {// eslint-disable-next-line react/display-namediff --git a/apps/carbon/app/modules/sales/ui/Quotes/index.ts b/apps/carbon/app/modules/sales/ui/Quotes/index.tsindex ac91321f74..ab1458dbbb 100644--- a/apps/carbon/app/modules/sales/ui/Quotes/index.ts+++ b/apps/carbon/app/modules/sales/ui/Quotes/index.ts@@ -1,15 +1,21 @@+import DeleteQuoteLine from "./DeleteQuoteLine";import QuoteBoMExplorer from "./QuoteBoMExplorer";+import QuoteBreadcrumbs from "./QuoteBreadcrumbs";import QuoteDocuments from "./QuoteDocuments";import QuoteForm from "./QuoteForm";import QuoteHeader from "./QuoteHeader";+import QuoteLineDocuments from "./QuoteLineDocuments";import QuoteLineForm from "./QuoteLineForm";import QuotesTable from "./QuotesTable";export {+ DeleteQuoteLine,QuoteBoMExplorer,+ QuoteBreadcrumbs,QuoteDocuments,QuoteForm,QuoteHeader,+ QuoteLineDocuments,QuoteLineForm,QuotesTable,};diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsxindex 0e7bd20e64..a7d838fd97 100644--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx@@ -360,118 +360,113 @@ const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {</div>),},- ];-- if (!item.isTemporary) {- tabs.push(- {- id: 1,- label: "Model",-- content: (- <div className="flex flex-col py-4">- <motion.div- initial={{ opacity: 0, filter: "blur(4px)" }}- animate={{ opacity: 1, filter: "blur(0px)" }}- transition={{- type: "spring",- bounce: 0.2,- duration: 0.75,- delay: 0.15,- }}- >- <CadModel- autodeskUrn={item.data.autodeskUrn ?? null}- metadata={{- salesRfqLineId: item.id,- }}- modelPath={item.data.modelPath ?? null}- uploadClassName="min-h-[300px]"- />- </motion.div>- </div>- ),- },- {- id: 2,- label: "Files",-- content: (- <div className="flex flex-col">- <motion.div- initial={{ opacity: 0, filter: "blur(4px)" }}- animate={{ opacity: 1, filter: "blur(0px)" }}- transition={{- type: "spring",- bounce: 0.2,- duration: 0.75,- delay: 0.15,- }}- >- <SalesRFQLineDocuments- files={item.files ?? []}- modelUpload={item.data}- rfqId={rfqId}- salesRfqLineId={item.id}- />- </motion.div>- </div>- ),- },- {- id: 3,- label: "Internal Notes",-- content: (- <div className="flex flex-col">- <motion.div- initial={{ opacity: 0, filter: "blur(4px)" }}- animate={{ opacity: 1, filter: "blur(0px)" }}- transition={{- type: "spring",- bounce: 0.2,- duration: 0.75,- delay: 0.15,- }}- >- <Editor- className="min-h-[300px]"- initialValue={item.data.internalNotes}- onUpload={onUploadImage}- onChange={onUpdateInternalNotes}- />- </motion.div>- </div>- ),- },- {- id: 4,- label: "External Notes",-- content: (- <div className="flex flex-col">- <motion.div- initial={{ opacity: 0, filter: "blur(4px)" }}- animate={{ opacity: 1, filter: "blur(0px)" }}- transition={{- type: "spring",- bounce: 0.2,- duration: 0.75,- delay: 0.15,+ {+ id: 1,+ label: "Model",+ disabled: item.isTemporary,+ content: (+ <div className="flex flex-col py-4">+ <motion.div+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ bounce: 0.2,+ duration: 0.75,+ delay: 0.15,+ }}+ >+ <CadModel+ autodeskUrn={item.data.autodeskUrn ?? null}+ metadata={{+ salesRfqLineId: item.id,}}- >- <Editor- className="min-h-[300px]"- initialValue={item.data.externalNotes ?? ({} as JSONContent)}- onUpload={onUploadImage}- onChange={onUpdateExternalNotes}- />- </motion.div>- </div>- ),- }- );- }+ modelPath={item.data.modelPath ?? null}+ uploadClassName="min-h-[300px]"+ />+ </motion.div>+ </div>+ ),+ },+ {+ id: 2,+ label: "Files",+ disabled: item.isTemporary,+ content: (+ <div className="flex flex-col">+ <motion.div+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ bounce: 0.2,+ duration: 0.75,+ delay: 0.15,+ }}+ >+ <SalesRFQLineDocuments+ files={item.files ?? []}+ modelUpload={item.data}+ rfqId={rfqId}+ salesRfqLineId={item.id}+ />+ </motion.div>+ </div>+ ),+ },+ {+ id: 3,+ label: "Internal Notes",+ disabled: item.isTemporary,+ content: (+ <div className="flex flex-col">+ <motion.div+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ bounce: 0.2,+ duration: 0.75,+ delay: 0.15,+ }}+ >+ <Editor+ className="min-h-[300px]"+ initialValue={item.data.internalNotes}+ onUpload={onUploadImage}+ onChange={onUpdateInternalNotes}+ />+ </motion.div>+ </div>+ ),+ },+ {+ id: 4,+ label: "External Notes",+ disabled: item.isTemporary,+ content: (+ <div className="flex flex-col">+ <motion.div+ initial={{ opacity: 0, filter: "blur(4px)" }}+ animate={{ opacity: 1, filter: "blur(0px)" }}+ transition={{+ type: "spring",+ bounce: 0.2,+ duration: 0.75,+ delay: 0.15,+ }}+ >+ <Editor+ className="min-h-[300px]"+ initialValue={item.data.externalNotes ?? ({} as JSONContent)}+ onUpload={onUploadImage}+ onChange={onUpdateExternalNotes}+ />+ </motion.div>+ </div>+ ),+ },+ ];return (<SortableListItem<Line>diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.delete.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.delete.tsxnew file mode 100644index 0000000000..201d611a92--- /dev/null+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.delete.tsx@@ -0,0 +1,34 @@+import { json, redirect } from "@remix-run/react";++import type { ActionFunctionArgs } from "@remix-run/node";+import { deleteQuoteLine } from "~/modules/sales";+import { requirePermissions } from "~/services/auth/auth.server";+import { flash } from "~/services/session.server";+import { assertIsPost } from "~/utils/http";+import { path } from "~/utils/path";+import { error } from "~/utils/result";++export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client } = await requirePermissions(request, {+ delete: "sales",+ });++ const { quoteId, lineId: quoteLineId } = params;+ if (!quoteId) throw new Error("Could not find quoteId");+ if (!quoteLineId) throw new Error("Could not find quoteLineId");++ const deleteLine = await deleteQuoteLine(client, quoteLineId);++ if (deleteLine.error) {+ return json(+ path.to.quoteLine(quoteId, quoteLineId),+ await flash(+ request,+ error(deleteLine.error, "Failed to update quote line")+ )+ );+ }++ throw redirect(path.to.quote(quoteId));+}diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsxindex 7f1ecf36f5..1b19caeb10 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.$lineId.details.tsx@@ -1,14 +1,41 @@-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 type { JSONContent } from "@carbon/react";+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Editor,+ toast,+ useDebounce,+} from "@carbon/react";+import { validationError, validator } from "@carbon/remix-validated-form";+import { getLocalTimeZone, today } from "@internationalized/date";+import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";+import { json, redirect } from "@remix-run/node";+import { Outlet, useLoaderData, useParams } from "@remix-run/react";+import { usePermissions, useUser } from "~/hooks";+import { useSupabase } from "~/lib/supabase";+import { CadModel } from "~/modules/items";+import type { QuotationLine } from "~/modules/sales";+import {+ getFilesByQuoteLineId,+ getQuoteLine,+ quotationPricingValidator,+ QuoteLineDocuments,+ QuoteLineForm,+ quoteLineValidator,+ updateQuoteLinePrice,+ 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 const loader = async ({ request, params }: LoaderFunctionArgs) => {- const { client } = await requirePermissions(request, {+ const { client, companyId } = await requirePermissions(request, {view: "sales",});@@ -16,7 +43,10 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {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)]);+ const [line, files] = await Promise.all([+ getQuoteLine(client, lineId),+ getFilesByQuoteLineId(client, companyId, lineId),+ ]);if (line.error) {throw redirect(@@ -27,11 +57,85 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {return json({line: line.data,+ files: files?.data ?? [],});};+export async function action({ request, params }: ActionFunctionArgs) {+ assertIsPost(request);+ const { client, userId } = await requirePermissions(request, {+ create: "purchasing",+ });++ const { quoteId, lineId } = params;+ if (!quoteId) throw new Error("Could not find quoteId");+ if (!lineId) throw new Error("Could not find lineId");++ const formData = await request.formData();+ const intent = formData.get("intent");++ if (intent === "line") {+ const validation = await validator(quoteLineValidator).validate(formData);++ if (validation.error) {+ return validationError(validation.error);+ }++ const { id, ...data } = validation.data;++ const updateQuotationLine = await upsertQuoteLine(client, {+ id: lineId,+ ...data,+ updatedBy: userId,+ customFields: setCustomFields(formData),+ });++ if (updateQuotationLine.error) {+ throw redirect(+ path.to.quoteLine(quoteId, lineId),+ await flash(+ request,+ error(updateQuotationLine.error, "Failed to update quote line")+ )+ );+ }+ } else if (intent === "pricing") {+ const validation = await validator(quotationPricingValidator).validate(+ formData+ );++ if (validation.error) {+ return validationError(validation.error);+ }++ const updateLinePrice = await updateQuoteLinePrice(client, {+ quoteId,+ quoteLineId: lineId,+ ...validation.data,+ updatedBy: userId,+ });++ if (updateLinePrice.error) {+ throw redirect(+ path.to.quoteLine(quoteId, lineId),+ await flash(+ request,+ error(updateLinePrice.error, "Failed to update quote line price")+ )+ );+ }+ }++ throw redirect(path.to.quoteLine(quoteId, lineId));+}+export default function QuoteLine() {- const { line } = useLoaderData<typeof loader>();+ const { line, files } = useLoaderData<typeof loader>();+ const permissions = usePermissions();+ const { quoteId, lineId } = useParams();+ if (!quoteId) throw new Error("Could not find quoteId");+ if (!lineId) throw new Error("Could not find lineId");+const initialValues = {...line,id: line.id ?? undefined,@@ -49,8 +153,84 @@ export default function QuoteLine() {};return (- <VStack spacing={2} className="p-2">+ <><QuoteLineForm initialValues={initialValues} />- </VStack>+ {permissions.is("employee") && (+ <>+ <div className="grid grid-cols-1 xl:grid-cols-2 w-full flex-grow gap-2 ">+ <CadModel+ autodeskUrn={line?.autodeskUrn ?? null}+ metadata={{ quoteLineId: line.id ?? undefined }}+ modelPath={line?.modelPath ?? null}+ title="CAD Model"+ uploadClassName="min-h-[360px]"+ viewerClassName="min-h-[360px]"+ />+ <QuoteLineDocuments+ files={files ?? []}+ quoteId={quoteId}+ quoteLineId={lineId}+ modelUpload={line ?? undefined}+ />+ </div>+ <QuoteLineNotes line={line} />+ <Outlet />+ </>+ )}+ </>);}++const QuoteLineNotes = ({ line }: { line: QuotationLine }) => {+ const {+ id: userId,+ company: { id: companyId },+ } = useUser();+ const { supabase } = useSupabase();++ const onUploadImage = async (file: File) => {+ const fileName = `${companyId}/quote-line/${line.id}/${encodeURIComponent(+ file.name+ )}`;+ const result = await supabase?.storage+ .from("private")+ .upload(fileName, file);++ if (result?.error) {+ toast.error("Failed to upload image");+ throw new Error(result.error.message);+ }++ if (!result?.data) {+ throw new Error("Failed to upload image");+ }++ return `/file/preview/private/${result.data.path}`;+ };++ const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {+ await supabase+ ?.from("quoteLine")+ .update({+ notes: content,+ updatedAt: today(getLocalTimeZone()).toString(),+ updatedBy: userId,+ })+ .eq("id", line.id!);+ }, 3000);++ return (+ <Card>+ <CardHeader>+ <CardTitle>Internal Notes</CardTitle>+ </CardHeader>+ <CardContent>+ <Editor+ initialValue={(line.notes ?? {}) as JSONContent}+ onUpload={onUploadImage}+ onChange={onUpdateInternalNotes}+ />+ </CardContent>+ </Card>+ );+};diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsxindex bea771512a..9abdfa86d2 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.details.tsx@@ -1,10 +1,21 @@-import { VStack } from "@carbon/react";+import type { JSONContent } from "@carbon/react";+import {+ Card,+ CardContent,+ CardHeader,+ CardTitle,+ Editor,+ toast,+ useDebounce,+} from "@carbon/react";import { validationError, validator } from "@carbon/remix-validated-form";+import { getLocalTimeZone, today } from "@internationalized/date";import type { ActionFunctionArgs } from "@remix-run/node";import { redirect } from "@remix-run/node";import { useParams } from "@remix-run/react";import type { FileObject } from "@supabase/storage-js";-import { useRouteData } from "~/hooks";+import { useRouteData, useUser } from "~/hooks";+import { useSupabase } from "~/lib/supabase";import type { Quotation } from "~/modules/sales";import {QuoteDocuments,@@ -83,13 +94,64 @@ export default function QuoteDetailsRoute() {};return (- <VStack spacing={2} className="p-2">+ <><QuoteForm key={initialValues.id} initialValues={initialValues} />- <QuoteDocuments- id={quoteId}- attachments={quoteData?.files ?? []}- isExternal={false}- />- </VStack>+ <QuoteDocuments id={quoteId} attachments={quoteData?.files ?? []} />+ <QuoteNotes quote={quoteData?.quote} />+ </>);}++const QuoteNotes = ({ quote }: { quote: Quotation }) => {+ const {+ id: userId,+ company: { id: companyId },+ } = useUser();+ const { supabase } = useSupabase();++ const onUploadImage = async (file: File) => {+ const fileName = `${companyId}/quote/${quote.id}/${encodeURIComponent(+ file.name+ )}`;+ const result = await supabase?.storage+ .from("private")+ .upload(fileName, file);++ if (result?.error) {+ toast.error("Failed to upload image");+ throw new Error(result.error.message);+ }++ if (!result?.data) {+ throw new Error("Failed to upload image");+ }++ return `/file/preview/private/${result.data.path}`;+ };++ const onUpdateInternalNotes = useDebounce(async (content: JSONContent) => {+ await supabase+ ?.from("quoteLine")+ .update({+ notes: content,+ updatedAt: today(getLocalTimeZone()).toString(),+ updatedBy: userId,+ })+ .eq("id", quote.id!);+ }, 3000);++ return (+ <Card>+ <CardHeader>+ <CardTitle>External Notes</CardTitle>+ </CardHeader>+ <CardContent>+ <Editor+ initialValue={(quote.notes ?? {}) as JSONContent}+ onUpload={onUploadImage}+ onChange={onUpdateInternalNotes}+ />+ </CardContent>+ </Card>+ );+};diff --git a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx b/apps/carbon/app/routes/x+/quote+/$quoteId.tsxindex c17501d41f..fd33593134 100644--- a/apps/carbon/app/routes/x+/quote+/$quoteId.tsx+++ b/apps/carbon/app/routes/x+/quote+/$quoteId.tsx@@ -18,16 +18,19 @@ import {import type { LoaderFunctionArgs } from "@remix-run/node";import { json, redirect } from "@remix-run/node";import { Outlet, useNavigate, useParams } from "@remix-run/react";+import { useState } from "react";import { LuGhost, LuImage, LuPlus } from "react-icons/lu";import { MdMoreVert } from "react-icons/md";import type { FlatTree } from "~/components/TreeView/TreeView";import { useRouteData, useUser } from "~/hooks";import type { QuotationLine } from "~/modules/sales";import {+ DeleteQuoteLine,getQuote,- getQuoteInternalDocuments,+ getQuoteDocuments,getQuoteLines,QuoteBoMExplorer,+ QuoteBreadcrumbs,QuoteHeader,QuoteLineForm,} from "~/modules/sales";@@ -38,7 +41,7 @@ import { path } from "~/utils/path";import { error } from "~/utils/result";export const handle: Handle = {- breadcrumb: "Quote",+ breadcrumb: "Quotes",to: path.to.quotes,module: "sales",};@@ -54,7 +57,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {const [quote, lines, files] = await Promise.all([getQuote(client, quoteId),getQuoteLines(client, quoteId),- getQuoteInternalDocuments(client, companyId, quoteId),+ getQuoteDocuments(client, companyId, quoteId),]);if (quote.error) {@@ -98,9 +101,12 @@ export default function QuoteRoute() {</ScrollArea></ResizablePanel><ResizableHandle withHandle />- <ResizablePanel order={2} className="border-t border-border">+ <ResizablePanel order={2}><ScrollArea className="h-[calc(100vh-99px)]">- <Outlet key={JSON.stringify(params)} />+ <VStack spacing={2} className="p-2">+ <QuoteBreadcrumbs />+ <Outlet />+ </VStack></ScrollArea></ResizablePanel></ResizablePanelGroup>@@ -133,6 +139,18 @@ function QuoteExplorer() {};const newQuoteLineDisclosure = useDisclosure();+ const deleteLineDisclosure = useDisclosure();+ const [deleteLine, setDeleteLine] = useState<QuotationLine | null>(null);++ const onDeleteLine = (line: QuotationLine) => {+ setDeleteLine(line);+ deleteLineDisclosure.onOpen();+ };++ const onDeleteCancel = () => {+ setDeleteLine(null);+ deleteLineDisclosure.onClose();+ };return (<>@@ -140,7 +158,11 @@ function QuoteExplorer() {<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} />+ <QuoteLineItem+ key={line.id}+ line={line}+ onDelete={onDeleteLine}+ />))) : (<EmptyQuote onAdd={newQuoteLineDisclosure.onOpen} />@@ -159,6 +181,9 @@ function QuoteExplorer() {onClose={newQuoteLineDisclosure.onClose}/>)}+ {deleteLineDisclosure.isOpen && (+ <DeleteQuoteLine line={deleteLine!} onCancel={onDeleteCancel} />+ )}</>);}@@ -167,7 +192,7 @@ 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>+ <h3 className="text-base">Pretty empty around here</h3><Button leftIcon={<LuPlus />} onClick={onAdd}>Add Line Item</Button>@@ -270,7 +295,12 @@ const methods: FlatTree<{},];-function QuoteLineItem({ line }: { line: QuotationLine }) {+type QuoteLineItemProps = {+ line: QuotationLine;+ onDelete: (line: QuotationLine) => void;+};++function QuoteLineItem({ line, onDelete }: QuoteLineItemProps) {const { quoteId, lineId } = useParams();const navigate = useNavigate();const disclosure = useDisclosure();@@ -293,9 +323,9 @@ function QuoteLineItem({ line }: { line: QuotationLine }) {<VStack spacing={0}><HStackclassName={cn(- "w-full p-2 items-center justify-between hover:bg-accent/60 cursor-pointer",+ "w-full p-2 items-center justify-between hover:bg-accent/30 cursor-pointer",!disclosure.isOpen && "border-b border-border",- isSelected && "bg-accent/60"+ isSelected && "bg-accent/60 hover:bg-accent/50")}onClick={() => onLineClick(line)}>@@ -304,7 +334,7 @@ function QuoteLineItem({ line }: { line: QuotationLine }) {<imgalt="P2392303"className={cn(- "w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border border-border",+ "w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border border-transparent",line.status === "Complete" && "border-green-500",line.status === "In Progress" && "border-yellow-500")}@@ -313,7 +343,7 @@ function QuoteLineItem({ line }: { line: QuotationLine }) {) : (<divclassName={cn(- "w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border border-border p-2",+ "w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border border-transparent p-2",line.status === "Complete" && "border-green-500",line.status === "In Progress" && "border-yellow-500")}@@ -343,7 +373,14 @@ function QuoteLineItem({ line }: { line: QuotationLine }) {/></DropdownMenuTrigger><DropdownMenuContent>- <DropdownMenuItem>Delete Line</DropdownMenuItem>+ <DropdownMenuItem+ onClick={(e) => {+ e.stopPropagation();+ onDelete(line);+ }}+ >+ Delete Line+ </DropdownMenuItem></DropdownMenuContent></DropdownMenu></HStack>diff --git a/apps/carbon/app/styles/tailwind.css b/apps/carbon/app/styles/tailwind.cssindex de97754116..87994851e1 100644--- a/apps/carbon/app/styles/tailwind.css+++ b/apps/carbon/app/styles/tailwind.css@@ -122,3 +122,11 @@.forgeViewer > div {border-radius: var(--radius);}++p.is-editor-empty:first-child:before {+ color: var(--muted-foreground);+ content: attr(data-placeholder);+ float: left;+ height: 0;+ pointer-events: none;+}diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.tsindex d4dcf70bb7..8d119d5f3a 100644--- a/apps/carbon/app/utils/path.ts+++ b/apps/carbon/app/utils/path.ts@@ -240,7 +240,7 @@ export const path = {`${x}/quote/${quoteId}/lines/${lineId}/assembly/${assemblyId}/delete`),deleteQuoteLine: (id: string, lineId: string) =>- generatePath(`${x}/quote/${id}/lines/${lineId}/details/delete`),+ generatePath(`${x}/quote/${id}/${lineId}/delete`),deleteReceipt: (id: string) => generatePath(`${x}/receipt/delete/${id}`),deleteSalesOrder: (id: string) =>generatePath(`${x}/sales-order/delete/${id}`),diff --git a/apps/mes/index.html b/apps/mes/index.htmlindex 91efd1a283..bc06b94630 100644--- a/apps/mes/index.html+++ b/apps/mes/index.html@@ -4,6 +4,15 @@<meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>CarbonOS - MES</title>+ <style>+ p.is-editor-empty:first-child:before {+ color: var(--muted-foreground);+ content: attr(data-placeholder);+ float: left;+ height: 0;+ pointer-events: none;+ }+ </style></head><body class="bg-background dark"><div id="root"></div>diff --git a/packages/database/src/types.ts b/packages/database/src/types.tsindex 2d3f550e27..3bbfebdc4e 100644--- a/packages/database/src/types.ts+++ b/packages/database/src/types.ts@@ -12828,6 +12828,7 @@ export type Database = {itemReadableId: string | nullmethodType: Database["public"]["Enums"]["methodType"]modelUploadId: string | null+ notes: Json | nullquoteId: stringquoteRevisionId: numberstatus: Database["public"]["Enums"]["quoteLineStatus"]@@ -12848,6 +12849,7 @@ export type Database = {itemReadableId?: string | nullmethodType?: Database["public"]["Enums"]["methodType"]modelUploadId?: string | null+ notes?: Json | nullquoteId: stringquoteRevisionId?: numberstatus?: Database["public"]["Enums"]["quoteLineStatus"]@@ -12868,6 +12870,7 @@ export type Database = {itemReadableId?: string | nullmethodType?: Database["public"]["Enums"]["methodType"]modelUploadId?: string | null+ notes?: Json | nullquoteId?: stringquoteRevisionId?: numberstatus?: Database["public"]["Enums"]["quoteLineStatus"]@@ -22885,6 +22888,7 @@ export type Database = {modelPath: string | nullmodelSize: number | nullmodelUploadId: string | null+ notes: Json | nullpricingDiscountPercent: number | nullpricingExtendedPrice: number | nullpricingLeadTime: number | null@@ -23081,6 +23085,7 @@ export type Database = {Row: {assignee: string | nullcompanyId: string | null+ completedLines: number | nullcreatedAt: string | nullcreatedBy: string | nullcustomerContactId: string | null@@ -23093,7 +23098,7 @@ export type Database = {expirationDate: string | nullfavorite: boolean | nullid: string | null- itemIds: string[] | null+ lines: number | nulllocationId: string | nulllocationName: string | nullnotes: Json | nulldiff --git a/packages/database/supabase/functions/lib/types.ts b/packages/database/supabase/functions/lib/types.tsindex 2d3f550e27..3bbfebdc4e 100644--- a/packages/database/supabase/functions/lib/types.ts+++ b/packages/database/supabase/functions/lib/types.ts@@ -12828,6 +12828,7 @@ export type Database = {itemReadableId: string | nullmethodType: Database["public"]["Enums"]["methodType"]modelUploadId: string | null+ notes: Json | nullquoteId: stringquoteRevisionId: numberstatus: Database["public"]["Enums"]["quoteLineStatus"]@@ -12848,6 +12849,7 @@ export type Database = {itemReadableId?: string | nullmethodType?: Database["public"]["Enums"]["methodType"]modelUploadId?: string | null+ notes?: Json | nullquoteId: stringquoteRevisionId?: numberstatus?: Database["public"]["Enums"]["quoteLineStatus"]@@ -12868,6 +12870,7 @@ export type Database = {itemReadableId?: string | nullmethodType?: Database["public"]["Enums"]["methodType"]modelUploadId?: string | null+ notes?: Json | nullquoteId?: stringquoteRevisionId?: numberstatus?: Database["public"]["Enums"]["quoteLineStatus"]@@ -22885,6 +22888,7 @@ export type Database = {modelPath: string | nullmodelSize: number | nullmodelUploadId: string | null+ notes: Json | nullpricingDiscountPercent: number | nullpricingExtendedPrice: number | nullpricingLeadTime: number | null@@ -23081,6 +23085,7 @@ export type Database = {Row: {assignee: string | nullcompanyId: string | null+ completedLines: number | nullcreatedAt: string | nullcreatedBy: string | nullcustomerContactId: string | null@@ -23093,7 +23098,7 @@ export type Database = {expirationDate: string | nullfavorite: boolean | nullid: string | null- itemIds: string[] | null+ lines: number | nulllocationId: string | nulllocationName: string | nullnotes: Json | nulldiff --git a/packages/database/supabase/migrations/20240715024405_quotes.sql b/packages/database/supabase/migrations/20240715024405_quotes.sqlindex da39090916..47c33dd36b 100644--- a/packages/database/supabase/migrations/20240715024405_quotes.sql+++ b/packages/database/supabase/migrations/20240715024405_quotes.sql@@ -73,6 +73,7 @@ CREATE TABLE "quoteLine" ("customerPartRevision" TEXT,"methodType" "methodType" NOT NULL DEFAULT 'Make',"unitOfMeasureCode" TEXT,+ "notes" JSON DEFAULT '{}'::json,"companyId" TEXT NOT NULL,"createdBy" TEXT NOT NULL,"updatedAt" TIMESTAMP WITH TIME ZONE,@@ -230,13 +231,15 @@ CREATE OR REPLACE VIEW "quotes" WITH(SECURITY_INVOKER=true) ASSELECTq.*,l."name" AS "locationName",- ql."itemIds",+ ql."lines",+ ql."completedLines",EXISTS(SELECT 1 FROM "quoteFavorite" pf WHERE pf."quoteId" = q.id AND pf."userId" = auth.uid()::text) AS favoriteFROM "quote" qLEFT JOIN (SELECT"quoteId",- array_agg("itemId") AS "itemIds"+ COUNT("id") AS "lines",+ COUNT("id") FILTER (WHERE "status" = 'Complete') AS "completedLines"FROM "quoteLine"GROUP BY "quoteId") ql ON ql."quoteId" = q.iddiff --git a/packages/database/supabase/migrations/20240715055738_quote-files.sql b/packages/database/supabase/migrations/20240715055738_quote-files.sqlindex 51e167f70f..aa30c94693 100644--- a/packages/database/supabase/migrations/20240715055738_quote-files.sql+++ b/packages/database/supabase/migrations/20240715055738_quote-files.sql@@ -1,75 +1,65 @@-- Internal quote documents-CREATE POLICY "Internal quote documents view requires sales_view" ON storage.objects+CREATE POLICY "Quote documents view requires sales_view" ON storage.objectsFOR SELECT USING (bucket_id = 'private'AND has_role('employee', (storage.foldername(name))[1])AND has_company_permission('sales_view', (storage.foldername(name))[1])AND (storage.foldername(name))[2] = 'quote'- AND (storage.foldername(name))[3] = 'internal');-CREATE POLICY "Internal quote documents insert requires sales_create" ON storage.objects-FOR INSERT WITH CHECK (+CREATE POLICY "Quote line documents view requires sales_view" ON storage.objects+FOR SELECT USING (bucket_id = 'private'AND has_role('employee', (storage.foldername(name))[1])- AND has_company_permission('sales_create', (storage.foldername(name))[1])- AND (storage.foldername(name))[2] = 'quote'- AND (storage.foldername(name))[3] = 'internal'+ AND has_company_permission('sales_view', (storage.foldername(name))[1])+ AND (storage.foldername(name))[2] = 'quote-line');-CREATE POLICY "Internal quote documents update requires sales_update" ON storage.objects-FOR UPDATE USING (+CREATE POLICY "Quote documents insert requires sales_create" ON storage.objects+FOR INSERT WITH CHECK (bucket_id = 'private'AND has_role('employee', (storage.foldername(name))[1])- AND has_company_permission('sales_update', (storage.foldername(name))[1])+ AND has_company_permission('sales_create', (storage.foldername(name))[1])AND (storage.foldername(name))[2] = 'quote'- AND (storage.foldername(name))[3] = 'internal');-CREATE POLICY "Internal quote documents delete requires sales_delete" ON storage.objects-FOR DELETE USING (+CREATE POLICY "Quote line document insert requires sales_create" ON storage.objects+FOR INSERT WITH CHECK (bucket_id = 'private'AND has_role('employee', (storage.foldername(name))[1])- AND has_company_permission('sales_delete', (storage.foldername(name))[1])- AND (storage.foldername(name))[2] = 'quote'- AND (storage.foldername(name))[3] = 'internal'+ AND has_company_permission('sales_create', (storage.foldername(name))[1])+ AND (storage.foldername(name))[2] = 'quote-line');--- External quote documents--CREATE POLICY "External quote documents view requires sales_view" ON storage.objects-FOR SELECT USING (+CREATE POLICY "Quote documents update requires sales_update" ON storage.objects+FOR UPDATE USING (bucket_id = 'private'AND has_role('employee', (storage.foldername(name))[1])- AND has_company_permission('sales_view', (storage.foldername(name))[1])+ AND has_company_permission('sales_update', (storage.foldername(name))[1])AND (storage.foldername(name))[2] = 'quote'- AND (storage.foldername(name))[3] = 'external');-CREATE POLICY "External quote documents insert requires sales_create" ON storage.objects-FOR INSERT WITH CHECK (+CREATE POLICY "Quote line documents update requires sales_update" ON storage.objects+FOR UPDATE USING (bucket_id = 'private'AND has_role('employee', (storage.foldername(name))[1])- AND has_company_permission('sales_create', (storage.foldername(name))[1])- AND (storage.foldername(name))[2] = 'quote'- AND (storage.foldername(name))[3] = 'external'+ AND has_company_permission('sales_update', (storage.foldername(name))[1])+ AND (storage.foldername(name))[2] = 'quote-line');-CREATE POLICY "External quote documents update requires sales_update" ON storage.objects-FOR UPDATE USING (+CREATE POLICY "Quote documents delete requires sales_delete" ON storage.objects+FOR DELETE USING (bucket_id = 'private'AND has_role('employee', (storage.foldername(name))[1])- AND has_company_permission('sales_update', (storage.foldername(name))[1])+ AND has_company_permission('sales_delete', (storage.foldername(name))[1])AND (storage.foldername(name))[2] = 'quote'- AND (storage.foldername(name))[3] = 'external');-CREATE POLICY "External quote documents delete requires sales_delete" ON storage.objects+CREATE POLICY "Quote line documents delete requires sales_delete" ON storage.objectsFOR DELETE USING (bucket_id = 'private'AND has_role('employee', (storage.foldername(name))[1])AND has_company_permission('sales_delete', (storage.foldername(name))[1])- AND (storage.foldername(name))[2] = 'quote'- AND (storage.foldername(name))[3] = 'external'-);\ No newline at end of file+ AND (storage.foldername(name))[2] = 'quote-line'+);diff --git a/packages/database/supabase/migrations/20240719014956_model-uploads-thumbnail.sql b/packages/database/supabase/migrations/20240719014956_model-uploads-thumbnail.sqlindex 089e652e9a..bc78f6b4b7 100644--- a/packages/database/supabase/migrations/20240719014956_model-uploads-thumbnail.sql+++ b/packages/database/supabase/migrations/20240719014956_model-uploads-thumbnail.sql@@ -93,7 +93,7 @@ CREATE OR REPLACE VIEW "salesRfqLines" WITH(SECURITY_INVOKER=true) ASLEFT JOIN "modelUpload" mu ON mu.id = srl."modelUploadId";-DROP VIEW "quoteLines";+CREATE OR REPLACE VIEW "quoteLines" WITH(SECURITY_INVOKER=true) AS (SELECTql.*,diff --git a/packages/react/src/Table.tsx b/packages/react/src/Table.tsxindex 8c42780147..0f29187dcf 100644--- a/packages/react/src/Table.tsx+++ b/packages/react/src/Table.tsx@@ -72,7 +72,7 @@ const Th = forwardRef<<thref={ref}className={cn(- "group-hover:bg-muted h-11 px-6 text-left align-middle uppercase bg-card font-semibold tracking-tight text-muted-foreground [&:has([role=checkbox])]:pr-0 border-b border-border",+ "group-hover:bg-muted/30 h-11 px-6 text-left align-middle uppercase bg-card font-semibold tracking-tight text-muted-foreground [&:has([role=checkbox])]:pr-0 border-b border-border",className)}{...props}@@ -87,7 +87,7 @@ const Td = forwardRef<<tdref={ref}className={cn(- "group-hover:bg-muted text-foreground px-6 bg-card align-middle [&:has([role=checkbox])]:pr-0 h-11",+ "group-hover:bg-muted/30 text-foreground px-6 bg-card align-middle [&:has([role=checkbox])]:pr-0 h-11",className)}{...props}