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(items): CSV bulk import for material properties

sidgaikwad844969a1e7c3
diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.md
index 1b6f960adc..9d9ddee5af 100644
--- a/.claude/rules/csv-import-system.md
+++ b/.claude/rules/csv-import-system.md
@@ -62,13 +62,33 @@ Other exports: `creatableLookups`, and types `CreatableLookup`, `CreatableForm`.
`customer`, `customerContact` → `sales`; `supplier`, `supplierContact` → `purchasing`;
`part`, `material`, `tool`, `fixture`, `consumable`, `methodMaterial`, `bom`,
-`operations`, `partWithMethod` → `parts`; `workCenter`, `process` → `production`;
-`fixedAsset` → `accounting`.
+`operations`, `partWithMethod`, `materialSubstance`, `materialForm`, `materialFinish`,
+`materialGrade`, `materialType`, `materialDimension` → `parts`;
+`workCenter`, `process` → `production`; `fixedAsset` → `accounting`.
The edge function's own `table` enum (`import-csv/index.ts`) accepts: `consumable`,
`customer`, `customerContact`, `fixture`, `material`, `bom`, `operations`,
`partWithMethod`, `part`, `supplier`, `supplierContact`, `tool`, `workCenter`,
-`process`. Note it does **not** list `fixedAsset` or `methodMaterial` (see Gotchas).
+`process`, `materialSubstance`, `materialForm`, `materialFinish`, `materialGrade`,
+`materialType`, `materialDimension`. Note it does **not** list `fixedAsset` or
+`methodMaterial` (see Gotchas).
+
+### Material-property imports (skip-duplicate, create-only)
+
+The six material-taxonomy lookups (`materialSubstance`, `materialForm`,
+`materialFinish`, `materialGrade`, `materialType`, `materialDimension`) are each a
+standalone import surfaced from its own config table (`apps/erp/app/modules/items/ui/Material*`).
+They are handled by `import-csv/material-property-import.ts` (not the item/customer
+paths) with **create-only, skip-duplicate** semantics — no `externalIntegrationMapping`,
+no updates. A row matching an existing entry for the company **or** a global system row
+(`companyId IS NULL`) is reported as `skipped`; re-importing the same file is a no-op.
+Dedup keys mirror the DB unique constraints (case/whitespace-insensitive):
+`code` (substance/form), `(materialSubstanceId, name)` (finish/grade),
+`(materialFormId, name)` (dimension), and both `(substance, form, code)` and
+`(substance, form, name)` (type). Parent substance/shape are referenced **by name**
+and resolved to ids by the FieldMappings enum-mapping step (fetchers on
+`materialSubstance` / `materialForm`), so parents must already exist — an unresolved
+parent is an `errors` row. New rows get a DB-generated `xid()` id.
> The models also include `customerStatus` / `customerType` field-mapping entries (used by
> creatable lookups), but only the tables above appear in `importPermissions`.
diff --git a/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx b/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx
index 6c3377ed94..f51aafd85b 100644
--- a/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialDimensions/MaterialDimensionsTable.tsx
@@ -148,6 +148,12 @@ const MaterialDimensionsTable = memo(
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "materialDimension" as const,
+ label: t`Material Dimensions`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx b/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx
index 47de93bf08..ad2328007e 100644
--- a/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialFinishes/MaterialFinishesTable.tsx
@@ -149,6 +149,12 @@ const MaterialFinishesTable = memo(
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "materialFinish" as const,
+ label: t`Material Finishes`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx b/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx
index 18d5f834ef..92dc7b1f04 100644
--- a/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialGrades/MaterialGradesTable.tsx
@@ -146,6 +146,12 @@ const MaterialGradesTable = memo(
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "materialGrade" as const,
+ label: t`Material Grades`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx b/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx
index cd2975633d..b6c0cd3746 100644
--- a/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialShapes/MaterialShapesTable.tsx
@@ -139,6 +139,12 @@ const MaterialShapesTable = memo(
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "materialForm" as const,
+ label: t`Material Shapes`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
index 70e7a2cab3..05e96a0ef2 100644
--- a/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialSubstances/MaterialSubstanceTable.tsx
@@ -141,6 +141,12 @@ const MaterialSubstancesTable = memo(
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "materialSubstance" as const,
+ label: t`Material Substances`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx b/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx
index 7985e81519..f177a45e30 100644
--- a/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx
+++ b/apps/erp/app/modules/items/ui/MaterialTypes/MaterialTypesTable.tsx
@@ -161,6 +161,12 @@ const MaterialTypesTable = memo(({ data, count }: MaterialTypesTableProps) => {
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "materialType" as const,
+ label: t`Material Types`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.ts
index 22ad15abe1..ecccef3706 100644
--- a/apps/erp/app/modules/shared/imports.models.ts
+++ b/apps/erp/app/modules/shared/imports.models.ts
@@ -178,6 +178,32 @@ const unitOfMeasureFetcher = async (
return { data: data.map((u) => ({ name: u.name, id: u.code })) };
};
+// Material-taxonomy parent fetchers, shared by the material-property imports
+// (finish/grade/type reference a substance; dimension/type reference a form).
+// Both global system rows (companyId IS NULL) and company rows are returned so a
+// CSV can reference either; the FieldMappings step matches by name → id.
+const materialSubstanceFetcher = async (
+ client: SupabaseClient<Database>,
+ companyId: string
+) => {
+ return client
+ .from("materialSubstance")
+ .select("id, name")
+ .or(`companyId.eq.${companyId},companyId.is.null`)
+ .order("name");
+};
+
+const materialFormFetcher = async (
+ client: SupabaseClient<Database>,
+ companyId: string
+) => {
+ return client
+ .from("materialForm")
+ .select("id, name")
+ .or(`companyId.eq.${companyId},companyId.is.null`)
+ .order("name");
+};
+
// Row-type discriminator + explicit parent key. Spread into every method entry.
const methodParentKeyFields = {
rowType: {
@@ -1602,6 +1628,126 @@ export const fieldMappings = {
required: false,
type: "string"
}
+ },
+ // Material taxonomy lookups. Each is a standalone import; child taxonomies
+ // (finish/grade/type/dimension) reference their parent substance/form by name
+ // via the enum fetchers above — the parent must already exist. Duplicates are
+ // skipped in the edge function (see material-property-import.ts).
+ materialSubstance: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ code: {
+ label: "Code",
+ required: true,
+ type: "string"
+ }
+ },
+ materialForm: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ code: {
+ label: "Code",
+ required: true,
+ type: "string"
+ }
+ },
+ materialFinish: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ materialSubstanceId: {
+ label: "Substance",
+ required: true,
+ type: "enum",
+ enumData: {
+ description:
+ "The substance this finish belongs to — match by substance name",
+ fetcher: materialSubstanceFetcher,
+ default: ""
+ }
+ }
+ },
+ materialGrade: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ materialSubstanceId: {
+ label: "Substance",
+ required: true,
+ type: "enum",
+ enumData: {
+ description:
+ "The substance this grade belongs to — match by substance name",
+ fetcher: materialSubstanceFetcher,
+ default: ""
+ }
+ }
+ },
+ materialType: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ code: {
+ label: "Code",
+ required: true,
+ type: "string"
+ },
+ materialSubstanceId: {
+ label: "Substance",
+ required: true,
+ type: "enum",
+ enumData: {
+ description:
+ "The substance this type belongs to — match by substance name",
+ fetcher: materialSubstanceFetcher,
+ default: ""
+ }
+ },
+ materialFormId: {
+ label: "Shape",
+ required: true,
+ type: "enum",
+ enumData: {
+ description: "The shape this type belongs to — match by shape name",
+ fetcher: materialFormFetcher,
+ default: ""
+ }
+ }
+ },
+ materialDimension: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ materialFormId: {
+ label: "Shape",
+ required: true,
+ type: "enum",
+ enumData: {
+ description:
+ "The shape this dimension belongs to — match by shape name",
+ fetcher: materialFormFetcher,
+ default: ""
+ }
+ },
+ isMetric: {
+ label: "Metric",
+ required: false,
+ type: "boolean"
+ }
}
} as const;
@@ -1620,7 +1766,13 @@ export const importPermissions: Record<keyof typeof fieldMappings, string> = {
consumable: "parts",
workCenter: "production",
process: "production",
- fixedAsset: "accounting"
+ fixedAsset: "accounting",
+ materialSubstance: "parts",
+ materialForm: "parts",
+ materialFinish: "parts",
+ materialGrade: "parts",
+ materialType: "parts",
+ materialDimension: "parts"
};
// Zod fragments for the method imports. Every method cell is an optional string at
@@ -2254,5 +2406,77 @@ export const importSchemas: Record<
.string()
.optional()
.describe("The location ID where the asset is located")
+ }),
+ materialSubstance: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the material substance (e.g. Steel, Aluminum)"),
+ code: z
+ .string()
+ .min(1, { message: "Code is required" })
+ .describe("A short code for the substance (e.g. ST, AL)")
+ }),
+ materialForm: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the shape/form (e.g. Sheet, Plate, Round Bar)"),
+ code: z
+ .string()
+ .min(1, { message: "Code is required" })
+ .describe("A short code for the shape (e.g. SHT, PL)")
+ }),
+ materialFinish: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the finish"),
+ materialSubstanceId: z
+ .string()
+ .optional()
+ .describe("The substance this finish belongs to")
+ }),
+ materialGrade: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the grade"),
+ materialSubstanceId: z
+ .string()
+ .optional()
+ .describe("The substance this grade belongs to")
+ }),
+ materialType: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the material type"),
+ code: z
+ .string()
+ .min(1, { message: "Code is required" })
+ .describe("A short code for the material type"),
+ materialSubstanceId: z
+ .string()
+ .optional()
+ .describe("The substance this type belongs to"),
+ materialFormId: z
+ .string()
+ .optional()
+ .describe("The shape this type belongs to")
+ }),
+ materialDimension: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the dimension"),
+ materialFormId: z
+ .string()
+ .optional()
+ .describe("The shape this dimension belongs to"),
+ isMetric: z
+ .string()
+ .optional()
+ .describe("Whether the dimension is metric (true/false)")
})
} as const;
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 760ba75eda..d5f6f3a3cd 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -9,6 +9,7 @@ import { requirePermissions } from "../lib/supabase.ts";
import { Database } from "../lib/types.ts";
import { getReadableIdWithRevision } from "../lib/utils.ts";
import { classifyImportRow } from "./classify-import-row.ts";
+import { importMaterialProperties } from "./material-property-import.ts";
import { importMethods } from "./method-import.ts";
const pool = getConnectionPool(1);
@@ -30,6 +31,12 @@ const importCsvValidator = z.object({
"tool",
"workCenter",
"process",
+ "materialSubstance",
+ "materialForm",
+ "materialFinish",
+ "materialGrade",
+ "materialType",
+ "materialDimension",
]),
filePath: z.string(),
columnMappings: z.record(z.string()),
@@ -2302,6 +2309,21 @@ serve(async (req: Request) => {
});
break;
}
+ case "materialSubstance":
+ case "materialForm":
+ case "materialFinish":
+ case "materialGrade":
+ case "materialType":
+ case "materialDimension": {
+ await importMaterialProperties(db, {
+ table,
+ mappedRecords,
+ companyId,
+ userId,
+ summary,
+ });
+ break;
+ }
default: {
throw new Error(`Invalid table: ${table}`);
}
diff --git a/packages/database/supabase/functions/import-csv/material-property-import.ts b/packages/database/supabase/functions/import-csv/material-property-import.ts
new file mode 100644
index 0000000000..e87e559190
--- /dev/null
+++ b/packages/database/supabase/functions/import-csv/material-property-import.ts
@@ -0,0 +1,389 @@
+// Material-taxonomy importer — backs the six standalone material-property CSV
+// imports: materialSubstance, materialForm, materialFinish, materialGrade,
+// materialType, materialDimension.
+//
+// These are plain global-or-company lookup tables (see .claude/rules/material-tables.md).
+// Unlike the item/customer/supplier importers this is intentionally **create-only
+// with skip-duplicate** semantics (never upserts, never mutates existing rows):
+// a row that matches an existing entry — for THIS company OR a global system row
+// (companyId IS NULL) — is skipped, so re-importing the same file is a no-op.
+//
+// Parent references (a finish/grade/type's substance, a type/dimension's shape)
+// arrive already resolved to ids by the FieldMappings enum-mapping step, so this
+// importer treats them as ids; a blank/unresolved parent is reported as a row error.
+
+import { Kysely, Transaction } from "npm:[email protected]";
+import { DB } from "../lib/database.ts";
+
+type Rec = Record<string, string>;
+
+type Summary = {
+ inserted: number;
+ updated: number;
+ errors: Array<{ row: number; reason: string }>;
+ skipped: Array<{ row: number; reason: string }>;
+};
+
+export type MaterialPropertyTable =
+ | "materialSubstance"
+ | "materialForm"
+ | "materialFinish"
+ | "materialGrade"
+ | "materialType"
+ | "materialDimension";
+
+// Case/whitespace-insensitive normalization for the dedup keys. Slightly stricter
+// than the DB unique constraints (which are case-sensitive), matching the
+// "never make a duplicate" intent for these human-entered lookups.
+const norm = (s: string | undefined) => (s ?? "").trim().toLowerCase();
+
+const isMetricValue = (s: string | undefined) => {
+ const v = norm(s);
+ return v === "true" || v === "1" || v === "yes" || v === "y" || v === "metric";
+};
+
+const SUBSTANCE_UNMATCHED =
+ "Substance could not be matched — make sure the substance exists and is mapped in the wizard";
+const SHAPE_UNMATCHED =
+ "Shape could not be matched — make sure the shape exists and is mapped in the wizard";
+
+type TableConfig = {
+ // Validate a mapped row; return an error reason, or null if the row is usable.
+ validate: (r: Rec) => string | null;
+ // Every natural (uniqueness) key the row occupies. A row is a duplicate if ANY
+ // of its keys already exists (in the DB, or earlier in the same file). Types
+ // carry two keys (code + name, both enforced unique); the rest carry one.
+ keysOf: (r: Rec) => string[];
+ // Preload the natural keys already present for this company OR the global
+ // (companyId IS NULL) system rows, so a company row never shadows a system row.
+ loadExistingKeys: (
+ trx: Transaction<DB>,
+ companyId: string
+ ) => Promise<Set<string>>;
+ // Insert the accepted rows. ON CONFLICT DO NOTHING guards races; the pre-scan
+ // above handles the normal skip path. Returns the number actually written.
+ insert: (
+ trx: Transaction<DB>,
+ rows: Rec[],
+ companyId: string,
+ userId: string
+ ) => Promise<number>;
+};
+
+const CONFIGS: Record<MaterialPropertyTable, TableConfig> = {
+ materialSubstance: {
+ validate: (r) =>
+ !r.name?.trim()
+ ? "Name is required"
+ : !r.code?.trim()
+ ? "Code is required"
+ : null,
+ keysOf: (r) => [`c:${norm(r.code)}`],
+ loadExistingKeys: async (trx, companyId) => {
+ const rows = await trx
+ .selectFrom("materialSubstance")
+ .select(["code"])
+ .where((eb) =>
+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])
+ )
+ .execute();
+ return new Set(rows.map((x) => `c:${norm(x.code ?? "")}`));
+ },
+ insert: async (trx, rows, companyId, userId) => {
+ const now = new Date().toISOString();
+ const inserted = await trx
+ .insertInto("materialSubstance")
+ .values(
+ rows.map(
+ (r) =>
+ ({
+ name: r.name.trim(),
+ code: r.code.trim(),
+ companyId,
+ createdBy: userId,
+ createdAt: now,
+ }) as never
+ )
+ )
+ .onConflict((oc) => oc.doNothing())
+ .returning(["id"])
+ .execute();
+ return inserted.length;
+ },
+ },
+ materialForm: {
+ validate: (r) =>
+ !r.name?.trim()
+ ? "Name is required"
+ : !r.code?.trim()
+ ? "Code is required"
+ : null,
+ keysOf: (r) => [`c:${norm(r.code)}`],
+ loadExistingKeys: async (trx, companyId) => {
+ const rows = await trx
+ .selectFrom("materialForm")
+ .select(["code"])
+ .where((eb) =>
+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])
+ )
+ .execute();
+ return new Set(rows.map((x) => `c:${norm(x.code ?? "")}`));
+ },
+ insert: async (trx, rows, companyId, userId) => {
+ const now = new Date().toISOString();
+ const inserted = await trx
+ .insertInto("materialForm")
+ .values(
+ rows.map(
+ (r) =>
+ ({
+ name: r.name.trim(),
+ code: r.code.trim(),
+ companyId,
+ createdBy: userId,
+ createdAt: now,
+ }) as never
+ )
+ )
+ .onConflict((oc) => oc.doNothing())
+ .returning(["id"])
+ .execute();
+ return inserted.length;
+ },
+ },
+ materialFinish: {
+ validate: (r) =>
+ !r.name?.trim()
+ ? "Name is required"
+ : !r.materialSubstanceId?.trim()
+ ? SUBSTANCE_UNMATCHED
+ : null,
+ keysOf: (r) => [`${r.materialSubstanceId.trim()}:${norm(r.name)}`],
+ loadExistingKeys: async (trx, companyId) => {
+ const rows = await trx
+ .selectFrom("materialFinish")
+ .select(["materialSubstanceId", "name"])
+ .where((eb) =>
+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])
+ )
+ .execute();
+ return new Set(rows.map((x) => `${x.materialSubstanceId}:${norm(x.name)}`));
+ },
+ insert: async (trx, rows, companyId) => {
+ const inserted = await trx
+ .insertInto("materialFinish")
+ .values(
+ rows.map(
+ (r) =>
+ ({
+ name: r.name.trim(),
+ materialSubstanceId: r.materialSubstanceId.trim(),
+ companyId,
+ }) as never
+ )
+ )
+ .onConflict((oc) => oc.doNothing())
+ .returning(["id"])
+ .execute();
+ return inserted.length;
+ },
+ },
+ materialGrade: {
+ validate: (r) =>
+ !r.name?.trim()
+ ? "Name is required"
+ : !r.materialSubstanceId?.trim()
+ ? SUBSTANCE_UNMATCHED
+ : null,
+ keysOf: (r) => [`${r.materialSubstanceId.trim()}:${norm(r.name)}`],
+ loadExistingKeys: async (trx, companyId) => {
+ const rows = await trx
+ .selectFrom("materialGrade")
+ .select(["materialSubstanceId", "name"])
+ .where((eb) =>
+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])
+ )
+ .execute();
+ return new Set(rows.map((x) => `${x.materialSubstanceId}:${norm(x.name)}`));
+ },
+ insert: async (trx, rows, companyId) => {
+ const inserted = await trx
+ .insertInto("materialGrade")
+ .values(
+ rows.map(
+ (r) =>
+ ({
+ name: r.name.trim(),
+ materialSubstanceId: r.materialSubstanceId.trim(),
+ companyId,
+ }) as never
+ )
+ )
+ .onConflict((oc) => oc.doNothing())
+ .returning(["id"])
+ .execute();
+ return inserted.length;
+ },
+ },
+ materialType: {
+ validate: (r) =>
+ !r.name?.trim()
+ ? "Name is required"
+ : !r.code?.trim()
+ ? "Code is required"
+ : !r.materialSubstanceId?.trim()
+ ? SUBSTANCE_UNMATCHED
+ : !r.materialFormId?.trim()
+ ? SHAPE_UNMATCHED
+ : null,
+ keysOf: (r) => {
+ const sub = r.materialSubstanceId.trim();
+ const form = r.materialFormId.trim();
+ // Both (substance, form, code) and (substance, form, name) are unique.
+ return [`${sub}:${form}:c:${norm(r.code)}`, `${sub}:${form}:n:${norm(r.name)}`];
+ },
+ loadExistingKeys: async (trx, companyId) => {
+ const rows = await trx
+ .selectFrom("materialType")
+ .select(["materialSubstanceId", "materialFormId", "code", "name"])
+ .where((eb) =>
+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])
+ )
+ .execute();
+ const set = new Set<string>();
+ for (const x of rows) {
+ set.add(
+ `${x.materialSubstanceId}:${x.materialFormId}:c:${norm(x.code ?? "")}`
+ );
+ set.add(`${x.materialSubstanceId}:${x.materialFormId}:n:${norm(x.name)}`);
+ }
+ return set;
+ },
+ insert: async (trx, rows, companyId) => {
+ const inserted = await trx
+ .insertInto("materialType")
+ .values(
+ rows.map(
+ (r) =>
+ ({
+ name: r.name.trim(),
+ code: r.code.trim(),
+ materialSubstanceId: r.materialSubstanceId.trim(),
+ materialFormId: r.materialFormId.trim(),
+ companyId,
+ }) as never
+ )
+ )
+ .onConflict((oc) => oc.doNothing())
+ .returning(["id"])
+ .execute();
+ return inserted.length;
+ },
+ },
+ materialDimension: {
+ validate: (r) =>
+ !r.name?.trim()
+ ? "Name is required"
+ : !r.materialFormId?.trim()
+ ? SHAPE_UNMATCHED
+ : null,
+ keysOf: (r) => [`${r.materialFormId.trim()}:${norm(r.name)}`],
+ loadExistingKeys: async (trx, companyId) => {
+ const rows = await trx
+ .selectFrom("materialDimension")
+ .select(["materialFormId", "name"])
+ .where((eb) =>
+ eb.or([eb("companyId", "=", companyId), eb("companyId", "is", null)])
+ )
+ .execute();
+ return new Set(rows.map((x) => `${x.materialFormId}:${norm(x.name)}`));
+ },
+ insert: async (trx, rows, companyId) => {
+ const inserted = await trx
+ .insertInto("materialDimension")
+ .values(
+ rows.map(
+ (r) =>
+ ({
+ name: r.name.trim(),
+ materialFormId: r.materialFormId.trim(),
+ isMetric: isMetricValue(r.isMetric),
+ companyId,
+ }) as never
+ )
+ )
+ .onConflict((oc) => oc.doNothing())
+ .returning(["id"])
+ .execute();
+ return inserted.length;
+ },
+ },
+};
+
+/**
+ * Import a batch of material-property rows for one taxonomy table. Validates each
+ * row, skips duplicates (against the DB and within the file), and bulk-inserts the
+ * rest inside a single transaction. Mutates `summary` in place with the counts and
+ * per-row error/skip reasons the results UI renders.
+ */
+export async function importMaterialProperties(
+ db: Kysely<DB>,
+ {
+ table,
+ mappedRecords,
+ companyId,
+ userId,
+ summary,
+ }: {
+ table: MaterialPropertyTable;
+ mappedRecords: Rec[];
+ companyId: string;
+ userId: string;
+ summary: Summary;
+ }
+) {
+ const config = CONFIGS[table];
+
+ await db.transaction().execute(async (trx) => {
+ const existingKeys = await config.loadExistingKeys(trx, companyId);
+ const seenKeys = new Set<string>();
+ const accepted: Rec[] = [];
+
+ for (const [rowIndex, record] of mappedRecords.entries()) {
+ const reason = config.validate(record);
+ if (reason) {
+ summary.errors.push({ row: rowIndex, reason });
+ continue;
+ }
+
+ const keys = config.keysOf(record);
+ if (keys.some((k) => existingKeys.has(k))) {
+ summary.skipped.push({ row: rowIndex, reason: "Already exists — skipped" });
+ continue;
+ }
+ if (keys.some((k) => seenKeys.has(k))) {
+ summary.skipped.push({
+ row: rowIndex,
+ reason: "Duplicate row in file — skipped",
+ });
+ continue;
+ }
+
+ keys.forEach((k) => seenKeys.add(k));
+ accepted.push(record);
+ }
+
+ console.log({
+ function: "import-material-properties",
+ table,
+ totalRecords: mappedRecords.length,
+ accepted: accepted.length,
+ skipped: summary.skipped.length,
+ errors: summary.errors.length,
+ });
+
+ if (accepted.length > 0) {
+ summary.inserted += await config.insert(trx, accepted, companyId, userId);
+ }
+ });
+}