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: add downloadable template to csv import

Brad Barbin032115b44ec3
diff --git a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
index 72ea39b3cc..68ec76fa1a 100644
--- a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
+++ b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
@@ -1,11 +1,12 @@
import { Hidden, ValidatedForm } from "@carbon/form";
-import { Modal, ModalContent, toast } from "@carbon/react";
-import { useEffect, useState } from "react";
+import { Button, Modal, ModalContent, ModalFooter, toast } from "@carbon/react";
+import Papa from "papaparse";
+import { useCallback, useEffect, useState } from "react";
import { flushSync } from "react-dom";
import { useFetcher } from "react-router";
import { z } from "zod";
-import type { fieldMappings } from "~/modules/shared/imports.models";
-import { importSchemas } from "~/modules/shared/imports.models";
+
+import { fieldMappings, importSchemas } from "~/modules/shared";
import type { action } from "~/routes/x+/shared+/import.$tableId";
import { path } from "~/utils/path";
import { AnimatedSizeContainer } from "../AnimatedSizeContainer";
@@ -57,6 +58,19 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
}
}, [file, fileColumns, page]);
+ const downloadTemplate = useCallback(() => {
+ const mapping = fieldMappings[table];
+ const headers = Object.values(mapping).map((field) => field.label);
+ const csv = Papa.unparse({ fields: headers, data: [] });
+ const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });
+ const url = URL.createObjectURL(blob);
+ const link = document.createElement("a");
+ link.href = url;
+ link.download = `${table}-template.csv`;
+ link.click();
+ URL.revokeObjectURL(url);
+ }, [table]);
+
return (
<Modal
open
@@ -67,62 +81,65 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
}}
>
<ModalContent>
- <div className="p-4">
- <div className="relative">
- <AnimatedSizeContainer height>
- <ImportCsvContext.Provider
- value={{
- file,
- fileColumns,
- firstRows,
- filePath,
- setFile,
- setFileColumns,
- setFirstRows,
- setFilePath
- }}
- >
- <div>
- <ValidatedForm
- className="flex flex-col gap-y-4"
- fetcher={fetcher}
- method="post"
- action={path.to.import(table)}
- validator={importSchemas[table].extend({
- filePath: z
- .string()
- .min(1, { message: "Path is required" }),
- enumMappings: z.string().optional()
- })}
- id={formId}
- onSubmit={() => {
- toast.info("Importing...");
- }}
- >
- <Hidden name="filePath" value={filePath ?? ""} />
- {page === ImportCSVPage.UploadCSV && (
- <UploadCSV table={table} />
- )}
- {page === ImportCSVPage.FieldMappings && (
- <FieldMapping
- formId={formId}
- table={table}
- onReset={() => {
- flushSync(() => {
- setFile(null);
- setFileColumns(null);
- setFirstRows(null);
- });
- setPage(ImportCSVPage.UploadCSV);
- }}
- />
- )}
- </ValidatedForm>
- </div>
- </ImportCsvContext.Provider>
- </AnimatedSizeContainer>
- </div>
+ <div className="relative">
+ <AnimatedSizeContainer height>
+ <ImportCsvContext.Provider
+ value={{
+ file,
+ fileColumns,
+ firstRows,
+ filePath,
+ setFile,
+ setFileColumns,
+ setFirstRows,
+ setFilePath
+ }}
+ >
+ <div>
+ <ValidatedForm
+ className="flex flex-col gap-y-4"
+ fetcher={fetcher}
+ method="post"
+ action={path.to.import(table)}
+ validator={importSchemas[table].extend({
+ filePath: z
+ .string()
+ .min(1, { message: "Path is required" }),
+ enumMappings: z.string().optional()
+ })}
+ id={formId}
+ onSubmit={() => {
+ toast.info("Importing...");
+ }}
+ >
+ <Hidden name="filePath" value={filePath ?? ""} />
+ {page === ImportCSVPage.UploadCSV && (
+ <UploadCSV table={table} />
+ )}
+ {page === ImportCSVPage.FieldMappings && (
+ <FieldMapping
+ formId={formId}
+ table={table}
+ onReset={() => {
+ flushSync(() => {
+ setFile(null);
+ setFileColumns(null);
+ setFirstRows(null);
+ });
+ setPage(ImportCSVPage.UploadCSV);
+ }}
+ />
+ )}
+ </ValidatedForm>
+ </div>
+ </ImportCsvContext.Provider>
+ </AnimatedSizeContainer>
</div>
+ <ModalFooter>
+ <Button variant="secondary" onClick={downloadTemplate}>
+ Download Template
+ </Button>
+ </ModalFooter>
</ModalContent>
</Modal>
);
diff --git a/apps/erp/app/components/ImportCSVModal/UploadCSV.tsx b/apps/erp/app/components/ImportCSVModal/UploadCSV.tsx
index 6820c5d79e..27cdafc404 100644
--- a/apps/erp/app/components/ImportCSVModal/UploadCSV.tsx
+++ b/apps/erp/app/components/ImportCSVModal/UploadCSV.tsx
@@ -1,6 +1,7 @@
import { useCarbon } from "@carbon/auth";
import {
cn,
+ ModalBody,
ModalDescription,
ModalHeader,
ModalTitle,
@@ -132,43 +133,44 @@ export const UploadCSV = ({ table }: { table: keyof typeof importSchemas }) => {
return (
<>
<ModalHeader>
- <div className="flex space-x-4 items-center mb-4">
- <ModalTitle className="m-0 p-0">Upload CSV</ModalTitle>
- </div>
+ <ModalTitle>Upload CSV</ModalTitle>
+
<ModalDescription>
Please upload a CSV file of your data
</ModalDescription>
</ModalHeader>
- <div
- {...getRootProps()}
- className={cn(
- "w-full border-2 border-dashed h-[200px] rounded-md mt-8 mb-8 flex items-center justify-center text-muted-foreground hover:border-primary hover:text-foreground cursor-pointer focus-visible:border-primary focus-visible:text-foreground hover:bg-primary/5 focus-visible:outline-none",
- isDragActive
- ? "border-primary text-foreground bg-primary/5"
- : "border-muted",
- isDragReject && "border-destructive"
- )}
- >
- <div className="text-center flex items-center justify-center flex-col text-xs">
- <input {...getInputProps()} />
-
- {loading ? (
- <div className="flex space-x-1 items-center">
- <Spinner />
- <span>Loading...</span>
- </div>
- ) : (
- <div>
- <p>Drop your file here, or click to browse.</p>
- <span>5MB file limit</span>
- </div>
- )}
-
- {error && (
- <p className="text-center text-sm text-red-600 mt-4">{error}</p>
+ <ModalBody>
+ <div
+ {...getRootProps()}
+ className={cn(
+ "w-full border-2 border-dashed h-[200px] rounded-md mt-8 mb-8 flex items-center justify-center text-muted-foreground hover:border-primary hover:text-foreground cursor-pointer focus-visible:border-primary focus-visible:text-foreground hover:bg-primary/5 focus-visible:outline-none",
+ isDragActive
+ ? "border-primary text-foreground bg-primary/5"
+ : "border-muted",
+ isDragReject && "border-destructive"
)}
+ >
+ <div className="text-center flex items-center justify-center flex-col text-xs">
+ <input {...getInputProps()} />
+
+ {loading ? (
+ <div className="flex space-x-1 items-center">
+ <Spinner />
+ <span>Loading...</span>
+ </div>
+ ) : (
+ <div>
+ <p>Drop your file here, or click to browse.</p>
+ <span>5MB file limit</span>
+ </div>
+ )}
+
+ {error && (
+ <p className="text-center text-sm text-red-600 mt-4">{error}</p>
+ )}
+ </div>
</div>
- </div>
+ </ModalBody>
</>
);
};
diff --git a/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx b/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx
index df93474ca5..2e197d80ac 100644
--- a/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx
+++ b/apps/erp/app/routes/api+/ai+/csv+/$table.columns.tsx
@@ -33,28 +33,59 @@ export async function action({ request, params }: ActionFunctionArgs) {
throw notFound("Table not found in the list of supported tables");
}
+ const dbFields = Object.keys(getZodSchemaFieldsShallow(schema));
+ const fileColumnsLower = fileColumns.map((c) => c.toLowerCase().trim());
+
+ // Deterministic exact match pass
+ const 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);
+ }
+ }
+
+ // If all fields matched, skip AI entirely
+ if (unmatchedFields.length === 0) {
+ return matched;
+ }
+
+ // Use AI only for unmatched fields
+ const unmatchedSchema = schema.pick(
+ Object.fromEntries(unmatchedFields.map((f) => [f, true])) as Record<
+ string,
+ true
+ >
+ );
+
+ const unmatchedFileColumns = fileColumns.filter(
+ (c) => !Object.values(matched).includes(c)
+ );
+
try {
const { object } = await generateObject({
model: openai("gpt-4o"),
- schema,
+ schema: unmatchedSchema,
prompt: `
- The following columns are the headings from a CSV import file for importing a ${table}.
- Map these column names to the correct fields in our database (${[
- ...Object.keys(getZodSchemaFieldsShallow(schema))
- ].join(", ")}) by providing the matching column name for each field.
-
- If you are not sure or there is no matching column, please return "N/A".
-
+ The following columns are the headings from a CSV import file for importing a ${table}.
+ Map these column names to the correct fields in our database (${unmatchedFields.join(", ")}) by providing the matching column name for each field.
+
+ If you are not sure or there is no matching column, please return "N/A".
+
Columns:
- ${fileColumns.join(",")}
+ ${unmatchedFileColumns.join(",")}
`,
temperature: 0.2
});
- return object;
+ return { ...matched, ...object };
} catch (error) {
console.error(error);
- return {} as Record<string, string>;
+ return matched;
}
}