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
fix(import): resolve material Finish, Grade, and Dimensions on CSV import (#1267)
Siddharth Gaikwad217d5da898bc
diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.mdindex 1b6f960adc..41137ab52e 100644--- a/.claude/rules/csv-import-system.md+++ b/.claude/rules/csv-import-system.md@@ -100,6 +100,14 @@ Deno `serve` handler. Payload validated by `importCsvValidator` (table enum, `fiwhen the strict parser rejects uneven row widths.- Applies `columnMappings`, then `enumMappings` (unknown CSV value → the enum's `"Default"`);`"N/A"` / unmapped columns are skipped.+- **Material Finish / Grade / Dimensions arrive as raw text** (`finish`, `grade`,+ `dimensions` — they can't be flat enum mappings because `materialFinish`/`materialGrade`+ are scoped by substance and `materialDimension` by form). `resolveMaterialTaxonomyIds()`+ resolves them per row within the row's substance/form scope — case-insensitive match+ against global (`companyId IS NULL`) + company rows (company wins) — and **creates a+ company-scoped taxonomy row for unmatched names** (mirroring the creatable comboboxes on+ the material form). A row with no substance (finish/grade) or no form (dimensions) leaves+ the attribute unset.- Classifies each row with `classifyImportRow()` (see `classify-import-row.ts`):returns `{ action: "insert" }`, `{ action: "update"; entityId }`, or`{ action: "skip"; reason }`. Skips on missing Name or duplicate id/name within the file.diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.tsindex 4944abdfa2..407799f4a1 100644--- a/packages/database/supabase/functions/import-csv/index.ts+++ b/packages/database/supabase/functions/import-csv/index.ts@@ -298,6 +298,108 @@ async function upsertCsvMappings(.execute();}+/**+ * Key for a scoped material-taxonomy lookup: the parent scope id (substance+ * for finish/grade, form for dimensions) plus the case-insensitively+ * normalized name.+ */+function materialTaxonomyKey(scopeId: string, name: string): string {+ return `${scopeId.trim()}:${name.trim().toLowerCase()}`;+}++/**+ * Resolve raw Finish / Grade / Dimensions CSV text to material-taxonomy ids.+ * The taxonomy tables are scoped — materialFinish/materialGrade by substance,+ * materialDimension by form — so names are matched within the row's scope+ * against both global (companyId IS NULL) and company rows; a company row wins+ * a name clash. Unmatched names create a company-scoped row, mirroring the+ * creatable comboboxes on the material form. Returns ids keyed by+ * materialTaxonomyKey.+ */+async function resolveMaterialTaxonomyIds(+ trx: typeof db,+ taxonomyTable: "materialFinish" | "materialGrade" | "materialDimension",+ scopeColumn: "materialSubstanceId" | "materialFormId",+ pairs: Array<{ scopeId: string; name: string }>,+ cId: string+): Promise<Map<string, string>> {+ const needed = new Map<string, { scopeId: string; name: string }>();+ for (const pair of pairs) {+ const scopeId = pair.scopeId?.trim();+ const name = pair.name?.trim();+ if (!scopeId || !name) continue;+ const key = materialTaxonomyKey(scopeId, name);+ if (!needed.has(key)) {+ needed.set(key, { scopeId, name });+ }+ }++ const idByKey = new Map<string, string>();+ if (needed.size === 0) return idByKey;++ const scopeIds = [...new Set([...needed.values()].map((p) => p.scopeId))];++ const selectMatches = async () => {+ const rows = await trx+ .selectFrom(taxonomyTable)+ .select(["id", "name", "companyId", scopeColumn] as never)+ .where(trx.dynamic.ref<string>(scopeColumn), "in", scopeIds)+ .where(sql<boolean>`("companyId" = ${cId} OR "companyId" IS NULL)`)+ .$castTo<Record<string, string | null>>()+ .execute();+ return rows.map((row) => ({+ id: row.id as string,+ name: row.name as string,+ companyId: row.companyId ?? null,+ scopeId: row[scopeColumn] as string,+ }));+ };++ const collect = (rows: Awaited<ReturnType<typeof selectMatches>>) => {+ for (const row of rows) {+ const key = materialTaxonomyKey(row.scopeId, row.name);+ // Company-scoped rows win over global (NULL companyId) rows.+ if (!idByKey.has(key) || row.companyId === cId) {+ idByKey.set(key, row.id);+ }+ }+ };++ collect(await selectMatches());++ const missing = [...needed.values()].filter(+ (pair) => !idByKey.has(materialTaxonomyKey(pair.scopeId, pair.name))+ );++ if (missing.length > 0) {+ await trx+ .insertInto(taxonomyTable)+ .values(+ missing.map((pair) => ({+ name: pair.name,+ companyId: cId,+ [scopeColumn]: pair.scopeId,+ })) as never+ )+ // A concurrent import may have created the same name first; the+ // re-select below picks up whichever row won. The unique constraint is+ // exact-match, so two concurrent imports inserting different CASINGS of+ // the same new name can both land, leaving a case-variant duplicate —+ // the same duplicate the app's creatable comboboxes permit. Closing+ // that window needs a case-insensitive unique index on+ // (scope, lower(name), companyId), which requires a migration plus a+ // dedupe of existing case-variant rows.+ .onConflict((oc) =>+ oc.columns([scopeColumn, "name", "companyId"] as never).doNothing()+ )+ .execute();++ collect(await selectMatches());+ }++ return idByKey;+}+/*** Address/payment/shipping fields that can ride along on a supplier or* customer CSV row. Written to side-tables (address + supplierLocation /@@ -1407,8 +1509,99 @@ serve(async (req: Request) => {finishId: z.string().optional(),dimensionId: z.string().optional(),gradeId: z.string().optional(),+ // Raw text from the mapping UI; resolved to the *Id columns below.+ finish: z.string().optional(),+ grade: z.string().optional(),+ dimensions: z.string().optional(),});+ // The mapping UI sends Finish / Grade / Dimensions as raw CSV text —+ // materialFinish/materialGrade are scoped by substance and+ // materialDimension by form, so a flat enum mapping can't target+ // them. Resolve the text to taxonomy ids up front (creating+ // company-scoped rows for unmatched names). Rows without a resolved+ // substance/form keep the attribute unset, since the taxonomy+ // tables require the scope.+ let finishIdByKey = new Map<string, string>();+ let gradeIdByKey = new Map<string, string>();+ let dimensionIdByKey = new Map<string, string>();++ if (table === "material") {+ const finishPairs: Array<{ scopeId: string; name: string }> = [];+ const gradePairs: Array<{ scopeId: string; name: string }> = [];+ const dimensionPairs: Array<{ scopeId: string; name: string }> =+ [];++ for (const record of mappedRecords) {+ const substanceId = record.materialSubstanceId;+ const formId = record.materialFormId;+ // An explicit *Id (possible via direct invocation) wins over the+ // raw text, so don't resolve — and possibly create — a taxonomy+ // row that nothing would reference.+ if (substanceId && record.finish && !record.finishId) {+ finishPairs.push({ scopeId: substanceId, name: record.finish });+ }+ if (substanceId && record.grade && !record.gradeId) {+ gradePairs.push({ scopeId: substanceId, name: record.grade });+ }+ if (formId && record.dimensions && !record.dimensionId) {+ dimensionPairs.push({ scopeId: formId, name: record.dimensions });+ }+ }++ finishIdByKey = await resolveMaterialTaxonomyIds(+ trx,+ "materialFinish",+ "materialSubstanceId",+ finishPairs,+ companyId+ );+ gradeIdByKey = await resolveMaterialTaxonomyIds(+ trx,+ "materialGrade",+ "materialSubstanceId",+ gradePairs,+ companyId+ );+ dimensionIdByKey = await resolveMaterialTaxonomyIds(+ trx,+ "materialDimension",+ "materialFormId",+ dimensionPairs,+ companyId+ );+ }++ const resolveFinishId = (data: {+ materialSubstanceId?: string;+ finish?: string;+ }) =>+ data.materialSubstanceId && data.finish+ ? finishIdByKey.get(+ materialTaxonomyKey(data.materialSubstanceId, data.finish)+ )+ : undefined;++ const resolveGradeId = (data: {+ materialSubstanceId?: string;+ grade?: string;+ }) =>+ data.materialSubstanceId && data.grade+ ? gradeIdByKey.get(+ materialTaxonomyKey(data.materialSubstanceId, data.grade)+ )+ : undefined;++ const resolveDimensionId = (data: {+ materialFormId?: string;+ dimensions?: string;+ }) =>+ data.materialFormId && data.dimensions+ ? dimensionIdByKey.get(+ materialTaxonomyKey(data.materialFormId, data.dimensions)+ )+ : undefined;+// Rows on the INSERT path whose Unique ID already exists in this// company's catalog (e.g. a re-import after the item was deleted,// which frees the Unique ID to collide on the un-onConflict'd@@ -1532,9 +1725,18 @@ serve(async (req: Request) => {materialSubstanceId:material.data.materialSubstanceId || undefined,materialFormId: material.data.materialFormId || undefined,- dimensionId: material.data.dimensionId || undefined,- gradeId: material.data.gradeId || undefined,- finishId: material.data.finishId || undefined,+ dimensionId:+ material.data.dimensionId ||+ resolveDimensionId(material.data) ||+ undefined,+ gradeId:+ material.data.gradeId ||+ resolveGradeId(material.data) ||+ undefined,+ finishId:+ material.data.finishId ||+ resolveFinishId(material.data) ||+ undefined,companyId,updatedAt: new Date().toISOString(),updatedBy: userId,@@ -1603,6 +1805,13 @@ serve(async (req: Request) => {materialPartialInserts[material.data.readableId!] = {...material.data,id: material.data.readableId,+ dimensionId:+ material.data.dimensionId ||+ resolveDimensionId(material.data),+ gradeId:+ material.data.gradeId || resolveGradeId(material.data),+ finishId:+ material.data.finishId || resolveFinishId(material.data),companyId,createdAt: new Date().toISOString(),createdBy: userId,@@ -1799,6 +2008,7 @@ serve(async (req: Request) => {.updateTable("material").set(update.data).where("id", "=", update.id)+ .where("companyId", "=", companyId).execute();}}