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(csv-import): six new import types — services and five config lookups

Raul3db2c4b13c62
diff --git a/.ai/research/2026-08-30-csv-import-coverage.md b/.ai/research/2026-08-30-csv-import-coverage.md
new file mode 100644
index 0000000000..12a5640db2
--- /dev/null
+++ b/.ai/research/2026-08-30-csv-import-coverage.md
@@ -0,0 +1,214 @@
+# CSV import coverage — what exists, and what a new import type costs
+
+Research for expanding the CSV import system. Every fact verified against `main` at `7f5f1d214`
+on 2026-08-30 by reading the file cited.
+
+## The system as it stands
+
+One import path, one entry point. PapaParse appears in exactly two files, both under
+`apps/erp/app/components/ImportCSVModal/` — the wizard is the only CSV-ingest surface in the ERP
+app. Nothing else in `apps/` or `packages/` reads an uploaded CSV.
+
+A list page opts in by passing `importCSV={[{ table, label }]}` to `<Table>`, which renders the
+Bulk Import dropdown in `components/Table/components/TableHeader.tsx:264`. That prop is the whole
+registration mechanism on the UI side.
+
+Adding a new import type therefore costs five edits:
+
+1. `fieldMappings[table]` — labels, types, required flags, enum fetchers.
+2. `importSchemas[table]` — the zod object the route validates against.
+3. `importPermissions[table]` — the module whose `update` permission gates it.
+4. The edge function's `table` enum plus a `case` in the switch.
+5. `importCSV={[...]}` on the list page's `<Table>`.
+
+Miss (2) and the field is silently dropped by the route; miss (4) and the whole import 400s; miss
+(5) and it is unreachable. All three failure modes exist on `main` today — see Defects.
+
+## Current coverage
+
+22 registered, 21 accepted by the edge function, 20 reachable.
+
+| Registered | Reachable from | Write path |
+|---|---|---|
+| `customer`, `customerContact` | Customers | main |
+| `supplier`, `supplierContact` | Suppliers | main |
+| `part`, `bom`, `operations`, `partWithMethod` | Parts, Tools | main |
+| `material`, `tool`, `consumable` | own list pages | main |
+| `workCenter`, `process` | own list pages | main |
+| `storageUnit` | Storage Units | main, two-pass parent linking |
+| 6 × material taxonomy | own config pages | `material-property-import.ts`, create-only |
+| `fixture` | nowhere | main |
+| `fixedAsset` | nowhere | none — rejected by the edge function |
+
+15 of the app's 124 table components carry a Bulk Import button.
+
+Idempotency for the main path is `externalIntegrationMapping` with `integration = "csv"`. The
+material-taxonomy path skips it entirely and dedups on the DB's own unique constraints.
+
+## Defects on main
+
+- `revision` is in `fieldMappings` for `part`/`tool`/`fixture`/`consumable`/`material` and marked
+ required. It is absent from the matching `importSchemas` entry. The route builds `columnMappings`
+ from `validation.data` (`x+/shared+/import.$tableId.tsx:38`) and a zod object strips unknown keys,
+ so the mapping never leaves the route. The edge function supports it and falls back to
+ `revision: rest.revision ?? "0"` (`import-csv/index.ts:1688,1787`). Every CSV-imported item lands
+ at revision `"0"` while the wizard demands the column. `mpn` on `partWithMethod` is identical.
+- The LLM mapping fallback fires on nearly every file. `FieldMappings.tsx:133` skips it only when
+ *every* field in `fieldMappings[table]` matched a header, not every *required* field. `part` has
+ 19 fields and 4 required. Mitigated but not fixed by the server doing its own exact-match pass and
+ returning `{...matched, ...object}` (`api+/ai+/csv+/$table.columns.tsx`).
+- `fixedAsset` is registered in models and permissions but missing from the edge function's `table`
+ enum (`import-csv/index.ts:19`), and no page surfaces it.
+- `fixture` is registered and implemented, but `Fixture` was dropped from the app's item-type enum
+ (`items.models.ts:919`) and no Fixtures page exists. It survives only in the DB `itemType` enum.
+- `api+/ai+/csv+/$table.columns.tsx:19` calls `requirePermissions(request, {})` — no module gate on
+ an endpoint that makes a `gpt-4o` call. Headers only, so no data exposure; the cost is unmetered.
+- Export and import are not round-trippable. `Table/components/Download.tsx` builds headers from the
+ grid's column headers. On Parts, 2 of 16 match the import labels, `Part ID` exports
+ `readableIdWithRevision` combined where import wants two columns, `Description` means
+ `item.description` on export and `item.name` on import, and export emits no `Unique ID` at all.
+- `writeSupplierPartLinks` parses minimum order quantity and order multiple with `Number.parseInt`
+ (`import-csv/index.ts:748-751`), flooring fractional values silently.
+
+## Candidate new types
+
+Ordered by onboarding need. "Shape" is what makes each one different from a plain table insert.
+
+### Tier 1 — blocks a greenfield go-live
+
+**Opening stock, including serial and batch numbers.** No path exists. The natural vehicle does not
+work: `generateInventoryCountLines` (`inventory.service.ts:1841`) snapshots one line per bucket
+*that already has `itemLedger` history*, so a new company's count generates zero lines. The working
+primitive is `post-inventory-adjustment`, one call per row, validated by
+`inventoryAdjustmentValidator` (`inventory.models.ts:154`) with `adjustmentType: "Set Quantity"`.
+Shape: not a Kysely transaction over one table but an N-call loop through an edge function that
+writes ledger, cost layers and, when accounting is on, a balanced journal. Cost is taken from
+`itemCost.unitCost`, not from the row — a per-line cost column is not possible without changing the
+adjustment contract.
+
+Serial and batch numbers ride on the same call and need no separate importer. When the caller
+supplies a `trackedEntityId` that has no current quantity, the positive branch inserts a
+`trackedEntity` outright (`post-inventory-adjustment/index.ts:991-1007`) with
+`sourceDocument: "Item"`, `sourceDocumentId: itemId`, and `readableId` taken verbatim from the
+request — so the serial or lot number arrives as a plain string and the importer generates the id.
+Two consequences for the design:
+
+- A serial-tracked item is capped at quantity 1 per call
+ (`inventory.models.ts:187-194`), so N serialized units means N rows and N calls. A batch is one
+ call carrying the lot quantity. Expect an import of a few hundred serials to be a few hundred
+ round trips — batching or a queued run matters here in a way it does not for any existing import.
+- The cap is enforced off `requiresSerialTracking`, a **caller-supplied** flag the forms set. An
+ importer must derive it from the item's `itemTrackingType` itself rather than trust a column, or
+ the guard is trivially bypassed.
+
+`expirationDate` is accepted on the same call and stamped onto the new entity, so shelf-life data
+loads in the same pass.
+
+**Supplier price breaks.** `supplierPartPrice` has existed since
+`20260129150000_quantity-price-breaks.sql`. The item import writes one flat `supplierPart.unitPrice`
+and never touches the child table. Consumed by quote BOM costing and the PO/invoice forms
+(`items.service.ts:5204,5277`), so absent breaks make quoting and purchasing suggestions wrong, not
+just incomplete. Shape: child of `supplierPart`, natural key `(supplierPartId, quantity)` from the
+table's own PK, so no `externalIntegrationMapping` row is needed. `sourceType` has a `Manual Entry`
+value to write. Open: which page mounts it, since there is no price-break list page.
+
+**Locations.** `location` requires `name`, `addressLine1`, `city`, `postalCode` and `timezone`,
+with no default for `timezone`. Shape: plain, except that the timezone column needs either a
+required field or a company-default fallback.
+
+### Tier 2 — closes an obvious symmetry gap
+
+**Services.** `Service` is a first-class item type with a full UI
+(`items/ui/Services/`) and is the only one of the five item types with no import. Shape: reuses the
+existing item path almost verbatim.
+
+**Units of measure, item posting groups, storage types, scrap reasons, departments.** Small
+company-scoped lookups: name (+ code) + active. Shape: create-only with skip-duplicate, exactly the
+`material-property-import.ts` pattern, which is the cheapest template in the codebase.
+
+**Customer part numbers.** `customerPartToItem`, keyed `(customerId, itemId)` with a unique
+constraint on the same pair. Needed before a customer portal or an RFQ conversion means anything.
+
+### Tier 3 — a whole module with no coverage
+
+**Quality.** Eleven tables, zero imports. `gauge` (requires `gaugeId`, `gaugeTypeId`),
+`gaugeType` (name only), and `gaugeCalibrationRecord` (requires `gaugeId`, `dateCalibrated`,
+`inspectionStatus`) are the three that arrive as a spreadsheet from any shop with a calibration
+programme. Shape: `gaugeType` is a trivial lookup, `gauge` is a plain insert with lookups,
+`gaugeCalibrationRecord` is a child keyed on a gauge that must exist first.
+
+### Deliberately excluded
+
+- **A standalone `trackedEntity` import.** Not excluded as a capability — serial and batch loading
+ is required, and is in Tier 1 above. Excluded only as a *separate import type*: the table's
+ required `sourceDocument` / `sourceDocumentId` mean a row has to originate from something, and the
+ adjustment path already supplies `"Item"` and creates the entity. A direct table import would
+ write ledger-less entities that no inventory query would ever see.
+- **Chart of accounts.** Rendered as a tree, so there is no `<Table>` to hang a button on, and
+ `seed-company` already installs a default chart. This is "replace the seeded one", a different
+ and larger problem.
+- **Employees.** Creating one provisions an auth user and sends an invite. Bulk-inviting from a CSV
+ is a different risk class from bulk-inserting rows and should not ride along with this work.
+- **Fixtures.** Dead config: `Fixture` was dropped from the app's item-type enum and there is
+ no Fixtures list page. Removing the registration is cleanup, not coverage.
+ (`fixedAsset` is NOT in this category — Fixed Assets is a live module with a full UI and six
+ routes. Its import is half-wired: models and permissions exist, the edge-function case and the
+ Bulk Import button do not. Finishing it is real coverage, sized with the Tier 2 batch.)
+
+## Column mapping quality — its own workstream
+
+Reported from use: the mapping step misses columns it should obviously catch. It does, and the
+cause is that there is no matching logic beyond string equality.
+
+- Matching is `toLowerCase().trim()` and nothing else, on both the client
+ (`FieldMappings.tsx:114-131`) and the server (`api+/ai+/csv+/$table.columns.tsx:38-66`). A header
+ matches only if it equals the field's single `label` or its field name. `Part Number` matches;
+ `part_number`, `PartNumber`, `Part No.`, `Part #` and `Part Number (Rev)` all miss and fall to the
+ model.
+- A field definition carries one `label` and no synonyms. The same folder already has an alias
+ mechanism — `enumMatch.ts` lets an *enum option* match by label or any of its `aliases` — and it
+ was never applied to column headers. Adding `aliases?: string[]` to the field type and populating
+ it for the common industry spellings is the single highest-yield change here.
+- The skip-the-model condition requires *every* field in `fieldMappings[table]` to have matched, not
+ every required one (`FieldMappings.tsx:133`). `part` has 19 fields and 4 required, so a clean file
+ that simply omits optional supplier and cost columns always calls `gpt-4o`. Gating on required
+ fields would take most real imports off the model path entirely.
+- The client and server run two separate exact-match passes over two different field sources —
+ `fieldMappings` on the client, the zod schema on the server — and the client discards its own
+ result in favour of the server's. Any field the two disagree on is lost, which is the mechanism
+ behind the `revision` defect above. One pass, one source, shared by both.
+- The UI shows one sample value from the first row beside each mapped field
+ (`FieldMappings.tsx:358`), which is what makes a wrong mapping noticeable at all. It does not
+ distinguish a deterministic match from a model guess, so there is no signal about which rows
+ deserve the scrutiny.
+- `gpt-4o` is hardcoded and the endpoint has no permission gate (see Defects).
+
+## Agreed ordering
+
+Foundation, then mapping, then coverage, with opening stock last. Settled 2026-08-30.
+
+| # | Work | Why here |
+|---|---|---|
+| 0 | Fix `revision` being stripped by the route | Live data-correctness bug on `main`; one key in a zod object. Ships on its own branch, not behind this work. |
+| 1 | Registration consistency check | Would have caught `revision`, `mpn`, `fixedAsset` and `fixture` — four bugs, four halves of the same five-edit pattern. Not worth its own PR: folded into the first coverage batch, where the same maps are already being edited. |
+| 2 | Column mapping quality | Adding `aliases` changes the shape of every `fieldMappings` entry. Better to write eight new entries once against the new shape than write and revise them. |
+| 3 | Tier 2 coverage, one batch | Services, units of measure, item posting groups, storage types, scrap reasons, departments, customer part numbers. Seven configs sharing the `material-property-import.ts` template — closer to one piece of work than seven. First visibly useful output. |
+| 4 | Price breaks and locations | Ordinary writes on the existing path, but each has an unresolved design question: no list page to mount price breaks on, and `location.timezone` has no default. |
+| 5 | Opening stock, including serial and batch | Last and separate. The only one that cannot use the existing write path, the only one with a round-trip volume problem, and the only one that posts to the general ledger. |
+
+The live argument is 3 versus 5 — the go-live blocker could reasonably lead. It is held to last
+because 1 and 2 are prerequisites for it regardless: opening stock will be the ninth registration
+and the one whose column mapping matters most. The choice only decides whether the cheap batch ships
+along the way.
+
+## Cross-cutting questions the new types raise
+
+- Every existing import targets one top-level list page. Opening stock and price breaks are
+ child-of-parent data with no list page of their own. Either they get a home page, or the wizard
+ learns to mount inside a detail view — the first such case.
+- The main edge-function path assumes "insert or update one row per CSV row inside one transaction".
+ Opening stock breaks that assumption. It either gets its own path, like material properties did,
+ or the posting is moved behind a batch endpoint.
+- The five-edit registration list above is unenforced, and two of its three failure modes are live
+ on `main`. A type-level or test-level check that `fieldMappings`, `importSchemas` and the edge
+ function's enum agree would prevent the next `revision` before it ships.
diff --git a/.claude/rules/csv-import-system.md b/.claude/rules/csv-import-system.md
index da4d90631c..c1bea3237e 100644
--- a/.claude/rules/csv-import-system.md
+++ b/.claude/rules/csv-import-system.md
@@ -70,18 +70,32 @@ Other exports: `creatableLookups`, and types `CreatableLookup`, `CreatableForm`.
### Tables & permissions
`customer`, `customerContact` → `sales`; `supplier`, `supplierContact` → `purchasing`;
-`part`, `material`, `tool`, `fixture`, `consumable`, `bom`,
+`part`, `material`, `tool`, `fixture`, `consumable`, `service`, `bom`,
`operations`, `partWithMethod`, `materialSubstance`, `materialForm`, `materialFinish`,
-`materialGrade`, `materialType`, `materialDimension` → `parts`;
-`workCenter`, `process` → `production`; `storageUnit` → `inventory`;
-`fixedAsset` → `accounting`.
+`materialGrade`, `materialType`, `materialDimension`, `unitOfMeasure`,
+`itemPostingGroup`, `storageType` → `parts`;
+`workCenter`, `process`, `scrapReason` → `production`; `storageUnit` → `inventory`;
+`department` → `people`; `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`, `storageUnit`, `materialSubstance`, `materialForm`, `materialFinish`,
-`materialGrade`, `materialType`, `materialDimension`. Note it does **not** list
-`fixedAsset` (see Gotchas).
+`partWithMethod`, `part`, `service`, `supplier`, `supplierContact`, `tool`,
+`workCenter`, `process`, `storageUnit`, `unitOfMeasure`, `itemPostingGroup`,
+`storageType`, `scrapReason`, `department`, `materialSubstance`, `materialForm`,
+`materialFinish`, `materialGrade`, `materialType`, `materialDimension`. Note it does
+**not** list `fixedAsset` (see Gotchas).
+
+### Service import (rides the item path)
+
+A `service` is an item — `item.type = "Service"` plus a row in `service` keyed by
+`readableId` — so it is handled by the SAME case as part/tool/fixture/consumable
+rather than a path of its own. Two service-specific rules live in that case:
+`itemTrackingType` is forced to `"Non-Inventory"` before validation (a service can
+never be shipped, received or stocked, so the wizard offers no Tracking Type
+column, and the item validator requires one), and the type-row insert writes the
+legacy `serviceType: "External"` instead of `approved: true`. Both mirror
+`upsertService` in `items.service.ts`; the wizard's replenishment options are
+narrowed to `Buy | Make`, since "Buy and Make" is not a service.
### Storage-unit import (natural-key match + two-pass parent linking)
@@ -104,6 +118,28 @@ same file resolves and an unresolved/cyclic/self parent reports a per-row error
of rolling back the whole import. The DB same-location / no-cycle interceptors
(`20260417000200`) are the final guard; their exceptions are caught per row.
+### Configuration-lookup imports (skip-duplicate, create-only)
+
+`unitOfMeasure`, `itemPostingGroup`, `storageType`, `scrapReason` and `department`
+are small company-scoped config tables filled in once during onboarding. They are
+handled by `import-csv/config-lookup-import.ts` — one `CONFIGS` entry per table,
+one shared walk — with the same **create-only, skip-duplicate** semantics as the
+material lookups below: no `externalIntegrationMapping`, no updates, and no
+`id` column in the wizard, because none of these carries a natural external id.
+
+Dedup mirrors the DB unique constraints, case- and whitespace-insensitively.
+`unitOfMeasure` is the one with TWO of them (`code` and `name`, each unique per
+company), so it contributes two keys and a row colliding on either is reported as
+skipped rather than swallowed by the `ON CONFLICT DO NOTHING` clause. Every other
+table keys on `name` alone.
+
+`department.parentName` resolves in a **second pass** after the inserts commit —
+individual `UPDATE`s outside the insert transaction, so a parent defined further
+down the same file resolves and an unresolved or self-referencing parent reports
+one row error instead of rolling back the batch. Same shape as the storage-unit
+parent pass. `CONFIGS[table].parentField` is what gates it; only `department` sets
+one, and `config-lookup-import.test.ts` pins that.
+
### Material-property imports (skip-duplicate, create-only)
The six material-taxonomy lookups (`materialSubstance`, `materialForm`,
diff --git a/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx b/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx
index ea9d5a360b..761678c4b9 100644
--- a/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx
+++ b/apps/erp/app/modules/inventory/ui/StorageTypes/StorageTypesTable.tsx
@@ -86,6 +86,12 @@ const StorageTypesTable = memo(({ data, count }: StorageTypesTableProps) => {
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "storageType" as const,
+ label: t`Storage Types`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx b/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx
index feadcf9913..44eaa92943 100644
--- a/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx
+++ b/apps/erp/app/modules/items/ui/ItemPostingGroups/ItemPostingGroupsTable.tsx
@@ -91,6 +91,12 @@ const ItemGroupsTable = memo(({ data, count }: ItemGroupsTableProps) => {
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "itemPostingGroup" as const,
+ label: t`Item Groups`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
index f9324d76be..fd9a7591c6 100644
--- a/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
+++ b/apps/erp/app/modules/items/ui/Services/ServicesTable.tsx
@@ -547,6 +547,12 @@ const ServicesTable = memo(({ data, tags, count }: ServicesTableProps) => {
updatedBy: false,
updatedAt: false
}}
+ importCSV={[
+ {
+ table: "service" as const,
+ label: t`Services`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<div className="flex items-center gap-2">
diff --git a/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx b/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
index 10959f8b19..01beeacaf4 100644
--- a/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
+++ b/apps/erp/app/modules/items/ui/UnitOfMeasure/UnitOfMeasuresTable.tsx
@@ -84,6 +84,12 @@ const UnitOfMeasuresTable = memo(
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "unitOfMeasure" as const,
+ label: t`Unit of Measures`
+ }
+ ]}
primaryAction={
permissions.can("create", "parts") && (
<New
diff --git a/apps/erp/app/modules/people/ui/Departments/DepartmentsTable.tsx b/apps/erp/app/modules/people/ui/Departments/DepartmentsTable.tsx
index 32f7d37e55..df0e214df1 100644
--- a/apps/erp/app/modules/people/ui/Departments/DepartmentsTable.tsx
+++ b/apps/erp/app/modules/people/ui/Departments/DepartmentsTable.tsx
@@ -99,6 +99,12 @@ const DepartmentsTable = memo(({ data, count }: DepartmentsTableProps) => {
data={rows}
count={count}
columns={columns}
+ importCSV={[
+ {
+ table: "department" as const,
+ label: t`Departments`
+ }
+ ]}
primaryAction={
permissions.can("create", "people") && (
<New label={t`Department`} to={`new?${params.toString()}`} />
diff --git a/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx b/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx
index f6d9883ff4..ad6316acf5 100644
--- a/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx
+++ b/apps/erp/app/modules/production/ui/ScrapReasons/ScrapReasonsTable.tsx
@@ -76,6 +76,12 @@ const ScrapReasonsTable = memo(({ data, count }: ScrapReasonsTableProps) => {
data={data}
columns={columns}
count={count}
+ importCSV={[
+ {
+ table: "scrapReason" as const,
+ label: t`Scrap Reasons`
+ }
+ ]}
primaryAction={
permissions.can("create", "production") && (
<New
diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.ts
index 55aef38d53..dec58155db 100644
--- a/apps/erp/app/modules/shared/imports.models.ts
+++ b/apps/erp/app/modules/shared/imports.models.ts
@@ -15,6 +15,9 @@ const methodType = [
"Make to Order"
] as const;
const itemReplenishmentSystems = ["Buy", "Make", "Buy and Make"] as const;
+// Services are either bought from a supplier (outside processing) or performed
+// in-house — they are never both.
+const serviceReplenishmentSystems = ["Buy", "Make"] as const;
const itemTrackingTypes = [
"Inventory",
"Non-Inventory",
@@ -1265,6 +1268,69 @@ export const fieldMappings = {
...itemPurchasingImportFields,
...itemCostImportFields
},
+ service: {
+ id: {
+ label: "Unique ID",
+ required: true,
+ type: "string"
+ },
+ readableId: {
+ label: "Service ID",
+ required: true,
+ type: "string"
+ },
+ revision: {
+ label: "Revision",
+ required: true,
+ type: "string",
+ default: "0"
+ },
+ name: {
+ label: "Description",
+ required: true,
+ type: "string"
+ },
+ active: {
+ label: "Active",
+ required: false,
+ type: "boolean"
+ },
+ replenishmentSystem: {
+ label: "Replenishment System",
+ required: false,
+ type: "enum",
+ enumData: {
+ description:
+ "Whether the service is bought from a supplier (outside processing) or performed in-house",
+ options: serviceReplenishmentSystems,
+ default: "Buy"
+ }
+ },
+ defaultMethodType: {
+ label: "Default Method",
+ required: false,
+ type: "enum",
+ enumData: {
+ description:
+ "How the service is fulfilled when it is required in production",
+ options: methodType,
+ default: "Purchase to Order"
+ }
+ },
+ unitOfMeasureCode: {
+ label: "Unit of Measure",
+ required: false,
+ type: "enum",
+ enumData: {
+ description: "The unit of measure of the service",
+ fetcher: unitOfMeasureFetcher,
+ default: "EA"
+ }
+ },
+ ...supplierPartImportFields,
+ ...itemPurchasingImportFields,
+ ...itemCostImportFields
+ },
material: {
id: {
label: "Unique ID",
@@ -1614,6 +1680,56 @@ export const fieldMappings = {
type: "boolean"
}
},
+ unitOfMeasure: {
+ code: {
+ label: "Code",
+ required: true,
+ type: "string"
+ },
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ }
+ },
+ itemPostingGroup: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ description: {
+ label: "Description",
+ required: false,
+ type: "string"
+ }
+ },
+ storageType: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ }
+ },
+ scrapReason: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ }
+ },
+ department: {
+ name: {
+ label: "Name",
+ required: true,
+ type: "string"
+ },
+ parentName: {
+ label: "Parent Department",
+ required: false,
+ type: "string"
+ }
+ },
fixedAsset: {
name: {
label: "Name",
@@ -1805,6 +1921,12 @@ export const importPermissions: Record<keyof typeof fieldMappings, string> = {
workCenter: "production",
process: "production",
storageUnit: "inventory",
+ service: "parts",
+ unitOfMeasure: "parts",
+ itemPostingGroup: "accounting",
+ storageType: "parts",
+ scrapReason: "production",
+ department: "people",
fixedAsset: "accounting",
materialSubstance: "parts",
materialForm: "parts",
@@ -2467,6 +2589,114 @@ export const importSchemas: Record<
.optional()
.describe("Whether the storage unit is active (true/false)")
}),
+ service: z.object({
+ id: z
+ .string()
+ .min(1, { message: "ID is required" })
+ .describe("The unique ID of the service"),
+ readableId: z
+ .string()
+ .min(1, { message: "Service ID is required" })
+ .describe("The service ID shown throughout the app"),
+ revision: z.string().optional().describe("The revision of the service"),
+ name: z
+ .string()
+ .min(1, { message: "Description is required" })
+ .describe("The description of the service"),
+ active: z
+ .string()
+ .optional()
+ .describe("Whether the service is active (true/false)"),
+ replenishmentSystem: z
+ .string()
+ .optional()
+ .describe(
+ "Whether the service is bought from a supplier or performed in-house"
+ ),
+ defaultMethodType: z
+ .string()
+ .optional()
+ .describe("How the service is fulfilled when required in production"),
+ unitOfMeasureCode: z
+ .string()
+ .optional()
+ .describe("The unit of measure code of the service"),
+ supplierId: z
+ .string()
+ .optional()
+ .describe("The supplier that performs the service"),
+ supplierPartId: z
+ .string()
+ .optional()
+ .describe("The supplier's own identifier for the service"),
+ supplierUnitOfMeasureCode: z
+ .string()
+ .optional()
+ .describe("How the supplier sells the service"),
+ minimumOrderQuantity: z
+ .string()
+ .optional()
+ .describe("The minimum order quantity for the service"),
+ orderMultiple: z
+ .string()
+ .optional()
+ .describe("The order multiple for the service"),
+ conversionFactor: z
+ .string()
+ .optional()
+ .describe("The supplier-to-internal unit conversion factor"),
+ unitPrice: z
+ .string()
+ .optional()
+ .describe("The supplier's unit price for the service"),
+ leadTime: z
+ .string()
+ .optional()
+ .describe("The lead time in days for the service"),
+ unitCost: z.string().optional().describe("The unit cost of the service")
+ }),
+ unitOfMeasure: z.object({
+ code: z
+ .string()
+ .min(1, { message: "Code is required" })
+ .describe("The short code for the unit of measure (e.g. EA, BOX, KG)"),
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the unit of measure")
+ }),
+ itemPostingGroup: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the item posting group"),
+ description: z
+ .string()
+ .optional()
+ .describe("The description of the item posting group")
+ }),
+ storageType: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the storage type (e.g. Cold Storage, Hazardous)")
+ }),
+ scrapReason: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the scrap reason")
+ }),
+ department: z.object({
+ name: z
+ .string()
+ .min(1, { message: "Name is required" })
+ .describe("The name of the department"),
+ parentName: z
+ .string()
+ .optional()
+ .describe("The name of the parent department, if any")
+ }),
fixedAsset: z.object({
name: z
.string()
diff --git a/packages/database/supabase/functions/import-csv/config-lookup-import.test.ts b/packages/database/supabase/functions/import-csv/config-lookup-import.test.ts
new file mode 100644
index 0000000000..bf4a7504dd
--- /dev/null
+++ b/packages/database/supabase/functions/import-csv/config-lookup-import.test.ts
@@ -0,0 +1,82 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import { CONFIGS } from "./config-lookup-import.ts";
+
+Deno.test("unit of measure requires both a code and a name", () => {
+ assertEquals(
+ CONFIGS.unitOfMeasure.validate({ code: "", name: "Each" }),
+ "Code is required"
+ );
+ assertEquals(
+ CONFIGS.unitOfMeasure.validate({ code: "EA", name: " " }),
+ "Name is required"
+ );
+ assertEquals(CONFIGS.unitOfMeasure.validate({ code: "EA", name: "Each" }), null);
+});
+
+Deno.test("unit of measure enforces the same lengths the form does", () => {
+ assertEquals(
+ CONFIGS.unitOfMeasure.validate({ code: "X".repeat(11), name: "Each" }),
+ "Code must be 10 characters or fewer"
+ );
+ assertEquals(
+ CONFIGS.unitOfMeasure.validate({ code: "EA", name: "X".repeat(51) }),
+ "Name must be 50 characters or fewer"
+ );
+});
+
+// unitOfMeasure has UNIQUE (code, companyId) AND UNIQUE (name, companyId).
+// Dedup on the code alone would let a row with a fresh code but a taken name
+// through, where ON CONFLICT DO NOTHING would drop it with no reported reason.
+Deno.test("unit of measure dedups on code and name", () => {
+ const existing = CONFIGS.unitOfMeasure.keysOfExisting({
+ name: "Each",
+ code: "EA"
+ });
+ const sameNameNewCode = CONFIGS.unitOfMeasure.keysOf({
+ code: "EACH",
+ name: "each"
+ });
+ assertEquals(
+ sameNameNewCode.some((k) => existing.includes(k)),
+ true
+ );
+});
+
+Deno.test("name-keyed lookups match case- and whitespace-insensitively", () => {
+ for (const table of ["storageType", "scrapReason", "department"] as const) {
+ assertEquals(
+ CONFIGS[table].keysOf({ name: " Cold Storage " }),
+ CONFIGS[table].keysOfExisting({ name: "cold storage" })
+ );
+ }
+});
+
+Deno.test("optional columns are omitted rather than written blank", () => {
+ assertEquals(CONFIGS.itemPostingGroup.values({ name: "Finished Goods" }), {
+ name: "Finished Goods"
+ });
+ assertEquals(
+ CONFIGS.itemPostingGroup.values({
+ name: "Finished Goods",
+ description: " "
+ }),
+ { name: "Finished Goods" }
+ );
+ assertEquals(
+ CONFIGS.itemPostingGroup.values({
+ name: " Finished Goods ",
+ description: " Sellable "
+ }),
+ { name: "Finished Goods", description: "Sellable" }
+ );
+});
+
+// Only `department` carries a parent; the second pass in `importConfigLookups`
+// is gated on this field, so a stray one would start resolving parent names
+// against a table that has no parent column.
+Deno.test("department is the only table with a parent pass", () => {
+ const withParent = (
+ Object.keys(CONFIGS) as Array<keyof typeof CONFIGS>
+ ).filter((table) => CONFIGS[table].parentField);
+ assertEquals(withParent, ["department"]);
+});
diff --git a/packages/database/supabase/functions/import-csv/config-lookup-import.ts b/packages/database/supabase/functions/import-csv/config-lookup-import.ts
new file mode 100644
index 0000000000..fc3ea06737
--- /dev/null
+++ b/packages/database/supabase/functions/import-csv/config-lookup-import.ts
@@ -0,0 +1,283 @@
+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 }>;
+};
+
+// Company-scoped configuration lookups: small, flat, name-keyed tables a
+// customer fills in once during onboarding. They share create-only,
+// skip-duplicate semantics with the material-taxonomy imports
+// (`material-property-import.ts`) rather than the id-mapped upsert the
+// workCenter/process/item paths use, because none of them carries a natural
+// external id — a customer's UoM list is a column of codes, not a keyed
+// export. Every one of these tables has a UNIQUE (name, companyId) constraint,
+// so a duplicate row would otherwise abort the whole transaction instead of
+// reporting one skipped row.
+export type ConfigLookupTable =
+ | "unitOfMeasure"
+ | "itemPostingGroup"
+ | "storageType"
+ | "scrapReason"
+ | "department";
+
+const norm = (s: string | undefined) => (s ?? "").trim().toLowerCase();
+
+const requireName = (r: Rec) => (!r.name?.trim() ? "Name is required" : null);
+
+type TableConfig = {
+ // Row-level validation. Returns a reason string, or null when the row is fine.
+ validate: (r: Rec) => string | null;
+ // The natural keys used for both in-file dedup and match-against-existing.
+ // A table with two unique constraints yields two keys, so a row colliding on
+ // either is reported rather than dropped by the ON CONFLICT clause.
+ keysOf: (r: Rec) => string[];
+ // The same keys, read off a row already in the database.
+ keysOfExisting: (r: {
+ name: string | null;
+ code?: string | null;
+ }) => string[];
+ // The columns to read off the mapped record, beyond the audit fields.
+ values: (r: Rec) => Record<string, string>;
+ // Set when the table carries a self-referencing parent applied in a second
+ // pass (see `applyParents` below).
+ parentField?: "parentDepartmentId";
+};
+
+// Exported for `config-lookup-import.test.ts` — the validation rules and
+// dedup keys are the parts that fail silently.
+export const CONFIGS: Record<ConfigLookupTable, TableConfig> = {
+ unitOfMeasure: {
+ validate: (r) => {
+ if (!r.code?.trim()) return "Code is required";
+ if (r.code.trim().length > 10)
+ return "Code must be 10 characters or fewer";
+ if (!r.name?.trim()) return "Name is required";
+ if (r.name.trim().length > 50)
+ return "Name must be 50 characters or fewer";
+ return null;
+ },
+ // `code` and `name` are BOTH unique per company, so both are dedup keys —
+ // importing "Each" against an existing EA/Each is a skip with a reason,
+ // not a row silently swallowed by ON CONFLICT.
+ keysOf: (r) => [`c:${norm(r.code)}`, `n:${norm(r.name)}`],
+ keysOfExisting: (r) => [
+ `c:${norm(r.code ?? "")}`,
+ `n:${norm(r.name ?? "")}`
+ ],
+ values: (r) => ({ code: r.code.trim(), name: r.name.trim() })
+ },
+ itemPostingGroup: {
+ validate: (r) => {
+ const reason = requireName(r);
+ if (reason) return reason;
+ if (r.name.trim().length > 255)
+ return "Name must be 255 characters or fewer";
+ return null;
+ },
+ keysOf: (r) => [norm(r.name)],
+ keysOfExisting: (r) => [norm(r.name ?? "")],
+ values: (r) => {
+ const values: Record<string, string> = { name: r.name.trim() };
+ if (r.description?.trim()) values.description = r.description.trim();
+ return values;
+ }
+ },
+ storageType: {
+ validate: requireName,
+ keysOf: (r) => [norm(r.name)],
+ keysOfExisting: (r) => [norm(r.name ?? "")],
+ values: (r) => ({ name: r.name.trim() })
+ },
+ scrapReason: {
+ validate: requireName,
+ keysOf: (r) => [norm(r.name)],
+ keysOfExisting: (r) => [norm(r.name ?? "")],
+ values: (r) => ({ name: r.name.trim() })
+ },
+ department: {
+ validate: requireName,
+ keysOf: (r) => [norm(r.name)],
+ keysOfExisting: (r) => [norm(r.name ?? "")],
+ values: (r) => ({ name: r.name.trim() }),
+ parentField: "parentDepartmentId"
+ }
+};
+
+const loadExisting = async (
+ trx: Kysely<DB> | Transaction<DB>,
+ table: ConfigLookupTable,
+ companyId: string
+) => {
+ const rows = await trx
+ .selectFrom(table)
+ .select(table === "unitOfMeasure" ? ["id", "name", "code"] : ["id", "name"])
+ .where("companyId", "=", companyId)
+ .execute();
+ return rows as Array<{ id: string; name: string | null; code?: string }>;
+};
+
+// Parents are applied AFTER every insert, as individual UPDATEs outside the
+// insert transaction, so a parent defined further down the same file still
+// resolves and an unresolved or self-referencing parent reports one row error
+// instead of rolling the whole import back. Mirrors the storage-unit parent
+// pass in `index.ts`.
+const applyParents = async (
+ db: Kysely<DB>,
+ table: ConfigLookupTable,
+ parentField: "parentDepartmentId",
+ pending: Array<{ row: number; name: string; parentName: string }>,
+ companyId: string,
+ summary: Summary
+) => {
+ if (pending.length === 0) return;
+
+ const idsByName = new Map<string, string>();
+ for (const row of await loadExisting(db, table, companyId)) {
+ idsByName.set(norm(row.name ?? ""), row.id);
+ }
+
+ for (const { row, name, parentName } of pending) {
+ const id = idsByName.get(norm(name));
+ if (!id) continue;
+
+ if (norm(parentName) === norm(name)) {
+ summary.errors.push({ row, reason: "A record cannot be its own parent" });
+ continue;
+ }
+
+ const parentId = idsByName.get(norm(parentName));
+ if (!parentId) {
+ summary.errors.push({
+ row,
+ reason: `Parent "${parentName}" was not found`
+ });
+ continue;
+ }
+
+ try {
+ await db
+ .updateTable(table)
+ .set({ [parentField]: parentId } as never)
+ .where("id", "=", id)
+ .where("companyId", "=", companyId)
+ .execute();
+ } catch (err) {
+ summary.errors.push({ row, reason: (err as Error).message });
+ }
+ }
+};
+
+export async function importConfigLookups(
+ db: Kysely<DB>,
+ {
+ table,
+ mappedRecords,
+ companyId,
+ userId,
+ summary
+ }: {
+ table: ConfigLookupTable;
+ mappedRecords: Rec[];
+ companyId: string;
+ userId: string;
+ summary: Summary;
+ }
+) {
+ const config = CONFIGS[table];
+ const pendingParents: Array<{
+ row: number;
+ name: string;
+ parentName: string;
+ }> = [];
+
+ await db.transaction().execute(async (trx) => {
+ const existingKeys = new Set(
+ (await loadExisting(trx, table, companyId)).flatMap(config.keysOfExisting)
+ );
+
+ 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;
+ }
+
+ for (const key of keys) seenKeys.add(key);
+ accepted.push(record);
+
+ if (config.parentField && record.parentName?.trim()) {
+ pendingParents.push({
+ row: rowIndex,
+ name: record.name.trim(),
+ parentName: record.parentName.trim()
+ });
+ }
+ }
+
+ console.log({
+ function: "import-config-lookups",
+ table,
+ totalRecords: mappedRecords.length,
+ accepted: accepted.length,
+ skipped: summary.skipped.length,
+ errors: summary.errors.length
+ });
+
+ if (accepted.length > 0) {
+ const now = new Date().toISOString();
+ const inserted = await trx
+ .insertInto(table)
+ .values(
+ accepted.map(
+ (r) =>
+ ({
+ ...config.values(r),
+ companyId,
+ createdBy: userId,
+ createdAt: now
+ }) as never
+ )
+ )
+ .onConflict((oc) => oc.doNothing())
+ .returning(["id"])
+ .execute();
+ summary.inserted += inserted.length;
+ }
+ });
+
+ if (config.parentField) {
+ await applyParents(
+ db,
+ table,
+ config.parentField,
+ pendingParents,
+ companyId,
+ summary
+ );
+ }
+}
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 1512e6d1ac..bfa6452c5d 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -10,6 +10,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 { importConfigLookups } from "./config-lookup-import.ts";
import { importMaterialProperties } from "./material-property-import.ts";
import { importMethods } from "./method-import.ts";
@@ -28,12 +29,18 @@ const importCsvValidator = z.object({
"operations",
"partWithMethod",
"part",
+ "service",
"supplier",
"supplierContact",
"tool",
"workCenter",
"process",
"storageUnit",
+ "unitOfMeasure",
+ "itemPostingGroup",
+ "storageType",
+ "scrapReason",
+ "department",
"materialSubstance",
"materialForm",
"materialFinish",
@@ -1434,11 +1441,21 @@ serve(async (req: Request) => {
case "consumable":
case "tool":
case "fixture":
+ case "service":
case "part": {
const getExternalId = (id: string) => {
return `${table}:${id}`;
};
+ // A service can never be shipped, received or stocked, so the wizard
+ // does not offer a Tracking Type column for it. The item validator
+ // below requires one, and `upsertService` hard-codes the same value.
+ if (table === "service") {
+ for (const record of mappedRecords) {
+ record.itemTrackingType = "Non-Inventory";
+ }
+ }
+
const externalIdMap = await getCsvExternalIdMap("item", companyId);
const readableIds = new Set();
@@ -1865,10 +1882,19 @@ serve(async (req: Request) => {
userId
);
- if (["part", "fixture", "tool", "consumable"].includes(table)) {
+ if (
+ ["part", "fixture", "tool", "consumable", "service"].includes(
+ table
+ )
+ ) {
const specificInserts = insertedItems.map((item) => ({
id: item.readableId,
- approved: true,
+ // `service` has its own `approved` default and a legacy
+ // NOT NULL `serviceType` the UI no longer surfaces —
+ // `upsertService` writes "External" for the same reason.
+ ...(table === "service"
+ ? { serviceType: "External" }
+ : { approved: true }),
companyId,
createdAt: new Date().toISOString(),
createdBy: userId,
@@ -2884,6 +2910,20 @@ serve(async (req: Request) => {
});
break;
}
+ case "unitOfMeasure":
+ case "itemPostingGroup":
+ case "storageType":
+ case "scrapReason":
+ case "department": {
+ await importConfigLookups(db, {
+ table,
+ mappedRecords,
+ companyId,
+ userId,
+ summary,
+ });
+ break;
+ }
case "materialSubstance":
case "materialForm":
case "materialFinish":