A full-featured CRM built with React, shadcn/ui, and Supabase.
refactor(search): make global_search branch templates easier to read
fzaninotto1c8afd6815c2
diff --git a/src/components/atomic-crm/providers/fakerest/search.ts b/src/components/atomic-crm/providers/fakerest/search.tsindex 01e3f8cd..df7df6c2 100644--- a/src/components/atomic-crm/providers/fakerest/search.ts+++ b/src/components/atomic-crm/providers/fakerest/search.ts@@ -47,10 +47,10 @@ const attachmentTitles = (note: ContactNote | DealNote) =>*/type Candidate = { result: SearchResult; document: string; name?: string };-type RankedResult = { result: SearchResult; isTitleMatch: boolean };+type RankedResult = { result: SearchResult; isNameMatch: boolean };-const byTitleMatchThenDateDesc = (a: RankedResult, b: RankedResult) =>- Number(b.isTitleMatch) - Number(a.isTitleMatch) ||+const byNameMatchThenDateDesc = (a: RankedResult, b: RankedResult) =>+ Number(b.isNameMatch) - Number(a.isNameMatch) ||(b.result.date ?? "").localeCompare(a.result.date ?? "");/**@@ -237,11 +237,11 @@ export async function getSearchResults(.filter(({ document }) => matchesAllTerms(document, terms)).map(({ result, name }) => ({result,- isTitleMatch: name != null && matchesAllTerms(name, terms),+ isNameMatch: name != null && matchesAllTerms(name, terms),}))- .sort(byTitleMatchThenDateDesc)+ .sort(byNameMatchThenDateDesc).slice(0, maxResults),)- .sort(byTitleMatchThenDateDesc)+ .sort(byNameMatchThenDateDesc).map(({ result }) => result);}diff --git a/supabase/migrations/20261029133628_global_search_rank_name_matches.sql b/supabase/migrations/20261029133628_global_search_rank_name_matches.sqlindex 70b88b21..ff8a24f1 100644--- a/supabase/migrations/20261029133628_global_search_rank_name_matches.sql+++ b/supabase/migrations/20261029133628_global_search_rank_name_matches.sql@@ -55,13 +55,17 @@ CREATE OR REPLACE FUNCTION public.global_search(query text, resources text[] DEFAS $function$declaretsq tsquery := public.search_query(query);+ name_tsq tsquery := public.search_name_query(query);+ -- Placeholders: %1$L is the query, %2$s the row limit. Branches of named+ -- resources also take %3$s, whether the name matches, and %4$s, the+ -- matching condition on fts.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),- %4$s+ %3$s as is_name_matchfrom public.companies c- where %3$s+ where %4$sorder by c.created_at desclimit %2$s $q$,'contacts', $q$@@ -70,25 +74,25 @@ declareconcat_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)),- %4$s+ %3$s as is_name_matchfrom public.contacts co- where %3$s+ where %4$sorder by co.first_seen desc nulls lastlimit %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(' · ', variadic d.categories || d.description),- %4$s+ %3$s as is_name_matchfrom public.deals d- where d.archived_at is null and %3$s+ where d.archived_at is null and %4$sorder by d.created_at desclimit %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), false+ concat_ws(' · ', t.text, t.type), false as is_name_matchfrom public.tasks twhere t.done_date is null and t.fts @@ %1$L::tsqueryorder by t.created_at desc@@ -97,23 +101,26 @@ declareselect '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)), false+ concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)), false as is_name_matchfrom public.contact_notes cnwhere cn.fts @@ %1$L::tsqueryorder by cn.date desc nulls lastlimit %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)), false+ concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)), false as is_name_matchfrom public.deal_notes dnjoin public.deals nd on nd.id = dn.deal_idwhere nd.archived_at is null and dn.fts @@ %1$L::tsqueryorder by dn.date desc nulls lastlimit %2$s $q$);- name_tsq tsquery := public.search_name_query(query);+ -- A named resource's branch runs once with each condition+ named_resources constant text[] := array['companies', 'contacts', 'deals'];+ name_match constant text := format('fts @@ %L::tsquery', name_tsq);+ other_match constant text := format('fts @@ %L::tsquery and not fts @@ %L::tsquery', tsq, name_tsq);row_limit constant integer := least(coalesce(max_results, 50), 200);- columns constant text := 'resource, record_id, title, subtitle, contact_id, deal_id, date, content, is_title_match';+ columns constant text := 'resource, record_id, title, subtitle, contact_id, deal_id, date, content, is_name_match';branches text[];beginif tsq is null or row_limit < 1 then@@ -121,15 +128,13 @@ beginend if;select array_agg(case- -- %3$s is the search condition, %4$s whether it is a name match- when position('%3$s' in template) > 0 then format(- '(select * from ((%s) union all (%s)) b(%s) order by is_title_match desc, date desc nulls last limit %s)',- format(template, tsq::text, row_limit, format('fts @@ %L::tsquery', name_tsq::text), 'true'),- format(template, tsq::text, row_limit,- format('fts @@ %L::tsquery and not fts @@ %L::tsquery', tsq::text, name_tsq::text), 'false'),+ when b.name = any(named_resources) then format(+ '(select * from ((%s) union all (%s)) halves(%s) order by is_name_match desc, date desc nulls last limit %s)',+ format(template, tsq, row_limit, 'true', name_match),+ format(template, tsq, row_limit, 'false', other_match),columns,row_limit)- else format('(%s)', format(template, tsq::text, row_limit))+ else format('(%s)', format(template, tsq, row_limit))end)into branchesfrom jsonb_each_text(branch_templates) as b(name, template)@@ -142,7 +147,7 @@ beginreturn query execute format('select resource, record_id, title, subtitle, contact_id, deal_id, date, contentfrom (%s) results(%s)- order by is_title_match desc, date desc nulls last',+ order by is_name_match desc, date desc nulls last',array_to_string(branches, ' union all '),columns);diff --git a/supabase/schemas/08_search.sql b/supabase/schemas/08_search.sqlindex 312846dc..396a2e3b 100644--- a/supabase/schemas/08_search.sql+++ b/supabase/schemas/08_search.sql@@ -104,32 +104,38 @@ alter table public.tasks alter column fts set statistics 10000;alter table public.contact_notes alter column fts set statistics 10000;alter table public.deal_notes alter column fts set statistics 10000;--- Records whose name matches every query word (a contact named John Doe)--- rank before those matching elsewhere (a contact whose background mentions--- John Doe), then newest first. Companies, contacts and deals run their branch--- twice, once per kind of match, so each half can still walk the date index:--- testing the name on every match instead is what makes a common word slow.-- 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. 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)--- from a common one (walk the date index).+-- 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) from a common one (walk the date index).+--+-- Records whose name matches every query word (a contact named John Doe) rank+-- before those matching elsewhere (a contact whose background mentions John+-- Doe), then newest first. Companies, contacts and deals run their branch+-- twice, once for name matches and once for the others, so each half can still+-- walk the date index: testing the name on every match is slow for a common+-- word.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" STABLESET "search_path" TO ''AS $_$declaretsq tsquery := public.search_query(query);+ name_tsq tsquery := public.search_name_query(query);+ -- Placeholders: %1$L is the query, %2$s the row limit. Branches of named+ -- resources also take %3$s, whether the name matches, and %4$s, the+ -- matching condition on fts.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),- %4$s+ %3$s as is_name_matchfrom public.companies c- where %3$s+ where %4$sorder by c.created_at desclimit %2$s $q$,'contacts', $q$@@ -138,25 +144,25 @@ declareconcat_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)),- %4$s+ %3$s as is_name_matchfrom public.contacts co- where %3$s+ where %4$sorder by co.first_seen desc nulls lastlimit %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(' · ', variadic d.categories || d.description),- %4$s+ %3$s as is_name_matchfrom public.deals d- where d.archived_at is null and %3$s+ where d.archived_at is null and %4$sorder by d.created_at desclimit %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), false+ concat_ws(' · ', t.text, t.type), false as is_name_matchfrom public.tasks twhere t.done_date is null and t.fts @@ %1$L::tsqueryorder by t.created_at desc@@ -165,23 +171,26 @@ declareselect '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)), false+ concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)), false as is_name_matchfrom public.contact_notes cnwhere cn.fts @@ %1$L::tsqueryorder by cn.date desc nulls lastlimit %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)), false+ concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)), false as is_name_matchfrom public.deal_notes dnjoin public.deals nd on nd.id = dn.deal_idwhere nd.archived_at is null and dn.fts @@ %1$L::tsqueryorder by dn.date desc nulls lastlimit %2$s $q$);- name_tsq tsquery := public.search_name_query(query);+ -- A named resource's branch runs once with each condition+ named_resources constant text[] := array['companies', 'contacts', 'deals'];+ name_match constant text := format('fts @@ %L::tsquery', name_tsq);+ other_match constant text := format('fts @@ %L::tsquery and not fts @@ %L::tsquery', tsq, name_tsq);row_limit constant integer := least(coalesce(max_results, 50), 200);- columns constant text := 'resource, record_id, title, subtitle, contact_id, deal_id, date, content, is_title_match';+ columns constant text := 'resource, record_id, title, subtitle, contact_id, deal_id, date, content, is_name_match';branches text[];beginif tsq is null or row_limit < 1 then@@ -189,15 +198,13 @@ beginend if;select array_agg(case- -- %3$s is the search condition, %4$s whether it is a name match- when position('%3$s' in template) > 0 then format(- '(select * from ((%s) union all (%s)) b(%s) order by is_title_match desc, date desc nulls last limit %s)',- format(template, tsq::text, row_limit, format('fts @@ %L::tsquery', name_tsq::text), 'true'),- format(template, tsq::text, row_limit,- format('fts @@ %L::tsquery and not fts @@ %L::tsquery', tsq::text, name_tsq::text), 'false'),+ when b.name = any(named_resources) then format(+ '(select * from ((%s) union all (%s)) halves(%s) order by is_name_match desc, date desc nulls last limit %s)',+ format(template, tsq, row_limit, 'true', name_match),+ format(template, tsq, row_limit, 'false', other_match),columns,row_limit)- else format('(%s)', format(template, tsq::text, row_limit))+ else format('(%s)', format(template, tsq, row_limit))end)into branchesfrom jsonb_each_text(branch_templates) as b(name, template)@@ -210,7 +217,7 @@ beginreturn query execute format('select resource, record_id, title, subtitle, contact_id, deal_id, date, contentfrom (%s) results(%s)- order by is_title_match desc, date desc nulls last',+ order by is_name_match desc, date desc nulls last',array_to_string(branches, ' union all '),columns);