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
[Fiber] Add CSV import tools (#486)
fiber-bot[bot]ef45a12382bb
diff --git a/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx b/apps/erp/app/components/ImportCSVModal/FieldMappings.tsxindex e0fe747525..1bce0a209b 100644--- a/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx+++ b/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx@@ -5,6 +5,7 @@ import type { Database } from "@carbon/database";import { Combobox, useFormContext } from "@carbon/form";import {Button,+ ModalBody,ModalDescription,ModalHeader,ModalTitle,@@ -77,7 +78,34 @@ export function FieldMapping({// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migrationuseEffect(() => {- if (!fileColumns || !firstRows) return;+ if (!fileColumns || !firstRows || initialized.current) return;++ // Try exact matching by label and field name before calling the LLM+ const fileColumnsLower = fileColumns.map((c) => c.toLowerCase().trim());+ const exactMatches: Record<string, string> = {};++ for (const [fieldName, fieldDef] of Object.entries(mappableFields)) {+ // Match by label (e.g., "Process Type" === "Process Type")+ const labelIdx = fileColumnsLower.indexOf(fieldDef.label.toLowerCase());+ if (labelIdx !== -1) {+ exactMatches[fieldName] = fileColumns[labelIdx];+ continue;+ }+ // Match by field name (e.g., "processType" === "processtype")+ const nameIdx = fileColumnsLower.indexOf(fieldName.toLowerCase());+ if (nameIdx !== -1) {+ exactMatches[fieldName] = fileColumns[nameIdx];+ }+ }++ // If all fields matched exactly, skip the LLM call+ if (+ Object.keys(exactMatches).length === Object.keys(mappableFields).length+ ) {+ initialized.current = true;+ setColumnMappings(exactMatches);+ return;+ }fetcher.submit({@@ -171,93 +199,96 @@ export function FieldMapping({: enumFields[currentStep - 1][1].enumData.description}</ModalDescription></ModalHeader>- <div className="mt-6">- {currentStep === 0 ? (- <div className="grid grid-cols-2 gap-x-4 gap-y-2">- <div className="text-sm">CSV column</div>- <div className="text-sm">Carbon column</div>- {Object.entries(mappableFields).map(- ([name, { label, required, type }]) => (- <FieldRow+ <ModalBody>+ <div className="mt-6">+ {currentStep === 0 ? (+ <div className="grid grid-cols-2 gap-x-4 gap-y-2">+ <div className="text-sm">CSV column</div>+ <div className="text-sm">Carbon column</div>+ {Object.entries(mappableFields).map(+ ([name, { label, required, type }]) => (+ <FieldRow+ key={name}+ label={label}+ type={type}+ required={required}+ name={name}+ mappedColumn={columnMappings[name]}+ isLoading={fetcher.state !== "idle"}+ onColumnMappingChange={onColumnMappingChange}+ />+ )+ )}+ </div>+ ) : (+ <>+ {Object.entries(columnMappings).map(([name, value]) => (+ <input type="hidden" key={name} name={name} value={value} />+ ))}+ <input+ type="hidden"+ name="enumMappings"+ value={JSON.stringify(enumMappings)}+ />+ </>+ )}+ {enumFields.map(+ ([name, { enumData }], index) =>+ currentStep === index + 1 && (+ <EnumMappingStepkey={name}- label={label}- type={type}- required={required}name={name}+ enumData={enumData}mappedColumn={columnMappings[name]}- isLoading={fetcher.state !== "idle"}- onColumnMappingChange={onColumnMappingChange}+ firstRows={firstRows}+ mappings={enumMappings[name]}+ onEnumMappingChange={onEnumMappingChange}/>)- )}- </div>- ) : (- <>- {Object.entries(columnMappings).map(([name, value]) => (- <input type="hidden" key={name} name={name} value={value} />- ))}- <input- type="hidden"- name="enumMappings"- value={JSON.stringify(enumMappings)}- />- </>- )}- {enumFields.map(- ([name, { enumData }], index) =>- currentStep === index + 1 && (- <EnumMappingStep- key={name}- name={name}- enumData={enumData}- mappedColumn={columnMappings[name]}- firstRows={firstRows}- mappings={enumMappings[name]}- onEnumMappingChange={onEnumMappingChange}- />- )- )}- </div>- <div className="flex flex-col w-full gap-2 pb-4">- {currentStep === steps - 1 && (- <Submit- isDisabled={!filePath || fetcher.state !== "idle"}- type="submit"- >- Confirm Import- </Submit>- )}- {currentStep < steps - 1 && (- <Button- variant="secondary"- type="button"- onClick={async () => {- if (currentStep === 0) {- const result = await validate();-- if (!result.error) {+ )}+ </div>++ <div className="flex flex-col w-full gap-2 mt-4">+ {currentStep === steps - 1 && (+ <Submit+ isDisabled={!filePath || fetcher.state !== "idle"}+ type="submit"+ >+ Confirm Import+ </Submit>+ )}+ {currentStep < steps - 1 && (+ <Button+ variant="secondary"+ type="button"+ onClick={async () => {+ if (currentStep === 0) {+ const result = await validate();++ if (!result.error) {+ onNext();+ }+ } else {onNext();}- } else {- onNext();- }- }}- >- Next- </Button>- )}- {currentStep === 0 && (- <Button variant="link" type="button" onClick={onReset}>- Choose another file- </Button>- )}-- {currentStep > 0 && (- <Button variant="link" type="button" onClick={onPrevious}>- Previous- </Button>- )}- </div>+ }}+ >+ Next+ </Button>+ )}+ {currentStep === 0 && (+ <Button variant="link" type="button" onClick={onReset}>+ Choose another file+ </Button>+ )}++ {currentStep > 0 && (+ <Button variant="link" type="button" onClick={onPrevious}>+ Previous+ </Button>+ )}+ </div>+ </ModalBody></>);}diff --git a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsxindex 68ec76fa1a..4424d0f15a 100644--- a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx+++ b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx@@ -135,11 +135,13 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {</ImportCsvContext.Provider></AnimatedSizeContainer></div>- <ModalFooter>- <Button variant="secondary" onClick={downloadTemplate}>- Download Template- </Button>- </ModalFooter>+ {page === ImportCSVPage.UploadCSV && (+ <ModalFooter>+ <Button variant="secondary" onClick={downloadTemplate}>+ Download Template+ </Button>+ </ModalFooter>+ )}</ModalContent></Modal>);diff --git a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsxindex 82bee9a486..f2a61292d3 100644--- a/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx+++ b/apps/erp/app/modules/resources/ui/Processes/ProcessesTable.tsx@@ -299,6 +299,12 @@ const ProcessesTable = memo(({ data, count }: ProcessesTableProps) => {count={count}columns={columns}defaultColumnVisibility={defaultColumnVisibility}+ importCSV={[+ {+ table: "process" as const,+ label: "Processes"+ }+ ]}primaryAction={permissions.can("create", "resources") && (<New label="Process" to={`new?${params.toString()}`} />diff --git a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsxindex f436c4ec99..daba429224 100644--- a/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx+++ b/apps/erp/app/modules/resources/ui/WorkCenters/WorkCentersTable.tsx@@ -309,6 +309,12 @@ const WorkCentersTable = memo(defaultColumnVisibility={defaultColumnVisibility}columns={columns}count={count ?? 0}+ importCSV={[+ {+ table: "workCenter" as const,+ label: "Work Centers"+ }+ ]}primaryAction={permissions.can("update", "resources") && (<New label="Work Center" to={`new?${params.toString()}`} />diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.tsindex 92471a2038..8fa979011b 100644--- a/apps/erp/app/modules/shared/imports.models.ts+++ b/apps/erp/app/modules/shared/imports.models.ts@@ -809,6 +809,135 @@ export const fieldMappings = {default: "EA"}}+ },+ workCenter: {+ id: {+ label: "Unique ID",+ required: true,+ type: "string"+ },+ name: {+ label: "Name",+ required: true,+ type: "string"+ },+ description: {+ label: "Description",+ required: true,+ type: "string"+ },+ defaultStandardFactor: {+ label: "Standard Factor",+ required: false,+ type: "enum",+ enumData: {+ description: "The standard factor unit for time tracking",+ options: [+ "Hours/Piece",+ "Hours/100 Pieces",+ "Hours/1000 Pieces",+ "Minutes/Piece",+ "Minutes/100 Pieces",+ "Minutes/1000 Pieces",+ "Pieces/Hour",+ "Pieces/Minute",+ "Seconds/Piece",+ "Total Hours",+ "Total Minutes"+ ],+ default: "Hours/Piece"+ }+ },+ laborRate: {+ label: "Labor Rate",+ required: true,+ type: "number"+ },+ machineRate: {+ label: "Machine Rate",+ required: true,+ type: "number"+ },+ overheadRate: {+ label: "Overhead Rate",+ required: true,+ type: "number"+ },+ locationId: {+ label: "Location",+ required: true,+ type: "enum",+ enumData: {+ description: "The location of the work center",+ fetcher: async (+ client: SupabaseClient<Database>,+ companyId: string+ ) => {+ return client+ .from("location")+ .select("id, name")+ .eq("companyId", companyId)+ .order("name");+ }+ }+ }+ },+ process: {+ id: {+ label: "Unique ID",+ required: true,+ type: "string"+ },+ name: {+ label: "Name",+ required: true,+ type: "string"+ },+ processType: {+ label: "Process Type",+ required: false,+ type: "enum",+ enumData: {+ description:+ "Whether the process is Inside (in-house), Outside (outsourced), or both",+ options: ["Inside", "Outside", "Inside and Outside"],+ default: "Inside"+ }+ },+ defaultStandardFactor: {+ label: "Standard Factor",+ required: false,+ type: "enum",+ enumData: {+ description:+ "The standard factor unit for time tracking (required for Inside processes)",+ options: [+ "Hours/Piece",+ "Hours/100 Pieces",+ "Hours/1000 Pieces",+ "Minutes/Piece",+ "Minutes/100 Pieces",+ "Minutes/1000 Pieces",+ "Pieces/Hour",+ "Pieces/Minute",+ "Seconds/Piece",+ "Total Hours",+ "Total Minutes"+ ],+ default: "Hours/Piece"+ }+ },+ completeAllOnScan: {+ label: "Complete All On Scan",+ required: false,+ type: "enum",+ enumData: {+ description:+ "Whether scanning a barcode should complete all operations for this process",+ options: ["true", "false"],+ default: "false"+ }+ }}} as const;@@ -822,7 +951,9 @@ export const importPermissions: Record<keyof typeof fieldMappings, string> = {methodMaterial: "parts",tool: "parts",fixture: "parts",- consumable: "parts"+ consumable: "parts",+ workCenter: "production",+ process: "production"};export const importSchemas: Record<@@ -1195,5 +1326,58 @@ export const importSchemas: Record<.string().optional().describe("The unit of measure of the part")+ }),+ workCenter: z.object({+ id: z+ .string()+ .min(1, { message: "ID is required" })+ .describe("The unique ID of the work center"),+ name: z+ .string()+ .min(1, { message: "Name is required" })+ .describe("The name of the work center"),+ description: z+ .string()+ .min(1, { message: "Description is required" })+ .describe("The description of the work center"),+ defaultStandardFactor: z+ .string()+ .optional()+ .describe("The standard factor unit for time tracking"),+ laborRate: z.string().describe("The labor rate for the work center"),+ machineRate: z.string().describe("The machine rate for the work center"),+ overheadRate: z.string().describe("The overhead rate for the work center"),+ locationId: z+ .string()+ .min(1, { message: "Location is required" })+ .describe("The location ID of the work center")+ }),+ process: z.object({+ id: z+ .string()+ .min(1, { message: "ID is required" })+ .describe("The unique ID of the process"),+ name: z+ .string()+ .min(1, { message: "Name is required" })+ .describe("The name of the process"),+ processType: z+ .string()+ .optional()+ .describe(+ "Whether the process is Inside (in-house), Outside (outsourced), or both"+ ),+ defaultStandardFactor: z+ .string()+ .optional()+ .describe(+ "The standard factor unit for time tracking (required for Inside processes)"+ ),+ completeAllOnScan: z+ .string()+ .optional()+ .describe(+ "Whether scanning a barcode should complete all operations for this process"+ )})} as const;diff --git a/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx b/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsxindex 2e197d80ac..90b180efde 100644--- a/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx+++ b/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx@@ -5,7 +5,7 @@ import { generateObject } from "ai";import type { ActionFunctionArgs } from "react-router";import type { ZodSchema } from "zod";import { z } from "zod";-import { importSchemas } from "~/modules/shared";+import { fieldMappings, importSchemas } from "~/modules/shared";const inputSchema = z.object({fileColumns: z.array(z.string())@@ -35,18 +35,31 @@ export async function action({ request, params }: ActionFunctionArgs) {const dbFields = Object.keys(getZodSchemaFieldsShallow(schema));const fileColumnsLower = fileColumns.map((c) => c.toLowerCase().trim());+ const mappings = fieldMappings[table as keyof typeof fieldMappings];- // Deterministic exact match pass+ // Deterministic exact match pass — check both field name and labelconst matched: Record<string, string> = {};const unmatchedFields: string[] = [];for (const field of dbFields) {- const idx = fileColumnsLower.indexOf(field.toLowerCase());- if (idx !== -1) {- matched[field] = fileColumns[idx];- } else {- unmatchedFields.push(field);+ // Match by field name (e.g., "processType" === "processtype")+ const nameIdx = fileColumnsLower.indexOf(field.toLowerCase());+ if (nameIdx !== -1) {+ matched[field] = fileColumns[nameIdx];+ continue;}+ // Match by label (e.g., "Process Type" === "process type")+ const label = (mappings as Record<string, { label: string }>)?.[+ field as keyof typeof mappings+ ]?.label;+ if (label) {+ const labelIdx = fileColumnsLower.indexOf(label.toLowerCase());+ if (labelIdx !== -1) {+ matched[field] = fileColumns[labelIdx];+ continue;+ }+ }+ unmatchedFields.push(field);}// If all fields matched, skip AI entirelydiff --git a/llm/cache/csv-import-system.md b/llm/cache/csv-import-system.mdnew file mode 100644index 0000000000..3ec20797be--- /dev/null+++ b/llm/cache/csv-import-system.md@@ -0,0 +1,283 @@+# CSV Import System++## Overview++The Carbon system includes a comprehensive CSV import system that allows users to bulk import data for various entities including customers, suppliers, parts, materials, work centers, and processes. The import system is designed to be idempotent and supports enum mappings for dropdown fields.++## Architecture++### Frontend Components++- **Location**: `/apps/erp/app/components/ImportCSVModal/`+- **Main Component**: `ImportCSVModal.tsx` - Modal interface for CSV imports+- **Sub-components**:+ - `UploadCSV.tsx` - Handles CSV file upload to private storage+ - `FieldMappings.tsx` - UI for mapping CSV columns to database fields+ - `useCsvContext.tsx` - Context management for import state++### Backend Route++- **Location**: `/apps/erp/app/routes/x+/shared+/import.$tableId.tsx`+- **Method**: Validates permissions and form data+- **Flow**:+ 1. Checks user permissions for the table being imported+ 2. Validates form data using Zod schemas+ 3. Extracts column mappings and enum mappings+ 4. Calls Supabase edge function++### Supabase Edge Function++- **Location**: `/packages/database/supabase/functions/import-csv/index.ts`+- **Runtime**: Deno+- **Responsibilities**:+ 1. Downloads CSV file from private storage+ 2. Parses CSV using Deno std library+ 3. Maps CSV columns to database fields+ 4. Handles enum value mappings+ 5. Performs upsert operations with idempotent behavior+ 6. Stores external ID mappings for re-imports++## Field Mappings++Field mappings are defined in `/apps/erp/app/modules/shared/imports.models.ts` and include:++### Field Mapping Structure++```typescript+{+ label: string; // User-friendly field name+ required: boolean; // Whether field is mandatory+ type: string; // "string" | "number" | "boolean" | "enum"+ enumData?: { // For enum fields+ description: string; // Explanation of the field+ options?: string[]; // Static enum options+ fetcher?: Function; // Database fetcher for dynamic options+ default?: string; // Default value+ };+ default?: string; // Optional default value+}+```++## Supported Import Tables++### Core Tables with Field Mappings++1. **customer** - Permission: `sales`++ - Fields: id, name, accountManagerId, fax, taxId, currencyCode, website++2. **customerContact** - Permission: `sales`++ - Fields: id, companyId, firstName, lastName, email, title, mobilePhone, workPhone, homePhone, fax, notes++3. **supplier** - Permission: `purchasing`++ - Fields: id, name, accountManagerId, phone, fax, taxId, currencyCode, website++4. **supplierContact** - Permission: `purchasing`++ - Fields: id, companyId, firstName, lastName, email, title, mobilePhone, workPhone, homePhone, fax, notes++5. **part** - Permission: `parts`++ - Fields: id, readableId, revision, name, description, active, replenishmentSystem, defaultMethodType, itemTrackingType, unitOfMeasureCode++6. **material** - Permission: `parts`++ - Fields: Same as part, plus: materialSubstanceId, materialFormId, finish, grade, dimensions++7. **tool** - Permission: `parts`++ - Fields: Same as part++8. **fixture** - Permission: `parts`++ - Fields: Same as part++9. **consumable** - Permission: `parts`++ - Fields: Same as part++10. **methodMaterial** - Permission: `parts`+ - Fields: level, partId, description, methodType, quantity, unitOfMeasureCode+ - Status: Not yet implemented++### NEW: Production Tables++11. **workCenter** - Permission: `production`++ - Required Fields: id, name, description, defaultStandardFactor, laborRate, machineRate, overheadRate, locationId+ - Description: Bulk import work centers with cost rates and location assignment++12. **process** - Permission: `production`+ - Required Fields: id, name, processType+ - Optional Fields: defaultStandardFactor (required for Inside processes), completeAllOnScan+ - Description: Bulk import processes (Inside/Outside) with default standards++## Import Process Flow++### Frontend Flow++1. User opens ImportCSVModal+2. Uploads CSV file to `/private` storage (via browser)+3. Selects field mappings (which CSV columns map to which database fields)+4. Configures enum mappings for dropdown fields (e.g., "Buy" → "Make")+5. Submits form to `/import/$tableId` route++### Backend Flow++1. **Route Handler** (`import.$tableId.tsx`):++ - Verifies user has permission to import the table+ - Validates input data using Zod schema+ - Extracts column mappings and enum mappings+ - Calls Supabase edge function++2. **Edge Function** (`import-csv/index.ts`):+ - Downloads CSV from private storage+ - Parses CSV into records+ - Maps CSV columns to field names using columnMappings+ - Applies enum mappings for enum fields+ - Validates records+ - Handles insert/update logic:+ - **Insert**: Creates new records with external ID mapping+ - **Update**: Updates existing records found via external ID mapping+ - Performs database transaction with rollback on error++### Idempotent Imports++- Uses `externalIntegrationMapping` table to track CSV imports+- Format: `integration: "csv"`, `externalId: <CSV_ID>`+- Allows re-importing same CSV without duplicates+- Updates existing records if CSV ID already exists++## Zod Validators++All import tables have Zod validators in `importSchemas` for client-side validation:++- Ensures required fields are present+- Validates field types+- Provides user-friendly error messages++## Permissions++Import permissions are defined in `importPermissions`:++```typescript+{+ customer: "sales",+ customerContact: "sales",+ supplier: "purchasing",+ supplierContact: "purchasing",+ part: "parts",+ material: "parts",+ tool: "parts",+ fixture: "parts",+ consumable: "parts",+ methodMaterial: "parts",+ workCenter: "production", // NEW+ process: "production" // NEW+}+```++## Key Features++1. **Column Mapping**: Flexible assignment of CSV columns to database fields+2. **Enum Mapping**: Custom value mappings for dropdown fields (e.g., "B" → "Buy")+3. **Default Values**: Auto-populate fields from predefined defaults+4. **Validation**: Both client and server-side validation with schema enforcemen t+5. **Idempotent Imports**: Re-import same data without creating duplicates+6. **Transaction Safety**: All or nothing behavior for database operations+7. **Error Handling**: Graceful error reporting with detailed messages++## Example: Importing Work Centers++### CSV Format++```+id,name,description,defaultStandardFactor,laborRate,machineRate,overheadRate,locationId+WC001,Lathe A,Primary lathe machine,Hours,50.00,75.00,25.00,LOC-A+WC002,Mill B,CNC milling machine,Minutes,55.00,80.00,30.00,LOC-A+```++### Field Mapping (User Selection)++- CSV Column "id" → Database Field "id"+- CSV Column "name" → Database Field "name"+- CSV Column "description" → Database Field "description"+- CSV Column "defaultStandardFactor" → Database Field "defaultStandardFactor"+- CSV Column "laborRate" → Database Field "laborRate"+- CSV Column "machineRate" → Database Field "machineRate"+- CSV Column "overheadRate" → Database Field "overheadRate"+- CSV Column "locationId" → Database Field "locationId"++### Edge Function Processing++1. Parses CSV rows+2. Maps columns: "WC001" → id, "Lathe A" → name, etc.+3. Converts numeric fields: "50.00" → 50+4. Creates workCenter records with proper types+5. Stores external ID mapping: "WC001" → internal UUID++## Example: Importing Processes++### CSV Format++```+id,name,processType,defaultStandardFactor,completeAllOnScan+PROC-001,Drilling,Inside,Hours,false+PROC-002,Assembly,Inside,Hours,true+PROC-003,Plating,Outside,,false+```++### Field Mapping (User Selection)++- CSV Column "id" → Database Field "id"+- CSV Column "name" → Database Field "name"+- CSV Column "processType" → Database Field "processType"+- CSV Column "defaultStandardFactor" → Database Field "defaultStandardFactor"+- CSV Column "completeAllOnScan" → Database Field "completeAllOnScan"++### Edge Function Processing++1. Parses CSV rows+2. Maps columns: "PROC-001" → id, "Drilling" → name, etc.+3. Validates processType is "Inside" or "Outside"+4. Converts boolean: "true" → true, "false" → false+5. Creates process records+6. Stores external ID mapping: "PROC-001" → internal UUID++## Location References++### Models & Validation++- `/apps/erp/app/modules/shared/imports.models.ts` - Field mappings and Zod schemas+- `/apps/erp/app/modules/resources/resources.models.ts` - Work center validator+- `/apps/erp/app/modules/production/production.models.ts` - Process validator++### Routes & Controllers++- `/apps/erp/app/routes/x+/shared+/import.$tableId.tsx` - Import route handler++### Frontend Components++- `/apps/erp/app/components/ImportCSVModal/` - Import UI components++### Backend Processing++- `/packages/database/supabase/functions/import-csv/index.ts` - Edge function++## Limitations & Future Work++1. **methodMaterial**: Not yet implemented+2. **Process-WorkCenter Association**: Currently manual association after import+3. **Bulk Updates**: No bulk update from existing records+4. **Error Reporting**: Limited line-by-line error reporting for malformed rows+5. **Preview**: No CSV preview before import confirmation++## Related Systems++- **Authentication**: Uses Carbon auth for permission checks+- **Database**: Uses Supabase/PostgreSQL for storage+- **File Storage**: Uses Supabase private storage for CSV files+- **Form Validation**: Uses Zod for schema validationdiff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.tsindex 445f33ba4c..a04adbe2a2 100644--- a/packages/database/supabase/functions/import-csv/index.ts+++ b/packages/database/supabase/functions/import-csv/index.ts@@ -24,6 +24,8 @@ const importCsvValidator = z.object({"supplier","supplierContact","tool",+ "workCenter",+ "process",]),filePath: z.string(),columnMappings: z.record(z.string()),@@ -51,7 +53,9 @@ async function getCsvExternalIdMap(return new Map(result- .filter((r): r is typeof r & { externalId: string } => r.externalId !== null)+ .filter(+ (r): r is typeof r & { externalId: string } => r.externalId !== null+ ).map((r) => [r.externalId, r.entityId]));}@@ -642,8 +646,14 @@ serve(async (req: Request) => {break;}case "customerContact": {- const externalContactIdMap = await getCsvExternalIdMap("contact", companyId);- const externalCustomerIdMap = await getCsvExternalIdMap("customer", companyId);+ const externalContactIdMap = await getCsvExternalIdMap(+ "contact",+ companyId+ );+ const externalCustomerIdMap = await getCsvExternalIdMap(+ "customer",+ companyId+ );await db.transaction().execute(async (trx) => {const contactInserts: Database["public"]["Tables"]["contact"]["Insert"][] =@@ -747,8 +757,14 @@ serve(async (req: Request) => {break;}case "supplierContact": {- const externalContactIdMap = await getCsvExternalIdMap("contact", companyId);- const externalSupplierIdMap = await getCsvExternalIdMap("supplier", companyId);+ const externalContactIdMap = await getCsvExternalIdMap(+ "contact",+ companyId+ );+ const externalSupplierIdMap = await getCsvExternalIdMap(+ "supplier",+ companyId+ );await db.transaction().execute(async (trx) => {const contactInserts: Database["public"]["Tables"]["contact"]["Insert"][] =@@ -850,6 +866,200 @@ serve(async (req: Request) => {break;}+ case "workCenter": {+ const externalIdMap = await getCsvExternalIdMap(+ "workCenter",+ companyId+ );+ const workCenterIds = new Set();++ await db.transaction().execute(async (trx) => {+ const workCenterInserts: Database["public"]["Tables"]["workCenter"]["Insert"][] =+ [];+ const csvIdsForInserts: string[] = [];+ const workCenterUpdates: {+ id: string;+ data: Database["public"]["Tables"]["workCenter"]["Update"];+ }[] = [];++ const isWorkCenterValid = (+ record: Record<string, string>+ ): record is { name: string; locationId: string } => {+ return (+ typeof record.name === "string" &&+ record.name.trim() !== "" &&+ typeof record.locationId === "string" &&+ record.locationId.trim() !== ""+ );+ };++ for (const record of mappedRecords) {+ const { id, ...rest } = record;+ if (externalIdMap.has(id)) {+ const existingEntityId = externalIdMap.get(id)!;+ if (isWorkCenterValid(rest) && !workCenterIds.has(id)) {+ workCenterIds.add(id);+ workCenterUpdates.push({+ id: existingEntityId,+ data: {+ ...rest,+ laborRate: rest.laborRate ? parseFloat(rest.laborRate) : 0,+ machineRate: rest.machineRate+ ? parseFloat(rest.machineRate)+ : 0,+ overheadRate: rest.overheadRate+ ? parseFloat(rest.overheadRate)+ : 0,+ updatedAt: new Date().toISOString(),+ updatedBy: userId,+ },+ });+ }+ } else if (isWorkCenterValid(rest) && !workCenterIds.has(id)) {+ workCenterIds.add(id);+ workCenterInserts.push({+ ...rest,+ laborRate: rest.laborRate ? parseFloat(rest.laborRate) : 0,+ machineRate: rest.machineRate+ ? parseFloat(rest.machineRate)+ : 0,+ overheadRate: rest.overheadRate+ ? parseFloat(rest.overheadRate)+ : 0,+ companyId,+ createdAt: new Date().toISOString(),+ createdBy: userId,+ } as never);+ csvIdsForInserts.push(id);+ }+ }++ console.log({+ totalRecords: mappedRecords.length,+ workCenterInserts: workCenterInserts.length,+ workCenterUpdates: workCenterUpdates.length,+ });++ if (workCenterInserts.length > 0) {+ const inserted = await trx+ .insertInto("workCenter")+ .values(workCenterInserts)+ .returning(["id"])+ .execute();+ await upsertCsvMappings(+ trx,+ "workCenter",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForInserts[i],+ })),+ companyId,+ userId+ );+ }+ if (workCenterUpdates.length > 0) {+ for (const update of workCenterUpdates) {+ await trx+ .updateTable("workCenter")+ .set(update.data)+ .where("id", "=", update.id)+ .execute();+ }+ }+ });+ break;+ }+ case "process": {+ const externalIdMap = await getCsvExternalIdMap("process", companyId);+ const processIds = new Set();++ await db.transaction().execute(async (trx) => {+ const processInserts: Database["public"]["Tables"]["process"]["Insert"][] =+ [];+ const csvIdsForInserts: string[] = [];+ const processUpdates: {+ id: string;+ data: Database["public"]["Tables"]["process"]["Update"];+ }[] = [];++ const isProcessValid = (+ record: Record<string, string>+ ): record is { name: string; processType: string } => {+ return (+ typeof record.name === "string" &&+ record.name.trim() !== "" &&+ typeof record.processType === "string" &&+ (record.processType === "Inside" ||+ record.processType === "Outside")+ );+ };++ for (const record of mappedRecords) {+ const { id, ...rest } = record;+ if (externalIdMap.has(id)) {+ const existingEntityId = externalIdMap.get(id)!;+ if (isProcessValid(rest) && !processIds.has(id)) {+ processIds.add(id);+ processUpdates.push({+ id: existingEntityId,+ data: {+ ...rest,+ completeAllOnScan:+ rest.completeAllOnScan?.toLowerCase() === "true" ?? false,+ updatedAt: new Date().toISOString(),+ updatedBy: userId,+ },+ });+ }+ } else if (isProcessValid(rest) && !processIds.has(id)) {+ processIds.add(id);+ processInserts.push({+ ...rest,+ completeAllOnScan:+ rest.completeAllOnScan?.toLowerCase() === "true" ?? false,+ companyId,+ createdAt: new Date().toISOString(),+ createdBy: userId,+ } as never);+ csvIdsForInserts.push(id);+ }+ }++ console.log({+ totalRecords: mappedRecords.length,+ processInserts: processInserts.length,+ processUpdates: processUpdates.length,+ });++ if (processInserts.length > 0) {+ const inserted = await trx+ .insertInto("process")+ .values(processInserts)+ .returning(["id"])+ .execute();+ await upsertCsvMappings(+ trx,+ "process",+ inserted.map((row, i) => ({+ entityId: row.id!,+ externalId: csvIdsForInserts[i],+ })),+ companyId,+ userId+ );+ }+ if (processUpdates.length > 0) {+ for (const update of processUpdates) {+ await trx+ .updateTable("process")+ .set(update.data)+ .where("id", "=", update.id)+ .execute();+ }+ }+ });+ break;+ }case "methodMaterial": {throw new Error("Not implemented");}