Skip to content

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

fix(contacts): mount the import provider from CRM, not from the layouts

Jerome30891678ce07
diff --git a/registry.json b/registry.json
index 92675009..7ed47743 100644
--- a/registry.json
+++ b/registry.json
@@ -641,6 +641,10 @@
"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"
diff --git a/src/components/atomic-crm/contacts/ContactImport.test.tsx b/src/components/atomic-crm/contacts/ContactImport.test.tsx
index bd83be4d..c59ccadd 100644
--- a/src/components/atomic-crm/contacts/ContactImport.test.tsx
+++ b/src/components/atomic-crm/contacts/ContactImport.test.tsx
@@ -1,5 +1,11 @@
+import { useState, type ReactNode } from "react";
import { render } from "vitest-browser-react";
-import { useNotify } from "ra-core";
+import {
+ useNotify,
+ type CreateParams,
+ type CreateResult,
+ type DataProvider,
+} from "ra-core";
import { toast } from "sonner";
import { StoryWrapper } from "@/test/StoryWrapper";
@@ -38,22 +44,50 @@ const NotifyTrigger = () => {
);
};
-const ImportHarness = () => (
+const UnmountableImportControls = () => {
+ const [isMounted, setIsMounted] = useState(true);
+ return (
+ <>
+ <button onClick={() => setIsMounted(false)}>unmount contact list</button>
+ {isMounted ? (
+ <>
+ <ContactImportButton />
+ <StartImportTrigger />
+ </>
+ ) : (
+ <p>contact list unmounted</p>
+ )}
+ </>
+ );
+};
+
+const createContact = async (
+ _resource: string,
+ params: CreateParams,
+): Promise<CreateResult> => {
+ await new Promise((resolve) => setTimeout(resolve, createDelay));
+ createdCount += 1;
+ return { data: { ...params.data, id: createdCount } };
+};
+
+const ImportHarness = ({ children }: { children?: ReactNode }) => (
<StoryWrapper
- dataProvider={{
- create: async (_resource, params) => {
- await new Promise((resolve) => setTimeout(resolve, createDelay));
- createdCount += 1;
- return { data: { ...params.data, id: createdCount } } as any;
- },
- }}
+ dataProvider={{ create: createContact as DataProvider["create"] }}
>
- <ContactImportButton />
- <StartImportTrigger />
- <NotifyTrigger />
+ {children ?? (
+ <>
+ <ContactImportButton />
+ <StartImportTrigger />
+ <NotifyTrigger />
+ </>
+ )}
</StoryWrapper>
);
+const finishRemainingBatchesFast = () => {
+ createDelay = 0;
+};
+
const getToasterPositions = () =>
Array.from(document.querySelectorAll("[data-sonner-toaster]")).map(
(toaster) => ({
@@ -90,7 +124,7 @@ describe("contact import", () => {
.element(screen.getByText(new RegExp(`/ ${ROW_COUNT} contacts`)))
.toBeInTheDocument();
- createDelay = 0;
+ finishRemainingBatchesFast();
await expect
.element(
@@ -116,7 +150,7 @@ describe("contact import", () => {
expect(dispatchBeforeUnload().defaultPrevented).toBe(true);
- createDelay = 0;
+ finishRemainingBatchesFast();
await expect
.element(screen.getByText(/Contacts import complete/))
@@ -148,7 +182,7 @@ describe("contact import", () => {
expect(notificationStack?.position).toBe("bottom-center");
expect(progressStack).not.toBe(notificationStack);
- createDelay = 0;
+ finishRemainingBatchesFast();
await expect
.element(screen.getByText(/Contacts import complete/))
.toBeInTheDocument();
@@ -179,7 +213,7 @@ describe("contact import", () => {
.element(screen.getByText(/Importing contacts/))
.toBeInTheDocument();
- createDelay = 0;
+ finishRemainingBatchesFast();
await expect
.element(
@@ -190,4 +224,76 @@ describe("contact import", () => {
.toBeInTheDocument();
expect(createdCount).toBe(ROW_COUNT);
});
+
+ it("keeps importing after the subtree holding the import button unmounts", async () => {
+ const screen = await render(
+ <ImportHarness>
+ <UnmountableImportControls />
+ </ImportHarness>,
+ );
+
+ await screen.getByRole("button", { name: "start import" }).click();
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .toBeInTheDocument();
+
+ await screen.getByRole("button", { name: "unmount contact list" }).click();
+ await expect
+ .element(screen.getByText("contact list unmounted"))
+ .toBeVisible();
+ await expect
+ .element(screen.getByRole("button", { name: /import csv/i }))
+ .not.toBeInTheDocument();
+
+ 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("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 expect.element(screen.getByText(/Download CSV sample/)).toBeVisible();
+ await expect
+ .element(
+ screen
+ .getByRole("toolbar")
+ .getByRole("button", { name: /import csv/i }),
+ )
+ .toBeDisabled();
+ });
+
+ 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 screen.getByRole("button", { name: /stop import/i }).click();
+
+ await expect
+ .element(screen.getByText(/Importing contacts/))
+ .not.toBeInTheDocument();
+
+ const createdWhenStopped = createdCount;
+ await expect
+ .element(screen.getByText(/Contacts import complete/))
+ .not.toBeInTheDocument();
+ expect(createdWhenStopped).toBeLessThan(ROW_COUNT);
+ });
});
diff --git a/src/components/atomic-crm/contacts/ContactImportProgressToast.tsx b/src/components/atomic-crm/contacts/ContactImportProgressToast.tsx
index aa7bebef..b2ba2c83 100644
--- a/src/components/atomic-crm/contacts/ContactImportProgressToast.tsx
+++ b/src/components/atomic-crm/contacts/ContactImportProgressToast.tsx
@@ -2,6 +2,7 @@ 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";
@@ -9,10 +10,11 @@ const TOAST_ID = "contact-import-progress";
export const ContactImportProgressToast = () => {
const translate = useTranslate();
- const { importer, isDialogOpen } = useContactImportContext();
+ 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;
@@ -26,25 +28,48 @@ export const ContactImportProgressToast = () => {
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 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, isDialogOpen, importCount, rowCount, errorCount, translate]);
+ }, [
+ isRunning,
+ hasProgress,
+ isDialogOpen,
+ importCount,
+ rowCount,
+ errorCount,
+ translate,
+ reset,
+ ]);
useEffect(
() => () => {
diff --git a/src/components/atomic-crm/contacts/ContactImportProvider.tsx b/src/components/atomic-crm/contacts/ContactImportProvider.tsx
index d08849a9..c614aba7 100644
--- a/src/components/atomic-crm/contacts/ContactImportProvider.tsx
+++ b/src/components/atomic-crm/contacts/ContactImportProvider.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
import { useNotify, useRefresh } from "ra-core";
@@ -23,21 +23,26 @@ export const ContactImportProvider = ({
});
const [isDialogOpen, setIsDialogOpen] = useState(false);
+ const importerRef = useRef(importer);
+ importerRef.current = importer;
+
useEffect(() => {
if (importer.state === "complete") {
+ const finished = importerRef.current;
+ if (finished.state !== "complete") return;
refresh();
notify("resources.contacts.import.complete", {
type: "success",
messageArgs: {
- importCount: importer.importCount,
- errorCount: importer.errorCount,
+ importCount: finished.importCount,
+ errorCount: finished.errorCount,
},
});
}
if (importer.state === "error") {
notify("resources.contacts.import.error", { type: "error" });
}
- }, [importer, notify, refresh]);
+ }, [importer.state, notify, refresh]);
const isRunning =
importer.state === "parsing" || importer.state === "running";
diff --git a/src/components/atomic-crm/contacts/withContactImport.tsx b/src/components/atomic-crm/contacts/withContactImport.tsx
new file mode 100644
index 00000000..df1b6e5a
--- /dev/null
+++ b/src/components/atomic-crm/contacts/withContactImport.tsx
@@ -0,0 +1,11 @@
+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 d98e8664..41981658 100644
--- a/src/components/atomic-crm/layout/Layout.tsx
+++ b/src/components/atomic-crm/layout/Layout.tsx
@@ -4,14 +4,13 @@ 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}>
@@ -21,6 +20,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 ddb8bf00..334ae0e8 100644
--- a/src/components/atomic-crm/layout/MobileLayout.tsx
+++ b/src/components/atomic-crm/layout/MobileLayout.tsx
@@ -4,14 +4,13 @@ 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}
@@ -19,6 +18,6 @@ export const MobileLayout = ({ children }: { children: ReactNode }) => {
</ErrorBoundary>
<MobileNavigation />
<Notification mobileOffset={{ bottom: "72px" }} />
- </ContactImportProvider>
+ </>
);
};
diff --git a/src/components/atomic-crm/root/CRM.tsx b/src/components/atomic-crm/root/CRM.tsx
index 9dcf0f9f..deffc457 100644
--- a/src/components/atomic-crm/root/CRM.tsx
+++ b/src/components/atomic-crm/root/CRM.tsx
@@ -17,6 +17,7 @@ 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";
@@ -236,12 +237,13 @@ const DesktopAdmin = (
layout?: LayoutComponent;
},
) => {
+ const layout = useMemo(
+ () => withContactImport(props.layout ?? Layout),
+ [props.layout],
+ );
+
return (
- <Admin
- layout={props.layout ?? Layout}
- dashboard={props.dashboard ?? Dashboard}
- {...props}
- >
+ <Admin dashboard={props.dashboard ?? Dashboard} {...props} layout={layout}>
<CustomRoutes noLayout>
<Route path={SignupPage.path} element={<SignupPage />} />
<Route
@@ -294,6 +296,10 @@ const MobileAdmin = (
const asyncStoragePersister = createAsyncStoragePersister({
storage: localStorage,
});
+ const layout = useMemo(
+ () => withContactImport(props.layout ?? MobileLayout),
+ [props.layout],
+ );
return (
<PersistQueryClientProvider
@@ -302,9 +308,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 ef64b597..f9f1a16f 100644
--- a/src/test/StoryWrapper.tsx
+++ b/src/test/StoryWrapper.tsx
@@ -4,7 +4,6 @@ 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";
@@ -115,10 +114,10 @@ export const StoryWrapper = ({
store={store}
disableTelemetry
layout={({ children }) => (
- <ContactImportProvider>
+ <>
{children}
<Notification />
- </ContactImportProvider>
+ </>
)}
/>
</MemoryRouter>