Skip to content

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

fix(search): address review feedback on global search

erwanMarmelaba493ed79da30
diff --git a/doc/astro.config.mjs b/doc/astro.config.mjs
index 2b9ae489..8684488e 100644
--- a/doc/astro.config.mjs
+++ b/doc/astro.config.mjs
@@ -86,6 +86,7 @@ export default defineConfig({
items: [
"users/user-management",
"users/settings",
+ "users/global-search",
"users/import-data",
"users/merging-contacts",
"users/inbound-email",
diff --git a/doc/src/content/docs/users/global-search.mdx b/doc/src/content/docs/users/global-search.mdx
new file mode 100644
index 00000000..9fb56f07
--- /dev/null
+++ b/doc/src/content/docs/users/global-search.mdx
@@ -0,0 +1,43 @@
+---
+title: Global Search
+---
+
+Global search looks across every record type at once, so you can find a note by
+a phrase you remember without knowing which contact it belongs to.
+
+## Opening the search
+
+On desktop, click the magnifier in the top bar, or press **Ctrl+K**
+(**Cmd+K** on macOS) from anywhere in the app. The shortcut is ignored while you
+are typing in a field, so it never interrupts a note you are writing.
+
+On mobile, tap the magnifier in the header. It is available on every screen.
+
+## What is searched
+
+| Record | Searched fields |
+| ------------------------ | ------------------------------------------------------------------------ |
+| Companies | name, sector, description, website, phone, zip code, city, state |
+| Contacts | first and last name, job title, background, company name, emails, phones |
+| Deals | name, category, description, company name |
+| Tasks | text, type, contact name |
+| Notes (contact and deal) | note text, attachment file names, parent contact or deal name |
+
+Archived deals and completed tasks are left out, along with notes attached to an
+archived deal.
+
+## Searching with several words
+
+Every word must appear somewhere in the same record. Searching
+`sourdough Anderson` returns the notes about sourdough written on Thomas
+Anderson, and not the ones written on anybody else — the parent contact's name
+counts as part of the note.
+
+## Good to know
+
+- Search starts at **2 characters**.
+- Results are capped at **50**, most recent first, with no pagination. Add a
+ word to narrow them down rather than scrolling.
+- Deals and deal notes do not appear on mobile, which has no deal screen to open.
+- The page-specific searches (the search box on the Contacts page, and so on)
+ are unchanged and still filter their own list.
diff --git a/src/components/atomic-crm/dashboard/MobileDashboard.tsx b/src/components/atomic-crm/dashboard/MobileDashboard.tsx
index 3f1c517e..faf77a1a 100644
--- a/src/components/atomic-crm/dashboard/MobileDashboard.tsx
+++ b/src/components/atomic-crm/dashboard/MobileDashboard.tsx
@@ -8,7 +8,6 @@ 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();
@@ -28,7 +27,6 @@ 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/MobileHeader.tsx b/src/components/atomic-crm/layout/MobileHeader.tsx
index e300584f..03e40bfa 100644
--- a/src/components/atomic-crm/layout/MobileHeader.tsx
+++ b/src/components/atomic-crm/layout/MobileHeader.tsx
@@ -1,7 +1,10 @@
+import { GlobalSearchButton } from "../search";
+
const MobileHeader = ({ children }: { children: React.ReactNode }) => {
return (
<header className="fixed top-0 left-0 right-0 z-10 bg-secondary h-14 px-4 w-full flex justify-between items-center">
{children}
+ <GlobalSearchButton variant="icon" />
</header>
);
};
diff --git a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
index def2c5f5..b84d8589 100644
--- a/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/englishCrmMessages.ts
@@ -446,6 +446,7 @@ export const englishCrmMessages = {
placeholder: "Search contacts, companies, deals, tasks and notes...",
hint: "Type at least %{min} characters to search",
empty: "No result found",
+ error: "Search is unavailable right now. Please try again.",
untitled_result: "(no title)",
groups: {
contacts: "Contacts",
diff --git a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
index 4aa30ef0..0085f778 100644
--- a/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
+++ b/src/components/atomic-crm/providers/commons/frenchCrmMessages.ts
@@ -454,6 +454,8 @@ export const frenchCrmMessages = {
"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",
+ error:
+ "La recherche est indisponible pour le moment. Veuillez réessayer.",
untitled_result: "(sans titre)",
groups: {
contacts: "Contacts",
diff --git a/src/components/atomic-crm/providers/commons/search.ts b/src/components/atomic-crm/providers/commons/search.ts
index 983e78d8..bb2a4654 100644
--- a/src/components/atomic-crm/providers/commons/search.ts
+++ b/src/components/atomic-crm/providers/commons/search.ts
@@ -6,9 +6,11 @@ import type {
ContactNote,
Deal,
DealNote,
+ SearchResourceName,
SearchResult,
Task,
} from "../../types";
+import { DESKTOP_SEARCH_RESOURCES } from "../../search/searchResources";
const PER_RESOURCE_LIMIT = 50;
const MAX_RESULTS = 250;
@@ -18,9 +20,10 @@ const searchResource = async <T>(
resource: string,
q: string,
sortField: string,
+ extraFilter: Record<string, unknown> = {},
): Promise<T[]> => {
const { data } = await dataProvider.getList<any>(resource, {
- filter: { q },
+ filter: { q, ...extraFilter },
pagination: { page: 1, perPage: PER_RESOURCE_LIMIT },
sort: { field: sortField, order: "DESC" },
});
@@ -54,13 +57,18 @@ const byDateDesc = (a: SearchResult, b: SearchResult) =>
* 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.
+ * FIXME: this is an approximation of the view, not a reimplementation.
+ * - one query per resource instead of one;
+ * - FakeRest matches the whole term as a single substring, where Postgres ANDs
+ * one `ilike` per word;
+ * - the result SET differs, not only the field values: this path takes the top
+ * 50 per resource and caps at 250, while Supabase takes one global top 50, so
+ * the demo build can surface a record production would not return.
*/
export async function getSearchResults(
dataProvider: DataProvider,
query: string,
+ resources: SearchResourceName[] = [...DESKTOP_SEARCH_RESOURCES],
): Promise<SearchResult[]> {
const q = query.trim();
if (!q) {
@@ -70,14 +78,18 @@ export async function getSearchResults(
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<Contact>(dataProvider, "contacts", q, "first_seen"),
+ searchResource<Deal>(dataProvider, "deals", q, "created_at", {
+ "archived_at@is": null,
+ }),
+ searchResource<Task>(dataProvider, "tasks", q, "created_at", {
+ "done_date@is": null,
+ }),
searchResource<ContactNote>(dataProvider, "contact_notes", q, "date"),
searchResource<DealNote>(dataProvider, "deal_notes", q, "date"),
]);
- const [contactLabels, dealLabels] = await Promise.all([
+ const [contactLabels, dealLabels, companyLabels] = await Promise.all([
getLabels<Contact>(
dataProvider,
"contacts",
@@ -93,6 +105,12 @@ export async function getSearchResults(
dealNotes.map((note) => note.deal_id),
(deal) => deal.name,
),
+ getLabels<Company>(
+ dataProvider,
+ "companies",
+ deals.map((deal) => deal.company_id),
+ (company) => company.name,
+ ),
]);
const rows: SearchResult[] = [
@@ -102,8 +120,6 @@ export async function getSearchResults(
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,
@@ -114,37 +130,31 @@ export async function getSearchResults(
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,
- })),
+ ...deals.map((deal) => ({
+ id: `deal.${deal.id}`,
+ resource: "deals" as const,
+ record_id: deal.id,
+ title: deal.name,
+ subtitle: deal.company_id
+ ? (companyLabels.get(deal.company_id) ?? null)
+ : 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,
+ date: task.created_at ?? null,
})),
...contactNotes.map((note) => ({
id: `contactNote.${note.id}`,
@@ -152,8 +162,6 @@ export async function getSearchResults(
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,
@@ -164,13 +172,14 @@ export async function getSearchResults(
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);
+ return rows
+ .filter((row) => resources.includes(row.resource))
+ .sort(byDateDesc)
+ .slice(0, MAX_RESULTS);
}
diff --git a/src/components/atomic-crm/providers/fakerest/dataGenerator/tasks.ts b/src/components/atomic-crm/providers/fakerest/dataGenerator/tasks.ts
index f5a50fe4..539a94f6 100644
--- a/src/components/atomic-crm/providers/fakerest/dataGenerator/tasks.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataGenerator/tasks.ts
@@ -48,6 +48,7 @@ export const generateTasks = (db: Db) => {
).toISOString(),
done_date: undefined,
sales_id: 0,
+ created_at: randomDate(new Date(contact.first_seen)).toISOString(),
};
});
};
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
index f23c4464..898b133f 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
@@ -16,6 +16,7 @@ import type {
DealNote,
Sale,
SalesFormData,
+ SearchResourceName,
SignUpData,
Task,
} from "../../types";
@@ -140,6 +141,11 @@ const preserveAttachmentMimeType = <
})),
});
+const parseResourceFilter = (
+ value: unknown,
+): SearchResourceName[] | undefined =>
+ Array.isArray(value) ? (value as SearchResourceName[]) : undefined;
+
export const createDataProvider = ({
db = generateData(),
latency = 300,
@@ -173,7 +179,11 @@ export const createDataProvider = ({
async getList(resource: string, params: any) {
if (resource === "search_index") {
const { filter = {}, pagination } = params;
- const all = await getSearchResults(baseDataProvider, filter.q ?? "");
+ const all = await getSearchResults(
+ withSupabaseFilterAdapter(baseDataProvider),
+ filter.q ?? "",
+ parseResourceFilter(filter.resource_eq_any),
+ );
const { page, perPage } = pagination;
const start = (page - 1) * perPage;
return { data: all.slice(start, start + perPage), total: all.length };
diff --git a/src/components/atomic-crm/providers/fakerest/internal/listParser.ts b/src/components/atomic-crm/providers/fakerest/internal/listParser.ts
index c2c3ca99..26b53986 100644
--- a/src/components/atomic-crm/providers/fakerest/internal/listParser.ts
+++ b/src/components/atomic-crm/providers/fakerest/internal/listParser.ts
@@ -1,5 +1,5 @@
-export const UNQUOTED_ALLOWED_CHARS = "[A-Za-zÀ-ÖØ-öø-ÿ0-9-]+";
-export const QUOTED_ALLOWED_CHARS = "[A-Za-zÀ-ÖØ-öø-ÿ0-9, -]+";
+export const UNQUOTED_ALLOWED_CHARS = "[A-Za-zÀ-ÖØ-öø-ÿ0-9_-]+";
+export const QUOTED_ALLOWED_CHARS = "[A-Za-zÀ-ÖØ-öø-ÿ0-9_, -]+";
export const LIST_REGEX_BASE = `(${UNQUOTED_ALLOWED_CHARS}|"${QUOTED_ALLOWED_CHARS}")(,(${UNQUOTED_ALLOWED_CHARS}|"${QUOTED_ALLOWED_CHARS}"))*`;
/**
diff --git a/src/components/atomic-crm/providers/supabase/dataProvider.ts b/src/components/atomic-crm/providers/supabase/dataProvider.ts
index e0e34f07..92caed48 100644
--- a/src/components/atomic-crm/providers/supabase/dataProvider.ts
+++ b/src/components/atomic-crm/providers/supabase/dataProvider.ts
@@ -361,8 +361,10 @@ const lifeCycleCallbacks: ResourceCallbacks[] = [
}
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.
+ // and emits one `ilike` per word. qs.stringify uses the indices format,
+ // so the query string carries `content[0]=ilike.*a*&content[1]=ilike.*b*`;
+ // PostgREST strips the `[n]` subscripts and ANDs the repeated column, so
+ // "Thomas TF1" matches only rows whose content contains both words.
return {
...params,
filter: {
diff --git a/src/components/atomic-crm/search/GlobalSearchButton.tsx b/src/components/atomic-crm/search/GlobalSearchButton.tsx
index 79032ce6..1266b1a1 100644
--- a/src/components/atomic-crm/search/GlobalSearchButton.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchButton.tsx
@@ -6,6 +6,18 @@ import { Button } from "@/components/ui/button";
import { GlobalSearchDialog } from "./GlobalSearchDialog";
+const isEditableTarget = (target: EventTarget | null): boolean => {
+ if (!(target instanceof HTMLElement)) {
+ return false;
+ }
+ return (
+ target.isContentEditable ||
+ target.tagName === "INPUT" ||
+ target.tagName === "TEXTAREA" ||
+ target.tagName === "SELECT"
+ );
+};
+
/**
* Opens the global search dialog. `variant="icon"` renders the compact
* icon-only trigger used on mobile; the default renders a labelled trigger for
@@ -21,10 +33,14 @@ export const GlobalSearchButton = ({
useEffect(() => {
const onKeyDown = (event: KeyboardEvent) => {
- if (event.key === "k" && (event.metaKey || event.ctrlKey)) {
- event.preventDefault();
- setOpen((previousOpen) => !previousOpen);
+ if (event.key !== "k" || !(event.metaKey || event.ctrlKey)) {
+ return;
+ }
+ if (isEditableTarget(event.target)) {
+ return;
}
+ event.preventDefault();
+ setOpen(true);
};
document.addEventListener("keydown", onKeyDown);
return () => document.removeEventListener("keydown", onKeyDown);
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx b/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
index e680a702..bca8f132 100644
--- a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
@@ -1,4 +1,5 @@
-import { describe, expect, it } from "vitest";
+import { page } from "vitest/browser";
+import { beforeEach, describe, expect, it } from "vitest";
import { render } from "vitest-browser-react";
import { StoryWrapper, buildContact } from "@/test/StoryWrapper";
@@ -25,6 +26,45 @@ const data = {
text: "Called about the sourdough contract",
},
],
+ deals: [
+ {
+ company_id: 1,
+ created_at: "2025-01-05T10:00:00.000Z",
+ description: "sourdough supply",
+ id: 1,
+ name: "Live sourdough deal",
+ stage: "opportunity",
+ },
+ {
+ archived_at: "2025-01-20T10:00:00.000Z",
+ company_id: 1,
+ created_at: "2025-01-06T10:00:00.000Z",
+ id: 2,
+ name: "Archived sourdough deal",
+ stage: "lost",
+ },
+ ],
+ tasks: [
+ {
+ contact_id: 1,
+ created_at: "2025-01-10T10:00:00.000Z",
+ due_date: "2027-01-01T10:00:00.000Z",
+ id: 1,
+ sales_id: 0,
+ text: "Chase the sourdough quote",
+ type: "Call",
+ },
+ {
+ contact_id: 1,
+ created_at: "2025-01-11T10:00:00.000Z",
+ done_date: "2025-01-12T10:00:00.000Z",
+ due_date: "2025-01-15T10:00:00.000Z",
+ id: 2,
+ sales_id: 0,
+ text: "Finished sourdough task",
+ type: "Call",
+ },
+ ],
} as any;
const renderDialog = (open = true) =>
@@ -35,6 +75,12 @@ const renderDialog = (open = true) =>
);
describe("GlobalSearchDialog", () => {
+ // The dialog reads useIsMobile, and the layouts expose different resources,
+ // so the viewport is part of the arrangement in every test below.
+ beforeEach(() => {
+ page.viewport(1600, 900);
+ });
+
it("puts nothing in the document while closed", async () => {
const screen = await renderDialog(false);
@@ -100,7 +146,57 @@ describe("GlobalSearchDialog", () => {
await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough");
- await expect.element(screen.getByText("Ada Lovelace")).toBeVisible();
+ await expect
+ .element(
+ screen
+ .getByRole("group", { name: "Contact notes" })
+ .getByText("Ada Lovelace"),
+ )
+ .toBeVisible();
+ });
+
+ it("matches a note word together with its contact's name", async () => {
+ const screen = await renderDialog();
+
+ // The reason `content` carries the subtitle: each word is ANDed, so the
+ // parent name has to be searchable on the note's own row.
+ await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough Lovelace");
+
+ await expect
+ .element(
+ screen
+ .getByRole("group", { name: "Contact notes" })
+ .getByText("Called about the sourdough contract"),
+ )
+ .toBeVisible();
+ });
+
+ it("shows the deal's company as its subtitle", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough");
+
+ await expect
+ .element(
+ screen
+ .getByRole("group", { name: "Deals" })
+ .getByText("Boulangerie Martin"),
+ )
+ .toBeVisible();
+ });
+
+ it("hides archived deals and completed tasks", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough");
+
+ await expect.element(screen.getByText("Live sourdough deal")).toBeVisible();
+ await expect
+ .element(screen.getByText("Archived sourdough deal"))
+ .not.toBeInTheDocument();
+ await expect
+ .element(screen.getByText("Finished sourdough task"))
+ .not.toBeInTheDocument();
});
it("reports when nothing matches", async () => {
@@ -111,3 +207,37 @@ describe("GlobalSearchDialog", () => {
await expect.element(screen.getByText("No result found")).toBeVisible();
});
});
+
+describe("GlobalSearchDialog on mobile", () => {
+ beforeEach(() => {
+ page.viewport(375, 667);
+ });
+
+ it("omits deals, which have no page on the mobile layout", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough");
+
+ // The note matches too, so a visible result proves the query ran.
+ await expect
+ .element(screen.getByText("Called about the sourdough contract"))
+ .toBeVisible();
+ await expect
+ .element(screen.getByText("Live sourdough deal"))
+ .not.toBeInTheDocument();
+ });
+
+ it("still finds tasks, which link to their contact", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("sourdough");
+
+ await expect
+ .element(
+ screen
+ .getByRole("group", { name: "Tasks" })
+ .getByText("Chase the sourdough quote"),
+ )
+ .toBeVisible();
+ });
+});
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.tsx b/src/components/atomic-crm/search/GlobalSearchDialog.tsx
index 96c47a57..6ca5b4cd 100644
--- a/src/components/atomic-crm/search/GlobalSearchDialog.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchDialog.tsx
@@ -14,7 +14,11 @@ import { useIsMobile } from "@/hooks/use-mobile";
import type { SearchResult } from "../types";
import { getSearchResultUrl } from "./getSearchResultUrl";
-import { SEARCH_RESOURCES } from "./searchResources";
+import {
+ DESKTOP_SEARCH_RESOURCES,
+ MOBILE_SEARCH_RESOURCES,
+ SEARCH_RESOURCES,
+} from "./searchResources";
import { MIN_SEARCH_LENGTH, useGlobalSearch } from "./useGlobalSearch";
type LinkedResult = { result: SearchResult; url: string };
@@ -30,10 +34,13 @@ export const GlobalSearchDialog = ({
const navigate = useNavigate();
const isMobile = useIsMobile();
const [query, setQuery] = useState("");
- const { results, isPending, debouncedQuery } = useGlobalSearch(query);
+ const { results, isPending, error, debouncedQuery } = useGlobalSearch(
+ query,
+ isMobile ? MOBILE_SEARCH_RESOURCES : DESKTOP_SEARCH_RESOURCES,
+ );
- // Results whose resource has no page on this layout are dropped rather than
- // rendered as dead entries.
+ // Resources are already scoped to this layout server-side; this only drops
+ // the rare row whose parent record is missing.
const linkedResults = useMemo(
() =>
results.reduce<LinkedResult[]>((acc, result) => {
@@ -75,6 +82,13 @@ export const GlobalSearchDialog = ({
<div className="py-6 text-center text-sm text-muted-foreground">
{translate("crm.search.hint", { min: MIN_SEARCH_LENGTH })}
</div>
+ ) : error ? (
+ <div
+ role="alert"
+ className="py-6 text-center text-sm text-destructive"
+ >
+ {translate("crm.search.error")}
+ </div>
) : isPending ? (
<div className="py-6 text-center text-sm text-muted-foreground">
{translate("crm.common.loading")}
diff --git a/src/components/atomic-crm/search/searchResources.ts b/src/components/atomic-crm/search/searchResources.ts
index c23d365c..da192452 100644
--- a/src/components/atomic-crm/search/searchResources.ts
+++ b/src/components/atomic-crm/search/searchResources.ts
@@ -30,3 +30,11 @@ export const SEARCH_RESOURCES: SearchResourceDescriptor[] = [
labelKey: "crm.search.groups.deal_notes",
},
];
+
+export const DESKTOP_SEARCH_RESOURCES: SearchResourceName[] =
+ SEARCH_RESOURCES.map(({ name }) => name);
+
+export const MOBILE_SEARCH_RESOURCES: SearchResourceName[] =
+ DESKTOP_SEARCH_RESOURCES.filter(
+ (name) => name !== "deals" && name !== "deal_notes",
+ );
diff --git a/src/components/atomic-crm/search/useGlobalSearch.ts b/src/components/atomic-crm/search/useGlobalSearch.ts
index be987b49..c36024cb 100644
--- a/src/components/atomic-crm/search/useGlobalSearch.ts
+++ b/src/components/atomic-crm/search/useGlobalSearch.ts
@@ -1,12 +1,22 @@
import { useGetList } from "ra-core";
import { useEffect, useState } from "react";
-import type { SearchResult } from "../types";
+import type { SearchResourceName, SearchResult } from "../types";
export const MIN_SEARCH_LENGTH = 2;
const DEBOUNCE_MS = 300;
const MAX_RESULTS = 50;
+const DISPLAYED_COLUMNS = [
+ "id",
+ "resource",
+ "record_id",
+ "title",
+ "subtitle",
+ "contact_id",
+ "deal_id",
+] as const;
+
export const useDebouncedValue = <T>(value: T, delay: number): T => {
const [debouncedValue, setDebouncedValue] = useState(value);
@@ -22,18 +32,26 @@ export const useDebouncedValue = <T>(value: T, delay: number): T => {
* 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.
+ * does not fire a request. `resources` restricts the query server-side, so the
+ * row cap is spent only on resources the current layout can actually link to.
*/
-export const useGlobalSearch = (query: string) => {
+export const useGlobalSearch = (
+ query: string,
+ resources: readonly SearchResourceName[],
+) => {
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 },
+ filter: {
+ q: debouncedQuery,
+ "resource@in": `(${resources.join(",")})`,
+ },
pagination: { page: 1, perPage: MAX_RESULTS },
sort: { field: "date", order: "DESC" },
+ meta: { columns: [...DISPLAYED_COLUMNS] },
},
{ enabled: isEnabled },
);
diff --git a/src/components/atomic-crm/types.ts b/src/components/atomic-crm/types.ts
index efb9b41d..2ed27154 100644
--- a/src/components/atomic-crm/types.ts
+++ b/src/components/atomic-crm/types.ts
@@ -151,6 +151,7 @@ export type Task = {
due_date: string;
done_date?: string | null;
sales_id?: Identifier;
+ created_at?: string;
} & Pick<RaRecord, "id">;
export type ActivityCompanyCreated = {
@@ -241,8 +242,6 @@ export type SearchResult = {
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/supabase/migrations/20260910132555_global_search_review_fixes.sql b/supabase/migrations/20260910132555_global_search_review_fixes.sql
new file mode 100644
index 00000000..d577241b
--- /dev/null
+++ b/supabase/migrations/20260910132555_global_search_review_fixes.sql
@@ -0,0 +1,85 @@
+drop view if exists "public"."search_index";
+
+alter table "public"."tasks" add column "created_at" timestamp with time zone not null default now();
+
+update "public"."tasks" set "created_at" = coalesce("done_date", "due_date", "created_at");
+
+create or replace view "public"."search_index" with (security_invoker = on) as SELECT ('company.'::text || c.id) AS id,
+ 'companies'::text AS resource,
+ c.id AS record_id,
+ c.name AS title,
+ c.sector AS subtitle,
+ concat_ws(' '::text, c.name, c.sector, c.description, c.website, c.phone_number, c.zipcode, c.city, c.state_abbr) AS content,
+ NULL::bigint AS contact_id,
+ NULL::bigint AS deal_id,
+ c.created_at AS date
+ FROM public.companies c
+UNION ALL
+ SELECT ('contact.'::text || co.id) AS id,
+ 'contacts'::text AS resource,
+ co.id AS record_id,
+ concat_ws(' '::text, co.first_name, co.last_name) AS title,
+ cc.name AS subtitle,
+ concat_ws(' '::text, co.first_name, co.last_name, co.title, co.background, cc.name, (jsonb_path_query_array(co.email_jsonb, '$[*]."email"'::jsonpath))::text, (jsonb_path_query_array(co.phone_jsonb, '$[*]."number"'::jsonpath))::text) AS content,
+ 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.'::text || d.id) AS id,
+ 'deals'::text AS resource,
+ d.id AS record_id,
+ d.name AS title,
+ dc.name AS subtitle,
+ concat_ws(' '::text, d.name, d.category, d.description, dc.name) AS content,
+ 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.'::text || t.id) AS id,
+ 'tasks'::text AS resource,
+ t.id AS record_id,
+ "left"(t.text, 200) AS title,
+ concat_ws(' '::text, tco.first_name, tco.last_name) AS subtitle,
+ concat_ws(' '::text, t.text, t.type, tco.first_name, tco.last_name) AS content,
+ t.contact_id,
+ NULL::bigint AS deal_id,
+ t.created_at AS date
+ FROM (public.tasks t
+ LEFT JOIN public.contacts tco ON ((tco.id = t.contact_id)))
+ WHERE (t.done_date IS NULL)
+UNION ALL
+ SELECT ('contactNote.'::text || cn.id) AS id,
+ 'contact_notes'::text AS resource,
+ cn.id AS record_id,
+ "left"(cn.text, 200) AS title,
+ concat_ws(' '::text, nco.first_name, nco.last_name) AS subtitle,
+ concat_ws(' '::text, cn.text, nco.first_name, nco.last_name, ( SELECT string_agg((a.a ->> 'title'::text), ' '::text) AS string_agg
+ FROM unnest(cn.attachments) a(a))) AS content,
+ 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.'::text || dn.id) AS id,
+ 'deal_notes'::text AS resource,
+ dn.id AS record_id,
+ "left"(dn.text, 200) AS title,
+ nd.name AS subtitle,
+ concat_ws(' '::text, dn.text, nd.name, ( SELECT string_agg((a.a ->> 'title'::text), ' '::text) AS string_agg
+ FROM unnest(dn.attachments) a(a))) AS content,
+ 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)))
+ WHERE (nd.archived_at IS NULL);
+
+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/01_tables.sql b/supabase/schemas/01_tables.sql
index 7e3d8752..1072b7aa 100644
--- a/supabase/schemas/01_tables.sql
+++ b/supabase/schemas/01_tables.sql
@@ -115,7 +115,8 @@ create table public.tasks (
text text,
due_date timestamp with time zone,
done_date timestamp with time zone,
- sales_id bigint
+ sales_id bigint,
+ created_at timestamp with time zone not null default now()
);
create table public.configuration (
diff --git a/supabase/schemas/03_views.sql b/supabase/schemas/03_views.sql
index 42913279..a43b80e9 100644
--- a/supabase/schemas/03_views.sql
+++ b/supabase/schemas/03_views.sql
@@ -140,8 +140,17 @@ select
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,
+ concat_ws(
+ ' ',
+ c.name,
+ c.sector,
+ c.description,
+ c.website,
+ c.phone_number,
+ c.zipcode,
+ c.city,
+ c.state_abbr
+ ) as content,
null::bigint as contact_id,
null::bigint as deal_id,
c.created_at as date
@@ -158,11 +167,11 @@ select
co.first_name,
co.last_name,
co.title,
+ co.background,
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
@@ -175,8 +184,7 @@ select
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,
+ concat_ws(' ', d.name, d.category, d.description, dc.name) as content,
null::bigint as contact_id,
d.id as deal_id,
d.created_at as date
@@ -188,28 +196,29 @@ select
('task.' || t.id) as id,
'tasks' as resource,
t.id as record_id,
- t.text as title,
+ left(t.text, 200) as title,
concat_ws(' ', tco.first_name, tco.last_name) as subtitle,
- concat_ws(' ', t.text, t.type) as content,
- tco.company_id,
+ concat_ws(' ', t.text, t.type, tco.first_name, tco.last_name) as content,
t.contact_id,
null::bigint as deal_id,
- t.due_date as date
+ t.created_at as date
from public.tasks t
left join public.contacts tco on tco.id = t.contact_id
+where t.done_date is null
union all
select
('contactNote.' || cn.id) as id,
'contact_notes' as resource,
cn.id as record_id,
- cn.text as title,
+ left(cn.text, 200) as title,
concat_ws(' ', nco.first_name, nco.last_name) as subtitle,
concat_ws(
' ',
cn.text,
+ nco.first_name,
+ nco.last_name,
(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
@@ -220,16 +229,17 @@ select
('dealNote.' || dn.id) as id,
'deal_notes' as resource,
dn.id as record_id,
- dn.text as title,
+ left(dn.text, 200) as title,
nd.name as subtitle,
concat_ws(
' ',
dn.text,
+ nd.name,
(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;
+ left join public.deals nd on nd.id = dn.deal_id
+where nd.archived_at is null;