Skip to content

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

Make the FakeRest global search follow global_search

François Zaninottoa52a7adc15a4
diff --git a/src/components/atomic-crm/providers/commons/search.ts b/src/components/atomic-crm/providers/commons/search.ts
index 71d034ba..d0d0b4ce 100644
--- a/src/components/atomic-crm/providers/commons/search.ts
+++ b/src/components/atomic-crm/providers/commons/search.ts
@@ -10,44 +10,24 @@ import type {
SearchResult,
Task,
} from "../../types";
+import { getSearchTerms, matchesAllTerms } from "../../search/searchHighlight";
import { DESKTOP_SEARCH_RESOURCES } from "../../search/searchResources";
-const PER_RESOURCE_LIMIT = 50;
-const MAX_RESULTS = 250;
+const DEFAULT_MAX_RESULTS = 50;
+const TITLE_LENGTH = 200;
-const searchResource = async <T>(
+const getAll = async <T>(
dataProvider: DataProvider,
resource: string,
- q: string,
- sortField: string,
- extraFilter: Record<string, unknown> = {},
): Promise<T[]> => {
const { data } = await dataProvider.getList<any>(resource, {
- filter: { q, ...extraFilter },
- pagination: { page: 1, perPage: PER_RESOURCE_LIMIT },
- sort: { field: sortField, order: "DESC" },
+ filter: {},
+ pagination: { page: 1, perPage: Number.MAX_SAFE_INTEGER },
+ sort: { field: "id", order: "ASC" },
});
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((id) => id != null) 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(" ");
@@ -61,153 +41,195 @@ const attachmentTitles = (note: ContactNote | DealNote) =>
const byDateDesc = (a: SearchResult, b: SearchResult) =>
(b.date ?? "").localeCompare(a.date ?? "");
+/** A result, plus the text its table's `fts` column indexes in Postgres. */
+type Candidate = { result: SearchResult; document: string };
+
/**
- * Emulates the `global_search` database function for the FakeRest provider,
- * by running FakeRest's own `q` search on each searchable resource and mapping
- * the matches to the function's result shape.
+ * Emulates the `global_search` database function for the FakeRest provider.
*
- * FIXME: this is an approximation of the function, not a reimplementation.
- * - one query per resource instead of one;
- * - FakeRest matches the whole term as a single substring, where Postgres
- * matches each word as a word prefix, ignoring accents;
- * - FakeRest searches its own `q` fields, which differ from the fields
- * indexed by `global_search`.
+ * 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.
*/
export async function getSearchResults(
dataProvider: DataProvider,
query: string,
- resources: SearchResourceName[] = [...DESKTOP_SEARCH_RESOURCES],
+ resources: readonly SearchResourceName[] = DESKTOP_SEARCH_RESOURCES,
+ maxResults = DEFAULT_MAX_RESULTS,
): Promise<SearchResult[]> {
- const q = query.trim();
- if (!q) {
+ const terms = getSearchTerms(query);
+ if (terms.length === 0) {
return [];
}
const [companies, contacts, deals, tasks, contactNotes, dealNotes] =
await Promise.all([
- searchResource<Company>(dataProvider, "companies", q, "created_at"),
- 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"),
+ getAll<Company>(dataProvider, "companies"),
+ getAll<Contact>(dataProvider, "contacts"),
+ getAll<Deal>(dataProvider, "deals"),
+ getAll<Task>(dataProvider, "tasks"),
+ getAll<ContactNote>(dataProvider, "contact_notes"),
+ getAll<DealNote>(dataProvider, "deal_notes"),
]);
- const [contactLabels, dealLabels, companyLabels] = 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,
- ),
- getLabels<Company>(
- dataProvider,
- "companies",
- deals.map((deal) => deal.company_id),
- (company) => company.name,
- ),
- ]);
+ const companiesById = new Map<Identifier, Company>(
+ companies.map((company) => [company.id, company]),
+ );
+ const contactsById = new Map<Identifier, Contact>(
+ contacts.map((contact) => [contact.id, contact]),
+ );
+ const dealsById = new Map<Identifier, Deal>(
+ deals.map((deal) => [deal.id, deal]),
+ );
+ const companyName = (id: Identifier | null | undefined) =>
+ id != null ? (companiesById.get(id)?.name ?? null) : null;
+ const contactLabel = (id: Identifier) => {
+ const contact = contactsById.get(id);
+ return contact ? contactName(contact) : null;
+ };
+ const liveDeals = deals.filter((deal) => !deal.archived_at);
- 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,
- contact_id: null,
- deal_id: null,
- date: company.created_at ?? null,
- content: joinFields(
- company.sector,
- company.description,
- company.website,
- company.phone_number,
- company.zipcode,
- company.city,
- company.state_abbr,
- ),
- })),
- ...contacts.map((contact) => ({
- id: `contact.${contact.id}`,
- resource: "contacts" as const,
- record_id: contact.id,
- title: contactName(contact),
- subtitle: contact.company_name ?? null,
- contact_id: contact.id,
- deal_id: null,
- date: contact.first_seen ?? null,
- content: joinFields(
- contact.title,
- contact.background,
- contact.email_jsonb?.map(({ email }) => email).join(" "),
- contact.phone_jsonb?.map(({ number }) => number).join(" "),
- ),
- })),
- ...deals.map((deal) => ({
- id: `deal.${deal.id}`,
- resource: "deals" as const,
- record_id: deal.id,
- title: deal.name,
- subtitle:
- deal.company_id != null
- ? (companyLabels.get(deal.company_id) ?? null)
- : null,
- contact_id: null,
- deal_id: deal.id,
- date: deal.created_at ?? null,
- content: joinFields(deal.category, deal.description),
- })),
- ...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,
- contact_id: task.contact_id,
- deal_id: null,
- date: task.created_at ?? null,
- content: joinFields(task.text, task.type),
- })),
- ...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,
- contact_id: note.contact_id,
- deal_id: null,
- date: note.date ?? null,
- content: joinFields(note.text, attachmentTitles(note)),
- })),
- ...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,
- contact_id: null,
- deal_id: note.deal_id,
- date: note.date ?? null,
- content: joinFields(note.text, attachmentTitles(note)),
- })),
- ];
+ const candidates: Record<SearchResourceName, () => Candidate[]> = {
+ companies: () =>
+ companies.map((company) => {
+ const content = joinFields(
+ company.sector,
+ company.description,
+ company.website,
+ company.phone_number,
+ company.zipcode,
+ company.city,
+ company.state_abbr,
+ );
+ return {
+ document: [company.name, content].join(" "),
+ result: {
+ id: `company.${company.id}`,
+ resource: "companies",
+ record_id: company.id,
+ title: company.name,
+ subtitle: company.sector ?? null,
+ contact_id: null,
+ deal_id: null,
+ date: company.created_at ?? null,
+ content,
+ },
+ };
+ }),
+ contacts: () =>
+ contacts.map((contact) => {
+ const content = joinFields(
+ contact.title,
+ contact.background,
+ contact.email_jsonb?.map(({ email }) => email).join(" "),
+ contact.phone_jsonb?.map(({ number }) => number).join(" "),
+ );
+ return {
+ document: [contact.first_name, contact.last_name, content].join(" "),
+ result: {
+ id: `contact.${contact.id}`,
+ resource: "contacts",
+ record_id: contact.id,
+ title: contactName(contact),
+ subtitle: companyName(contact.company_id),
+ contact_id: contact.id,
+ deal_id: null,
+ date: contact.first_seen ?? null,
+ content,
+ },
+ };
+ }),
+ deals: () =>
+ liveDeals.map((deal) => {
+ const content = joinFields(deal.category, deal.description);
+ return {
+ document: [deal.name, content].join(" "),
+ result: {
+ id: `deal.${deal.id}`,
+ resource: "deals",
+ record_id: deal.id,
+ title: deal.name,
+ subtitle: companyName(deal.company_id),
+ contact_id: null,
+ deal_id: deal.id,
+ date: deal.created_at ?? null,
+ content,
+ },
+ };
+ }),
+ tasks: () =>
+ tasks
+ .filter((task) => !task.done_date)
+ .map((task) => {
+ const content = joinFields(task.text, task.type);
+ return {
+ document: content ?? "",
+ result: {
+ id: `task.${task.id}`,
+ resource: "tasks",
+ record_id: task.id,
+ title: task.text?.slice(0, TITLE_LENGTH) ?? null,
+ subtitle: contactLabel(task.contact_id),
+ contact_id: task.contact_id,
+ deal_id: null,
+ date: task.created_at ?? null,
+ content,
+ },
+ };
+ }),
+ contact_notes: () =>
+ contactNotes.map((note) => {
+ const content = joinFields(note.text, attachmentTitles(note));
+ return {
+ document: content ?? "",
+ result: {
+ id: `contactNote.${note.id}`,
+ resource: "contact_notes",
+ record_id: note.id,
+ title: note.text?.slice(0, TITLE_LENGTH) ?? null,
+ subtitle: contactLabel(note.contact_id),
+ contact_id: note.contact_id,
+ deal_id: null,
+ date: note.date ?? null,
+ content,
+ },
+ };
+ }),
+ deal_notes: () =>
+ dealNotes
+ .filter((note) => {
+ const deal = dealsById.get(note.deal_id);
+ return deal != null && !deal.archived_at;
+ })
+ .map((note) => {
+ const content = joinFields(note.text, attachmentTitles(note));
+ return {
+ document: content ?? "",
+ result: {
+ id: `dealNote.${note.id}`,
+ resource: "deal_notes",
+ record_id: note.id,
+ title: note.text?.slice(0, TITLE_LENGTH) ?? null,
+ subtitle: dealsById.get(note.deal_id)?.name ?? null,
+ contact_id: null,
+ deal_id: note.deal_id,
+ date: note.date ?? null,
+ content,
+ },
+ };
+ }),
+ };
- return rows
- .filter((row) => resources.includes(row.resource))
+ return resources
+ .flatMap((resource) =>
+ candidates[resource]()
+ .filter(({ document }) => matchesAllTerms(document, terms))
+ .map(({ result }) => result)
+ .sort(byDateDesc)
+ .slice(0, maxResults),
+ )
.sort(byDateDesc)
- .slice(0, MAX_RESULTS);
+ .slice(0, maxResults);
}
diff --git a/src/components/atomic-crm/providers/fakerest/dataProvider.ts b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
index 3c355c28..950ddf3f 100644
--- a/src/components/atomic-crm/providers/fakerest/dataProvider.ts
+++ b/src/components/atomic-crm/providers/fakerest/dataProvider.ts
@@ -302,12 +302,12 @@ export const createDataProvider = ({
resources: readonly SearchResourceName[],
maxResults: number,
): Promise<SearchResult[]> => {
- const results = await getSearchResults(
+ return getSearchResults(
withSupabaseFilterAdapter(baseDataProvider),
query,
- [...resources],
+ resources,
+ maxResults,
);
- return results.slice(0, maxResults);
},
mergeContacts: async (sourceId: Identifier, targetId: Identifier) => {
return mergeContacts(sourceId, targetId, baseDataProvider);
diff --git a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx b/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
index b0ce31c9..df76285f 100644
--- a/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
+++ b/src/components/atomic-crm/search/GlobalSearchDialog.test.tsx
@@ -141,20 +141,28 @@ describe("GlobalSearchDialog", () => {
.toBeVisible();
});
- it("also surfaces the contacts of a matching company", async () => {
+ it("matches words by their start, ignoring accents and case", async () => {
const screen = await renderDialog();
- await screen.getByPlaceholder(PLACEHOLDER).fill("Boulangerie");
+ await screen.getByPlaceholder(PLACEHOLDER).fill("BOULÂN mar");
await expect
.element(
screen
- .getByRole("group", { name: "Contacts" })
- .getByText("Ada Lovelace"),
+ .getByRole("group", { name: "Companies" })
+ .getByText(/Boulangerie Martin/),
)
.toBeVisible();
});
+ it("does not match a term found inside a word", async () => {
+ const screen = await renderDialog();
+
+ await screen.getByPlaceholder(PLACEHOLDER).fill("langerie");
+
+ await expect.element(screen.getByText("No result found")).toBeVisible();
+ });
+
it("finds a note by its text, which no page-specific search can do", async () => {
const screen = await renderDialog();
@@ -180,20 +188,22 @@ describe("GlobalSearchDialog", () => {
.toBeVisible();
});
- it("matches a note word together with its contact's name", async () => {
+ it("searches a record's own fields only, like the database", 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");
-
+ // the company matches, but its contact Ada Lovelace does not: her
+ // company's name is not one of her own fields
+ await screen.getByPlaceholder(PLACEHOLDER).fill("Boulangerie");
await expect
.element(
screen
- .getByRole("group", { name: "Contact notes" })
- .getByText("Called about the sourdough contract"),
+ .getByRole("group", { name: "Companies" })
+ .getByText(/Boulangerie Martin/),
)
.toBeVisible();
+ await expect
+ .element(screen.getByRole("group", { name: "Contacts" }))
+ .not.toBeInTheDocument();
});
it("keeps subtitles for records on id 0, which FakeRest generators use", async () => {
diff --git a/src/components/atomic-crm/search/searchHighlight.ts b/src/components/atomic-crm/search/searchHighlight.ts
index efc55e8c..781dde17 100644
--- a/src/components/atomic-crm/search/searchHighlight.ts
+++ b/src/components/atomic-crm/search/searchHighlight.ts
@@ -21,6 +21,15 @@ export const getSearchTerms = (query: string): string[] => [
...new Set(normalize(query).match(WORD) ?? []),
];
+/**
+ * Whether every term starts a word of `text`: the `@@` test `global_search`
+ * runs in Postgres, for the FakeRest emulation.
+ */
+export const matchesAllTerms = (text: string, terms: string[]): boolean => {
+ const words = normalize(text).match(WORD) ?? [];
+ return terms.every((term) => words.some((word) => word.startsWith(term)));
+};
+
/** Length of `word` covered by `term` when it is a prefix of it, else 0. */
const prefixLength = (word: string, term: string): number => {
let normalized = "";