Skip to content

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

Show recently viewed contacts on the dashboard

fzaninotto90b2ce04c5fd
diff --git a/registry.json b/registry.json
index b36216df..d31caace 100644
--- a/registry.json
+++ b/registry.json
@@ -703,6 +703,10 @@
"path": "src/components/atomic-crm/dashboard/TasksList.tsx",
"type": "registry:component"
},
+ {
+ "path": "src/components/atomic-crm/dashboard/RecentContacts.tsx",
+ "type": "registry:component"
+ },
{
"path": "src/components/atomic-crm/dashboard/MobileDashboard.tsx",
"type": "registry:component"
@@ -727,6 +731,10 @@
"path": "src/components/atomic-crm/dashboard/DashboardStepper.tsx",
"type": "registry:component"
},
+ {
+ "path": "src/components/atomic-crm/dashboard/DashboardContactList.tsx",
+ "type": "registry:component"
+ },
{
"path": "src/components/atomic-crm/dashboard/DashboardActivityLog.tsx",
"type": "registry:component"
@@ -735,6 +743,10 @@
"path": "src/components/atomic-crm/dashboard/Dashboard.tsx",
"type": "registry:component"
},
+ {
+ "path": "src/components/atomic-crm/contacts/useRecentContacts.ts",
+ "type": "registry:component"
+ },
{
"path": "src/components/atomic-crm/contacts/useContactImport.tsx",
"type": "registry:component"
diff --git a/src/components/atomic-crm/contacts/ContactShow.tsx b/src/components/atomic-crm/contacts/ContactShow.tsx
index ca467d7f..36fddbb6 100644
--- a/src/components/atomic-crm/contacts/ContactShow.tsx
+++ b/src/components/atomic-crm/contacts/ContactShow.tsx
@@ -31,6 +31,7 @@ import { ContactTasksList } from "./ContactTasksList";
import type { Contact } from "../types";
import { Avatar } from "./Avatar";
import { ContactAside } from "./ContactAside";
+import { useTrackRecentContact } from "./useRecentContacts";
import { MobileBackButton } from "../misc/MobileBackButton";
export const ContactShow = (props: ShowBaseProps = {}) => {
@@ -82,6 +83,7 @@ const ContactShowContentMobile = () => {
const { defaultTitle, record, isPending, error } = useShowContext<Contact>();
const [noteCreateOpen, setNoteCreateOpen] = useState(false);
const [editOpen, setEditOpen] = useState(false);
+ useTrackRecentContact();
if (isPending) return null;
// The error notification is disabled on mobile, so show the error here,
// unless a cached record is still available (e.g. offline refetch failure)
@@ -264,6 +266,7 @@ const ContactShowContentMobile = () => {
const ContactShowContent = () => {
const translate = useTranslate();
const { record, isPending } = useShowContext<Contact>();
+ useTrackRecentContact();
if (isPending || !record) return null;
return (
diff --git a/src/components/atomic-crm/contacts/useRecentContacts.ts b/src/components/atomic-crm/contacts/useRecentContacts.ts
new file mode 100644
index 00000000..8dbeefdb
--- /dev/null
+++ b/src/components/atomic-crm/contacts/useRecentContacts.ts
@@ -0,0 +1,42 @@
+import { useEffect } from "react";
+import { useRecordContext, useStore } from "ra-core";
+import type { Identifier } from "ra-core";
+
+export const RECENT_CONTACTS_STORE_KEY = "contacts.recentlyViewed";
+const MAX_RECENT_CONTACTS = 5;
+export const RECENT_PERIOD = 24 * 60 * 60 * 1000; // one day
+
+export type RecentContactView = { id: Identifier; viewedAt: number };
+
+const NO_VIEWS: RecentContactView[] = [];
+
+export const useRecentContacts = () => {
+ const [views] = useStore<RecentContactView[]>(
+ RECENT_CONTACTS_STORE_KEY,
+ NO_VIEWS,
+ );
+ const since = Date.now() - RECENT_PERIOD;
+ return views
+ .filter((view) => view.viewedAt > since)
+ .slice(0, MAX_RECENT_CONTACTS)
+ .map((view) => view.id);
+};
+
+export const useTrackRecentContact = () => {
+ const record = useRecordContext();
+ const [, setViews] = useStore<RecentContactView[]>(
+ RECENT_CONTACTS_STORE_KEY,
+ NO_VIEWS,
+ );
+ const id = record?.id;
+
+ useEffect(() => {
+ if (id == null) return;
+ setViews((views) => [
+ { id, viewedAt: Date.now() },
+ ...views
+ .filter((view) => view.id !== id)
+ .slice(0, MAX_RECENT_CONTACTS - 1),
+ ]);
+ }, [id, setViews]);
+};
diff --git a/src/components/atomic-crm/dashboard/Dashboard.tsx b/src/components/atomic-crm/dashboard/Dashboard.tsx
index a944c5fa..82e0abe9 100644
--- a/src/components/atomic-crm/dashboard/Dashboard.tsx
+++ b/src/components/atomic-crm/dashboard/Dashboard.tsx
@@ -5,6 +5,7 @@ import { DashboardActivityLog } from "./DashboardActivityLog";
import { DashboardStepper } from "./DashboardStepper";
import { DealsChart } from "./DealsChart";
import { HotContacts } from "./HotContacts";
+import { RecentContacts } from "./RecentContacts";
import { TasksList } from "./TasksList";
import { Welcome } from "./Welcome";
@@ -48,6 +49,7 @@ export const Dashboard = () => {
<div className="md:col-span-3">
<div className="flex flex-col gap-4">
{import.meta.env.VITE_IS_DEMO === "true" ? <Welcome /> : null}
+ <RecentContacts />
<HotContacts />
</div>
</div>
diff --git a/src/components/atomic-crm/dashboard/DashboardContactList.tsx b/src/components/atomic-crm/dashboard/DashboardContactList.tsx
new file mode 100644
index 00000000..348273e6
--- /dev/null
+++ b/src/components/atomic-crm/dashboard/DashboardContactList.tsx
@@ -0,0 +1,69 @@
+import type { ReactElement } from "react";
+import { RecordsIterator, useTranslate } from "ra-core";
+import { Link } from "react-router";
+import { Card } from "@/components/ui/card";
+import { useIsMobile } from "@/hooks/use-mobile";
+
+import { SimpleListLoading } from "../simple-list/SimpleListLoading";
+import { Avatar } from "../contacts/Avatar";
+import type { Contact } from "../types";
+
+export const DashboardContactList = ({
+ data,
+ empty = null,
+ isPending,
+ total,
+}: {
+ data?: Contact[];
+ empty?: ReactElement | null;
+ isPending?: boolean;
+ total?: number;
+}) => {
+ const translate = useTranslate();
+ const isMobile = useIsMobile();
+ const className = isMobile
+ ? "divide-y [&_a]:px-0"
+ : "[&>li:first-child>a]:rounded-t-xl [&>li:last-child>a]:rounded-b-xl";
+
+ const content = isPending ? (
+ <SimpleListLoading
+ className={className}
+ hasLeftAvatarOrIcon
+ hasSecondaryText
+ />
+ ) : !data?.length ? (
+ empty
+ ) : (
+ <ul className={className}>
+ <RecordsIterator
+ data={data}
+ total={total}
+ render={(contact) => (
+ <li>
+ <Link
+ to={`/contacts/${contact.id}/show`}
+ className="flex items-center gap-3 p-3 hover:bg-muted focus:bg-muted focus:outline-none"
+ >
+ <Avatar />
+ <div className="flex-1 min-w-0">
+ <div className="text-sm font-medium truncate">
+ {contact.first_name} {contact.last_name}
+ </div>
+ <div className="text-sm text-muted-foreground truncate">
+ {contact.title && contact.company_name
+ ? translate("resources.contacts.position_at_company", {
+ title: contact.title,
+ company: contact.company_name,
+ })
+ : contact.title || contact.company_name}
+ </div>
+ </div>
+ </Link>
+ </li>
+ )}
+ />
+ </ul>
+ );
+
+ return isMobile ? content : <Card className="py-0">{content}</Card>;
+};
diff --git a/src/components/atomic-crm/dashboard/HotContacts.tsx b/src/components/atomic-crm/dashboard/HotContacts.tsx
index 1d72234a..a1816c0d 100644
--- a/src/components/atomic-crm/dashboard/HotContacts.tsx
+++ b/src/components/atomic-crm/dashboard/HotContacts.tsx
@@ -3,7 +3,6 @@ import { useGetIdentity, useGetList, useTranslate } from "ra-core";
import { Link } from "react-router";
import { buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
-import { Card } from "@/components/ui/card";
import {
Tooltip,
TooltipContent,
@@ -11,9 +10,8 @@ import {
TooltipTrigger,
} from "@/components/ui/tooltip";
-import { SimpleList } from "../simple-list/SimpleList";
-import { Avatar } from "../contacts/Avatar";
import type { Contact } from "../types";
+import { DashboardContactList } from "./DashboardContactList";
export const HotContacts = () => {
const { identity } = useGetIdentity();
@@ -63,40 +61,21 @@ export const HotContacts = () => {
</Tooltip>
</TooltipProvider>
</div>
- <Card className="py-0">
- <SimpleList<Contact>
- linkType="show"
- data={contactData}
- total={contactTotal}
- isPending={contactsLoading}
- resource="contacts"
- className="[&>li:first-child>a]:rounded-t-xl [&>li:last-child>a]:rounded-b-xl"
- primaryText={(contact) =>
- `${contact.first_name} ${contact.last_name}`
- }
- secondaryText={(contact) => (
- <>
- {contact.title && contact.company_name
- ? translate("resources.contacts.position_at_company", {
- title: contact.title,
- company: contact.company_name,
- })
- : contact.title || contact.company_name}
- </>
- )}
- leftAvatar={(contact) => <Avatar record={contact} />}
- empty={
- <div className="p-4">
- <p className="text-sm mb-4">
- {translate("resources.contacts.hot.empty_hint")}
- </p>
- <p className="text-sm">
- {translate("resources.contacts.hot.empty_change_status")}
- </p>
- </div>
- }
- />
- </Card>
+ <DashboardContactList
+ data={contactData}
+ total={contactTotal}
+ isPending={contactsLoading}
+ empty={
+ <div className="p-4">
+ <p className="text-sm mb-4">
+ {translate("resources.contacts.hot.empty_hint")}
+ </p>
+ <p className="text-sm">
+ {translate("resources.contacts.hot.empty_change_status")}
+ </p>
+ </div>
+ }
+ />
</div>
);
};
diff --git a/src/components/atomic-crm/dashboard/MobileDashboard.tsx b/src/components/atomic-crm/dashboard/MobileDashboard.tsx
index 52ab6331..2327e1f7 100644
--- a/src/components/atomic-crm/dashboard/MobileDashboard.tsx
+++ b/src/components/atomic-crm/dashboard/MobileDashboard.tsx
@@ -4,6 +4,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import type { Contact, ContactNote } from "../types";
import { DashboardActivityLog } from "./DashboardActivityLog";
import { DashboardStepper } from "./DashboardStepper";
+import { RecentContacts } from "./RecentContacts";
import { Welcome } from "./Welcome";
import MobileHeader from "../layout/MobileHeader";
import { MobileContent } from "../layout/MobileContent";
@@ -83,6 +84,7 @@ export const MobileDashboard = () => {
<Wrapper>
<div className="grid grid-cols-1 md:grid-cols-12 gap-6 mt-1">
{import.meta.env.VITE_IS_DEMO === "true" ? <Welcome /> : null}
+ <RecentContacts />
<DashboardActivityLog />
</div>
</Wrapper>
diff --git a/src/components/atomic-crm/dashboard/RecentContacts.test.tsx b/src/components/atomic-crm/dashboard/RecentContacts.test.tsx
new file mode 100644
index 00000000..831f16bf
--- /dev/null
+++ b/src/components/atomic-crm/dashboard/RecentContacts.test.tsx
@@ -0,0 +1,117 @@
+import { useStore } from "ra-core";
+import { useEffect } from "react";
+import { render } from "vitest-browser-react";
+import { buildContact, StoryWrapper } from "@/test/StoryWrapper";
+import { ContactShow } from "../contacts/ContactShow";
+import {
+ RECENT_CONTACTS_STORE_KEY,
+ RECENT_PERIOD,
+ type RecentContactView,
+} from "../contacts/useRecentContacts";
+import { RecentContacts } from "./RecentContacts";
+
+const SeedViews = ({ views }: { views: RecentContactView[] }) => {
+ const [, setViews] = useStore<RecentContactView[]>(RECENT_CONTACTS_STORE_KEY);
+ useEffect(() => setViews(views), [views, setViews]);
+ return null;
+};
+
+describe("RecentContacts", () => {
+ it("renders nothing until a contact has been viewed", async () => {
+ const screen = await render(
+ <StoryWrapper data={{ contacts: [buildContact({ id: 1 })] }}>
+ <RecentContacts />
+ </StoryWrapper>,
+ );
+
+ await expect
+ .element(screen.getByRole("heading", { name: "Recently Viewed" }))
+ .not.toBeInTheDocument();
+ });
+
+ it("links to the contacts viewed on this device, latest first", async () => {
+ const screen = await render(
+ <StoryWrapper
+ data={{
+ contacts: [
+ buildContact({ id: 1, first_name: "Ada", last_name: "Lovelace" }),
+ buildContact({ id: 2, first_name: "Alan", last_name: "Turing" }),
+ ],
+ }}
+ >
+ <ContactShow resource="contacts" id={1} />
+ <ContactShow resource="contacts" id={2} />
+ <RecentContacts />
+ </StoryWrapper>,
+ );
+
+ const list = screen.getByRole("list");
+ await expect
+ .element(list.getByRole("link", { name: /Alan Turing/ }))
+ .toHaveAttribute("href", "/contacts/2/show");
+ const links = list.getByRole("link").elements();
+ expect(links.map((link) => link.textContent)).toEqual([
+ expect.stringContaining("Alan Turing"),
+ expect.stringContaining("Ada Lovelace"),
+ ]);
+ });
+
+ it("ignores contacts deleted since they were viewed", async () => {
+ const screen = await render(
+ <StoryWrapper
+ data={{
+ contacts: [
+ buildContact({ id: 1, first_name: "Ada", last_name: "Lovelace" }),
+ ],
+ }}
+ >
+ <SeedViews
+ views={[
+ { id: 2, viewedAt: Date.now() },
+ { id: 1, viewedAt: Date.now() },
+ ]}
+ />
+ <RecentContacts />
+ </StoryWrapper>,
+ );
+
+ await expect
+ .element(screen.getByRole("link", { name: /Ada Lovelace/ }))
+ .toHaveAttribute("href", "/contacts/1/show");
+ expect(screen.getByRole("list").getByRole("link").elements()).toHaveLength(
+ 1,
+ );
+ });
+
+ it("renders nothing when all recently viewed contacts were deleted", async () => {
+ const screen = await render(
+ <StoryWrapper data={{ contacts: [buildContact({ id: 1 })] }}>
+ <SeedViews views={[{ id: 2, viewedAt: Date.now() }]} />
+ <RecentContacts />
+ <h1>Dashboard</h1>
+ </StoryWrapper>,
+ );
+
+ await expect
+ .element(screen.getByRole("heading", { name: "Dashboard" }))
+ .toBeVisible();
+ await expect
+ .element(screen.getByRole("heading", { name: "Recently Viewed" }))
+ .not.toBeInTheDocument();
+ });
+
+ it("forgets contacts viewed more than 24 hours ago", async () => {
+ const screen = await render(
+ <StoryWrapper data={{ contacts: [buildContact({ id: 1 })] }}>
+ <SeedViews
+ views={[{ id: 1, viewedAt: Date.now() - RECENT_PERIOD - 1000 }]}
+ />
+ <RecentContacts />
+ </StoryWrapper>,
+ );
+
+ await expect
+ .element(screen.getByRole("heading", { name: "Recently Viewed" }))
+ .not.toBeInTheDocument();
+ });
+});
diff --git a/src/components/atomic-crm/dashboard/RecentContacts.tsx b/src/components/atomic-crm/dashboard/RecentContacts.tsx
new file mode 100644
index 00000000..aab75356
--- /dev/null
+++ b/src/components/atomic-crm/dashboard/RecentContacts.tsx
@@ -0,0 +1,40 @@
+import { History } from "lucide-react";
+import { useGetMany, useTranslate } from "ra-core";
+
+import { useRecentContacts } from "../contacts/useRecentContacts";
+import type { Contact } from "../types";
+import { DashboardContactList } from "./DashboardContactList";
+
+export const RecentContacts = () => {
+ const translate = useTranslate();
+ const ids = useRecentContacts();
+ const { data, isPending } = useGetMany<Contact>(
+ "contacts",
+ { ids },
+ { enabled: ids.length > 0 },
+ );
+
+ const contacts = ids
+ .map((id) => data?.find((contact) => contact.id === id))
+ .filter((contact) => contact != null);
+
+ if (!ids.length || (!isPending && !contacts.length)) return null;
+
+ return (
+ <div className="flex flex-col">
+ <div className="flex items-center mb-4 md:mb-2">
+ <div className="mr-3 flex">
+ <History className="text-muted-foreground w-6 h-6" />
+ </div>
+ <h2 className="text-xl font-semibold text-muted-foreground">
+ {translate("crm.dashboard.recent_contacts")}
+ </h2>
+ </div>
+ <DashboardContactList
+ data={contacts}
+ total={contacts.length}
+ isPending={isPending}
+ />
+ </div>
+ );
+};
diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
index 776f47b9..890f8422 100644
--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
@@ -434,6 +434,7 @@ export const englishCrmMessages = {
latest_activity_error: "Error loading latest activity",
latest_notes: "My Latest Notes",
latest_notes_added_ago: "added %{timeAgo}",
+ recent_contacts: "Recently Viewed",
stepper: {
install: "Install Atomic CRM",
progress: "%{step}/3 done",
diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
index f4dc4a6e..e060b1ba 100644
--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
@@ -440,6 +440,7 @@ export const frenchCrmMessages = {
"Erreur lors du chargement de la dernière activité",
latest_notes: "Mes dernières notes",
latest_notes_added_ago: "ajouté %{timeAgo}",
+ recent_contacts: "Consultés récemment",
stepper: {
install: "Installer Atomic CRM",
progress: "%{step}/3 terminé",
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts
index 037ad7f6..f57646f9 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts
@@ -42,6 +42,20 @@ describe("fakerest dataProvider", () => {
expect(tags.map((tag) => tag.id)).toEqual([2]);
});
+ it("ignores unknown ids when getting many contacts", async () => {
+ const dataProvider = createDataProvider({
+ db: { contacts: [{ id: 2, first_name: "Ann" }] } as unknown as Db,
+ latency: 0,
+ silent: true,
+ });
+
+ const { data: contacts } = await dataProvider.getMany("contacts", {
+ ids: [1, 2],
+ });
+
+ expect(contacts.map((contact) => contact.id)).toEqual([2]);
+ });
+
it("lists a task created in the app before older ones in the global search", async () => {
const dataProvider = createDataProvider({
db: {
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
index 0cd7f743..74844ac3 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
@@ -177,8 +177,9 @@ export const createDataProvider = ({
const dataProviderWithCustomMethod: CrmDataProvider = {
...baseDataProvider,
async getMany(resource: string, params: any) {
- if (resource === "tags") {
- // like PostgREST, ignore unknown ids (a deleted tag may still be in cached contacts)
+ if (resource === "tags" || resource === "contacts") {
+ // like PostgREST, ignore unknown ids (a deleted tag may still be in cached contacts,
+ // a deleted contact in the recently viewed contacts)
const { data } = await baseDataProvider.getList(resource, {
filter: { id_eq_any: params.ids },
pagination: { page: 1, perPage: params.ids.length },