Skip to content

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

fix(search): rank name matches first in global search

fzaninotto883bcdb95329
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts
index 35433547..037ad7f6 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.test.ts
@@ -116,6 +116,46 @@ describe("fakerest dataProvider", () => {
).toHaveLength(10);
});
+ it("lists contacts named like the query before contacts whose background mentions it", async () => {
+ const dataProvider = createDataProvider({
+ db: {
+ companies: [],
+ contacts: [
+ {
+ id: 1,
+ first_name: "Alice",
+ last_name: "Martin",
+ background: "Introduced by John Doe",
+ first_seen: "2025-01-01T00:00:00.000Z",
+ },
+ {
+ id: 2,
+ first_name: "John",
+ last_name: "Doe",
+ first_seen: "2020-01-01T00:00:00.000Z",
+ },
+ ],
+ deals: [],
+ tasks: [],
+ contact_notes: [],
+ deal_notes: [],
+ } as unknown as Db,
+ latency: 0,
+ silent: true,
+ });
+
+ const results = await dataProvider.globalSearch(
+ "john doe",
+ ["contacts"],
+ 10,
+ );
+
+ expect(results.map((result) => result.title)).toEqual([
+ "John Doe",
+ "Alice Martin",
+ ]);
+ });
+
it("finds a deal in the global search by any of its categories", async () => {
const dataProvider = createDataProvider({
db: {
diff --git a/src/components/atomic-crm/providers/fakerest/search.ts b/src/components/atomic-crm/providers/fakerest/search.ts
index 16d855e5..01e3f8cd 100644
--- a/src/components/atomic-crm/providers/fakerest/search.ts
+++ b/src/components/atomic-crm/providers/fakerest/search.ts
@@ -41,18 +41,25 @@ const joinFields = (...values: (string | null | undefined)[]) =>
const attachmentTitles = (note: ContactNote | DealNote) =>
note.attachments?.map((attachment) => attachment.title).join(" ");
-const byDateDesc = (a: SearchResult, b: SearchResult) =>
- (b.date ?? "").localeCompare(a.date ?? "");
+/**
+ * A result, plus the text its table's `fts` column indexes in Postgres, and
+ * the record's name for the resources that have one.
+ */
+type Candidate = { result: SearchResult; document: string; name?: string };
+
+type RankedResult = { result: SearchResult; isTitleMatch: boolean };
-/** A result, plus the text its table's `fts` column indexes in Postgres. */
-type Candidate = { result: SearchResult; document: string };
+const byTitleMatchThenDateDesc = (a: RankedResult, b: RankedResult) =>
+ Number(b.isTitleMatch) - Number(a.isTitleMatch) ||
+ (b.result.date ?? "").localeCompare(a.result.date ?? "");
/**
* Emulates the `global_search` database function for the FakeRest provider.
*
* 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, newest first.
+ * live deals only, records whose name matches first, then newest first, each
+ * resource's first `maxResults` matches.
* It scans every record, which is fine for the in-browser demo data.
*/
export async function getSearchResults(
@@ -107,6 +114,7 @@ export async function getSearchResults(
);
return {
document: [company.name, content].join(" "),
+ name: company.name,
result: {
resource: "companies",
record_id: company.id,
@@ -129,6 +137,7 @@ export async function getSearchResults(
);
return {
document: [contact.first_name, contact.last_name, content].join(" "),
+ name: contactName(contact),
result: {
resource: "contacts",
record_id: contact.id,
@@ -149,6 +158,7 @@ export async function getSearchResults(
);
return {
document: [deal.name, content].join(" "),
+ name: deal.name,
result: {
resource: "deals",
record_id: deal.id,
@@ -225,9 +235,13 @@ export async function getSearchResults(
.flatMap((resource) =>
candidates[resource]()
.filter(({ document }) => matchesAllTerms(document, terms))
- .map(({ result }) => result)
- .sort(byDateDesc)
+ .map(({ result, name }) => ({
+ result,
+ isTitleMatch: name != null && matchesAllTerms(name, terms),
+ }))
+ .sort(byTitleMatchThenDateDesc)
.slice(0, maxResults),
)
- .sort(byDateDesc);
+ .sort(byTitleMatchThenDateDesc)
+ .map(({ result }) => result);
}
diff --git a/supabase/migrations/20261029131652_global_search_rank_title_matches.sql b/supabase/migrations/20261029131652_global_search_rank_title_matches.sql
new file mode 100644
index 00000000..79883604
--- /dev/null
+++ b/supabase/migrations/20261029131652_global_search_rank_title_matches.sql
@@ -0,0 +1,89 @@
+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 $function$
+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),
+ public.search_document(c.name) @@ %1$L::tsquery as is_title_match
+ from public.companies c
+ where c.fts @@ %1$L::tsquery
+ order by is_title_match desc, 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)),
+ public.search_document(co.first_name, co.last_name) @@ %1$L::tsquery as is_title_match
+ from public.contacts co
+ where co.fts @@ %1$L::tsquery
+ order by is_title_match desc, 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(' · ', variadic d.categories || d.description),
+ public.search_document(d.name) @@ %1$L::tsquery as is_title_match
+ from public.deals d
+ where d.archived_at is null and d.fts @@ %1$L::tsquery
+ order by is_title_match desc, 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), false
+ 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)), false
+ 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)), false
+ 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 resource, record_id, title, subtitle, contact_id, deal_id, date, content
+ from (%s) results(resource, record_id, title, subtitle, contact_id, deal_id, date, content, is_title_match)
+ order by is_title_match desc, date desc nulls last',
+ array_to_string(branches, ' union all ')
+ );
+end
+$function$
+;
diff --git a/supabase/schemas/08_search.sql b/supabase/schemas/08_search.sql
index 02a5d1ab..7e85ea14 100644
--- a/supabase/schemas/08_search.sql
+++ b/supabase/schemas/08_search.sql
@@ -96,6 +96,9 @@ 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.
-- 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
@@ -113,34 +116,37 @@ declare
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)
+ concat_ws(' · ', c.sector, c.description, c.website::text, c.phone_number, c.zipcode, c.city, c.state_abbr),
+ public.search_document(c.name) @@ %1$L::tsquery as is_title_match
from public.companies c
where c.fts @@ %1$L::tsquery
- order by c.created_at desc
+ order by is_title_match desc, 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))
+ (select string_agg(p ->> 'number', ' ') from jsonb_array_elements(co.phone_jsonb) p)),
+ public.search_document(co.first_name, co.last_name) @@ %1$L::tsquery as is_title_match
from public.contacts co
where co.fts @@ %1$L::tsquery
- order by co.first_seen desc nulls last
+ order by is_title_match desc, 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(' · ', variadic d.categories || d.description)
+ concat_ws(' · ', variadic d.categories || d.description),
+ public.search_document(d.name) @@ %1$L::tsquery as is_title_match
from public.deals d
where d.archived_at is null and d.fts @@ %1$L::tsquery
- order by d.created_at desc
+ order by is_title_match desc, 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)
+ concat_ws(' · ', t.text, t.type), false
from public.tasks t
where t.done_date is null and t.fts @@ %1$L::tsquery
order by t.created_at desc
@@ -149,14 +155,14 @@ declare
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))
+ concat_ws(' · ', cn.text, public.search_attachment_titles(cn.attachments)), false
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))
+ concat_ws(' · ', dn.text, public.search_attachment_titles(dn.attachments)), false
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
@@ -180,7 +186,9 @@ begin
end if;
return query execute format(
- 'select * from (%s) results order by 7 desc nulls last',
+ 'select resource, record_id, title, subtitle, contact_id, deal_id, date, content
+ from (%s) results(resource, record_id, title, subtitle, contact_id, deal_id, date, content, is_title_match)
+ order by is_title_match desc, date desc nulls last',
array_to_string(branches, ' union all ')
);
end