A full-featured CRM built with React, shadcn/ui, and Supabase.
Cap global search results per resource
fzaninotto4c0d037be56b
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.test.tsindex 7bc68c95..be3fefec 100644--- a/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts@@ -74,4 +74,45 @@ describe("fakerest dataProvider", () => {"Call back",]);});++ it("finds an old contact in the global search despite many newer notes mentioning them", async () => {+ const dataProvider = createDataProvider({+ db: {+ companies: [],+ contacts: [+ {+ id: 1,+ first_name: "Marc",+ last_name: "Durand",+ first_seen: "2021-03-01T00:00:00.000Z",+ },+ ],+ deals: [],+ tasks: [],+ contact_notes: Array.from({ length: 20 }, (_, index) => ({+ id: index + 1,+ contact_id: 1,+ text: `Called Marc about the renewal (${index})`,+ date: "2026-09-01T00:00:00.000Z",+ attachments: [],+ })),+ deal_notes: [],+ } as unknown as Db,+ latency: 0,+ silent: true,+ });++ const results = await dataProvider.globalSearch(+ "marc",+ ["contacts", "contact_notes"],+ 10,+ );++ expect(+ results.filter((result) => result.resource === "contacts"),+ ).toHaveLength(1);+ expect(+ results.filter((result) => result.resource === "contact_notes"),+ ).toHaveLength(10);+ });});diff --git a/src/components/atomic-crm/providers/fakerest/search.ts b/src/components/atomic-crm/providers/fakerest/search.tsindex bf5a59b4..d90eaaac 100644--- a/src/components/atomic-crm/providers/fakerest/search.ts+++ b/src/components/atomic-crm/providers/fakerest/search.ts@@ -52,9 +52,8 @@ type Candidate = { result: SearchResult; document: string };** It follows the same rules: the same fields per resource, every query word* must start a word of the record (accents and case ignored), open tasks and- * live deals only, each resource's newest `maxResults` matches, then the- * newest `maxResults` overall. It scans every record, which is fine for the- * in-browser demo data.+ * live deals only, each resource's newest `maxResults` matches, newest first.+ * It scans every record, which is fine for the in-browser demo data.*/export async function getSearchResults(dataProvider: DataProvider,@@ -227,6 +226,5 @@ export async function getSearchResults(.sort(byDateDesc).slice(0, maxResults),)- .sort(byDateDesc)- .slice(0, maxResults);+ .sort(byDateDesc);}diff --git a/src/components/atomic-crm/search/GlobalSearchButton.tsx b/src/components/atomic-crm/search/GlobalSearchButton.tsxindex 8bbdb990..178253ea 100644--- a/src/components/atomic-crm/search/GlobalSearchButton.tsx+++ b/src/components/atomic-crm/search/GlobalSearchButton.tsx@@ -124,14 +124,15 @@ export const GlobalSearchButton = ({const MIN_SEARCH_LENGTH = 2;const DEBOUNCE_MS = 300;-const MAX_RESULTS = 50;+const MAX_RESULTS_PER_RESOURCE = 10;/*** Run the global search for an already debounced search term.** Stays idle until the term reaches MIN_SEARCH_LENGTH, so opening the dialog- * 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.+ * does not fire a request. `resources` restricts the query server-side to the+ * resources the current layout can actually link to. The row cap applies to+ * each resource, so every group shows its own newest matches.*/const useGlobalSearch = (debouncedQuery: string,@@ -143,7 +144,11 @@ const useGlobalSearch = (const { data, isPending, error } = useQuery({queryKey: ["globalSearch", debouncedQuery, resources],queryFn: () =>- dataProvider.globalSearch(debouncedQuery, resources, MAX_RESULTS),+ dataProvider.globalSearch(+ debouncedQuery,+ resources,+ MAX_RESULTS_PER_RESOURCE,+ ),enabled: isEnabled,meta: { persist: false },// offlineFirst (the app default) pauses a failed search while offline,diff --git a/supabase/migrations/20261022120000_global_search_per_resource_cap.sql b/supabase/migrations/20261022120000_global_search_per_resource_cap.sqlnew file mode 100644index 00000000..d0f51009--- /dev/null+++ b/supabase/migrations/20261022120000_global_search_per_resource_cap.sql@@ -0,0 +1,84 @@+-- Cap global_search results per resource instead of overall, so newer notes+-- that mention a name no longer crowd the matching contact out of the results.++CREATE OR REPLACE FUNCTION "public"."global_search"("query" "text", "resources" "text"[] DEFAULT NULL::"text"[], "max_results" integer DEFAULT 50) RETURNS TABLE("resource" "text", "record_id" bigint, "title" "text", "subtitle" "text", "contact_id" bigint, "deal_id" bigint, "date" timestamp with time zone, "content" "text")+ LANGUAGE "plpgsql" STABLE+ SET "search_path" TO ''+ AS $_$+declare+ tsq tsquery := public.search_query(query);+ branch_templates constant jsonb := jsonb_build_object(+ 'companies', $q$+ select 'companies', c.id, c.name, c.sector, null::bigint, null::bigint, c.created_at,+ concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr)+ from public.companies c+ where c.fts @@ %1$L::tsquery+ order by c.created_at desc+ limit %2$s $q$,+ 'contacts', $q$+ select 'contacts', co.id, concat_ws(' ', co.first_name, co.last_name),+ (select cc.name from public.companies cc where cc.id = co.company_id), co.id, null::bigint, co.first_seen,+ concat_ws(' · ', co.title, co.background,+ (select string_agg(e ->> 'email', ' ') from jsonb_array_elements(co.email_jsonb) e),+ (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p))+ from public.contacts co+ where co.fts @@ %1$L::tsquery+ order by co.first_seen desc nulls last+ limit %2$s $q$,+ 'deals', $q$+ select 'deals', d.id, d.name,+ (select dc.name from public.companies dc where dc.id = d.company_id), null::bigint, d.id, d.created_at,+ concat_ws(' · ', d.category, d.description)+ from public.deals d+ where d.archived_at is null and d.fts @@ %1$L::tsquery+ order by d.created_at desc+ limit %2$s $q$,+ 'tasks', $q$+ select 'tasks', t.id, left(t.text, 200),+ (select concat_ws(' ', tc.first_name, tc.last_name) from public.contacts tc where tc.id = t.contact_id),+ t.contact_id, null::bigint, t.created_at,+ concat_ws(' · ', t.text, t.type)+ from public.tasks t+ where t.done_date is null and t.fts @@ %1$L::tsquery+ order by t.created_at desc+ limit %2$s $q$,+ 'contact_notes', $q$+ select 'contact_notes', cn.id, left(cn.text, 200),+ (select concat_ws(' ', nc.first_name, nc.last_name) from public.contacts nc where nc.id = cn.contact_id),+ cn.contact_id, null::bigint, cn.date,+ concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments))+ from public.contact_notes cn+ where cn.fts @@ %1$L::tsquery+ order by cn.date desc nulls last+ limit %2$s $q$,+ 'deal_notes', $q$+ select 'deal_notes', dn.id, left(dn.text, 200), nd.name, null::bigint, dn.deal_id, dn.date,+ concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments))+ from public.deal_notes dn+ join public.deals nd on nd.id = dn.deal_id+ where nd.archived_at is null and dn.fts @@ %1$L::tsquery+ order by dn.date desc nulls last+ limit %2$s $q$+ );+ row_limit constant integer := least(coalesce(max_results, 50), 200);+ branches text[];+begin+ if tsq is null or row_limit < 1 then+ return;+ end if;++ select array_agg(format('(%s)', format(template, tsq::text, row_limit)))+ into branches+ from jsonb_each_text(branch_templates) as b(name, template)+ where resources is null or b.name = any(resources);++ if branches is null then+ return;+ end if;++ return query execute format(+ 'select * from (%s) results order by 7 desc nulls last',+ array_to_string(branches, ' union all ')+ );+end+$_$;diff --git a/supabase/schemas/08_search.sql b/supabase/schemas/08_search.sqlindex 6cc658d7..c7ae246c 100644--- a/supabase/schemas/08_search.sql+++ b/supabase/schemas/08_search.sql@@ -98,7 +98,8 @@ alter table public.deal_notes alter column fts set statistics 10000;-- Each branch takes its own newest max_results matches (at most 200), so the-- union never holds more than 6 * max_results rows, and the lookups that build--- display labels only run on those. `content` carries the searched fields in+-- display labels only run on those. The cap is per resource, not overall: an+-- old contact must not be crowded out by newer notes that mention its name. `content` carries the searched fields in-- their original form, so the client can show and highlight where the words-- matched. The SQL is built per call with the tsquery inlined as a literal:-- with a parameter the planner could not tell a rare word (use the GIN index)@@ -179,9 +180,8 @@ beginend if;return query execute format(- 'select * from (%s) results order by 7 desc nulls last limit %s',- array_to_string(branches, ' union all '),- row_limit+ 'select * from (%s) results order by 7 desc nulls last',+ array_to_string(branches, ' union all '));end$_$;