@open-mercato/search 0.9.1-develop.7477.1.64ba865101 → 0.9.1-develop.7497.1.543ea44c40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- [build:search] found 100 entry points
1
+ [build:search] found 101 entry points
2
2
  [build:search] built successfully
@@ -0,0 +1,198 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { getTokenContext, readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ import { login } from "@open-mercato/core/modules/core/__integration__/helpers/auth";
5
+ import {
6
+ createCompanyFixture,
7
+ createPersonFixture,
8
+ deleteEntityIfExists
9
+ } from "@open-mercato/core/helpers/integration/crmFixtures";
10
+ const integrationMeta = { dependsOnModules: ["search", "customers"] };
11
+ const DEFAULT_STRATEGIES = ["fulltext", "vector", "tokens"];
12
+ const PERSON_PROFILE = "customers:customer_person_profile";
13
+ const COMPANY_PROFILE = "customers:customer_company_profile";
14
+ const LIST_SEARCH_PLACEHOLDER = /Search by name/i;
15
+ function presenterTitle(result) {
16
+ const title = result.presenter?.title;
17
+ return typeof title === "string" && title.trim().length > 0 ? title.trim() : null;
18
+ }
19
+ async function readEnabledStrategies(request, token) {
20
+ const response = await apiRequest(request, "GET", "/api/search/settings/global-search", { token });
21
+ expect(response.ok(), "GET global-search settings should succeed").toBeTruthy();
22
+ const body = await readJsonSafe(response) ?? {};
23
+ return Array.isArray(body.enabledStrategies) && body.enabledStrategies.length > 0 ? body.enabledStrategies : DEFAULT_STRATEGIES;
24
+ }
25
+ async function writeEnabledStrategies(request, token, strategies) {
26
+ const response = await apiRequest(request, "POST", "/api/search/settings/global-search", {
27
+ token,
28
+ data: { enabledStrategies: strategies }
29
+ });
30
+ expect(response.status(), "POST global-search settings should return 200").toBe(200);
31
+ }
32
+ async function waitForIndexedProfile(request, token, title, expectedEntityId) {
33
+ await expect.poll(
34
+ async () => {
35
+ const params = new URLSearchParams({ q: title, limit: "20" });
36
+ const response = await apiRequest(
37
+ request,
38
+ "GET",
39
+ `/api/search/search/global?${params.toString()}`,
40
+ { token }
41
+ );
42
+ if (!response.ok()) return `status:${response.status()}`;
43
+ const body = await readJsonSafe(response) ?? {};
44
+ const results = Array.isArray(body.results) ? body.results : [];
45
+ const matches = results.filter((result) => presenterTitle(result) === title);
46
+ if (!matches.some((match) => match.entityId === expectedEntityId)) {
47
+ return `awaiting ${expectedEntityId} (titles matched: ${matches.length})`;
48
+ }
49
+ return "ready";
50
+ },
51
+ { timeout: 3e4 }
52
+ ).toBe("ready");
53
+ }
54
+ async function resolveTokens(request) {
55
+ const adminToken = await getAuthToken(request, "admin");
56
+ const superToken = await getAuthToken(request, "superadmin");
57
+ const adminTenant = getTokenContext(adminToken).tenantId;
58
+ const superTenant = getTokenContext(superToken).tenantId;
59
+ expect(adminTenant.length, "the admin token carries a tenant id").toBeGreaterThan(0);
60
+ expect(
61
+ superTenant,
62
+ "admin and superadmin must share a tenant, or the superadmin palette cannot see the seeded customers"
63
+ ).toBe(adminTenant);
64
+ return { adminToken, superToken };
65
+ }
66
+ async function openPaletteWithQuery(page, query) {
67
+ await page.locator("header").getByRole("button", { name: "Open global search" }).click();
68
+ const input = page.locator('[data-search-expanded="true"] input[type="text"]');
69
+ await expect(input).toBeVisible();
70
+ await input.fill(query);
71
+ }
72
+ test.describe("TC-SEARCH-014: a customer appears once in the global search palette", () => {
73
+ test("the palette renders exactly one navigable row per customer", async ({ page, request }) => {
74
+ test.setTimeout(18e4);
75
+ const stamp = Date.now();
76
+ const personName = `QASRCH014P${stamp}`;
77
+ const companyName = `QASRCH014C${stamp}`;
78
+ let adminToken = null;
79
+ let superToken = null;
80
+ let originalStrategies = null;
81
+ let personId = null;
82
+ let companyId = null;
83
+ try {
84
+ const tokens = await resolveTokens(request);
85
+ adminToken = tokens.adminToken;
86
+ superToken = tokens.superToken;
87
+ originalStrategies = await readEnabledStrategies(request, superToken);
88
+ await writeEnabledStrategies(request, superToken, ["tokens"]);
89
+ personId = await createPersonFixture(request, adminToken, {
90
+ firstName: "QA",
91
+ lastName: `Search 014 ${stamp}`,
92
+ displayName: personName
93
+ });
94
+ companyId = await createCompanyFixture(request, adminToken, companyName);
95
+ const fixtures = [
96
+ {
97
+ label: "person",
98
+ title: personName,
99
+ entityId: PERSON_PROFILE,
100
+ detailPrefix: "/backend/customers/people-v2",
101
+ listPath: "/backend/customers/people"
102
+ },
103
+ {
104
+ label: "company",
105
+ title: companyName,
106
+ entityId: COMPANY_PROFILE,
107
+ detailPrefix: "/backend/customers/companies-v2",
108
+ listPath: "/backend/customers/companies"
109
+ }
110
+ ];
111
+ for (const fixture of fixtures) {
112
+ await waitForIndexedProfile(request, superToken, fixture.title, fixture.entityId);
113
+ }
114
+ await login(page, "superadmin");
115
+ for (const fixture of fixtures) {
116
+ await page.goto("/backend");
117
+ await page.waitForLoadState("domcontentloaded");
118
+ await openPaletteWithQuery(page, fixture.title);
119
+ const panel = page.locator("#topbar-search-results");
120
+ await expect(panel).toBeVisible();
121
+ const options = panel.getByRole("option");
122
+ await expect(options).toHaveCount(1, { timeout: 2e4 });
123
+ const option = options.first();
124
+ await expect(
125
+ option,
126
+ `the single ${fixture.label} row must be the seeded customer, not an unrelated result`
127
+ ).toContainText(fixture.title);
128
+ const optionClass = await option.getAttribute("class") ?? "";
129
+ expect(
130
+ optionClass,
131
+ `the ${fixture.label} row must have a primary link \u2014 'opacity-60' marks the greyed-out, unclickable duplicate`
132
+ ).not.toContain("opacity-60");
133
+ await option.click();
134
+ await page.waitForURL(new RegExp(`${fixture.detailPrefix}/[^/?#]+$`), { timeout: 2e4 });
135
+ }
136
+ } finally {
137
+ await deleteEntityIfExists(request, adminToken, "/api/customers/people", personId);
138
+ await deleteEntityIfExists(request, adminToken, "/api/customers/companies", companyId);
139
+ if (superToken && originalStrategies) {
140
+ await writeEnabledStrategies(request, superToken, originalStrategies).catch(() => void 0);
141
+ }
142
+ }
143
+ });
144
+ test("the People and Companies list search still finds the customer", async ({ page, request }) => {
145
+ test.setTimeout(18e4);
146
+ const stamp = Date.now();
147
+ const personName = `QASRCH014LP${stamp}`;
148
+ const companyName = `QASRCH014LC${stamp}`;
149
+ let adminToken = null;
150
+ let personId = null;
151
+ let companyId = null;
152
+ try {
153
+ adminToken = (await resolveTokens(request)).adminToken;
154
+ personId = await createPersonFixture(request, adminToken, {
155
+ firstName: "QA",
156
+ lastName: `Search 014 List ${stamp}`,
157
+ displayName: personName
158
+ });
159
+ companyId = await createCompanyFixture(request, adminToken, companyName);
160
+ await login(page, "superadmin");
161
+ const listArms = [
162
+ { label: "people", path: "/backend/customers/people", endpoint: "/api/customers/people", title: personName },
163
+ {
164
+ label: "companies",
165
+ path: "/backend/customers/companies",
166
+ endpoint: "/api/customers/companies",
167
+ title: companyName
168
+ }
169
+ ];
170
+ for (const arm of listArms) {
171
+ await page.goto(arm.path);
172
+ await page.waitForLoadState("domcontentloaded");
173
+ const searchBox = page.getByPlaceholder(LIST_SEARCH_PLACEHOLDER);
174
+ await expect(searchBox).toBeVisible();
175
+ const filteredResponse = page.waitForResponse(
176
+ (response) => {
177
+ const url = new URL(response.url());
178
+ return url.pathname === arm.endpoint && url.searchParams.get("search") === arm.title && response.status() === 200;
179
+ },
180
+ { timeout: 3e4 }
181
+ );
182
+ await searchBox.fill(arm.title);
183
+ await filteredResponse;
184
+ await expect(
185
+ page.getByText(arm.title, { exact: true }).first(),
186
+ `${arm.label} list search must still return the customer after #5073 stopped offering base customer rows as search results`
187
+ ).toBeVisible({ timeout: 2e4 });
188
+ }
189
+ } finally {
190
+ await deleteEntityIfExists(request, adminToken, "/api/customers/people", personId);
191
+ await deleteEntityIfExists(request, adminToken, "/api/customers/companies", companyId);
192
+ }
193
+ });
194
+ });
195
+ export {
196
+ integrationMeta
197
+ };
198
+ //# sourceMappingURL=TC-SEARCH-014.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-014.spec.ts"],
4
+ "sourcesContent": ["import { expect, test, type APIRequestContext, type Page } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { getTokenContext, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport { login } from '@open-mercato/core/modules/core/__integration__/helpers/auth'\nimport {\n createCompanyFixture,\n createPersonFixture,\n deleteEntityIfExists,\n} from '@open-mercato/core/helpers/integration/crmFixtures'\n\nexport const integrationMeta = { dependsOnModules: ['search', 'customers'] }\n\ntype GlobalSearchSettings = { enabledStrategies?: string[] }\ntype SearchResultItem = {\n entityId?: string\n recordId?: string\n presenter?: { title?: string } | null\n url?: string | null\n}\ntype GlobalSearchResponse = { results?: SearchResultItem[] }\n\nconst DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']\nconst PERSON_PROFILE = 'customers:customer_person_profile'\nconst COMPANY_PROFILE = 'customers:customer_company_profile'\n// Matched as a pattern, not the full string. The rendered placeholder is\n// `customers.{people,companies}.list.searchPlaceholder` \u2014 \"Search by name, email, phone\u2026\" \u2014 whose\n// trailing ellipsis is a single U+2026 character and whose tail is ordinary copy. TC-CRM-001, -014,\n// -015, -029, -030, -033 and -065 all locate this same input with `/Search by name/i`; matching\n// the stable prefix keeps this spec failing on the palette contract it guards rather than on an\n// i18n copy edit.\nconst LIST_SEARCH_PLACEHOLDER = /Search by name/i\n\ntype Fixture = {\n label: 'person' | 'company'\n title: string\n entityId: string\n detailPrefix: string\n listPath: string\n}\n\nfunction presenterTitle(result: SearchResultItem): string | null {\n const title = result.presenter?.title\n return typeof title === 'string' && title.trim().length > 0 ? title.trim() : null\n}\n\nasync function readEnabledStrategies(request: APIRequestContext, token: string): Promise<string[]> {\n const response = await apiRequest(request, 'GET', '/api/search/settings/global-search', { token })\n expect(response.ok(), 'GET global-search settings should succeed').toBeTruthy()\n const body = (await readJsonSafe<GlobalSearchSettings>(response)) ?? {}\n return Array.isArray(body.enabledStrategies) && body.enabledStrategies.length > 0\n ? body.enabledStrategies\n : DEFAULT_STRATEGIES\n}\n\nasync function writeEnabledStrategies(\n request: APIRequestContext,\n token: string,\n strategies: string[],\n): Promise<void> {\n const response = await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: strategies },\n })\n expect(response.status(), 'POST global-search settings should return 200').toBe(200)\n}\n\n/**\n * Waits until global search has indexed the customer's profile row for `title`.\n *\n * The wait exists for one reason only: to keep the browser assertions below from racing the\n * indexer. A palette that renders zero rows because indexing has not caught up is\n * indistinguishable, at the DOM level, from a palette that correctly renders one.\n *\n * It therefore polls for the PRESENCE of the expected profile and never for a row count.\n * Requiring exactly one match here would be the palette's own assertion moved to the API \u2014 and\n * moved in front of the browser, where it short-circuits the run: on a pre-#5073 build the\n * global-search API returns two rows for the title, so a count-based poll would spin for its\n * full timeout and fail here, before `login()` and before the palette was ever opened. The\n * duplicate has to flow through to the DOM `toHaveCount(1)`, which is precisely what this spec\n * adds over the API-level TC-SEARCH-006.\n */\nasync function waitForIndexedProfile(\n request: APIRequestContext,\n token: string,\n title: string,\n expectedEntityId: string,\n): Promise<void> {\n await expect\n .poll(\n async () => {\n const params = new URLSearchParams({ q: title, limit: '20' })\n const response = await apiRequest(\n request,\n 'GET',\n `/api/search/search/global?${params.toString()}`,\n { token },\n )\n if (!response.ok()) return `status:${response.status()}`\n const body = (await readJsonSafe<GlobalSearchResponse>(response)) ?? {}\n const results = Array.isArray(body.results) ? body.results : []\n const matches = results.filter((result) => presenterTitle(result) === title)\n if (!matches.some((match) => match.entityId === expectedEntityId)) {\n return `awaiting ${expectedEntityId} (titles matched: ${matches.length})`\n }\n return 'ready'\n },\n { timeout: 30_000 },\n )\n .toBe('ready')\n}\n\n/**\n * Fixtures are seeded with the `admin` token, never the `superadmin` one, even though every\n * search-side operation below runs as `superadmin`.\n *\n * `withScopedPayload` (`packages/shared/src/lib/api/scoped.ts`) rejects a create with\n * `400 organizationRequired` unless an organization resolves from\n * `payload.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId`. A superadmin is\n * tenant-wide with `orgId: null`, so seeding an org-scoped customer with its token is a\n * guaranteed 400 \u2014 the same split TC-CRM-084 uses, where `superadmin` does tenant-level work\n * and `admin` creates the org-scoped records.\n *\n * Both accounts are seeded into the same tenant, which is what makes the split safe: the\n * superadmin's tenant-wide search still sees the admin's records. That assumption is asserted\n * rather than trusted, so a seeding change fails here with a clear message instead of\n * surfacing later as an inexplicably empty palette.\n */\nasync function resolveTokens(\n request: APIRequestContext,\n): Promise<{ adminToken: string; superToken: string }> {\n const adminToken = await getAuthToken(request, 'admin')\n const superToken = await getAuthToken(request, 'superadmin')\n const adminTenant = getTokenContext(adminToken).tenantId\n const superTenant = getTokenContext(superToken).tenantId\n expect(adminTenant.length, 'the admin token carries a tenant id').toBeGreaterThan(0)\n expect(\n superTenant,\n 'admin and superadmin must share a tenant, or the superadmin palette cannot see the seeded customers',\n ).toBe(adminTenant)\n return { adminToken, superToken }\n}\n\nasync function openPaletteWithQuery(page: Page, query: string): Promise<void> {\n await page.locator('header').getByRole('button', { name: 'Open global search' }).click()\n const input = page.locator('[data-search-expanded=\"true\"] input[type=\"text\"]')\n await expect(input).toBeVisible()\n await input.fill(query)\n}\n\n/**\n * TC-SEARCH-014: a customer appears exactly ONCE in the \u2318K palette, as a navigable row.\n * Source: issue #5547, the browser-level follow-up to #5073 (fixes #5046).\n *\n * #5073 shipped TC-SEARCH-006, which asserts the same contract against the JSON of\n * `GET /api/search/search{,/global}`. That is the right level for the strategy/entity-type\n * contract, but it cannot see the thing the original report describes: two rows in the\n * palette, one greyed out and unclickable. `TopbarSearchInline.tsx` renders a result with no\n * primary link at `opacity-60` with muted text and makes `openResult` a no-op for it, and it\n * is that rendering \u2014 not the response shape \u2014 that made the duplicate look like a broken\n * search result rather than an extra API row.\n *\n * Two things make this spec load-bearing rather than a duplicate of TC-SEARCH-006:\n *\n * 1. It asserts the `role=\"option\"` COUNT. A `toBeVisible()` on the profile row passes even\n * when the duplicate sits next to it, which is precisely the failure mode being guarded.\n * The count also stays honest if a future strategy, enricher or injected result\n * re-introduces a second row by some path other than the token strategy.\n * 2. It signs in as `superadmin`, and that is essential. `resolveReadableEntityTypes`\n * (`packages/shared/src/lib/search/entityAccess.ts:90` \u2014 note that the `packages/search`\n * `lib/entity-access.ts` path, which #5547 cites, is a six-line re-export shim, so the\n * reasoning below is only readable at the shared implementation) returns the caller's\n * requested entity types unchanged for a superadmin and narrows every other principal to\n * entity types a module registered in its `search.ts`. No module registers\n * `customers:customer_entity`, so the duplicate was only ever visible to a superadmin \u2014\n * the same test written as `admin` passes on the broken build too.\n *\n * Strategies are pinned to `tokens` (and restored in `finally`) so the run needs neither\n * Meilisearch nor an embedding provider, and because the duplicate is a token-strategy\n * artifact in the first place. `workers: 1` in the shared Playwright config keeps that\n * tenant-scoped settings write from colliding with a concurrent spec.\n */\ntest.describe('TC-SEARCH-014: a customer appears once in the global search palette', () => {\n test('the palette renders exactly one navigable row per customer', async ({ page, request }) => {\n test.setTimeout(180_000)\n\n const stamp = Date.now()\n const personName = `QASRCH014P${stamp}`\n const companyName = `QASRCH014C${stamp}`\n let adminToken: string | null = null\n let superToken: string | null = null\n let originalStrategies: string[] | null = null\n let personId: string | null = null\n let companyId: string | null = null\n\n try {\n const tokens = await resolveTokens(request)\n adminToken = tokens.adminToken\n superToken = tokens.superToken\n\n originalStrategies = await readEnabledStrategies(request, superToken)\n await writeEnabledStrategies(request, superToken, ['tokens'])\n\n personId = await createPersonFixture(request, adminToken, {\n firstName: 'QA',\n lastName: `Search 014 ${stamp}`,\n displayName: personName,\n })\n companyId = await createCompanyFixture(request, adminToken, companyName)\n\n const fixtures: Fixture[] = [\n {\n label: 'person',\n title: personName,\n entityId: PERSON_PROFILE,\n detailPrefix: '/backend/customers/people-v2',\n listPath: '/backend/customers/people',\n },\n {\n label: 'company',\n title: companyName,\n entityId: COMPANY_PROFILE,\n detailPrefix: '/backend/customers/companies-v2',\n listPath: '/backend/customers/companies',\n },\n ]\n\n // Poll as `superadmin` \u2014 the same principal the palette queries as \u2014 so an entity-access\n // difference between the two accounts surfaces here rather than as an empty palette.\n for (const fixture of fixtures) {\n await waitForIndexedProfile(request, superToken, fixture.title, fixture.entityId)\n }\n\n await login(page, 'superadmin')\n\n for (const fixture of fixtures) {\n await page.goto('/backend')\n await page.waitForLoadState('domcontentloaded')\n await openPaletteWithQuery(page, fixture.title)\n\n const panel = page.locator('#topbar-search-results')\n await expect(panel).toBeVisible()\n\n // -- The duplicate guard, and the reason it counts EVERY option rather than only the\n // ones whose text matches the title. Pre-#5073 a superadmin saw two rows here: the\n // person/company profile plus a navigation-less `customers:customer_entity` row.\n // Filtering by `hasText: title` first would make the assertion depend on the\n // duplicate carrying the same title \u2014 true today, because `customer_entity`\n // registers no `formatResult` and the fallback resolver picks `display_name`, but\n // not a property this spec controls. Since the query is a `Date.now()`-stamped\n // token that matches nothing else in the tenant, the honest assertion is that the\n // palette holds exactly one row, whatever it is titled. `role=\"option\"` is rendered\n // once per result and nowhere else in the listbox (`TopbarSearchInline.tsx`), so\n // the count is exactly the result rows.\n //\n // The palette also debounces by 220ms and renders a \"no results\" placeholder until\n // the response lands, so this waits for the row rather than asserting on an empty\n // list.\n const options = panel.getByRole('option')\n await expect(options).toHaveCount(1, { timeout: 20_000 })\n\n const option = options.first()\n await expect(\n option,\n `the single ${fixture.label} row must be the seeded customer, not an unrelated result`,\n ).toContainText(fixture.title)\n const optionClass = (await option.getAttribute('class')) ?? ''\n expect(\n optionClass,\n `the ${fixture.label} row must have a primary link \u2014 'opacity-60' marks the greyed-out, unclickable duplicate`,\n ).not.toContain('opacity-60')\n\n // -- The row navigates. `openResult` is a no-op when the result has no primary link,\n // so a duplicate row would leave the URL on /backend.\n await option.click()\n await page.waitForURL(new RegExp(`${fixture.detailPrefix}/[^/?#]+$`), { timeout: 20_000 })\n }\n } finally {\n await deleteEntityIfExists(request, adminToken, '/api/customers/people', personId)\n await deleteEntityIfExists(request, adminToken, '/api/customers/companies', companyId)\n if (superToken && originalStrategies) {\n await writeEnabledStrategies(request, superToken, originalStrategies).catch(() => undefined)\n }\n }\n })\n\n /**\n * End-to-end sanity arm for the deliberate read-side-only decision behind #5073: #5073 stopped\n * the token strategy from OFFERING base `customers:customer_entity` rows, but deliberately kept\n * writing them, because the People/Companies list search resolves ids through them. This arm\n * asserts that a customer is still findable through the list search boxes.\n *\n * What this arm pins is exactly that \u2014 the customer stays findable \u2014 and NOT the write-side\n * decision, so a future engineer weighing a `search_tokens` cleanup should not read a green run\n * here as clearance. Searching by `displayName` can be served by three different paths:\n *\n * 1. The `customers:customer_entity` token source \u2014 the one the read-side-only decision is\n * about.\n * 2. The `customers:customer_person_profile` / `customer_company_profile` token source. Both\n * list routes pass TWO sources to `findMatchingEntityIdsBySearchTokensAcrossSources`\n * (`api/people/route.ts`, `api/companies/route.ts`), the profile source also indexes\n * `display_name`, and `api/utils.ts` UNIONS the per-source ids.\n * 3. The `$or` ILIKE fallback both routes take when that union comes back null or empty.\n *\n * Path 2 is why a green run here says nothing about path 1, and the mechanism is the union\n * rather than anything about encryption. A source that queries successfully and matches nothing\n * returns `[]`, not `null` \u2014 `findEntityIdsBySearchTokensCompat` reserves `null` for a blank\n * query alone (`shared/lib/search/tokenLookup.ts`) \u2014 so ONE matching source keeps the union\n * non-empty, and the route then takes `applyEntityIdRestriction` and never builds the ILIKE\n * `$or` at all. Drop the base rows write-side and the profile source still resolves\n * `display_name` by itself, because a profile's index document merges the parent\n * `customer_entities` row before tokenizing (`query_index/lib/indexer.ts`). The union stays\n * non-empty, the customer is still found, and this arm stays green \u2014 encrypted or not.\n *\n * Pinning the write-side property IS reachable, just not by this query. `next_interaction_name`\n * is listed by the base source in BOTH routes and by NEITHER profile source, and the token\n * lookup restricts its query to the field names its source declares (`tokenLookup.ts`), so no\n * profile-source token can answer it. It is also declared encrypted for\n * `customers:customer_entity` (`packages/core/src/modules/customers/encryption.ts`), so the\n * ILIKE fallback cannot serve it either: against a known-encrypted column the query engine\n * rewrites the ILIKE back into a `search_tokens` EXISTS subquery, or \u2014 once the availability\n * probe finds no tokens at all \u2014 runs a literal ILIKE against ciphertext that matches nothing\n * (`query_index/lib/engine.ts`). So with the base rows gone both sources return `[]`, the union\n * empties, the route falls through to ILIKE, and a search on that field finds nothing \u2014 failing\n * exactly when the write-side rows go away. Left for a follow-up rather than written here:\n * `createPersonFixture` would need to accept the field first.\n *\n * Treat a failure here as a real signal that list search broke, and a pass as saying nothing\n * about whether the base `customers:customer_entity` rows still exist.\n */\n test('the People and Companies list search still finds the customer', async ({ page, request }) => {\n test.setTimeout(180_000)\n\n const stamp = Date.now()\n const personName = `QASRCH014LP${stamp}`\n const companyName = `QASRCH014LC${stamp}`\n let adminToken: string | null = null\n let personId: string | null = null\n let companyId: string | null = null\n\n try {\n adminToken = (await resolveTokens(request)).adminToken\n\n personId = await createPersonFixture(request, adminToken, {\n firstName: 'QA',\n lastName: `Search 014 List ${stamp}`,\n displayName: personName,\n })\n companyId = await createCompanyFixture(request, adminToken, companyName)\n\n await login(page, 'superadmin')\n\n const listArms = [\n { label: 'people', path: '/backend/customers/people', endpoint: '/api/customers/people', title: personName },\n {\n label: 'companies',\n path: '/backend/customers/companies',\n endpoint: '/api/customers/companies',\n title: companyName,\n },\n ] as const\n\n for (const arm of listArms) {\n await page.goto(arm.path)\n await page.waitForLoadState('domcontentloaded')\n\n const searchBox = page.getByPlaceholder(LIST_SEARCH_PLACEHOLDER)\n await expect(searchBox).toBeVisible()\n\n // Wait for the FILTERED response specifically. Asserting only that the row is\n // visible after typing would be a false guard: a freshly created customer can\n // already sit on the unfiltered first page, so the assertion would pass even if\n // list search resolved no ids at all \u2014 the exact regression this arm exists to\n // catch. Keying the wait on `search=<token>` proves the query really ran.\n const filteredResponse = page.waitForResponse(\n (response) => {\n const url = new URL(response.url())\n return (\n url.pathname === arm.endpoint &&\n url.searchParams.get('search') === arm.title &&\n response.status() === 200\n )\n },\n { timeout: 30_000 },\n )\n await searchBox.fill(arm.title)\n await filteredResponse\n\n await expect(\n page.getByText(arm.title, { exact: true }).first(),\n `${arm.label} list search must still return the customer after #5073 stopped offering base customer rows as search results`,\n ).toBeVisible({ timeout: 20_000 })\n }\n } finally {\n await deleteEntityIfExists(request, adminToken, '/api/customers/people', personId)\n await deleteEntityIfExists(request, adminToken, '/api/customers/companies', companyId)\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAA+C;AAChE,SAAS,YAAY,oBAAoB;AACzC,SAAS,iBAAiB,oBAAoB;AAC9C,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEA,MAAM,kBAAkB,EAAE,kBAAkB,CAAC,UAAU,WAAW,EAAE;AAW3E,MAAM,qBAAqB,CAAC,YAAY,UAAU,QAAQ;AAC1D,MAAM,iBAAiB;AACvB,MAAM,kBAAkB;AAOxB,MAAM,0BAA0B;AAUhC,SAAS,eAAe,QAAyC;AAC/D,QAAM,QAAQ,OAAO,WAAW;AAChC,SAAO,OAAO,UAAU,YAAY,MAAM,KAAK,EAAE,SAAS,IAAI,MAAM,KAAK,IAAI;AAC/E;AAEA,eAAe,sBAAsB,SAA4B,OAAkC;AACjG,QAAM,WAAW,MAAM,WAAW,SAAS,OAAO,sCAAsC,EAAE,MAAM,CAAC;AACjG,SAAO,SAAS,GAAG,GAAG,2CAA2C,EAAE,WAAW;AAC9E,QAAM,OAAQ,MAAM,aAAmC,QAAQ,KAAM,CAAC;AACtE,SAAO,MAAM,QAAQ,KAAK,iBAAiB,KAAK,KAAK,kBAAkB,SAAS,IAC5E,KAAK,oBACL;AACN;AAEA,eAAe,uBACb,SACA,OACA,YACe;AACf,QAAM,WAAW,MAAM,WAAW,SAAS,QAAQ,sCAAsC;AAAA,IACvF;AAAA,IACA,MAAM,EAAE,mBAAmB,WAAW;AAAA,EACxC,CAAC;AACD,SA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
+ "version": "0.9.1-develop.7497.1.543ea44c40",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -127,9 +127,9 @@
127
127
  "zod": "^4.4.3"
128
128
  },
129
129
  "peerDependencies": {
130
- "@open-mercato/core": "0.9.1-develop.7477.1.64ba865101",
131
- "@open-mercato/queue": "0.9.1-develop.7477.1.64ba865101",
132
- "@open-mercato/shared": "0.9.1-develop.7477.1.64ba865101"
130
+ "@open-mercato/core": "0.9.1-develop.7497.1.543ea44c40",
131
+ "@open-mercato/queue": "0.9.1-develop.7497.1.543ea44c40",
132
+ "@open-mercato/shared": "0.9.1-develop.7497.1.543ea44c40"
133
133
  },
134
134
  "devDependencies": {
135
135
  "@types/jest": "^30.0.0",
@@ -0,0 +1,398 @@
1
+ import { expect, test, type APIRequestContext, type Page } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { getTokenContext, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+ import { login } from '@open-mercato/core/modules/core/__integration__/helpers/auth'
5
+ import {
6
+ createCompanyFixture,
7
+ createPersonFixture,
8
+ deleteEntityIfExists,
9
+ } from '@open-mercato/core/helpers/integration/crmFixtures'
10
+
11
+ export const integrationMeta = { dependsOnModules: ['search', 'customers'] }
12
+
13
+ type GlobalSearchSettings = { enabledStrategies?: string[] }
14
+ type SearchResultItem = {
15
+ entityId?: string
16
+ recordId?: string
17
+ presenter?: { title?: string } | null
18
+ url?: string | null
19
+ }
20
+ type GlobalSearchResponse = { results?: SearchResultItem[] }
21
+
22
+ const DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']
23
+ const PERSON_PROFILE = 'customers:customer_person_profile'
24
+ const COMPANY_PROFILE = 'customers:customer_company_profile'
25
+ // Matched as a pattern, not the full string. The rendered placeholder is
26
+ // `customers.{people,companies}.list.searchPlaceholder` — "Search by name, email, phone…" — whose
27
+ // trailing ellipsis is a single U+2026 character and whose tail is ordinary copy. TC-CRM-001, -014,
28
+ // -015, -029, -030, -033 and -065 all locate this same input with `/Search by name/i`; matching
29
+ // the stable prefix keeps this spec failing on the palette contract it guards rather than on an
30
+ // i18n copy edit.
31
+ const LIST_SEARCH_PLACEHOLDER = /Search by name/i
32
+
33
+ type Fixture = {
34
+ label: 'person' | 'company'
35
+ title: string
36
+ entityId: string
37
+ detailPrefix: string
38
+ listPath: string
39
+ }
40
+
41
+ function presenterTitle(result: SearchResultItem): string | null {
42
+ const title = result.presenter?.title
43
+ return typeof title === 'string' && title.trim().length > 0 ? title.trim() : null
44
+ }
45
+
46
+ async function readEnabledStrategies(request: APIRequestContext, token: string): Promise<string[]> {
47
+ const response = await apiRequest(request, 'GET', '/api/search/settings/global-search', { token })
48
+ expect(response.ok(), 'GET global-search settings should succeed').toBeTruthy()
49
+ const body = (await readJsonSafe<GlobalSearchSettings>(response)) ?? {}
50
+ return Array.isArray(body.enabledStrategies) && body.enabledStrategies.length > 0
51
+ ? body.enabledStrategies
52
+ : DEFAULT_STRATEGIES
53
+ }
54
+
55
+ async function writeEnabledStrategies(
56
+ request: APIRequestContext,
57
+ token: string,
58
+ strategies: string[],
59
+ ): Promise<void> {
60
+ const response = await apiRequest(request, 'POST', '/api/search/settings/global-search', {
61
+ token,
62
+ data: { enabledStrategies: strategies },
63
+ })
64
+ expect(response.status(), 'POST global-search settings should return 200').toBe(200)
65
+ }
66
+
67
+ /**
68
+ * Waits until global search has indexed the customer's profile row for `title`.
69
+ *
70
+ * The wait exists for one reason only: to keep the browser assertions below from racing the
71
+ * indexer. A palette that renders zero rows because indexing has not caught up is
72
+ * indistinguishable, at the DOM level, from a palette that correctly renders one.
73
+ *
74
+ * It therefore polls for the PRESENCE of the expected profile and never for a row count.
75
+ * Requiring exactly one match here would be the palette's own assertion moved to the API — and
76
+ * moved in front of the browser, where it short-circuits the run: on a pre-#5073 build the
77
+ * global-search API returns two rows for the title, so a count-based poll would spin for its
78
+ * full timeout and fail here, before `login()` and before the palette was ever opened. The
79
+ * duplicate has to flow through to the DOM `toHaveCount(1)`, which is precisely what this spec
80
+ * adds over the API-level TC-SEARCH-006.
81
+ */
82
+ async function waitForIndexedProfile(
83
+ request: APIRequestContext,
84
+ token: string,
85
+ title: string,
86
+ expectedEntityId: string,
87
+ ): Promise<void> {
88
+ await expect
89
+ .poll(
90
+ async () => {
91
+ const params = new URLSearchParams({ q: title, limit: '20' })
92
+ const response = await apiRequest(
93
+ request,
94
+ 'GET',
95
+ `/api/search/search/global?${params.toString()}`,
96
+ { token },
97
+ )
98
+ if (!response.ok()) return `status:${response.status()}`
99
+ const body = (await readJsonSafe<GlobalSearchResponse>(response)) ?? {}
100
+ const results = Array.isArray(body.results) ? body.results : []
101
+ const matches = results.filter((result) => presenterTitle(result) === title)
102
+ if (!matches.some((match) => match.entityId === expectedEntityId)) {
103
+ return `awaiting ${expectedEntityId} (titles matched: ${matches.length})`
104
+ }
105
+ return 'ready'
106
+ },
107
+ { timeout: 30_000 },
108
+ )
109
+ .toBe('ready')
110
+ }
111
+
112
+ /**
113
+ * Fixtures are seeded with the `admin` token, never the `superadmin` one, even though every
114
+ * search-side operation below runs as `superadmin`.
115
+ *
116
+ * `withScopedPayload` (`packages/shared/src/lib/api/scoped.ts`) rejects a create with
117
+ * `400 organizationRequired` unless an organization resolves from
118
+ * `payload.organizationId ?? ctx.selectedOrganizationId ?? ctx.auth?.orgId`. A superadmin is
119
+ * tenant-wide with `orgId: null`, so seeding an org-scoped customer with its token is a
120
+ * guaranteed 400 — the same split TC-CRM-084 uses, where `superadmin` does tenant-level work
121
+ * and `admin` creates the org-scoped records.
122
+ *
123
+ * Both accounts are seeded into the same tenant, which is what makes the split safe: the
124
+ * superadmin's tenant-wide search still sees the admin's records. That assumption is asserted
125
+ * rather than trusted, so a seeding change fails here with a clear message instead of
126
+ * surfacing later as an inexplicably empty palette.
127
+ */
128
+ async function resolveTokens(
129
+ request: APIRequestContext,
130
+ ): Promise<{ adminToken: string; superToken: string }> {
131
+ const adminToken = await getAuthToken(request, 'admin')
132
+ const superToken = await getAuthToken(request, 'superadmin')
133
+ const adminTenant = getTokenContext(adminToken).tenantId
134
+ const superTenant = getTokenContext(superToken).tenantId
135
+ expect(adminTenant.length, 'the admin token carries a tenant id').toBeGreaterThan(0)
136
+ expect(
137
+ superTenant,
138
+ 'admin and superadmin must share a tenant, or the superadmin palette cannot see the seeded customers',
139
+ ).toBe(adminTenant)
140
+ return { adminToken, superToken }
141
+ }
142
+
143
+ async function openPaletteWithQuery(page: Page, query: string): Promise<void> {
144
+ await page.locator('header').getByRole('button', { name: 'Open global search' }).click()
145
+ const input = page.locator('[data-search-expanded="true"] input[type="text"]')
146
+ await expect(input).toBeVisible()
147
+ await input.fill(query)
148
+ }
149
+
150
+ /**
151
+ * TC-SEARCH-014: a customer appears exactly ONCE in the ⌘K palette, as a navigable row.
152
+ * Source: issue #5547, the browser-level follow-up to #5073 (fixes #5046).
153
+ *
154
+ * #5073 shipped TC-SEARCH-006, which asserts the same contract against the JSON of
155
+ * `GET /api/search/search{,/global}`. That is the right level for the strategy/entity-type
156
+ * contract, but it cannot see the thing the original report describes: two rows in the
157
+ * palette, one greyed out and unclickable. `TopbarSearchInline.tsx` renders a result with no
158
+ * primary link at `opacity-60` with muted text and makes `openResult` a no-op for it, and it
159
+ * is that rendering — not the response shape — that made the duplicate look like a broken
160
+ * search result rather than an extra API row.
161
+ *
162
+ * Two things make this spec load-bearing rather than a duplicate of TC-SEARCH-006:
163
+ *
164
+ * 1. It asserts the `role="option"` COUNT. A `toBeVisible()` on the profile row passes even
165
+ * when the duplicate sits next to it, which is precisely the failure mode being guarded.
166
+ * The count also stays honest if a future strategy, enricher or injected result
167
+ * re-introduces a second row by some path other than the token strategy.
168
+ * 2. It signs in as `superadmin`, and that is essential. `resolveReadableEntityTypes`
169
+ * (`packages/shared/src/lib/search/entityAccess.ts:90` — note that the `packages/search`
170
+ * `lib/entity-access.ts` path, which #5547 cites, is a six-line re-export shim, so the
171
+ * reasoning below is only readable at the shared implementation) returns the caller's
172
+ * requested entity types unchanged for a superadmin and narrows every other principal to
173
+ * entity types a module registered in its `search.ts`. No module registers
174
+ * `customers:customer_entity`, so the duplicate was only ever visible to a superadmin —
175
+ * the same test written as `admin` passes on the broken build too.
176
+ *
177
+ * Strategies are pinned to `tokens` (and restored in `finally`) so the run needs neither
178
+ * Meilisearch nor an embedding provider, and because the duplicate is a token-strategy
179
+ * artifact in the first place. `workers: 1` in the shared Playwright config keeps that
180
+ * tenant-scoped settings write from colliding with a concurrent spec.
181
+ */
182
+ test.describe('TC-SEARCH-014: a customer appears once in the global search palette', () => {
183
+ test('the palette renders exactly one navigable row per customer', async ({ page, request }) => {
184
+ test.setTimeout(180_000)
185
+
186
+ const stamp = Date.now()
187
+ const personName = `QASRCH014P${stamp}`
188
+ const companyName = `QASRCH014C${stamp}`
189
+ let adminToken: string | null = null
190
+ let superToken: string | null = null
191
+ let originalStrategies: string[] | null = null
192
+ let personId: string | null = null
193
+ let companyId: string | null = null
194
+
195
+ try {
196
+ const tokens = await resolveTokens(request)
197
+ adminToken = tokens.adminToken
198
+ superToken = tokens.superToken
199
+
200
+ originalStrategies = await readEnabledStrategies(request, superToken)
201
+ await writeEnabledStrategies(request, superToken, ['tokens'])
202
+
203
+ personId = await createPersonFixture(request, adminToken, {
204
+ firstName: 'QA',
205
+ lastName: `Search 014 ${stamp}`,
206
+ displayName: personName,
207
+ })
208
+ companyId = await createCompanyFixture(request, adminToken, companyName)
209
+
210
+ const fixtures: Fixture[] = [
211
+ {
212
+ label: 'person',
213
+ title: personName,
214
+ entityId: PERSON_PROFILE,
215
+ detailPrefix: '/backend/customers/people-v2',
216
+ listPath: '/backend/customers/people',
217
+ },
218
+ {
219
+ label: 'company',
220
+ title: companyName,
221
+ entityId: COMPANY_PROFILE,
222
+ detailPrefix: '/backend/customers/companies-v2',
223
+ listPath: '/backend/customers/companies',
224
+ },
225
+ ]
226
+
227
+ // Poll as `superadmin` — the same principal the palette queries as — so an entity-access
228
+ // difference between the two accounts surfaces here rather than as an empty palette.
229
+ for (const fixture of fixtures) {
230
+ await waitForIndexedProfile(request, superToken, fixture.title, fixture.entityId)
231
+ }
232
+
233
+ await login(page, 'superadmin')
234
+
235
+ for (const fixture of fixtures) {
236
+ await page.goto('/backend')
237
+ await page.waitForLoadState('domcontentloaded')
238
+ await openPaletteWithQuery(page, fixture.title)
239
+
240
+ const panel = page.locator('#topbar-search-results')
241
+ await expect(panel).toBeVisible()
242
+
243
+ // -- The duplicate guard, and the reason it counts EVERY option rather than only the
244
+ // ones whose text matches the title. Pre-#5073 a superadmin saw two rows here: the
245
+ // person/company profile plus a navigation-less `customers:customer_entity` row.
246
+ // Filtering by `hasText: title` first would make the assertion depend on the
247
+ // duplicate carrying the same title — true today, because `customer_entity`
248
+ // registers no `formatResult` and the fallback resolver picks `display_name`, but
249
+ // not a property this spec controls. Since the query is a `Date.now()`-stamped
250
+ // token that matches nothing else in the tenant, the honest assertion is that the
251
+ // palette holds exactly one row, whatever it is titled. `role="option"` is rendered
252
+ // once per result and nowhere else in the listbox (`TopbarSearchInline.tsx`), so
253
+ // the count is exactly the result rows.
254
+ //
255
+ // The palette also debounces by 220ms and renders a "no results" placeholder until
256
+ // the response lands, so this waits for the row rather than asserting on an empty
257
+ // list.
258
+ const options = panel.getByRole('option')
259
+ await expect(options).toHaveCount(1, { timeout: 20_000 })
260
+
261
+ const option = options.first()
262
+ await expect(
263
+ option,
264
+ `the single ${fixture.label} row must be the seeded customer, not an unrelated result`,
265
+ ).toContainText(fixture.title)
266
+ const optionClass = (await option.getAttribute('class')) ?? ''
267
+ expect(
268
+ optionClass,
269
+ `the ${fixture.label} row must have a primary link — 'opacity-60' marks the greyed-out, unclickable duplicate`,
270
+ ).not.toContain('opacity-60')
271
+
272
+ // -- The row navigates. `openResult` is a no-op when the result has no primary link,
273
+ // so a duplicate row would leave the URL on /backend.
274
+ await option.click()
275
+ await page.waitForURL(new RegExp(`${fixture.detailPrefix}/[^/?#]+$`), { timeout: 20_000 })
276
+ }
277
+ } finally {
278
+ await deleteEntityIfExists(request, adminToken, '/api/customers/people', personId)
279
+ await deleteEntityIfExists(request, adminToken, '/api/customers/companies', companyId)
280
+ if (superToken && originalStrategies) {
281
+ await writeEnabledStrategies(request, superToken, originalStrategies).catch(() => undefined)
282
+ }
283
+ }
284
+ })
285
+
286
+ /**
287
+ * End-to-end sanity arm for the deliberate read-side-only decision behind #5073: #5073 stopped
288
+ * the token strategy from OFFERING base `customers:customer_entity` rows, but deliberately kept
289
+ * writing them, because the People/Companies list search resolves ids through them. This arm
290
+ * asserts that a customer is still findable through the list search boxes.
291
+ *
292
+ * What this arm pins is exactly that — the customer stays findable — and NOT the write-side
293
+ * decision, so a future engineer weighing a `search_tokens` cleanup should not read a green run
294
+ * here as clearance. Searching by `displayName` can be served by three different paths:
295
+ *
296
+ * 1. The `customers:customer_entity` token source — the one the read-side-only decision is
297
+ * about.
298
+ * 2. The `customers:customer_person_profile` / `customer_company_profile` token source. Both
299
+ * list routes pass TWO sources to `findMatchingEntityIdsBySearchTokensAcrossSources`
300
+ * (`api/people/route.ts`, `api/companies/route.ts`), the profile source also indexes
301
+ * `display_name`, and `api/utils.ts` UNIONS the per-source ids.
302
+ * 3. The `$or` ILIKE fallback both routes take when that union comes back null or empty.
303
+ *
304
+ * Path 2 is why a green run here says nothing about path 1, and the mechanism is the union
305
+ * rather than anything about encryption. A source that queries successfully and matches nothing
306
+ * returns `[]`, not `null` — `findEntityIdsBySearchTokensCompat` reserves `null` for a blank
307
+ * query alone (`shared/lib/search/tokenLookup.ts`) — so ONE matching source keeps the union
308
+ * non-empty, and the route then takes `applyEntityIdRestriction` and never builds the ILIKE
309
+ * `$or` at all. Drop the base rows write-side and the profile source still resolves
310
+ * `display_name` by itself, because a profile's index document merges the parent
311
+ * `customer_entities` row before tokenizing (`query_index/lib/indexer.ts`). The union stays
312
+ * non-empty, the customer is still found, and this arm stays green — encrypted or not.
313
+ *
314
+ * Pinning the write-side property IS reachable, just not by this query. `next_interaction_name`
315
+ * is listed by the base source in BOTH routes and by NEITHER profile source, and the token
316
+ * lookup restricts its query to the field names its source declares (`tokenLookup.ts`), so no
317
+ * profile-source token can answer it. It is also declared encrypted for
318
+ * `customers:customer_entity` (`packages/core/src/modules/customers/encryption.ts`), so the
319
+ * ILIKE fallback cannot serve it either: against a known-encrypted column the query engine
320
+ * rewrites the ILIKE back into a `search_tokens` EXISTS subquery, or — once the availability
321
+ * probe finds no tokens at all — runs a literal ILIKE against ciphertext that matches nothing
322
+ * (`query_index/lib/engine.ts`). So with the base rows gone both sources return `[]`, the union
323
+ * empties, the route falls through to ILIKE, and a search on that field finds nothing — failing
324
+ * exactly when the write-side rows go away. Left for a follow-up rather than written here:
325
+ * `createPersonFixture` would need to accept the field first.
326
+ *
327
+ * Treat a failure here as a real signal that list search broke, and a pass as saying nothing
328
+ * about whether the base `customers:customer_entity` rows still exist.
329
+ */
330
+ test('the People and Companies list search still finds the customer', async ({ page, request }) => {
331
+ test.setTimeout(180_000)
332
+
333
+ const stamp = Date.now()
334
+ const personName = `QASRCH014LP${stamp}`
335
+ const companyName = `QASRCH014LC${stamp}`
336
+ let adminToken: string | null = null
337
+ let personId: string | null = null
338
+ let companyId: string | null = null
339
+
340
+ try {
341
+ adminToken = (await resolveTokens(request)).adminToken
342
+
343
+ personId = await createPersonFixture(request, adminToken, {
344
+ firstName: 'QA',
345
+ lastName: `Search 014 List ${stamp}`,
346
+ displayName: personName,
347
+ })
348
+ companyId = await createCompanyFixture(request, adminToken, companyName)
349
+
350
+ await login(page, 'superadmin')
351
+
352
+ const listArms = [
353
+ { label: 'people', path: '/backend/customers/people', endpoint: '/api/customers/people', title: personName },
354
+ {
355
+ label: 'companies',
356
+ path: '/backend/customers/companies',
357
+ endpoint: '/api/customers/companies',
358
+ title: companyName,
359
+ },
360
+ ] as const
361
+
362
+ for (const arm of listArms) {
363
+ await page.goto(arm.path)
364
+ await page.waitForLoadState('domcontentloaded')
365
+
366
+ const searchBox = page.getByPlaceholder(LIST_SEARCH_PLACEHOLDER)
367
+ await expect(searchBox).toBeVisible()
368
+
369
+ // Wait for the FILTERED response specifically. Asserting only that the row is
370
+ // visible after typing would be a false guard: a freshly created customer can
371
+ // already sit on the unfiltered first page, so the assertion would pass even if
372
+ // list search resolved no ids at all — the exact regression this arm exists to
373
+ // catch. Keying the wait on `search=<token>` proves the query really ran.
374
+ const filteredResponse = page.waitForResponse(
375
+ (response) => {
376
+ const url = new URL(response.url())
377
+ return (
378
+ url.pathname === arm.endpoint &&
379
+ url.searchParams.get('search') === arm.title &&
380
+ response.status() === 200
381
+ )
382
+ },
383
+ { timeout: 30_000 },
384
+ )
385
+ await searchBox.fill(arm.title)
386
+ await filteredResponse
387
+
388
+ await expect(
389
+ page.getByText(arm.title, { exact: true }).first(),
390
+ `${arm.label} list search must still return the customer after #5073 stopped offering base customer rows as search results`,
391
+ ).toBeVisible({ timeout: 20_000 })
392
+ }
393
+ } finally {
394
+ await deleteEntityIfExists(request, adminToken, '/api/customers/people', personId)
395
+ await deleteEntityIfExists(request, adminToken, '/api/customers/companies', companyId)
396
+ }
397
+ })
398
+ })