Skip to content

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

Add reusable fake CRM UI harness

Anibal Svarcas2cc4315a3642
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
index 0f85b48e..ade484a1 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
@@ -25,16 +25,17 @@ import { getCompanyAvatar } from "../commons/getCompanyAvatar";
import { getContactAvatar } from "../commons/getContactAvatar";
import { mergeContacts } from "../commons/mergeContacts";
import type { CrmDataProvider } from "../types";
-import { authProvider, USER_STORAGE_KEY } from "./authProvider";
+import {
+ authProvider as defaultAuthProvider,
+ USER_STORAGE_KEY,
+} from "./authProvider";
import generateData from "./dataGenerator";
+import type { Db } from "./dataGenerator/types";
import { withSupabaseFilterAdapter } from "./internal/supabaseAdapter";
-const baseDataProvider = fakeRestDataProvider(generateData(), true, 300);
-
const TASK_MARKED_AS_DONE = "TASK_MARKED_AS_DONE";
const TASK_MARKED_AS_UNDONE = "TASK_MARKED_AS_UNDONE";
const TASK_DONE_NOT_CHANGED = "TASK_DONE_NOT_CHANGED";
-let taskUpdateType = TASK_DONE_NOT_CHANGED;
const processCompanyLogo = async (params: any) => {
let logo = params.data.logo;
@@ -111,156 +112,10 @@ async function fetchAndUpdateCompanyData(
return { ...params, data: newData };
}
-const dataProviderWithCustomMethod: CrmDataProvider = {
- ...baseDataProvider,
- unarchiveDeal: async (deal: Deal) => {
- // get all deals where stage is the same as the deal to unarchive
- const { data: deals } = await baseDataProvider.getList<Deal>("deals", {
- filter: { stage: deal.stage },
- pagination: { page: 1, perPage: 1000 },
- sort: { field: "index", order: "ASC" },
- });
-
- // set index for each deal starting from 1, if the deal to unarchive is found, set its index to the last one
- const updatedDeals = deals.map((d, index) => ({
- ...d,
- index: d.id === deal.id ? 0 : index + 1,
- archived_at: d.id === deal.id ? null : d.archived_at,
- }));
-
- return await Promise.all(
- updatedDeals.map((updatedDeal) =>
- dataProvider.update("deals", {
- id: updatedDeal.id,
- data: updatedDeal,
- previousData: deals.find((d) => d.id === updatedDeal.id),
- }),
- ),
- );
- },
- // We simulate a remote endpoint that is in charge of returning activity log
- getActivityLog: async (companyId?: Identifier) => {
- return getActivityLog(dataProvider, companyId);
- },
- signUp: async ({
- email,
- password,
- first_name,
- last_name,
- }: SignUpData): Promise<{ id: string; email: string; password: string }> => {
- const user = await baseDataProvider.create("sales", {
- data: {
- email,
- first_name,
- last_name,
- },
- });
-
- return {
- ...user.data,
- password,
- };
- },
- salesCreate: async ({ ...data }: SalesFormData): Promise<Sale> => {
- const response = await dataProvider.create("sales", {
- data: {
- ...data,
- password: "new_password",
- },
- });
-
- return response.data;
- },
- salesUpdate: async (
- id: Identifier,
- data: Partial<Omit<SalesFormData, "password">>,
- ): Promise<Sale> => {
- const { data: previousData } = await dataProvider.getOne<Sale>("sales", {
- id,
- });
-
- if (!previousData) {
- throw new Error("User not found");
- }
-
- const { data: sale } = await dataProvider.update<Sale>("sales", {
- id,
- data,
- previousData,
- });
- return { ...sale, user_id: sale.id.toString() };
- },
- isInitialized: async (): Promise<boolean> => {
- const sales = await dataProvider.getList<Sale>("sales", {
- filter: {},
- pagination: { page: 1, perPage: 1 },
- sort: { field: "id", order: "ASC" },
- });
- if (sales.data.length === 0) {
- return false;
- }
- return true;
- },
- updatePassword: async (id: Identifier): Promise<true> => {
- const currentUser = await authProvider.getIdentity?.();
- if (!currentUser) {
- throw new Error("User not found");
- }
- const { data: previousData } = await dataProvider.getOne<Sale>("sales", {
- id: currentUser.id,
- });
-
- if (!previousData) {
- throw new Error("User not found");
- }
-
- await dataProvider.update("sales", {
- id,
- data: {
- password: "demo_newPassword",
- },
- previousData,
- });
-
- return true;
- },
- mergeContacts: async (sourceId: Identifier, targetId: Identifier) => {
- return mergeContacts(sourceId, targetId, baseDataProvider);
- },
- getConfiguration: async (): Promise<ConfigurationContextValue> => {
- const { data } = await baseDataProvider.getOne("configuration", { id: 1 });
- return (data?.config as ConfigurationContextValue) ?? {};
- },
- updateConfiguration: async (
- config: ConfigurationContextValue,
- ): Promise<ConfigurationContextValue> => {
- const { data: prev } = await baseDataProvider.getOne("configuration", {
- id: 1,
- });
- await baseDataProvider.update("configuration", {
- id: 1,
- data: { config },
- previousData: prev,
- });
- return config;
- },
-};
-
-async function updateCompany(
- companyId: Identifier,
- updateFn: (company: Company) => Partial<Company>,
-) {
- const { data: company } = await dataProvider.getOne<Company>("companies", {
- id: companyId,
- });
-
- return await dataProvider.update("companies", {
- id: companyId,
- data: {
- ...updateFn(company),
- },
- previousData: company,
- });
+export interface CreateFakeRestDataProviderOptions {
+ db?: Db;
+ latency?: number;
+ authProvider?: Pick<typeof defaultAuthProvider, "getIdentity">;
}
const processConfigLogo = async (logo: any): Promise<string> => {
@@ -283,9 +138,176 @@ const preserveAttachmentMimeType = <
})),
});
-export const dataProvider = withLifecycleCallbacks(
- withSupabaseFilterAdapter(dataProviderWithCustomMethod),
- [
+export const createDataProvider = ({
+ db = generateData(),
+ latency = 300,
+ authProvider,
+}: CreateFakeRestDataProviderOptions = {}): CrmDataProvider => {
+ const baseDataProvider = fakeRestDataProvider(db, true, latency);
+ let taskUpdateType = TASK_DONE_NOT_CHANGED;
+ let dataProvider: CrmDataProvider;
+ const getIdentity = async () =>
+ authProvider?.getIdentity?.() ?? defaultAuthProvider.getIdentity?.();
+
+ const updateCompany = async (
+ companyId: Identifier,
+ updateFn: (company: Company) => Partial<Company>,
+ ) => {
+ const { data: company } = await dataProvider.getOne<Company>("companies", {
+ id: companyId,
+ });
+
+ return await dataProvider.update("companies", {
+ id: companyId,
+ data: {
+ ...updateFn(company),
+ },
+ previousData: company,
+ });
+ };
+
+ const dataProviderWithCustomMethod: CrmDataProvider = {
+ ...baseDataProvider,
+ unarchiveDeal: async (deal: Deal) => {
+ // get all deals where stage is the same as the deal to unarchive
+ const { data: deals } = await baseDataProvider.getList<Deal>("deals", {
+ filter: { stage: deal.stage },
+ pagination: { page: 1, perPage: 1000 },
+ sort: { field: "index", order: "ASC" },
+ });
+
+ // set index for each deal starting from 1, if the deal to unarchive is found, set its index to the last one
+ const updatedDeals = deals.map((d, index) => ({
+ ...d,
+ index: d.id === deal.id ? 0 : index + 1,
+ archived_at: d.id === deal.id ? null : d.archived_at,
+ }));
+
+ return await Promise.all(
+ updatedDeals.map((updatedDeal) =>
+ dataProvider.update("deals", {
+ id: updatedDeal.id,
+ data: updatedDeal,
+ previousData: deals.find((d) => d.id === updatedDeal.id),
+ }),
+ ),
+ );
+ },
+ // We simulate a remote endpoint that is in charge of returning activity log
+ getActivityLog: async (companyId?: Identifier) => {
+ return getActivityLog(dataProvider, companyId);
+ },
+ signUp: async ({
+ email,
+ password,
+ first_name,
+ last_name,
+ }: SignUpData): Promise<{
+ id: string;
+ email: string;
+ password: string;
+ }> => {
+ const user = await baseDataProvider.create("sales", {
+ data: {
+ email,
+ first_name,
+ last_name,
+ },
+ });
+
+ return {
+ ...user.data,
+ password,
+ };
+ },
+ salesCreate: async ({ ...data }: SalesFormData): Promise<Sale> => {
+ const response = await dataProvider.create("sales", {
+ data: {
+ ...data,
+ password: "new_password",
+ },
+ });
+
+ return response.data;
+ },
+ salesUpdate: async (
+ id: Identifier,
+ data: Partial<Omit<SalesFormData, "password">>,
+ ): Promise<Sale> => {
+ const { data: previousData } = await dataProvider.getOne<Sale>("sales", {
+ id,
+ });
+
+ if (!previousData) {
+ throw new Error("User not found");
+ }
+
+ const { data: sale } = await dataProvider.update<Sale>("sales", {
+ id,
+ data,
+ previousData,
+ });
+ return { ...sale, user_id: sale.id.toString() };
+ },
+ isInitialized: async (): Promise<boolean> => {
+ const sales = await dataProvider.getList<Sale>("sales", {
+ filter: {},
+ pagination: { page: 1, perPage: 1 },
+ sort: { field: "id", order: "ASC" },
+ });
+ if (sales.data.length === 0) {
+ return false;
+ }
+ return true;
+ },
+ updatePassword: async (id: Identifier): Promise<true> => {
+ const currentUser = await getIdentity();
+ if (!currentUser) {
+ throw new Error("User not found");
+ }
+ const { data: previousData } = await dataProvider.getOne<Sale>("sales", {
+ id: currentUser.id,
+ });
+
+ if (!previousData) {
+ throw new Error("User not found");
+ }
+
+ await dataProvider.update("sales", {
+ id,
+ data: {
+ password: "demo_newPassword",
+ },
+ previousData,
+ });
+
+ return true;
+ },
+ mergeContacts: async (sourceId: Identifier, targetId: Identifier) => {
+ return mergeContacts(sourceId, targetId, baseDataProvider);
+ },
+ getConfiguration: async (): Promise<ConfigurationContextValue> => {
+ const { data } = await baseDataProvider.getOne("configuration", { id: 1 });
+ return (data?.config as ConfigurationContextValue) ?? {};
+ },
+ updateConfiguration: async (
+ config: ConfigurationContextValue,
+ ): Promise<ConfigurationContextValue> => {
+ const { data: prev } = await baseDataProvider.getOne("configuration", {
+ id: 1,
+ });
+ await baseDataProvider.update("configuration", {
+ id: 1,
+ data: { config },
+ previousData: prev,
+ });
+ return config;
+ },
+ };
+
+ dataProvider = withLifecycleCallbacks(
+ withSupabaseFilterAdapter(dataProviderWithCustomMethod),
+ [
{
resource: "configuration",
beforeUpdate: async (params) => {
@@ -310,7 +332,7 @@ export const dataProvider = withLifecycleCallbacks(
afterSave: async (data) => {
// Since the current user is stored in localStorage in fakerest authProvider
// we need to update it to keep information up to date in the UI
- const currentUser = await authProvider.getIdentity?.();
+ const currentUser = await getIdentity();
if (currentUser?.id === data.id) {
localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(data));
}
@@ -567,8 +589,13 @@ export const dataProvider = withLifecycleCallbacks(
resource: "deal_notes",
beforeSave: async (params) => preserveAttachmentMimeType(params),
} satisfies ResourceCallbacks<DealNote>,
- ],
-) as CrmDataProvider;
+ ],
+ ) as CrmDataProvider;
+
+ return dataProvider;
+};
+
+export const dataProvider = createDataProvider();
/**
* Convert a `File` object returned by the upload input into a base 64 string.
diff --git a/src/components/atomic-crm/providers/fakerest/index.ts b/src/components/atomic-crm/providers/fakerest/index.ts
index 75a08a19..d071b9a3 100644
--- a/src/components/atomic-crm/providers/fakerest/index.ts
+++ b/src/components/atomic-crm/providers/fakerest/index.ts
@@ -1,2 +1,2 @@
export { authProvider } from "./authProvider";
-export { dataProvider } from "./dataProvider";
+export { createDataProvider, dataProvider } from "./dataProvider";
diff --git a/src/test/browser/atomic-crm/crmUiHarness.tsx b/src/test/browser/atomic-crm/crmUiHarness.tsx
new file mode 100644
index 00000000..54221e19
--- /dev/null
+++ b/src/test/browser/atomic-crm/crmUiHarness.tsx
@@ -0,0 +1,316 @@
+import { Notification } from "@/components/admin/notification";
+import { ThemeProvider } from "@/components/admin/theme-provider";
+import { ContactList } from "@/components/atomic-crm/contacts/ContactList";
+import {
+ ContactListContent,
+ ContactListContentMobile,
+} from "@/components/atomic-crm/contacts/ContactListContent";
+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 { CONFIGURATION_STORE_KEY } from "@/components/atomic-crm/root/ConfigurationContext";
+import { defaultConfiguration } from "@/components/atomic-crm/root/defaultConfiguration";
+import { i18nProvider } from "@/components/atomic-crm/root/i18nProvider";
+import { TaskCreateSheet } from "@/components/atomic-crm/tasks/TaskCreateSheet";
+import type {
+ Company,
+ Contact,
+ Sale,
+ Tag,
+ Task,
+} from "@/components/atomic-crm/types";
+import {
+ CoreAdminContext,
+ InfiniteListBase,
+ ListBase,
+ ResourceContextProvider,
+ ResourceDefinitionContextProvider,
+ localStorageStore,
+ type AuthProvider,
+} from "ra-core";
+import { useMemo, useState, type ReactNode } from "react";
+import { MemoryRouter } from "react-router";
+
+const listSort = { field: "last_seen", order: "DESC" } as const;
+const listPerPage = 25;
+
+let scenarioCount = 0;
+
+const wait = (ms: number) =>
+ new Promise((resolve) => {
+ window.setTimeout(resolve, ms);
+ });
+
+const getContactName = (record?: Contact) =>
+ `${record?.first_name ?? ""} ${record?.last_name ?? ""}`.trim();
+
+const getCompanyName = (record?: Company) => record?.name ?? "";
+const getSaleName = (record?: Sale) =>
+ `${record?.first_name ?? ""} ${record?.last_name ?? ""}`.trim();
+const getTagName = (record?: Tag) => record?.name ?? "";
+const getTaskName = (record?: Task) => record?.text ?? "";
+
+const resourceDefinitions = {
+ companies: {
+ hasList: true,
+ name: "companies",
+ recordRepresentation: getCompanyName,
+ },
+ configuration: {
+ name: "configuration",
+ },
+ contacts: {
+ hasCreate: true,
+ hasList: true,
+ hasShow: true,
+ name: "contacts",
+ recordRepresentation: getContactName,
+ },
+ contacts_summary: {
+ hasList: true,
+ name: "contacts_summary",
+ recordRepresentation: getContactName,
+ },
+ sales: {
+ hasList: true,
+ name: "sales",
+ recordRepresentation: getSaleName,
+ },
+ tags: {
+ hasList: true,
+ name: "tags",
+ recordRepresentation: getTagName,
+ },
+ tasks: {
+ hasCreate: true,
+ hasList: true,
+ name: "tasks",
+ recordRepresentation: getTaskName,
+ },
+};
+
+const createTestAuthProvider = (): AuthProvider => ({
+ canAccess: async () => true,
+ checkAuth: async () => undefined,
+ checkError: async () => undefined,
+ getIdentity: async () => ({
+ avatar: DEFAULT_USER.avatar.src,
+ fullName: `${DEFAULT_USER.first_name} ${DEFAULT_USER.last_name}`,
+ id: DEFAULT_USER.id,
+ }),
+ login: async () => undefined,
+ logout: async () => undefined,
+});
+
+const baseSale: Sale = {
+ administrator: true,
+ avatar: DEFAULT_USER.avatar,
+ disabled: false,
+ email: DEFAULT_USER.email,
+ first_name: DEFAULT_USER.first_name,
+ id: DEFAULT_USER.id,
+ last_name: DEFAULT_USER.last_name,
+ password: DEFAULT_USER.password,
+ user_id: DEFAULT_USER.id.toString(),
+};
+
+export interface CrmScenarioOptions {
+ db?: Db;
+ failGetListOnce?: Partial<Record<string, string>>;
+ getListDelays?: Partial<Record<string, number>>;
+ latency?: number;
+}
+
+export interface CrmScenario {
+ authProvider: AuthProvider;
+ dataProvider: ReturnType<typeof createDataProvider>;
+ db: Db;
+ store: ReturnType<typeof localStorageStore>;
+}
+
+// Provide a minimal FakeRest database shape so tests can override only the records
+// that matter for each scenario.
+export const createCrmDb = (overrides: Partial<Db> = {}): Db =>
+ ({
+ companies: [],
+ configuration: [{ config: {}, id: 1 }],
+ contact_notes: [],
+ contacts: [],
+ deal_notes: [],
+ deals: [],
+ sales: [baseSale],
+ tags: [],
+ tasks: [],
+ ...overrides,
+ }) as Db;
+
+// Build a valid contact record with sensible defaults to keep tests and stories terse.
+export const buildContact = (overrides: Partial<Contact> = {}): Contact => ({
+ background: "",
+ company_id: null,
+ company_name: undefined,
+ email_jsonb: [{ email: "[email protected]", type: "Work" }],
+ first_name: "Ada",
+ first_seen: "2025-01-01T09:00:00.000Z",
+ gender: "female",
+ has_newsletter: false,
+ id: 1,
+ last_name: "Lovelace",
+ last_seen: "2025-01-02T10:00:00.000Z",
+ linkedin_url: null,
+ nb_tasks: 0,
+ phone_jsonb: [],
+ sales_id: 0,
+ status: "warm",
+ tags: [],
+ title: "CTO",
+ ...overrides,
+});
+
+// Create an isolated CRM runtime backed by FakeRest, with optional delays and
+// one-shot failures to exercise loading and error states.
+export const createCrmScenario = ({
+ db = createCrmDb(),
+ failGetListOnce = {},
+ getListDelays = {},
+ latency = 0,
+}: CrmScenarioOptions = {}): CrmScenario => {
+ const authProvider = createTestAuthProvider();
+ const baseDataProvider = createDataProvider({
+ authProvider,
+ db,
+ latency,
+ });
+ const pendingFailures = new Map(Object.entries(failGetListOnce));
+ const dataProvider = {
+ ...baseDataProvider,
+ getList: async (resource, params) => {
+ const delayMs = getListDelays[resource] ?? 0;
+ if (delayMs > 0) {
+ await wait(delayMs);
+ }
+
+ const failureMessage = pendingFailures.get(resource);
+ if (failureMessage) {
+ pendingFailures.delete(resource);
+ throw new Error(failureMessage);
+ }
+
+ return baseDataProvider.getList(resource, params);
+ },
+ } as ReturnType<typeof createDataProvider>;
+ const store = localStorageStore(undefined, `CRM_TEST_${scenarioCount += 1}`);
+ store.setItem(CONFIGURATION_STORE_KEY, defaultConfiguration);
+
+ return {
+ authProvider,
+ dataProvider,
+ db,
+ store,
+ };
+};
+
+// Mount the minimum react-admin and app providers required by the CRM widgets
+// under test, without booting the full application shell.
+export const CrmTestProvider = ({
+ children,
+ className,
+ initialEntries = ["/"],
+ resource,
+ scenario,
+}: {
+ children: ReactNode;
+ className?: string;
+ initialEntries?: string[];
+ resource?: string;
+ scenario: CrmScenario;
+}) => (
+ <MemoryRouter initialEntries={initialEntries}>
+ <CoreAdminContext
+ authProvider={scenario.authProvider}
+ dataProvider={scenario.dataProvider}
+ i18nProvider={i18nProvider}
+ store={scenario.store}
+ >
+ <ResourceDefinitionContextProvider definitions={resourceDefinitions}>
+ <ThemeProvider>
+ <div className={className}>
+ {resource ? (
+ <ResourceContextProvider value={resource}>
+ {children}
+ </ResourceContextProvider>
+ ) : (
+ children
+ )}
+ </div>
+ <Notification />
+ </ThemeProvider>
+ </ResourceDefinitionContextProvider>
+ </CoreAdminContext>
+ </MemoryRouter>
+);
+
+// Reuse the same scenario factory in Storybook so stories match the integration
+// test environment as closely as possible.
+export const CrmStoryProvider = ({
+ children,
+ className,
+ initialEntries,
+ resource,
+ scenarioOptions,
+}: {
+ children: ReactNode;
+ className?: string;
+ initialEntries?: string[];
+ resource?: string;
+ scenarioOptions: CrmScenarioOptions;
+}) => {
+ const scenario = useMemo(
+ () => createCrmScenario(scenarioOptions),
+ [scenarioOptions],
+ );
+
+ return (
+ <CrmTestProvider
+ className={className}
+ initialEntries={initialEntries}
+ resource={resource}
+ scenario={scenario}
+ >
+ {children}
+ </CrmTestProvider>
+ );
+};
+
+export const DesktopContactListHarness = () => <ContactList />;
+
+// ContactListContent expects the desktop list controller to already be mounted.
+export const DesktopContactListContentHarness = () => (
+ <ListBase perPage={listPerPage} resource="contacts" sort={listSort}>
+ <ContactListContent />
+ </ListBase>
+);
+
+// The mobile content uses the infinite list controller and exposes retry UX for
+// request failures.
+export const MobileContactListContentHarness = () => (
+ <div className="mx-auto max-w-sm px-4 py-6">
+ <InfiniteListBase
+ perPage={listPerPage}
+ queryOptions={{
+ onError: () => undefined,
+ }}
+ resource="contacts"
+ sort={listSort}
+ >
+ <ContactListContentMobile />
+ </InfiniteListBase>
+ </div>
+);
+
+// Keep the sheet stateful so tests can assert that save flows close it.
+export const OpenTaskCreateSheetHarness = () => {
+ const [open, setOpen] = useState(true);
+
+ return <TaskCreateSheet open={open} onOpenChange={setOpen} />;
+};