Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat: optimistic updates for drag and drop + logs in autodesk upload function
Brad Barbin5bf741d734fa
diff --git a/apps/carbon/app/jobs/autodesk-upload.server.ts b/apps/carbon/app/jobs/autodesk-upload.server.tsindex 512adae49f..6cf55a2293 100644--- a/apps/carbon/app/jobs/autodesk-upload.server.ts+++ b/apps/carbon/app/jobs/autodesk-upload.server.ts@@ -40,7 +40,10 @@ const job = triggerClient.defineJob({quoteLineId,} = payload;+ io.logger.info("Starting autodesk-upload job", { payload });+try {+ io.logger.info("Getting Autodesk token");const autodeskToken = await getAutodeskToken();if (autodeskToken.error) {throw new Error(@@ -48,8 +51,14 @@ const job = triggerClient.defineJob({);}const token = autodeskToken.data?.token;+ io.logger.info("Autodesk token obtained", {+ token: token?.slice(0, 10) + "...",+ });+const encodedFilename = modelPath.split("/").pop() as string;+ io.logger.info("Encoded filename", { encodedFilename });+ io.logger.info("Getting signed URL and downloading blob");const [signedUrl, blob] = await Promise.all([getAutodeskSignedUrl(encodedFilename, token),supabaseClient.storage.from("private").download(modelPath),@@ -61,16 +70,24 @@ const job = triggerClient.defineJob({throw new Error("Failed to download blob: " + blob.error.message);}+ io.logger.info("Signed URL and blob obtained", {+ signedUrl: signedUrl.data?.url,+ blobSize: blob.data?.size,+ });+const file = new File([blob.data], encodedFilename);const { uploadKey, url } = signedUrl.data;+ io.logger.info("Uploading to Autodesk", { url, uploadKey });const initialUpload = await uploadToAutodesk(url, file, uploadKey);if (initialUpload.error) {throw new Error("Failed to upload file: " + initialUpload.error.message);}+ io.logger.info("Autodesk upload succeeded");+ io.logger.info("Finalizing Autodesk upload");const upload = await finalizeAutodeskUpload(encodedFilename,token,@@ -82,14 +99,18 @@ const job = triggerClient.defineJob({const { urn } = upload.data;const autodeskUrn = Buffer.from(urn).toString("base64");+ io.logger.info("Upload finalized", { urn, autodeskUrn });+ io.logger.info("Translating file");const translation = await translateFile(autodeskUrn, token);if (translation.error) {throw new Error("Failed to translate file: " + translation.error.message);}+ io.logger.info("File translation initiated");+ io.logger.info("Sending autodesk.poll event");const event = await triggerClient.sendEvent({name: "autodesk.poll",payload: {@@ -101,30 +122,40 @@ const job = triggerClient.defineJob({},});- io.logger.info("Event sent", event);+ io.logger.info("Event sent", { event });} catch (err) {+ io.logger.error("Error in autodesk-upload job", { error: err });+const client = getSupabaseServiceRole();+ io.logger.info("Resetting modelUploadId");+if (itemId) {+ io.logger.info("Resetting item modelUploadId", { itemId });await client.from("item").update({ modelUploadId: null }).eq("id", itemId);}if (salesRfqLineId) {+ io.logger.info("Resetting salesRfqLine modelUploadId", {+ salesRfqLineId,+ });await client.from("salesRfqLine").update({ modelUploadId: null }).eq("id", salesRfqLineId);}if (quoteLineId) {+ io.logger.info("Resetting quoteLine modelUploadId", { quoteLineId });await client.from("quoteLine").update({ modelUploadId: null }).eq("id", quoteLineId);}- io.logger.error("Error uploading to Autodesk");- io.logger.info(JSON.stringify(err, null, 2));+ io.logger.error("Error uploading to Autodesk", {+ error: JSON.stringify(err, null, 2),+ });}},});diff --git a/apps/carbon/app/modules/sales/sales.models.ts b/apps/carbon/app/modules/sales/sales.models.tsindex dcaaaa12d0..41245d361e 100644--- a/apps/carbon/app/modules/sales/sales.models.ts+++ b/apps/carbon/app/modules/sales/sales.models.ts@@ -639,6 +639,7 @@ export const salesRfqValidator = z.object({});export const salesRfqDragValidator = z.object({+ id: z.string(),customerPartId: z.string(),is3DModel: z.boolean().optional(),lineId: z.string().optional(),diff --git a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsxindex 1a4f2a5198..a43686345e 100644--- a/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx+++ b/apps/carbon/app/modules/sales/ui/OpportunityDocuments/OpportunityDocuments.tsx@@ -39,6 +39,7 @@ import { useSupabase } from "~/lib/supabase";import { DocumentIcon, getDocumentType } from "~/modules/documents";import { path } from "~/utils/path";import type { Opportunity } from "../../types";+import { useOptimisticDocumentDrag } from "../SalesRFQ/useOptimiticDocumentDrag";type OpportunityDocumentsProps = {attachments: FileObject[];@@ -60,6 +61,8 @@ const OpportunityDocuments = ({type,});+ const optimisticData = useOptimisticDocumentDrag();+const onDrop = useCallback((acceptedFiles: File[]) => {upload(acceptedFiles);@@ -144,42 +147,44 @@ const OpportunityDocuments = ({</Thead><Tbody>{attachments.length ? (- attachments.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>- ))+ 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>+ ))) : (<Tr><Tddiff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsxindex 66ba8ad945..f864ca81ad 100644--- a/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/SalesRFQExplorer.tsx@@ -19,21 +19,17 @@ import {} from "@carbon/react";import { prettifyKeyboardShortcut } from "@carbon/utils";import { useDroppable } from "@dnd-kit/core";-import { useNavigate, useParams } from "@remix-run/react";+import { Link, useParams } from "@remix-run/react";import { useRef, useState } from "react";import { LuImage, LuPlus, LuTrash } from "react-icons/lu";import { MdMoreVert } from "react-icons/md";import { Empty } from "~/components";-import {- useOptimisticLocation,- usePermissions,- useRealtime,- useRouteData,-} from "~/hooks";+import { usePermissions, useRealtime, useRouteData } from "~/hooks";import { path } from "~/utils/path";import type { SalesRFQ, SalesRFQLine } from "../../types";import DeleteSalesRFQLine from "./DeleteSalesRFQLine";import SalesRFQLineForm from "./SalesRFQLineForm";+import { useOptimisticDocumentDrag } from "./useOptimiticDocumentDrag";export default function SalesRFQExplorer() {const { rfqId } = useParams();@@ -83,6 +79,8 @@ export default function SalesRFQExplorer() {unitOfMeasureCode: "EA",};+ const optimisticData = useOptimisticDocumentDrag();+const isDisabled = ["Ready for Quote"].includes(salesRfqData?.rfqSummary.status ?? "");@@ -124,6 +122,24 @@ export default function SalesRFQExplorer() {)}</Empty>)}+ {optimisticData && (+ <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>@@ -208,80 +224,76 @@ function SalesRFQLineItem({const { rfqId, lineId } = useParams();if (!rfqId) throw new Error("Could not find rfqId");const permissions = usePermissions();- const navigate = useNavigate();-- const location = useOptimisticLocation();const isSelected = lineId === line.id;- const onLineClick = (line: SalesRFQLine) => {- if (location.pathname !== path.to.salesRfqLine(rfqId, line.id!)) {- // navigate to line- navigate(path.to.salesRfqLine(rfqId, line.id!));- }- };return (<VStack spacing={0} className="border-b border-border">- <HStack- className={cn(- "w-full p-2 items-center justify-between hover:bg-accent/30 cursor-pointer",- isSelected && "bg-accent/60 hover:bg-accent/50 shadow-inner"- )}- onClick={() => onLineClick(line)}+ <Link+ className="w-full"+ prefetch="intent"+ to={path.to.salesRfqLine(rfqId, line.id!)}>- <HStack spacing={2}>- {line.thumbnailPath ? (- <img- alt="P2392303"- className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent"- src={`/file/preview/private/${line.thumbnailPath}`}- />- ) : !!line.modelId && !line.thumbnailPath ? (- <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>- ) : (- <div className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent p-2">- <LuImage className="w-6 h-6 text-muted-foreground" />- </div>+ <HStack+ className={cn(+ "w-full p-2 items-center justify-between hover:bg-accent/30 cursor-pointer",+ isSelected && "bg-accent/60 hover:bg-accent/50 shadow-inner")}-- <VStack spacing={0}>- <span className="font-semibold line-clamp-1">- {" "}- {line.customerPartId}- {line.customerPartRevision && ` (${line.customerPartRevision})`}- </span>- <span className="font-mono text-muted-foreground text-xs line-clamp-1">- {line.itemReadableId}- </span>- </VStack>- </HStack>- <HStack spacing={0}>- <DropdownMenu>- <DropdownMenuTrigger asChild>- <IconButton- aria-label="More"- icon={<MdMoreVert />}- variant="ghost"- onClick={(e) => e.stopPropagation()}+ >+ <HStack spacing={2}>+ {line.thumbnailPath ? (+ <img+ alt="P2392303"+ className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent"+ src={`/file/preview/private/${line.thumbnailPath}`}/>- </DropdownMenuTrigger>- <DropdownMenuContent>- <DropdownMenuItem- disabled={isDisabled || !permissions.can("update", "sales")}- onClick={(e) => {- e.stopPropagation();- onDelete(line);- }}- >- <DropdownMenuIcon icon={<LuTrash />} />- Delete Line- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>+ ) : !!line.modelId && !line.thumbnailPath ? (+ <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>+ ) : (+ <div className="w-10 h-10 bg-gradient-to-bl from-muted to-muted/40 rounded-lg border-2 border-transparent p-2">+ <LuImage className="w-6 h-6 text-muted-foreground" />+ </div>+ )}++ <VStack spacing={0}>+ <span className="font-semibold line-clamp-1">+ {" "}+ {line.customerPartId}+ {line.customerPartRevision && ` (${line.customerPartRevision})`}+ </span>+ <span className="font-mono text-muted-foreground text-xs line-clamp-1">+ {line.itemReadableId}+ </span>+ </VStack>+ </HStack>+ <HStack spacing={0}>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <IconButton+ aria-label="More"+ icon={<MdMoreVert />}+ variant="ghost"+ onClick={(e) => e.stopPropagation()}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ <DropdownMenuItem+ disabled={isDisabled || !permissions.can("update", "sales")}+ onClick={(e) => {+ e.stopPropagation();+ onDelete(line);+ }}+ >+ <DropdownMenuIcon icon={<LuTrash />} />+ Delete Line+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </HStack></HStack>- </HStack>+ </Link></VStack>);}diff --git a/apps/carbon/app/modules/sales/ui/SalesRFQ/useOptimiticDocumentDrag.tsx b/apps/carbon/app/modules/sales/ui/SalesRFQ/useOptimiticDocumentDrag.tsxnew file mode 100644index 0000000000..b43e728630--- /dev/null+++ b/apps/carbon/app/modules/sales/ui/SalesRFQ/useOptimiticDocumentDrag.tsx@@ -0,0 +1,19 @@+import { useFetchers, useParams } from "@remix-run/react";+import { path } from "~/utils/path";++export function useOptimisticDocumentDrag() {+ const { rfqId } = useParams();+ if (!rfqId) throw new Error("rfqId not found");+ const fetchers = useFetchers();++ const relevantFetcher = fetchers.find(+ (fetcher) => fetcher.formAction === path.to.salesRfqDrag(rfqId)+ );++ const payload = relevantFetcher?.formData?.get("payload");+ if (payload) {+ return JSON.parse(payload as string);+ }++ return null;+}diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsxindex 01858e0ea9..d827dd2b43 100644--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.drag.tsx@@ -40,6 +40,7 @@ export async function action({ request, params }: ActionFunctionArgs) {} = validation.data;let targetLineId = lineId;+ console.log({ targetLineId });if (!targetLineId) {// we are creating a new linelet data = {@@ -73,14 +74,16 @@ export async function action({ request, params }: ActionFunctionArgs) {);}}-+ console.log("targetLineId2", { targetLineId });const fileName = documentPath.split("/").pop();let newPath = "";if (is3DModel) {+ console.log("is3DModel");const fileId = nanoid();const fileExtension = fileName?.split(".").pop();newPath = `${companyId}/models/${fileId}.${fileExtension}`;+ console.log("updating models");const [recordUpdate, recordCreate] = await Promise.all([client.from("salesRfqLine")@@ -93,7 +96,7 @@ export async function action({ request, params }: ActionFunctionArgs) {createdBy: userId,}),]);-+ console.log("model update complete");if (recordUpdate.error) {throw redirect(path.to.salesRfqDetails(rfqId),@@ -114,6 +117,7 @@ export async function action({ request, params }: ActionFunctionArgs) {);}+ console.log("sending autodesk event");await triggerClient.sendEvent({name: "autodesk.upload",payload: {@@ -131,6 +135,7 @@ export async function action({ request, params }: ActionFunctionArgs) {newPath = `${companyId}/opportunity-line/${targetLineId}/${fileName}`;}+ console.log("moving to", { newPath });// Move the file to the new pathconst move = await client.storage.from("private").move(documentPath, newPath);diff --git a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsxindex 264624dc28..17b53607d8 100644--- a/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx+++ b/apps/carbon/app/routes/x+/sales-rfq+/$rfqId.tsx@@ -118,6 +118,7 @@ export default function SalesRFQRoute() {const formData = new FormData();const payload = {+ id: document.id,customerPartId: fileName,is3DModel: is3DModel ? true : undefined,lineId: targetId.startsWith("sales-rfq-line-")