Skip to content

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

fix(contacts): fold the import into one file and one mount point

Jerome4df286c670e0
diff --git a/registry.json b/registry.json
index 7ed47743..d1b74058 100644
--- a/registry.json
+++ b/registry.json
@@ -641,10 +641,6 @@
"path": "src/components/atomic-crm/dashboard/Dashboard.tsx",
"type": "registry:component"
},
- {
- "path": "src/components/atomic-crm/contacts/withContactImport.tsx",
- "type": "registry:component"
- },
{
"path": "src/components/atomic-crm/contacts/useContactImport.tsx",
"type": "registry:component"
@@ -705,18 +701,6 @@
"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
index c59ccadd..daeb2068 100644
--- a/src/components/atomic-crm/contacts/ContactImport.test.tsx
+++ b/src/components/atomic-crm/contacts/ContactImport.test.tsx
@@ -1,5 +1,6 @@
import { useState, type ReactNode } from "react";
import { render } from "vitest-browser-react";
+import { page } from "vitest/browser";
import {
useNotify,
type CreateParams,
@@ -10,7 +11,6 @@ import { toast } from "sonner";
import { StoryWrapper } from "@/test/StoryWrapper";
import { ContactImportButton } from "./ContactImportButton";
-import { useContactImportContext } from "./ContactImportContext";
const ROW_COUNT = 80;
@@ -22,19 +22,6 @@ const csv = [
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 (
@@ -49,14 +36,7 @@ const UnmountableImportControls = () => {
return (
<>
<button onClick={() => setIsMounted(false)}>unmount contact list</button>
- {isMounted ? (
- <>
- <ContactImportButton />
- <StartImportTrigger />
- </>
- ) : (
- <p>contact list unmounted</p>
- )}
+ {isMounted ? <ContactImportButton /> : <p>contact list unmounted</p>}
</>
);
};
@@ -77,13 +57,40 @@ const ImportHarness = ({ children }: { children?: ReactNode }) => (
{children ?? (
<>
<ContactImportButton />
- <StartImportTrigger />
<NotifyTrigger />
</>
)}
</StoryWrapper>
);
+type Screen = Awaited<ReturnType<typeof render>>;
+
+const openImportDialog = (screen: Screen) =>
+ screen.getByRole("button", { name: /import csv/i }).click();
+
+const selectCsvFile = () => {
+ const input = document.querySelector<HTMLInputElement>('input[type="file"]');
+ if (!input) throw new Error("The import dialog has no file input");
+ return page
+ .elementLocator(input)
+ .upload(new File([csv], "contacts.csv", { type: "text/csv" }));
+};
+
+const submitImportDialog = (screen: Screen) =>
+ screen
+ .getByRole("toolbar")
+ .getByRole("button", { name: /import csv/i })
+ .click();
+
+const startImport = async (screen: Screen) => {
+ await openImportDialog(screen);
+ await selectCsvFile();
+ await submitImportDialog(screen);
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .toBeInTheDocument();
+};
+
const finishRemainingBatchesFast = () => {
createDelay = 0;
};
@@ -115,11 +122,8 @@ 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 startImport(screen);
- await expect
- .element(screen.getByText(/Importing contacts/))
- .toBeInTheDocument();
await expect
.element(screen.getByText(new RegExp(`/ ${ROW_COUNT} contacts`)))
.toBeInTheDocument();
@@ -138,15 +142,50 @@ describe("contact import", () => {
.not.toBeInTheDocument();
});
- it("asks the browser to confirm leaving the page only while the import runs", async () => {
+ it("closes the dialog when the import starts", async () => {
const screen = await render(<ImportHarness />);
- expect(dispatchBeforeUnload().defaultPrevented).toBe(false);
+ await startImport(screen);
+
+ await expect.element(screen.getByRole("dialog")).not.toBeInTheDocument();
+
+ finishRemainingBatchesFast();
- await screen.getByRole("button", { name: "start import" }).click();
await expect
- .element(screen.getByText(/Importing contacts/))
+ .element(
+ screen.getByText(
+ `Contacts import complete. Imported ${ROW_COUNT} contacts, with 0 errors`,
+ ),
+ )
.toBeInTheDocument();
+ expect(createdCount).toBe(ROW_COUNT);
+ });
+
+ it("prevents starting a second import while one is running", async () => {
+ const screen = await render(<ImportHarness />);
+
+ await startImport(screen);
+
+ await expect
+ .element(screen.getByRole("button", { name: /import csv/i }))
+ .toBeDisabled();
+
+ finishRemainingBatchesFast();
+
+ await expect
+ .element(screen.getByText(/Contacts import complete/))
+ .toBeInTheDocument();
+ await expect
+ .element(screen.getByRole("button", { name: /import csv/i }))
+ .toBeEnabled();
+ });
+
+ 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 startImport(screen);
expect(dispatchBeforeUnload().defaultPrevented).toBe(true);
@@ -162,10 +201,7 @@ describe("contact import", () => {
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 startImport(screen);
await screen.getByRole("button", { name: "notify" }).click();
await expect.element(screen.getByText("Contact updated")).toBeVisible();
@@ -188,43 +224,6 @@ describe("contact import", () => {
.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();
-
- finishRemainingBatchesFast();
-
- await expect
- .element(
- screen.getByText(
- `Contacts import complete. Imported ${ROW_COUNT} contacts, with 0 errors`,
- ),
- )
- .toBeInTheDocument();
- expect(createdCount).toBe(ROW_COUNT);
- });
-
it("keeps importing after the subtree holding the import button unmounts", async () => {
const screen = await render(
<ImportHarness>
@@ -232,10 +231,7 @@ describe("contact import", () => {
</ImportHarness>,
);
- await screen.getByRole("button", { name: "start import" }).click();
- await expect
- .element(screen.getByText(/Importing contacts/))
- .toBeInTheDocument();
+ await startImport(screen);
await screen.getByRole("button", { name: "unmount contact list" }).click();
await expect
@@ -264,7 +260,7 @@ describe("contact import", () => {
it("disables the dialog submit button until a file is selected", async () => {
const screen = await render(<ImportHarness />);
- await screen.getByRole("button", { name: /import csv/i }).click();
+ await openImportDialog(screen);
await expect.element(screen.getByText(/Download CSV sample/)).toBeVisible();
await expect
@@ -279,10 +275,7 @@ describe("contact import", () => {
it("stops the import from the progress snackbar", async () => {
const screen = await render(<ImportHarness />);
- await screen.getByRole("button", { name: "start import" }).click();
- await expect
- .element(screen.getByText(/Importing contacts/))
- .toBeInTheDocument();
+ await startImport(screen);
await screen.getByRole("button", { name: /stop import/i }).click();
diff --git a/src/components/atomic-crm/contacts/ContactImportButton.tsx b/src/components/atomic-crm/contacts/ContactImportButton.tsx
index fd15121c..3cc822bf 100644
--- a/src/components/atomic-crm/contacts/ContactImportButton.tsx
+++ b/src/components/atomic-crm/contacts/ContactImportButton.tsx
@@ -2,16 +2,22 @@ import { Upload } from "lucide-react";
import { useTranslate } from "ra-core";
import { Button } from "@/components/ui/button";
-import { useContactImportContext } from "./ContactImportContext";
+import { useContactImportContext } from "./ContactImportProvider";
export const ContactImportButton = () => {
const translate = useTranslate();
- const { openDialog } = useContactImportContext();
+ const { isImporting, openDialog } = useContactImportContext();
return (
<Button
variant="outline"
onClick={openDialog}
+ disabled={isImporting}
+ title={
+ isImporting
+ ? translate("resources.contacts.import.in_progress")
+ : undefined
+ }
className="flex items-center gap-2 cursor-pointer"
>
<Upload /> {translate("resources.contacts.import.button")}
diff --git a/src/components/atomic-crm/contacts/ContactImportContext.tsx b/src/components/atomic-crm/contacts/ContactImportContext.tsx
deleted file mode 100644
index ae0c916d..00000000
--- a/src/components/atomic-crm/contacts/ContactImportContext.tsx
+++ /dev/null
@@ -1,26 +0,0 @@
-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
deleted file mode 100644
index 8a1eb85f..00000000
--- a/src/components/atomic-crm/contacts/ContactImportDialog.tsx
+++ /dev/null
@@ -1,179 +0,0 @@
-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
deleted file mode 100644
index b2ba2c83..00000000
--- a/src/components/atomic-crm/contacts/ContactImportProgressToast.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import { useEffect } from "react";
-import { useTranslate } from "ra-core";
-import { toast } from "sonner";
-
-import { Button } from "@/components/ui/button";
-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, reset } = useContactImportContext();
-
- const isRunning =
- importer.state === "parsing" || importer.state === "running";
- const hasProgress = 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">
- <div className="flex flex-row items-start justify-between gap-4">
- <p className="text-sm font-medium">
- {translate("resources.contacts.import.in_progress")}
- </p>
- <Button
- variant="link"
- size="sm"
- onClick={reset}
- className="text-destructive h-auto p-0 text-xs"
- >
- {translate("resources.contacts.import.stop")}
- </Button>
- </div>
- {hasProgress && (
- <>
- <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,
- hasProgress,
- isDialogOpen,
- importCount,
- rowCount,
- errorCount,
- translate,
- reset,
- ]);
-
- 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
index c614aba7..74b0a74d 100644
--- a/src/components/atomic-crm/contacts/ContactImportProvider.tsx
+++ b/src/components/atomic-crm/contacts/ContactImportProvider.tsx
@@ -1,13 +1,53 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
-import type { ReactNode } from "react";
-import { useNotify, useRefresh } from "ra-core";
+/* eslint-disable react-refresh/only-export-components */
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+ type ReactNode,
+} from "react";
+import { Form, useNotify, useRefresh, useTranslate } from "ra-core";
+import { Link } from "react-router";
+import { toast } from "sonner";
-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";
+import { FileField } from "@/components/admin/file-field";
+import { FileInput } from "@/components/admin/file-input";
+import { FormToolbar } from "@/components/admin/simple-form";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Progress } from "@/components/ui/progress";
+
+import { usePapaParse, type ImportState } from "../misc/usePapaParse";
+import * as sampleCsv from "./contacts_export.csv?raw";
+import { useContactImport, type ContactImportSchema } from "./useContactImport";
+
+type ContactImportContextValue = {
+ isImporting: boolean;
+ openDialog(): void;
+};
+
+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;
+};
export const ContactImportProvider = ({
children,
@@ -44,11 +84,11 @@ export const ContactImportProvider = ({
}
}, [importer.state, notify, refresh]);
- const isRunning =
+ const isImporting =
importer.state === "parsing" || importer.state === "running";
useEffect(() => {
- if (!isRunning) return;
+ if (!isImporting) return;
const confirmLeave = (event: BeforeUnloadEvent) => {
event.preventDefault();
@@ -57,7 +97,7 @@ export const ContactImportProvider = ({
window.addEventListener("beforeunload", confirmLeave);
return () => window.removeEventListener("beforeunload", confirmLeave);
- }, [isRunning]);
+ }, [isImporting]);
const openDialog = useCallback(() => {
if (importer.state === "complete" || importer.state === "error") {
@@ -66,25 +106,197 @@ export const ContactImportProvider = ({
setIsDialogOpen(true);
}, [importer.state, reset]);
- const closeDialog = useCallback(() => setIsDialogOpen(false), []);
+ const startImport = (file: File) => {
+ parseCsv(file);
+ setIsDialogOpen(false);
+ };
const value = useMemo(
- () => ({
- importer,
- isDialogOpen,
- openDialog,
- closeDialog,
- startImport: parseCsv,
- reset,
- }),
- [importer, isDialogOpen, openDialog, closeDialog, parseCsv, reset],
+ () => ({ isImporting, openDialog }),
+ [isImporting, openDialog],
);
return (
<ContactImportContext.Provider value={value}>
{children}
- <ContactImportDialog />
- <ContactImportProgressToast />
+ <ContactImportDialog
+ open={isDialogOpen}
+ onClose={() => setIsDialogOpen(false)}
+ onStart={startImport}
+ />
+ <ContactImportProgressToast importer={importer} onStop={reset} />
</ContactImportContext.Provider>
);
};
+
+const SAMPLE_URL = `data:text/csv;name=crm_contacts_sample.csv;charset=utf-8,${encodeURIComponent(
+ sampleCsv.default,
+)}`;
+
+const ContactImportDialog = ({
+ open,
+ onClose,
+ onStart,
+}: {
+ open: boolean;
+ onClose(): void;
+ onStart(file: File): void;
+}) => {
+ const translate = useTranslate();
+ const [file, setFile] = useState<File | null>(null);
+
+ const handleFileChange = (selected: File | null) => {
+ setFile(selected);
+ };
+
+ const handleClose = () => {
+ setFile(null);
+ onClose();
+ };
+
+ const handleStartImport = () => {
+ if (!file) return;
+ setFile(null);
+ onStart(file);
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={(isOpen) => !isOpen && 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">
+ <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>
+ <Button onClick={handleStartImport} disabled={!file}>
+ {translate("resources.contacts.import.button")}
+ </Button>
+ </FormToolbar>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+};
+
+const TOAST_ID = "contact-import-progress";
+
+const ContactImportProgressToast = ({
+ importer,
+ onStop,
+}: {
+ importer: ImportState;
+ onStop(): void;
+}) => {
+ const translate = useTranslate();
+
+ const isImporting =
+ importer.state === "parsing" || importer.state === "running";
+ const hasProgress = 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;
+ const remainingTime =
+ importer.state === "running" ? importer.remainingTime : null;
+
+ useEffect(() => {
+ if (!isImporting) {
+ 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">
+ <div className="flex flex-row items-start justify-between gap-4">
+ <p className="text-sm font-medium">
+ {translate("resources.contacts.import.in_progress")}
+ </p>
+ <Button
+ variant="link"
+ size="sm"
+ onClick={onStop}
+ className="text-destructive h-auto p-0 text-xs"
+ >
+ {translate("resources.contacts.import.stop")}
+ </Button>
+ </div>
+ {hasProgress && (
+ <>
+ <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,
+ })}
+ {remainingTime !== null && (
+ <>
+ {" "}
+ {translate("resources.contacts.import.remaining_time")}{" "}
+ <strong>{millisecondsToTime(remainingTime)}</strong>.
+ </>
+ )}
+ </p>
+ </>
+ )}
+ </div>
+ ),
+ { id: TOAST_ID, duration: Infinity, position: "bottom-right" },
+ );
+ }, [
+ isImporting,
+ hasProgress,
+ importCount,
+ rowCount,
+ errorCount,
+ remainingTime,
+ translate,
+ onStop,
+ ]);
+
+ useEffect(
+ () => () => {
+ toast.dismiss(TOAST_ID);
+ },
+ [],
+ );
+
+ return null;
+};
+
+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/withContactImport.tsx b/src/components/atomic-crm/contacts/withContactImport.tsx
deleted file mode 100644
index df1b6e5a..00000000
--- a/src/components/atomic-crm/contacts/withContactImport.tsx
+++ /dev/null
@@ -1,11 +0,0 @@
-import type { LayoutComponent } from "ra-core";
-
-import { ContactImportProvider } from "./ContactImportProvider";
-
-export const withContactImport =
- (AppLayout: LayoutComponent): LayoutComponent =>
- ({ children }) => (
- <AppLayout>
- <ContactImportProvider>{children}</ContactImportProvider>
- </AppLayout>
- );
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/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
index 11562d86..8e01ff17 100644
--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
@@ -119,10 +119,7 @@ export const englishCrmMessages = {
"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",
sample_hint: "Here is a sample CSV file you can use as a template",
stop: "Stop import",
diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
index e37d47cd..c4dab51a 100644
--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
@@ -122,10 +122,7 @@ export const frenchCrmMessages = {
"É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",
sample_hint:
"Voici un exemple de fichier CSV que vous pouvez utiliser comme modèle",
diff --git a/src/components/atomic-crm/root/CRM.tsx b/src/components/atomic-crm/root/CRM.tsx
index deffc457..9dcf0f9f 100644
--- a/src/components/atomic-crm/root/CRM.tsx
+++ b/src/components/atomic-crm/root/CRM.tsx
@@ -17,7 +17,6 @@ import { OAuthConsentPage } from "@/components/supabase/oauth-consent-page";
import companies from "../companies";
import contacts from "../contacts";
-import { withContactImport } from "../contacts/withContactImport";
import { Dashboard } from "../dashboard/Dashboard";
import { MobileDashboard } from "../dashboard/MobileDashboard";
import deals from "../deals";
@@ -237,13 +236,12 @@ const DesktopAdmin = (
layout?: LayoutComponent;
},
) => {
- const layout = useMemo(
- () => withContactImport(props.layout ?? Layout),
- [props.layout],
- );
-
return (
- <Admin dashboard={props.dashboard ?? Dashboard} {...props} layout={layout}>
+ <Admin
+ layout={props.layout ?? Layout}
+ dashboard={props.dashboard ?? Dashboard}
+ {...props}
+ >
<CustomRoutes noLayout>
<Route path={SignupPage.path} element={<SignupPage />} />
<Route
@@ -296,10 +294,6 @@ const MobileAdmin = (
const asyncStoragePersister = createAsyncStoragePersister({
storage: localStorage,
});
- const layout = useMemo(
- () => withContactImport(props.layout ?? MobileLayout),
- [props.layout],
- );
return (
<PersistQueryClientProvider
@@ -308,9 +302,9 @@ const MobileAdmin = (
>
<Admin
queryClient={queryClient}
+ layout={props.layout ?? MobileLayout}
dashboard={props.dashboard ?? MobileDashboard}
{...props}
- layout={layout}
>
<CustomRoutes noLayout>
<Route path={SignupPage.path} element={<SignupPage />} />
diff --git a/src/test/StoryWrapper.tsx b/src/test/StoryWrapper.tsx
index f9f1a16f..c694b8e5 100644
--- a/src/test/StoryWrapper.tsx
+++ b/src/test/StoryWrapper.tsx
@@ -8,6 +8,7 @@ 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 { Contact, Sale } from "@/components/atomic-crm/types";
+import { ContactImportProvider } from "@/components/atomic-crm/contacts/ContactImportProvider";
import { CRM } from "@/components/atomic-crm/root/CRM";
import { testI18nProvider } from "@/components/atomic-crm/providers/commons/i18nProvider";
@@ -114,10 +115,10 @@ export const StoryWrapper = ({
store={store}
disableTelemetry
layout={({ children }) => (
- <>
+ <ContactImportProvider>
{children}
<Notification />
- </>
+ </ContactImportProvider>
)}
/>
</MemoryRouter>