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.

Add improvements to the import flow (#888)

Gaurav Bhattd55d8508b273
diff --git a/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx b/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx
index b33f8e67c2..f22aaf8b46 100644
--- a/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx
+++ b/apps/erp/app/components/ImportCSVModal/FieldMappings.tsx
@@ -2,7 +2,7 @@
import { useCarbon } from "@carbon/auth";
import type { Database } from "@carbon/database";
-import { Combobox, useFormContext } from "@carbon/form";
+import { Combobox, CreatableCombobox, useFormContext } from "@carbon/form";
import {
Button,
ModalBody,
@@ -13,32 +13,63 @@ import {
TooltipContent,
TooltipProvider,
TooltipTrigger,
- toast
+ toast,
+ useDisclosure
} from "@carbon/react";
import { Trans, useLingui } from "@lingui/react/macro";
import type { PostgrestResponse, SupabaseClient } from "@supabase/supabase-js";
-import { Fragment, useCallback, useEffect, useRef, useState } from "react";
-import { LuInfo, LuMoveRight } from "react-icons/lu";
+import {
+ Fragment,
+ type ReactNode,
+ useCallback,
+ useEffect,
+ useRef,
+ useState
+} from "react";
+import { LuInfo, LuListPlus, LuMoveRight, LuPlus } from "react-icons/lu";
import { useFetcher } from "react-router";
import { Submit } from "~/components/Form";
-import { useCurrencyFormatter, useDateFormatter, useUser } from "~/hooks";
-import type { importSchemas } from "~/modules/shared";
+import {
+ useCompanySettings,
+ useCurrencyFormatter,
+ useDateFormatter,
+ usePermissions,
+ useUser
+} from "~/hooks";
+import PaymentTermForm from "~/modules/accounting/ui/PaymentTerms/PaymentTermForm";
+import { ShippingMethodForm } from "~/modules/inventory";
+import type {
+ CreatableForm,
+ CreatableLookup,
+ importSchemas
+} from "~/modules/shared";
import { fieldMappings } from "~/modules/shared";
import type { action } from "~/routes/api+/ai+/csv+/$table.columns";
import type { ListItem } from "~/types";
import { path } from "~/utils/path";
import { capitalize } from "~/utils/string";
+import {
+ buildOptionLookup,
+ type MatchableOption,
+ matchCsvValue,
+ toMatchableOption
+} from "./enumMatch";
+import { useCreateLookup } from "./useCreateLookup";
import { useCsvContext } from "./useCsvContext";
type EnumData =
| {
default: string;
description: string;
+ creatableLookup?: CreatableLookup;
+ creatableForm?: CreatableForm;
options: readonly string[];
}
| {
default: string;
description: string;
+ creatableLookup?: CreatableLookup;
+ creatableForm?: CreatableForm;
fetcher: (
client: SupabaseClient<Database>,
companyId: string
@@ -192,6 +223,11 @@ export function FieldMapping({
? t`Field Mapping`
: enumFields[currentStep - 1][1].label}
</ModalTitle>
+ {steps > 1 && (
+ <span className="ml-auto text-sm text-muted-foreground whitespace-nowrap">
+ {t`Step`} {currentStep + 1} {t`of`} {steps}
+ </span>
+ )}
</div>
<ModalDescription>
@@ -403,20 +439,19 @@ function EnumMappingStep({
}) {
const { carbon } = useCarbon();
const { company } = useUser();
- const [options, setOptions] = useState<{ label: string; value: string }[]>(
- () => {
- if ("options" in enumData) {
- return (
- enumData.options.map((option) => ({
- label: option,
- value: option
- })) || []
- );
- } else {
- return [];
- }
+ const showReadableId = useCompanySettings()?.showSupplierReadableId ?? false;
+ const [options, setOptions] = useState<MatchableOption[]>(() => {
+ if ("options" in enumData) {
+ return (
+ enumData.options.map((option) => ({
+ label: option,
+ value: option
+ })) || []
+ );
+ } else {
+ return [];
}
- );
+ });
const uniqueValues = Array.from(
new Set(
@@ -432,17 +467,10 @@ function EnumMappingStep({
if (error) {
toast.error(error.message);
} else {
- // Use email as label when present (employees) so auto-match keys on
- // email; falls back to name for lookups without an email column.
- setOptions(
- data.map((item) => ({
- label: item.email ?? item.name,
- value: item.id
- }))
- );
+ setOptions(data.map((item) => toMatchableOption(item, showReadableId)));
}
}
- }, [enumData, carbon, company.id]);
+ }, [enumData, carbon, company.id, showReadableId]);
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
@@ -459,19 +487,101 @@ function EnumMappingStep({
if (autoMatchedRef.current) return;
if (options.length === 0 || uniqueValues.length === 0) return;
- const lookup = new Map(
- options.map((o) => [o.label.toLowerCase().trim(), o.value])
- );
+ const lookup = buildOptionLookup(options);
for (const csvValue of uniqueValues) {
if (mappings[csvValue]) continue;
- const matched = lookup.get(csvValue.toLowerCase().trim());
+ const matched = matchCsvValue(lookup, csvValue);
if (matched) onEnumMappingChange(name, csvValue, matched);
}
autoMatchedRef.current = true;
}, [options, mappedColumn]);
+ // Inline create-and-link for name-only lookups (e.g. supplier type). Created
+ // ids flow through onEnumMappingChange into enumMappings, so the import
+ // payload is unchanged — the edge function only ever sees real ids. The same
+ // batch path serves both the per-value combobox create and the "create all
+ // missing" banner; the route is idempotent, so values that already exist are
+ // linked instead of duplicated.
+ const creatableLookup = enumData.creatableLookup;
+ const { create: createMissingValues, isCreating } = useCreateLookup({
+ lookup: creatableLookup,
+ onLinked: (csvValue, id, label) => {
+ setOptions((prev) =>
+ prev.some((o) => o.value === id)
+ ? prev
+ : [...prev, { label, value: id }]
+ );
+ onEnumMappingChange(name, csvValue, id);
+ }
+ });
+
+ const unmatchedValues = creatableLookup
+ ? uniqueValues.filter((csvValue) => !mappings[csvValue])
+ : [];
+
+ // Rich lookups (payment term, shipping method) need more than a name, so
+ // "create" opens the existing form modal pre-filled with the typed value.
+ // Once the refreshed options contain it, the pending CSV value is linked.
+ const creatableForm = enumData.creatableForm;
+ const permissions = usePermissions();
+ const canCreateViaForm =
+ (creatableForm === "paymentTerm" &&
+ permissions.can("create", "accounting")) ||
+ (creatableForm === "shippingMethod" &&
+ permissions.can("create", "inventory"));
+ const formModal = useDisclosure();
+ const [formCreatedName, setFormCreatedName] = useState("");
+ const pendingFormCsvValueRef = useRef<string | null>(null);
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: link once options refresh
+ useEffect(() => {
+ const csvValue = pendingFormCsvValueRef.current;
+ if (csvValue === null || !formCreatedName) return;
+ const matched = matchCsvValue(buildOptionLookup(options), formCreatedName);
+ if (matched) {
+ onEnumMappingChange(name, csvValue, matched);
+ pendingFormCsvValueRef.current = null;
+ setFormCreatedName("");
+ }
+ }, [options]);
+
return (
<div>
+ {creatableLookup && unmatchedValues.length > 0 && (
+ <div className="mt-1 mb-4 flex items-center justify-between gap-4 rounded-md border bg-muted/40 px-4 py-3">
+ <div className="flex min-w-0 items-center gap-3">
+ <div className="flex h-9 w-9 flex-shrink-0 items-center justify-center rounded-md border bg-background">
+ <LuListPlus className="h-4 w-4 text-muted-foreground" />
+ </div>
+ <div className="flex min-w-0 flex-col">
+ <span className="text-sm font-medium">
+ <Trans>{unmatchedValues.length} values missing</Trans>
+ </span>
+ <TooltipProvider delayDuration={50}>
+ <Tooltip>
+ <TooltipTrigger className="w-fit text-left text-xs text-muted-foreground">
+ <Trans>View missing values</Trans>
+ </TooltipTrigger>
+ <TooltipContent className="max-w-64 p-2 text-sm">
+ {unmatchedValues.join(", ")}
+ </TooltipContent>
+ </Tooltip>
+ </TooltipProvider>
+ </div>
+ </div>
+ <Button
+ variant="secondary"
+ size="md"
+ leftIcon={<LuPlus />}
+ disabled={isCreating}
+ onClick={() =>
+ createMissingValues(unmatchedValues, unmatchedValues)
+ }
+ >
+ <Trans>Create {unmatchedValues.length} values</Trans>
+ </Button>
+ </div>
+ )}
<div className="grid grid-cols-2 gap-4">
<div className="font-medium ">
{`${capitalize(mappedColumn ?? "CSV")} Value`}
@@ -481,6 +591,16 @@ function EnumMappingStep({
</div>
{[...new Set([...uniqueValues, "Default"])].map((csvValue) => {
+ const comboboxProps = {
+ name: `${name}-${csvValue}`,
+ value: mappings[csvValue],
+ options,
+ onChange: (value: { value: string; label: ReactNode } | null) => {
+ if (value?.value) {
+ onEnumMappingChange(name, csvValue, value.value);
+ }
+ }
+ };
return (
<Fragment key={csvValue}>
<div className="relative flex min-w-0 items-center gap-2">
@@ -489,20 +609,58 @@ function EnumMappingStep({
<LuMoveRight className="text-muted-foreground" />
</div>
</div>
- <Combobox
- name={`${name}-${csvValue}`}
- onChange={(value) => {
- if (value?.value) {
- onEnumMappingChange(name, csvValue, value.value);
+ {creatableLookup ? (
+ <CreatableCombobox
+ {...comboboxProps}
+ onCreateOption={(inputValue) =>
+ createMissingValues([csvValue], [inputValue])
}
- }}
- value={mappings[csvValue]}
- options={options}
- />
+ />
+ ) : canCreateViaForm ? (
+ <CreatableCombobox
+ {...comboboxProps}
+ onCreateOption={(inputValue) => {
+ setFormCreatedName(inputValue);
+ pendingFormCsvValueRef.current = csvValue;
+ formModal.onOpen();
+ }}
+ />
+ ) : (
+ <Combobox {...comboboxProps} />
+ )}
</Fragment>
);
})}
</div>
+ {formModal.isOpen && creatableForm === "paymentTerm" && (
+ <PaymentTermForm
+ type="modal"
+ onClose={() => {
+ formModal.onClose();
+ fetchOptions();
+ }}
+ initialValues={{
+ name: formCreatedName,
+ calculationMethod: "Net" as const,
+ daysDue: 0,
+ discountPercentage: 0,
+ daysDiscount: 0
+ }}
+ />
+ )}
+ {formModal.isOpen && creatableForm === "shippingMethod" && (
+ <ShippingMethodForm
+ type="modal"
+ onClose={() => {
+ formModal.onClose();
+ fetchOptions();
+ }}
+ initialValues={{
+ name: formCreatedName,
+ carrier: "" as "FedEx"
+ }}
+ />
+ )}
</div>
);
}
diff --git a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
index a3e6b73af9..1fa8bd0790 100644
--- a/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
+++ b/apps/erp/app/components/ImportCSVModal/ImportCSVModal.tsx
@@ -1,5 +1,5 @@
import { Hidden, ValidatedForm } from "@carbon/form";
-import { Modal, ModalContent, toast } from "@carbon/react";
+import { Button, Modal, ModalContent, toast } from "@carbon/react";
import { useEffect, useState } from "react";
import { flushSync } from "react-dom";
import { useFetcher } from "react-router";
@@ -43,8 +43,18 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
// biome-ignore lint/correctness/useExhaustiveDependencies: suppressed due to migration
useEffect(() => {
if (fetcher.data?.success === true) {
- toast.success("Import successful.");
- onClose();
+ const inserted = fetcher.data.inserted ?? 0;
+ const updated = fetcher.data.updated ?? 0;
+ const skipped = fetcher.data.skipped ?? 0;
+ if (skipped > 0) {
+ // Leave the modal open so the user sees which rows were skipped.
+ toast.info(
+ `Imported ${inserted}, updated ${updated}, skipped ${skipped} row(s).`
+ );
+ } else {
+ toast.success(`Imported ${inserted}, updated ${updated}.`);
+ onClose();
+ }
} else if (fetcher.data?.success === false) {
toast.error(fetcher.data.message);
}
@@ -117,6 +127,30 @@ export const ImportCSVModal = ({ table, onClose }: ImportCSVModalProps) => {
/>
)}
</ValidatedForm>
+ {fetcher.data?.success === true &&
+ (fetcher.data.skipped ?? 0) > 0 && (
+ <div className="mt-4 rounded-md border border-border p-3">
+ <p className="text-sm font-medium">
+ {fetcher.data.skipped} row(s) were skipped:
+ </p>
+ <ul className="mt-2 max-h-48 overflow-auto text-sm text-muted-foreground">
+ {(fetcher.data.errors ?? []).map(
+ (e: { row: number; reason: string }) => (
+ <li key={e.row}>
+ Row {e.row + 1}: {e.reason}
+ </li>
+ )
+ )}
+ </ul>
+ <Button
+ className="mt-3"
+ variant="secondary"
+ onClick={onClose}
+ >
+ Done
+ </Button>
+ </div>
+ )}
</div>
</ImportCsvContext.Provider>
</AnimatedSizeContainer>
diff --git a/apps/erp/app/components/ImportCSVModal/enumMatch.test.ts b/apps/erp/app/components/ImportCSVModal/enumMatch.test.ts
new file mode 100644
index 0000000000..1081147082
--- /dev/null
+++ b/apps/erp/app/components/ImportCSVModal/enumMatch.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it } from "vitest";
+import {
+ buildOptionLookup,
+ matchCsvValue,
+ toMatchableOption
+} from "./enumMatch";
+
+describe("buildOptionLookup / matchCsvValue", () => {
+ it("matches by label (case- and whitespace-insensitive)", () => {
+ const lookup = buildOptionLookup([{ label: "TW Metals", value: "sup-1" }]);
+ expect(matchCsvValue(lookup, " tw metals ")).toBe("sup-1");
+ });
+
+ it("matches by an alias (e.g. readableId) as well as the label", () => {
+ const lookup = buildOptionLookup([
+ { label: "TW Metals", value: "sup-1", aliases: ["SUP000001"] }
+ ]);
+ expect(matchCsvValue(lookup, "TW Metals")).toBe("sup-1");
+ expect(matchCsvValue(lookup, "sup000001")).toBe("sup-1");
+ });
+
+ it("returns undefined when nothing matches", () => {
+ const lookup = buildOptionLookup([
+ { label: "TW Metals", value: "sup-1", aliases: ["SUP000001"] }
+ ]);
+ expect(matchCsvValue(lookup, "Unknown Co")).toBeUndefined();
+ });
+
+ it("ignores empty / whitespace-only keys", () => {
+ const lookup = buildOptionLookup([
+ { label: "Acme", value: "sup-2", aliases: ["", " "] }
+ ]);
+ expect(matchCsvValue(lookup, "acme")).toBe("sup-2");
+ expect(matchCsvValue(lookup, "")).toBeUndefined();
+ });
+
+ it("keeps the first option on key collision (deterministic)", () => {
+ const lookup = buildOptionLookup([
+ { label: "Acme", value: "first" },
+ { label: "ACME", value: "second" }
+ ]);
+ expect(matchCsvValue(lookup, "acme")).toBe("first");
+ });
+
+ it("keeps the earlier option when an alias collides with a later option's label", () => {
+ const lookup = buildOptionLookup([
+ { label: "Alpha", value: "a", aliases: ["shared"] },
+ { label: "shared", value: "b" }
+ ]);
+ expect(matchCsvValue(lookup, "shared")).toBe("a");
+ });
+});
+
+describe("toMatchableOption", () => {
+ it("employees match by email only (name is not a match key)", () => {
+ const option = toMatchableOption(
+ { id: "e1", name: "Jane Doe", email: "[email protected]" },
+ false
+ );
+ expect(option).toEqual({ label: "[email protected]", value: "e1" });
+ });
+
+ it("supplier with readable IDs hidden: label is name, readableId is an alias", () => {
+ const option = toMatchableOption(
+ { id: "s1", name: "TW Metals", readableId: "SUP000001" },
+ false
+ );
+ expect(option).toEqual({
+ label: "TW Metals",
+ value: "s1",
+ aliases: ["SUP000001"]
+ });
+ });
+
+ it("supplier with readable IDs shown: label is readableId, name is an alias", () => {
+ const option = toMatchableOption(
+ { id: "s1", name: "TW Metals", readableId: "SUP000001" },
+ true
+ );
+ expect(option).toEqual({
+ label: "SUP000001",
+ value: "s1",
+ aliases: ["TW Metals"]
+ });
+ });
+
+ it("name-only lookup: label is name, no aliases", () => {
+ const option = toMatchableOption({ id: "t1", name: "Raw Material" }, false);
+ expect(option).toEqual({ label: "Raw Material", value: "t1", aliases: [] });
+ });
+});
diff --git a/apps/erp/app/components/ImportCSVModal/enumMatch.ts b/apps/erp/app/components/ImportCSVModal/enumMatch.ts
new file mode 100644
index 0000000000..518b6773ca
--- /dev/null
+++ b/apps/erp/app/components/ImportCSVModal/enumMatch.ts
@@ -0,0 +1,57 @@
+// Pure matching helpers for the CSV import enum-mapping step. Extracted so the
+// auto-match logic is unit-testable without a DOM. An option may carry
+// `aliases` — additional identifiers (e.g. a supplier's readableId) that resolve
+// to the same value as the visible label.
+
+import type { ListItem } from "~/types";
+
+export type MatchableOption = {
+ label: string;
+ value: string;
+ aliases?: string[];
+};
+
+const normalize = (value: string): string => value.toLowerCase().trim();
+
+// Build a normalized lookup of every match key (label + aliases) -> option
+// value. Earlier options win on collision so results are deterministic.
+export function buildOptionLookup(
+ options: MatchableOption[]
+): Map<string, string> {
+ const lookup = new Map<string, string>();
+ for (const option of options) {
+ for (const key of [option.label, ...(option.aliases ?? [])]) {
+ const normalized = normalize(key);
+ if (normalized === "") continue;
+ if (!lookup.has(normalized)) lookup.set(normalized, option.value);
+ }
+ }
+ return lookup;
+}
+
+// Resolve a CSV cell value to an option value, or undefined when no key matches.
+export function matchCsvValue(
+ lookup: Map<string, string>,
+ csvValue: string
+): string | undefined {
+ return lookup.get(normalize(csvValue));
+}
+
+// Derive a MatchableOption from a fetched list item. Employees (items with an
+// email) match by email ONLY — their names are not unique, so name must not be
+// a match key. For suppliers and other no-email lookups, the label is the
+// readableId when the company displays readable IDs (else the name), and the
+// other identifier(s) become aliases so auto-match resolves by either.
+export function toMatchableOption(
+ item: ListItem,
+ showReadableId: boolean
+): MatchableOption {
+ if (item.email) {
+ return { label: item.email, value: item.id };
+ }
+ const label = showReadableId && item.readableId ? item.readableId : item.name;
+ const aliases = [item.readableId, item.name].filter(
+ (alias): alias is string => !!alias && alias !== label
+ );
+ return { label, value: item.id, aliases };
+}
diff --git a/apps/erp/app/components/ImportCSVModal/useCreateLookup.ts b/apps/erp/app/components/ImportCSVModal/useCreateLookup.ts
new file mode 100644
index 0000000000..dce7f3a32a
--- /dev/null
+++ b/apps/erp/app/components/ImportCSVModal/useCreateLookup.ts
@@ -0,0 +1,68 @@
+import { toast } from "@carbon/react";
+import { useEffect, useRef } from "react";
+import { useFetcher } from "react-router";
+import type { CreatableLookup } from "~/modules/shared";
+import type { action } from "~/routes/api+/csv+/create-lookup";
+import { path } from "~/utils/path";
+
+// Submits create-lookup batches and reports each created/existing id back via
+// `onLinked`. `csvValues[i]` pairs with `names[i]` — they differ for the inline
+// combobox create, where the user can type a corrected name for a CSV cell
+// (e.g. CSV "Raw Matl" -> create "Raw Material").
+export function useCreateLookup({
+ lookup,
+ onLinked
+}: {
+ lookup: CreatableLookup | undefined;
+ onLinked: (csvValue: string, id: string, label: string) => void;
+}) {
+ const fetcher = useFetcher<typeof action>();
+ const pendingCsvValuesRef = useRef<string[] | null>(null);
+
+ const create = (csvValues: string[], names: string[]) => {
+ if (!lookup || names.length === 0) return;
+ pendingCsvValuesRef.current = csvValues;
+ fetcher.submit(
+ { lookup, names },
+ {
+ method: "POST",
+ action: path.to.api.createCsvLookup,
+ encType: "application/json"
+ }
+ );
+ };
+
+ // biome-ignore lint/correctness/useExhaustiveDependencies: respond to create result
+ useEffect(() => {
+ const data = fetcher.data;
+ const pending = pendingCsvValuesRef.current;
+ if (!data || pending === null) return;
+ if ("results" in data && data.results) {
+ const created: string[] = [];
+ const failures: string[] = [];
+ data.results.forEach((result, index) => {
+ const csvValue = pending[index];
+ if (result.id && csvValue !== undefined) {
+ onLinked(csvValue, result.id, result.name);
+ created.push(result.name);
+ } else if (result.error) {
+ failures.push(result.name);
+ }
+ });
+ if (created.length === 1) {
+ toast.success(`Created "${created[0]}"`);
+ } else if (created.length > 1) {
+ toast.success(`Created ${created.length} values`);
+ }
+ if (failures.length > 0) {
+ toast.error(`Could not create: ${failures.join(", ")}`);
+ }
+ pendingCsvValuesRef.current = null;
+ } else if ("error" in data && data.error) {
+ toast.error(data.error);
+ pendingCsvValuesRef.current = null;
+ }
+ }, [fetcher.data]);
+
+ return { create, isCreating: fetcher.state !== "idle" };
+}
diff --git a/apps/erp/app/components/RealtimeDataProvider.tsx b/apps/erp/app/components/RealtimeDataProvider.tsx
index cd32fac5c6..03b5280c01 100644
--- a/apps/erp/app/components/RealtimeDataProvider.tsx
+++ b/apps/erp/app/components/RealtimeDataProvider.tsx
@@ -120,7 +120,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
name: string;
website: string;
supplierStatus: string;
- readableId: string | null;
+ readableId: string;
}>(
carbon,
"supplier",
@@ -131,7 +131,7 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
id: string;
name: string;
website: string;
- readableId: string | null;
+ readableId: string;
}>(carbon, "customer", "id, name, website, readableId", (query) =>
query.eq("companyId", companyId).order("name")
),
@@ -290,7 +290,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
{
id: inserted.id,
name: inserted.name,
- website: inserted.website
+ website: inserted.website,
+ readableId: inserted.readableId ?? undefined
}
].sort((a, b) => a.name.localeCompare(b.name))
);
@@ -304,7 +305,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
return {
...p,
name: updated.name,
- website: updated.website
+ website: updated.website,
+ readableId: updated.readableId ?? undefined
};
}
return p;
@@ -347,7 +349,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
id: inserted.id,
name: inserted.name,
website: inserted.website,
- supplierStatus: inserted.supplierStatus
+ supplierStatus: inserted.supplierStatus,
+ readableId: inserted.readableId ?? undefined
}
].sort((a, b) => a.name.localeCompare(b.name))
);
@@ -362,7 +365,8 @@ const RealtimeDataProvider = ({ children }: { children: React.ReactNode }) => {
...p,
name: updated.name,
website: updated.website,
- supplierStatus: updated.supplierStatus
+ supplierStatus: updated.supplierStatus,
+ readableId: updated.readableId ?? undefined
};
}
return p;
diff --git a/apps/erp/app/modules/shared/imports.models.ts b/apps/erp/app/modules/shared/imports.models.ts
index f68fba5a7d..8e18fbe344 100644
--- a/apps/erp/app/modules/shared/imports.models.ts
+++ b/apps/erp/app/modules/shared/imports.models.ts
@@ -23,6 +23,21 @@ const supplierStatusTypes = [
"Rejected"
] as const;
+// Name-only lookups that may be created inline during a CSV import. The value
+// doubles as the lookup's table name; the create-lookup route's zod enum, its
+// permission map, and the import modal's types all derive from this list.
+export const creatableLookups = [
+ "supplierType",
+ "customerType",
+ "customerStatus"
+] as const;
+export type CreatableLookup = (typeof creatableLookups)[number];
+
+// Rich lookups need more than a name (Net days, carrier, ...), so during a CSV
+// import they are created through their existing form modal, pre-filled with
+// the typed value. Client-only: maps a field to the form it opens.
+export type CreatableForm = "paymentTerm" | "shippingMethod";
+
// Shared supplier-part import fields. Spread into every item-type entry
// (part / material / tool / fixture / consumable) so a single CSV row can
// optionally create a supplierPart link alongside the item itself. All
@@ -34,7 +49,7 @@ const supplierPartImportFields = {
type: "enum",
enumData: {
description:
- "Optional — link this item to a supplier (match by Supplier ID)",
+ "Optional — link this item to a supplier (match by Supplier ID or name)",
fetcher: async (client: SupabaseClient<Database>, companyId: string) => {
const { data, error } = await client
.from("supplier")
@@ -42,14 +57,15 @@ const supplierPartImportFields = {
.eq("companyId", companyId)
.order("name");
if (error) return { data: null, error };
- // Returning readableId in the `name` slot makes it the option label;
- // auto-match in FieldMappings keys on lowercase-trimmed label, so a
- // CSV value of "SUPP-12" resolves to the supplier whose readableId
- // is "SUPP-12".
+ // Return name and readableId as separate fields. FieldMappings chooses
+ // the display label per the showSupplierReadableId company setting and
+ // auto-matches on BOTH name and readableId — so a CSV that references
+ // suppliers by name still resolves when readable IDs are hidden.
return {
data: data.map((s) => ({
id: s.id,
- name: s.readableId ?? s.name
+ name: s.name,
+ readableId: s.readableId ?? undefined
}))
};
}
@@ -177,6 +193,7 @@ const partnerPaymentImportFields = {
type: "enum",
enumData: {
description: "Payment term (e.g., Net 30)",
+ creatableForm: "paymentTerm",
fetcher: async (client: SupabaseClient<Database>, companyId: string) => {
return client
.from("paymentTerm")
@@ -199,6 +216,7 @@ const supplierShippingImportFields = {
type: "enum",
enumData: {
description: "Carrier / shipping method (e.g., FedEx Ground)",
+ creatableForm: "shippingMethod",
fetcher: async (client: SupabaseClient<Database>, companyId: string) => {
return client
.from("shippingMethod")
@@ -264,6 +282,7 @@ export const fieldMappings = {
enumData: {
description:
"The status of the customer (from your configured statuses)",
+ creatableLookup: "customerStatus",
fetcher: async (
client: SupabaseClient<Database>,
companyId: string
@@ -283,6 +302,7 @@ export const fieldMappings = {
enumData: {
description:
"The category/type of the customer (from your configured types)",
+ creatableLookup: "customerType",
fetcher: async (
client: SupabaseClient<Database>,
companyId: string
@@ -423,6 +443,7 @@ export const fieldMappings = {
enumData: {
description:
"The category/type of the supplier (from your configured types)",
+ creatableLookup: "supplierType",
fetcher: async (
client: SupabaseClient<Database>,
companyId: string
diff --git a/apps/erp/app/routes/api+/csv+/create-lookup.tsx b/apps/erp/app/routes/api+/csv+/create-lookup.tsx
new file mode 100644
index 0000000000..19e821634e
--- /dev/null
+++ b/apps/erp/app/routes/api+/csv+/create-lookup.tsx
@@ -0,0 +1,81 @@
+import { requirePermissions } from "@carbon/auth/auth.server";
+import type { ActionFunctionArgs } from "react-router";
+import { z } from "zod";
+import { type CreatableLookup, creatableLookups } from "~/modules/shared";
+
+const inputSchema = z.object({
+ lookup: z.enum(creatableLookups),
+ names: z.array(z.string().trim().min(1)).min(1).max(100)
+});
+
+// Creating a lookup is gated by the module that owns it. Record<CreatableLookup, ...>
+// keeps this map exhaustive: adding a lookup without a permission fails typecheck.
+const lookupPermissions: Record<CreatableLookup, "purchasing" | "sales"> = {
+ supplierType: "purchasing",
+ customerType: "sales",
+ customerStatus: "sales"
+};
+
+const normalize = (value: string) => value.toLowerCase().trim();
+
+// Create name-only lookup values during CSV import. Accepts a batch (a single
+// inline create sends a one-element array). Idempotent: existing values are
+// matched case-insensitively and returned instead of created, and intra-batch
+// case variants converge on one row. Results answer every input name so the
+// client can link each id back to the CSV value that asked for it.
+export async function action({ request }: ActionFunctionArgs) {
+ const parsed = inputSchema.safeParse(await request.json());
+ if (!parsed.success) {
+ return { error: "Invalid create-lookup request" };
+ }
+ const { lookup, names } = parsed.data;
+
+ const { client, companyId, userId } = await requirePermissions(request, {
+ create: lookupPermissions[lookup]
+ });
+
+ // One read, one bulk insert. The lookup value is the table name (constrained
+ // by the zod enum above), and all three tables share the same name-only shape
+ // with a unique (name, companyId) constraint.
+ const existing = await client
+ .from(lookup)
+ .select("id, name")
+ .eq("companyId", companyId);
+ if (existing.error) {
+ return { error: existing.error.message };
+ }
+
+ const rowByName = new Map(
+ existing.data.map((row) => [normalize(row.name), row])
+ );
+
+ const missing = [
+ ...new Map(
+ names
+ .filter((name) => !rowByName.has(normalize(name)))
+ .map((name) => [normalize(name), name])
+ ).values()
+ ];
+
+ if (missing.length > 0) {
+ const inserted = await client
+ .from(lookup)
+ .insert(missing.map((name) => ({ name, companyId, createdBy: userId })))
+ .select("id, name");
+ if (inserted.error) {
+ return { error: inserted.error.message };
+ }
+ for (const row of inserted.data) {
+ rowByName.set(normalize(row.name), row);
+ }
+ }
+
+ return {
+ results: names.map((name) => {
+ const row = rowByName.get(normalize(name));
+ return row
+ ? { id: row.id, name: row.name }
+ : { name, error: "Could not create value" };
+ })
+ };
+}
diff --git a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
index 2e36bf4e70..8a976c3bde 100644
--- a/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
+++ b/apps/erp/app/routes/x+/shared+/import.$tableId.tsx
@@ -54,8 +54,19 @@ export async function action({ request, params }: ActionFunctionArgs) {
};
}
+ const data = (importResult.data ?? {}) as {
+ inserted?: number;
+ updated?: number;
+ skipped?: number;
+ errors?: Array<{ row: number; reason: string }>;
+ };
+
return {
success: true,
- message: "Import successful"
+ message: "Import successful",
+ inserted: data.inserted ?? 0,
+ updated: data.updated ?? 0,
+ skipped: data.skipped ?? 0,
+ errors: data.errors ?? []
};
}
diff --git a/apps/erp/app/types/index.ts b/apps/erp/app/types/index.ts
index d14bf6c5c2..0087ab4ac2 100644
--- a/apps/erp/app/types/index.ts
+++ b/apps/erp/app/types/index.ts
@@ -28,6 +28,8 @@ export type ListItem = {
id: string;
name: string;
email?: string;
+ // Optional secondary human-readable identifier (e.g. a supplier's readableId).
+ readableId?: string;
};
// Topbar notification shape. `payload` mirrors what notify.ts writes into
diff --git a/apps/erp/app/utils/path.ts b/apps/erp/app/utils/path.ts
index 511ab8d308..47375b0f6d 100644
--- a/apps/erp/app/utils/path.ts
+++ b/apps/erp/app/utils/path.ts
@@ -52,6 +52,7 @@ export const path = {
emptyPermissions: `${api}/users/empty-permissions`,
failureModes: `${api}/resources/failure-modes`,
gauges: `${api}/quality/gauges`,
+ createCsvLookup: `${api}/csv/create-lookup`,
generateCsvColumns: (table: string) =>
generatePath(`${api}/ai/csv/${table}/columns`),
inspectionDocumentBalloonAnalyze: (inspectionDocumentId: string) =>
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.ts
new file mode 100644
index 0000000000..9a2add30eb
--- /dev/null
+++ b/packages/database/supabase/functions/import-csv/classify-import-row.test.ts
@@ -0,0 +1,95 @@
+import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
+import { classifyImportRow } from "./classify-import-row.ts";
+
+const base = () => ({
+ externalIdMap: new Map<string, string>(),
+ nameMap: new Map<string, string>(),
+ seenIds: new Set<string>(),
+ seenNames: new Set<string>(),
+});
+
+Deno.test("skips a row whose name is blank", () => {
+ assertEquals(
+ classifyImportRow({ ...base(), id: "X", name: " " }),
+ { action: "skip", reason: "Missing required Name" }
+ );
+});
+
+Deno.test("blank-id rows each insert independently (no collapse on empty id)", () => {
+ const ctx = base();
+ const d1 = classifyImportRow({ ...ctx, id: "", name: "Acme" });
+ assertEquals(d1, { action: "insert" });
+ ctx.seenNames.add("Acme");
+ const d2 = classifyImportRow({ ...ctx, id: "", name: "Globex" });
+ assertEquals(d2, { action: "insert" });
+});
+
+Deno.test("updates when the id matches an existing external id", () => {
+ assertEquals(
+ classifyImportRow({
+ ...base(),
+ id: "SUP-1",
+ name: "Acme",
+ externalIdMap: new Map([["SUP-1", "uuid-1"]]),
+ }),
+ { action: "update", entityId: "uuid-1" }
+ );
+});
+
+Deno.test("updates when only the name matches an existing record", () => {
+ assertEquals(
+ classifyImportRow({
+ ...base(),
+ id: "",
+ name: "Acme",
+ nameMap: new Map([["Acme", "uuid-2"]]),
+ }),
+ { action: "update", entityId: "uuid-2" }
+ );
+});
+
+Deno.test("skips a duplicate non-empty id within the file", () => {
+ assertEquals(
+ classifyImportRow({
+ ...base(),
+ id: "SUP-1",
+ name: "Acme 2",
+ seenIds: new Set(["SUP-1"]),
+ }),
+ { action: "skip", reason: 'Duplicate ID "SUP-1" in file' }
+ );
+});
+
+Deno.test("skips a duplicate name within the file", () => {
+ assertEquals(
+ classifyImportRow({
+ ...base(),
+ id: "",
+ name: "Acme",
+ seenNames: new Set(["Acme"]),
+ }),
+ { action: "skip", reason: 'Duplicate name "Acme" in file' }
+ );
+});
+
+Deno.test("skips a repeated non-empty id once the caller has recorded it", () => {
+ const ctx = base();
+ const d1 = classifyImportRow({ ...ctx, id: "SUP-1", name: "Acme" });
+ assertEquals(d1, { action: "insert" });
+ 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' });
+});
+
+Deno.test("falls back to name match when a non-empty id has no id match", () => {
+ assertEquals(
+ classifyImportRow({
+ ...base(),
+ id: "SUP-NEW",
+ name: "Acme",
+ nameMap: new Map([["Acme", "uuid-3"]]),
+ }),
+ { action: "update", entityId: "uuid-3" }
+ );
+});
diff --git a/packages/database/supabase/functions/import-csv/classify-import-row.ts b/packages/database/supabase/functions/import-csv/classify-import-row.ts
new file mode 100644
index 0000000000..d377f44f47
--- /dev/null
+++ b/packages/database/supabase/functions/import-csv/classify-import-row.ts
@@ -0,0 +1,46 @@
+// Pure per-row decision for supplier/customer CSV import. No DB, no I/O — so it
+// is unit-testable with `deno test`. The driver loop owns the running `seenIds`
+// / `seenNames` sets and applies the returned action.
+//
+// Root-cause fix: a blank CSV id must NEVER participate in in-file dedup. The
+// previous loop added "" to a Set and then treated every later blank-id row as a
+// duplicate, silently dropping them (1 of 58 imported). Here, dedup keys are the
+// non-empty id and the (always-present) name.
+
+export type RowDecision =
+ | { action: "insert" }
+ | { action: "update"; entityId: string }
+ | { action: "skip"; reason: string };
+
+export function classifyImportRow(params: {
+ id: string;
+ name: string;
+ externalIdMap: Map<string, string>;
+ nameMap: Map<string, string>;
+ seenIds: Set<string>;
+ seenNames: Set<string>;
+}): RowDecision {
+ const { id, name, externalIdMap, nameMap, seenIds, seenNames } = 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" };
+ }
+ if (id && seenIds.has(id)) {
+ return { action: "skip", reason: `Duplicate ID "${id}" in file` };
+ }
+ if (seenNames.has(name)) {
+ return { action: "skip", reason: `Duplicate name "${name}" in file` };
+ }
+
+ // The CSV name is matched as-is. Whitespace/case normalization is intentionally
+ // out of scope for this data-loss fix and is handled by the later identity redesign.
+ const matchedById = id ? externalIdMap.get(id) : undefined;
+ const matchedByName = matchedById === undefined ? nameMap.get(name) : undefined;
+ const existingEntityId = matchedById ?? matchedByName;
+
+ if (existingEntityId !== undefined) {
+ return { action: "update", entityId: existingEntityId };
+ }
+ return { action: "insert" };
+}
diff --git a/packages/database/supabase/functions/import-csv/index.ts b/packages/database/supabase/functions/import-csv/index.ts
index 6cd2e2eead..21735b6731 100644
--- a/packages/database/supabase/functions/import-csv/index.ts
+++ b/packages/database/supabase/functions/import-csv/index.ts
@@ -8,6 +8,7 @@ import { corsHeaders } from "../lib/headers.ts";
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";
const pool = getConnectionPool(1);
const db = getDatabaseClient<DB>(pool);
@@ -256,14 +257,17 @@ async function upsertCsvMappings(
cId: string,
userId: string
): Promise<void> {
- if (mappings.length === 0) return;
+ // Skip blank external ids: they carry no match value, and multiple "" rows
+ // would collide on the ON CONFLICT key and abort the entire batch insert.
+ const valid = mappings.filter((m) => m.externalId);
+ if (valid.length === 0) return;
const now = new Date().toISOString();
await trx
.insertInto("externalIntegrationMapping")
.values(
- mappings.map((m) => ({
+ valid.map((m) => ({
entityType,
entityId: m.entityId,
integration: EXTERNAL_ID_KEY,
@@ -861,6 +865,12 @@ serve(async (req: Request) => {
});
}
+ const summary = {
+ inserted: 0,
+ updated: 0,
+ errors: [] as Array<{ row: number; reason: string }>,
+ };
+
switch (table) {
case "customer": {
const externalIdMap = await getCsvExternalIdMap("customer", companyId);
@@ -872,7 +882,7 @@ serve(async (req: Request) => {
)
);
const nameMap = await getNameMap("customer", companyId, csvNames);
- const customerIds = new Set();
+ const customerIds = new Set<string>();
// Tracks names queued for INSERT in this batch so a second CSV row
// with the same name doesn't trip the (name, companyId) unique
// constraint at flush time. The customer table enforces one record
@@ -907,13 +917,7 @@ serve(async (req: Request) => {
ext: PartnerExtensionData;
}> = [];
- const isCustomerValid = (
- record: Record<string, string>
- ): record is { name: string } => {
- return typeof record.name === "string" && record.name.trim() !== "";
- };
-
- for (const record of mappedRecords) {
+ for (const [rowIndex, record] of mappedRecords.entries()) {
const ext = extractPartnerExtensions(record);
const {
id,
@@ -931,42 +935,46 @@ serve(async (req: Request) => {
incotermLocation: _icl,
...rest
} = record;
- const matchedByCsvId = externalIdMap.get(id);
- const matchedByName =
- matchedByCsvId === undefined && rest.name
- ? nameMap.get(rest.name)
- : undefined;
- const existingEntityId = matchedByCsvId ?? matchedByName;
-
- if (existingEntityId !== undefined) {
- if (isCustomerValid(rest) && !customerIds.has(id)) {
- customerIds.add(id);
- customerUpdates.push({
- id: existingEntityId,
- data: {
- ...nullifyEmptyStrings(rest),
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
- },
+ const matchedByCsvId = id ? externalIdMap.get(id) : undefined;
+ const decision = classifyImportRow({
+ id,
+ name: rest.name,
+ externalIdMap,
+ nameMap,
+ seenIds: customerIds,
+ seenNames: namesQueuedForInsert,
+ });
+
+ if (decision.action === "skip") {
+ summary.errors.push({ row: rowIndex, reason: decision.reason });
+ continue;
+ }
+
+ if (id) customerIds.add(id);
+ if (decision.action === "insert") namesQueuedForInsert.add(rest.name);
+
+ if (decision.action === "update") {
+ customerUpdates.push({
+ id: decision.entityId,
+ data: {
+ ...nullifyEmptyStrings(rest),
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ },
+ });
+ customerTaxUpdates.push({ entityId: decision.entityId, taxId });
+ extForUpdates.push({ entityId: decision.entityId, ext });
+ // Only attach a CSV->entity mapping when there is a real external id.
+ if (matchedByCsvId === undefined && id) {
+ csvIdsForNameMatchedUpdates.push({
+ entityId: decision.entityId,
+ externalId: id,
});
- customerTaxUpdates.push({ entityId: existingEntityId, taxId });
- extForUpdates.push({ entityId: existingEntityId, ext });
- if (matchedByCsvId === undefined) {
- csvIdsForNameMatchedUpdates.push({
- entityId: existingEntityId,
- externalId: id,
- });
- }
}
- } else if (isCustomerValid(rest) && !customerIds.has(id)) {
- if (namesQueuedForInsert.has(rest.name)) continue;
- customerIds.add(id);
- namesQueuedForInsert.add(rest.name);
+ } else {
customerInserts.push({
...nullifyEmptyStrings(rest),
- // Use the CSV's Unique ID as the readableId; trigger no-ops
- // when readableId is non-null.
- readableId: id,
+ readableId: id || null,
companyId,
createdAt: new Date().toISOString(),
createdBy: userId,
@@ -982,6 +990,8 @@ serve(async (req: Request) => {
customerInserts: customerInserts.length,
customerUpdates: customerUpdates.length,
});
+ summary.inserted += customerInserts.length;
+ summary.updated += customerUpdates.length;
if (customerInserts.length > 0) {
const inserted = await trx
@@ -1075,7 +1085,7 @@ serve(async (req: Request) => {
)
);
const nameMap = await getNameMap("supplier", companyId, csvNames);
- const supplierIds = new Set();
+ const supplierIds = new Set<string>();
const namesQueuedForInsert = new Set<string>();
await db.transaction().execute(async (trx) => {
@@ -1106,13 +1116,7 @@ serve(async (req: Request) => {
ext: PartnerExtensionData;
}> = [];
- const isSupplierValid = (
- record: Record<string, string>
- ): record is { name: string } => {
- return typeof record.name === "string" && record.name.trim() !== "";
- };
-
- for (const record of mappedRecords) {
+ for (const [rowIndex, record] of mappedRecords.entries()) {
const ext = extractPartnerExtensions(record);
const {
id,
@@ -1130,42 +1134,46 @@ serve(async (req: Request) => {
incotermLocation: _icl,
...rest
} = record;
- const matchedByCsvId = externalIdMap.get(id);
- const matchedByName =
- matchedByCsvId === undefined && rest.name
- ? nameMap.get(rest.name)
- : undefined;
- const existingEntityId = matchedByCsvId ?? matchedByName;
-
- if (existingEntityId !== undefined && !supplierIds.has(id)) {
- supplierIds.add(id);
- if (isSupplierValid(rest)) {
- supplierUpdates.push({
- id: existingEntityId,
- data: {
- ...nullifyEmptyStrings(rest),
- updatedAt: new Date().toISOString(),
- updatedBy: userId,
- },
+ const matchedByCsvId = id ? externalIdMap.get(id) : undefined;
+ const decision = classifyImportRow({
+ id,
+ name: rest.name,
+ externalIdMap,
+ nameMap,
+ seenIds: supplierIds,
+ seenNames: namesQueuedForInsert,
+ });
+
+ if (decision.action === "skip") {
+ summary.errors.push({ row: rowIndex, reason: decision.reason });
+ continue;
+ }
+
+ if (id) supplierIds.add(id);
+ if (decision.action === "insert") namesQueuedForInsert.add(rest.name);
+
+ if (decision.action === "update") {
+ supplierUpdates.push({
+ id: decision.entityId,
+ data: {
+ ...nullifyEmptyStrings(rest),
+ updatedAt: new Date().toISOString(),
+ updatedBy: userId,
+ },
+ });
+ supplierTaxUpdates.push({ entityId: decision.entityId, taxId });
+ extForUpdates.push({ entityId: decision.entityId, ext });
+ // Only attach a CSV->entity mapping when there is a real external id.
+ if (matchedByCsvId === undefined && id) {
+ csvIdsForNameMatchedUpdates.push({
+ entityId: decision.entityId,
+ externalId: id,
});
- supplierTaxUpdates.push({ entityId: existingEntityId, taxId });
- extForUpdates.push({ entityId: existingEntityId, ext });
- if (matchedByCsvId === undefined) {
- csvIdsForNameMatchedUpdates.push({
- entityId: existingEntityId,
- externalId: id,
- });
- }
}
- } else if (isSupplierValid(rest) && !supplierIds.has(id)) {
- if (namesQueuedForInsert.has(rest.name)) continue;
- supplierIds.add(id);
- namesQueuedForInsert.add(rest.name);
+ } else {
supplierInserts.push({
...nullifyEmptyStrings(rest),
- // Use the CSV's Unique ID as the readableId; trigger no-ops
- // when readableId is non-null.
- readableId: id,
+ readableId: id || null,
companyId,
createdAt: new Date().toISOString(),
createdBy: userId,
@@ -1181,6 +1189,8 @@ serve(async (req: Request) => {
supplierInserts: supplierInserts.length,
supplierUpdates: supplierUpdates.length,
});
+ summary.inserted += supplierInserts.length;
+ summary.updated += supplierUpdates.length;
if (supplierInserts.length > 0) {
const inserted = await trx
@@ -1714,7 +1724,7 @@ serve(async (req: Request) => {
);
};
- for (const record of mappedRecords) {
+ for (const [rowIndex, record] of mappedRecords.entries()) {
const { id, companyId: customerId, ...contactData } = record;
if (externalContactIdMap.has(id)) {
@@ -1746,9 +1756,19 @@ serve(async (req: Request) => {
customerId: existingCustomerId,
customFields: {},
});
+ } else {
+ summary.errors.push({
+ row: rowIndex,
+ reason: isContactValid(contactData)
+ ? `No customer found for External Company ID "${customerId}"`
+ : "Invalid contact (missing required fields)",
+ });
}
}
+ summary.inserted += contactInserts.length;
+ summary.updated += contactUpdates.length;
+
console.log({
totalRecords: mappedRecords.length,
contactInserts: contactInserts.length,
@@ -1825,7 +1845,7 @@ serve(async (req: Request) => {
);
};
- for (const record of mappedRecords) {
+ for (const [rowIndex, record] of mappedRecords.entries()) {
const { id, companyId: supplierId, ...contactData } = record;
if (externalContactIdMap.has(id)) {
@@ -1856,9 +1876,19 @@ serve(async (req: Request) => {
supplierId: existingSupplierId,
customFields: {},
});
+ } else {
+ summary.errors.push({
+ row: rowIndex,
+ reason: isContactValid(contactData)
+ ? `No supplier found for External Company ID "${supplierId}"`
+ : "Invalid contact (missing required fields)",
+ });
}
}
+ summary.inserted += contactInserts.length;
+ summary.updated += contactUpdates.length;
+
console.log({
totalRecords: mappedRecords.length,
contactInserts: contactInserts.length,
@@ -2109,6 +2139,10 @@ serve(async (req: Request) => {
return new Response(
JSON.stringify({
success: true,
+ inserted: summary.inserted,
+ updated: summary.updated,
+ skipped: summary.errors.length,
+ errors: summary.errors,
}),
{
headers: { ...corsHeaders, "Content-Type": "application/json" },
diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.po
index 6fcfe9a44d..d73cf050b4 100644
--- a/packages/locale/locales/de/erp.po
+++ b/packages/locale/locales/de/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} nicht beprobte Entitäten werden freigegeben. Beprobte Annahmen blei
msgid "{0} uploaded successfully"
msgstr "{0} erfolgreich hochgeladen"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB-Limit"
@@ -1832,6 +1836,10 @@ msgstr "Erstellen"
msgid "Create {0}"
msgstr "Erstelle {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "Erstellen Sie eine neue Kanban-Karte für scan-basierte Nachschubversorgung."
@@ -8497,6 +8505,9 @@ msgstr "Artikelstamm anzeigen"
msgid "View maintenance dispatch"
msgstr "Wartungseinsatz anzeigen"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "Offene anzeigen"
diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.po
index 0108684be3..9ad38b39f2 100644
--- a/packages/locale/locales/en/erp.po
+++ b/packages/locale/locales/en/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} un-sampled entities will be released to Available. Sampled passes st
msgid "{0} uploaded successfully"
msgstr "{0} uploaded successfully"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr "{0} values missing"
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
@@ -1832,6 +1836,10 @@ msgstr "Create"
msgid "Create {0}"
msgstr "Create {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr "Create {0} values"
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "Create a new kanban card for scan-based replenishment."
@@ -8497,6 +8505,9 @@ msgstr "View Item Master"
msgid "View maintenance dispatch"
msgstr "View maintenance dispatch"
+msgid "View missing values"
+msgstr "View missing values"
+
msgid "View Open"
msgstr "View Open"
diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.po
index a6d954e0b5..9636a8c050 100644
--- a/packages/locale/locales/es/erp.po
+++ b/packages/locale/locales/es/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} entidades no muestreadas serán liberadas a Disponible. Los pases mu
msgid "{0} uploaded successfully"
msgstr "{0} cargado exitosamente"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB límite"
@@ -1832,6 +1836,10 @@ msgstr "Crear"
msgid "Create {0}"
msgstr "Crear {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "Crea una nueva tarjeta kanban para reabastecimiento basado en escaneo."
@@ -8497,6 +8505,9 @@ msgstr "Ver Maestro de Artículos"
msgid "View maintenance dispatch"
msgstr "Ver despacho de mantenimiento"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "Ver Abiertos"
diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.po
index 838f900176..405684ce1c 100644
--- a/packages/locale/locales/fr/erp.po
+++ b/packages/locale/locales/fr/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} entités non échantillonnées seront libérées en Disponible. Les
msgid "{0} uploaded successfully"
msgstr "{0} téléchargé avec succès"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limite"
@@ -1832,6 +1836,10 @@ msgstr "Créer"
msgid "Create {0}"
msgstr "Créer {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "Créer une nouvelle carte kanban pour le réapprovisionnement basé sur la numérisation."
@@ -8497,6 +8505,9 @@ msgstr "Afficher la fiche article"
msgid "View maintenance dispatch"
msgstr "Afficher la dépêche de maintenance"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "Afficher les ouvertes"
diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.po
index 936ed0c92d..d650e0f5cc 100644
--- a/packages/locale/locales/hi/erp.po
+++ b/packages/locale/locales/hi/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} नमूना न किए गए इकाइयों को
msgid "{0} uploaded successfully"
msgstr "{0} सफलतापूर्वक अपलोड हो गया"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB सीमा"
@@ -1832,6 +1836,10 @@ msgstr "बनाएं"
msgid "Create {0}"
msgstr "{0} बनाएं"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "स्कैन-आधारित पुनःपूर्ति के लिए एक नया कानबन कार्ड बनाएं।"
@@ -8497,6 +8505,9 @@ msgstr "आइटम मास्टर देखें"
msgid "View maintenance dispatch"
msgstr "रखरखाव डिस्पैच देखें"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "खुला देखें"
diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.po
index ca165378e8..205bf39028 100644
--- a/packages/locale/locales/it/erp.po
+++ b/packages/locale/locales/it/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} entità non campionate verranno rilasciate a Disponibile. I campioni
msgid "{0} uploaded successfully"
msgstr "{0} caricato con successo"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limite"
@@ -1832,6 +1836,10 @@ msgstr "Crea"
msgid "Create {0}"
msgstr "Crea {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "Crea una nuova scheda kanban per il rifornimento basato su scansione."
@@ -8497,6 +8505,9 @@ msgstr "Visualizza Anagrafica Articolo"
msgid "View maintenance dispatch"
msgstr "Visualizza manutenzione dispatch"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "Visualizza Aperto"
diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.po
index 2cca47e4b5..eb8b8cdaa4 100644
--- a/packages/locale/locales/ja/erp.po
+++ b/packages/locale/locales/ja/erp.po
@@ -50,6 +50,10 @@ msgstr "{0}個の未サンプリングエンティティが利用可能にリリ
msgid "{0} uploaded successfully"
msgstr "{0}が正常にアップロードされました"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB制限"
@@ -1832,6 +1836,10 @@ msgstr "作成"
msgid "Create {0}"
msgstr "{0}を作成"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "スキャンベースの補充用に新しいかんばんカードを作成します。"
@@ -8497,6 +8505,9 @@ msgstr "アイテムマスターを表示"
msgid "View maintenance dispatch"
msgstr "メンテナンスディスパッチを表示"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "開く"
diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.po
index 452f1b2c7d..2cf44b4e15 100644
--- a/packages/locale/locales/pl/erp.po
+++ b/packages/locale/locales/pl/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} nieprzetestowane jednostki zostaną zwolnione do Dostępne. Przebada
msgid "{0} uploaded successfully"
msgstr "{0} przesłano pomyślnie"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
@@ -1832,6 +1836,10 @@ msgstr "Utwórz"
msgid "Create {0}"
msgstr "Utwórz {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "Utwórz nową kartę kanban do uzupełniania opartego na skanowaniu."
@@ -8497,6 +8505,9 @@ msgstr "Wyświetl Główny Katalog Pozycji"
msgid "View maintenance dispatch"
msgstr "Wyświetl dyspozycję konserwacji"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "Wyświetl Otwarte"
diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.po
index f39a2b9a0c..02a5bc6227 100644
--- a/packages/locale/locales/pt/erp.po
+++ b/packages/locale/locales/pt/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} entidades não amostradas serão liberadas para Disponível. Passes
msgid "{0} uploaded successfully"
msgstr "{0} enviado com sucesso"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB limit"
@@ -1832,6 +1836,10 @@ msgstr "Criar"
msgid "Create {0}"
msgstr "Criar {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "Crie um novo cartão kanban para reabastecimento baseado em varredura."
@@ -8497,6 +8505,9 @@ msgstr "Ver Mestre do Item"
msgid "View maintenance dispatch"
msgstr "Ver despacho de manutenção"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "Ver Abertos"
diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.po
index f356b2eb6f..057c5d632b 100644
--- a/packages/locale/locales/ru/erp.po
+++ b/packages/locale/locales/ru/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} необследованных объектов будут отпу
msgid "{0} uploaded successfully"
msgstr "{0} успешно загружен"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}МБ максимум"
@@ -1832,6 +1836,10 @@ msgstr "Создать"
msgid "Create {0}"
msgstr "Создать {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "Создайте новую карточку канбана для пополнения на основе сканирования."
@@ -8497,6 +8505,9 @@ msgstr "Просмотр основных данных товара"
msgid "View maintenance dispatch"
msgstr "Просмотр заказа на техническое обслуживание"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "Просмотреть открытые"
diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.po
index 86820dfc45..b08cd6bcc4 100644
--- a/packages/locale/locales/zh/erp.po
+++ b/packages/locale/locales/zh/erp.po
@@ -50,6 +50,10 @@ msgstr "{0} 个未采样的实体将被释放到可用状态。已采样的合
msgid "{0} uploaded successfully"
msgstr "{0} 上传成功"
+#. placeholder {0}: unmatchedValues.length
+msgid "{0} values missing"
+msgstr ""
+
msgid "{maxSizeMB}MB limit"
msgstr "{maxSizeMB}MB 限制"
@@ -1832,6 +1836,10 @@ msgstr "创建"
msgid "Create {0}"
msgstr "创建 {0}"
+#. placeholder {0}: unmatchedValues.length
+msgid "Create {0} values"
+msgstr ""
+
msgid "Create a new kanban card for scan-based replenishment."
msgstr "为扫描式补货创建新的看板卡。"
@@ -8497,6 +8505,9 @@ msgstr "查看物料主数据"
msgid "View maintenance dispatch"
msgstr "查看维护派遣"
+msgid "View missing values"
+msgstr ""
+
msgid "View Open"
msgstr "查看开放"