Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat: upload files if not export controlled

Brad Barbin2082f61574ca
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index 643750afeb..fb37ddf071 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -6,11 +6,10 @@ import {
cn,
ModelViewer,
Spinner,
- supportedModelTypes,
toast,
} from "@carbon/react";
import { useMode } from "@carbon/remix";
-import { convertKbToString } from "@carbon/utils";
+import { convertKbToString, supportedModelTypes } from "@carbon/utils";
import { useFetcher } from "@remix-run/react";
import { nanoid } from "nanoid";
import { useState } from "react";
diff --git a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx b/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
index ba6fe6ab6d..26070a88ff 100644
--- a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
+++ b/apps/erp/app/modules/items/ui/Parts/PartForm.tsx
@@ -13,10 +13,9 @@ import {
ModalCardTitle,
VStack,
cn,
- supportedModelTypes,
toast,
} from "@carbon/react";
-import { convertKbToString } from "@carbon/utils";
+import { convertKbToString, supportedModelTypes } from "@carbon/utils";
import { useFetcher } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
diff --git a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
index 64ca8717ed..6457b57db2 100644
--- a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
+++ b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx
@@ -13,10 +13,9 @@ import {
ModalCardTitle,
VStack,
cn,
- supportedModelTypes,
toast,
} from "@carbon/react";
-import { convertKbToString } from "@carbon/utils";
+import { convertKbToString, supportedModelTypes } from "@carbon/utils";
import { useFetcher } from "@remix-run/react";
import type { PostgrestResponse } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
diff --git a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
index bf8c8070cc..9650fe0fd7 100644
--- a/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
+++ b/apps/erp/app/modules/sales/ui/Opportunity/OpportunityLineDocuments.tsx
@@ -345,7 +345,7 @@ const useOpportunityLineDocuments = ({
toast.success(
`Moved ${file.name} to ${
- targetBucket === "parts" ? "Parts" : "Opportunity Line"
+ targetBucket === "parts" ? "Parts" : "Opportunity"
} bucket`
);
revalidator.revalidate();
@@ -478,7 +478,7 @@ const OpportunityLineDocuments = ({
: "--"}
</Td>
<Td>
- <Enumerable value="Opportunity Line" />
+ <Enumerable value="Opportunity" />
</Td>
<Td>
<div className="flex justify-end w-full">
diff --git a/apps/erp/app/modules/shared/shared.service.ts b/apps/erp/app/modules/shared/shared.service.ts
index 4787d9fedf..b141f4a4f3 100644
--- a/apps/erp/app/modules/shared/shared.service.ts
+++ b/apps/erp/app/modules/shared/shared.service.ts
@@ -1,5 +1,5 @@
import type { Database } from "@carbon/database";
-import { supportedModelTypes } from "@carbon/react";
+import { supportedModelTypes } from "@carbon/utils";
import { FunctionRegion, type SupabaseClient } from "@supabase/supabase-js";
import type { GenericQueryFilters } from "~/utils/query";
import { setGenericQueryFilters } from "~/utils/query";
diff --git a/apps/erp/app/routes/file+/model+/public.$.tsx b/apps/erp/app/routes/file+/model+/public.$.tsx
index b49a3029ff..f5185ae034 100644
--- a/apps/erp/app/routes/file+/model+/public.$.tsx
+++ b/apps/erp/app/routes/file+/model+/public.$.tsx
@@ -1,5 +1,5 @@
import { getCarbonServiceRole, notFound } from "@carbon/auth";
-import { supportedModelTypes } from "@carbon/react";
+import { supportedModelTypes } from "@carbon/utils";
import { type LoaderFunctionArgs } from "@vercel/remix";
const supportedFileTypes: Record<string, string> = {
diff --git a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
index 7ed09c0256..1258897ae2 100644
--- a/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/erp/app/routes/file+/preview+/$bucket.$.tsx
@@ -1,6 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { supportedModelTypes } from "@carbon/react";
+import { supportedModelTypes } from "@carbon/utils";
import { type LoaderFunctionArgs } from "@vercel/remix";
const supportedFileTypes: Record<string, string> = {
diff --git a/apps/erp/app/routes/share+/customer.$id.$.tsx b/apps/erp/app/routes/share+/customer.$id.$.tsx
index 147c3172fc..c98d800397 100644
--- a/apps/erp/app/routes/share+/customer.$id.$.tsx
+++ b/apps/erp/app/routes/share+/customer.$id.$.tsx
@@ -1,6 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { redis } from "@carbon/kv";
-import { supportedModelTypes } from "@carbon/react";
+import { supportedModelTypes } from "@carbon/utils";
import { Ratelimit } from "@upstash/ratelimit";
import { type LoaderFunctionArgs } from "@vercel/remix";
import { getJobByOperationId } from "~/modules/production";
diff --git a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
index cd222430d5..1bc695b0a0 100644
--- a/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
+++ b/apps/erp/app/routes/x+/sales-rfq+/$rfqId.tsx
@@ -1,4 +1,5 @@
-import { supportedModelTypes, VStack, type JSONContent } from "@carbon/react";
+import { VStack, type JSONContent } from "@carbon/react";
+import { supportedModelTypes } from "@carbon/utils";
import type { DragEndEvent } from "@dnd-kit/core";
import { DndContext } from "@dnd-kit/core";
import { Outlet, useParams, useSubmit } from "@remix-run/react";
diff --git a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
index 2c6b0e3e1b..31e10382b8 100644
--- a/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
+++ b/apps/mes/app/routes/file+/preview+/$bucket.$.tsx
@@ -1,6 +1,6 @@
import { getCarbonServiceRole } from "@carbon/auth";
import { requirePermissions } from "@carbon/auth/auth.server";
-import { supportedModelTypes } from "@carbon/react";
+import { supportedModelTypes } from "@carbon/utils";
import { type LoaderFunctionArgs } from "@vercel/remix";
const supportedFileTypes: Record<string, string> = {
diff --git a/package-lock.json b/package-lock.json
index d81490772f..6667f70866 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -36622,6 +36622,7 @@
"name": "@carbon/react",
"version": "*",
"dependencies": {
+ "@carbon/utils": "*",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-avatar": "^1.0.3",
"@radix-ui/react-checkbox": "^1.0.4",
diff --git a/packages/integrations/src/paperless-parts/lib/schemas.ts b/packages/integrations/src/paperless-parts/lib/schemas.ts
index 71111bcc39..17124b16f9 100644
--- a/packages/integrations/src/paperless-parts/lib/schemas.ts
+++ b/packages/integrations/src/paperless-parts/lib/schemas.ts
@@ -38,12 +38,12 @@ export const AccountSchema = z.object({
// Contact schema
export const ContactSchema = z.object({
- account: AccountSchema.optional(),
+ account: AccountSchema.optional().nullable(),
email: z.string().email().optional(),
first_name: z.string().optional(),
id: z.number().optional(),
last_name: z.string().optional(),
- notes: z.string().optional(),
+ notes: z.string().optional().nullable(),
phone: z.string().optional().nullable(),
phone_ext: z.string().optional().nullable(),
});
@@ -53,8 +53,8 @@ export const CompanySchema = z.object({
business_name: z.string().optional(),
erp_code: z.string().nullable().optional(),
id: z.number().nullable().optional(),
- metrics: AccountMetricsSchema.optional(),
- notes: z.string().nullable().optional(),
+ metrics: AccountMetricsSchema.optional().nullable(),
+ notes: z.string().nullable().optional().nullable(),
phone: z.string().optional().nullable(),
phone_ext: z.string().optional().nullable(),
});
@@ -62,11 +62,11 @@ export const CompanySchema = z.object({
// Customer schema
export const CustomerSchema = z.object({
id: z.number().nullable().optional(),
- company: CompanySchema.optional(),
+ company: CompanySchema.optional().nullable(),
email: z.string().email().optional(),
first_name: z.string().optional(),
last_name: z.string().optional(),
- notes: z.string().optional(),
+ notes: z.string().optional().nullable(),
phone: z.string().optional().nullable(),
phone_ext: z.string().optional().nullable(),
});
@@ -144,7 +144,7 @@ export const OrderItemSchema = z.object({
ships_on: z.string().optional(), // Date string
total_price: z.string().optional(), // API returns as string
unit_price: z.string().optional(), // API returns as string
- base_price: z.string().optional(), // API returns as string
+ base_price: z.string().optional().nullable(), // API returns as string
add_on_fees: z.unknown().nullable().optional(),
unit_price_before_discounts: z.string().optional(), // API returns as string
ordered_add_ons: z.array(z.unknown()).optional(),
@@ -157,14 +157,14 @@ export const PaymentDetailsSchema = z.object({
card_last4: z.string().nullable().optional(),
net_payout: z.string().optional(), // API returns as string
payment_type: z.enum(["credit_card", "purchase_order"]).nullable().optional(),
- purchase_order_number: z.string().optional(),
+ purchase_order_number: z.string().optional().nullable(),
purchasing_dept_contact_email: z.string().email().nullable().optional(),
- purchasing_dept_contact_name: z.string().optional(),
+ purchasing_dept_contact_name: z.string().optional().nullable(),
shipping_cost: z.string().optional(), // API returns as string
subtotal: z.string().optional(), // API returns as string
tax_cost: z.string().optional(), // API returns as string
tax_rate: z.string().optional(), // API returns as string
- payment_terms: z.string().optional(),
+ payment_terms: z.string().optional().nullable(),
total_price: z.string().optional(), // API returns as string
});
@@ -182,7 +182,7 @@ export const ShipmentSchema = z.array(z.unknown()); // Empty array in the exampl
// Main Order schema
export const OrderSchema = z.object({
uuid: z.string().uuid().optional(),
- billing_info: AddressSchema.optional(),
+ billing_info: AddressSchema.optional().nullable(),
created: z.string().optional(), // Loosened datetime restriction
contact: ContactSchema.optional(),
customer: CustomerSchema.optional(),
@@ -201,8 +201,8 @@ export const OrderSchema = z.object({
sales_person: SalesPersonSchema.optional().nullable(),
salesperson: SalesPersonSchema.optional().nullable(),
shipments: ShipmentSchema.optional(),
- shipping_info: AddressSchema.optional(),
- shipping_option: ShippingOptionSchema.optional(),
+ shipping_info: AddressSchema.optional().nullable(),
+ shipping_option: ShippingOptionSchema.optional().nullable(),
ships_on: z.string().optional(), // Date string
status: z
.enum([
diff --git a/packages/integrations/src/paperless-parts/lib/utils.ts b/packages/integrations/src/paperless-parts/lib/utils.ts
index 6e3c06d16c..c02a763d20 100644
--- a/packages/integrations/src/paperless-parts/lib/utils.ts
+++ b/packages/integrations/src/paperless-parts/lib/utils.ts
@@ -1,5 +1,5 @@
import type { Database } from "@carbon/database";
-import { textToTiptap } from "@carbon/utils";
+import { supportedModelTypes, textToTiptap } from "@carbon/utils";
import type { SupabaseClient } from "@supabase/supabase-js";
import { nanoid } from "nanoid";
import type z from "zod";
@@ -12,6 +12,333 @@ import type {
SalesPersonSchema,
} from "./schemas";
+/**
+ * Strip special characters from filename for safe storage
+ */
+function stripSpecialCharacters(inputString: string): string {
+ // Keep only characters that are valid for S3 keys
+ return inputString?.replace(/[^a-zA-Z0-9/!_\-.*'() &$@=;:+,?]/g, "");
+}
+
+/**
+ * Download file from external URL and convert to File object
+ */
+async function downloadFileFromUrl(
+ url: string,
+ filename: string
+): Promise<File | null> {
+ try {
+ console.log(`Downloading file from: ${url}`);
+ const response = await fetch(url);
+
+ if (!response.ok) {
+ console.error(
+ `Failed to download file from ${url}: ${response.statusText}`
+ );
+ return null;
+ }
+
+ const blob = await response.blob();
+ const file = new File([blob], filename, { type: blob.type });
+
+ console.log(`Successfully downloaded: ${filename} (${blob.size} bytes)`);
+ return file;
+ } catch (error) {
+ console.error(`Error downloading file from ${url}:`, error);
+ return null;
+ }
+}
+
+/**
+ * Check if file extension is a supported model type
+ */
+function isModelFile(filename: string): boolean {
+ const extension = filename.toLowerCase().split(".").pop() || "";
+ return supportedModelTypes.includes(extension);
+}
+
+/**
+ * Upload CAD model file and create model record
+ */
+async function uploadModelFile(
+ carbon: SupabaseClient<Database>,
+ args: {
+ file: File;
+ companyId: string;
+ salesOrderLineId: string;
+ }
+): Promise<boolean> {
+ const { file, companyId, salesOrderLineId } = args;
+
+ try {
+ const modelId = nanoid();
+ const fileExtension = file.name.split(".").pop();
+ const modelPath = `${companyId}/models/${modelId}.${fileExtension}`;
+
+ console.log(`Uploading CAD model ${file.name} to ${modelPath}`);
+
+ // Upload model to storage
+ const modelUpload = await carbon.storage
+ .from("private")
+ .upload(modelPath, file, {
+ upsert: true,
+ });
+
+ if (modelUpload.error) {
+ console.error(`Failed to upload model ${file.name}:`, modelUpload.error);
+ return false;
+ }
+
+ if (!modelUpload.data?.path) {
+ console.error(`No path returned for uploaded model ${file.name}`);
+ return false;
+ }
+
+ // Create model record
+ const modelRecord = await carbon.from("modelUpload").insert({
+ id: modelId,
+ modelPath: modelUpload.data.path,
+ name: file.name,
+ size: file.size,
+ companyId,
+ createdBy: "system",
+ });
+
+ if (modelRecord.error) {
+ console.error(
+ `Failed to create model record for ${file.name}:`,
+ modelRecord.error
+ );
+ return false;
+ }
+
+ // Link model to sales order line
+ const lineUpdate = await carbon
+ .from("salesOrderLine")
+ .update({ modelUploadId: modelId })
+ .eq("id", salesOrderLineId);
+
+ if (lineUpdate.error) {
+ console.error(
+ `Failed to link model to sales order line:`,
+ lineUpdate.error
+ );
+ return false;
+ }
+
+ console.log(
+ `Successfully uploaded CAD model ${file.name} and linked to line ${salesOrderLineId}`
+ );
+ return true;
+ } catch (error) {
+ console.error(`Error uploading model ${file.name}:`, error);
+ return false;
+ }
+}
+
+/**
+ * Upload file to Carbon storage and create document record using upsertDocument
+ */
+async function uploadFileToOpportunityLine(
+ carbon: SupabaseClient<Database>,
+ args: {
+ file: File;
+ companyId: string;
+ lineId: string;
+ sourceDocumentType: string;
+ sourceDocumentId: string;
+ }
+): Promise<boolean> {
+ const { file, companyId, lineId, sourceDocumentType, sourceDocumentId } =
+ args;
+
+ try {
+ // Create storage path similar to OpportunityLineDocuments
+ const storagePath = `${companyId}/opportunity-line/${lineId}/${stripSpecialCharacters(
+ file.name
+ )}`;
+
+ console.log(`Uploading ${file.name} to ${storagePath}`);
+
+ const fileUpload = await carbon.storage
+ .from("private")
+ .upload(storagePath, file, {
+ cacheControl: `${12 * 60 * 60}`,
+ upsert: true,
+ });
+
+ if (fileUpload.error) {
+ console.error(`Failed to upload file ${file.name}:`, fileUpload.error);
+ return false;
+ }
+
+ if (!fileUpload.data?.path) {
+ console.error(`No path returned for uploaded file ${file.name}`);
+ return false;
+ }
+
+ // Create document record using a simpler approach
+ // Since we're in a backend context, we'll use a minimal document record
+ const documentType = getDocumentTypeFromFilename(file.name);
+ const documentData = {
+ name: file.name,
+ path: fileUpload.data.path,
+ size: Math.round(file.size / 1024), // Convert to KB
+ sourceDocument: sourceDocumentType as "Sales Order",
+ sourceDocumentId,
+ companyId,
+ type: documentType,
+ readGroups: ["system"],
+ writeGroups: ["system"],
+ createdBy: "system",
+ active: true,
+ };
+
+ console.log(`Document data for ${file.name}:`, {
+ ...documentData,
+ type: documentType,
+ });
+
+ const documentInsert = await carbon
+ .from("document")
+ .insert(documentData)
+ .select("id")
+ .single();
+
+ if (documentInsert.error) {
+ console.error(
+ `Failed to create document record for ${file.name}:`,
+ documentInsert.error
+ );
+ return false;
+ }
+
+ console.log(
+ `Successfully uploaded and created document record for ${file.name}`
+ );
+ return true;
+ } catch (error) {
+ console.error(`Error uploading file ${file.name}:`, error);
+ return false;
+ }
+}
+
+/**
+ * Simple document type detection from filename
+ */
+function getDocumentTypeFromFilename(
+ filename: string
+): Database["public"]["Enums"]["documentType"] {
+ const extension = filename.toLowerCase().split(".").pop() || "";
+
+ if (["pdf"].includes(extension)) return "PDF";
+ if (["jpg", "jpeg", "png", "gif", "bmp", "svg"].includes(extension))
+ return "Image";
+ if (["doc", "docx"].includes(extension)) return "Document";
+ if (["xls", "xlsx"].includes(extension)) return "Spreadsheet";
+ if (["ppt", "pptx"].includes(extension)) return "Presentation";
+ if (["txt"].includes(extension)) return "Text";
+ if (["zip", "rar", "7z"].includes(extension)) return "Archive";
+ if (["mp4", "avi", "mov"].includes(extension)) return "Video";
+ if (["mp3", "wav"].includes(extension)) return "Audio";
+ if (["step", "stp", "iges", "igs", "dwg", "dxf"].includes(extension))
+ return "Model";
+
+ return "Other";
+}
+
+/**
+ * Download and upload supporting files for a component
+ */
+async function processSupportingFiles(
+ carbon: SupabaseClient<Database>,
+ args: {
+ supportingFiles: Array<{ filename?: string; url?: string }>;
+ companyId: string;
+ lineId: string;
+ sourceDocumentType: string;
+ sourceDocumentId: string;
+ }
+): Promise<void> {
+ const {
+ supportingFiles,
+ companyId,
+ lineId,
+ sourceDocumentType,
+ sourceDocumentId,
+ } = args;
+
+ if (!supportingFiles?.length) {
+ return;
+ }
+
+ console.log(
+ `Processing ${supportingFiles.length} supporting files for line ${lineId}`
+ );
+
+ for (const supportingFile of supportingFiles) {
+ if (!supportingFile.url || !supportingFile.filename) {
+ console.warn(
+ "Skipping supporting file with missing URL or filename:",
+ supportingFile
+ );
+ continue;
+ }
+
+ try {
+ // Download the file
+ const file = await downloadFileFromUrl(
+ supportingFile.url,
+ supportingFile.filename
+ );
+
+ if (!file) {
+ console.error(
+ `Failed to download supporting file: ${supportingFile.filename}`
+ );
+ continue;
+ }
+
+ // Check if this is a CAD model file
+ if (isModelFile(file.name)) {
+ console.log(`Processing ${file.name} as CAD model`);
+ const uploadSuccess = await uploadModelFile(carbon, {
+ file,
+ companyId,
+ salesOrderLineId: lineId,
+ });
+
+ if (!uploadSuccess) {
+ console.error(
+ `Failed to upload CAD model: ${supportingFile.filename}`
+ );
+ }
+ } else {
+ console.log(`Processing ${file.name} as document`);
+ // Upload as regular document
+ const uploadSuccess = await uploadFileToOpportunityLine(carbon, {
+ file,
+ companyId,
+ lineId,
+ sourceDocumentType,
+ sourceDocumentId,
+ });
+
+ if (!uploadSuccess) {
+ console.error(
+ `Failed to upload supporting file: ${supportingFile.filename}`
+ );
+ }
+ }
+ } catch (error) {
+ console.error(
+ `Error processing supporting file ${supportingFile.filename}:`,
+ error
+ );
+ }
+ }
+}
+
export async function getCustomerIdAndContactId(
carbon: SupabaseClient<Database>,
paperless: PaperlessPartsClient<unknown>,
@@ -669,21 +996,50 @@ export async function createPartFromComponent(
args: {
companyId: string;
createdBy: string;
- component: {
- id?: number;
- part_number?: string;
- part_name?: string;
- part_uuid?: string;
- revision?: string;
- description?: string | null;
- thumbnail_url?: string;
- part_url?: string;
- };
+ component: z.infer<
+ typeof OrderSchema
+ >["order_items"][number]["components"][number];
}
): Promise<{ itemId: string; partId: string }> {
const { companyId, createdBy, component } = args;
- console.log(component);
+ console.log("material_operations");
+ console.log(component.material_operations);
+ console.log("material");
+ console.log(component.material);
+ console.log("shop_operations");
+ console.log(component.shop_operations);
+
+ // Log costing variables and quantities if they exist
+ if (component.material_operations) {
+ component.material_operations.forEach((operation: any) => {
+ if (operation.costing_variables) {
+ operation.costing_variables.forEach((cv: any) => {
+ console.log("material costing_variable", cv.costing_variable);
+ });
+ }
+ if (operation.quantities) {
+ operation.quantities.forEach((q: any) => {
+ console.log("material quantity", q.quantity);
+ });
+ }
+ });
+ }
+
+ if (component.shop_operations) {
+ component.shop_operations.forEach((operation: any) => {
+ if (operation.costing_variables) {
+ operation.costing_variables.forEach((cv: any) => {
+ console.log("shop costing_variable", cv.costing_variable);
+ });
+ }
+ if (operation.quantities) {
+ operation.quantities.forEach((q: any) => {
+ console.log("shop quantity", q.quantity);
+ });
+ }
+ });
+ }
// Generate a readable ID for the part
const partId =
@@ -813,6 +1169,7 @@ export async function insertOrderLines(
carbon: SupabaseClient<Database>,
args: {
salesOrderId: string;
+ opportunityId: string;
companyId: string;
createdBy: string;
orderItems: z.infer<typeof OrderSchema>["order_items"];
@@ -824,20 +1181,33 @@ export async function insertOrderLines(
return;
}
- const linesToInsert: Database["public"]["Tables"]["salesOrderLine"]["Insert"][] =
- [];
+ let insertedLinesCount = 0;
for (const orderItem of orderItems) {
if (!orderItem.components?.length) {
// Handle order items without components as comment lines
if (orderItem.description || orderItem.public_notes) {
- linesToInsert.push({
- salesOrderId,
- salesOrderLineType: "Comment",
- description: orderItem.description || orderItem.public_notes || "",
- companyId,
- createdBy,
- });
+ const commentLine: Database["public"]["Tables"]["salesOrderLine"]["Insert"] =
+ {
+ salesOrderId,
+ salesOrderLineType: "Comment",
+ description: orderItem.description || orderItem.public_notes || "",
+ companyId,
+ createdBy,
+ };
+
+ const result = await carbon
+ .from("salesOrderLine")
+ .insert(commentLine)
+ .select("id")
+ .single();
+
+ if (result.error) {
+ console.error("Failed to insert comment line:", result.error);
+ continue;
+ }
+
+ insertedLinesCount++;
}
continue;
}
@@ -873,6 +1243,10 @@ export async function insertOrderLines(
companyId,
createdBy,
quantitySent: component.deliver_quantity,
+ // TODO: use the order date and the lead time to calculate the promsied date
+ /*
+ SL: I was hoping that Carbon could take the date the order was pushed and calculate the ship date based on the lead time selected. So let's say the lead time is 3 business days. If I push it tomorrow 8/20 at 7 AM that would be a ship date of 8/22, but if the order comes in a 11 AM that would roll into the next business day and the ship date would be 8/25. It would be nice if it also accounted for days off automatically because we pushed orders the past couple weeks thru but didn't tack on the extra day since labor day is 9/1.
+ */
promisedDate: orderItem.ships_on
? new Date(orderItem.ships_on).toISOString()
: null,
@@ -884,7 +1258,54 @@ export async function insertOrderLines(
: null,
};
- linesToInsert.push(salesOrderLine);
+ // Insert the line first to get the line ID
+ const lineResult = await carbon
+ .from("salesOrderLine")
+ .insert(salesOrderLine)
+ .select("id")
+ .single();
+
+ if (lineResult.error) {
+ console.error(
+ `Failed to insert sales order line for component ${component.part_uuid}:`,
+ lineResult.error
+ );
+ continue;
+ }
+
+ const lineId = lineResult.data.id;
+ insertedLinesCount++;
+
+ // Now process supporting files with the actual line ID
+ if (
+ !orderItem.export_controlled &&
+ (orderItem.filename || component.supporting_files?.length)
+ ) {
+ console.log("orderItem.filename");
+ console.log(orderItem.filename);
+ try {
+ console.log(
+ `Processing supporting files for line ${lineId} (component ${component.part_uuid})`
+ );
+
+ await processSupportingFiles(carbon, {
+ supportingFiles: component.supporting_files as Array<{
+ filename?: string;
+ url?: string;
+ }>,
+ companyId,
+ lineId, // Use the actual line ID
+ sourceDocumentType: "Sales Order",
+ sourceDocumentId: salesOrderId,
+ });
+ } catch (error) {
+ console.error(
+ `Failed to process supporting files for component ${component.part_uuid}:`,
+ error
+ );
+ // Continue processing instead of failing the entire order
+ }
+ }
} catch (error) {
console.error(
`Failed to process component ${component.part_uuid}:`,
@@ -896,18 +1317,10 @@ export async function insertOrderLines(
}
}
- if (linesToInsert.length === 0) {
- console.warn("No valid order lines to insert");
+ if (insertedLinesCount === 0) {
+ console.warn("No valid order lines were inserted");
return;
}
- // Insert all lines in a single operation
- const result = await carbon.from("salesOrderLine").insert(linesToInsert);
-
- if (result.error) {
- console.error("Failed to insert order lines:", result.error);
- throw new Error(`Failed to insert order lines: ${result.error.message}`);
- }
-
- console.log(`Successfully inserted ${linesToInsert.length} order lines`);
+ console.log(`Successfully inserted ${insertedLinesCount} order lines`);
}
diff --git a/packages/jobs/trigger/paperless-parts.ts b/packages/jobs/trigger/paperless-parts.ts
index 8a08b9fb0c..e6b831af6e 100644
--- a/packages/jobs/trigger/paperless-parts.ts
+++ b/packages/jobs/trigger/paperless-parts.ts
@@ -594,6 +594,7 @@ export const paperlessPartsTask = task({
try {
await insertOrderLines(carbon, {
salesOrderId,
+ opportunityId: orderOpportunity.data?.id,
companyId: payload.companyId,
createdBy: orderCreatedBy,
orderItems: orderData.order_items || [],
diff --git a/packages/react/package.json b/packages/react/package.json
index 54206ba177..50a2b8fda9 100644
--- a/packages/react/package.json
+++ b/packages/react/package.json
@@ -1,6 +1,7 @@
{
"name": "@carbon/react",
"dependencies": {
+ "@carbon/utils": "*",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-avatar": "^1.0.3",
"@radix-ui/react-checkbox": "^1.0.4",
diff --git a/packages/react/src/ModelViewer.tsx b/packages/react/src/ModelViewer.tsx
index 4f66dddfa5..15b37de800 100644
--- a/packages/react/src/ModelViewer.tsx
+++ b/packages/react/src/ModelViewer.tsx
@@ -8,27 +8,6 @@ import { Spinner } from "./Spinner";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "./Tabs";
import { cn } from "./utils/cn";
-export const supportedModelTypes = [
- "3dm",
- "3ds",
- "3mf",
- "amf",
- "bim",
- "brep",
- "dae",
- "fbx",
- "fcstd",
- "gltf",
- "ifc",
- "iges",
- "obj",
- "off",
- "ply",
- "step",
- "stl",
- "stp",
-];
-
const darkColor = "#9797a5";
const lightColor = "#8c8a8a";
diff --git a/packages/react/src/index.tsx b/packages/react/src/index.tsx
index ee1ea16154..3b1bb364b1 100644
--- a/packages/react/src/index.tsx
+++ b/packages/react/src/index.tsx
@@ -200,7 +200,7 @@ import {
ModalDrawerTypeProvider,
useModalDrawerType,
} from "./ModalDrawer";
-import { ModelViewer, supportedModelTypes } from "./ModelViewer";
+import { ModelViewer } from "./ModelViewer";
import type { MultiSelectProps } from "./MultiSelect";
import { MultiSelect } from "./MultiSelect";
import type { NumberFieldProps } from "./Number";
@@ -567,7 +567,6 @@ export {
multiSelectTriggerVariants,
reactNodeToString,
shortcutKeyVariants,
- supportedModelTypes,
toast,
useModalCardType,
useModalDrawerType,
diff --git a/packages/utils/src/file.ts b/packages/utils/src/file.ts
index 2ffa2a3881..00e8564c8f 100644
--- a/packages/utils/src/file.ts
+++ b/packages/utils/src/file.ts
@@ -9,3 +9,24 @@ export const convertKbToString = (kb: number) => {
const gb = mb / 1024;
return `${gb.toFixed(2)} GB`;
};
+
+export const supportedModelTypes = [
+ "3dm",
+ "3ds",
+ "3mf",
+ "amf",
+ "bim",
+ "brep",
+ "dae",
+ "fbx",
+ "fcstd",
+ "gltf",
+ "ifc",
+ "iges",
+ "obj",
+ "off",
+ "ply",
+ "step",
+ "stl",
+ "stp",
+];
diff --git a/scripts/paperless-test.ts b/scripts/paperless-test.ts
index d9140d8e66..f9c3282cc7 100644
--- a/scripts/paperless-test.ts
+++ b/scripts/paperless-test.ts
@@ -13,7 +13,7 @@ import {
insertOrderLines,
} from "../packages/integrations/src/paperless-parts/lib/index";
import { OrderSchema } from "../packages/integrations/src/paperless-parts/lib/schemas";
-const orderNumber = 884;
+const orderNumber = 868;
const apiKey = "7fb257095cc635004ecb149c0978c2010f44b99e";
const companyId = "SanLTzPk93kscfQ7oCnSSu";
@@ -78,8 +78,8 @@ const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;
await getCustomerLocationIds(carbon, {
company: company.data!,
customerId,
- billingInfo: orderData.billing_info,
- shippingInfo: orderData.shipping_info,
+ billingInfo: orderData.billing_info ?? undefined,
+ shippingInfo: orderData.shipping_info ?? undefined,
});
const [customerPayment, customerShipping, sequence, opportunity] =
@@ -208,6 +208,7 @@ const SUPABASE_SERVICE_ROLE_KEY = process.env.SUPABASE_SERVICE_ROLE_KEY;
try {
await insertOrderLines(carbon, {
salesOrderId,
+ opportunityId: opportunity.data?.id,
companyId,
createdBy,
orderItems: orderData.order_items || [],