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
refactor(import): drop Part-with-Method import; server-authoritative results
sidgaikwad200ad3dd9c6b
diff --git a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsxindex 77dd27a68c..b9a6ce4f3a 100644--- a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx+++ b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx@@ -46,12 +46,17 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {if (fetcher.data?.success === true) {const inserted = fetcher.data.inserted ?? 0;const updated = fetcher.data.updated ?? 0;- const skipped = fetcher.data.skipped ?? 0;+ const errorCount = fetcher.data.errors?.length ?? 0;+ const skippedCount = fetcher.data.skipped?.length ?? 0;// The results modal renders next (see the early return below); just// surface a quick toast summary here.- if (skipped > 0) {+ if (errorCount > 0) {toast.info(- `Imported ${inserted}, updated ${updated}, skipped ${skipped} row(s).`+ `Imported ${inserted}, updated ${updated} — ${errorCount} row(s) need fixing.`+ );+ } else if (skippedCount > 0) {+ toast.info(+ `Imported ${inserted}, updated ${updated}, skipped ${skippedCount} row(s).`);} else {toast.success(`Imported ${inserted}, updated ${updated}.`);@@ -71,17 +76,14 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {// After a successful import, swap the wizard for the bigger results modal:// every parsed row marked valid/error, filterable, with an errors-only CSV// download (firstRows holds the full file, so no re-parse needed).- if (fetcher.data?.success === true && firstRows && fileColumns) {+ if (fetcher.data?.success === true && fileColumns) {return (<ImportResultsModaltable={table}- result={{- inserted: fetcher.data.inserted ?? 0,- updated: fetcher.data.updated ?? 0,- skipped: fetcher.data.skipped ?? 0,- errors: fetcher.data.errors ?? []- }}- rows={firstRows}+ inserted={fetcher.data.inserted ?? 0}+ updated={fetcher.data.updated ?? 0}+ errors={fetcher.data.errors ?? []}+ skipped={fetcher.data.skipped ?? []}columns={fileColumns}onClose={onClose}/>diff --git a/apps/erp/app/components/ImportCSVModal/ImportResultsModal.tsx b/apps/erp/app/components/ImportCSVModal/ImportResultsModal.tsxindex 7257664780..de5df895ea 100644--- a/apps/erp/app/components/ImportCSVModal/ImportResultsModal.tsx+++ b/apps/erp/app/components/ImportCSVModal/ImportResultsModal.tsx@@ -1,5 +1,4 @@import {- Badge,Button,Count,cn,@@ -16,70 +15,58 @@ import {} from "@carbon/react";import { Trans, useLingui } from "@lingui/react/macro";import Papa from "papaparse";-import { useMemo, useState } from "react";-import { LuCircleCheck, LuCircleX, LuDownload } from "react-icons/lu";+import { useState } from "react";+import { LuCircleCheck, LuCircleX, LuDownload, LuInfo } from "react-icons/lu";-type ImportResult = {- inserted: number;- updated: number;- skipped: number;- errors: Array<{ row: number; reason: string }>;+// A row the importer did not insert/update. `values` holds the original CSV cells+// (keyed by the user's headers) exactly as the server parsed them — so the modal+// renders the real rows without re-parsing the file client-side.+type RowIssue = {+ row: number;+ reason: string;+ values: Record<string, string>;};-type RowFilter = "all" | "valid" | "errors";-type ImportResultsModalProps = {table: string;- result: ImportResult;- // Every parsed CSV data row, keyed by column header (the wizard's `firstRows`,- // which holds the full file — not a sample). Row index aligns with the edge- // function's per-row `errors[].row`, so we can mark each row valid/error.- rows: Record<string, string>[];+ inserted: number;+ updated: number;+ // Rows the user should fix and re-import (validation / missing required data).+ errors: RowIssue[];+ // Rows intentionally not written (duplicates, already-existing) — informational.+ skipped: RowIssue[];columns: string[];onClose: () => void;};+type Bucket = "errors" | "skipped";+export const ImportResultsModal = ({table,- result,- rows,+ inserted,+ updated,+ errors,+ skipped,columns,onClose}: ImportResultsModalProps) => {const { t } = useLingui();- const [filter, setFilter] = useState<RowFilter>("all");-- const reasonByRow = useMemo(() => {- const map = new Map<number, string>();- for (const error of result.errors ?? []) map.set(error.row, error.reason);- return map;- }, [result.errors]);-- const classified = useMemo(- () =>- rows.map((data, index) => ({- index,- data,- reason: reasonByRow.get(index),- isError: reasonByRow.has(index)- })),- [rows, reasonByRow]+ const hasErrors = errors.length > 0;+ const hasSkipped = skipped.length > 0;+ const allClean = !hasErrors && !hasSkipped;+ const [bucket, setBucket] = useState<Bucket>(+ hasErrors ? "errors" : "skipped");- const errorCount = reasonByRow.size;- const validCount = rows.length - errorCount;+ const rows = bucket === "errors" ? errors : skipped;- const visibleRows = classified.filter((row) =>- filter === "errors" ? row.isError : filter === "valid" ? !row.isError : true- );-- // The CSV is already uploaded; the user just needs the failed rows back to fix- // and re-import. Re-emit the original column values for error rows only.+ // Only the fixable rows go into the "fix and re-import" download — duplicates and+ // already-existing rows aren't something the user re-imports.const downloadInvalidRows = () => {- const invalid = classified- .filter((row) => row.isError)- .map((row) => columns.map((column) => row.data[column] ?? ""));- const csv = Papa.unparse({ fields: columns, data: invalid });+ const data = errors.map((issue) =>+ columns.map((column) => issue.values[column] ?? "")+ );+ const csv = Papa.unparse({ fields: columns, data });const blob = new Blob([csv], { type: "text/csv;charset=utf-8;" });const url = URL.createObjectURL(blob);const link = document.createElement("a");@@ -106,119 +93,127 @@ export const ImportResultsModal = ({<Trans>Import results</Trans></ModalTitle><ModalDescription>- {errorCount > 0 ? (+ {allClean ? (<Trans>- {result.inserted} inserted, {result.updated} updated —{" "}- {errorCount} row(s) need fixing.+ All rows imported — {inserted} inserted, {updated} updated.</Trans>) : (<Trans>- All {rows.length} row(s) imported — {result.inserted} inserted,{" "}- {result.updated} updated.+ {inserted} inserted, {updated} updated, {errors.length} need+ fixing, {skipped.length} skipped.</Trans>)}</ModalDescription></ModalHeader><ModalBody className="min-w-0">- <div className="flex items-center justify-between gap-4">- <Tabs- value={filter}- onValueChange={(value) => setFilter(value as RowFilter)}- >- <TabsList>- <TabsTrigger value="all" className="gap-1.5">- <Trans>All</Trans>- <Count count={rows.length} />- </TabsTrigger>- <TabsTrigger value="valid" className="gap-1.5">- <Trans>Valid</Trans>- <Count count={validCount} />- </TabsTrigger>- <TabsTrigger value="errors" className="gap-1.5">- <Trans>Errors</Trans>- <Count count={errorCount} />- </TabsTrigger>- </TabsList>- </Tabs>- {errorCount > 0 && (- <Button- variant="secondary"- size="md"- leftIcon={<LuDownload />}- onClick={downloadInvalidRows}- >- <Trans>Download {errorCount} invalid row(s)</Trans>- </Button>- )}- </div>-- <div className="mt-4 w-full min-w-0 max-h-[420px] overflow-auto rounded-md border border-border">- <table className="w-full border-collapse text-sm">- <thead className="sticky top-0 z-10 bg-card">- <tr className="border-b border-border text-left text-muted-foreground">- <th className="w-10 px-3 py-2 font-medium" />- {columns.map((column) => (- <th- key={column}- className="whitespace-nowrap px-3 py-2 font-medium"- >- {column}- </th>- ))}- <th className="whitespace-nowrap px-3 py-2 font-medium">- <Trans>Result</Trans>- </th>- </tr>- </thead>- <tbody>- {visibleRows.map((row) => (- <tr- key={row.index}- className={cn(- "border-b border-border last:border-0",- row.isError && "bg-destructive/5"- )}+ {allClean ? (+ <div className="flex flex-col items-center justify-center gap-2 py-10 text-center">+ <LuCircleCheck className="h-8 w-8 text-emerald-500" />+ <p className="text-sm text-muted-foreground">+ <Trans>Every row was imported successfully.</Trans>+ </p>+ </div>+ ) : (+ <>+ <div className="flex items-center justify-between gap-4">+ <Tabs+ value={bucket}+ onValueChange={(value) => setBucket(value as Bucket)}+ >+ <TabsList>+ <TabsTrigger value="errors" className="gap-1.5">+ <Trans>Needs fixing</Trans>+ <Count count={errors.length} />+ </TabsTrigger>+ <TabsTrigger value="skipped" className="gap-1.5">+ <Trans>Skipped</Trans>+ <Count count={skipped.length} />+ </TabsTrigger>+ </TabsList>+ </Tabs>+ {hasErrors && (+ <Button+ variant="secondary"+ size="md"+ leftIcon={<LuDownload />}+ onClick={downloadInvalidRows}>- <td className="px-3 py-2 align-top">- {row.isError ? (- <LuCircleX className="h-4 w-4 text-destructive" />- ) : (- <LuCircleCheck className="h-4 w-4 text-emerald-500" />- )}- </td>- {columns.map((column) => (- <td- key={column}- className="max-w-48 truncate px-3 py-2 align-top"- title={row.data[column]}+ <Trans>Download {errors.length} row(s) to fix</Trans>+ </Button>+ )}+ </div>++ <div className="mt-4 w-full min-w-0 max-h-[420px] overflow-auto rounded-md border border-border">+ <table className="w-full border-collapse text-sm">+ <thead className="sticky top-0 z-10 bg-card">+ <tr className="border-b border-border text-left text-muted-foreground">+ <th className="w-10 px-3 py-2 font-medium" />+ {columns.map((column) => (+ <th+ key={column}+ className="whitespace-nowrap px-3 py-2 font-medium"+ >+ {column}+ </th>+ ))}+ <th className="whitespace-nowrap px-3 py-2 font-medium">+ <Trans>Reason</Trans>+ </th>+ </tr>+ </thead>+ <tbody>+ {rows.map((row) => (+ <tr+ key={row.row}+ className={cn(+ "border-b border-border last:border-0",+ bucket === "errors" && "bg-destructive/5"+ )}>- {row.data[column]}- </td>+ <td className="px-3 py-2 align-top">+ {bucket === "errors" ? (+ <LuCircleX className="h-4 w-4 text-destructive" />+ ) : (+ <LuInfo className="h-4 w-4 text-muted-foreground" />+ )}+ </td>+ {columns.map((column) => (+ <td+ key={column}+ className="max-w-48 truncate px-3 py-2 align-top"+ title={row.values[column]}+ >+ {row.values[column]}+ </td>+ ))}+ <td className="px-3 py-2 align-top">+ <span+ className={cn(+ bucket === "errors"+ ? "text-destructive"+ : "text-muted-foreground"+ )}+ >+ {row.reason}+ </span>+ </td>+ </tr>))}- <td className="px-3 py-2 align-top">- {row.isError ? (- <span className="text-destructive">{row.reason}</span>- ) : (- <Badge variant="secondary">- <Trans>Imported</Trans>- </Badge>- )}- </td>- </tr>- ))}- {visibleRows.length === 0 && (- <tr>- <td- colSpan={columns.length + 2}- className="px-3 py-8 text-center text-muted-foreground"- >- <Trans>No rows to show.</Trans>- </td>- </tr>- )}- </tbody>- </table>- </div>+ {rows.length === 0 && (+ <tr>+ <td+ colSpan={columns.length + 2}+ className="px-3 py-8 text-center text-muted-foreground"+ >+ <Trans>No rows here.</Trans>+ </td>+ </tr>+ )}+ </tbody>+ </table>+ </div>+ </>+ )}</ModalBody><ModalFooter><Button onClick={onClose}>{t`Done`}</Button>diff --git a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsxindex aac0511e4e..d04807f29e 100644--- a/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartsTable.tsx@@ -578,10 +578,6 @@ const PartsTable = memo(({ data, tags, count }: PartsTableProps) => {{table: "operations" as const,label: "Operations"- },- {- table: "partWithMethod" as const,- label: "Parts with Methods"}]}primaryAction={diff --git a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsxindex 9c68b010c1..2505e45df3 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolsTable.tsx@@ -566,10 +566,6 @@ const ToolsTable = memo(({ data, tags, count }: ToolsTableProps) => {{table: "operations" as const,label: "Operations"- },- {- table: "partWithMethod" as const,- label: "Parts with Methods"}]}primaryAction={diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.tsindex 43ee784b69..7e7f838b2b 100644--- a/apps/erp/app/modules/shared/imports.models.ts+++ b/apps/erp/app/modules/shared/imports.models.ts@@ -156,13 +156,12 @@ const itemCostImportFields = {}} as const;-// Method (BOM/BOP) import — one row-type-multiplexed format (ADR-0002). A single-// CSV may carry six row kinds discriminated by `Row Type`; each non-PART row names-// its parent part explicitly, so multi-level BOMs need no positional Level column.-// The combined file is the union of every group below (wide, mostly-empty rows);-// the focused BOM / Operations files carry a subset. Field-level `required` here is-// kept loose because a column's necessity depends on the row kind — the authoritative-// per-row validation lives in the import-csv edge function (ADR-0001).+// Method (BOM/BOP) import — one row-type-multiplexed format (ADR-0002). The focused+// BOM file carries BOM rows; the Operations file carries BOP/STEP/TOOL/PARAM rows,+// each naming its parent part explicitly so multi-level BOMs need no positional Level+// column. Field-level `required` here is kept loose because a column's necessity+// depends on the row kind — the authoritative per-row validation lives in the+// import-csv edge function (ADR-0001).const methodRowTypes = ["PART", "BOM", "BOP", "STEP", "TOOL", "PARAM"] as const;const unitOfMeasureFetcher = async (@@ -451,8 +450,7 @@ const methodParamFields = {}} as const;-// Part import fields, hoisted so the combined `partWithMethod` entry can reuse the-// exact same columns the standalone `part` import uses.+// Part import fields for the standalone `part` import.const partImportFields = {id: {label: "Unique ID",@@ -1375,19 +1373,6 @@ export const fieldMappings = {...methodToolFields,...methodParamFields},- // Combined file — creates parts and their full BOM + BOP together. The union of- // every row type's columns, so most cells are blank on any given row.- partWithMethod: {- ...partImportFields,- ...methodParentKeyFields,- rowType: { ...methodParentKeyFields.rowType, required: true },- ...methodOpNoField,- ...methodBomFields,- ...methodBopFields,- ...methodStepFields,- ...methodToolFields,- ...methodParamFields- },workCenter: {id: {label: "Unique ID",@@ -1585,7 +1570,6 @@ export const importPermissions: Record<keyof typeof fieldMappings, string> = {material: "parts",bom: "parts",operations: "parts",- partWithMethod: "parts",tool: "parts",fixture: "parts",consumable: "parts",@@ -1642,25 +1626,6 @@ const methodOpSchema = {paramKey: z.string().optional(),paramValue: z.string().optional()};-const methodPartSchema = {- id: z.string().optional(),- readableId: z.string().optional(),- revision: z.string().optional(),- name: z.string().optional(),- active: z.string().optional(),- replenishmentSystem: z.string().optional(),- defaultMethodType: z.string().optional(),- itemTrackingType: z.string().optional(),- supplierId: z.string().optional(),- supplierPartId: z.string().optional(),- supplierUnitOfMeasureCode: z.string().optional(),- minimumOrderQuantity: z.string().optional(),- orderMultiple: z.string().optional(),- conversionFactor: z.string().optional(),- unitPrice: z.string().optional(),- leadTime: z.string().optional()-};-export const importSchemas: Record<keyof typeof fieldMappings,z.ZodObject<any>@@ -2105,16 +2070,6 @@ export const importSchemas: Record<.min(1, { message: "Op No is required" }).describe("The operation number, unique within the parent part")}),- partWithMethod: z.object({- ...methodPartSchema,- ...methodParentKeySchema,- rowType: z- .string()- .min(1, { message: "Row Type is required" })- .describe("PART, BOM, BOP, STEP, TOOL, or PARAM"),- ...methodBomSchema,- ...methodOpSchema- }),workCenter: z.object({id: z.string()diff --git a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx b/apps/erp/app/routes/x+/shared+/import.$tableId.tsxindex 8a976c3bde..38483856db 100644--- a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx+++ b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx@@ -54,11 +54,16 @@ export async function action({ request, params }: ActionFunctionArgs) {};}+ type RowIssue = {+ row: number;+ reason: string;+ values: Record<string, string>;+ };const data = (importResult.data ?? {}) as {inserted?: number;updated?: number;- skipped?: number;- errors?: Array<{ row: number; reason: string }>;+ errors?: RowIssue[];+ skipped?: RowIssue[];};return {@@ -66,7 +71,7 @@ export async function action({ request, params }: ActionFunctionArgs) {message: "Import successful",inserted: data.inserted ?? 0,updated: data.updated ?? 0,- skipped: data.skipped ?? 0,- errors: data.errors ?? []+ errors: data.errors ?? [],+ skipped: data.skipped ?? []};}diff --git a/packages/database/supabase/functions/import-csv/classify-import-row.test.ts b/packages/database/supabase/functions/import-csv/classify-import-row.test.tsindex 9a2add30eb..6fb1d8e578 100644--- a/packages/database/supabase/functions/import-csv/classify-import-row.test.ts+++ b/packages/database/supabase/functions/import-csv/classify-import-row.test.ts@@ -11,7 +11,7 @@ const base = () => ({Deno.test("skips a row whose name is blank", () => {assertEquals(classifyImportRow({ ...base(), id: "X", name: " " }),- { action: "skip", reason: "Missing required Name" }+ { action: "skip", reason: "Missing required Name", category: "error" });});@@ -56,7 +56,7 @@ Deno.test("skips a duplicate non-empty id within the file", () => {name: "Acme 2",seenIds: new Set(["SUP-1"]),}),- { action: "skip", reason: 'Duplicate ID "SUP-1" in file' }+ { action: "skip", reason: 'Duplicate ID "SUP-1" in file', category: "skipped" });});@@ -68,7 +68,7 @@ Deno.test("skips a duplicate name within the file", () => {name: "Acme",seenNames: new Set(["Acme"]),}),- { action: "skip", reason: 'Duplicate name "Acme" in file' }+ { action: "skip", reason: 'Duplicate name "Acme" in file', category: "skipped" });});@@ -79,7 +79,7 @@ Deno.test("skips a repeated non-empty id once the caller has recorded it", () =>ctx.seenIds.add("SUP-1");ctx.seenNames.add("Acme");const d2 = classifyImportRow({ ...ctx, id: "SUP-1", name: "Acme 2" });- assertEquals(d2, { action: "skip", reason: 'Duplicate ID "SUP-1" in file' });+ assertEquals(d2, { action: "skip", reason: 'Duplicate ID "SUP-1" in file', category: "skipped" });});Deno.test("falls back to name match when a non-empty id has no id match", () => {diff --git a/packages/database/supabase/functions/import-csv/classify-import-row.ts b/packages/database/supabase/functions/import-csv/classify-import-row.tsindex d377f44f47..27be0de3b7 100644--- a/packages/database/supabase/functions/import-csv/classify-import-row.ts+++ b/packages/database/supabase/functions/import-csv/classify-import-row.ts@@ -10,7 +10,7 @@export type RowDecision =| { action: "insert" }| { action: "update"; entityId: string }- | { action: "skip"; reason: string };+ | { action: "skip"; reason: string; category: "error" | "skipped" };export function classifyImportRow(params: {id: string;@@ -24,13 +24,21 @@ export function classifyImportRow(params: {// `name` can be undefined at runtime when the CSV's Name column is unmapped.if (!name || name.trim() === "") {- return { action: "skip", reason: "Missing required Name" };+ return { action: "skip", reason: "Missing required Name", category: "error" };}if (id && seenIds.has(id)) {- return { action: "skip", reason: `Duplicate ID "${id}" in file` };+ return {+ action: "skip",+ reason: `Duplicate ID "${id}" in file`,+ category: "skipped",+ };}if (seenNames.has(name)) {- return { action: "skip", reason: `Duplicate name "${name}" in file` };+ return {+ action: "skip",+ reason: `Duplicate name "${name}" in file`,+ category: "skipped",+ };}// The CSV name is matched as-is. Whitespace/case normalization is intentionallydiff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.tsindex 8868614149..0d4ac28e3c 100644--- a/packages/database/supabase/functions/import-csv/index.ts+++ b/packages/database/supabase/functions/import-csv/index.ts@@ -23,7 +23,6 @@ const importCsvValidator = z.object({"material","bom","operations",- "partWithMethod","part","supplier","supplierContact",@@ -904,7 +903,10 @@ serve(async (req: Request) => {const summary = {inserted: 0,updated: 0,+ // Rows the user should fix and re-import (validation / missing required data).errors: [] as Array<{ row: number; reason: string }>,+ // Rows intentionally not written (duplicates, already-existing) — informational.+ skipped: [] as Array<{ row: number; reason: string }>,};switch (table) {@@ -982,7 +984,9 @@ serve(async (req: Request) => {});if (decision.action === "skip") {- summary.errors.push({ row: rowIndex, reason: decision.reason });+ const bucket =+ decision.category === "error" ? summary.errors : summary.skipped;+ bucket.push({ row: rowIndex, reason: decision.reason });continue;}@@ -1181,7 +1185,9 @@ serve(async (req: Request) => {});if (decision.action === "skip") {- summary.errors.push({ row: rowIndex, reason: decision.reason });+ const bucket =+ decision.category === "error" ? summary.errors : summary.skipped;+ bucket.push({ row: rowIndex, reason: decision.reason });continue;}@@ -2250,8 +2256,7 @@ serve(async (req: Request) => {break;}case "bom":- case "operations":- case "partWithMethod": {+ case "operations": {await importMethods(db, {table,mappedRecords,@@ -2266,13 +2271,20 @@ serve(async (req: Request) => {}}+ // Attach each failed/skipped row's original CSV cells (keyed by the user's+ // headers) so the results UI renders the exact rows the server parsed — no+ // dependence on a second, client-side parse. `row` is the 0-based index into+ // parsedCsv for both the standard and method importers.+ const withValues = (issues: Array<{ row: number; reason: string }>) =>+ issues.map((issue) => ({ ...issue, values: parsedCsv[issue.row] ?? {} }));+return new Response(JSON.stringify({success: true,inserted: summary.inserted,updated: summary.updated,- skipped: summary.errors.length,- errors: summary.errors,+ errors: withValues(summary.errors),+ skipped: withValues(summary.skipped),}),{headers: { ...corsHeaders, "Content-Type": "application/json" },diff --git a/packages/database/supabase/functions/import-csv/method-import.ts b/packages/database/supabase/functions/import-csv/method-import.tsindex cfb824d56c..213afd905d 100644--- a/packages/database/supabase/functions/import-csv/method-import.ts+++ b/packages/database/supabase/functions/import-csv/method-import.ts@@ -1,5 +1,5 @@-// Method (BOM/BOP) importer — backs the `bom`, `operations`, and `partWithMethod`-// CSV imports. One row-type-multiplexed engine (ADR-0002): a single file carries+// Method (BOM/BOP) importer — backs the `bom` and `operations` CSV imports.+// One row-type-multiplexed engine (ADR-0002): a single file carries// PART/BOM/BOP/STEP/TOOL/PARAM rows, each non-PART row naming its parent part// explicitly. Atomic per parent part and create-only / fill-if-empty (ADR-0001).//@@ -16,6 +16,7 @@ type Summary = {inserted: number;updated: number;errors: Array<{ row: number; reason: string }>;+ skipped: Array<{ row: number; reason: string }>;};const ROW_TYPES = ["PART", "BOM", "BOP", "STEP", "TOOL", "PARAM"] as const;@@ -74,8 +75,10 @@ const bool = (s: string | undefined): boolean =>const text = (s: string | undefined): string => (s ?? "").trim();-// A CSV row number for messages: header is row 1, data starts at row 2.-const lineNo = (index: number) => index + 2;+// The `row` reported on each error: the 0-based index of the data row. This must+// match how the results modal keys errors to rows (by array index into the parsed+// rows) and the standard importer in index.ts — NOT a human CSV line number.+const rowOf = (index: number) => index;// Plain text → minimal tiptap doc for a step's rich-text description.function plainTextToTiptap(value: string): Record<string, unknown> {@@ -106,7 +109,7 @@ function normalizeRowType(export async function importMethods(db: Kysely<DB>,args: {- table: "bom" | "operations" | "partWithMethod";+ table: "bom" | "operations";mappedRecords: Rec[];companyId: string;userId: string;@@ -139,7 +142,7 @@ export async function importMethods(const rowType = normalizeRowType(record.rowType, table);if (!rowType) {summary.errors.push({- row: lineNo(index),+ row: rowOf(index),reason: `Unknown or missing Row Type "${text(record.rowType)}"`,});return;@@ -149,7 +152,7 @@ export async function importMethods(const readableId = text(record.readableId);if (!readableId) {summary.errors.push({- row: lineNo(index),+ row: rowOf(index),reason: "PART row is missing Part Number",});return;@@ -163,7 +166,7 @@ export async function importMethods(const parentId = text(record.parentId);if (!parentId) {summary.errors.push({- row: lineNo(index),+ row: rowOf(index),reason: `${rowType} row is missing Parent ID`,});return;@@ -305,8 +308,9 @@ export async function importMethods(else summary.updated++;} else if (result.skippedExisting) {// The targeted version already had content — create-only, never clobber.- summary.errors.push({- row: lineNo(g.firstIndex),+ // Benign: not something the user needs to fix, so it's a skip, not an error.+ summary.skipped.push({+ row: rowOf(g.firstIndex),reason: `Part ${partLabel} already has a method; skipped`,});} else if (g.partRow) {@@ -315,7 +319,7 @@ export async function importMethods(}} catch (err) {summary.errors.push({- row: lineNo(g.firstIndex),+ row: rowOf(g.firstIndex),reason: `Part ${partLabel} failed to import: ${err instanceof Error ? err.message : String(err)}`,@@ -378,12 +382,12 @@ function validateGroup(const parent = lk.itemMap.get(parentKey);if (!parent) {errors.push({- row: lineNo(g.firstIndex),+ row: rowOf(g.firstIndex),reason: `Parent part ${partLabel} not found`,});} else if (parent.type !== "Part" && parent.type !== "Tool") {errors.push({- row: lineNo(g.firstIndex),+ row: rowOf(g.firstIndex),reason: `Parent ${partLabel} is a ${parent.type}; only a Part or Tool can own a method`,});}@@ -395,12 +399,12 @@ function validateGroup(for (const e of bucket.bop) {const opNo = text(e.record.opNo);if (!opNo) {- errors.push({ row: lineNo(e.index), reason: "BOP row is missing Op No" });+ errors.push({ row: rowOf(e.index), reason: "BOP row is missing Op No" });continue;}if (opNos.has(opNo)) {errors.push({- row: lineNo(e.index),+ row: rowOf(e.index),reason: `Duplicate Op No "${opNo}" for ${partLabel}`,});}@@ -409,19 +413,19 @@ function validateGroup(// process required + resolvableconst proc = text(e.record.process).toLowerCase();if (!proc) {- errors.push({ row: lineNo(e.index), reason: `Op ${opNo}: Process is required` });+ errors.push({ row: rowOf(e.index), reason: `Op ${opNo}: Process is required` });} else if (lk.processAmbiguous.has(proc)) {- errors.push({ row: lineNo(e.index), reason: `Op ${opNo}: Process name is ambiguous` });+ errors.push({ row: rowOf(e.index), reason: `Op ${opNo}: Process name is ambiguous` });} else if (!lk.processMap.has(proc)) {- errors.push({ row: lineNo(e.index), reason: `Op ${opNo}: Process "${text(e.record.process)}" not found` });+ errors.push({ row: rowOf(e.index), reason: `Op ${opNo}: Process "${text(e.record.process)}" not found` });}const wc = text(e.record.workCenter).toLowerCase();if (wc) {if (lk.workCenterAmbiguous.has(wc)) {- errors.push({ row: lineNo(e.index), reason: `Op ${opNo}: Work Center name is ambiguous` });+ errors.push({ row: rowOf(e.index), reason: `Op ${opNo}: Work Center name is ambiguous` });} else if (!lk.workCenterMap.has(wc)) {- errors.push({ row: lineNo(e.index), reason: `Op ${opNo}: Work Center "${text(e.record.workCenter)}" not found` });+ errors.push({ row: rowOf(e.index), reason: `Op ${opNo}: Work Center "${text(e.record.workCenter)}" not found` });}}@@ -430,7 +434,7 @@ function validateGroup(if (opType === "Inside") {if (!text(e.record.setupUnit) || !text(e.record.laborUnit) || !text(e.record.machineUnit)) {errors.push({- row: lineNo(e.index),+ row: rowOf(e.index),reason: `Op ${opNo}: Inside operations require Setup, Labor, and Machine units`,});}@@ -441,22 +445,22 @@ function validateGroup(for (const e of bucket.bom) {const componentId = text(e.record.componentId);if (!componentId) {- errors.push({ row: lineNo(e.index), reason: "BOM row is missing Material ID" });+ errors.push({ row: rowOf(e.index), reason: "BOM row is missing Material ID" });continue;}const compKey = key(componentId, text(e.record.componentRevision));if (!lk.itemMap.has(compKey) && !lk.fileCreatedParts.has(compKey)) {errors.push({- row: lineNo(e.index),+ row: rowOf(e.index),reason: `Material ${componentId} rev ${text(e.record.componentRevision) || "0"} not found`,});}if (num(e.record.quantity) === undefined) {- errors.push({ row: lineNo(e.index), reason: "BOM row has an invalid Quantity" });+ errors.push({ row: rowOf(e.index), reason: "BOM row has an invalid Quantity" });}const uom = text(e.record.unitOfMeasureCode);if (uom && !lk.uomSet.has(uom)) {- errors.push({ row: lineNo(e.index), reason: `Unit of Measure "${uom}" not found` });+ errors.push({ row: rowOf(e.index), reason: `Unit of Measure "${uom}" not found` });}}@@ -464,50 +468,50 @@ function validateGroup(for (const e of bucket.step) {const opNo = text(e.record.opNo);if (!opNos.has(opNo)) {- errors.push({ row: lineNo(e.index), reason: `STEP references unknown Op No "${opNo}"` });+ errors.push({ row: rowOf(e.index), reason: `STEP references unknown Op No "${opNo}"` });}if (!text(e.record.stepName)) {- errors.push({ row: lineNo(e.index), reason: "STEP row is missing Name" });+ errors.push({ row: rowOf(e.index), reason: "STEP row is missing Name" });}const stepType = text(e.record.stepType) || "Task";if (!(STEP_TYPES as readonly string[]).includes(stepType)) {- errors.push({ row: lineNo(e.index), reason: `Invalid Step Type "${stepType}"` });+ errors.push({ row: rowOf(e.index), reason: `Invalid Step Type "${stepType}"` });}if (stepType === "Measurement" && !text(e.record.stepUnitOfMeasureCode)) {- errors.push({ row: lineNo(e.index), reason: "Measurement step requires a Step Unit of Measure" });+ errors.push({ row: rowOf(e.index), reason: "Measurement step requires a Step Unit of Measure" });}if (stepType === "List" && !text(e.record.stepListValues)) {- errors.push({ row: lineNo(e.index), reason: "List step requires Step List Values" });+ errors.push({ row: rowOf(e.index), reason: "List step requires Step List Values" });}}for (const e of bucket.tool) {const opNo = text(e.record.opNo);if (!opNos.has(opNo)) {- errors.push({ row: lineNo(e.index), reason: `TOOL references unknown Op No "${opNo}"` });+ errors.push({ row: rowOf(e.index), reason: `TOOL references unknown Op No "${opNo}"` });}const toolId = text(e.record.toolId);if (!toolId) {- errors.push({ row: lineNo(e.index), reason: "TOOL row is missing Tool ID" });+ errors.push({ row: rowOf(e.index), reason: "TOOL row is missing Tool ID" });} else {const toolKey = key(toolId, text(e.record.toolRevision));if (!lk.itemMap.has(toolKey) && !lk.fileCreatedParts.has(toolKey)) {- errors.push({ row: lineNo(e.index), reason: `Tool ${toolId} rev ${text(e.record.toolRevision) || "0"} not found` });+ errors.push({ row: rowOf(e.index), reason: `Tool ${toolId} rev ${text(e.record.toolRevision) || "0"} not found` });}}if (num(e.record.toolQuantity) === undefined) {- errors.push({ row: lineNo(e.index), reason: "TOOL row has an invalid Quantity" });+ errors.push({ row: rowOf(e.index), reason: "TOOL row has an invalid Quantity" });}}for (const e of bucket.param) {const opNo = text(e.record.opNo);if (!opNos.has(opNo)) {- errors.push({ row: lineNo(e.index), reason: `PARAM references unknown Op No "${opNo}"` });+ errors.push({ row: rowOf(e.index), reason: `PARAM references unknown Op No "${opNo}"` });}if (!text(e.record.paramKey)) {- errors.push({ row: lineNo(e.index), reason: "PARAM row is missing Key" });+ errors.push({ row: rowOf(e.index), reason: "PARAM row is missing Key" });}if (!text(e.record.paramValue)) {- errors.push({ row: lineNo(e.index), reason: "PARAM row is missing Value" });+ errors.push({ row: rowOf(e.index), reason: "PARAM row is missing Value" });}}}