Skip to content

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

feat: Global search

erwanMarmelabd0e60223ca50
diff --git a/src/components/atomic-crm/dashboard/MobileDashboard.tsx b/src/components/atomic-crm/dashboard/MobileDashboard.tsx
index faf77a1a..3f1c517e 100644
--- a/src/components/atomic-crm/dashboard/MobileDashboard.tsx
+++ b/src/components/atomic-crm/dashboard/MobileDashboard.tsx
@@ -8,6 +8,7 @@ import { Welcome } from "./Welcome";
import MobileHeader from "../layout/MobileHeader";
import { MobileContent } from "../layout/MobileContent";
import { useConfigurationContext } from "../root/ConfigurationContext";
+import { GlobalSearchButton } from "../search";
const Wrapper = ({ children }: { children: React.ReactNode }) => {
const { darkModeLogo, lightModeLogo, title } = useConfigurationContext();
@@ -27,6 +28,7 @@ const Wrapper = ({ children }: { children: React.ReactNode }) => {
/>
<h1 className="text-xl font-semibold">{title}</h1>
</div>
+ <GlobalSearchButton variant="icon" />
</MobileHeader>
<MobileContent>{children}</MobileContent>
</>
diff --git a/src/components/atomic-crm/layout/Header.tsx b/src/components/atomic-crm/layout/Header.tsx
index 2e8f983d..80e130df 100644
--- a/src/components/atomic-crm/layout/Header.tsx
+++ b/src/components/atomic-crm/layout/Header.tsx
@@ -9,6 +9,7 @@ import { DropdownMenuItem } from "@/components/ui/dropdown-menu";
import { useConfigurationContext } from "../root/ConfigurationContext";
import { ImportPage } from "../misc/ImportPage";
import { ChangelogPage } from "../misc/ChangelogPage";
+import { GlobalSearchButton } from "../search";
const Header = () => {
const { darkModeLogo, lightModeLogo, title } = useConfigurationContext();
@@ -81,6 +82,7 @@ const Header = () => {
</nav>
</div>
<div className="flex items-center">
+ <GlobalSearchButton />
<ThemeModeToggle />
<RefreshButton />
<UserMenu>
diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
index de9e8443..def2c5f5 100644
--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
@@ -441,6 +441,21 @@ export const englishCrmMessages = {
header: {
import_data: "Import data",
},
+ search: {
+ title: "Search",
+ placeholder: "Search contacts, companies, deals, tasks and notes...",
+ hint: "Type at least %{min} characters to search",
+ empty: "No result found",
+ untitled_result: "(no title)",
+ groups: {
+ contacts: "Contacts",
+ companies: "Companies",
+ deals: "Deals",
+ tasks: "Tasks",
+ contact_notes: "Contact notes",
+ deal_notes: "Deal notes",
+ },
+ },
image_editor: {
change: "Change",
drop_hint: "Drop a file to upload, or click to select it.",
diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
index 5d30e91f..4aa30ef0 100644
--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
@@ -448,6 +448,22 @@ export const frenchCrmMessages = {
header: {
import_data: "Importer des données",
},
+ search: {
+ title: "Rechercher",
+ placeholder:
+ "Rechercher un contact, une entreprise, une affaire, une tâche, une note...",
+ hint: "Saisissez au moins %{min} caractères pour lancer la recherche",
+ empty: "Aucun résultat",
+ untitled_result: "(sans titre)",
+ groups: {
+ contacts: "Contacts",
+ companies: "Entreprises",
+ deals: "Affaires",
+ tasks: "Tâches",
+ contact_notes: "Notes de contact",
+ deal_notes: "Notes d'affaire",
+ },
+ },
image_editor: {
change: "Changer",
drop_hint:
diff --git a/src/components/atomic-crm/providers/commons/search.ts b/src/components/atomic-crm/providers/commons/search.ts
new file mode 100644
index 00000000..983e78d8
--- /dev/null
+++ b/src/components/atomic-crm/providers/commons/search.ts
@@ -0,0 +1,176 @@
+import type { DataProvider, Identifier } from "ra-core";
+
+import type {
+ Company,
+ Contact,
+ ContactNote,
+ Deal,
+ DealNote,
+ SearchResult,
+ Task,
+} from "../../types";
+
+const PER_RESOURCE_LIMIT = 50;
+const MAX_RESULTS = 250;
+
+const searchResource = async <T>(
+ dataProvider: DataProvider,
+ resource: string,
+ q: string,
+ sortField: string,
+): Promise<T[]> => {
+ const { data } = await dataProvider.getList<any>(resource, {
+ filter: { q },
+ pagination: { page: 1, perPage: PER_RESOURCE_LIMIT },
+ sort: { field: sortField, order: "DESC" },
+ });
+ return data as T[];
+};
+
+const getLabels = async <T extends { id: Identifier }>(
+ dataProvider: DataProvider,
+ resource: string,
+ ids: (Identifier | undefined | null)[],
+ getLabel: (record: T) => string,
+): Promise<Map<Identifier, string>> => {
+ const uniqueIds = [...new Set(ids.filter(Boolean) as Identifier[])];
+ if (uniqueIds.length === 0) {
+ return new Map();
+ }
+ const { data } = await dataProvider.getMany<any>(resource, {
+ ids: uniqueIds,
+ });
+ return new Map((data as T[]).map((record) => [record.id, getLabel(record)]));
+};
+
+const contactName = (contact: Pick<Contact, "first_name" | "last_name">) =>
+ [contact.first_name, contact.last_name].filter(Boolean).join(" ");
+
+const byDateDesc = (a: SearchResult, b: SearchResult) =>
+ (b.date ?? "").localeCompare(a.date ?? "");
+
+/**
+ * Emulates the `search_index` database view for the FakeRest provider, by
+ * running FakeRest's own `q` search on each searchable resource and mapping
+ * the matches to the view's shape.
+ *
+ * FIXME: requires one query per resource, and FakeRest matches the whole term
+ * as a single substring where Postgres ANDs one `ilike` per word. The Supabase
+ * provider queries the real view instead.
+ */
+export async function getSearchResults(
+ dataProvider: DataProvider,
+ query: string,
+): Promise<SearchResult[]> {
+ const q = query.trim();
+ if (!q) {
+ return [];
+ }
+
+ const [companies, contacts, deals, tasks, contactNotes, dealNotes] =
+ await Promise.all([
+ searchResource<Company>(dataProvider, "companies", q, "created_at"),
+ searchResource<Contact>(dataProvider, "contacts", q, "last_seen"),
+ searchResource<Deal>(dataProvider, "deals", q, "created_at"),
+ searchResource<Task>(dataProvider, "tasks", q, "due_date"),
+ searchResource<ContactNote>(dataProvider, "contact_notes", q, "date"),
+ searchResource<DealNote>(dataProvider, "deal_notes", q, "date"),
+ ]);
+
+ const [contactLabels, dealLabels] = await Promise.all([
+ getLabels<Contact>(
+ dataProvider,
+ "contacts",
+ [
+ ...tasks.map((task) => task.contact_id),
+ ...contactNotes.map((note) => note.contact_id),
+ ],
+ contactName,
+ ),
+ getLabels<Deal>(
+ dataProvider,
+ "deals",
+ dealNotes.map((note) => note.deal_id),
+ (deal) => deal.name,
+ ),
+ ]);
+
+ const rows: SearchResult[] = [
+ ...companies.map((company) => ({
+ id: `company.${company.id}`,
+ resource: "companies" as const,
+ record_id: company.id,
+ title: company.name,
+ subtitle: company.sector ?? null,
+ content: null,
+ company_id: company.id,
+ contact_id: null,
+ deal_id: null,
+ date: company.created_at ?? null,
+ })),
+ ...contacts.map((contact) => ({
+ id: `contact.${contact.id}`,
+ resource: "contacts" as const,
+ record_id: contact.id,
+ title: contactName(contact),
+ subtitle: contact.company_name ?? null,
+ content: null,
+ company_id: contact.company_id ?? null,
+ contact_id: contact.id,
+ deal_id: null,
+ date: contact.first_seen ?? null,
+ })),
+ ...deals
+ .filter((deal) => !deal.archived_at)
+ .map((deal) => ({
+ id: `deal.${deal.id}`,
+ resource: "deals" as const,
+ record_id: deal.id,
+ title: deal.name,
+ subtitle: null,
+ content: null,
+ company_id: deal.company_id ?? null,
+ contact_id: null,
+ deal_id: deal.id,
+ date: deal.created_at ?? null,
+ })),
+ ...tasks.map((task) => ({
+ id: `task.${task.id}`,
+ resource: "tasks" as const,
+ record_id: task.id,
+ title: task.text,
+ subtitle: contactLabels.get(task.contact_id) ?? null,
+ content: null,
+ company_id: null,
+ contact_id: task.contact_id,
+ deal_id: null,
+ date: task.due_date ?? null,
+ })),
+ ...contactNotes.map((note) => ({
+ id: `contactNote.${note.id}`,
+ resource: "contact_notes" as const,
+ record_id: note.id,
+ title: note.text,
+ subtitle: contactLabels.get(note.contact_id) ?? null,
+ content: null,
+ company_id: null,
+ contact_id: note.contact_id,
+ deal_id: null,
+ date: note.date ?? null,
+ })),
+ ...dealNotes.map((note) => ({
+ id: `dealNote.${note.id}`,
+ resource: "deal_notes" as const,
+ record_id: note.id,
+ title: note.text,
+ subtitle: dealLabels.get(note.deal_id) ?? null,
+ content: null,
+ company_id: null,
+ contact_id: null,
+ deal_id: note.deal_id,
+ date: note.date ?? null,
+ })),
+ ];
+
+ return rows.sort(byDateDesc).slice(0, MAX_RESULTS);
+}
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
index 4469fd47..f23c4464 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
@@ -24,6 +24,7 @@ import { getActivityLog } from "../commons/activity";
import { getCompanyAvatar } from "../commons/getCompanyAvatar";
import { getContactAvatar } from "../commons/getContactAvatar";
import { mergeContacts } from "../commons/mergeContacts";
+import { getSearchResults } from "../commons/search";
import type { CrmDataProvider } from "../types";
import {
authProvider as defaultAuthProvider,
@@ -170,6 +171,13 @@ export const createDataProvider = ({
const dataProviderWithCustomMethod: CrmDataProvider = {
...baseDataProvider,
async getList(resource: string, params: any) {
+ if (resource === "search_index") {
+ const { filter = {}, pagination } = params;
+ const all = await getSearchResults(baseDataProvider, filter.q ?? "");
+ const { page, perPage } = pagination;
+ const start = (page - 1) * perPage;
+ return { data: all.slice(start, start + perPage), total: all.length };
+ }
if (resource === "activity_log") {
const { filter = {}, pagination } = params;
const all = await getActivityLog(
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.ts
index 664943d8..e0e34f07 100644
--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts
@@ -353,6 +353,25 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [
return applyFullTextSearch(["name", "category", "description"])(params);
},
},
+ {
+ resource: "search_index",
+ beforeGetList: async (params) => {
+ if (!params.filter?.q) {
+ return params;
+ }
+ const { q, ...filter } = params.filter;
+ // A single `ilike` column: ra-data-postgrest splits the term on spaces
+ // and ANDs one `ilike` per word, so "Thomas TF1" matches rows whose
+ // aggregated content contains both words.
+ return {
+ ...params,
+ filter: {
+ ...filter,
+ "content@ilike": q,
+ },
+ };
+ },
+ },
];
export const getDataProvider = () => {
diff --git a/src/components/atomic-crm/search/GlobalSearchButton.tsx b/src/components/atomic-crm/search/GlobalSearchButton.tsx
new file mode 100644
index 00000000..79032ce6
--- /dev/null
+++ b/src/components/atomic-crm/search/GlobalSearchButton.tsx
@@ -0,0 +1,52 @@
+import { Search } from "lucide-react";
+import { useTranslate } from "ra-core";
+import { useEffect, useState } from "react";
+
+import { Button } from "@/components/ui/button";
+
+import { GlobalSearchDialog } from "./GlobalSearchDialog";
+
+/**
+ * Opens the global search dialog. `variant="icon"` renders the compact
+ * icon-only trigger used on mobile; the default renders a labelled trigger for
+ * the desktop app bar.
+ */
+export const GlobalSearchButton = ({
+ variant = "labelled",
+}: {
+ variant?: "labelled" | "icon";
+}) => {
+ const translate = useTranslate();
+ const [open, setOpen] = useState(false);
+
+ useEffect(() => {
+ const onKeyDown = (event: KeyboardEvent) => {
+ if (event.key === "k" && (event.metaKey || event.ctrlKey)) {
+ event.preventDefault();
+ setOpen((previousOpen) => !previousOpen);
+ }
+ };
+ document.addEventListener("keydown", onKeyDown);
+ return () => document.removeEventListener("keydown", onKeyDown);
+ }, []);
+
+ return (
+ <>
+ <Button
+ variant="ghost"
+ size={variant === "icon" ? "icon" : "sm"}
+ onClick={() => setOpen(true)}
+ aria-label={translate("crm.search.title")}
+ aria-keyshortcuts="Control+K Meta+K"
+ >
+ <Search />
+ {variant === "labelled" ? (
+ <span className="hidden lg:inline text-muted-foreground">
+ {translate("crm.search.title")}
+ </span>
+ ) : null}
+ </Button>
+ <GlobalSearchDialog open={open} onOpenChange={setOpen} />
+ </>
+ );
+};
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx b/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
new file mode 100644
index 00000000..15669afd
--- /dev/null
+++ b/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
@@ -0,0 +1,102 @@
+import { describe, expect, it } from "vitest";
+import { render } from "vitest-browser-react";
+
+import { StoryWrapper, buildContact } from "@/test/StoryWrapper";
+
+import { GlobalSearchDialog } from "./GlobalSearchDialog";
+
+const PLACEHOLDER = "Search contacts, companies, deals, tasks and notes...";
+
+const data = {
+ companies: [
+ { id: 1, name: "Boulangerie Martin", sector: "Food" },
+ { id: 2, name: "Acme Corp", sector: "Tech" },
+ ],
+ contacts: [
+ buildContact({ company_id: 1, company_name: "Boulangerie Martin", id: 1 }),
+ ],
+ contact_notes: [
+ {
+ contact_id: 1,
+ date: "2025-02-01T10:00:00.000Z",
+ id: 1,
+ sales_id: 0,
+ status: "warm",
+ text: "Called about the sourdough contract",
+ },
+ ],
+} as any;
+
+const renderDialog = () =>
+ render(
+ <StoryWrapper data={data}>
+ <GlobalSearchDialog open onOpenChange={() => {}} />
+ </StoryWrapper>,
+ );
+
+describe("GlobalSearchDialog", () => {
+ it("asks for a longer query before searching", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("a");
+
+ await expect
+ .element(screen.getByText("Type at least 2 characters to search"))
+ .toBeVisible();
+ });
+
+ it("finds a company by name", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("Boulangerie");
+
+ await expect
+ .element(
+ screen
+ .getByRole("group", { name: "Companies" })
+ .getByText("Boulangerie Martin"),
+ )
+ .toBeVisible();
+ });
+
+ it("also surfaces the contacts of a matching company", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("Boulangerie");
+
+ await expect
+ .element(
+ screen
+ .getByRole("group", { name: "Contacts" })
+ .getByText("Ada Lovelace"),
+ )
+ .toBeVisible();
+ });
+
+ it("finds a note by its text, which no page-specific search can do", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough");
+
+ await expect.element(screen.getByText("Contact notes")).toBeVisible();
+ await expect
+ .element(screen.getByText("Called about the sourdough contract"))
+ .toBeVisible();
+ });
+
+ it("shows the note's contact as the result subtitle", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough");
+
+ await expect.element(screen.getByText("Ada Lovelace")).toBeVisible();
+ });
+
+ it("reports when nothing matches", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("zzzzznomatch");
+
+ await expect.element(screen.getByText("No result found")).toBeVisible();
+ });
+});
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.tsx b/src/components/atomic-crm/search/GlobalSearchDialog.tsx
new file mode 100644
index 00000000..96c47a57
--- /dev/null
+++ b/src/components/atomic-crm/search/GlobalSearchDialog.tsx
@@ -0,0 +1,120 @@
+import { useTranslate } from "ra-core";
+import { useMemo, useState } from "react";
+import { useNavigate } from "react-router";
+
+import {
+ CommandDialog,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@/components/ui/command";
+import { useIsMobile } from "@/hooks/use-mobile";
+
+import type { SearchResult } from "../types";
+import { getSearchResultUrl } from "./getSearchResultUrl";
+import { SEARCH_RESOURCES } from "./searchResources";
+import { MIN_SEARCH_LENGTH, useGlobalSearch } from "./useGlobalSearch";
+
+type LinkedResult = { result: SearchResult; url: string };
+
+export const GlobalSearchDialog = ({
+ open,
+ onOpenChange,
+}: {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) => {
+ const translate = useTranslate();
+ const navigate = useNavigate();
+ const isMobile = useIsMobile();
+ const [query, setQuery] = useState("");
+ const { results, isPending, debouncedQuery } = useGlobalSearch(query);
+
+ // Results whose resource has no page on this layout are dropped rather than
+ // rendered as dead entries.
+ const linkedResults = useMemo(
+ () =>
+ results.reduce<LinkedResult[]>((acc, result) => {
+ const url = getSearchResultUrl(result, isMobile);
+ return url ? [...acc, { result, url }] : acc;
+ }, []),
+ [results, isMobile],
+ );
+
+ const handleOpenChange = (nextOpen: boolean) => {
+ if (!nextOpen) {
+ setQuery("");
+ }
+ onOpenChange(nextOpen);
+ };
+
+ const handleSelect = (url: string) => {
+ handleOpenChange(false);
+ navigate(url);
+ };
+
+ const isTooShort = debouncedQuery.length < MIN_SEARCH_LENGTH;
+
+ return (
+ <CommandDialog
+ open={open}
+ onOpenChange={handleOpenChange}
+ title={translate("crm.search.title")}
+ description={translate("crm.search.placeholder")}
+ shouldFilter={false}
+ >
+ <CommandInput
+ placeholder={translate("crm.search.placeholder")}
+ value={query}
+ onValueChange={setQuery}
+ />
+ <CommandList className="max-h-[60vh]">
+ {isTooShort ? (
+ <div className="py-6 text-center text-sm text-muted-foreground">
+ {translate("crm.search.hint", { min: MIN_SEARCH_LENGTH })}
+ </div>
+ ) : isPending ? (
+ <div className="py-6 text-center text-sm text-muted-foreground">
+ {translate("crm.common.loading")}
+ </div>
+ ) : (
+ <>
+ <CommandEmpty>{translate("crm.search.empty")}</CommandEmpty>
+ {SEARCH_RESOURCES.map(({ name, icon: Icon, labelKey }) => {
+ const groupResults = linkedResults.filter(
+ ({ result }) => result.resource === name,
+ );
+ if (groupResults.length === 0) {
+ return null;
+ }
+ return (
+ <CommandGroup key={name} heading={translate(labelKey)}>
+ {groupResults.map(({ result, url }) => (
+ <CommandItem
+ key={result.id}
+ value={String(result.id)}
+ onSelect={() => handleSelect(url)}
+ >
+ <Icon className="shrink-0" />
+ <span className="truncate">
+ {result.title ||
+ translate("crm.search.untitled_result")}
+ </span>
+ {result.subtitle ? (
+ <span className="ml-auto shrink-0 pl-2 text-xs text-muted-foreground">
+ {result.subtitle}
+ </span>
+ ) : null}
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ );
+ })}
+ </>
+ )}
+ </CommandList>
+ </CommandDialog>
+ );
+};
diff --git a/src/components/atomic-crm/search/getSearchResultUrl.test.ts b/src/components/atomic-crm/search/getSearchResultUrl.test.ts
new file mode 100644
index 00000000..686a05d7
--- /dev/null
+++ b/src/components/atomic-crm/search/getSearchResultUrl.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from "vitest";
+
+import { getSearchResultUrl } from "./getSearchResultUrl";
+
+const buildResult = (overrides: Parameters<typeof getSearchResultUrl>[0]) =>
+ overrides;
+
+describe("getSearchResultUrl", () => {
+ it("links a company to its show page", () => {
+ const result = buildResult({
+ resource: "companies",
+ record_id: 7,
+ contact_id: null,
+ deal_id: null,
+ });
+
+ expect(getSearchResultUrl(result, false)).toBe("/companies/7/show");
+ });
+
+ it("links a contact to its show page", () => {
+ const result = buildResult({
+ resource: "contacts",
+ record_id: 3,
+ contact_id: 3,
+ deal_id: null,
+ });
+
+ expect(getSearchResultUrl(result, false)).toBe("/contacts/3/show");
+ });
+
+ it("links a deal to its show page on desktop", () => {
+ const result = buildResult({
+ resource: "deals",
+ record_id: 5,
+ contact_id: null,
+ deal_id: 5,
+ });
+
+ expect(getSearchResultUrl(result, false)).toBe("/deals/5/show");
+ });
+
+ it("returns null for a deal on mobile, where no deal page exists", () => {
+ const result = buildResult({
+ resource: "deals",
+ record_id: 5,
+ contact_id: null,
+ deal_id: 5,
+ });
+
+ expect(getSearchResultUrl(result, true)).toBeNull();
+ });
+
+ it("links a task to the contact it belongs to", () => {
+ const result = buildResult({
+ resource: "tasks",
+ record_id: 11,
+ contact_id: 4,
+ deal_id: null,
+ });
+
+ expect(getSearchResultUrl(result, false)).toBe("/contacts/4/show");
+ });
+
+ it("links a contact note to the contact page on desktop", () => {
+ const result = buildResult({
+ resource: "contact_notes",
+ record_id: 12,
+ contact_id: 4,
+ deal_id: null,
+ });
+
+ expect(getSearchResultUrl(result, false)).toBe("/contacts/4/show");
+ });
+
+ it("links a contact note to the note detail page on mobile", () => {
+ const result = buildResult({
+ resource: "contact_notes",
+ record_id: 12,
+ contact_id: 4,
+ deal_id: null,
+ });
+
+ expect(getSearchResultUrl(result, true)).toBe("/contacts/4/notes/12");
+ });
+
+ it("links a deal note to its deal on desktop and nowhere on mobile", () => {
+ const result = buildResult({
+ resource: "deal_notes",
+ record_id: 20,
+ contact_id: null,
+ deal_id: 9,
+ });
+
+ expect(getSearchResultUrl(result, false)).toBe("/deals/9/show");
+ expect(getSearchResultUrl(result, true)).toBeNull();
+ });
+
+ it("returns null when the parent record of a note or task is missing", () => {
+ expect(
+ getSearchResultUrl(
+ {
+ resource: "tasks",
+ record_id: 11,
+ contact_id: null,
+ deal_id: null,
+ },
+ false,
+ ),
+ ).toBeNull();
+ expect(
+ getSearchResultUrl(
+ {
+ resource: "contact_notes",
+ record_id: 12,
+ contact_id: null,
+ deal_id: null,
+ },
+ false,
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/src/components/atomic-crm/search/getSearchResultUrl.ts b/src/components/atomic-crm/search/getSearchResultUrl.ts
new file mode 100644
index 00000000..1f50585f
--- /dev/null
+++ b/src/components/atomic-crm/search/getSearchResultUrl.ts
@@ -0,0 +1,43 @@
+import type { SearchResult } from "../types";
+
+type LinkableResult = Pick<
+ SearchResult,
+ "resource" | "record_id" | "contact_id" | "deal_id"
+>;
+
+/**
+ * Resolve the in-app URL for a global search result.
+ *
+ * Returns null when the result has no reachable page on the current layout:
+ * the mobile app registers no deal resource, and a note or task whose parent
+ * record is missing cannot be linked.
+ */
+export const getSearchResultUrl = (
+ result: LinkableResult,
+ isMobile: boolean,
+): string | null => {
+ switch (result.resource) {
+ case "companies":
+ return `/companies/${result.record_id}/show`;
+ case "contacts":
+ return `/contacts/${result.record_id}/show`;
+ case "deals":
+ return isMobile ? null : `/deals/${result.record_id}/show`;
+ case "tasks":
+ // Tasks have no page of their own: link to the contact they belong to.
+ return result.contact_id ? `/contacts/${result.contact_id}/show` : null;
+ case "contact_notes":
+ if (!result.contact_id) {
+ return null;
+ }
+ return isMobile
+ ? `/contacts/${result.contact_id}/notes/${result.record_id}`
+ : `/contacts/${result.contact_id}/show`;
+ case "deal_notes":
+ return isMobile || !result.deal_id
+ ? null
+ : `/deals/${result.deal_id}/show`;
+ default:
+ return null;
+ }
+};
diff --git a/src/components/atomic-crm/search/index.ts b/src/components/atomic-crm/search/index.ts
new file mode 100644
index 00000000..4c8e2d33
--- /dev/null
+++ b/src/components/atomic-crm/search/index.ts
@@ -0,0 +1,4 @@
+export { GlobalSearchButton } from "./GlobalSearchButton";
+export { GlobalSearchDialog } from "./GlobalSearchDialog";
+export { getSearchResultUrl } from "./getSearchResultUrl";
+export { MIN_SEARCH_LENGTH } from "./useGlobalSearch";
diff --git a/src/components/atomic-crm/search/searchResources.ts b/src/components/atomic-crm/search/searchResources.ts
new file mode 100644
index 00000000..c23d365c
--- /dev/null
+++ b/src/components/atomic-crm/search/searchResources.ts
@@ -0,0 +1,32 @@
+import { Building2, DollarSign, FileText, ListTodo, User } from "lucide-react";
+import type { ComponentType } from "react";
+
+import type { SearchResourceName } from "../types";
+
+export type SearchResourceDescriptor = {
+ name: SearchResourceName;
+ icon: ComponentType<{ className?: string }>;
+ labelKey: string;
+};
+
+/** Result groups, in the order they appear in the search dialog. */
+export const SEARCH_RESOURCES: SearchResourceDescriptor[] = [
+ { name: "contacts", icon: User, labelKey: "crm.search.groups.contacts" },
+ {
+ name: "companies",
+ icon: Building2,
+ labelKey: "crm.search.groups.companies",
+ },
+ { name: "deals", icon: DollarSign, labelKey: "crm.search.groups.deals" },
+ { name: "tasks", icon: ListTodo, labelKey: "crm.search.groups.tasks" },
+ {
+ name: "contact_notes",
+ icon: FileText,
+ labelKey: "crm.search.groups.contact_notes",
+ },
+ {
+ name: "deal_notes",
+ icon: FileText,
+ labelKey: "crm.search.groups.deal_notes",
+ },
+];
diff --git a/src/components/atomic-crm/search/useGlobalSearch.ts b/src/components/atomic-crm/search/useGlobalSearch.ts
new file mode 100644
index 00000000..be987b49
--- /dev/null
+++ b/src/components/atomic-crm/search/useGlobalSearch.ts
@@ -0,0 +1,47 @@
+import { useGetList } from "ra-core";
+import { useEffect, useState } from "react";
+
+import type { SearchResult } from "../types";
+
+export const MIN_SEARCH_LENGTH = 2;
+const DEBOUNCE_MS = 300;
+const MAX_RESULTS = 50;
+
+export const useDebouncedValue = <T>(value: T, delay: number): T => {
+ const [debouncedValue, setDebouncedValue] = useState(value);
+
+ useEffect(() => {
+ const timeout = setTimeout(() => setDebouncedValue(value), delay);
+ return () => clearTimeout(timeout);
+ }, [value, delay]);
+
+ return debouncedValue;
+};
+
+/**
+ * Query the `search_index` view for a debounced search term.
+ *
+ * Stays idle until the term reaches MIN_SEARCH_LENGTH, so opening the dialog
+ * does not fire a request.
+ */
+export const useGlobalSearch = (query: string) => {
+ const debouncedQuery = useDebouncedValue(query.trim(), DEBOUNCE_MS);
+ const isEnabled = debouncedQuery.length >= MIN_SEARCH_LENGTH;
+
+ const { data, isPending, error } = useGetList<SearchResult>(
+ "search_index",
+ {
+ filter: { q: debouncedQuery },
+ pagination: { page: 1, perPage: MAX_RESULTS },
+ sort: { field: "date", order: "DESC" },
+ },
+ { enabled: isEnabled },
+ );
+
+ return {
+ results: isEnabled ? (data ?? []) : [],
+ isPending: isEnabled && isPending,
+ error,
+ debouncedQuery,
+ };
+};
diff --git a/src/components/atomic-crm/types.ts b/src/components/atomic-crm/types.ts
index 6d1d6ff6..efb9b41d 100644
--- a/src/components/atomic-crm/types.ts
+++ b/src/components/atomic-crm/types.ts
@@ -226,3 +226,24 @@ export interface ContactGender {
label: string;
icon: ComponentType<{ className?: string }>;
}
+
+export type SearchResourceName =
+ | "companies"
+ | "contacts"
+ | "deals"
+ | "tasks"
+ | "contact_notes"
+ | "deal_notes";
+
+export type SearchResult = {
+ id: Identifier;
+ resource: SearchResourceName;
+ record_id: Identifier;
+ title: string | null;
+ subtitle: string | null;
+ content: string | null;
+ company_id: Identifier | null;
+ contact_id: Identifier | null;
+ deal_id: Identifier | null;
+ date: string | null;
+};
diff --git a/src/components/ui/command.tsx b/src/components/ui/command.tsx
index 5360f6db..066c9fad 100644
--- a/src/components/ui/command.tsx
+++ b/src/components/ui/command.tsx
@@ -30,11 +30,13 @@ function Command({
function CommandDialog({
title = "Command Palette",
description = "Search for a command to run...",
+ shouldFilter,
children,
...props
}: React.ComponentProps<typeof Dialog> & {
title?: string
description?: string
+ shouldFilter?: boolean
}) {
return (
<Dialog {...props}>
@@ -43,7 +45,10 @@ function CommandDialog({
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<DialogContent className="overflow-hidden p-0">
- <Command className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
+ <Command
+ shouldFilter={shouldFilter}
+ className="[&_[cmdk-group-heading]]:text-muted-foreground **:data-[slot=command-input-wrapper]:h-12 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group]]:px-2 [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5"
+ >
{children}
</Command>
</DialogContent>
diff --git a/supabase/migrations/20260907120000_search_index_view.sql b/supabase/migrations/20260907120000_search_index_view.sql
new file mode 100644
index 00000000..4ff96292
--- /dev/null
+++ b/supabase/migrations/20260907120000_search_index_view.sql
@@ -0,0 +1,104 @@
+create or replace view public.search_index with (security_invoker = on) as
+select
+ ('company.' || c.id) as id,
+ 'companies' as resource,
+ c.id as record_id,
+ c.name as title,
+ c.sector as subtitle,
+ concat_ws(' ', c.name, c.description, c.website, c.city) as content,
+ c.id as company_id,
+ null::bigint as contact_id,
+ null::bigint as deal_id,
+ c.created_at as date
+from public.companies c
+union all
+select
+ ('contact.' || co.id) as id,
+ 'contacts' as resource,
+ co.id as record_id,
+ concat_ws(' ', co.first_name, co.last_name) as title,
+ cc.name as subtitle,
+ concat_ws(
+ ' ',
+ co.first_name,
+ co.last_name,
+ co.title,
+ cc.name,
+ (jsonb_path_query_array(co.email_jsonb, '$[*]."email"'))::text,
+ (jsonb_path_query_array(co.phone_jsonb, '$[*]."number"'))::text
+ ) as content,
+ co.company_id,
+ co.id as contact_id,
+ null::bigint as deal_id,
+ co.first_seen as date
+from public.contacts co
+ left join public.companies cc on cc.id = co.company_id
+union all
+select
+ ('deal.' || d.id) as id,
+ 'deals' as resource,
+ d.id as record_id,
+ d.name as title,
+ dc.name as subtitle,
+ concat_ws(' ', d.name, d.description, dc.name) as content,
+ d.company_id,
+ null::bigint as contact_id,
+ d.id as deal_id,
+ d.created_at as date
+from public.deals d
+ left join public.companies dc on dc.id = d.company_id
+where d.archived_at is null
+union all
+select
+ ('task.' || t.id) as id,
+ 'tasks' as resource,
+ t.id as record_id,
+ t.text as title,
+ concat_ws(' ', tco.first_name, tco.last_name) as subtitle,
+ concat_ws(' ', t.text, t.type) as content,
+ tco.company_id,
+ t.contact_id,
+ null::bigint as deal_id,
+ t.due_date as date
+from public.tasks t
+ left join public.contacts tco on tco.id = t.contact_id
+union all
+select
+ ('contactNote.' || cn.id) as id,
+ 'contact_notes' as resource,
+ cn.id as record_id,
+ cn.text as title,
+ concat_ws(' ', nco.first_name, nco.last_name) as subtitle,
+ concat_ws(
+ ' ',
+ cn.text,
+ (select string_agg(a ->> 'title', ' ') from unnest(cn.attachments) as a)
+ ) as content,
+ nco.company_id,
+ cn.contact_id,
+ null::bigint as deal_id,
+ cn.date
+from public.contact_notes cn
+ left join public.contacts nco on nco.id = cn.contact_id
+union all
+select
+ ('dealNote.' || dn.id) as id,
+ 'deal_notes' as resource,
+ dn.id as record_id,
+ dn.text as title,
+ nd.name as subtitle,
+ concat_ws(
+ ' ',
+ dn.text,
+ (select string_agg(a ->> 'title', ' ') from unnest(dn.attachments) as a)
+ ) as content,
+ nd.company_id,
+ null::bigint as contact_id,
+ dn.deal_id,
+ dn.date
+from public.deal_notes dn
+ left join public.deals nd on nd.id = dn.deal_id;
+
+grant all on table public.search_index to anon;
+grant all on table public.search_index to authenticated;
+grant all on table public.search_index to service_role;
diff --git a/supabase/schemas/03_views.sql b/supabase/schemas/03_views.sql
index 1b2ec74f..42913279 100644
--- a/supabase/schemas/03_views.sql
+++ b/supabase/schemas/03_views.sql
@@ -132,3 +132,104 @@ select count(sub.id) as is_initialized
from (
select sales.id from public.sales limit 1
) sub;
+
+create or replace view public.search_index with (security_invoker = on) as
+select
+ ('company.' || c.id) as id,
+ 'companies' as resource,
+ c.id as record_id,
+ c.name as title,
+ c.sector as subtitle,
+ concat_ws(' ', c.name, c.description, c.website, c.city) as content,
+ c.id as company_id,
+ null::bigint as contact_id,
+ null::bigint as deal_id,
+ c.created_at as date
+from public.companies c
+union all
+select
+ ('contact.' || co.id) as id,
+ 'contacts' as resource,
+ co.id as record_id,
+ concat_ws(' ', co.first_name, co.last_name) as title,
+ cc.name as subtitle,
+ concat_ws(
+ ' ',
+ co.first_name,
+ co.last_name,
+ co.title,
+ cc.name,
+ (jsonb_path_query_array(co.email_jsonb, '$[*]."email"'))::text,
+ (jsonb_path_query_array(co.phone_jsonb, '$[*]."number"'))::text
+ ) as content,
+ co.company_id,
+ co.id as contact_id,
+ null::bigint as deal_id,
+ co.first_seen as date
+from public.contacts co
+ left join public.companies cc on cc.id = co.company_id
+union all
+select
+ ('deal.' || d.id) as id,
+ 'deals' as resource,
+ d.id as record_id,
+ d.name as title,
+ dc.name as subtitle,
+ concat_ws(' ', d.name, d.description, dc.name) as content,
+ d.company_id,
+ null::bigint as contact_id,
+ d.id as deal_id,
+ d.created_at as date
+from public.deals d
+ left join public.companies dc on dc.id = d.company_id
+where d.archived_at is null
+union all
+select
+ ('task.' || t.id) as id,
+ 'tasks' as resource,
+ t.id as record_id,
+ t.text as title,
+ concat_ws(' ', tco.first_name, tco.last_name) as subtitle,
+ concat_ws(' ', t.text, t.type) as content,
+ tco.company_id,
+ t.contact_id,
+ null::bigint as deal_id,
+ t.due_date as date
+from public.tasks t
+ left join public.contacts tco on tco.id = t.contact_id
+union all
+select
+ ('contactNote.' || cn.id) as id,
+ 'contact_notes' as resource,
+ cn.id as record_id,
+ cn.text as title,
+ concat_ws(' ', nco.first_name, nco.last_name) as subtitle,
+ concat_ws(
+ ' ',
+ cn.text,
+ (select string_agg(a ->> 'title', ' ') from unnest(cn.attachments) as a)
+ ) as content,
+ nco.company_id,
+ cn.contact_id,
+ null::bigint as deal_id,
+ cn.date
+from public.contact_notes cn
+ left join public.contacts nco on nco.id = cn.contact_id
+union all
+select
+ ('dealNote.' || dn.id) as id,
+ 'deal_notes' as resource,
+ dn.id as record_id,
+ dn.text as title,
+ nd.name as subtitle,
+ concat_ws(
+ ' ',
+ dn.text,
+ (select string_agg(a ->> 'title', ' ') from unnest(dn.attachments) as a)
+ ) as content,
+ nd.company_id,
+ null::bigint as contact_id,
+ dn.deal_id,
+ dn.date
+from public.deal_notes dn
+ left join public.deals nd on nd.id = dn.deal_id;
diff --git a/supabase/schemas/06_grants.sql b/supabase/schemas/06_grants.sql
index 865c9dbc..7d2f7aac 100644
--- a/supabase/schemas/06_grants.sql
+++ b/supabase/schemas/06_grants.sql
@@ -123,6 +123,10 @@ grant all on table public.init_state to anon;
grant all on table public.init_state to authenticated;
grant all on table public.init_state to service_role;
+grant all on table public.search_index to anon;
+grant all on table public.search_index to authenticated;
+grant all on table public.search_index to service_role;
+
-- Sequence grants
grant all on sequence public.companies_id_seq to anon;
grant all on sequence public.companies_id_seq to authenticated;