A full-featured CRM built with React, shadcn/ui, and Supabase.
Apply review
erwanMarmelab13bd219e5357
diff --git a/src/components/atomic-crm/contacts/useContactImport.tsx b/src/components/atomic-crm/contacts/useContactImport.tsxindex f2145333..dd124501 100644--- a/src/components/atomic-crm/contacts/useContactImport.tsx+++ b/src/components/atomic-crm/contacts/useContactImport.tsx@@ -2,6 +2,7 @@ import { useDataProvider, useGetIdentity } from "ra-core";import { useCallback, useMemo } from "react";import type { Tag } from "../types";+import { createEachRow } from "../dataImport/createEachRow";import { fetchRecordsWithCache } from "../dataImport/fetchRecordsWithCache";import { useCompanyResolver } from "../dataImport/useCompanyResolver";@@ -64,9 +65,9 @@ export function useContactImport() {getTags(batch.flatMap((batch) => parseTags(batch.tags))),]);- await Promise.all(+ return createEachRow(batch.map(- async ({+ ({first_name,last_name,gender,diff --git a/src/components/atomic-crm/dashboard/DashboardStepper.test.tsx b/src/components/atomic-crm/dashboard/DashboardStepper.test.tsxindex 6bbf5142..557c666a 100644--- a/src/components/atomic-crm/dashboard/DashboardStepper.test.tsx+++ b/src/components/atomic-crm/dashboard/DashboardStepper.test.tsx@@ -1,9 +1,18 @@-import { describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";import { render } from "vitest-browser-react";import { FirstStep } from "./DashboardStepper.stories";+// The test viewport is narrower than the mobile breakpoint, so the desktop+// branch of the stepper is only reachable by driving the hook itself.+const mockIsMobile = vi.hoisted(() => vi.fn(() => false));+vi.mock("@/hooks/use-mobile", () => ({ useIsMobile: mockIsMobile }));+describe("DashboardStepper", () => {+ beforeEach(() => {+ mockIsMobile.mockReturnValue(false);+ });+it("opens the data import dialog from the onboarding header", async () => {const screen = await render(<FirstStep />);@@ -15,4 +24,25 @@ describe("DashboardStepper", () => {await expect.element(screen.getByLabelText("Resource")).toBeVisible();});++ it("links to the contact creation page on desktop", async () => {+ const screen = await render(<FirstStep />);++ // A plain link, as CreateButton renders one: an anchor given role="button"+ // is announced as a button but does not answer to Space+ await expect+ .element(screen.getByRole("link", { name: "Add contact" }))+ .toHaveAttribute("href", "/contacts/create");+ });++ it("opens the contact creation sheet on mobile", async () => {+ mockIsMobile.mockReturnValue(true);+ const screen = await render(<FirstStep />);++ await screen.getByRole("button", { name: "Add contact" }).click();++ await expect+ .element(screen.getByRole("heading", { name: "New Contact" }))+ .toBeVisible();+ });});diff --git a/src/components/atomic-crm/dashboard/DashboardStepper.tsx b/src/components/atomic-crm/dashboard/DashboardStepper.tsxindex fbcab5d4..d452fcfb 100644--- a/src/components/atomic-crm/dashboard/DashboardStepper.tsx+++ b/src/components/atomic-crm/dashboard/DashboardStepper.tsx@@ -3,7 +3,7 @@ import { Card, CardContent } from "@/components/ui/card";import { Progress } from "@/components/ui/progress";import { CheckCircle, Circle, Plus } from "lucide-react";import type { Identifier } from "ra-core";-import { useTranslate } from "ra-core";+import { useCreatePath, useTranslate } from "ra-core";import { useState } from "react";import { Link } from "react-router";@@ -21,6 +21,7 @@ export const DashboardStepper = ({contactId?: Identifier;}) => {const translate = useTranslate();+ const createPath = useCreatePath();const appbarHeight = useAppBarHeight();const isMobile = useIsMobile();const [contactCreateOpen, setContactCreateOpen] = useState(false);@@ -100,7 +101,12 @@ export const DashboardStepper = ({</Button>) : (<Button asChild className="w-fit">- <Link role="button" to="/contacts/create">+ <Link+ to={createPath({+ resource: "contacts",+ type: "create",+ })}+ >{addContactLabel}</Link></Button>@@ -134,7 +140,13 @@ export const DashboardStepper = ({</Button>) : (<Button asChild disabled={step < 2} className="w-fit">- <Link role="button" to={`/contacts/${contactId}/show`}>+ <Link+ to={createPath({+ resource: "contacts",+ type: "show",+ id: contactId,+ })}+ >{translate("resources.notes.action.add", {_: "Add note",})}diff --git a/src/components/atomic-crm/dataImport/DataImportButton.test.tsx b/src/components/atomic-crm/dataImport/DataImportButton.test.tsxindex 7d7c8ec3..cff7156b 100644--- a/src/components/atomic-crm/dataImport/DataImportButton.test.tsx+++ b/src/components/atomic-crm/dataImport/DataImportButton.test.tsx@@ -3,8 +3,12 @@ import { render } from "vitest-browser-react";import { useState } from "react";import { createDataProvider } from "@/components/atomic-crm/providers/fakerest";+import { DEFAULT_USER } from "@/components/atomic-crm/providers/fakerest/authProvider";+import type { Db } from "@/components/atomic-crm/providers/fakerest/dataGenerator/types";+import type { Deal } from "@/components/atomic-crm/types";import { createCrmDb, StoryWrapper } from "@/test/StoryWrapper";import type { DataProvider } from "ra-core";+import { DataImportButton } from "./DataImportButton";import { AllResources, SingleResource } from "./DataImportButton.stories";import type { ImportRow, ProcessImportBatch } from "./types";import { useCompanyImport } from "./useCompanyImport";@@ -52,9 +56,10 @@ const ImportHarness = ({const renderImport = async (useImport: () => ProcessImportBatch,rows: ImportRow[],+ db?: Partial<Db>,) => {const dataProvider = createDataProvider({- db: createCrmDb(),+ db: createCrmDb(db),latency: 0,silent: true,});@@ -66,6 +71,10 @@ const renderImport = async (return { dataProvider, screen };};+/** A CSV file as the file input would hand it to the dialog. */+const csvFile = (name: string, lines: string[]) =>+ new File([lines.join("\n")], name, { type: "text/csv" });+describe("DataImportButton", () => {beforeEach(() => {mockIsMobile.mockReturnValue(false);@@ -219,4 +228,157 @@ describe("DataImportButton", () => {// stage is required, so an empty cell falls back to the first stageexpect(deals[1].stage).toBe("opportunity");});++ it("appends imported deals below the deals already in their stage", async () => {+ const { dataProvider, screen } = await renderImport(+ useDealImport,+ [+ { name: "First", stage: "Opportunity" },+ { name: "Second", stage: "Opportunity" },+ { name: "Other column", stage: "Proposal Sent" },+ ],+ {+ deals: [+ { id: 1, name: "Already there", stage: "opportunity", index: 0 },+ ] as Deal[],+ },+ );++ await screen.getByRole("button", { name: "run import" }).click();+ await expect.element(screen.getByText("imported")).toBeVisible();++ const { data: deals } = await listAll(dataProvider, "deals");+ // The Kanban board sorts a column on `index` and reorders it by shifting+ // the indexes around the drop target, so two deals of one stage sharing an+ // index cannot be dragged at all+ expect(+ deals.map(({ name, stage, index }) => ({ name, stage, index })),+ ).toEqual([+ { name: "Already there", stage: "opportunity", index: 0 },+ { name: "First", stage: "opportunity", index: 1 },+ { name: "Second", stage: "opportunity", index: 2 },+ { name: "Other column", stage: "proposal-sent", index: 0 },+ ]);+ });++ it("imports a deal the dialog parsed, down to its owner", async () => {+ const dataProvider = createDataProvider({+ db: createCrmDb(),+ latency: 0,+ silent: true,+ });+ const screen = await render(+ <StoryWrapper dataProvider={dataProvider}>+ <DataImportButton />+ </StoryWrapper>,+ );++ await screen.getByRole("button", { name: "Import data" }).click();+ await screen.getByLabelText("Resource").click();+ await screen.getByRole("listbox").getByText("Deals").click();++ await screen+ .getByLabelText("CSV File")+ .upload(+ csvFile("deals.csv", [+ "name,company,stage,amount,expected_closing_date",+ "New website,Acme,Proposal Sent,4500.50,2026-09-30",+ ]),+ );+ await screen.getByRole("button", { name: "Start import" }).click();++ await expect.element(screen.getByText(/Import complete/)).toBeVisible();++ const { data: deals } = await listAll(dataProvider, "deals");+ expect(deals).toHaveLength(1);+ // The hooks are read through the dialog rather than called directly, so the+ // wiring this feature adds is covered too — the owner in particular, which+ // the dialog is the only thing to bring in+ expect(deals[0]).toMatchObject({+ // A fractional amount would make the bigint column reject the row+ amount: 4501,+ sales_id: DEFAULT_USER.id,+ stage: "proposal-sent",+ });+ expect(deals[0].expected_closing_date).toBe("2026-09-30T00:00:00.000Z");+ });++ it("keeps the leading zero of the text columns of a company CSV", async () => {+ const dataProvider = createDataProvider({+ db: createCrmDb(),+ latency: 0,+ silent: true,+ });+ const screen = await render(+ <StoryWrapper dataProvider={dataProvider}>+ <DataImportButton resource="companies" />+ </StoryWrapper>,+ );++ await screen.getByRole("button", { name: "Import CSV" }).click();+ await screen+ .getByLabelText("CSV File")+ .upload(+ csvFile("companies.csv", [+ "name,zipcode,phone_number,tax_identifier",+ "Acme,02134,0155123456,0123456789",+ ]),+ );+ await screen.getByRole("button", { name: "Start import" }).click();++ await expect.element(screen.getByText(/Import complete/)).toBeVisible();++ const { data: companies } = await listAll(dataProvider, "companies");+ expect(companies[0]).toMatchObject({+ phone_number: "0155123456",+ tax_identifier: "0123456789",+ zipcode: "02134",+ });+ });++ it("reports as errors only the rows the backend refused", async () => {+ const dataProvider = createDataProvider({+ db: createCrmDb(),+ latency: 0,+ silent: true,+ });+ const screen = await render(+ <StoryWrapper+ dataProvider={{+ ...dataProvider,+ // `name` is NOT NULL in the database+ create: (resource, params) =>+ resource === "companies" && params.data.name === undefined+ ? Promise.reject(new Error("null value in column name"))+ : dataProvider.create(resource, params),+ }}+ >+ <DataImportButton resource="companies" />+ </StoryWrapper>,+ );++ await screen.getByRole("button", { name: "Import CSV" }).click();+ await screen+ .getByLabelText("CSV File")+ .upload(+ csvFile("companies.csv", [+ "name,city",+ "Acme,New York",+ ",Boston",+ "Globex,Paris",+ ]),+ );+ await screen.getByRole("button", { name: "Start import" }).click();++ // A rejected row used to fail the accounting of its whole batch, so users+ // re-imported a file whose records had in fact been created+ await expect+ .element(+ screen.getByText("Import complete. Imported 2 records, with 1 errors"),+ )+ .toBeVisible();++ const { data: companies } = await listAll(dataProvider, "companies");+ expect(companies.map(({ name }) => name)).toEqual(["Acme", "Globex"]);+ });});diff --git a/src/components/atomic-crm/dataImport/DataImportDialog.tsx b/src/components/atomic-crm/dataImport/DataImportDialog.tsxindex f152bee0..d0c1b37a 100644--- a/src/components/atomic-crm/dataImport/DataImportDialog.tsx+++ b/src/components/atomic-crm/dataImport/DataImportDialog.tsx@@ -47,9 +47,17 @@ export function DataImportDialog({const translate = useTranslate();const getResourceLabel = useGetResourceLabel();const refresh = useRefresh();- const [resource, setResource] = useState(resources[0]);+ const [resourceName, setResourceName] = useState(resources[0].name);const [file, setFile] = useState<File | null>(null);+ // The resource is read from `resources` on every render, keeping only the+ // selected name in state: `useConfigurationLoader` fills the configuration+ // asynchronously, so a resource object captured at mount would keep its+ // `processBatch` pinned to `defaultConfiguration` — importing a deal into a+ // stage that does not exist in a customized pipeline, and with no `sales_id`.+ const resource =+ resources.find(({ name }) => name === resourceName) ?? resources[0];+// Importing a single resource names the dialog after it, falling back to the// generic heading for a resource that has no title of its own.const title = useResourceTranslation({@@ -61,6 +69,7 @@ export function DataImportDialog({});const { importer, parseCsv, reset } = usePapaParse<ImportRow>({batchSize: 10,+ textColumns: resource.textColumns,processBatch: resource.processBatch,});@@ -76,7 +85,7 @@ export function DataImportDialog({const next = resources.find((candidate) => candidate.name === name);if (!next) return;setFile(null);- setResource(next);+ setResourceName(next.name);};const handleFileChange = (file: File | null) => {@@ -220,7 +229,7 @@ export function DataImportDialog({<FormToolbar>{importer.state === "idle" ? (<Button onClick={startImport} disabled={!file}>- {translate("crm.data_import.button")}+ {translate("crm.data_import.start")}</Button>) : (<Buttondiff --git a/src/components/atomic-crm/dataImport/createEachRow.ts b/src/components/atomic-crm/dataImport/createEachRow.tsnew file mode 100644index 00000000..6f4177b6--- /dev/null+++ b/src/components/atomic-crm/dataImport/createEachRow.ts@@ -0,0 +1,21 @@+/**+ * Creates one record per row and reports how many actually landed.+ *+ * `Promise.all` would reject on the first row the database refuses while the+ * other creates have already fired, so `usePapaParse` counted a whole batch as+ * failed even though most of its records existed — users then fixed the file+ * and re-imported, duplicating everything that had gone through. Settling every+ * create instead keeps the report in line with what was written.+ */+export const createEachRow = async (+ creates: Promise<unknown>[],+): Promise<number> => {+ const results = await Promise.allSettled(creates);+ const rejected = results.filter(+ (result): result is PromiseRejectedResult => result.status === "rejected",+ );+ for (const { reason } of rejected) {+ console.error("Failed to import a row", reason);+ }+ return results.length - rejected.length;+};diff --git a/src/components/atomic-crm/dataImport/parseCell.test.ts b/src/components/atomic-crm/dataImport/parseCell.test.tsindex e5c88436..f7f78e0a 100644--- a/src/components/atomic-crm/dataImport/parseCell.test.ts+++ b/src/components/atomic-crm/dataImport/parseCell.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from "vitest";-import { toConfiguredValue, toIsoDate, toNumber, toText } from "./parseCell";+import {+ toConfiguredValue,+ toInteger,+ toIsoDate,+ toNumber,+ toText,+} from "./parseCell";const stages = [{ value: "opportunity", label: "Opportunity" },@@ -35,14 +41,39 @@ describe("toNumber", () => {});});+describe("toInteger", () => {+ it("rounds a fractional cell, which an integer column would reject", () => {+ expect(toInteger("4500.50")).toBe(4501);+ expect(toInteger(12000)).toBe(12000);+ });++ it("returns undefined for an empty or non-numeric cell", () => {+ expect(toInteger(null)).toBeUndefined();+ expect(toInteger("a lot")).toBeUndefined();+ });+});+describe("toIsoDate", () => {it("converts a date cell to an ISO string", () => {expect(toIsoDate("2026-09-30")).toBe("2026-09-30T00:00:00.000Z");});- it("returns undefined for an empty or unparsable cell", () => {+ it("reads the date as UTC, whatever the timezone of the browser", () => {+ // A local-midnight date shifts to the previous day in any timezone ahead+ // of UTC, and a date column then stores the wrong day+ expect(toIsoDate("2026-01-01")).toBe("2026-01-01T00:00:00.000Z");+ expect(toIsoDate("2026-12-31")).toBe("2026-12-31T00:00:00.000Z");+ });++ it("returns undefined for a cell that is not a plain YYYY-MM-DD date", () => {expect(toIsoDate(null)).toBeUndefined();expect(toIsoDate("next quarter")).toBeUndefined();+ // Ambiguous or locale-dependent formats are refused rather than guessed+ expect(toIsoDate("09/30/2026")).toBeUndefined();+ expect(toIsoDate("30/09/2026")).toBeUndefined();+ // An impossible day rolls over to the next month rather than failing+ expect(toIsoDate("2026-02-31")).toBeUndefined();+ expect(toIsoDate("2026-13-01")).toBeUndefined();});});diff --git a/src/components/atomic-crm/dataImport/parseCell.ts b/src/components/atomic-crm/dataImport/parseCell.tsindex ffd6f991..49eaea7c 100644--- a/src/components/atomic-crm/dataImport/parseCell.ts+++ b/src/components/atomic-crm/dataImport/parseCell.ts@@ -16,12 +16,38 @@ export const toNumber = (cell: ImportCell): number | undefined => {return Number.isFinite(value) ? value : undefined;};-/** Cell content as an ISO 8601 date, or undefined when it is empty or invalid. */+/**+ * Cell content as a whole number, for the integer columns of the database: an+ * amount of `4500.50` would make PostgREST reject the whole row with+ * `invalid input syntax for type bigint`.+ */+export const toInteger = (cell: ImportCell): number | undefined => {+ const value = toNumber(cell);+ return value === undefined ? undefined : Math.round(value);+};++const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/;++/**+ * Cell content as an ISO 8601 date, or undefined when it is empty or is not a+ * plain `YYYY-MM-DD` date — the format the sample CSV documents.+ *+ * Only that format is accepted because `new Date(text)` reads anything else as+ * local midnight: in a timezone ahead of UTC, `09/30/2026` becomes+ * `2026-09-29T22:00:00Z`, which a `date` column truncates to the day before.+ * `dealUtils.formatISODateString` refuses `new Date` for the same reason on the+ * read path.+ */export const toIsoDate = (cell: ImportCell): string | undefined => {const text = toText(cell);- if (text === undefined) return undefined;- const date = new Date(text);- return Number.isNaN(date.getTime()) ? undefined : date.toISOString();+ if (text === undefined || !isoDateRegex.test(text)) return undefined;+ // Parsed as UTC midnight, so the stored day is the one the CSV names+ const date = new Date(`${text}T00:00:00.000Z`);+ if (Number.isNaN(date.getTime())) return undefined;+ // An impossible day rolls over rather than failing — "2026-02-31" becomes+ // March 3 — so the parsed date has to name the day back+ const iso = date.toISOString();+ return iso.startsWith(text) ? iso : undefined;};/**diff --git a/src/components/atomic-crm/dataImport/types.ts b/src/components/atomic-crm/dataImport/types.tsindex 542d9ec8..6db86928 100644--- a/src/components/atomic-crm/dataImport/types.ts+++ b/src/components/atomic-crm/dataImport/types.ts@@ -10,8 +10,11 @@ export type ImportCell = string | number | boolean | null;/** One parsed CSV row, keyed by column header. */export type ImportRow = Record<string, ImportCell>;-/** Creates the records of one batch of parsed CSV rows. */-export type ProcessImportBatch = (batch: ImportRow[]) => Promise<void>;+/**+ * Creates the records of one batch of parsed CSV rows, and returns how many of+ * them were created: the rows the database refused are the batch's errors.+ */+export type ProcessImportBatch = (batch: ImportRow[]) => Promise<number>;/** A resource the import dialog can import a CSV file into. */export type ImportableResource = {@@ -19,5 +22,10 @@ export type ImportableResource = {name: ImportableResourceName;/** CSV content offered as a downloadable template for this resource */sampleCsv: string;+ /**+ * Columns Papa Parse must leave as text, because a leading zero carries+ * meaning there: a `02134` zipcode would otherwise be stored as `2134`.+ */+ textColumns?: string[];processBatch: ProcessImportBatch;};diff --git a/src/components/atomic-crm/dataImport/useCompanyImport.ts b/src/components/atomic-crm/dataImport/useCompanyImport.tsindex a1821c84..885f4a9a 100644--- a/src/components/atomic-crm/dataImport/useCompanyImport.ts+++ b/src/components/atomic-crm/dataImport/useCompanyImport.ts@@ -3,6 +3,7 @@ import { useDataProvider, useGetIdentity } from "ra-core";import { mapSizeToCategory } from "../companies/sizes";import { useConfigurationContext } from "../root/ConfigurationContext";+import { createEachRow } from "./createEachRow";import { toConfiguredValue, toNumber, toText } from "./parseCell";import type { ImportCell, ProcessImportBatch } from "./types";@@ -16,8 +17,8 @@ export function useCompanyImport(): ProcessImportBatch {const dataProvider = useDataProvider();return useCallback(- async (batch) => {- await Promise.all(+ (batch) =>+ createEachRow(batch.map((row) =>dataProvider.create("companies", {data: {@@ -40,8 +41,7 @@ export function useCompanyImport(): ProcessImportBatch {},}),),- );- },+ ),[companySectors, dataProvider, identity?.id],);}diff --git a/src/components/atomic-crm/dataImport/useDealImport.ts b/src/components/atomic-crm/dataImport/useDealImport.tsindex 748a2e85..3bfe7a22 100644--- a/src/components/atomic-crm/dataImport/useDealImport.ts+++ b/src/components/atomic-crm/dataImport/useDealImport.ts@@ -1,10 +1,18 @@import { useCallback } from "react";-import { useDataProvider, useGetIdentity } from "ra-core";+import { useDataProvider, useGetIdentity, type DataProvider } from "ra-core";import { useConfigurationContext } from "../root/ConfigurationContext";import { useCompanyResolver } from "./useCompanyResolver";-import { toConfiguredValue, toIsoDate, toNumber, toText } from "./parseCell";-import type { ProcessImportBatch } from "./types";+import { createEachRow } from "./createEachRow";+import { toConfiguredValue, toInteger, toIsoDate, toText } from "./parseCell";+import type { ImportRow, ProcessImportBatch } from "./types";++/** One CSV row, with the values needed before its deal can be created. */+type DealRow = {+ row: ImportRow;+ companyName: string | undefined;+ stage: string | undefined;+};/*** Creates a deal per CSV row. Unknown columns are ignored, missing ones are@@ -19,22 +27,28 @@ export function useDealImport(): ProcessImportBatch {return useCallback(async (batch) => {- // Parse the company name once per row: it is needed to resolve the- // companies up front, then again to link each deal to its own.- const rows = batch.map((row) => ({+ // Parse the company name and the stage once per row: both are needed to+ // resolve companies and column indexes up front, then again per deal.+ const rows: DealRow[] = batch.map((row) => ({row,companyName: toText(row.company),+ // stage is required, so fall back to the first configured one+ stage: toConfiguredValue(row.stage, dealStages) ?? dealStages[0]?.value,}));- const companies = await getCompanies(- rows- .map(({ companyName }) => companyName)- .filter((name): name is string => name !== undefined),- );++ const [companies, indexes] = await Promise.all([+ getCompanies(+ rows+ .map(({ companyName }) => companyName)+ .filter((name): name is string => name !== undefined),+ ),+ appendedIndexes(rows, dataProvider),+ ]);const now = new Date().toISOString();- await Promise.all(- rows.map(({ row, companyName }) => {- return dataProvider.create("deals", {+ return createEachRow(+ rows.map(({ row, companyName, stage }) =>+ dataProvider.create("deals", {data: {name: toText(row.name),company_id: companyName@@ -42,22 +56,69 @@ export function useDealImport(): ProcessImportBatch {: undefined,contact_ids: [],category: toConfiguredValue(row.category, dealCategories),- // stage is required, so fall back to the first configured one- stage:- toConfiguredValue(row.stage, dealStages) ??- dealStages[0]?.value,+ stage,description: toText(row.description),- amount: toNumber(row.amount),+ // amount lands in a bigint column, which rejects "4500.50"+ amount: toInteger(row.amount),expected_closing_date: toIsoDate(row.expected_closing_date),sales_id: identity?.id,- index: 0,+ index: indexes.get(row) ?? 0,created_at: now,updated_at: now,},- });- }),+ }),+ ),);},[dataProvider, dealCategories, dealStages, getCompanies, identity?.id],);}++/**+ * One distinct index per imported deal, appended below the deals already in its+ * stage and keeping the CSV row order.+ *+ * The Kanban board sorts each column on `index`, and its drag handler shifts the+ * indexes of the cards around the drop target. A column whose deals all share+ * `index: 0` therefore cannot be reordered — the drop writes `index: 0` again+ * and the card snaps back — and its order is whatever the backend returns.+ */+const appendedIndexes = async (+ rows: DealRow[],+ dataProvider: DataProvider,+): Promise<Map<ImportRow, number>> => {+ const stages = [+ ...new Set(+ rows+ .map(({ stage }) => stage)+ .filter((stage): stage is string => stage !== undefined),+ ),+ ];+ const lastIndexes = new Map(+ await Promise.all(+ stages.map(+ async (stage) =>+ [stage, await lastIndexOf(stage, dataProvider)] as const,+ ),+ ),+ );++ return new Map(+ stages.flatMap((stage) => {+ const firstIndex = (lastIndexes.get(stage) ?? -1) + 1;+ return rows+ .filter((candidate) => candidate.stage === stage)+ .map(({ row }, position) => [row, firstIndex + position] as const);+ }),+ );+};++/** Highest index currently used in a stage, or -1 when it holds no deal. */+const lastIndexOf = async (stage: string, dataProvider: DataProvider) => {+ const { data } = await dataProvider.getList("deals", {+ filter: { stage },+ pagination: { page: 1, perPage: 1 },+ sort: { field: "index", order: "DESC" },+ });+ return data[0]?.index ?? -1;+};diff --git a/src/components/atomic-crm/dataImport/useImportableResources.ts b/src/components/atomic-crm/dataImport/useImportableResources.tsindex 1443b601..1175405d 100644--- a/src/components/atomic-crm/dataImport/useImportableResources.ts+++ b/src/components/atomic-crm/dataImport/useImportableResources.ts@@ -36,6 +36,9 @@ export function useImportableResources(): ImportableResource[] {{name: "companies",sampleCsv: companiesSampleCsv,+ // These are text columns whose leading zero must survive the parsing:+ // a "02134" zipcode would otherwise be stored as 2134.+ textColumns: ["zipcode", "phone_number", "tax_identifier"],processBatch: processCompanies,},{ name: "deals", sampleCsv: dealsSampleCsv, processBatch: processDeals },diff --git a/src/components/atomic-crm/misc/useImportFromJson.ts b/src/components/atomic-crm/misc/useImportFromJson.tsindex 454469cd..0a555f61 100644--- a/src/components/atomic-crm/misc/useImportFromJson.ts+++ b/src/components/atomic-crm/misc/useImportFromJson.ts@@ -802,8 +802,3 @@ const isTask = (data: any): data is TaskImport =>data.sales_id != null &&data.contact_id != null &&data.text != null;--/**- * Maps a company size number to the appropriate size category.- * Categories: 1, 10, 50, 250, 500- */diff --git a/src/components/atomic-crm/misc/usePapaParse.tsx b/src/components/atomic-crm/misc/usePapaParse.tsxindex c8bc8c26..7c71e204 100644--- a/src/components/atomic-crm/misc/usePapaParse.tsx+++ b/src/components/atomic-crm/misc/usePapaParse.tsx@@ -28,12 +28,16 @@ type usePapaParseProps<T> = {// The import batch sizebatchSize?: number;+ // Columns to keep as text, because a leading zero is meaningful there+ textColumns?: string[];+// processBatch returns the number of imported items- processBatch(batch: T[]): Promise<void>;+ processBatch(batch: T[]): Promise<number>;};export function usePapaParse<T>({batchSize = 10,+ textColumns,processBatch,}: usePapaParseProps<T>) {const importIdRef = useRef<number>(0);@@ -81,18 +85,25 @@ export function usePapaParse<T>({const batch = results.data.slice(i, i + batchSize);try {const start = Date.now();- await processBatch(batch);+ // A batch reports how many of its rows the backend accepted, so+ // the rows it refused count as errors while the records that did+ // land are not reported as failures.+ const created = await processBatch(batch);totalTime += Date.now() - start;const meanTime = totalTime / (i + batch.length);setImporter((previous) => {if (previous.state === "running") {- const importCount = previous.importCount + batch.length;+ const importCount = previous.importCount + created;+ const errorCount =+ previous.errorCount + (batch.length - created);return {...previous,importCount,+ errorCount,remainingTime:- meanTime * (results.data.length - importCount),+ meanTime *+ (results.data.length - importCount - errorCount),};}return previous;@@ -127,10 +138,12 @@ export function usePapaParse<T>({error,});},- dynamicTyping: true,+ // Numeric-looking cells are converted, except where a leading zero+ // carries meaning: a "02134" zipcode would be stored as 2134.+ dynamicTyping: (field) => !textColumns?.includes(String(field)),});},- [batchSize, processBatch],+ [batchSize, processBatch, textColumns],);return useMemo(diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.tsindex 813ef51b..8954d890 100644--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts@@ -443,6 +443,7 @@ export const englishCrmMessages = {running: "The import is running, please do not close this tab.",sample_download: "Download CSV sample",sample_hint: "Here is a sample CSV file you can use as a template",+ start: "Start import",stop: "Stop import",title: "Import data",},diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.tsindex e2624815..1c63328a 100644--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts@@ -450,6 +450,7 @@ export const frenchCrmMessages = {sample_download: "Télécharger un exemple CSV",sample_hint:"Voici un exemple de fichier CSV que vous pouvez utiliser comme modèle",+ start: "Démarrer l'import",stop: "Arrêter l'importation",title: "Importer des données",},