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(inventory): add CSV import for storage units

sidgaikwad8256c9ee5765
diff --git a/.ai/plans/2026-08-25-storage-units-csv-import.md b/.ai/plans/2026-08-25-storage-units-csv-import.md
new file mode 100644
index 0000000000..a45cdbb323
--- /dev/null
+++ b/.ai/plans/2026-08-25-storage-units-csv-import.md
@@ -0,0 +1,39 @@
+# Storage Units CSV Import
+
+Add a CSV import tool for Storage Units (requested by Heaviside), mirroring the
+existing `workCenter` import path, plus two sample CSVs (perfect + mixed edge cases).
+
+## Key schema facts
+- `storageUnit` cols: `id` (default), `name` (req), `locationId` (req, FK location),
+ `parentId` (nullable self-FK), `storageTypeIds TEXT[]`, `workCenterId`, `active`,
+ audit. UNIQUE `("name","locationId")` → names unique **per location**.
+- DB interceptors enforce: parent same-location, no locationId change with children,
+ no parent cycles (raise → abort). So resolve parents within same location and set
+ parent as a resilient second pass.
+- `storageType`: `id`, `name`, `companyId`, audit. No unique-name constraint.
+- Storage-unit create/update route permission = `inventory`.
+
+## Fields imported
+`id` (Unique ID, req), `name` (req), `locationId` (Location, req, enum+fetcher),
+`parentName` (optional, resolved by name within location), `storageTypeNames`
+(optional, comma-separated, resolved/created), `active` (optional boolean).
+
+## Changes
+1. `apps/erp/app/modules/shared/imports.models.ts` — add `storageUnit` to
+ `fieldMappings`, `importPermissions` (→ `inventory`), `importSchemas`.
+2. `packages/database/supabase/functions/import-csv/index.ts` — add `storageUnit`
+ to the `table` enum, `CsvEntityType`, `fetchLiveEntityIds`, and a `case
+ "storageUnit"` handler:
+ - match/dedup by `(locationId, lower(name))` natural key + csv external id;
+ - resolve/create storage types by name;
+ - insert/update inside one txn, then a second pass sets `parentId` (per-row
+ try/catch, row errors instead of a full rollback).
+3. `apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx` — add
+ `importCSV={[{ table: "storageUnit", label: "Storage Units" }]}`.
+4. Docs sync: `.claude/rules/csv-import-system.md`, inventory `AGENTS.md`.
+5. Deliverables: `storage-units-perfect.csv`, `storage-units-mixed.csv`.
+
+## Verify
+- `pnpm exec turbo run typecheck --filter=erp`
+- Deno check of the edge function file.
+- Biome lint on changed files.
diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.md
index c0e40d68a2..8cfc568a09 100644
--- a/.claude/rules/csv-import-system.md
+++ b/.claude/rules/csv-import-system.md
@@ -64,14 +64,32 @@ Other exports: `creatableLookups`, and types `CreatableLookup`, `CreatableForm`.
`part`, `material`, `tool`, `fixture`, `consumable`, `methodMaterial`, `bom`,
`operations`, `partWithMethod`, `materialSubstance`, `materialForm`, `materialFinish`,
`materialGrade`, `materialType`, `materialDimension` → `parts`;
-`workCenter`, `process` → `production`; `fixedAsset` → `accounting`.
+`workCenter`, `process` → `production`; `storageUnit` → `inventory`;
+`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`, `materialSubstance`, `materialForm`, `materialFinish`, `materialGrade`,
-`materialType`, `materialDimension`. Note it does **not** list `fixedAsset` or
-`methodMaterial` (see Gotchas).
+`process`, `storageUnit`, `materialSubstance`, `materialForm`, `materialFinish`,
+`materialGrade`, `materialType`, `materialDimension`. Note it does **not** list
+`fixedAsset` or `methodMaterial` (see Gotchas).
+
+### Storage-unit import (natural-key match + two-pass parent linking)
+
+`storageUnit` imports the fields `id` (Unique ID), `name`, `locationId` (Location,
+an enum resolved via the FieldMappings location fetcher), `parentName`,
+`storageTypeNames` (comma-separated), and `active`. Because storage unit names are
+unique **per location** (`storageUnit_name_locationId_key`), both in-file dedup and
+match-existing-to-update key on `(locationId, lower(name))` — NOT `classifyImportRow`'s
+name-only dedup. A csv `id` still writes an `externalIntegrationMapping` for id-based
+re-import. Updates deliberately never change `locationId` (avoids the "cannot move a
+unit with children" interceptor). `storageTypeNames` resolve case-insensitively against
+existing company `storageType` rows, **creating** any missing ones (mirrors the creatable
+StorageTypes combobox). `parentName` is applied in a **second pass** after all inserts —
+individual `UPDATE`s outside the insert transaction — so a parent defined later in the
+same file resolves and an unresolved/cyclic/self parent reports a per-row error instead
+of rolling back the whole import. The DB same-location / no-cycle interceptors
+(`20260417000200`) are the final guard; their exceptions are caught per row.
### Material-property imports (skip-duplicate, create-only)
diff --git a/apps/erp/app/modules/inventory/AGENTS.md b/apps/erp/app/modules/inventory/AGENTS.md
index 90110bb25c..ba281bf9bd 100644
--- a/apps/erp/app/modules/inventory/AGENTS.md
+++ b/apps/erp/app/modules/inventory/AGENTS.md
@@ -4,7 +4,7 @@ Tracks item quantities across locations and storage units. Manages receipts, shi
## Key Domain Concepts
-- **Storage Unit** — hierarchical container (bin, shelf, rack, zone) within a location. Tree structure via `parentId`. Renamed from `shelf` in migration `20260417000100`. MUST use `storageUnit` naming, never `shelf`.
+- **Storage Unit** — hierarchical container (bin, shelf, rack, zone) within a location. Tree structure via `parentId`. Renamed from `shelf` in migration `20260417000100`. MUST use `storageUnit` naming, never `shelf`. Bulk **CSV import** is wired via the shared import system (`table: "storageUnit"`, permission `inventory`): fields `id`, `name`, `locationId`, `parentName`, `storageTypeNames`, `active`; matched on `(locationId, lower(name))` since names are unique per location, parents linked in a second pass. See `.claude/rules/csv-import-system.md`.
- **Tracked Entity** — serial/batch/lot-tracked item instance with `readableId` (serial or batch number), `status` (Available/Reserved/On Hold/Consumed/Rejected/Scrapped), `quantity`, and `expirationDate`. `Scrapped` is terminal but recoverable via the Unscrap adjustment. Batch items have `batchProperty` definitions.
- **Item Ledger** — append-only log of every inventory movement (`itemLedger` table). Source of truth for on-hand quantities. MUST never INSERT directly — always go through service functions.
- **Receipt** — inbound inventory from POs or production. Lines link to `purchaseOrderLine` or jobs. Posting creates ledger entries and tracked entities.
diff --git a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx
index e0d2d599ca..a3ceb5d3a7 100644
--- a/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StorageUnits/StorageUnitsTable.tsx
@@ -578,6 +578,12 @@ const StorageUnitsTable = memo(
data={displayRows}
defaultColumnVisibility={defaultColumnVisibility}
defaultColumnPinning={defaultColumnPinning}
+ importCSV={[
+ {
+ table: "storageUnit" as const,
+ label: "Storage Units"
+ }
+ ]}
primaryAction={actions}
renderContextMenu={renderContextMenu}
title={t`Storage Units`}
diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.ts
index dcf1a4b904..8a91a6727a 100644
--- a/apps/erp/app/modules/shared/imports.models.ts
+++ b/apps/erp/app/modules/shared/imports.models.ts
@@ -1568,6 +1568,52 @@ export const fieldMappings = {
}
}
},
+ storageUnit: {
+ id: {
+ label: "Unique ID",
+ required: true,
+ type: "string"
+ },
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ locationId: {
+ label: "Location",
+ required: true,
+ type: "enum",
+ enumData: {
+ description:
+ "The location this storage unit belongs to — match by location name",
+ fetcher: async (
+ client: SupabaseClient<Database>,
+ companyId: string
+ ) => {
+ return client
+ .from("location")
+ .select("id, name")
+ .eq("companyId", companyId)
+ .order("name");
+ }
+ }
+ },
+ parentName: {
+ label: "Parent Storage Unit",
+ required: false,
+ type: "string"
+ },
+ storageTypeNames: {
+ label: "Storage Types",
+ required: false,
+ type: "string"
+ },
+ active: {
+ label: "Active",
+ required: false,
+ type: "boolean"
+ }
+ },
fixedAsset: {
name: {
label: "Name",
@@ -1758,6 +1804,7 @@ export const importPermissions: Record<keyof typeof fieldMappings, string> = {
consumable: "parts",
workCenter: "production",
process: "production",
+ storageUnit: "inventory",
fixedAsset: "accounting",
materialSubstance: "parts",
materialForm: "parts",
@@ -2355,6 +2402,40 @@ export const importSchemas: Record<
"Whether scanning a barcode should complete all operations for this process"
)
}),
+ storageUnit: z.object({
+ id: z
+ .string()
+ .min(1, { message: "ID is required" })
+ .describe(
+ "The unique ID of the storage unit, usually a number or set of alphanumeric characters."
+ ),
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe(
+ "The name/label of the storage unit (e.g. bin, shelf, rack, or zone). Unique within a location."
+ ),
+ locationId: z
+ .string()
+ .min(1, { message: "Location is required" })
+ .describe("The location ID of the storage unit"),
+ parentName: z
+ .string()
+ .optional()
+ .describe(
+ "The name of the parent storage unit — must be in the same location"
+ ),
+ storageTypeNames: z
+ .string()
+ .optional()
+ .describe(
+ "Comma-separated storage type names (e.g. Cold Storage, Hazardous)"
+ ),
+ active: z
+ .string()
+ .optional()
+ .describe("Whether the storage unit is active (true/false)")
+ }),
fixedAsset: z.object({
name: z
.string()
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 5ef18d4498..cbd9848923 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -31,6 +31,7 @@ const importCsvValidator = z.object({
"tool",
"workCenter",
"process",
+ "storageUnit",
"materialSubstance",
"materialForm",
"materialFinish",
@@ -113,7 +114,8 @@ type CsvEntityType =
| "item"
| "contact"
| "workCenter"
- | "process";
+ | "process"
+ | "storageUnit";
/**
* Look up the ids that still exist in the entity table. Done as a typed
@@ -169,6 +171,13 @@ async function fetchLiveEntityIds(
.where("id", "in", ids)
.execute();
break;
+ case "storageUnit":
+ rows = await db
+ .selectFrom("storageUnit")
+ .select(["id"])
+ .where("id", "in", ids)
+ .execute();
+ break;
}
return new Set(rows.map((r) => r.id));
}
@@ -2506,6 +2515,300 @@ serve(async (req: Request) => {
});
break;
}
+ case "storageUnit": {
+ const externalIdMap = await getCsvExternalIdMap(
+ "storageUnit",
+ companyId
+ );
+
+ // Storage unit names are unique per location
+ // (storageUnit_name_locationId_key), so the natural key for both in-file
+ // dedup and match-existing-to-update is (locationId + lowercased name).
+ const naturalKey = (locationId: string, name: string) =>
+ `${locationId}::${name.trim().toLowerCase()}`;
+
+ // Preload existing units for the referenced locations so a name that
+ // already exists updates instead of tripping the unique constraint, and
+ // so parent references can resolve against pre-existing units.
+ const referencedLocationIds = Array.from(
+ new Set(
+ mappedRecords
+ .map((r) => r.locationId)
+ .filter(
+ (l): l is string => typeof l === "string" && l.trim() !== ""
+ )
+ )
+ );
+ const existingUnits =
+ referencedLocationIds.length > 0
+ ? await db
+ .selectFrom("storageUnit")
+ .select(["id", "name", "locationId"])
+ .where("companyId", "=", companyId)
+ .where("locationId", "in", referencedLocationIds)
+ .execute()
+ : [];
+ // (locationId + lowercased name) -> storageUnit id. Grows as we insert,
+ // so a child whose parent is defined later in the same file resolves.
+ const naturalKeyMap = new Map<string, string>();
+ for (const u of existingUnits) {
+ naturalKeyMap.set(naturalKey(u.locationId, u.name), u.id);
+ }
+
+ // Preload existing storage types (lowercased name -> id). Unmatched
+ // names create a company-scoped storageType, mirroring the creatable
+ // StorageTypes combobox on the storage-unit form.
+ const existingTypes = await db
+ .selectFrom("storageType")
+ .select(["id", "name"])
+ .where("companyId", "=", companyId)
+ .execute();
+ const storageTypeByName = new Map<string, string>();
+ for (const st of existingTypes) {
+ storageTypeByName.set(st.name.trim().toLowerCase(), st.id);
+ }
+
+ const parseActive = (value: string | undefined): boolean => {
+ const v = (value ?? "").trim().toLowerCase();
+ // Default active; only explicit falsey values deactivate.
+ return !["false", "no", "0", "inactive", "n"].includes(v);
+ };
+ const parseTypeNames = (value: string | undefined): string[] =>
+ (value ?? "")
+ .split(",")
+ .map((s) => s.trim())
+ .filter((s) => s !== "");
+
+ const seenNaturalKeys = new Set<string>();
+ const seenCsvIds = new Set<string>();
+ // Parent links are applied in a second pass (after all inserts) so a
+ // parent defined later in the same file resolves and a bad parent
+ // reports a row error instead of rolling back the whole import.
+ const parentIntents: Array<{
+ locationId: string;
+ childKey: string;
+ parentName: string;
+ rowIndex: number;
+ }> = [];
+
+ await db.transaction().execute(async (trx) => {
+ const inserts: Database["public"]["Tables"]["storageUnit"]["Insert"][] =
+ [];
+ const csvIdsForInserts: string[] = [];
+ const updates: {
+ id: string;
+ data: Database["public"]["Tables"]["storageUnit"]["Update"];
+ }[] = [];
+ const csvIdsForNameMatchedUpdates: Array<{
+ entityId: string;
+ externalId: string;
+ }> = [];
+
+ // Resolve storage type names to ids, creating any that don't exist.
+ const resolveTypeIds = async (names: string[]): Promise<string[]> => {
+ const ids: string[] = [];
+ for (const name of names) {
+ const key = name.toLowerCase();
+ let id = storageTypeByName.get(key);
+ if (!id) {
+ const created = await trx
+ .insertInto("storageType")
+ .values({
+ id: nanoid(),
+ name,
+ companyId,
+ createdBy: userId,
+ createdAt: new Date().toISOString(),
+ } as never)
+ .returning(["id"])
+ .execute();
+ id = created[0]?.id ?? undefined;
+ if (id) storageTypeByName.set(key, id);
+ }
+ if (id && !ids.includes(id)) ids.push(id);
+ }
+ return ids;
+ };
+
+ for (const [rowIndex, record] of mappedRecords.entries()) {
+ const id = record.id ?? "";
+ const name = (record.name ?? "").trim();
+ const locationId = (record.locationId ?? "").trim();
+ const parentName = (record.parentName ?? "").trim();
+
+ if (name === "" || locationId === "") {
+ summary.errors.push({
+ row: rowIndex,
+ reason:
+ name === ""
+ ? "Missing required Name"
+ : "Missing required Location",
+ });
+ continue;
+ }
+ if (id && seenCsvIds.has(id)) {
+ summary.skipped.push({
+ row: rowIndex,
+ reason: `Duplicate ID "${id}" in file`,
+ });
+ continue;
+ }
+ const key = naturalKey(locationId, name);
+ if (seenNaturalKeys.has(key)) {
+ summary.skipped.push({
+ row: rowIndex,
+ reason: `Duplicate storage unit "${name}" for this location in file`,
+ });
+ continue;
+ }
+ seenNaturalKeys.add(key);
+ if (id) seenCsvIds.add(id);
+
+ const storageTypeIds = await resolveTypeIds(
+ parseTypeNames(record.storageTypeNames)
+ );
+ const active = parseActive(record.active);
+
+ if (parentName) {
+ parentIntents.push({
+ locationId,
+ childKey: key,
+ parentName,
+ rowIndex,
+ });
+ }
+
+ const matchedByCsvId = id ? externalIdMap.get(id) : undefined;
+ const matchedByName =
+ matchedByCsvId === undefined ? naturalKeyMap.get(key) : undefined;
+ const existingEntityId = matchedByCsvId ?? matchedByName;
+
+ if (existingEntityId !== undefined) {
+ // Deliberately does not touch locationId (the match/natural key)
+ // to avoid the "cannot move a unit with children" interceptor.
+ updates.push({
+ id: existingEntityId,
+ data: {
+ name,
+ storageTypeIds,
+ active,
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ },
+ });
+ if (matchedByCsvId === undefined && id) {
+ csvIdsForNameMatchedUpdates.push({
+ entityId: existingEntityId,
+ externalId: id,
+ });
+ }
+ naturalKeyMap.set(key, existingEntityId);
+ } else {
+ const newId = nanoid();
+ inserts.push({
+ id: newId,
+ name,
+ locationId,
+ storageTypeIds,
+ active,
+ companyId,
+ createdBy: userId,
+ createdAt: new Date().toISOString(),
+ } as never);
+ csvIdsForInserts.push(id);
+ naturalKeyMap.set(key, newId);
+ }
+ }
+
+ console.log({
+ totalRecords: mappedRecords.length,
+ storageUnitInserts: inserts.length,
+ storageUnitUpdates: updates.length,
+ });
+ summary.inserted += inserts.length;
+ summary.updated += updates.length;
+
+ if (inserts.length > 0) {
+ const inserted = await trx
+ .insertInto("storageUnit")
+ .values(inserts)
+ .returning(["id"])
+ .execute();
+ await upsertCsvMappings(
+ trx,
+ "storageUnit",
+ inserted.map((row, i) => ({
+ entityId: row.id!,
+ externalId: csvIdsForInserts[i],
+ })),
+ companyId,
+ userId
+ );
+ }
+ for (const update of updates) {
+ await trx
+ .updateTable("storageUnit")
+ .set(update.data)
+ .where("id", "=", update.id)
+ .execute();
+ }
+ if (csvIdsForNameMatchedUpdates.length > 0) {
+ await upsertCsvMappings(
+ trx,
+ "storageUnit",
+ csvIdsForNameMatchedUpdates,
+ companyId,
+ userId
+ );
+ }
+ });
+
+ // Second pass: link parents by (locationId + name) now that every unit
+ // in the file exists. Individual UPDATEs (outside the insert txn) so an
+ // unresolved or cyclic parent reports a row error without discarding the
+ // successful imports. The DB same-location / no-cycle interceptors are
+ // the final guard; their exceptions are caught per-row.
+ for (const intent of parentIntents) {
+ const childId = naturalKeyMap.get(intent.childKey);
+ const parentId = naturalKeyMap.get(
+ naturalKey(intent.locationId, intent.parentName)
+ );
+ if (!childId) continue;
+ if (!parentId) {
+ summary.errors.push({
+ row: intent.rowIndex,
+ reason: `Parent storage unit "${intent.parentName}" not found in the same location`,
+ });
+ continue;
+ }
+ if (parentId === childId) {
+ summary.errors.push({
+ row: intent.rowIndex,
+ reason: `Storage unit cannot be its own parent`,
+ });
+ continue;
+ }
+ try {
+ await db
+ .updateTable("storageUnit")
+ .set({
+ parentId,
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ })
+ .where("id", "=", childId)
+ .execute();
+ } catch (parentErr) {
+ summary.errors.push({
+ row: intent.rowIndex,
+ reason: `Could not set parent "${intent.parentName}": ${
+ (parentErr as Error).message
+ }`,
+ });
+ }
+ }
+ break;
+ }
case "bom":
case "operations":
case "partWithMethod": {