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.

style: rfq layout similar to quote

Brad Barbineea83f32c85e
diff --git a/apps/carbon/app/components/Table/Table.tsx b/apps/carbon/app/components/Table/Table.tsx
index 7d152e6e5a..4a9126121c 100644
--- a/apps/carbon/app/components/Table/Table.tsx
+++ b/apps/carbon/app/components/Table/Table.tsx
@@ -520,6 +520,7 @@ const Table = <T extends object>({
right: isPinned === "right" ? column.getAfter("right") : undefined,
position: isPinned ? "sticky" : "relative",
zIndex: isPinned ? 1 : 0,
+ backgroundColor: isPinned ? "hsl(var(--card))" : undefined,
borderColor: "hsl(var(--border))",
borderRightWidth:
lastLeftPinnedColumn?.id === column.id
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
index 622222442b..e232858f11 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentsTable.tsx
@@ -172,16 +172,19 @@ const DocumentsTable = memo(
<HStack>
{row.original.favorite ? (
<LuPin
- className="cursor-pointer w-4 h-4 outline-primary/50 fill-yellow-400"
+ className="cursor-pointer w-4 h-4 outline-primary/50 fill-yellow-400 flex-shrink-0"
onClick={() => onFavorite(row.original)}
/>
) : (
<LuPin
- className="cursor-pointer w-4 h-4 text-muted-foreground"
+ className="cursor-pointer w-4 h-4 text-muted-foreground flex-shrink-0"
onClick={() => onFavorite(row.original)}
/>
)}
- <DocumentIcon type={row.original.type!} />
+ <DocumentIcon
+ className="flex-shrink-0"
+ type={row.original.type!}
+ />
<Hyperlink
onClick={() => view(row.original)}
className="max-w-[260px] truncate"
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx
index ab573360d5..dd386f9115 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrders/PurchaseOrdersTable.tsx
@@ -88,7 +88,7 @@ const PurchaseOrdersTable = memo(
<input type="hidden" name="favorite" value="unfavorite" />
<button type="submit">
<LuPin
- className="text-yellow-400 cursor-pointer h-4 w-4"
+ className="text-yellow-400 cursor-pointer h-4 w-4 flex-shrink-0"
type="submit"
/>
</button>
@@ -103,7 +103,7 @@ const PurchaseOrdersTable = memo(
<input type="hidden" name="favorite" value="favorite" />
<button type="submit">
<LuPin
- className="text-yellow-400 cursor-pointer h-4 w-4"
+ className="text-yellow-400 cursor-pointer h-4 w-4 flex-shrink-0"
type="submit"
/>
</button>
diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.ts
index 561eceeb44..7fe380b172 100644
--- a/apps/carbon/app/modules/sales/sales.models.ts
+++ b/apps/carbon/app/modules/sales/sales.models.ts
@@ -432,7 +432,7 @@ export const salesRfqValidator = z.object({
});
export const salesRfqLineValidator = z.object({
- id: z.string().min(1, { message: "ID is required" }),
+ id: zfd.text(z.string().optional()),
salesRfqId: z.string().min(20, { message: "RFQ is required" }),
customerPartId: z.string().min(1, { message: "Part Number is required" }),
customerPartRevision: 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 87fe2bb3dd..ca86c12662 100644
--- a/apps/carbon/app/modules/sales/sales.service.ts
+++ b/apps/carbon/app/modules/sales/sales.service.ts
@@ -178,6 +178,13 @@ export async function deleteSalesOrderLine(
return client.from("salesOrderLine").delete().eq("id", salesOrderLineId);
}
+export async function deleteSalesRFQ(
+ client: SupabaseClient<Database>,
+ salesRfqId: string
+) {
+ return client.from("salesRfq").delete().eq("id", salesRfqId);
+}
+
export async function deleteSalesRFQLine(
client: SupabaseClient<Database>,
salesRFQLineId: string
@@ -399,13 +406,12 @@ export async function getSalesRFQDocuments(
export async function getSalesRfqLineDocuments(
client: SupabaseClient<Database>,
- rfqId: string,
- lineId: string,
- companyId: string
+ companyId: string,
+ lineId: string
) {
return client.storage
.from("private")
- .list(`${companyId}/sales-rfq/${rfqId}/${lineId}`);
+ .list(`${companyId}/sales-rfq-line/${lineId}`);
}
export async function getFilesByQuoteLineId(
@@ -834,6 +840,13 @@ export async function getSalesRFQs(
return query;
}
+export async function getSalesRFQLine(
+ client: SupabaseClient<Database>,
+ lineId: string
+) {
+ return client.from("salesRfqLines").select("*").eq("id", lineId).single();
+}
+
export async function getSalesRFQLines(
client: SupabaseClient<Database>,
salesRfqId: string
@@ -1837,12 +1850,13 @@ export async function upsertSalesRFQLine(
client: SupabaseClient<Database>,
salesRfqLine:
- | (z.infer<typeof salesRfqLineValidator> & {
+ | (Omit<z.infer<typeof salesRfqLineValidator>, "id"> & {
companyId: string;
createdBy: string;
customFields?: Json;
})
- | (z.infer<typeof salesRfqLineValidator> & {
+ | (Omit<z.infer<typeof salesRfqLineValidator>, "id"> & {
+ id: string;
updatedBy: string;
customFields?: Json;
})
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
index 0d8bc29170..1fbb4686c8 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteForm.tsx
@@ -78,6 +78,7 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
setCustomer(newValue?.value as string | undefined)
}
/>
+ <Input name="customerReference" label="Customer Ref. Number" />
<CustomerLocation
name="customerLocationId"
label="Customer Location"
@@ -88,7 +89,6 @@ const QuoteForm = ({ initialValues }: QuoteFormProps) => {
label="Customer Contact"
customer={customer}
/>
- <Input name="customerReference" label="Customer Ref. Number" />
<Employee name="salesPersonId" label="Sales Person" />
<Employee name="estimatorId" label="Estimator" />
<Location name="locationId" label="Location" />
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx
index 01761a75fe..4ca909e3b6 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuoteLineDocuments.tsx
@@ -35,13 +35,7 @@ import { path } from "~/utils/path";
import { useCallback } from "react";
-const useQuoteLineDocuments = ({
- quoteId,
- quoteLineId,
-}: {
- quoteId: string;
- quoteLineId: string;
-}) => {
+const useQuoteLineDocuments = ({ quoteLineId }: { quoteLineId: string }) => {
const navigate = useNavigate();
const permissions = usePermissions();
const revalidator = useRevalidator();
@@ -155,7 +149,6 @@ const QuoteLineDocuments = ({
}: QuoteLineDocumentsProps) => {
const { canDelete, download, deleteFile, deleteModel, getPath, viewModel } =
useQuoteLineDocuments({
- quoteId,
quoteLineId,
});
diff --git a/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx b/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx
index d81f1b7d8f..2abd3bdc20 100644
--- a/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/Quotes/QuotesTable.tsx
@@ -85,7 +85,7 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
<input type="hidden" name="favorite" value="unfavorite" />
<button type="submit">
<LuPin
- className="cursor-pointer w-4 h-4 outline-primary/50 fill-yellow-400"
+ className="cursor-pointer w-4 h-4 outline-primary/50 fill-yellow-400 flex-shrink-0"
type="submit"
/>
</button>
@@ -100,7 +100,7 @@ const QuotesTable = memo(({ data, count }: QuotesTableProps) => {
<input type="hidden" name="favorite" value="favorite" />
<button type="submit">
<LuPin
- className="cursor-pointer w-4 h-4 text-muted-foreground"
+ className="cursor-pointer w-4 h-4 text-muted-foreground flex-shrink-0"
type="submit"
/>
</button>
diff --git a/apps/carbon/app/modules/sales/ui/SalesOrders/SalesOrdersTable.tsx b/apps/carbon/app/modules/sales/ui/SalesOrders/SalesOrdersTable.tsx
index b70e9f7861..f319931c5b 100644
--- a/apps/carbon/app/modules/sales/ui/SalesOrders/SalesOrdersTable.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesOrders/SalesOrdersTable.tsx
@@ -83,7 +83,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
<input type="hidden" name="favorite" value="unfavorite" />
<button type="submit">
<LuPin
- className="cursor-pointer w-4 h-4 outline-primary/50 fill-yellow-400"
+ className="cursor-pointer w-4 h-4 outline-primary/50 fill-yellow-400 flex-shrink-0"
type="submit"
/>
</button>
@@ -98,7 +98,7 @@ const SalesOrdersTable = memo(({ data, count }: SalesOrdersTableProps) => {
<input type="hidden" name="favorite" value="favorite" />
<button type="submit">
<LuPin
- className="cursor-pointer w-4 h-4 text-muted-foreground"
+ className="cursor-pointer w-4 h-4 text-muted-foreground flex-shrink-0"
type="submit"
/>
</button>
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQBreadcrumbs.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQBreadcrumbs.tsx
index 92e1b39115..cfcc7560d0 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQBreadcrumbs.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQBreadcrumbs.tsx
@@ -33,7 +33,7 @@ const SalesRFQBreadcrumbs = () => {
<BreadcrumbItem>
<Button variant="ghost" asChild>
<Link to={path.to.salesRfqLine(rfqId, line.id!)}>
- {line.itemReadableId}
+ {line.customerPartId}
</Link>
</Button>
</BreadcrumbItem>
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/SalesRFQDocumentForm.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/SalesRFQDocumentForm.tsx
new file mode 100644
index 0000000000..17b54858b0
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/SalesRFQDocumentForm.tsx
@@ -0,0 +1,78 @@
+import { File, toast } from "@carbon/react";
+import { useSubmit } from "@remix-run/react";
+import type { ChangeEvent } from "react";
+import { LuUpload } from "react-icons/lu";
+import { usePermissions, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import { path } from "~/utils/path";
+
+type SalesRFQDocumentFormProps = {
+ id: string;
+};
+
+const SalesRFQDocumentForm = ({ id }: SalesRFQDocumentFormProps) => {
+ const submit = useSubmit();
+ const { company } = useUser();
+ const { supabase } = useSupabase();
+ const permissions = usePermissions();
+
+ const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
+ if (e.target.files && supabase && company) {
+ const file = e.target.files[0];
+ const fileName = `${company.id}/sales-rfq/${id}/${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", "Request for Quote");
+ formData.append("sourceDocumentId", id);
+
+ submit(formData, {
+ method: "post",
+ action: path.to.newDocument,
+ });
+ };
+
+ return (
+ <File
+ isDisabled={!permissions.can("update", "sales")}
+ leftIcon={<LuUpload />}
+ onChange={uploadFile}
+ >
+ New
+ </File>
+ );
+};
+
+export default SalesRFQDocumentForm;
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/SalesRFQDocuments.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/SalesRFQDocuments.tsx
new file mode 100644
index 0000000000..7970fe8c60
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/SalesRFQDocuments.tsx
@@ -0,0 +1,139 @@
+import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ Table,
+ Tbody,
+ Td,
+ Th,
+ Thead,
+ Tr,
+} from "@carbon/react";
+import { convertKbToString } from "@carbon/utils";
+import { Outlet } from "@remix-run/react";
+import type { FileObject } from "@supabase/storage-js";
+import { MdMoreVert } from "react-icons/md";
+import { DocumentPreview, Hyperlink } from "~/components";
+import { DocumentIcon, getDocumentType } from "~/modules/documents";
+import SalesRFQDocumentForm from "./SalesRFQDocumentForm";
+import { useSalesRFQDocuments } from "./useSalesRFQDocuments";
+
+type SalesRFQDocumentsProps = {
+ attachments: FileObject[];
+ id: string;
+};
+
+const SalesRFQDocuments = ({ attachments, id }: SalesRFQDocumentsProps) => {
+ const { canDelete, download, deleteAttachment, getPath } =
+ useSalesRFQDocuments({
+ id,
+ });
+
+ return (
+ <>
+ <Card>
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Documents</CardTitle>
+ </CardHeader>
+ <CardAction>
+ <SalesRFQDocumentForm id={id} />
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <Table>
+ <Thead>
+ <Tr>
+ <Th>Name</Th>
+ <Th>Size</Th>
+
+ <Th></Th>
+ </Tr>
+ </Thead>
+ <Tbody>
+ {attachments.length ? (
+ attachments.map((attachment) => {
+ const type = getDocumentType(attachment.name);
+ return (
+ <Tr key={attachment.id}>
+ <Td>
+ <HStack>
+ <DocumentIcon type={type} />
+ <Hyperlink onClick={() => download(attachment)}>
+ {["PDF", "Image"].includes(type) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getPath(attachment)}
+ // @ts-ignore
+ type={type}
+ >
+ {attachment.name}
+ </DocumentPreview>
+ ) : (
+ attachment.name
+ )}
+ </Hyperlink>
+ </HStack>
+ </Td>
+ <Td className="text-xs font-mono">
+ {convertKbToString(
+ Math.floor((attachment.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(attachment)}
+ >
+ Download
+ </DropdownMenuItem>
+ <DropdownMenuItem
+ disabled={!canDelete}
+ onClick={() => deleteAttachment(attachment)}
+ >
+ Delete
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>
+ </Td>
+ </Tr>
+ );
+ })
+ ) : (
+ <Tr>
+ <Td
+ colSpan={24}
+ className="py-8 text-muted-foreground text-center"
+ >
+ No files uploaded
+ </Td>
+ </Tr>
+ )}
+ </Tbody>
+ </Table>
+ </CardContent>
+ </Card>
+ <Outlet />
+ </>
+ );
+};
+
+export default SalesRFQDocuments;
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/index.ts b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/index.ts
new file mode 100644
index 0000000000..2252500afa
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/index.ts
@@ -0,0 +1,3 @@
+import SalesRFQDocuments from "./SalesRFQDocuments";
+
+export default SalesRFQDocuments;
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/useSalesRFQDocuments.ts b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/useSalesRFQDocuments.ts
new file mode 100644
index 0000000000..9e35d883a3
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQDocuments/useSalesRFQDocuments.ts
@@ -0,0 +1,76 @@
+import { toast } from "@carbon/react";
+import { useRevalidator } from "@remix-run/react";
+import type { FileObject } from "@supabase/storage-js";
+import { useCallback } from "react";
+import { usePermissions, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+
+type Props = {
+ id: string;
+};
+
+export const useSalesRFQDocuments = ({ id }: Props) => {
+ const permissions = usePermissions();
+ const { company } = useUser();
+ const { supabase } = useSupabase();
+ const revalidator = useRevalidator();
+
+ const canDelete = permissions.can("delete", "sales"); // TODO: or is document owner
+
+ const getPath = useCallback(
+ (attachment: FileObject) => {
+ return `${company.id}/sales-rfq/${id}/${attachment.name}`;
+ },
+ [company.id, id]
+ );
+
+ const deleteAttachment = useCallback(
+ async (attachment: FileObject) => {
+ const result = await supabase?.storage
+ .from("private")
+ .remove([getPath(attachment)]);
+
+ if (!result || result.error) {
+ toast.error(result?.error?.message || "Error deleting file");
+ return;
+ }
+
+ toast.success("File deleted successfully");
+ revalidator.revalidate();
+ },
+ [supabase?.storage, getPath, revalidator]
+ );
+
+ const download = useCallback(
+ async (attachment: FileObject) => {
+ const result = await supabase?.storage
+ .from("private")
+ .download(getPath(attachment));
+
+ 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 = attachment.name;
+ a.click();
+
+ setTimeout(() => {
+ window.URL.revokeObjectURL(url);
+ document.body.removeChild(a);
+ }, 0);
+ },
+ [supabase?.storage, getPath]
+ );
+
+ return {
+ canDelete,
+ deleteAttachment,
+ download,
+ getPath,
+ };
+};
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
index 8e36b784ff..afd949587b 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
@@ -23,16 +23,17 @@ import { MdMoreVert } from "react-icons/md";
import { Empty } from "~/components";
import { useOptimisticLocation, usePermissions, useRouteData } from "~/hooks";
import { path } from "~/utils/path";
-import type { SalesRFQLine } from "../../types";
+import type { SalesRFQ, SalesRFQLine } from "../../types";
import DeleteSalesRFQLine from "./DeleteSalesRFQLine";
-// import NewSalesRFQLinesForm from "./NewSalesRFQLinesForm";
+import SalesRFQLineForm from "./SalesRFQLineForm";
export default function SalesRFQExplorer() {
const { rfqId } = useParams();
if (!rfqId) throw new Error("Could not find rfqId");
- const salesRfqData = useRouteData<{ lines: SalesRFQLine[] }>(
- path.to.salesRfq(rfqId)
- );
+ const salesRfqData = useRouteData<{
+ rfqSummary: SalesRFQ;
+ lines: SalesRFQLine[];
+ }>(path.to.salesRfq(rfqId));
const permissions = usePermissions();
const newSalesRFQLineDisclosure = useDisclosure();
@@ -57,6 +58,20 @@ export default function SalesRFQExplorer() {
},
});
+ const salesRfqLineInitialValues = {
+ salesRfqId: rfqId,
+ customerPartId: "",
+ customerPartRevision: "",
+ description: "",
+ itemId: "",
+ itemReadableId: "",
+ quantity: [1],
+ order: 1,
+ unitOfMeasureCode: "EA",
+ };
+
+ const isDisabled = salesRfqData?.rfqSummary.status !== "Draft";
+
return (
<>
<VStack className="w-full h-[calc(100vh-99px)] justify-between">
@@ -66,6 +81,7 @@ export default function SalesRFQExplorer() {
<SalesRFQLineItem
key={line.id}
line={line}
+ isDisabled={isDisabled}
onDelete={onDeleteLine}
/>
))
@@ -74,6 +90,7 @@ export default function SalesRFQExplorer() {
{permissions.can("update", "sales") && (
<Button
leftIcon={<LuPlus />}
+ isDisabled={isDisabled}
onClick={newSalesRFQLineDisclosure.onOpen}
>
Add Line Item
@@ -88,7 +105,7 @@ export default function SalesRFQExplorer() {
<Button
ref={newButtonRef}
className="w-full"
- isDisabled={!permissions.can("update", "sales")}
+ isDisabled={isDisabled || !permissions.can("update", "sales")}
leftIcon={<LuPlus />}
onClick={newSalesRFQLineDisclosure.onOpen}
>
@@ -104,12 +121,13 @@ export default function SalesRFQExplorer() {
</Tooltip>
</div>
</VStack>
- {/* {newSalesRFQLineDisclosure.isOpen && (
- <NewSalesRFQLinesForm
- rfqId={rfqId}
+ {newSalesRFQLineDisclosure.isOpen && (
+ <SalesRFQLineForm
+ initialValues={salesRfqLineInitialValues}
+ type="modal"
onClose={newSalesRFQLineDisclosure.onClose}
/>
- )} */}
+ )}
{deleteLineDisclosure.isOpen && (
<DeleteSalesRFQLine line={deleteLine!} onCancel={onDeleteCancel} />
)}
@@ -119,10 +137,15 @@ export default function SalesRFQExplorer() {
type SalesRFQLineItemProps = {
line: SalesRFQLine;
+ isDisabled: boolean;
onDelete: (line: SalesRFQLine) => void;
};
-function SalesRFQLineItem({ line, onDelete }: SalesRFQLineItemProps) {
+function SalesRFQLineItem({
+ line,
+ isDisabled,
+ onDelete,
+}: SalesRFQLineItemProps) {
const { rfqId, lineId } = useParams();
if (!rfqId) throw new Error("Could not find rfqId");
const permissions = usePermissions();
@@ -183,7 +206,7 @@ function SalesRFQLineItem({ line, onDelete }: SalesRFQLineItemProps) {
</DropdownMenuTrigger>
<DropdownMenuContent>
<DropdownMenuItem
- disabled={!permissions.can("update", "sales")}
+ disabled={isDisabled || !permissions.can("update", "sales")}
onClick={(e) => {
e.stopPropagation();
onDelete(line);
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineDocuments.tsx
index 52a8d59375..86d4c4ad2d 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineDocuments.tsx
@@ -1,4 +1,9 @@
import {
+ Card,
+ CardAction,
+ CardContent,
+ CardHeader,
+ CardTitle,
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
@@ -31,10 +36,8 @@ import { path } from "~/utils/path";
import { useCallback } from "react";
const useSalesRFQLineDocuments = ({
- rfqId,
salesRfqLineId,
}: {
- rfqId: string;
salesRfqLineId: string;
}) => {
const navigate = useNavigate();
@@ -47,9 +50,9 @@ const useSalesRFQLineDocuments = ({
const canUpdate = permissions.can("update", "sales");
const getPath = useCallback(
(file: ItemFile) => {
- return `${company.id}/sales-rfq/${rfqId}/${salesRfqLineId}/${file.name}`;
+ return `${company.id}/sales-rfq-line/${salesRfqLineId}/${file.name}`;
},
- [company.id, rfqId, salesRfqLineId]
+ [company.id, salesRfqLineId]
);
const deleteFile = useCallback(
@@ -136,7 +139,7 @@ const useSalesRFQLineDocuments = ({
};
type SalesRFQLineDocumentsProps = {
- files: (FileObject & { salesRfqLineId: string | null })[];
+ files: FileObject[];
rfqId: string;
salesRfqLineId: string;
modelUpload?: ModelUpload;
@@ -150,102 +153,55 @@ const SalesRFQLineDocuments = ({
}: SalesRFQLineDocumentsProps) => {
const { canDelete, download, deleteFile, deleteModel, getPath, viewModel } =
useSalesRFQLineDocuments({
- rfqId,
salesRfqLineId,
});
- return (
- <div className="min-h-[300px]">
- <Table>
- <Thead>
- <Tr>
- <Th>Name</Th>
- <Th>Size</Th>
+ console.log({ files });
- <Th className="flex items-center justify-end">
- <SalesRFQLineDocumentForm
- rfqId={rfqId}
- salesRfqLineId={salesRfqLineId}
- />
- </Th>
- </Tr>
- </Thead>
- <Tbody>
- {modelUpload?.autodeskUrn && (
+ return (
+ <Card className="flex-grow">
+ <HStack className="justify-between items-start">
+ <CardHeader>
+ <CardTitle>Files</CardTitle>
+ </CardHeader>
+ <CardAction>
+ <SalesRFQLineDocumentForm
+ rfqId={rfqId}
+ salesRfqLineId={salesRfqLineId}
+ />
+ </CardAction>
+ </HStack>
+ <CardContent>
+ <Table>
+ <Thead>
<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(salesRfqLineId)}
- >
- Delete
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- </Td>
+ <Th>Name</Th>
+ <Th>Size</Th>
+ <Th />
</Tr>
- )}
- {files.map((file) => {
- const type = getDocumentType(file.name);
- return (
- <Tr key={file.id}>
+ </Thead>
+ <Tbody>
+ {modelUpload?.autodeskUrn && (
+ <Tr>
<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
- )}
+ <LuAxis3D className="text-green-500 w-6 h-6" />
+ <Hyperlink
+ target="_blank"
+ onClick={() => viewModel(modelUpload)}
+ >
+ {modelUpload?.autodeskUrn
+ ? modelUpload.modelName
+ : "Uploading..."}
</Hyperlink>
</HStack>
</Td>
<Td>
- {convertKbToString(
- Math.floor((file.metadata?.size ?? 0) / 1024)
- )}
+ {modelUpload.modelSize
+ ? convertKbToString(
+ Math.floor((modelUpload.modelSize ?? 0) / 1024)
+ )
+ : "--"}
</Td>
<Td>
<div className="flex justify-end w-full">
@@ -258,12 +214,14 @@ const SalesRFQLineDocuments = ({
/>
</DropdownMenuTrigger>
<DropdownMenuContent>
- <DropdownMenuItem onClick={() => download(file)}>
- Download
+ <DropdownMenuItem
+ onClick={() => viewModel(modelUpload)}
+ >
+ View
</DropdownMenuItem>
<DropdownMenuItem
disabled={!canDelete}
- onClick={() => deleteFile(file)}
+ onClick={() => deleteModel(salesRfqLineId)}
>
Delete
</DropdownMenuItem>
@@ -272,21 +230,76 @@ const SalesRFQLineDocuments = ({
</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>
- </div>
+ )}
+ {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>
);
};
@@ -309,7 +322,7 @@ const SalesRFQLineDocumentForm = ({
const uploadFile = async (e: ChangeEvent<HTMLInputElement>) => {
if (e.target.files && supabase && company) {
const file = e.target.files[0];
- const fileName = `${company.id}/sales-rfq/${rfqId}/${salesRfqLineId}/${file.name}`;
+ const fileName = `${company.id}/sales-rfq-line/${salesRfqLineId}/${file.name}`;
const fileUpload = await supabase.storage
.from("private")
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx
new file mode 100644
index 0000000000..258480935d
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineForm.tsx
@@ -0,0 +1,325 @@
+import {
+ CardAction,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuIcon,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+ HStack,
+ IconButton,
+ ModalCard,
+ ModalCardBody,
+ ModalCardContent,
+ ModalCardDescription,
+ ModalCardFooter,
+ ModalCardHeader,
+ ModalCardProvider,
+ ModalCardTitle,
+ toast,
+ useDisclosure,
+ VStack,
+} from "@carbon/react";
+
+import { ValidatedForm } from "@carbon/remix-validated-form";
+import { useParams } from "@remix-run/react";
+import { useState } from "react";
+import { BsThreeDotsVertical } from "react-icons/bs";
+import { LuTrash } from "react-icons/lu";
+import type { z } from "zod";
+import {
+ ArrayNumeric,
+ CustomFormFields,
+ Hidden,
+ InputControlled,
+ Item,
+ Submit,
+ UnitOfMeasure,
+} from "~/components/Form";
+import { usePermissions, useRouteData, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { SalesRFQ, SalesRFQLine } from "~/modules/sales";
+import { DeleteSalesRFQLine, salesRfqLineValidator } from "~/modules/sales";
+import { path } from "~/utils/path";
+
+type SalesRFQLineFormProps = {
+ initialValues: z.infer<typeof salesRfqLineValidator>;
+ type?: "card" | "modal";
+ onClose?: () => void;
+};
+
+const SalesRFQLineForm = ({
+ initialValues,
+ type,
+ onClose,
+}: SalesRFQLineFormProps) => {
+ const permissions = usePermissions();
+ const { company } = useUser();
+ const { supabase } = useSupabase();
+
+ const { rfqId } = useParams();
+
+ if (!rfqId) throw new Error("rfqId not found");
+
+ const routeData = useRouteData<{
+ rfqSummary: SalesRFQ;
+ }>(path.to.salesRfq(rfqId));
+
+ const isEditable = ["Draft"].includes(routeData?.rfqSummary?.status ?? "");
+
+ const isEditing = initialValues.id !== undefined;
+
+ const [itemData, setItemData] = useState<{
+ customerPartId: string;
+ customerPartRevision: string;
+ itemId: string;
+ description: string;
+ unitOfMeasureCode: string;
+ modelUploadId: string | null;
+ }>({
+ customerPartId: initialValues.customerPartId ?? "",
+ customerPartRevision: initialValues.customerPartRevision ?? "",
+ itemId: initialValues.itemId ?? "",
+ description: initialValues.description ?? "",
+ unitOfMeasureCode: initialValues.unitOfMeasureCode ?? "EA",
+ modelUploadId: initialValues.modelUploadId ?? null,
+ });
+
+ const onCustomerPartChange = async (customerPartId: string) => {
+ console.log({ customerPartId, summary: routeData?.rfqSummary });
+ if (!supabase || !routeData?.rfqSummary?.customerId) return;
+ console.log("hello");
+
+ const customerPart = await supabase
+ .from("customerPartToItem")
+ .select("itemId")
+ .eq("customerPartId", customerPartId)
+ .eq("customerPartRevision", itemData.customerPartRevision ?? "")
+ .eq("customerId", routeData?.rfqSummary?.customerId!)
+ .maybeSingle();
+
+ if (customerPart.error) {
+ toast.error("Failed to load customer part details");
+ return;
+ }
+
+ if (customerPart.data && customerPart.data.itemId) {
+ onItemChange(customerPart.data.itemId);
+ }
+ };
+
+ const onCustomerPartRevisionChange = async (customerPartRevision: string) => {
+ if (
+ !supabase ||
+ !routeData?.rfqSummary?.customerId ||
+ !itemData.customerPartId
+ )
+ return;
+
+ let query = supabase
+ .from("customerPartToItem")
+ .select("itemId")
+ .eq("customerPartId", itemData.customerPartId)
+ .eq("customerPartRevision", customerPartRevision ?? "")
+ .eq("customerId", routeData?.rfqSummary?.customerId!);
+
+ const customerPart = await query.maybeSingle();
+
+ if (customerPart.error) {
+ toast.error("Failed to load customer part details");
+ return;
+ }
+
+ if (customerPart.data && customerPart.data.itemId) {
+ onItemChange(customerPart.data.itemId);
+ }
+ };
+
+ const onItemChange = async (itemId: string) => {
+ if (!supabase) return;
+
+ const [item] = await Promise.all([
+ supabase
+ .from("item")
+ .select("name, unitOfMeasureCode, modelUploadId")
+ .eq("id", itemId)
+ .eq("companyId", company.id)
+ .single(),
+ ]);
+
+ if (item.error) {
+ toast.error("Failed to load item details");
+ return;
+ }
+
+ setItemData((d) => ({
+ ...d,
+ itemId,
+ description: item.data?.name ?? "",
+ unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
+ modelUploadId: item.data?.modelUploadId ?? null,
+ }));
+ };
+
+ const deleteDisclosure = useDisclosure();
+
+ return (
+ <>
+ <ModalCardProvider type={type}>
+ <ModalCard onClose={onClose}>
+ <ModalCardContent>
+ <ValidatedForm
+ defaultValues={initialValues}
+ validator={salesRfqLineValidator}
+ method="post"
+ action={
+ isEditing
+ ? path.to.salesRfqLine(rfqId, initialValues.id!)
+ : path.to.newSalesRFQLine(rfqId)
+ }
+ className="w-full"
+ onSubmit={() => {
+ if (type === "modal") onClose?.();
+ }}
+ >
+ <HStack className="w-full justify-between items-start">
+ <ModalCardHeader>
+ <ModalCardTitle>
+ {isEditing
+ ? itemData?.customerPartId ?? "RFQ Line"
+ : "New RFQ Line"}
+ </ModalCardTitle>
+ <ModalCardDescription>
+ {isEditing
+ ? itemData?.description
+ : "An RFQ line contains part and quantity information about the requested item"}
+ </ModalCardDescription>
+ </ModalCardHeader>
+ {isEditing && permissions.can("update", "sales") && (
+ <CardAction>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <IconButton
+ icon={<BsThreeDotsVertical />}
+ aria-label="More"
+ variant="secondary"
+ />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ <DropdownMenuItem
+ disabled={!isEditable}
+ onClick={deleteDisclosure.onOpen}
+ >
+ <DropdownMenuIcon icon={<LuTrash />} />
+ Delete Line
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </CardAction>
+ )}
+ </HStack>
+ <ModalCardBody>
+ <Hidden name="id" />
+ <Hidden name="salesRfqId" />
+ <Hidden name="order" />
+ <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">
+ <div className="col-span-2 grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-2 auto-rows-min">
+ <InputControlled
+ name="customerPartId"
+ label="Customer Part Number"
+ value={itemData.customerPartId}
+ onChange={(newValue) => {
+ setItemData((d) => ({
+ ...d,
+ customerPartId: newValue,
+ }));
+ }}
+ onBlur={(e) => onCustomerPartChange(e.target.value)}
+ autoFocus
+ />
+ <InputControlled
+ name="customerPartRevision"
+ label="Customer Revision"
+ value={itemData.customerPartRevision}
+ onChange={(newValue) => {
+ setItemData((d) => ({
+ ...d,
+ customerPartRevision: newValue,
+ }));
+ }}
+ onBlur={(e) =>
+ onCustomerPartRevisionChange(e.target.value)
+ }
+ />
+ <Item
+ name="itemId"
+ label="Part"
+ type="Part"
+ value={itemData.itemId}
+ includeInactive
+ onChange={(value) => {
+ onItemChange(value?.value as string);
+ }}
+ />
+ <InputControlled
+ name="description"
+ label="Description"
+ value={itemData.description}
+ onChange={(newValue) => {
+ setItemData((d) => ({ ...d, description: newValue }));
+ }}
+ />
+ <UnitOfMeasure
+ name="unitOfMeasureCode"
+ value={itemData.unitOfMeasureCode}
+ onChange={(newValue) =>
+ setItemData((d) => ({
+ ...d,
+ unitOfMeasureCode: newValue?.value ?? "EA",
+ }))
+ }
+ />
+
+ <CustomFormFields table="salesRfqLine" />
+ </div>
+ <div className="flex gap-y-4">
+ <ArrayNumeric
+ name="quantity"
+ label="Quantity"
+ defaults={[1, 25, 50, 100]}
+ />
+ </div>
+ </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 && (
+ <DeleteSalesRFQLine
+ line={initialValues as SalesRFQLine}
+ onCancel={deleteDisclosure.onClose}
+ />
+ )}
+ </>
+ );
+};
+
+export default SalesRFQLineForm;
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx
new file mode 100644
index 0000000000..075cfa3ada
--- /dev/null
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLineNotes.tsx
@@ -0,0 +1,83 @@
+import type { JSONContent } from "@carbon/react";
+import {
+ Card,
+ CardContent,
+ CardHeader,
+ CardTitle,
+ Editor,
+ generateHTML,
+ toast,
+ useDebounce,
+} from "@carbon/react";
+import { getLocalTimeZone, today } from "@internationalized/date";
+import { nanoid } from "nanoid";
+import { usePermissions, useUser } from "~/hooks";
+import { useSupabase } from "~/lib/supabase";
+import type { SalesRFQLine } from "~/modules/sales";
+
+const SalesRFQLineNotes = ({ line }: { line: SalesRFQLine }) => {
+ const {
+ id: userId,
+ company: { id: companyId },
+ } = useUser();
+ const permissions = usePermissions();
+ const { supabase } = useSupabase();
+
+ const onUploadImage = async (file: File) => {
+ const fileType = file.name.split(".").pop();
+ const fileName = `${companyId}/sales-rfq-line/${
+ line.id
+ }/${nanoid()}.${fileType}`;
+ 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("salesRfqLine")
+ .update({
+ internalNotes: content,
+ updatedAt: today(getLocalTimeZone()).toString(),
+ updatedBy: userId,
+ })
+ .eq("id", line.id!);
+ }, 3000);
+
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Internal Notes</CardTitle>
+ </CardHeader>
+ <CardContent>
+ {permissions.can("update", "sales") ? (
+ <Editor
+ initialValue={(line.internalNotes ?? {}) as JSONContent}
+ onUpload={onUploadImage}
+ onChange={onUpdateInternalNotes}
+ />
+ ) : (
+ <div
+ className="prose dark:prose-invert"
+ dangerouslySetInnerHTML={{
+ __html: generateHTML(line.internalNotes as JSONContent),
+ }}
+ />
+ )}
+ </CardContent>
+ </Card>
+ );
+};
+
+export default SalesRFQLineNotes;
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx
deleted file mode 100644
index edce820f90..0000000000
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQLines.tsx
+++ /dev/null
@@ -1,843 +0,0 @@
-"use client";
-import type { JSONContent } from "@carbon/react";
-import {
- Badge,
- Button,
- Card,
- CardAction,
- CardContent,
- CardHeader,
- CardTitle,
- Editor,
- HStack,
- Kbd,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
- VStack,
- cn,
- generateHTML,
- toast,
- useDebounce,
- useKeyboardShortcuts,
- useMount,
-} from "@carbon/react";
-import { ValidatedForm } from "@carbon/remix-validated-form";
-import { prettifyKeyboardShortcut } from "@carbon/utils";
-import { getLocalTimeZone, today } from "@internationalized/date";
-import { useFetcher, useParams } from "@remix-run/react";
-import type { FileObject } from "@supabase/storage-js";
-import { AnimatePresence, LayoutGroup, motion } from "framer-motion";
-import { nanoid } from "nanoid";
-import type { Dispatch, SetStateAction } from "react";
-import { useCallback, useEffect, useRef, useState } from "react";
-import { LuMove3D, LuPaperclip, LuSettings2, LuX } from "react-icons/lu";
-import { DirectionAwareTabs } from "~/components/DirectionAwareTabs";
-import {
- ArrayNumeric,
- Hidden,
- Input,
- InputControlled,
- Item,
- Submit,
- UnitOfMeasure,
-} from "~/components/Form";
-import type {
- Item as SortableItem,
- SortableItemRenderProps,
-} from "~/components/SortableList";
-import { SortableList, SortableListItem } from "~/components/SortableList";
-import { usePermissions, useRouteData, useUser } from "~/hooks";
-import { useSupabase } from "~/lib/supabase";
-import { CadModel } from "~/modules/items";
-import { path } from "~/utils/path";
-import { salesRfqLineValidator } from "../../sales.models";
-import type { SalesRFQ, SalesRFQLine } from "../../types";
-import SalesRFQLineDocuments from "./SalesRFQLineDocuments";
-
-type ItemWithData = SortableItem & {
- data: SalesRFQLine;
- files?: (FileObject & { salesRfqLineId: string | null })[];
-};
-
-type SalesRFQLinesProps = {
- lines: SalesRFQLine[];
- files: (FileObject & { salesRfqLineId: string | null })[];
-};
-
-function makeItems(
- lines: SalesRFQLine[],
- files: (FileObject & { salesRfqLineId: string | null })[]
-): ItemWithData[] {
- return lines.map((line) =>
- makeItem(
- line,
- files.filter((f) => {
- return f.salesRfqLineId === line.id;
- })
- )
- );
-}
-
-function makeItem(
- line: SalesRFQLine,
- files?: (FileObject & { salesRfqLineId: string | null })[]
-): ItemWithData {
- return {
- id: line.id!,
- title: (
- <VStack spacing={0}>
- <h4 className="font-mono">
- {line.customerPartId}{" "}
- {line.customerPartRevision && (
- <span className="text-muted-foreground">{`Rev. ${line.customerPartRevision}`}</span>
- )}
- </h4>
- {line?.description && (
- <span className="text-xs text-muted-foreground">
- {line.description}{" "}
- </span>
- )}
- </VStack>
- ),
- isTemporary: false,
- checked: false,
- details: (
- <HStack spacing={2}>
- {line.quantity?.map((q, i) => (
- <Badge key={i} variant="secondary">
- {q}
- </Badge>
- ))}
- {line.autodeskUrn && (
- <Badge variant="secondary">
- <LuMove3D className="w-4 h-4 text-green-500" />
- </Badge>
- )}
- {files && files.length > 0 && (
- <Badge variant="secondary">
- <LuPaperclip className="w-4 h-4" />
- </Badge>
- )}
- </HStack>
- ),
- data: line,
- files,
- };
-}
-
-const initialLine: Omit<SalesRFQLine, "id" | "salesRfqId" | "order"> = {
- customerPartId: "",
- customerPartRevision: "",
- itemId: "",
- description: "",
- quantity: [1],
- unitOfMeasureCode: "EA",
- modelUploadId: undefined,
- autodeskUrn: null,
- modelId: "",
- modelName: "",
- modelPath: null,
- modelSize: 0,
- thumbnailPath: null,
- internalNotes: {} as JSONContent,
- externalNotes: {} as JSONContent,
-};
-
-const SalesRFQLines = ({ lines, files }: SalesRFQLinesProps) => {
- const { rfqId } = useParams();
- if (!rfqId) throw new Error("rfqId not found");
-
- const fetcher = useFetcher<{}>();
- const { supabase } = useSupabase();
- const permissions = usePermissions();
- const {
- company: { id: companyId },
- id: userId,
- } = useUser();
-
- const routeData = useRouteData<{ rfqSummary: SalesRFQ }>(
- path.to.salesRfq(rfqId)
- );
- const isDraft = routeData?.rfqSummary.status === "Draft";
-
- const [items, setItems] = useState<ItemWithData[]>(
- makeItems(lines ?? [], files)
- );
- const [selectedLineId, setSelectedLineId] = useState<string | null>(null);
-
- useEffect(() => {
- const temporaryItem = items.find((item) => item.isTemporary);
- const existingItems = makeItems(lines, files);
- setItems([...existingItems, ...(temporaryItem ? [temporaryItem] : [])]);
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [files, selectedLineId]);
-
- const onToggleItem = (id: string) => {
- if (permissions.can("delete", "sales") && isDraft) {
- setItems((prevItems) =>
- prevItems.map((item) =>
- item.id === id ? { ...item, checked: !item.checked } : item
- )
- );
- }
- };
-
- useMount(() => {
- if (lines.length === 0 && !selectedLineId) {
- onAddItem();
- }
- });
-
- // we create a temporary item and append it to the list
- const onAddItem = () => {
- const id = nanoid();
- setSelectedLineId(id);
- setItems((prevItems) => {
- let newOrder = 1;
- if (prevItems.length) {
- newOrder = prevItems[prevItems.length - 1].data.order + 1;
- }
-
- return [
- ...prevItems,
- {
- title: "",
- checked: false,
- id: id,
- isTemporary: true,
- data: {
- ...initialLine,
- id,
- order: newOrder,
- salesRfqId: rfqId,
- },
- },
- ];
- });
- };
-
- const onRemoveItem = async (id: string) => {
- if (!permissions.can("delete", "sales") || !isDraft) return;
- // get the item and it's order in the list
- const itemIndex = items.findIndex((i) => i.id === id);
- const item = items[itemIndex];
-
- setItems((prevItems) => prevItems.filter((item) => item.id !== id));
-
- fetcher.submit(new FormData(), {
- method: "post",
- action: path.to.deleteSalesRfqLine(rfqId, item.id),
- });
- };
-
- const onReorder = (reorderedItems: ItemWithData[]) => {
- const newItems = reorderedItems.map((item, index) => ({
- ...item,
- data: {
- ...item.data,
- order: index + 1,
- },
- }));
- const updates = newItems.reduce<Record<string, number>>((acc, item) => {
- if (!item.isTemporary) {
- acc[item.id] = item.data.order;
- }
- return acc;
- }, {});
-
- setItems(reorderedItems);
- updateSortOrder(updates);
- };
-
- const updateSortOrder = useDebounce((updates: Record<string, number>) => {
- let formData = new FormData();
- formData.append("updates", JSON.stringify(updates));
- fetcher.submit(formData, {
- method: "post",
- action: path.to.salesRfqLinesOrder(rfqId),
- });
- }, 1000);
-
- const onCloseOnDrag = useCallback(() => {
- setItems((prevItems) => {
- const updatedItems = prevItems.map((item) =>
- item.checked ? { ...item, checked: false } : item
- );
- return updatedItems.some(
- (item, index) => item.checked !== prevItems[index].checked
- )
- ? updatedItems
- : prevItems;
- });
- }, []);
-
- const onUploadImage = async (file: File) => {
- const fileType = file.name.split(".").pop();
- const fileName = `${companyId}/sales-rfqs/${selectedLineId}:${nanoid()}.${fileType}`;
- const result = await supabase?.storage
- .from("private")
- .upload(fileName, file);
-
- if (result?.error) {
- 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) => {
- setItems((prevItems) =>
- prevItems.map((item) =>
- item.id === selectedLineId
- ? {
- ...item,
- data: {
- ...item.data,
- internalNotes: content,
- },
- }
- : item
- )
- );
- await supabase
- ?.from("salesRfqLine")
- .update({
- internalNotes: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", selectedLineId!);
- }, 1000);
-
- const onUpdateExternalNotes = useDebounce(async (content: JSONContent) => {
- setItems((prevItems) =>
- prevItems.map((item) =>
- item.id === selectedLineId
- ? {
- ...item,
- data: {
- ...item.data,
- externalNotes: content,
- },
- }
- : item
- )
- );
- await supabase
- ?.from("salesRfqLine")
- .update({
- externalNotes: content,
- updatedAt: today(getLocalTimeZone()).toString(),
- updatedBy: userId,
- })
- .eq("id", selectedLineId!);
- }, 1000);
-
- const [tabChangeRerender, setTabChangeRerender] = useState<number>(1);
- const renderListItem = ({
- item,
- items,
- order,
- onToggleItem,
- onRemoveItem,
- }: SortableItemRenderProps<ItemWithData>) => {
- const isOpen = item.id === selectedLineId;
-
- const tabs = [
- {
- id: 0,
- label: "Details",
- content: (
- <div className="flex w-full flex-col pr-2 py-2">
- <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,
- }}
- >
- <SalesRFQLineForm
- item={item}
- setItems={setItems}
- setSelectedLineId={setSelectedLineId}
- isDraft={isDraft}
- />
- </motion.div>
- </div>
- ),
- },
- {
- 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}
- isReadOnly={!permissions.can("update", "sales")}
- metadata={{
- salesRfqLineId: item.id,
- }}
- modelPath={item.data.modelPath ?? null}
- viewerClassName="min-h-[520px]"
- 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,
- }}
- >
- {permissions.can("update", "sales") ? (
- <Editor
- className="min-h-[300px]"
- initialValue={item.data.internalNotes}
- onUpload={onUploadImage}
- onChange={onUpdateInternalNotes}
- />
- ) : (
- <div
- className="prose dark:prose-invert py-4"
- dangerouslySetInnerHTML={{
- __html: generateHTML(
- item.data.internalNotes as JSONContent
- ),
- }}
- />
- )}
- </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,
- }}
- >
- {permissions.can("update", "sales") ? (
- <Editor
- className="min-h-[300px]"
- initialValue={item.data.externalNotes}
- onUpload={onUploadImage}
- onChange={onUpdateExternalNotes}
- />
- ) : (
- <div
- className="prose dark:prose-invert py-4"
- dangerouslySetInnerHTML={{
- __html: generateHTML(
- item.data.externalNotes as JSONContent
- ),
- }}
- />
- )}
- </motion.div>
- </div>
- ),
- },
- ];
-
- return (
- <SortableListItem<SalesRFQLine>
- item={item}
- items={items}
- order={order}
- key={`${item.id}:${item.isTemporary}`}
- isExpanded={isOpen}
- onToggleItem={onToggleItem}
- onRemoveItem={onRemoveItem}
- handleDrag={onCloseOnDrag}
- className="my-2 "
- renderExtra={(item) => (
- <div
- key={`${isOpen}:${item.isTemporary}`}
- className={cn(
- "flex h-full flex-col items-center justify-center pl-2",
- isOpen ? "py-1" : "py-3 "
- )}
- >
- <motion.button
- layout
- onClick={
- isOpen
- ? () => {
- if (item.isTemporary) {
- setItems((prevItems) =>
- prevItems.filter((i) => i.id !== item.id)
- );
- }
- setSelectedLineId(null);
- }
- : () => {
- setSelectedLineId(item.id);
- }
- }
- key="collapse"
- className={cn(
- isOpen
- ? "absolute right-3 top-3 z-10 "
- : "relative z-10 ml-auto mr-3 "
- )}
- >
- {isOpen ? (
- <motion.span
- initial={{ opacity: 0, filter: "blur(4px)" }}
- animate={{ opacity: 1, filter: "blur(0px)" }}
- exit={{ opacity: 1, filter: "blur(0px)" }}
- transition={{
- type: "spring",
- duration: 1.95,
- }}
- >
- <LuX className="h-5 w-5 text-foreground" />
- </motion.span>
- ) : (
- <motion.span
- initial={{ opacity: 0, filter: "blur(4px)" }}
- animate={{ opacity: 1, filter: "blur(0px)" }}
- exit={{ opacity: 1, filter: "blur(0px)" }}
- transition={{
- type: "spring",
- duration: 0.95,
- }}
- >
- <LuSettings2 className="stroke-1 h-5 w-5 text-foreground/80 hover:stroke-primary/70 " />
- </motion.span>
- )}
- </motion.button>
-
- <LayoutGroup id={`${item.id}:${item.isTemporary}`}>
- <AnimatePresence mode="popLayout">
- {isOpen ? (
- <motion.div className="flex w-full flex-col ">
- <div className=" w-full p-2">
- <motion.div
- initial={{
- y: 0,
- opacity: 0,
- filter: "blur(4px)",
- }}
- animate={{
- y: 0,
- opacity: 1,
- filter: "blur(0px)",
- }}
- transition={{
- type: "spring",
- duration: 0.15,
- }}
- layout
- className="w-full "
- >
- <DirectionAwareTabs
- className="mr-auto"
- tabs={tabs}
- onChange={() =>
- setTabChangeRerender(tabChangeRerender + 1)
- }
- />
- </motion.div>
- </div>
- </motion.div>
- ) : null}
- </AnimatePresence>
- </LayoutGroup>
- </div>
- )}
- />
- );
- };
-
- const newLineRef = useRef<HTMLButtonElement>(null);
- useKeyboardShortcuts({
- "Command+Shift+l": (event: KeyboardEvent) => {
- event.stopPropagation();
- newLineRef.current?.click();
- },
- });
-
- return (
- <Card>
- <HStack className="justify-between">
- <CardHeader>
- <CardTitle>Lines</CardTitle>
- </CardHeader>
-
- <CardAction>
- <Tooltip>
- <TooltipTrigger className="w-full">
- <Button
- ref={newLineRef}
- variant="secondary"
- isDisabled={
- !isDraft ||
- !permissions.can("update", "sales") ||
- selectedLineId !== null
- }
- onClick={onAddItem}
- >
- Add Line
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <Kbd>{prettifyKeyboardShortcut("Command+Shift+l")}</Kbd>
- </TooltipContent>
- </Tooltip>
- </CardAction>
- </HStack>
- <CardContent>
- <SortableList
- items={items}
- onReorder={onReorder}
- onToggleItem={onToggleItem}
- onRemoveItem={onRemoveItem}
- renderItem={renderListItem}
- />
- </CardContent>
- </Card>
- );
-};
-
-export default SalesRFQLines;
-
-function SalesRFQLineForm({
- item,
- setItems,
- setSelectedLineId,
- isDraft,
-}: {
- item: ItemWithData;
- setItems: Dispatch<SetStateAction<ItemWithData[]>>;
- setSelectedLineId: Dispatch<SetStateAction<string | null>>;
- isDraft: boolean;
-}) {
- const { supabase } = useSupabase();
- const salesRfqLineFetcher = useFetcher<{ id: string }>();
- const permissions = usePermissions();
-
- const { company } = useUser();
-
- useEffect(() => {
- if (salesRfqLineFetcher.data && salesRfqLineFetcher.data.id) {
- setItems((prevItems) => {
- return prevItems.map((i) =>
- i.id === item.id
- ? {
- ...i,
- isTemporary: false,
- data: {
- ...i.data,
- },
- }
- : i
- );
- });
- }
- }, [item.id, salesRfqLineFetcher.data, setItems, setSelectedLineId]);
-
- const [itemData, setItemData] = useState<{
- itemId: string;
- description: string;
- unitOfMeasureCode: string;
- modelUploadId: string | null;
- }>({
- itemId: item.data.itemId ?? "",
- description: item.data.description ?? "",
- unitOfMeasureCode: item.data.unitOfMeasureCode ?? "EA",
- modelUploadId: item.data.modelUploadId ?? null,
- });
-
- const onItemChange = async (itemId: string) => {
- if (!supabase) return;
-
- const item = await supabase
- .from("item")
- .select("name, unitOfMeasureCode, modelUploadId")
- .eq("id", itemId)
- .eq("companyId", company.id)
- .single();
-
- if (item.error) {
- toast.error("Failed to load item details");
- return;
- }
-
- setItemData((d) => ({
- ...d,
- itemId,
- description: item.data?.name ?? "",
- unitOfMeasureCode: item.data?.unitOfMeasureCode ?? "EA",
- modelUploadId: item.data?.modelUploadId ?? null,
- }));
- };
-
- return (
- <ValidatedForm
- action={
- item.isTemporary
- ? path.to.newSalesRFQLine(item.data.salesRfqId!)
- : path.to.salesRfqLine(item.data.salesRfqId, item.id!)
- }
- method="post"
- defaultValues={item.data}
- validator={salesRfqLineValidator}
- className="w-full"
- fetcher={salesRfqLineFetcher}
- onSubmit={(values) => {
- setSelectedLineId(null);
- setItems((prevItems) =>
- prevItems.map((i) =>
- i.id === item.id
- ? {
- ...makeItem({
- ...item.data,
- ...values,
- }),
- isTemporary: false,
- id: item.id,
- }
- : i
- )
- );
- }}
- >
- <Hidden name="id" />
- <Hidden name="salesRfqId" />
- <Hidden name="order" />
- <Hidden
- name="modelUploadId"
- value={itemData.modelUploadId ?? undefined}
- />
- <VStack className="pt-4">
- <div className="grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-3">
- <div className="col-span-2 grid w-full gap-x-8 gap-y-4 grid-cols-1 lg:grid-cols-2 auto-rows-min">
- <Input
- name="customerPartId"
- label="Customer Part Number"
- autoFocus
- />
- <Input name="customerPartRevision" label="Customer Revision" />
- <Item
- name="itemId"
- label="Part"
- type="Part"
- includeInactive
- onChange={(value) => {
- onItemChange(value?.value as string);
- }}
- />
- <InputControlled
- name="description"
- label="Description"
- value={itemData.description}
- onChange={(newValue) => {
- setItemData((d) => ({ ...d, description: newValue }));
- }}
- />
- <UnitOfMeasure
- name="unitOfMeasureCode"
- value={itemData.unitOfMeasureCode}
- onChange={(newValue) =>
- setItemData((d) => ({
- ...d,
- unitOfMeasureCode: newValue?.value ?? "EA",
- }))
- }
- />
- </div>
- <ArrayNumeric
- name="quantity"
- label="Quantity"
- defaults={[1, 25, 50, 100]}
- />
- </div>
-
- <motion.div
- className="flex w-full items-center justify-end p-2"
- initial={{ opacity: 0, filter: "blur(4px)" }}
- animate={{ opacity: 1, filter: "blur(0px)" }}
- transition={{
- type: "spring",
- bounce: 0,
- duration: 0.55,
- }}
- >
- <motion.div layout className="ml-auto mr-1 pt-2">
- <Submit disabled={!isDraft || !permissions.can("update", "sales")}>
- Save
- </Submit>
- </motion.div>
- </motion.div>
- </VStack>
- </ValidatedForm>
- );
-}
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx
deleted file mode 100644
index dd48ad40b7..0000000000
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQProperties.tsx
+++ /dev/null
@@ -1,187 +0,0 @@
-import {
- Button,
- Enumerable,
- HStack,
- Tooltip,
- TooltipContent,
- TooltipTrigger,
- VStack,
-} from "@carbon/react";
-import { getLocalTimeZone, parseDate } from "@internationalized/date";
-import { useLocale } from "@react-aria/i18n";
-import { useParams } from "@remix-run/react";
-import { useMemo } from "react";
-import { LuCopy, LuLink } from "react-icons/lu";
-import {
- Assignee,
- CustomerAvatar,
- useOptimisticAssignment,
-} from "~/components";
-import { usePermissions, useRouteData } from "~/hooks";
-import type { ListItem } from "~/types";
-import { path } from "~/utils/path";
-import type { SalesRFQ } from "../../types";
-import SalesRFQStatus from "./SalesRFQStatus";
-
-const SalesRFQProperties = () => {
- const { rfqId } = useParams();
- if (!rfqId) throw new Error("rfqId not found");
-
- const permissions = usePermissions();
- const sharedData = useRouteData<{ locations: ListItem[] }>(
- path.to.salesRfqRoot
- );
- const routeData = useRouteData<{
- rfqSummary: SalesRFQ;
- }>(path.to.salesRfq(rfqId));
-
- const locations = sharedData?.locations ?? [];
-
- const optimisticAssignment = useOptimisticAssignment({
- id: rfqId,
- table: "salesRfq",
- });
- const assignee =
- optimisticAssignment !== undefined
- ? optimisticAssignment
- : routeData?.rfqSummary?.assignee;
-
- const { locale } = useLocale();
- // TODO: factor in default currency, sales order currency and exchange rate
- const formatter = useMemo(
- () =>
- new Intl.DateTimeFormat(locale, {
- dateStyle: "full",
- timeZone: getLocalTimeZone(),
- }),
- [locale]
- );
-
- return (
- <VStack
- spacing={4}
- className="w-96 bg-card h-full overflow-y-auto border-l border-border px-4 py-2"
- >
- <VStack spacing={2}>
- <HStack className="w-full justify-between">
- <h3 className="text-xs text-muted-foreground">Properties</h3>
- <HStack spacing={1}>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- aria-label="Link"
- size="sm"
- className="p-1"
- onClick={() =>
- navigator.clipboard.writeText(
- window.location.origin + path.to.salesRfq(rfqId)
- )
- }
- >
- <LuLink className="w-3 h-3" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <span>Copy link to RFQ</span>
- </TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- aria-label="Copy"
- size="sm"
- className="p-1"
- onClick={() =>
- navigator.clipboard.writeText(
- routeData?.rfqSummary?.rfqId ?? ""
- )
- }
- >
- <LuCopy className="w-3 h-3" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <span>Copy RFQ number</span>
- </TooltipContent>
- </Tooltip>
- </HStack>
- </HStack>
- <span className="text-sm">{routeData?.rfqSummary?.rfqId}</span>
- </VStack>
-
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">Assignee</h3>
- <Assignee
- id={rfqId}
- table="salesRfq"
- value={assignee ?? ""}
- isReadOnly={!permissions.can("update", "sales")}
- />
- </VStack>
-
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">Status</h3>
- <SalesRFQStatus status={routeData?.rfqSummary?.status} />
- </VStack>
-
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">Customer</h3>
- <CustomerAvatar
- customerId={routeData?.rfqSummary?.customerId ?? null}
- />
- </VStack>
-
- {routeData?.rfqSummary?.customerReference && (
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">
- Customer Reference Number
- </h3>
- <span className="text-sm">
- {routeData.rfqSummary.customerReference}
- </span>
- </VStack>
- )}
-
- {routeData?.rfqSummary?.rfqDate && (
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">RFQ Date</h3>
- <span className="text-sm">
- {formatter.format(
- parseDate(routeData.rfqSummary.rfqDate).toDate(getLocalTimeZone())
- )}
- </span>
- </VStack>
- )}
-
- {routeData?.rfqSummary?.expirationDate && (
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">Expiration Date</h3>
- <span className="text-sm">
- {formatter.format(
- parseDate(routeData.rfqSummary.expirationDate).toDate(
- getLocalTimeZone()
- )
- )}
- </span>
- </VStack>
- )}
-
- {routeData?.rfqSummary?.locationId && (
- <VStack spacing={2}>
- <h3 className="text-xs text-muted-foreground">Location</h3>
- <Enumerable
- value={
- locations.find(
- (location) => location.id === routeData?.rfqSummary?.locationId
- )?.name ?? null
- }
- />
- </VStack>
- )}
- </VStack>
- );
-};
-
-export default SalesRFQProperties;
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/index.ts b/apps/carbon/app/modules/sales/ui/SalesRFQ/index.ts
index 996d7dfc91..943d2cc686 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/index.ts
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/index.ts
@@ -1,19 +1,25 @@
+import DeleteSalesRFQLine from "./DeleteSalesRFQLine";
import SalesRFQBreadcrumbs from "./SalesRFQBreadcrumbs";
+import SalesRFQDocuments from "./SalesRFQDocuments";
import SalesRFQExplorer from "./SalesRFQExplorer";
import SalesRFQForm from "./SalesRFQForm";
import SalesRFQHeader from "./SalesRFQHeader";
-import SalesRFQLines from "./SalesRFQLines";
-import SalesRFQProperties from "./SalesRFQProperties";
+import SalesRFQLineDocuments from "./SalesRFQLineDocuments";
+import SalesRFQLineForm from "./SalesRFQLineForm";
+import SalesRFQLineNotes from "./SalesRFQLineNotes";
import SalesRFQStatus from "./SalesRFQStatus";
import SalesRFQsTable from "./SalesRFQsTable";
export {
+ DeleteSalesRFQLine,
SalesRFQBreadcrumbs,
+ SalesRFQDocuments,
SalesRFQExplorer,
SalesRFQForm,
SalesRFQHeader,
- SalesRFQLines,
- SalesRFQProperties,
+ SalesRFQLineDocuments,
+ SalesRFQLineForm,
+ SalesRFQLineNotes,
SalesRFQStatus,
SalesRFQsTable,
};
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.delete.$id.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.$lineId.delete.tsx
similarity index 53%
rename from apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.delete.$id.tsx
rename to apps/carbon/app/routes/x+/sales-rfq+/$rfqId.$lineId.delete.tsx
index 9ec773c144..2414ae3007 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.delete.$id.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.$lineId.delete.tsx
@@ -1,8 +1,9 @@
-import { json, type ActionFunctionArgs } from "@remix-run/node";
+import { redirect, type ActionFunctionArgs } from "@remix-run/node";
import { deleteSalesRFQLine } 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) {
@@ -11,23 +12,24 @@ export async function action({ request, params }: ActionFunctionArgs) {
delete: "sales",
});
- const { rfqId, id } = params;
+ const { rfqId, lineId } = params;
if (!rfqId) {
throw new Error("rfqId not found");
}
- if (!id) {
- throw new Error("id not found");
+ if (!lineId) {
+ throw new Error("lineId not found");
}
- const deleteLine = await deleteSalesRFQLine(client, id);
+ const deleteLine = await deleteSalesRFQLine(client, lineId);
if (deleteLine.error) {
- return json(
- {
- id: null,
- },
- await flash(request, error(deleteLine.error, "Failed to delete RFQ line"))
+ throw redirect(
+ path.to.quoteLine(rfqId, lineId),
+ await flash(
+ request,
+ error(deleteLine.error, "Failed to update quote line")
+ )
);
}
- return json({});
+ throw redirect(path.to.salesRfq(rfqId));
}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.$lineId.details.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.$lineId.details.tsx
index 5ff566a70f..86b29c5055 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.$lineId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.$lineId.details.tsx
@@ -2,23 +2,17 @@ import { validationError, validator } from "@carbon/remix-validated-form";
import type { ActionFunctionArgs, LoaderFunctionArgs } from "@remix-run/node";
import { json, redirect } from "@remix-run/node";
import { Outlet, useLoaderData, useParams } from "@remix-run/react";
-import { Fragment, useMemo } from "react";
-import type { Tree } from "~/components/TreeView";
-import { usePermissions, useRouteData } from "~/hooks";
+import { Fragment } from "react";
+import { usePermissions } from "~/hooks";
import { CadModel } from "~/modules/items";
-import type { QuotationPrice, QuoteMethod } from "~/modules/sales";
import {
- getFilesByQuoteLineId,
- getQuoteLine,
- getQuoteLinePrices,
- getQuoteOperationsByLine,
- QuoteLineCosting,
- QuoteLineDocuments,
- QuoteLineForm,
- QuoteLineNotes,
- quoteLineValidator,
- upsertQuoteLine,
- useLineCosts,
+ getSalesRFQLine,
+ getSalesRfqLineDocuments,
+ SalesRFQLineDocuments,
+ SalesRFQLineForm,
+ SalesRFQLineNotes,
+ salesRfqLineValidator,
+ upsertSalesRFQLine,
} from "~/modules/sales";
import { requirePermissions } from "~/services/auth/auth.server";
import { flash } from "~/services/session.server";
@@ -32,34 +26,27 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
view: "sales",
});
- const { quoteId, lineId } = params;
- if (!quoteId) throw new Error("Could not find quoteId");
+ const { rfqId, lineId } = params;
+ if (!rfqId) throw new Error("Could not find rfqId");
if (!lineId) throw new Error("Could not find lineId");
- const [line, operations, files, prices] = await Promise.all([
- getQuoteLine(client, lineId),
- getQuoteOperationsByLine(client, lineId),
- getFilesByQuoteLineId(client, companyId, lineId),
- getQuoteLinePrices(client, lineId),
+ const [line, files] = await Promise.all([
+ getSalesRFQLine(client, lineId),
+ getSalesRfqLineDocuments(client, companyId, lineId),
]);
if (line.error) {
throw redirect(
- path.to.quote(quoteId),
+ path.to.quote(rfqId),
await flash(request, error(line.error, "Failed to load line"))
);
}
+ console.log({ files });
+
return json({
line: line.data,
- operations: operations?.data ?? [],
files: files?.data ?? [],
- pricesByQuantity: (prices?.data ?? []).reduce<
- Record<number, QuotationPrice>
- >((acc, price) => {
- acc[price.quantity] = price;
- return acc;
- }, {}),
});
};
@@ -69,13 +56,13 @@ export async function action({ request, params }: ActionFunctionArgs) {
create: "sales",
});
- const { quoteId, lineId } = params;
- if (!quoteId) throw new Error("Could not find quoteId");
+ const { rfqId, lineId } = params;
+ if (!rfqId) throw new Error("Could not find rfqId");
if (!lineId) throw new Error("Could not find lineId");
const formData = await request.formData();
- const validation = await validator(quoteLineValidator).validate(formData);
+ const validation = await validator(salesRfqLineValidator).validate(formData);
if (validation.error) {
return validationError(validation.error);
@@ -83,93 +70,70 @@ export async function action({ request, params }: ActionFunctionArgs) {
const { id, ...data } = validation.data;
- const updateQuotationLine = await upsertQuoteLine(client, {
+ const updateLine = await upsertSalesRFQLine(client, {
id: lineId,
...data,
updatedBy: userId,
customFields: setCustomFields(formData),
});
- if (updateQuotationLine.error) {
+ if (updateLine.error) {
throw redirect(
- path.to.quoteLine(quoteId, lineId),
+ path.to.salesRfqLine(rfqId, lineId),
await flash(
request,
- error(updateQuotationLine.error, "Failed to update quote line")
+ error(updateLine.error, "Failed to update quote line")
)
);
}
- throw redirect(path.to.quoteLine(quoteId, lineId));
+ throw redirect(path.to.salesRfqLine(rfqId, lineId));
}
-export default function QuoteLine() {
- const { line, operations, files } = useLoaderData<typeof loader>();
+export default function SalesRFQLine() {
+ const { line, files } = useLoaderData<typeof loader>();
const permissions = usePermissions();
- const { quoteId, lineId } = useParams();
- if (!quoteId) throw new Error("Could not find quoteId");
+ const { rfqId, lineId } = useParams();
+ if (!rfqId) throw new Error("Could not find rfqId");
if (!lineId) throw new Error("Could not find lineId");
- const quoteData = useRouteData<{ methods: Tree<QuoteMethod>[] }>(
- path.to.quote(quoteId)
- );
-
- const methodTree = useMemo(
- () => quoteData?.methods?.find((m) => m.data.quoteLineId === line.id),
- [quoteData, line.id]
- );
-
- const getLineCosts = useLineCosts({
- methodTree,
- operations,
- });
-
const initialValues = {
...line,
id: line.id ?? undefined,
- quoteId: line.quoteId ?? "",
+ salesRfqId: line.salesRfqId ?? "",
customerPartId: line.customerPartId ?? "",
customerPartRevision: line.customerPartRevision ?? "",
description: line.description ?? "",
- estimatorId: line.estimatorId ?? "",
itemId: line.itemId ?? "",
- itemReadableId: line.itemReadableId ?? "",
- methodType: line.methodType ?? "Make",
- modelUploadId: line.modelUploadId ?? undefined,
- status: line.status ?? "Draft",
quantity: line.quantity ?? [1],
+ order: line.order ?? 1,
unitOfMeasureCode: line.unitOfMeasureCode ?? "",
+ modelUploadId: line.modelUploadId ?? undefined,
};
return (
<Fragment key={lineId}>
- <QuoteLineForm key={lineId} initialValues={initialValues} />
+ <SalesRFQLineForm key={lineId} initialValues={initialValues} />
{permissions.is("employee") && (
<Fragment key={lineId}>
<div className="grid grid-cols-1 xl:grid-cols-2 w-full flex-grow gap-2 ">
<CadModel
autodeskUrn={line?.autodeskUrn ?? null}
isReadOnly={!permissions.can("update", "sales")}
- metadata={{ quoteLineId: line.id ?? undefined }}
+ metadata={{ salesRfqLineId: line.id ?? undefined }}
modelPath={line?.modelPath ?? null}
title="CAD Model"
uploadClassName="min-h-[360px]"
viewerClassName="min-h-[360px]"
/>
- <QuoteLineDocuments
+ <SalesRFQLineDocuments
files={files ?? []}
- quoteId={quoteId}
- quoteLineId={lineId}
+ rfqId={rfqId}
+ salesRfqLineId={lineId}
modelUpload={line ?? undefined}
/>
</div>
- <QuoteLineNotes line={line} />
- {line.methodType === "Make" && (
- <QuoteLineCosting
- quantities={line.quantity ?? [1]}
- getLineCosts={getLineCosts}
- />
- )}
+ <SalesRFQLineNotes line={line} />
<Outlet />
</Fragment>
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.delete.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.delete.tsx
new file mode 100644
index 0000000000..708019228b
--- /dev/null
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.delete.tsx
@@ -0,0 +1,33 @@
+import { json, redirect } from "@remix-run/react";
+
+import type { ActionFunctionArgs } from "@remix-run/node";
+import { deleteSalesRFQ } 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 { rfqId } = params;
+ if (!rfqId) throw new Error("Could not find rfqId");
+
+ const quoteDelete = await deleteSalesRFQ(client, rfqId);
+
+ if (quoteDelete.error) {
+ return json(
+ path.to.quotes,
+ await flash(
+ request,
+ error(quoteDelete.error, "Failed to delete quote line")
+ )
+ );
+ }
+
+ throw redirect(path.to.quotes);
+}
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 f58b37eb3e..c735825725 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.details.tsx
@@ -21,6 +21,7 @@ import { usePermissions, useRouteData, useUser } from "~/hooks";
import { useSupabase } from "~/lib/supabase";
import type { SalesRFQ, SalesRFQLine, SalesRFQStatus } from "~/modules/sales";
import {
+ SalesRFQDocuments,
SalesRFQForm,
salesRfqValidator,
upsertSalesRFQ,
@@ -78,7 +79,7 @@ export default function SalesRFQDetailsRoute() {
const rfqData = useRouteData<{
rfqSummary: SalesRFQ;
lines: SalesRFQLine[];
- files: (FileObject & { salesRfqLineId: string | null })[];
+ files: FileObject[];
}>(path.to.salesRfq(rfqId));
if (!rfqData) throw new Error("Could not find rfq data");
@@ -106,6 +107,7 @@ export default function SalesRFQDetailsRoute() {
key={`${initialValues.id}:${initialValues.status}`}
initialValues={initialValues}
/>
+ <SalesRFQDocuments id={rfqId} attachments={rfqData?.files ?? []} />
<SalesRFQNotes salesRfq={rfqData.rfqSummary} />
</VStack>
);
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.$id.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.$id.tsx
deleted file mode 100644
index 258fc97fe3..0000000000
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.$id.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-import { validationError, validator } from "@carbon/remix-validated-form";
-import { json, type ActionFunctionArgs } from "@remix-run/node";
-import { salesRfqLineValidator, upsertSalesRFQLine } 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 { error } from "~/utils/result";
-
-export async function action({ request, params }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, companyId, userId } = await requirePermissions(request, {
- create: "parts",
- });
-
- const { rfqId, id } = params;
- if (!rfqId) {
- throw new Error("rfqId not found");
- }
- if (!id) {
- throw new Error("id not found");
- }
-
- const formData = await request.formData();
- const validation = await validator(salesRfqLineValidator).validate(formData);
-
- if (validation.error) {
- return validationError(validation.error);
- }
-
- const updateSalesRfqLine = await upsertSalesRFQLine(client, {
- ...validation.data,
- id: id,
- companyId,
- updatedBy: userId,
- customFields: setCustomFields(formData),
- });
- if (updateSalesRfqLine.error) {
- return json(
- {
- id: null,
- },
- await flash(
- request,
- error(updateSalesRfqLine.error, "Failed to update RFQ line")
- )
- );
- }
-
- const salesRfqLineId = updateSalesRfqLine.data?.id;
- if (!salesRfqLineId) {
- return json(
- {
- id: null,
- },
- await flash(
- request,
- error(updateSalesRfqLine, "Failed to update RFQ line")
- )
- );
- }
-
- return json({ id: salesRfqLineId });
-}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.order.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.order.tsx
deleted file mode 100644
index 324c845f02..0000000000
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.order.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-import { json, type ActionFunctionArgs } from "@remix-run/node";
-
-import { updateSalesRFQLineOrder } from "~/modules/sales";
-import { requirePermissions } from "~/services/auth/auth.server";
-import { flash } from "~/services/session.server";
-import { assertIsPost } from "~/utils/http";
-import { error } from "~/utils/result";
-
-export async function action({ request }: ActionFunctionArgs) {
- assertIsPost(request);
- const { client, userId } = await requirePermissions(request, {
- update: "parts",
- });
-
- const updateMap = (await request.formData()).get("updates") as string;
- if (!updateMap) {
- return json(
- {},
- await flash(request, error(null, "Failed to receive a new sort order"))
- );
- }
-
- const updates = Object.entries(JSON.parse(updateMap)).map(
- ([id, orderString]) => ({
- id,
- order: Number(orderString),
- updatedBy: userId,
- })
- );
-
- const updateSortOrders = await updateSalesRFQLineOrder(client, updates);
- if (updateSortOrders.some((update) => update.error))
- return json(
- {},
- await flash(
- request,
- error(updateSortOrders, "Failed to update sort order")
- )
- );
-
- return null;
-}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.new.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.new.tsx
similarity index 76%
rename from apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.new.tsx
rename to apps/carbon/app/routes/x+/sales-rfq+/$rfqId.new.tsx
index a84b708313..9564e9a4d7 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.lines.new.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.new.tsx
@@ -1,10 +1,11 @@
import { validationError, validator } from "@carbon/remix-validated-form";
-import { json, type ActionFunctionArgs } from "@remix-run/node";
+import { redirect, type ActionFunctionArgs } from "@remix-run/node";
import { salesRfqLineValidator, upsertSalesRFQLine } 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) {
@@ -25,30 +26,28 @@ export async function action({ request, params }: ActionFunctionArgs) {
return validationError(validation.error);
}
+ const { id, ...data } = validation.data;
+
const insertLine = await upsertSalesRFQLine(client, {
- ...validation.data,
+ ...data,
companyId,
createdBy: userId,
customFields: setCustomFields(formData),
});
if (insertLine.error) {
- return json(
- {
- id: null,
- },
+ throw redirect(
+ path.to.salesRfq(rfqId),
await flash(request, error(insertLine.error, "Failed to insert RFQ line"))
);
}
- const methodMaterialId = insertLine.data?.id;
- if (!methodMaterialId) {
- return json(
- {
- id: null,
- },
+ const lineId = insertLine.data?.id;
+ if (!lineId) {
+ throw redirect(
+ path.to.salesRfq(rfqId),
await flash(request, error(insertLine, "Failed to insert RFQ line"))
);
}
- return json({ id: methodMaterialId });
+ throw redirect(path.to.salesRfqLine(rfqId, lineId));
}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
index e5e176909d..c11c18cbf0 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
@@ -41,7 +41,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const [rfqSummary, lines, files] = await Promise.all([
getSalesRFQ(client, rfqId),
getSalesRFQLines(client, rfqId),
- getSalesRFQDocuments(client, rfqId, companyId),
+ getSalesRFQDocuments(client, companyId, rfqId),
]);
if (rfqSummary.error) {
@@ -77,7 +77,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
itemId: line.itemId ?? "",
quantity: line.quantity ?? [1],
})) ?? [],
- documents: files.data ?? [],
+ files: files.data ?? [],
});
}
diff --git a/apps/carbon/app/utils/path.ts b/apps/carbon/app/utils/path.ts
index e5268585bf..1d5dca180c 100644
--- a/apps/carbon/app/utils/path.ts
+++ b/apps/carbon/app/utils/path.ts
@@ -250,7 +250,7 @@ export const path = {
generatePath(`${x}/sales-order/${orderId}/lines/delete/${lineId}`),
deleteSalesRfq: (id: string) => generatePath(`${x}/sales-rfq/delete/${id}`),
deleteSalesRfqLine: (id: string, lineId: string) =>
- generatePath(`${x}/sales-rfq/${id}/lines/delete/${lineId}`),
+ generatePath(`${x}/sales-rfq/${id}/${lineId}/delete`),
deleteShift: (id: string) =>
generatePath(`${x}/resources/shifts/delete/${id}`),
deleteShippingMethod: (id: string) =>
@@ -453,8 +453,7 @@ export const path = {
newSalesOrderLine: (id: string) =>
generatePath(`${x}/sales-order/${id}/lines/new`),
newSalesRFQ: `${x}/sales-rfq/new`,
- newSalesRFQLine: (id: string) =>
- generatePath(`${x}/sales-rfq/${id}/lines/new`),
+ newSalesRFQLine: (id: string) => generatePath(`${x}/sales-rfq/${id}/new`),
newShift: `${x}/resources/shifts/new`,
newShippingMethod: `${x}/inventory/shipping-methods/new`,
newService: `${x}/service/new`,
@@ -636,7 +635,7 @@ export const path = {
generatePath(`${x}/sales-rfq/${id}/details`),
salesRfqFavorite: `${x}/sales/rfqs/favorite`,
salesRfqLine: (id: string, lineId: string) =>
- generatePath(`${x}/sales-rfq/${id}/lines/${lineId}`),
+ generatePath(`${x}/sales-rfq/${id}/${lineId}/details`),
salesRfqLinesOrder: (id: string) =>
generatePath(`${x}/sales-rfq/${id}/lines/order`),
salesRfqRoot: `${x}/sales-rfq`,
diff --git a/packages/database/supabase/migrations/20240814000622_sales-rfq-line-bucket.sql b/packages/database/supabase/migrations/20240814000622_sales-rfq-line-bucket.sql
new file mode 100644
index 0000000000..574bf332bb
--- /dev/null
+++ b/packages/database/supabase/migrations/20240814000622_sales-rfq-line-bucket.sql
@@ -0,0 +1,31 @@
+CREATE POLICY "Sales RFQ 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_view', (storage.foldername(name))[1])
+ AND (storage.foldername(name))[2] = 'sales-rfq-line'
+);
+
+CREATE POLICY "Sales RFQ line 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_create', (storage.foldername(name))[1])
+ AND (storage.foldername(name))[2] = 'sales-rfq-line'
+);
+
+CREATE POLICY "Sales RFQ 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_update', (storage.foldername(name))[1])
+ AND (storage.foldername(name))[2] = 'sales-rfq-line'
+);
+
+CREATE POLICY "Sales RFQ line 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_delete', (storage.foldername(name))[1])
+ AND (storage.foldername(name))[2] = 'sales-rfq-line'
+);
\ No newline at end of file