Skip to content

A full-featured CRM built with React, shadcn/ui, and Supabase.

fix(contacts): keep the CSV import alive when its dialog unmounts

Jerome578f86fead1c
diff --git a/registry.json b/registry.json
index a8337a71..92675009 100644
--- a/registry.json
+++ b/registry.json
@@ -697,6 +697,22 @@
"path": "src/components/atomic-crm/contacts/ContactInputs.tsx",
"type": "registry:component"
},
+ {
+ "path": "src/components/atomic-crm/contacts/ContactImportProvider.tsx",
+ "type": "registry:component"
+ },
+ {
+ "path": "src/components/atomic-crm/contacts/ContactImportProgressToast.tsx",
+ "type": "registry:component"
+ },
+ {
+ "path": "src/components/atomic-crm/contacts/ContactImportDialog.tsx",
+ "type": "registry:component"
+ },
+ {
+ "path": "src/components/atomic-crm/contacts/ContactImportContext.tsx",
+ "type": "registry:component"
+ },
{
"path": "src/components/atomic-crm/contacts/ContactImportButton.tsx",
"type": "registry:component"
diff --git a/src/components/atomic-crm/contacts/ContactImport.test.tsx b/src/components/atomic-crm/contacts/ContactImport.test.tsx
new file mode 100644
index 00000000..bd83be4d
--- /dev/null
+++ b/src/components/atomic-crm/contacts/ContactImport.test.tsx
@@ -0,0 +1,193 @@
+import { render } from "vitest-browser-react";
+import { useNotify } from "ra-core";
+import { toast } from "sonner";
+
+import { StoryWrapper } from "@/test/StoryWrapper";
+import { ContactImportButton } from "./ContactImportButton";
+import { useContactImportContext } from "./ContactImportContext";
+
+const ROW_COUNT = 80;
+
+const csv = [
+ "first_name,last_name",
+ ...Array.from({ length: ROW_COUNT }, (_, index) => `Ada${index},Lovelace`),
+].join("\n");
+
+let createDelay = 200;
+let createdCount = 0;
+
+const StartImportTrigger = () => {
+ const { startImport } = useContactImportContext();
+ return (
+ <button
+ onClick={() =>
+ startImport(new File([csv], "contacts.csv", { type: "text/csv" }))
+ }
+ >
+ start import
+ </button>
+ );
+};
+
+const NotifyTrigger = () => {
+ const notify = useNotify();
+ return (
+ <button onClick={() => notify("Contact updated", { type: "success" })}>
+ notify
+ </button>
+ );
+};
+
+const ImportHarness = () => (
+ <StoryWrapper
+ dataProvider={{
+ create: async (_resource, params) => {
+ await new Promise((resolve) => setTimeout(resolve, createDelay));
+ createdCount += 1;
+ return { data: { ...params.data, id: createdCount } } as any;
+ },
+ }}
+ >
+ <ContactImportButton />
+ <StartImportTrigger />
+ <NotifyTrigger />
+ </StoryWrapper>
+);
+
+const getToasterPositions = () =>
+ Array.from(document.querySelectorAll("[data-sonner-toaster]")).map(
+ (toaster) => ({
+ position: `${toaster.getAttribute("data-y-position")}-${toaster.getAttribute("data-x-position")}`,
+ text: (toaster as HTMLElement).innerText,
+ }),
+ );
+
+const dispatchBeforeUnload = () => {
+ const event = new Event("beforeunload", { cancelable: true });
+ window.dispatchEvent(event);
+ return event;
+};
+
+beforeEach(() => {
+ createDelay = 200;
+ createdCount = 0;
+});
+
+afterEach(() => {
+ toast.dismiss();
+});
+
+describe("contact import", () => {
+ it("reports progress in a snackbar and notifies when the import ends", async () => {
+ const screen = await render(<ImportHarness />);
+
+ await screen.getByRole("button", { name: "start import" }).click();
+
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .toBeInTheDocument();
+ await expect
+ .element(screen.getByText(new RegExp(`/ ${ROW_COUNT} contacts`)))
+ .toBeInTheDocument();
+
+ createDelay = 0;
+
+ await expect
+ .element(
+ screen.getByText(
+ `Contacts import complete. Imported ${ROW_COUNT} contacts, with 0 errors`,
+ ),
+ )
+ .toBeInTheDocument();
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .not.toBeInTheDocument();
+ });
+
+ it("asks the browser to confirm leaving the page only while the import runs", async () => {
+ const screen = await render(<ImportHarness />);
+
+ expect(dispatchBeforeUnload().defaultPrevented).toBe(false);
+
+ await screen.getByRole("button", { name: "start import" }).click();
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .toBeInTheDocument();
+
+ expect(dispatchBeforeUnload().defaultPrevented).toBe(true);
+
+ createDelay = 0;
+
+ await expect
+ .element(screen.getByText(/Contacts import complete/))
+ .toBeInTheDocument();
+
+ expect(dispatchBeforeUnload().defaultPrevented).toBe(false);
+ });
+
+ it("keeps the progress snackbar in its own stack when another notification pops up", async () => {
+ const screen = await render(<ImportHarness />);
+
+ await screen.getByRole("button", { name: "start import" }).click();
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .toBeInTheDocument();
+
+ await screen.getByRole("button", { name: "notify" }).click();
+ await expect.element(screen.getByText("Contact updated")).toBeVisible();
+
+ const positions = getToasterPositions();
+ const progressStack = positions.find((stack) =>
+ /Importing contacts/.test(stack.text),
+ );
+ const notificationStack = positions.find((stack) =>
+ /Contact updated/.test(stack.text),
+ );
+
+ expect(progressStack?.position).toBe("bottom-right");
+ expect(notificationStack?.position).toBe("bottom-center");
+ expect(progressStack).not.toBe(notificationStack);
+
+ createDelay = 0;
+ await expect
+ .element(screen.getByText(/Contacts import complete/))
+ .toBeInTheDocument();
+ });
+
+ it("keeps importing after the dialog is closed", async () => {
+ const screen = await render(<ImportHarness />);
+
+ await screen.getByRole("button", { name: "start import" }).click();
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .toBeInTheDocument();
+
+ await screen.getByRole("button", { name: /import csv/i }).click();
+ await expect
+ .element(screen.getByText(/The import is running/))
+ .toBeVisible();
+ await expect
+ .element(screen.getByText(/You can close this dialog/))
+ .toBeVisible();
+
+ await screen
+ .getByRole("toolbar")
+ .getByRole("button", { name: /^close$/i })
+ .click();
+
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .toBeInTheDocument();
+
+ createDelay = 0;
+
+ await expect
+ .element(
+ screen.getByText(
+ `Contacts import complete. Imported ${ROW_COUNT} contacts, with 0 errors`,
+ ),
+ )
+ .toBeInTheDocument();
+ expect(createdCount).toBe(ROW_COUNT);
+ });
+});
diff --git a/src/components/atomic-crm/contacts/ContactImportButton.tsx b/src/components/atomic-crm/contacts/ContactImportButton.tsx
index ce6e5d65..fd15121c 100644
--- a/src/components/atomic-crm/contacts/ContactImportButton.tsx
+++ b/src/components/atomic-crm/contacts/ContactImportButton.tsx
@@ -1,220 +1,20 @@
-import { useEffect, useState } from "react";
-import type { MouseEvent } from "react";
-import { Upload, Loader2 } from "lucide-react";
-import { Form, useRefresh, useTranslate } from "ra-core";
-import { Link } from "react-router";
-import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Upload } from "lucide-react";
+import { useTranslate } from "ra-core";
import { Button } from "@/components/ui/button";
-import {
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
-} from "@/components/ui/dialog";
-import { FormToolbar } from "@/components/admin/simple-form";
-import { FileInput } from "@/components/admin/file-input";
-import { FileField } from "@/components/admin/file-field";
-import { usePapaParse } from "../misc/usePapaParse";
-import type { ContactImportSchema } from "./useContactImport";
-import { useContactImport } from "./useContactImport";
-import * as sampleCsv from "./contacts_export.csv?raw";
+import { useContactImportContext } from "./ContactImportContext";
export const ContactImportButton = () => {
const translate = useTranslate();
- const [modalOpen, setModalOpen] = useState(false);
-
- const handleOpenModal = () => {
- setModalOpen(true);
- };
-
- const handleCloseModal = () => {
- setModalOpen(false);
- };
+ const { openDialog } = useContactImportContext();
return (
- <>
- <Button
- variant="outline"
- onClick={handleOpenModal}
- className="flex items-center gap-2 cursor-pointer"
- >
- <Upload /> {translate("resources.contacts.import.button")}
- </Button>
- <ContactImportDialog open={modalOpen} onClose={handleCloseModal} />
- </>
+ <Button
+ variant="outline"
+ onClick={openDialog}
+ className="flex items-center gap-2 cursor-pointer"
+ >
+ <Upload /> {translate("resources.contacts.import.button")}
+ </Button>
);
};
-
-const SAMPLE_URL = `data:text/csv;name=crm_contacts_sample.csv;charset=utf-8,${encodeURIComponent(
- sampleCsv.default,
-)}`;
-
-type ContactImportModalProps = {
- open: boolean;
- onClose(): void;
-};
-
-export function ContactImportDialog({
- open,
- onClose,
-}: ContactImportModalProps) {
- const translate = useTranslate();
- const refresh = useRefresh();
- const processBatch = useContactImport();
- const { importer, parseCsv, reset } = usePapaParse<ContactImportSchema>({
- batchSize: 10,
- processBatch,
- });
-
- const [file, setFile] = useState<File | null>(null);
-
- useEffect(() => {
- if (importer.state === "complete") {
- refresh();
- }
- }, [importer.state, refresh]);
-
- const handleFileChange = (file: File | null) => {
- setFile(file);
- };
-
- const startImport = () => {
- if (!file) return;
- parseCsv(file);
- };
-
- const handleClose = () => {
- reset();
- onClose();
- };
-
- const handleReset = (e: MouseEvent<HTMLButtonElement>) => {
- e.preventDefault();
- reset();
- };
-
- return (
- <Dialog open={open} onOpenChange={handleClose}>
- <DialogContent className="max-w-2xl">
- <Form className="flex flex-col gap-4">
- <DialogHeader>
- <DialogTitle>
- {translate("resources.contacts.import.title")}
- </DialogTitle>
- </DialogHeader>
-
- <div className="flex flex-col space-y-2">
- {importer.state === "running" && (
- <div className="flex flex-col gap-2">
- <Alert>
- <AlertDescription className="flex flex-row gap-4">
- <Loader2 className="h-5 w-5 animate-spin" />
- {translate("resources.contacts.import.running")}
- </AlertDescription>
- </Alert>
-
- <div className="text-sm">
- {translate("resources.contacts.import.progress", {
- importCount: importer.importCount,
- rowCount: importer.rowCount,
- errorCount: importer.errorCount,
- })}
- {importer.remainingTime !== null && (
- <>
- {" "}
- {translate(
- "resources.contacts.import.remaining_time",
- )}{" "}
- <strong>
- {millisecondsToTime(importer.remainingTime)}
- </strong>
- .{" "}
- <button
- onClick={handleReset}
- className="text-red-600 underline hover:text-red-800"
- >
- {translate("resources.contacts.import.stop")}
- </button>
- </>
- )}
- </div>
- </div>
- )}
-
- {importer.state === "error" && (
- <Alert variant="destructive">
- <AlertDescription>
- {translate("resources.contacts.import.error")}
- </AlertDescription>
- </Alert>
- )}
-
- {importer.state === "complete" && (
- <Alert>
- <AlertDescription>
- {translate("resources.contacts.import.complete", {
- importCount: importer.importCount,
- errorCount: importer.errorCount,
- })}
- </AlertDescription>
- </Alert>
- )}
-
- {importer.state === "idle" && (
- <>
- <Alert>
- <AlertDescription className="flex flex-col gap-4">
- {translate("resources.contacts.import.sample_hint")}
- <Button asChild variant="outline" size="sm">
- <Link
- to={SAMPLE_URL}
- download={"crm_contacts_sample.csv"}
- >
- {translate("resources.contacts.import.sample_download")}
- </Link>
- </Button>{" "}
- </AlertDescription>
- </Alert>
-
- <FileInput
- source="csv"
- label="resources.contacts.import.csv_file"
- accept={{ "text/csv": [".csv"] }}
- onChange={handleFileChange}
- >
- <FileField source="src" title="title" target="_blank" />
- </FileInput>
- </>
- )}
- </div>
- </Form>
-
- <div className="flex justify-start pt-6">
- <FormToolbar>
- {importer.state === "idle" ? (
- <Button onClick={startImport} disabled={!file}>
- {translate("resources.contacts.import.button")}
- </Button>
- ) : (
- <Button
- variant="outline"
- onClick={handleClose}
- disabled={importer.state === "running"}
- >
- {translate("ra.action.close")}
- </Button>
- )}
- </FormToolbar>
- </div>
- </DialogContent>
- </Dialog>
- );
-}
-
-function millisecondsToTime(ms: number) {
- const seconds = Math.floor((ms / 1000) % 60);
- const minutes = Math.floor((ms / (60 * 1000)) % 60);
-
- return `${minutes}m ${seconds}s`;
-}
diff --git a/src/components/atomic-crm/contacts/ContactImportContext.tsx b/src/components/atomic-crm/contacts/ContactImportContext.tsx
new file mode 100644
index 00000000..ae0c916d
--- /dev/null
+++ b/src/components/atomic-crm/contacts/ContactImportContext.tsx
@@ -0,0 +1,26 @@
+import { createContext, useContext } from "react";
+
+import type { ImportState } from "../misc/usePapaParse";
+
+export type ContactImportContextValue = {
+ importer: ImportState;
+ isDialogOpen: boolean;
+ openDialog(): void;
+ closeDialog(): void;
+ startImport(file: File): void;
+ reset(): void;
+};
+
+export const ContactImportContext = createContext<
+ ContactImportContextValue | undefined
+>(undefined);
+
+export const useContactImportContext = () => {
+ const context = useContext(ContactImportContext);
+ if (!context) {
+ throw new Error(
+ "useContactImportContext must be used inside a <ContactImportProvider>",
+ );
+ }
+ return context;
+};
diff --git a/src/components/atomic-crm/contacts/ContactImportDialog.tsx b/src/components/atomic-crm/contacts/ContactImportDialog.tsx
new file mode 100644
index 00000000..8a1eb85f
--- /dev/null
+++ b/src/components/atomic-crm/contacts/ContactImportDialog.tsx
@@ -0,0 +1,179 @@
+import { useState } from "react";
+import type { MouseEvent } from "react";
+import { Loader2 } from "lucide-react";
+import { Form, useTranslate } from "ra-core";
+import { Link } from "react-router";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { FormToolbar } from "@/components/admin/simple-form";
+import { FileInput } from "@/components/admin/file-input";
+import { FileField } from "@/components/admin/file-field";
+
+import { useContactImportContext } from "./ContactImportContext";
+import * as sampleCsv from "./contacts_export.csv?raw";
+
+const SAMPLE_URL = `data:text/csv;name=crm_contacts_sample.csv;charset=utf-8,${encodeURIComponent(
+ sampleCsv.default,
+)}`;
+
+export function ContactImportDialog() {
+ const translate = useTranslate();
+ const { importer, isDialogOpen, closeDialog, startImport, reset } =
+ useContactImportContext();
+
+ const [file, setFile] = useState<File | null>(null);
+
+ const handleFileChange = (file: File | null) => {
+ setFile(file);
+ };
+
+ const handleStartImport = () => {
+ if (!file) return;
+ startImport(file);
+ };
+
+ const handleClose = () => {
+ setFile(null);
+ closeDialog();
+ };
+
+ const handleOpenChange = (open: boolean) => {
+ if (!open) handleClose();
+ };
+
+ const handleReset = (e: MouseEvent<HTMLButtonElement>) => {
+ e.preventDefault();
+ setFile(null);
+ reset();
+ };
+
+ return (
+ <Dialog open={isDialogOpen} onOpenChange={handleOpenChange}>
+ <DialogContent className="max-w-2xl">
+ <Form className="flex flex-col gap-4">
+ <DialogHeader>
+ <DialogTitle>
+ {translate("resources.contacts.import.title")}
+ </DialogTitle>
+ </DialogHeader>
+
+ <div className="flex flex-col space-y-2">
+ {importer.state === "running" && (
+ <div className="flex flex-col gap-2">
+ <Alert>
+ <AlertDescription className="flex flex-row gap-4">
+ <Loader2 className="h-5 w-5 animate-spin" />
+ {translate("resources.contacts.import.running")}
+ </AlertDescription>
+ </Alert>
+
+ <div className="text-sm">
+ {translate("resources.contacts.import.progress", {
+ importCount: importer.importCount,
+ rowCount: importer.rowCount,
+ errorCount: importer.errorCount,
+ })}
+ {importer.remainingTime !== null && (
+ <>
+ {" "}
+ {translate(
+ "resources.contacts.import.remaining_time",
+ )}{" "}
+ <strong>
+ {millisecondsToTime(importer.remainingTime)}
+ </strong>
+ .{" "}
+ <button
+ onClick={handleReset}
+ className="text-red-600 underline hover:text-red-800"
+ >
+ {translate("resources.contacts.import.stop")}
+ </button>
+ </>
+ )}
+ </div>
+
+ <p className="text-muted-foreground text-sm">
+ {translate("resources.contacts.import.background_hint")}
+ </p>
+ </div>
+ )}
+
+ {importer.state === "error" && (
+ <Alert variant="destructive">
+ <AlertDescription>
+ {translate("resources.contacts.import.error")}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {importer.state === "complete" && (
+ <Alert>
+ <AlertDescription>
+ {translate("resources.contacts.import.complete", {
+ importCount: importer.importCount,
+ errorCount: importer.errorCount,
+ })}
+ </AlertDescription>
+ </Alert>
+ )}
+
+ {importer.state === "idle" && (
+ <>
+ <Alert>
+ <AlertDescription className="flex flex-col gap-4">
+ {translate("resources.contacts.import.sample_hint")}
+ <Button asChild variant="outline" size="sm">
+ <Link
+ to={SAMPLE_URL}
+ download={"crm_contacts_sample.csv"}
+ >
+ {translate("resources.contacts.import.sample_download")}
+ </Link>
+ </Button>{" "}
+ </AlertDescription>
+ </Alert>
+
+ <FileInput
+ source="csv"
+ label="resources.contacts.import.csv_file"
+ accept={{ "text/csv": [".csv"] }}
+ onChange={handleFileChange}
+ >
+ <FileField source="src" title="title" target="_blank" />
+ </FileInput>
+ </>
+ )}
+ </div>
+ </Form>
+
+ <div className="flex justify-start pt-6">
+ <FormToolbar>
+ {importer.state === "idle" ? (
+ <Button onClick={handleStartImport} disabled={!file}>
+ {translate("resources.contacts.import.button")}
+ </Button>
+ ) : (
+ <Button variant="outline" onClick={handleClose}>
+ {translate("ra.action.close")}
+ </Button>
+ )}
+ </FormToolbar>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
+
+function millisecondsToTime(ms: number) {
+ const seconds = Math.floor((ms / 1000) % 60);
+ const minutes = Math.floor((ms / (60 * 1000)) % 60);
+
+ return `${minutes}m ${seconds}s`;
+}
diff --git a/src/components/atomic-crm/contacts/ContactImportProgressToast.tsx b/src/components/atomic-crm/contacts/ContactImportProgressToast.tsx
new file mode 100644
index 00000000..aa7bebef
--- /dev/null
+++ b/src/components/atomic-crm/contacts/ContactImportProgressToast.tsx
@@ -0,0 +1,57 @@
+import { useEffect } from "react";
+import { useTranslate } from "ra-core";
+import { toast } from "sonner";
+
+import { Progress } from "@/components/ui/progress";
+import { useContactImportContext } from "./ContactImportContext";
+
+const TOAST_ID = "contact-import-progress";
+
+export const ContactImportProgressToast = () => {
+ const translate = useTranslate();
+ const { importer, isDialogOpen } = useContactImportContext();
+
+ const isRunning =
+ importer.state === "parsing" || importer.state === "running";
+ const rowCount = importer.state === "running" ? importer.rowCount : 0;
+ const importCount = importer.state === "running" ? importer.importCount : 0;
+ const errorCount = importer.state === "running" ? importer.errorCount : 0;
+
+ useEffect(() => {
+ if (!isRunning || isDialogOpen) {
+ toast.dismiss(TOAST_ID);
+ return;
+ }
+
+ toast.custom(
+ () => (
+ <div className="bg-popover text-popover-foreground flex w-full flex-col gap-2 rounded-md border p-4 shadow-lg">
+ <p className="text-sm font-medium">
+ {translate("resources.contacts.import.in_progress")}
+ </p>
+ <Progress
+ value={rowCount ? (importCount / rowCount) * 100 : 0}
+ aria-label={translate("resources.contacts.import.in_progress")}
+ />
+ <p className="text-muted-foreground text-xs">
+ {translate("resources.contacts.import.progress", {
+ importCount,
+ rowCount,
+ errorCount,
+ })}
+ </p>
+ </div>
+ ),
+ { id: TOAST_ID, duration: Infinity, position: "bottom-right" },
+ );
+ }, [isRunning, isDialogOpen, importCount, rowCount, errorCount, translate]);
+
+ useEffect(
+ () => () => {
+ toast.dismiss(TOAST_ID);
+ },
+ [],
+ );
+
+ return null;
+};
diff --git a/src/components/atomic-crm/contacts/ContactImportProvider.tsx b/src/components/atomic-crm/contacts/ContactImportProvider.tsx
new file mode 100644
index 00000000..d08849a9
--- /dev/null
+++ b/src/components/atomic-crm/contacts/ContactImportProvider.tsx
@@ -0,0 +1,85 @@
+import { useCallback, useEffect, useMemo, useState } from "react";
+import type { ReactNode } from "react";
+import { useNotify, useRefresh } from "ra-core";
+
+import { usePapaParse } from "../misc/usePapaParse";
+import { ContactImportContext } from "./ContactImportContext";
+import { ContactImportDialog } from "./ContactImportDialog";
+import { ContactImportProgressToast } from "./ContactImportProgressToast";
+import type { ContactImportSchema } from "./useContactImport";
+import { useContactImport } from "./useContactImport";
+
+export const ContactImportProvider = ({
+ children,
+}: {
+ children: ReactNode;
+}) => {
+ const notify = useNotify();
+ const refresh = useRefresh();
+ const processBatch = useContactImport();
+ const { importer, parseCsv, reset } = usePapaParse<ContactImportSchema>({
+ batchSize: 10,
+ processBatch,
+ });
+ const [isDialogOpen, setIsDialogOpen] = useState(false);
+
+ useEffect(() => {
+ if (importer.state === "complete") {
+ refresh();
+ notify("resources.contacts.import.complete", {
+ type: "success",
+ messageArgs: {
+ importCount: importer.importCount,
+ errorCount: importer.errorCount,
+ },
+ });
+ }
+ if (importer.state === "error") {
+ notify("resources.contacts.import.error", { type: "error" });
+ }
+ }, [importer, notify, refresh]);
+
+ const isRunning =
+ importer.state === "parsing" || importer.state === "running";
+
+ useEffect(() => {
+ if (!isRunning) return;
+
+ const confirmLeave = (event: BeforeUnloadEvent) => {
+ event.preventDefault();
+ event.returnValue = "";
+ };
+
+ window.addEventListener("beforeunload", confirmLeave);
+ return () => window.removeEventListener("beforeunload", confirmLeave);
+ }, [isRunning]);
+
+ const openDialog = useCallback(() => {
+ if (importer.state === "complete" || importer.state === "error") {
+ reset();
+ }
+ setIsDialogOpen(true);
+ }, [importer.state, reset]);
+
+ const closeDialog = useCallback(() => setIsDialogOpen(false), []);
+
+ const value = useMemo(
+ () => ({
+ importer,
+ isDialogOpen,
+ openDialog,
+ closeDialog,
+ startImport: parseCsv,
+ reset,
+ }),
+ [importer, isDialogOpen, openDialog, closeDialog, parseCsv, reset],
+ );
+
+ return (
+ <ContactImportContext.Provider value={value}>
+ {children}
+ <ContactImportDialog />
+ <ContactImportProgressToast />
+ </ContactImportContext.Provider>
+ );
+};
diff --git a/src/components/atomic-crm/layout/Layout.tsx b/src/components/atomic-crm/layout/Layout.tsx
index 41981658..d98e8664 100644
--- a/src/components/atomic-crm/layout/Layout.tsx
+++ b/src/components/atomic-crm/layout/Layout.tsx
@@ -4,13 +4,14 @@ import { Notification } from "@/components/admin/notification";
import { Error } from "@/components/admin/error";
import { Skeleton } from "@/components/ui/skeleton";
+import { ContactImportProvider } from "../contacts/ContactImportProvider";
import { useConfigurationLoader } from "../root/useConfigurationLoader";
import Header from "./Header";
export const Layout = ({ children }: { children: ReactNode }) => {
useConfigurationLoader();
return (
- <>
+ <ContactImportProvider>
<Header />
<main className="max-w-screen-xl mx-auto pt-4 px-4" id="main-content">
<ErrorBoundary FallbackComponent={Error}>
@@ -20,6 +21,6 @@ export const Layout = ({ children }: { children: ReactNode }) => {
</ErrorBoundary>
</main>
<Notification />
- </>
+ </ContactImportProvider>
);
};
diff --git a/src/components/atomic-crm/layout/MobileLayout.tsx b/src/components/atomic-crm/layout/MobileLayout.tsx
index 334ae0e8..ddb8bf00 100644
--- a/src/components/atomic-crm/layout/MobileLayout.tsx
+++ b/src/components/atomic-crm/layout/MobileLayout.tsx
@@ -4,13 +4,14 @@ import { Skeleton } from "@/components/ui/skeleton";
import { Suspense, type ReactNode } from "react";
import { ErrorBoundary } from "react-error-boundary";
+import { ContactImportProvider } from "../contacts/ContactImportProvider";
import { useConfigurationLoader } from "../root/useConfigurationLoader";
import { MobileNavigation } from "./MobileNavigation";
export const MobileLayout = ({ children }: { children: ReactNode }) => {
useConfigurationLoader();
return (
- <>
+ <ContactImportProvider>
<ErrorBoundary FallbackComponent={Error}>
<Suspense fallback={<Skeleton className="h-12 w-12 rounded-full" />}>
{children}
@@ -18,6 +19,6 @@ export const MobileLayout = ({ children }: { children: ReactNode }) => {
</ErrorBoundary>
<MobileNavigation />
<Notification mobileOffset={{ bottom: "72px" }} />
- </>
+ </ContactImportProvider>
);
};
diff --git a/src/components/atomic-crm/misc/usePapaParse.tsx b/src/components/atomic-crm/misc/usePapaParse.tsx
index c8bc8c26..02c01fad 100644
--- a/src/components/atomic-crm/misc/usePapaParse.tsx
+++ b/src/components/atomic-crm/misc/usePapaParse.tsx
@@ -1,7 +1,7 @@
import * as Papa from "papaparse";
import { useCallback, useMemo, useRef, useState } from "react";
-type Import =
+export type ImportState =
| {
state: "idle";
}
@@ -38,7 +38,7 @@ export function usePapaParse<T>({
}: usePapaParseProps<T>) {
const importIdRef = useRef<number>(0);
- const [importer, setImporter] = useState<Import>({
+ const [importer, setImporter] = useState<ImportState>({
state: "idle",
});
diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
index de9e8443..11562d86 100644
--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
@@ -118,6 +118,9 @@ export const englishCrmMessages = {
error:
"Failed to import this file, please make sure your provided a valid CSV file.",
imported: "Imported",
+ in_progress: "Importing contacts…",
+ background_hint:
+ "You can close this dialog: the import keeps running and you will be notified when it ends.",
remaining_time: "Estimated remaining time:",
running: "The import is running, please do not close this tab.",
sample_download: "Download CSV sample",
diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
index 5d30e91f..e37d47cd 100644
--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
@@ -121,6 +121,9 @@ export const frenchCrmMessages = {
error:
"Échec de l'importation de ce fichier. Veuillez vous assurer que vous avez fourni un fichier CSV valide.",
imported: "Importé",
+ in_progress: "Import des contacts en cours…",
+ background_hint:
+ "Vous pouvez fermer cette fenêtre : l'import continue et vous serez notifié à la fin.",
remaining_time: "Temps restant estimé :",
running: "L'import est en cours, merci de ne pas fermer cet onglet.",
sample_download: "Télécharger un exemple CSV",
diff --git a/src/test/StoryWrapper.tsx b/src/test/StoryWrapper.tsx
index f9f1a16f..ef64b597 100644
--- a/src/test/StoryWrapper.tsx
+++ b/src/test/StoryWrapper.tsx
@@ -4,6 +4,7 @@ import { useEffect, useMemo, type ReactNode } from "react";
import { MemoryRouter } from "react-router";
import cloneDeep from "lodash/cloneDeep";
import { Notification } from "@/components/admin/notification";
+import { ContactImportProvider } from "@/components/atomic-crm/contacts/ContactImportProvider";
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";
@@ -114,10 +115,10 @@ export const StoryWrapper = ({
store={store}
disableTelemetry
layout={({ children }) => (
- <>
+ <ContactImportProvider>
{children}
<Notification />
- </>
+ </ContactImportProvider>
)}
/>
</MemoryRouter>