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.

Optimistic UI for draggable RFQ lines and files (#85)

Brad Barbin0e696951332f
diff --git a/apps/carbon/app/components/Documents.tsx b/apps/carbon/app/components/Documents.tsx
index 5d9cacf156..f196d469fd 100644
--- a/apps/carbon/app/components/Documents.tsx
+++ b/apps/carbon/app/components/Documents.tsx
@@ -21,7 +21,12 @@ import {
toast,
} from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
-import { useNavigate, useRevalidator, useSubmit } from "@remix-run/react";
+import {
+ useFetchers,
+ useNavigate,
+ useRevalidator,
+ useSubmit,
+} from "@remix-run/react";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
import { LuAxis3D, LuUpload } from "react-icons/lu";
@@ -29,6 +34,7 @@ import { MdMoreVert } from "react-icons/md";
import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { usePermissions, useUser } from "~/hooks";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
+import type { OptimisticFileObject } from "~/modules/shared";
import type { ModelUpload, StorageItem } from "~/types";
import { path } from "~/utils/path";
import { stripSpecialCharacters } from "~/utils/string";
@@ -62,6 +68,20 @@ const Documents = ({
const canDelete = permissions.can("delete", writeBucketPermission);
const canUpdate = permissions.can("update", writeBucketPermission);
+ const attachmentsByName = new Map<string, StorageItem | OptimisticFileObject>(
+ files.map((file) => [file.name, file])
+ );
+ const pendingItems = usePendingItems();
+ for (let pendingItem of pendingItems) {
+ let item = attachmentsByName.get(pendingItem.name);
+ let merged = item ? { ...item, ...pendingItem } : pendingItem;
+ attachmentsByName.set(pendingItem.name, merged);
+ }
+
+ const allFiles = Array.from(attachmentsByName.values()).sort((a, b) =>
+ a.name.localeCompare(b.name)
+ ) as StorageItem[];
+
const getReadPath = useCallback(
(file: StorageItem) => {
const id = sourceDocumentLineId || sourceDocumentId;
@@ -189,6 +209,8 @@ const Documents = ({
submit(formData, {
method: "post",
action: path.to.newDocument,
+ navigate: false,
+ fetcherKey: `${sourceDocument}:${file.name}`,
});
}
}
@@ -292,7 +314,7 @@ const Documents = ({
</Td>
</Tr>
)}
- {files.map((file) => {
+ {allFiles.map((file) => {
const type = getDocumentType(file.name);
return (
<Tr key={file.id}>
@@ -350,7 +372,7 @@ const Documents = ({
</Tr>
);
})}
- {files.length === 0 && !modelUpload && (
+ {allFiles.length === 0 && !modelUpload && (
<Tr>
<Td
colSpan={24}
@@ -369,3 +391,34 @@ const Documents = ({
};
export default Documents;
+
+const usePendingItems = () => {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.newDocument;
+ })
+ .reduce<OptimisticFileObject[]>((acc, fetcher) => {
+ const path = fetcher.formData.get("path") as string;
+ const name = fetcher.formData.get("name") as string;
+ const size = parseInt(fetcher.formData.get("size") as string, 10) * 1024;
+
+ if (path && name && size) {
+ const newItem: OptimisticFileObject = {
+ id: path,
+ name: name,
+ bucket_id: "private",
+ bucket: "private",
+ metadata: {
+ size,
+ mimetype: getDocumentType(name),
+ },
+ };
+ return [...acc, newItem];
+ }
+ return acc;
+ }, []);
+};
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
index d5eab77128..e929f64c46 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentCreateForm.tsx
@@ -56,6 +56,7 @@ const DocumentCreateForm = () => {
submit(formData, {
method: "post",
action: path.to.newDocument,
+ navigate: false,
});
};
diff --git a/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx b/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
index 8e7f2687e3..6d21029ef9 100644
--- a/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
+++ b/apps/carbon/app/modules/documents/ui/Documents/DocumentIcon.tsx
@@ -17,62 +17,62 @@ type DocumentIconProps = {
className?: string;
};
-const documentIconBaseClase = "w-6 h-6 flex-shrink-0";
+const documentIconBaseClass = "flex w-6 h-6 flex-shrink-0";
const DocumentIcon = ({ type, className }: DocumentIconProps) => {
switch (type) {
case "Document":
return (
<BsFileWordFill
- className={cn(documentIconBaseClase, "text-blue-500", className)}
+ className={cn(documentIconBaseClass, "text-blue-500", className)}
/>
);
case "Spreadsheet":
return (
<BsFileExcelFill
- className={cn(documentIconBaseClase, "text-emerald-700", className)}
+ className={cn(documentIconBaseClass, "text-emerald-700", className)}
/>
);
case "Presentation":
return (
<BsFilePptFill
- className={cn(documentIconBaseClase, "text-orange-400", className)}
+ className={cn(documentIconBaseClass, "text-orange-400", className)}
/>
);
case "PDF":
return (
<BsFilePdfFill
- className={cn(documentIconBaseClase, "text-red-600", className)}
+ className={cn(documentIconBaseClass, "text-red-600", className)}
/>
);
case "Archive":
- return <BsFileZipFill className={cn(documentIconBaseClase, className)} />;
+ return <BsFileZipFill className={cn(documentIconBaseClass, className)} />;
case "Text":
return (
- <BsFileTextFill className={cn(documentIconBaseClase, className)} />
+ <BsFileTextFill className={cn(documentIconBaseClass, className)} />
);
case "Image":
return (
<BsFileImageFill
- className={cn(documentIconBaseClase, "text-yellow-400", className)}
+ className={cn(documentIconBaseClass, "text-yellow-400", className)}
/>
);
case "Video":
return (
<BsFileEarmarkPlayFill
- className={cn(documentIconBaseClase, "text-purple-500", className)}
+ className={cn(documentIconBaseClass, "text-purple-500", className)}
/>
);
case "Audio":
return (
<BsFileEarmarkPlayFill
- className={cn(documentIconBaseClase, "text-cyan-400", className)}
+ className={cn(documentIconBaseClass, "text-cyan-400", className)}
/>
);
case "Other":
default:
return (
- <BsFileEarmarkFill className={cn(documentIconBaseClase, className)} />
+ <BsFileEarmarkFill className={cn(documentIconBaseClass, className)} />
);
}
};
diff --git a/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
index 8737281177..2ed22d8fc2 100644
--- a/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
+++ b/apps/carbon/app/modules/items/ui/Item/ItemDocuments.tsx
@@ -26,9 +26,14 @@ import { MdMoreVert } from "react-icons/md";
import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { ItemFile } from "~/modules/items";
-import type { MethodItemType } from "~/modules/shared";
+import type { MethodItemType, OptimisticFileObject } from "~/modules/shared";
-import { useNavigate, useRevalidator, useSubmit } from "@remix-run/react";
+import {
+ useFetchers,
+ useNavigate,
+ useRevalidator,
+ useSubmit,
+} from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
@@ -70,6 +75,20 @@ const ItemDocuments = ({
[upload]
);
+ const attachmentsByName = new Map<string, FileObject | OptimisticFileObject>(
+ files.map((file) => [file.name, file])
+ );
+ const pendingItems = usePendingItems();
+ for (let pendingItem of pendingItems) {
+ let item = attachmentsByName.get(pendingItem.name);
+ let merged = item ? { ...item, ...pendingItem } : pendingItem;
+ attachmentsByName.set(pendingItem.name, merged);
+ }
+
+ const allFiles = Array.from(attachmentsByName.values()).sort((a, b) =>
+ a.name.localeCompare(b.name)
+ ) as FileObject[];
+
return (
<Card className="flex-grow">
<HStack className="justify-between items-start">
@@ -140,7 +159,7 @@ const ItemDocuments = ({
</Td>
</Tr>
)}
- {files.map((file) => {
+ {allFiles.map((file) => {
const type = getDocumentType(file.name);
return (
<Tr key={file.id}>
@@ -198,7 +217,7 @@ const ItemDocuments = ({
</Tr>
);
})}
- {files.length === 0 && !modelUpload && (
+ {allFiles.length === 0 && !modelUpload && (
<Tr>
<Td
colSpan={24}
@@ -368,6 +387,8 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
submit(formData, {
method: "post",
action: path.to.newDocument,
+ navigate: false,
+ fetcherKey: `item:${file.name}`,
});
}
}
@@ -386,3 +407,34 @@ export const useItemDocuments = ({ itemId, type }: Props) => {
upload,
};
};
+
+const usePendingItems = () => {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.newDocument;
+ })
+ .reduce<OptimisticFileObject[]>((acc, fetcher) => {
+ const path = fetcher.formData.get("path") as string;
+ const name = fetcher.formData.get("name") as string;
+ const size = parseInt(fetcher.formData.get("size") as string, 10) * 1024;
+
+ if (path && name && size) {
+ const newItem: OptimisticFileObject = {
+ id: path,
+ name: name,
+ bucket_id: "private",
+ bucket: "private",
+ metadata: {
+ size,
+ mimetype: getDocumentType(name),
+ },
+ };
+ return [...acc, newItem];
+ }
+ return acc;
+ }, []);
+};
diff --git a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
index d6f38422ca..9299b74518 100644
--- a/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
+++ b/apps/carbon/app/modules/purchasing/ui/PurchaseOrder/PurchaseOrderDocuments/PurchaseOrderDocumentForm.tsx
@@ -68,6 +68,8 @@ const PurchaseOrderDocumentForm = ({
submit(formData, {
method: "post",
action: path.to.newDocument,
+ navigate: false,
+ fetcherKey: `purchase-order:${name}`,
});
};
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
index ca57415948..e21f1b6fb6 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx
@@ -23,7 +23,12 @@ import {
} from "@carbon/react";
import { convertKbToString } from "@carbon/utils";
import { useDndContext, useDraggable } from "@dnd-kit/core";
-import { Outlet, useRevalidator, useSubmit } from "@remix-run/react";
+import {
+ Outlet,
+ useFetchers,
+ useRevalidator,
+ useSubmit,
+} from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import type { ChangeEvent } from "react";
import { useCallback } from "react";
@@ -62,8 +67,6 @@ const OpportunityDocuments = ({
type,
});
- const optimisticData = useOptimisticDocumentDrag();
-
const onDrop = useCallback(
(acceptedFiles: File[]) => {
upload(acceptedFiles);
@@ -71,56 +74,21 @@ const OpportunityDocuments = ({
[upload]
);
- const DraggableCell = ({ attachment }: { attachment: FileObject }) => {
- const context = useDndContext();
- const { attributes, listeners, setNodeRef, transform } = useDraggable({
- id: attachment.id,
- data: {
- ...attachment,
- path: getPath(attachment),
- },
- });
+ const optimisticDrags = useOptimisticDocumentDrag();
- const style = transform
- ? {
- transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
- zIndex: 1000,
- }
- : undefined;
-
- return (
- <Td ref={setNodeRef} style={style} {...attributes} {...listeners}>
- <HStack>
- {context.droppableContainers.size > 0 && <LuGripVertical />}
- <DocumentIcon type={getDocumentType(attachment.name)} />
- <span className="font-medium" onClick={() => download(attachment)}>
- {["PDF", "Image"].includes(getDocumentType(attachment.name)) ? (
- <DocumentPreview
- bucket="private"
- pathToFile={getPath(attachment)}
- // @ts-ignore
- type={getDocumentType(attachment.name)}
- >
- {attachment.name}
- </DocumentPreview>
- ) : (
- attachment.name
- )}
- </span>
- {opportunity?.purchaseOrderDocumentPath === getPath(attachment) && (
- <Badge variant="secondary">
- <LuShoppingCart />
- </Badge>
- )}
- {opportunity?.requestForQuoteDocumentPath === getPath(attachment) && (
- <Badge variant="secondary">
- <LuRadioTower />
- </Badge>
- )}
- </HStack>
- </Td>
- );
- };
+ const attachmentsByName = new Map<string, FileObject | OptimisticFileObject>(
+ attachments.map((file) => [file.name, file])
+ );
+ const pendingItems = usePendingItems();
+ for (let pendingItem of pendingItems) {
+ let item = attachmentsByName.get(pendingItem.name);
+ let merged = item ? { ...item, ...pendingItem } : pendingItem;
+ attachmentsByName.set(pendingItem.name, merged);
+ }
+
+ const attachmentsToRender = Array.from(attachmentsByName.values())
+ .filter((d) => !optimisticDrags?.find((o) => o.id === d.id))
+ .sort((a, b) => a.name.localeCompare(b.name)) as FileObject[];
return (
<>
@@ -147,45 +115,48 @@ const OpportunityDocuments = ({
</Tr>
</Thead>
<Tbody>
- {attachments.length ? (
- attachments
- .filter((d) => d.id !== optimisticData?.id)
- .map((attachment) => (
- <Tr key={attachment.id}>
- <DraggableCell attachment={attachment} />
- <Td className="text-xs font-mono">
- {convertKbToString(
- Math.floor((attachment.metadata?.size ?? 0) / 1024)
- )}
- </Td>
- <Td>
- <div className="flex justify-end gap-2">
- <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>
- ))
+ {attachmentsToRender.length ? (
+ attachmentsToRender.map((attachment) => (
+ <Tr key={attachment.id}>
+ <DraggableCell
+ attachment={attachment}
+ opportunity={opportunity}
+ download={download}
+ getPath={getPath}
+ />
+ <Td className="text-xs font-mono">
+ {convertKbToString(
+ Math.floor((attachment.metadata?.size ?? 0) / 1024)
+ )}
+ </Td>
+ <Td>
+ <div className="flex justify-end gap-2">
+ <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
@@ -207,6 +178,69 @@ const OpportunityDocuments = ({
);
};
+const DraggableCell = ({
+ attachment,
+ opportunity,
+ download,
+ getPath,
+}: {
+ attachment: FileObject;
+ opportunity: Opportunity;
+ download: (attachment: FileObject) => void;
+ getPath: (attachment: FileObject) => string;
+}) => {
+ const context = useDndContext();
+ const { attributes, listeners, setNodeRef, transform } = useDraggable({
+ id: attachment.id,
+ data: {
+ ...attachment,
+ path: getPath(attachment),
+ },
+ });
+
+ const style = transform
+ ? {
+ transform: `translate3d(${transform.x}px, ${transform.y}px, 0)`,
+ zIndex: 1000,
+ }
+ : undefined;
+
+ return (
+ <Td ref={setNodeRef} style={style} {...attributes} {...listeners}>
+ <HStack>
+ {context.droppableContainers.size > 0 && (
+ <LuGripVertical className="w-4 h-4 flex-shrink-0" />
+ )}
+ <DocumentIcon type={getDocumentType(attachment.name)} />
+ <span className="font-medium" onClick={() => download(attachment)}>
+ {["PDF", "Image"].includes(getDocumentType(attachment.name)) ? (
+ <DocumentPreview
+ bucket="private"
+ pathToFile={getPath(attachment)}
+ // @ts-ignore
+ type={getDocumentType(attachment.name)}
+ >
+ {attachment.name}
+ </DocumentPreview>
+ ) : (
+ attachment.name
+ )}
+ </span>
+ {opportunity?.purchaseOrderDocumentPath === getPath(attachment) && (
+ <Badge variant="secondary">
+ <LuShoppingCart />
+ </Badge>
+ )}
+ {opportunity?.requestForQuoteDocumentPath === getPath(attachment) && (
+ <Badge variant="secondary">
+ <LuRadioTower />
+ </Badge>
+ )}
+ </HStack>
+ </Td>
+ );
+};
+
type OpportunityDocumentFormProps = {
opportunityId: string;
id: string;
@@ -300,6 +334,8 @@ export const useOpportunityDocuments = ({
submit(formData, {
method: "post",
action: path.to.newDocument,
+ navigate: false,
+ fetcherKey: `opportunity:${name}`,
});
},
[id, submit, type]
@@ -373,3 +409,37 @@ const OpportunityDocumentForm = (props: OpportunityDocumentFormProps) => {
};
export default OpportunityDocuments;
+
+type OptimisticFileObject = Omit<
+ FileObject,
+ "owner" | "updated_at" | "created_at" | "last_accessed_at" | "buckets"
+>;
+export const usePendingItems = () => {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.newDocument;
+ })
+ .reduce<OptimisticFileObject[]>((acc, fetcher) => {
+ const path = fetcher.formData.get("path") as string;
+ const name = fetcher.formData.get("name") as string;
+ const size = parseInt(fetcher.formData.get("size") as string, 10) * 1024;
+
+ if (path && name && size) {
+ const newItem: OptimisticFileObject = {
+ id: path,
+ name: name,
+ bucket_id: "private",
+ metadata: {
+ size,
+ mimetype: getDocumentType(name),
+ },
+ };
+ return [...acc, newItem];
+ }
+ return acc;
+ }, []);
+};
diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
index c2d4428808..67e5d9ae3b 100644
--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityLineDocuments.tsx
@@ -27,13 +27,19 @@ import { DocumentPreview, FileDropzone, Hyperlink } from "~/components";
import { DocumentIcon, getDocumentType } from "~/modules/documents";
import type { ItemFile } from "~/modules/items";
-import { useNavigate, useRevalidator, useSubmit } from "@remix-run/react";
+import {
+ useFetchers,
+ useNavigate,
+ useRevalidator,
+ useSubmit,
+} from "@remix-run/react";
import type { ChangeEvent } from "react";
import { usePermissions, useUser } from "~/hooks";
import { path } from "~/utils/path";
import { useCarbon } from "@carbon/auth";
import { useCallback } from "react";
+import type { OptimisticFileObject } from "~/modules/shared";
import type { ModelUpload } from "~/types";
import { stripSpecialCharacters } from "~/utils/string";
@@ -179,6 +185,8 @@ const useOpportunityLineDocuments = ({
submit(formData, {
method: "post",
action: path.to.newDocument,
+ navigate: false,
+ fetcherKey: `opportunity-line:${name}`,
});
},
[id, submit, type]
@@ -264,6 +272,20 @@ const OpportunityLineDocuments = ({
[upload]
);
+ const attachmentsByName = new Map<string, FileObject | OptimisticFileObject>(
+ files.map((file) => [file.name, file])
+ );
+ const pendingItems = usePendingItems();
+ for (let pendingItem of pendingItems) {
+ let item = attachmentsByName.get(pendingItem.name);
+ let merged = item ? { ...item, ...pendingItem } : pendingItem;
+ attachmentsByName.set(pendingItem.name, merged);
+ }
+
+ const allFiles = Array.from(attachmentsByName.values()).sort((a, b) =>
+ a.name.localeCompare(b.name)
+ ) as FileObject[];
+
return (
<>
<Card className="flex-grow">
@@ -335,7 +357,7 @@ const OpportunityLineDocuments = ({
</Td>
</Tr>
)}
- {files.map((file) => {
+ {allFiles.map((file) => {
const type = getDocumentType(file.name);
return (
<Tr key={file.id}>
@@ -393,7 +415,7 @@ const OpportunityLineDocuments = ({
</Tr>
);
})}
- {files.length === 0 && !modelUpload && (
+ {allFiles.length === 0 && !modelUpload && (
<Tr>
<Td
colSpan={24}
@@ -445,3 +467,34 @@ const OpportunityLineDocumentForm = ({
</File>
);
};
+
+const usePendingItems = () => {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.newDocument;
+ })
+ .reduce<OptimisticFileObject[]>((acc, fetcher) => {
+ const path = fetcher.formData.get("path") as string;
+ const name = fetcher.formData.get("name") as string;
+ const size = parseInt(fetcher.formData.get("size") as string, 10) * 1024;
+
+ if (path && name && size) {
+ const newItem: OptimisticFileObject = {
+ id: path,
+ name: name,
+ bucket_id: "private",
+ bucket: "private",
+ metadata: {
+ size,
+ mimetype: getDocumentType(name),
+ },
+ };
+ return [...acc, newItem];
+ }
+ return acc;
+ }, []);
+};
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
index f719b3bcb7..c4c434b860 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx
@@ -19,14 +19,16 @@ import {
} from "@carbon/react";
import { prettifyKeyboardShortcut } from "@carbon/utils";
import { useDroppable } from "@dnd-kit/core";
-import { Link, useParams } from "@remix-run/react";
+import { Link, useFetchers, useParams } from "@remix-run/react";
import { useRef, useState } from "react";
import { LuPlus, LuTrash } from "react-icons/lu";
import { MdMoreVert } from "react-icons/md";
+import type { z } from "zod";
import { Empty, ItemThumbnail } from "~/components";
import { usePermissions, useRealtime, useRouteData } from "~/hooks";
import type { MethodItemType } from "~/modules/shared";
import { path } from "~/utils/path";
+import { salesRfqDragValidator } from "../../sales.models";
import type { SalesRFQ, SalesRFQLine } from "../../types";
import DeleteSalesRFQLine from "./DeleteSalesRFQLine";
import SalesRFQLineForm from "./SalesRFQLineForm";
@@ -80,8 +82,6 @@ export default function SalesRFQExplorer() {
unitOfMeasureCode: "EA",
};
- const optimisticData = useOptimisticDocumentDrag();
-
const isDisabled = ["Ready for Quote"].includes(
salesRfqData?.rfqSummary.status ?? ""
);
@@ -90,7 +90,22 @@ export default function SalesRFQExplorer() {
id: "sales-rfq-explorer",
});
- const hasOptimisticData = optimisticData && !optimisticData.lineId;
+ const linesByCustomerPartId = new Map<
+ string,
+ SalesRFQLine | z.infer<typeof salesRfqDragValidator>
+ >(salesRfqData?.lines.map((line) => [line.customerPartId!, line]));
+ const pendingItems = useOptimisticDocumentDrag();
+
+ // merge pending items and existing items
+ for (let pendingItem of pendingItems) {
+ let item = linesByCustomerPartId.get(pendingItem.customerPartId!);
+ let merged = item
+ ? { ...item, ...pendingItem }
+ : { ...pendingItem, salesRfqId: rfqId };
+ linesByCustomerPartId.set(pendingItem.customerPartId!, merged);
+ }
+
+ const lines = Array.from(linesByCustomerPartId.values());
return (
<div
@@ -104,15 +119,22 @@ export default function SalesRFQExplorer() {
<VStack className="w-full h-[calc(100vh-99px)] justify-between">
<VStack className="flex-1 overflow-y-auto" spacing={0}>
{(salesRfqData?.lines && salesRfqData?.lines?.length > 0) ||
- hasOptimisticData ? (
- salesRfqData?.lines.map((line) => (
- <DroppableSalesRFQLineItem
- key={line.id}
- line={line}
- isDisabled={isDisabled}
- onDelete={onDeleteLine}
- />
- ))
+ lines.length > 0 ? (
+ lines.map((line) =>
+ !isSalesRFQLine(line) ? (
+ <OptimisticSalesRFQLineItem
+ key={line.id}
+ line={line as z.infer<typeof salesRfqDragValidator>}
+ />
+ ) : (
+ <DroppableSalesRFQLineItem
+ key={line.id}
+ line={line as SalesRFQLine}
+ isDisabled={isDisabled}
+ onDelete={onDeleteLine}
+ />
+ )
+ )
) : (
<Empty>
{permissions.can("update", "sales") && (
@@ -127,24 +149,6 @@ export default function SalesRFQExplorer() {
)}
</Empty>
)}
- {hasOptimisticData && (
- <VStack spacing={0} className="border-b border-border">
- <HStack className="w-full p-2 items-center justify-between hover:bg-accent/30 cursor-pointer">
- <HStack spacing={2}>
- <div className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent p-2">
- <Spinner className="w-6 h-6 text-muted-foreground" />
- </div>
-
- <VStack spacing={0}>
- <span className="font-semibold line-clamp-1">
- {optimisticData.customerPartId}
- </span>
- </VStack>
- </HStack>
- <HStack spacing={0}></HStack>
- </HStack>
- </VStack>
- )}
</VStack>
<div className="w-full flex flex-0 sm:flex-row border-t border-border p-4 sm:justify-start sm:space-x-2">
<Tooltip>
@@ -183,12 +187,43 @@ export default function SalesRFQExplorer() {
);
}
+function isSalesRFQLine(
+ line: SalesRFQLine | z.infer<typeof salesRfqDragValidator>
+) {
+ return "id" in line && "order" in line && "unitOfMeasureCode" in line;
+}
+
type DroppableSalesRFQLineItemProps = {
line: SalesRFQLine;
isDisabled: boolean;
onDelete: (line: SalesRFQLine) => void;
};
+function OptimisticSalesRFQLineItem({
+ line,
+}: {
+ line: z.infer<typeof salesRfqDragValidator>;
+}) {
+ return (
+ <VStack spacing={0} className="border-b border-border">
+ <HStack className="w-full p-2 items-center justify-between hover:bg-accent/30 cursor-pointer">
+ <HStack spacing={2}>
+ <div className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent p-2">
+ <Spinner className="w-6 h-6 text-muted-foreground" />
+ </div>
+
+ <VStack spacing={0}>
+ <span className="font-semibold line-clamp-1">
+ {line.customerPartId}
+ </span>
+ </VStack>
+ </HStack>
+ <HStack spacing={0}></HStack>
+ </HStack>
+ </VStack>
+ );
+}
+
function DroppableSalesRFQLineItem({
line,
isDisabled,
@@ -292,3 +327,28 @@ function SalesRFQLineItem({
</VStack>
);
}
+
+export function useOptimisticSalesRFQLineDrag() {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
+ const { rfqId } = useParams();
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.salesRfqDrag(rfqId!);
+ })
+ .reduce<z.infer<typeof salesRfqDragValidator>[]>((acc, fetcher) => {
+ const payload = fetcher?.formData?.get("payload");
+ if (payload) {
+ try {
+ const parsedPayload = salesRfqDragValidator.parse(
+ JSON.parse(payload as string)
+ );
+ return [...acc, parsedPayload];
+ } catch {
+ // nothing
+ }
+ }
+ return acc;
+ }, []);
+}
diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/useOptimiticDocumentDrag.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/useOptimiticDocumentDrag.tsx
index 2c6f5cb04a..e3f861531c 100644
--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/useOptimiticDocumentDrag.tsx
+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/useOptimiticDocumentDrag.tsx
@@ -1,30 +1,29 @@
import { useFetchers, useParams } from "@remix-run/react";
+import type { z } from "zod";
import { path } from "~/utils/path";
import { salesRfqDragValidator } from "../../sales.models";
export function useOptimisticDocumentDrag() {
+ type PendingItem = ReturnType<typeof useFetchers>[number] & {
+ formData: FormData;
+ };
const { rfqId } = useParams();
- const fetchers = useFetchers();
-
- if (!rfqId) return null;
-
- const relevantFetcher = fetchers.find(
- (fetcher) => fetcher.formAction === path.to.salesRfqDrag(rfqId)
- );
-
- const payload = relevantFetcher?.formData?.get("payload");
- if (payload) {
- try {
- const parsedPayload = salesRfqDragValidator.safeParse(
- JSON.parse(payload as string)
- );
- if (parsedPayload.success) {
- return parsedPayload.data;
+ return useFetchers()
+ .filter((fetcher): fetcher is PendingItem => {
+ return fetcher.formAction === path.to.salesRfqDrag(rfqId!);
+ })
+ .reduce<z.infer<typeof salesRfqDragValidator>[]>((acc, fetcher) => {
+ const payload = fetcher?.formData?.get("payload");
+ if (payload) {
+ try {
+ const parsedPayload = salesRfqDragValidator.parse(
+ JSON.parse(payload as string)
+ );
+ return [...acc, parsedPayload];
+ } catch {
+ // nothing
+ }
}
- } catch {
- // nothing
- }
- }
-
- return null;
+ return acc;
+ }, []);
}
diff --git a/apps/carbon/app/modules/shared/types.ts b/apps/carbon/app/modules/shared/types.ts
index cea82ef954..825f105a5c 100644
--- a/apps/carbon/app/modules/shared/types.ts
+++ b/apps/carbon/app/modules/shared/types.ts
@@ -1,3 +1,4 @@
+import type { StorageItem } from "~/types";
import type { methodItemType, methodType } from "./shared.models";
import type { getNotes } from "./shared.service";
@@ -36,6 +37,11 @@ export type Note = NonNullable<
Awaited<ReturnType<typeof getNotes>>["data"]
>[number];
+export type OptimisticFileObject = Omit<
+ StorageItem,
+ "owner" | "updated_at" | "created_at" | "last_accessed_at" | "buckets"
+>;
+
export const standardFactorType = [
"Hours/Piece",
"Hours/100 Pieces",
diff --git a/apps/carbon/app/routes/x+/documents+/new.tsx b/apps/carbon/app/routes/x+/documents+/new.tsx
index 8f3944fde6..e49b6baafe 100644
--- a/apps/carbon/app/routes/x+/documents+/new.tsx
+++ b/apps/carbon/app/routes/x+/documents+/new.tsx
@@ -2,9 +2,9 @@ import { assertIsPost, error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
import type { ActionFunctionArgs } from "@vercel/remix";
-import { redirect } from "@vercel/remix";
+import { json, redirect } from "@vercel/remix";
import { upsertDocument } from "~/modules/documents";
-import { path, requestReferrer } from "~/utils/path";
+import { path } from "~/utils/path";
export async function action({ request }: ActionFunctionArgs) {
assertIsPost(request);
@@ -49,5 +49,5 @@ export async function action({ request }: ActionFunctionArgs) {
);
}
- throw redirect(requestReferrer(request) ?? path.to.documents);
+ return json({ document: createDocument.data });
}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
index 1ec8ec36a2..b9b21023a7 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx
@@ -154,5 +154,5 @@ export async function action({ request, params }: ActionFunctionArgs) {
}
}
- throw redirect(path.to.salesRfqDetails(rfqId));
+ return json({ success: true });
}
diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
index 2276f67ba4..839575c156 100644
--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx
@@ -4,17 +4,15 @@ import {
ResizablePanel,
ResizablePanelGroup,
ScrollArea,
- toast,
VStack,
type JSONContent,
} from "@carbon/react";
import type { DragEndEvent } from "@dnd-kit/core";
import { DndContext } from "@dnd-kit/core";
-import { Outlet, useFetcher, useParams } from "@remix-run/react";
+import { Outlet, useParams, useSubmit } from "@remix-run/react";
import type { FileObject } from "@supabase/storage-js";
import type { LoaderFunctionArgs } from "@vercel/remix";
import { json, redirect } from "@vercel/remix";
-import { useCallback, useEffect } from "react";
import { supportedFileTypes } from "~/components/CadModel";
import type { SalesRFQLine } from "~/modules/sales";
import {
@@ -30,6 +28,7 @@ import {
import { error } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
import { flash } from "@carbon/auth/session.server";
+import { useOptimisticDocumentDrag } from "~/modules/sales/ui/SalesRFQ/useOptimiticDocumentDrag";
import type { Handle } from "~/utils/handle";
import { path } from "~/utils/path";
@@ -100,44 +99,44 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
export default function SalesRFQRoute() {
const { rfqId } = useParams();
if (!rfqId) throw new Error("Could not find rfqId");
- const fetcher = useFetcher<{ error: string }>();
-
- useEffect(() => {
- if (fetcher.data?.error) {
- toast.error(fetcher.data?.error);
- }
- }, [fetcher.data]);
-
- const handleDrop = useCallback(
- (document: FileObject & { path: string }, targetId: string) => {
- const fileName = document.name.split(".").slice(0, -1).join(".");
- const fileExtension = document.name.split(".").pop()?.toLowerCase();
- const is3DModel = fileExtension
- ? supportedFileTypes.includes(fileExtension)
- : false;
-
- const formData = new FormData();
-
- const payload = {
- id: document.id,
- customerPartId: fileName,
- is3DModel: is3DModel ? true : undefined,
- lineId: targetId.startsWith("sales-rfq-line-")
- ? targetId.replace("sales-rfq-line-", "")
- : undefined,
- path: document.path,
- salesRfqId: rfqId,
- };
-
- formData.append("payload", JSON.stringify(payload));
-
- fetcher.submit(formData, {
- method: "post",
- action: path.to.salesRfqDrag(rfqId),
- });
- },
- [fetcher, rfqId]
- );
+ const submit = useSubmit();
+
+ const pendingItems = useOptimisticDocumentDrag();
+
+ const handleDrop = (
+ document: FileObject & { path: string },
+ targetId: string
+ ) => {
+ if (pendingItems.find((item) => item.id === document.id)) return;
+
+ const fileName = document.name.split(".").slice(0, -1).join(".");
+ const fileExtension = document.name.split(".").pop()?.toLowerCase();
+ const is3DModel = fileExtension
+ ? supportedFileTypes.includes(fileExtension)
+ : false;
+
+ const formData = new FormData();
+
+ const payload = {
+ id: document.id,
+ customerPartId: fileName,
+ is3DModel: is3DModel ? true : undefined,
+ lineId: targetId.startsWith("sales-rfq-line-")
+ ? targetId.replace("sales-rfq-line-", "")
+ : undefined,
+ path: document.path,
+ salesRfqId: rfqId,
+ };
+
+ formData.append("payload", JSON.stringify(payload));
+
+ submit(formData, {
+ method: "post",
+ action: path.to.salesRfqDrag(rfqId),
+ navigate: false,
+ fetcherKey: `drag-${document.id}`,
+ });
+ };
const handleDragEnd = (event: DragEndEvent) => {
const { over, active } = event;