@open-mercato/search 0.6.5-develop.4516.1.88e6ab71a9 → 0.6.5-develop.4544.1.71c003c861

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.
Files changed (23) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/dist/modules/search/__integration__/TC-SEARCH-003.spec.js +64 -0
  3. package/dist/modules/search/__integration__/TC-SEARCH-003.spec.js.map +7 -0
  4. package/dist/modules/search/__integration__/TC-SEARCH-004.spec.js +97 -0
  5. package/dist/modules/search/__integration__/TC-SEARCH-004.spec.js.map +7 -0
  6. package/dist/modules/search/__integration__/TC-SEARCH-005.spec.js +28 -0
  7. package/dist/modules/search/__integration__/TC-SEARCH-005.spec.js.map +7 -0
  8. package/dist/modules/search/__integration__/TC-SEARCH-006.spec.js +47 -0
  9. package/dist/modules/search/__integration__/TC-SEARCH-006.spec.js.map +7 -0
  10. package/dist/modules/search/__integration__/TC-SEARCH-007.spec.js +28 -0
  11. package/dist/modules/search/__integration__/TC-SEARCH-007.spec.js.map +7 -0
  12. package/dist/modules/search/__integration__/TC-SEARCH-008.spec.js +77 -0
  13. package/dist/modules/search/__integration__/TC-SEARCH-008.spec.js.map +7 -0
  14. package/dist/modules/search/__integration__/TC-SEARCH-009.spec.js +54 -0
  15. package/dist/modules/search/__integration__/TC-SEARCH-009.spec.js.map +7 -0
  16. package/package.json +4 -4
  17. package/src/modules/search/__integration__/TC-SEARCH-003.spec.ts +102 -0
  18. package/src/modules/search/__integration__/TC-SEARCH-004.spec.ts +135 -0
  19. package/src/modules/search/__integration__/TC-SEARCH-005.spec.ts +45 -0
  20. package/src/modules/search/__integration__/TC-SEARCH-006.spec.ts +73 -0
  21. package/src/modules/search/__integration__/TC-SEARCH-007.spec.ts +59 -0
  22. package/src/modules/search/__integration__/TC-SEARCH-008.spec.ts +124 -0
  23. package/src/modules/search/__integration__/TC-SEARCH-009.spec.ts +85 -0
@@ -1,2 +1,2 @@
1
- [build:search] found 81 entry points
1
+ [build:search] found 88 entry points
2
2
  [build:search] built successfully
@@ -0,0 +1,64 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { getTokenScope } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ import {
5
+ createRoleFixture,
6
+ createUserFixture,
7
+ deleteRoleIfExists,
8
+ deleteUserIfExists,
9
+ setRoleAclFeatures
10
+ } from "@open-mercato/core/helpers/integration/authFixtures";
11
+ const VALID_PASSWORD = "Valid1!Pass";
12
+ test.describe("TC-SEARCH-003: search API auth & feature gates (401/403)", () => {
13
+ test("gates search.view and search.reindex by authentication and feature", async ({ request }) => {
14
+ test.slow();
15
+ const stamp = Date.now();
16
+ let adminToken = null;
17
+ let superToken = null;
18
+ let roleId = null;
19
+ let viewerUserId = null;
20
+ const roleName = `qa-search-003-viewer-${stamp}`;
21
+ const viewerEmail = `qa-search-003-viewer-${stamp}@acme.com`;
22
+ try {
23
+ const unauthSearch = await request.get("/api/search/search?q=test");
24
+ expect(unauthSearch.status(), "unauthenticated GET /api/search/search must be 401").toBe(401);
25
+ const unauthReindex = await request.post("/api/search/reindex", { data: {} });
26
+ expect(unauthReindex.status(), "unauthenticated POST /api/search/reindex must be 401").toBe(401);
27
+ adminToken = await getAuthToken(request, "admin");
28
+ const scope = getTokenScope(adminToken);
29
+ roleId = await createRoleFixture(request, adminToken, { name: roleName, tenantId: scope.tenantId });
30
+ await setRoleAclFeatures(request, adminToken, { roleId, features: ["search.view"] });
31
+ viewerUserId = await createUserFixture(request, adminToken, {
32
+ email: viewerEmail,
33
+ password: VALID_PASSWORD,
34
+ organizationId: scope.organizationId,
35
+ roles: [roleName],
36
+ name: "QA Search 003 Viewer"
37
+ });
38
+ const viewerToken = await getAuthToken(request, viewerEmail, VALID_PASSWORD);
39
+ const viewerSearch = await apiRequest(request, "GET", "/api/search/search?q=qa-search-003", { token: viewerToken });
40
+ expect(viewerSearch.status(), "viewer with search.view must not be unauthorized on search").not.toBe(401);
41
+ expect(viewerSearch.status(), "viewer with search.view must not be forbidden on search").not.toBe(403);
42
+ expect(viewerSearch.status(), "search.view passes the gate, so the search succeeds with 200").toBe(200);
43
+ const viewerReindex = await apiRequest(request, "POST", "/api/search/reindex", { token: viewerToken, data: {} });
44
+ expect(viewerReindex.status(), "viewer lacking search.reindex must be forbidden on reindex").toBe(403);
45
+ superToken = await getAuthToken(request, "superadmin");
46
+ const superReindex = await apiRequest(request, "POST", "/api/search/reindex", {
47
+ token: superToken,
48
+ data: { entityId: "customers:customer_company_profile", useQueue: false }
49
+ });
50
+ expect(superReindex.status(), "superadmin reindex must not be unauthorized").not.toBe(401);
51
+ expect(superReindex.status(), "superadmin reindex must not be forbidden").not.toBe(403);
52
+ expect([200, 503], "superadmin reindex returns ok (200) or service-unavailable (503)").toContain(
53
+ superReindex.status()
54
+ );
55
+ } finally {
56
+ if (superToken) {
57
+ await apiRequest(request, "POST", "/api/search/reindex/cancel", { token: superToken }).catch(() => void 0);
58
+ }
59
+ await deleteUserIfExists(request, adminToken, viewerUserId);
60
+ await deleteRoleIfExists(request, adminToken, roleId);
61
+ }
62
+ });
63
+ });
64
+ //# sourceMappingURL=TC-SEARCH-003.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-003.spec.ts"],
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport {\n createRoleFixture,\n createUserFixture,\n deleteRoleIfExists,\n deleteUserIfExists,\n setRoleAclFeatures,\n} from '@open-mercato/core/helpers/integration/authFixtures'\n\n/**\n * TC-SEARCH-003: Search API requires authentication and feature gates (401/403)\n * Source: issue #2483 (expand `search` integration coverage)\n *\n * Real routes (the `search` module id prefixes every route under /api/search):\n * - GET /api/search/search requireAuth + requireFeatures ['search.view']\n * - POST /api/search/reindex requireAuth + requireFeatures ['search.reindex']\n *\n * The framework route wrapper enforces requireAuth (401) and requireFeatures\n * (403) BEFORE the handler body runs, so these gates hold independently of each\n * route's own inline checks. Seeded role features: admin => search.* ,\n * employee => vector.* only, superadmin => all. A user that holds search.view\n * but NOT search.reindex must therefore be provisioned explicitly to prove the\n * granular reindex gate (employee cannot stand in \u2014 it lacks search.view too).\n */\nconst VALID_PASSWORD = 'Valid1!Pass'\n\ntest.describe('TC-SEARCH-003: search API auth & feature gates (401/403)', () => {\n test('gates search.view and search.reindex by authentication and feature', async ({ request }) => {\n test.slow()\n\n const stamp = Date.now()\n let adminToken: string | null = null\n let superToken: string | null = null\n let roleId: string | null = null\n let viewerUserId: string | null = null\n const roleName = `qa-search-003-viewer-${stamp}`\n const viewerEmail = `qa-search-003-viewer-${stamp}@acme.com`\n\n try {\n // 1. Unauthenticated search => 401. q is non-empty, so only the auth gate\n // can produce a 401 here (the handler's empty-query 400 is unreachable\n // because the framework wrapper denies first).\n const unauthSearch = await request.get('/api/search/search?q=test')\n expect(unauthSearch.status(), 'unauthenticated GET /api/search/search must be 401').toBe(401)\n\n // 2. Unauthenticated reindex => 401.\n const unauthReindex = await request.post('/api/search/reindex', { data: {} })\n expect(unauthReindex.status(), 'unauthenticated POST /api/search/reindex must be 401').toBe(401)\n\n adminToken = await getAuthToken(request, 'admin')\n const scope = getTokenScope(adminToken)\n\n // 3. A user with search.view but NOT search.reindex: search is allowed\n // (never 401/403), reindex is forbidden (403).\n roleId = await createRoleFixture(request, adminToken, { name: roleName, tenantId: scope.tenantId })\n await setRoleAclFeatures(request, adminToken, { roleId, features: ['search.view'] })\n viewerUserId = await createUserFixture(request, adminToken, {\n email: viewerEmail,\n password: VALID_PASSWORD,\n organizationId: scope.organizationId,\n roles: [roleName],\n name: 'QA Search 003 Viewer',\n })\n const viewerToken = await getAuthToken(request, viewerEmail, VALID_PASSWORD)\n\n const viewerSearch = await apiRequest(request, 'GET', '/api/search/search?q=qa-search-003', { token: viewerToken })\n expect(viewerSearch.status(), 'viewer with search.view must not be unauthorized on search').not.toBe(401)\n expect(viewerSearch.status(), 'viewer with search.view must not be forbidden on search').not.toBe(403)\n // The search route resolves searchService and returns 200 with results\n // (empty when no strategy returns hits) \u2014 it does not 503 here \u2014 so a passing\n // gate yields 200.\n expect(viewerSearch.status(), 'search.view passes the gate, so the search succeeds with 200').toBe(200)\n\n const viewerReindex = await apiRequest(request, 'POST', '/api/search/reindex', { token: viewerToken, data: {} })\n expect(viewerReindex.status(), 'viewer lacking search.reindex must be forbidden on reindex').toBe(403)\n\n // 4. Superadmin can initiate reindex \u2014 never blocked by auth/feature gates.\n // useQueue:false makes the route clear its own lock in `finally`, so this\n // leaves no lingering fulltext lock for other tests; scoping to a single\n // entity keeps the synchronous reindex cheap.\n superToken = await getAuthToken(request, 'superadmin')\n const superReindex = await apiRequest(request, 'POST', '/api/search/reindex', {\n token: superToken,\n data: { entityId: 'customers:customer_company_profile', useQueue: false },\n })\n expect(superReindex.status(), 'superadmin reindex must not be unauthorized').not.toBe(401)\n expect(superReindex.status(), 'superadmin reindex must not be forbidden').not.toBe(403)\n expect([200, 503], 'superadmin reindex returns ok (200) or service-unavailable (503)').toContain(\n superReindex.status(),\n )\n } finally {\n // Best-effort: release any fulltext lock, then tear down fixtures.\n if (superToken) {\n await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token: superToken }).catch(() => undefined)\n }\n await deleteUserIfExists(request, adminToken, viewerUserId)\n await deleteRoleIfExists(request, adminToken, roleId)\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,qBAAmC;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAiBP,MAAM,iBAAiB;AAEvB,KAAK,SAAS,4DAA4D,MAAM;AAC9E,OAAK,sEAA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AE,OAAO,aAAa,MAAM,CAAC,EAAE,CAAC;AAC/G,aAAO,cAAc,OAAO,GAAG,4DAA4D,EAAE,KAAK,GAAG;AAMrG,mBAAa,MAAM,aAAa,SAAS,YAAY;AACrD,YAAM,eAAe,MAAM,WAAW,SAAS,QAAQ,uBAAuB;AAAA,QAC5E,OAAO;AAAA,QACP,MAAM,EAAE,UAAU,sCAAsC,UAAU,MAAM;AAAA,MAC1E,CAAC;AACD,aAAO,aAAa,OAAO,GAAG,6CAA6C,EAAE,IAAI,KAAK,GAAG;AACzF,aAAO,aAAa,OAAO,GAAG,0CAA0C,EAAE,IAAI,KAAK,GAAG;AACtF,aAAO,CAAC,KAAK,GAAG,GAAG,kEAAkE,EAAE;AAAA,QACrF,aAAa,OAAO;AAAA,MACtB;AAAA,IACF,UAAE;AAEA,UAAI,YAAY;AACd,cAAM,WAAW,SAAS,QAAQ,8BAA8B,EAAE,OAAO,WAAW,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAC9G;AACA,YAAM,mBAAmB,SAAS,YAAY,YAAY;AAC1D,YAAM,mBAAmB,SAAS,YAAY,MAAM;AAAA,IACtD;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,97 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { expectId, getTokenScope, readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ import {
5
+ apiRequestWithSelectedOrg,
6
+ createRoleFixture,
7
+ createUserFixture,
8
+ deleteOrganizationIfExists,
9
+ deleteRoleIfExists,
10
+ deleteUserIfExists,
11
+ setRoleAclFeatures,
12
+ setUserAclVisibility
13
+ } from "@open-mercato/core/helpers/integration/authFixtures";
14
+ import { createCompanyFixture, deleteEntityIfExists } from "@open-mercato/core/helpers/integration/crmFixtures";
15
+ const COMPANY_ENTITY = "customers:customer_company_profile";
16
+ const VALID_PASSWORD = "Valid1!Pass";
17
+ function titleOf(item) {
18
+ const presenter = item?.presenter;
19
+ const title = presenter && typeof presenter === "object" ? presenter.title : void 0;
20
+ return typeof title === "string" ? title : "";
21
+ }
22
+ async function searchTitles(request, token, query) {
23
+ const params = new URLSearchParams({ q: query, limit: "20", entityTypes: COMPANY_ENTITY });
24
+ const res = await apiRequest(request, "GET", `/api/search/search?${params.toString()}`, { token });
25
+ if (!res.ok()) return [];
26
+ const body = await readJsonSafe(res) ?? {};
27
+ return (Array.isArray(body.results) ? body.results : []).map(titleOf);
28
+ }
29
+ test.describe("TC-SEARCH-004: search results are organization-scoped", () => {
30
+ test("a restricted org-B user cannot see org-A companies via search", async ({ request }) => {
31
+ test.slow();
32
+ const stamp = Date.now();
33
+ const unique = `QASRCH004${stamp}`;
34
+ let adminToken = null;
35
+ let superToken = null;
36
+ let orgBId = null;
37
+ let roleId = null;
38
+ let userBId = null;
39
+ let companyAId = null;
40
+ let companyBId = null;
41
+ const roleName = `qa-search-004-${stamp}`;
42
+ const userBEmail = `qa-search-004-${stamp}@acme.com`;
43
+ try {
44
+ adminToken = await getAuthToken(request, "admin");
45
+ superToken = await getAuthToken(request, "superadmin");
46
+ const adminScope = getTokenScope(adminToken);
47
+ const orgResp = await apiRequest(request, "POST", "/api/directory/organizations", {
48
+ token: superToken,
49
+ data: { name: `QA Search 004 OrgB ${stamp}`, tenantId: adminScope.tenantId }
50
+ });
51
+ if (orgResp.status() !== 201) {
52
+ test.skip(true, `cannot provision a second organization in this environment (status ${orgResp.status()})`);
53
+ return;
54
+ }
55
+ orgBId = expectId((await readJsonSafe(orgResp))?.id, "organization create returns an id");
56
+ companyAId = await createCompanyFixture(request, adminToken, `${unique} A`);
57
+ const companyBResp = await apiRequestWithSelectedOrg(request, "POST", "/api/customers/companies", {
58
+ token: superToken,
59
+ selectedOrgId: orgBId,
60
+ data: { displayName: `${unique} B` }
61
+ });
62
+ expect(companyBResp.status(), "create company in orgB should return 201").toBe(201);
63
+ companyBId = expectId((await readJsonSafe(companyBResp))?.id, "company B returns an id");
64
+ roleId = await createRoleFixture(request, adminToken, { name: roleName, tenantId: adminScope.tenantId });
65
+ await setRoleAclFeatures(request, adminToken, { roleId, features: ["search.view", "customers.*"] });
66
+ userBId = await createUserFixture(request, superToken, {
67
+ email: userBEmail,
68
+ password: VALID_PASSWORD,
69
+ organizationId: orgBId,
70
+ roles: [roleName],
71
+ name: "QA Search 004 OrgB User"
72
+ });
73
+ await setUserAclVisibility(request, superToken, {
74
+ userId: userBId,
75
+ organizations: [orgBId],
76
+ features: ["search.view", "customers.*"]
77
+ });
78
+ const userBToken = await getAuthToken(request, userBEmail, VALID_PASSWORD);
79
+ expect(getTokenScope(userBToken).organizationId, "org-B user is scoped to orgB").toBe(orgBId);
80
+ await expect.poll(async () => (await searchTitles(request, adminToken, unique)).includes(`${unique} A`), {
81
+ timeout: 15e3
82
+ }).toBe(true);
83
+ await expect.poll(async () => (await searchTitles(request, userBToken, unique)).includes(`${unique} B`), {
84
+ timeout: 15e3
85
+ }).toBe(true);
86
+ const orgBTitles = await searchTitles(request, userBToken, unique);
87
+ expect(orgBTitles, "org-B user must not see the org-A company").not.toContain(`${unique} A`);
88
+ } finally {
89
+ await deleteEntityIfExists(request, superToken, "/api/customers/companies", companyAId);
90
+ await deleteEntityIfExists(request, superToken, "/api/customers/companies", companyBId);
91
+ await deleteUserIfExists(request, superToken, userBId);
92
+ await deleteRoleIfExists(request, adminToken, roleId);
93
+ await deleteOrganizationIfExists(request, superToken, orgBId);
94
+ }
95
+ });
96
+ });
97
+ //# sourceMappingURL=TC-SEARCH-004.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-004.spec.ts"],
4
+ "sourcesContent": ["import { expect, test, type APIRequestContext } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { expectId, getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport {\n apiRequestWithSelectedOrg,\n createRoleFixture,\n createUserFixture,\n deleteOrganizationIfExists,\n deleteRoleIfExists,\n deleteUserIfExists,\n setRoleAclFeatures,\n setUserAclVisibility,\n} from '@open-mercato/core/helpers/integration/authFixtures'\nimport { createCompanyFixture, deleteEntityIfExists } from '@open-mercato/core/helpers/integration/crmFixtures'\n\ntype SearchResultItem = { entityId?: string; presenter?: { title?: string } | null }\ntype SearchResponse = { results?: SearchResultItem[] }\n\nconst COMPANY_ENTITY = 'customers:customer_company_profile'\nconst VALID_PASSWORD = 'Valid1!Pass'\n\nfunction titleOf(item: SearchResultItem): string {\n const presenter = item?.presenter\n const title = presenter && typeof presenter === 'object' ? (presenter as { title?: unknown }).title : undefined\n return typeof title === 'string' ? title : ''\n}\n\nasync function searchTitles(request: APIRequestContext, token: string, query: string): Promise<string[]> {\n const params = new URLSearchParams({ q: query, limit: '20', entityTypes: COMPANY_ENTITY })\n const res = await apiRequest(request, 'GET', `/api/search/search?${params.toString()}`, { token })\n if (!res.ok()) return []\n const body = (await readJsonSafe<SearchResponse>(res)) ?? {}\n return (Array.isArray(body.results) ? body.results : []).map(titleOf)\n}\n\n/**\n * TC-SEARCH-004: search results are organization-scoped.\n * Source: issue #2483 (P0 \u2014 cross-tenant/org isolation).\n *\n * A company created in the admin's home org (orgA) must be invisible to a user\n * confined to a second organization (orgB) in the same tenant, while that user\n * still sees a company that lives in their own org. This exercises the\n * organization scope filter the search route applies. orgB, its scoped user, and\n * orgB's company are provisioned via API as superadmin; the test skips if a\n * second organization cannot be provisioned in this environment.\n */\ntest.describe('TC-SEARCH-004: search results are organization-scoped', () => {\n test('a restricted org-B user cannot see org-A companies via search', async ({ request }) => {\n test.slow()\n\n const stamp = Date.now()\n const unique = `QASRCH004${stamp}`\n let adminToken: string | null = null\n let superToken: string | null = null\n let orgBId: string | null = null\n let roleId: string | null = null\n let userBId: string | null = null\n let companyAId: string | null = null\n let companyBId: string | null = null\n const roleName = `qa-search-004-${stamp}`\n const userBEmail = `qa-search-004-${stamp}@acme.com`\n\n try {\n adminToken = await getAuthToken(request, 'admin')\n superToken = await getAuthToken(request, 'superadmin')\n const adminScope = getTokenScope(adminToken)\n\n // Provision a second organization in the admin's tenant (superadmin bypasses\n // the directory create command's tenant-selection enforcement).\n const orgResp = await apiRequest(request, 'POST', '/api/directory/organizations', {\n token: superToken,\n data: { name: `QA Search 004 OrgB ${stamp}`, tenantId: adminScope.tenantId },\n })\n if (orgResp.status() !== 201) {\n test.skip(true, `cannot provision a second organization in this environment (status ${orgResp.status()})`)\n return\n }\n orgBId = expectId((await readJsonSafe<{ id?: string }>(orgResp))?.id, 'organization create returns an id')\n\n // Company A in the admin's home org (orgA).\n companyAId = await createCompanyFixture(request, adminToken, `${unique} A`)\n\n // Company B placed into orgB via the selected-org cookie (superadmin).\n const companyBResp = await apiRequestWithSelectedOrg(request, 'POST', '/api/customers/companies', {\n token: superToken,\n selectedOrgId: orgBId,\n data: { displayName: `${unique} B` },\n })\n expect(companyBResp.status(), 'create company in orgB should return 201').toBe(201)\n companyBId = expectId((await readJsonSafe<{ id?: string }>(companyBResp))?.id, 'company B returns an id')\n\n // A user confined to orgB with search + customers read access.\n roleId = await createRoleFixture(request, adminToken, { name: roleName, tenantId: adminScope.tenantId })\n await setRoleAclFeatures(request, adminToken, { roleId, features: ['search.view', 'customers.*'] })\n userBId = await createUserFixture(request, superToken, {\n email: userBEmail,\n password: VALID_PASSWORD,\n organizationId: orgBId,\n roles: [roleName],\n name: 'QA Search 004 OrgB User',\n })\n await setUserAclVisibility(request, superToken, {\n userId: userBId,\n organizations: [orgBId],\n features: ['search.view', 'customers.*'],\n })\n const userBToken = await getAuthToken(request, userBEmail, VALID_PASSWORD)\n expect(getTokenScope(userBToken).organizationId, 'org-B user is scoped to orgB').toBe(orgBId)\n\n // Admin (orgA) can find company A \u2014 confirms it is indexed and searchable.\n await expect\n .poll(async () => (await searchTitles(request, adminToken!, unique)).includes(`${unique} A`), {\n timeout: 15_000,\n })\n .toBe(true)\n\n // Org-B user can find company B (their own org) \u2014 confirms their search works.\n await expect\n .poll(async () => (await searchTitles(request, userBToken, unique)).includes(`${unique} B`), {\n timeout: 15_000,\n })\n .toBe(true)\n\n // Org-B user must NOT see company A (cross-org isolation \u2014 the P0 assertion).\n const orgBTitles = await searchTitles(request, userBToken, unique)\n expect(orgBTitles, 'org-B user must not see the org-A company').not.toContain(`${unique} A`)\n } finally {\n await deleteEntityIfExists(request, superToken, '/api/customers/companies', companyAId)\n await deleteEntityIfExists(request, superToken, '/api/customers/companies', companyBId)\n await deleteUserIfExists(request, superToken, userBId)\n await deleteRoleIfExists(request, adminToken, roleId)\n await deleteOrganizationIfExists(request, superToken, orgBId)\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAoC;AACrD,SAAS,YAAY,oBAAoB;AACzC,SAAS,UAAU,eAAe,oBAAoB;AACtD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,sBAAsB,4BAA4B;AAK3D,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AAEvB,SAAS,QAAQ,MAAgC;AAC/C,QAAM,YAAY,MAAM;AACxB,QAAM,QAAQ,aAAa,OAAO,cAAc,WAAY,UAAkC,QAAQ;AACtG,SAAO,OAAO,UAAU,WAAW,QAAQ;AAC7C;AAEA,eAAe,aAAa,SAA4B,OAAe,OAAkC;AACvG,QAAM,SAAS,IAAI,gBAAgB,EAAE,GAAG,OAAO,OAAO,MAAM,aAAa,eAAe,CAAC;AACzF,QAAM,MAAM,MAAM,WAAW,SAAS,OAAO,sBAAsB,OAAO,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;AACjG,MAAI,CAAC,IAAI,GAAG,EAAG,QAAO,CAAC;AACvB,QAAM,OAAQ,MAAM,aAA6B,GAAG,KAAM,CAAC;AAC3D,UAAQ,MAAM,QAAQ,K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@ -0,0 +1,28 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ test.describe("TC-SEARCH-005: search validates the query parameter (400)", () => {
5
+ let token = "";
6
+ test.beforeAll(async ({ request }) => {
7
+ token = await getAuthToken(request, "admin");
8
+ });
9
+ test("missing q returns 400", async ({ request }) => {
10
+ const res = await apiRequest(request, "GET", "/api/search/search", { token });
11
+ expect(res.status()).toBe(400);
12
+ const body = await readJsonSafe(res);
13
+ expect(typeof body?.error, "a 400 response carries an error message").toBe("string");
14
+ });
15
+ test("empty q returns 400", async ({ request }) => {
16
+ const res = await apiRequest(request, "GET", "/api/search/search?q=", { token });
17
+ expect(res.status()).toBe(400);
18
+ });
19
+ test("whitespace-only q returns 400", async ({ request }) => {
20
+ const res = await apiRequest(request, "GET", "/api/search/search?q=%20%20%20", { token });
21
+ expect(res.status()).toBe(400);
22
+ });
23
+ test("non-empty q is accepted with 200 (not rejected as 400)", async ({ request }) => {
24
+ const res = await apiRequest(request, "GET", `/api/search/search?q=qa-search-005-${Date.now()}`, { token });
25
+ expect(res.status(), "a valid query is accepted with 200").toBe(200);
26
+ });
27
+ });
28
+ //# sourceMappingURL=TC-SEARCH-005.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-005.spec.ts"],
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\n\n/**\n * TC-SEARCH-005: Search validates the query parameter (400)\n * Source: issue #2483.\n *\n * Route: GET /api/search/search (requireFeatures ['search.view']). The handler\n * trims `q` and returns 400 { error: 'Missing query' } when it is empty; a\n * non-empty query is accepted with 200 (empty results when no strategy matches),\n * never 400. All cases authenticate as `admin`, which holds search.view, so the\n * empty-query 400 is produced by the handler rather than the framework gate.\n */\ntest.describe('TC-SEARCH-005: search validates the query parameter (400)', () => {\n let token = ''\n\n test.beforeAll(async ({ request }) => {\n token = await getAuthToken(request, 'admin')\n })\n\n test('missing q returns 400', async ({ request }) => {\n const res = await apiRequest(request, 'GET', '/api/search/search', { token })\n expect(res.status()).toBe(400)\n const body = await readJsonSafe<{ error?: string }>(res)\n expect(typeof body?.error, 'a 400 response carries an error message').toBe('string')\n })\n\n test('empty q returns 400', async ({ request }) => {\n const res = await apiRequest(request, 'GET', '/api/search/search?q=', { token })\n expect(res.status()).toBe(400)\n })\n\n test('whitespace-only q returns 400', async ({ request }) => {\n const res = await apiRequest(request, 'GET', '/api/search/search?q=%20%20%20', { token })\n expect(res.status()).toBe(400)\n })\n\n test('non-empty q is accepted with 200 (not rejected as 400)', async ({ request }) => {\n const res = await apiRequest(request, 'GET', `/api/search/search?q=qa-search-005-${Date.now()}`, { token })\n // The route resolves searchService and returns 200 (empty results when no\n // strategy matches); it does not 503 on this path. So a valid query is a 200.\n expect(res.status(), 'a valid query is accepted with 200').toBe(200)\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAY7B,KAAK,SAAS,6DAA6D,MAAM;AAC/E,MAAI,QAAQ;AAEZ,OAAK,UAAU,OAAO,EAAE,QAAQ,MAAM;AACpC,YAAQ,MAAM,aAAa,SAAS,OAAO;AAAA,EAC7C,CAAC;AAED,OAAK,yBAAyB,OAAO,EAAE,QAAQ,MAAM;AACnD,UAAM,MAAM,MAAM,WAAW,SAAS,OAAO,sBAAsB,EAAE,MAAM,CAAC;AAC5E,WAAO,IAAI,OAAO,CAAC,EAAE,KAAK,GAAG;AAC7B,UAAM,OAAO,MAAM,aAAiC,GAAG;AACvD,WAAO,OAAO,MAAM,OAAO,yCAAyC,EAAE,KAAK,QAAQ;AAAA,EACrF,CAAC;AAED,OAAK,uBAAuB,OAAO,EAAE,QAAQ,MAAM;AACjD,UAAM,MAAM,MAAM,WAAW,SAAS,OAAO,yBAAyB,EAAE,MAAM,CAAC;AAC/E,WAAO,IAAI,OAAO,CAAC,EAAE,KAAK,GAAG;AAAA,EAC/B,CAAC;AAED,OAAK,iCAAiC,OAAO,EAAE,QAAQ,MAAM;AAC3D,UAAM,MAAM,MAAM,WAAW,SAAS,OAAO,kCAAkC,EAAE,MAAM,CAAC;AACxF,WAAO,IAAI,OAAO,CAAC,EAAE,KAAK,GAAG;AAAA,EAC/B,CAAC;AAED,OAAK,0DAA0D,OAAO,EAAE,QAAQ,MAAM;AACpF,UAAM,MAAM,MAAM,WAAW,SAAS,OAAO,sCAAsC,KAAK,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC;AAG1G,WAAO,IAAI,OAAO,GAAG,oCAAoC,EAAE,KAAK,GAAG;AAAA,EACrE,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,47 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ const DEFAULT_STRATEGIES = ["fulltext", "vector", "tokens"];
5
+ test.describe("TC-SEARCH-006: global search honors saved strategy config over URL override", () => {
6
+ test("persisted enabledStrategies wins over the strategies URL parameter", async ({ request }) => {
7
+ test.slow();
8
+ let token = null;
9
+ let originalStrategies = null;
10
+ try {
11
+ token = await getAuthToken(request, "admin");
12
+ const currentRes = await apiRequest(request, "GET", "/api/search/settings/global-search", { token });
13
+ expect(currentRes.ok(), "GET global-search settings should succeed").toBeTruthy();
14
+ const current = await readJsonSafe(currentRes) ?? {};
15
+ expect(Array.isArray(current.enabledStrategies), "settings expose an enabledStrategies array").toBe(true);
16
+ originalStrategies = Array.isArray(current.enabledStrategies) && current.enabledStrategies.length > 0 ? current.enabledStrategies : DEFAULT_STRATEGIES;
17
+ const updateRes = await apiRequest(request, "POST", "/api/search/settings/global-search", {
18
+ token,
19
+ data: { enabledStrategies: ["tokens"] }
20
+ });
21
+ expect(updateRes.status(), "POST global-search settings should return 200").toBe(200);
22
+ const updated = await readJsonSafe(updateRes) ?? {};
23
+ expect(updated.ok, "update reports ok").toBe(true);
24
+ expect(updated.enabledStrategies, "update echoes the saved strategies").toEqual(["tokens"]);
25
+ const globalRes = await apiRequest(
26
+ request,
27
+ "GET",
28
+ `/api/search/search/global?q=qa-search-006-${Date.now()}&strategies=fulltext,vector`,
29
+ { token }
30
+ );
31
+ expect(globalRes.ok(), "GET global search should succeed").toBeTruthy();
32
+ const globalBody = await readJsonSafe(globalRes) ?? {};
33
+ expect(
34
+ globalBody.strategiesEnabled,
35
+ "global search must use the saved config (tokens), ignoring the strategies URL override"
36
+ ).toEqual(["tokens"]);
37
+ } finally {
38
+ if (token && originalStrategies) {
39
+ await apiRequest(request, "POST", "/api/search/settings/global-search", {
40
+ token,
41
+ data: { enabledStrategies: originalStrategies }
42
+ }).catch(() => void 0);
43
+ }
44
+ }
45
+ });
46
+ });
47
+ //# sourceMappingURL=TC-SEARCH-006.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-006.spec.ts"],
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\n\ntype GlobalSearchSettings = { enabledStrategies?: string[] }\ntype GlobalSearchUpdate = { ok?: boolean; enabledStrategies?: string[] }\ntype GlobalSearchResponse = { strategiesEnabled?: string[] }\n\nconst DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']\n\n/**\n * TC-SEARCH-006: global (Cmd+K) search honors the saved strategy config over a\n * URL override. Source: issue #2483.\n *\n * Routes:\n * - GET/POST /api/search/settings/global-search (POST requires search.manage)\n * - GET /api/search/search/global (ignores any `strategies` URL param)\n *\n * Saves enabledStrategies = ['tokens'], then calls global search with a\n * conflicting ?strategies=fulltext,vector and asserts the response's\n * strategiesEnabled reflects the SAVED config, not the URL. The original config\n * is restored in `finally`. `admin` holds both search.view and search.manage.\n */\ntest.describe('TC-SEARCH-006: global search honors saved strategy config over URL override', () => {\n test('persisted enabledStrategies wins over the strategies URL parameter', async ({ request }) => {\n test.slow()\n\n let token: string | null = null\n let originalStrategies: string[] | null = null\n\n try {\n token = await getAuthToken(request, 'admin')\n\n const currentRes = await apiRequest(request, 'GET', '/api/search/settings/global-search', { token })\n expect(currentRes.ok(), 'GET global-search settings should succeed').toBeTruthy()\n const current = (await readJsonSafe<GlobalSearchSettings>(currentRes)) ?? {}\n expect(Array.isArray(current.enabledStrategies), 'settings expose an enabledStrategies array').toBe(true)\n originalStrategies =\n Array.isArray(current.enabledStrategies) && current.enabledStrategies.length > 0\n ? current.enabledStrategies\n : DEFAULT_STRATEGIES\n\n const updateRes = await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: ['tokens'] },\n })\n expect(updateRes.status(), 'POST global-search settings should return 200').toBe(200)\n const updated = (await readJsonSafe<GlobalSearchUpdate>(updateRes)) ?? {}\n expect(updated.ok, 'update reports ok').toBe(true)\n expect(updated.enabledStrategies, 'update echoes the saved strategies').toEqual(['tokens'])\n\n const globalRes = await apiRequest(\n request,\n 'GET',\n `/api/search/search/global?q=qa-search-006-${Date.now()}&strategies=fulltext,vector`,\n { token },\n )\n expect(globalRes.ok(), 'GET global search should succeed').toBeTruthy()\n const globalBody = (await readJsonSafe<GlobalSearchResponse>(globalRes)) ?? {}\n expect(\n globalBody.strategiesEnabled,\n 'global search must use the saved config (tokens), ignoring the strategies URL override',\n ).toEqual(['tokens'])\n } finally {\n if (token && originalStrategies) {\n await apiRequest(request, 'POST', '/api/search/settings/global-search', {\n token,\n data: { enabledStrategies: originalStrategies },\n }).catch(() => undefined)\n }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S,KAAM,CAAC;AAC7E;AAAA,QACE,WAAW;AAAA,QACX;AAAA,MACF,EAAE,QAAQ,CAAC,QAAQ,CAAC;AAAA,IACtB,UAAE;AACA,UAAI,SAAS,oBAAoB;AAC/B,cAAM,WAAW,SAAS,QAAQ,sCAAsC;AAAA,UACtE;AAAA,UACA,MAAM,EAAE,mBAAmB,mBAAmB;AAAA,QAChD,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAC1B;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,28 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ test.describe("TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info", () => {
5
+ test("a second reindex while one is active is rejected with 409", async ({ request }) => {
6
+ test.slow();
7
+ let token = null;
8
+ try {
9
+ token = await getAuthToken(request, "admin");
10
+ await apiRequest(request, "POST", "/api/search/reindex/cancel", { token }).catch(() => void 0);
11
+ const first = await apiRequest(request, "POST", "/api/search/reindex", { token, data: { useQueue: true } });
12
+ expect(first.status(), "first reindex must not hit a pre-existing lock").not.toBe(409);
13
+ expect([200, 503], "first reindex starts (200) or reports backend unavailable (503)").toContain(first.status());
14
+ const second = await apiRequest(request, "POST", "/api/search/reindex", { token, data: { useQueue: true } });
15
+ expect(second.status(), "a concurrent reindex must be rejected with 409").toBe(409);
16
+ const body = await readJsonSafe(second) ?? {};
17
+ expect(body.lock?.type, "the 409 lock descriptor identifies the fulltext lock").toBe("fulltext");
18
+ expect(typeof body.lock?.action, "the lock reports its action").toBe("string");
19
+ expect(typeof body.lock?.startedAt, "the lock reports when it started").toBe("string");
20
+ expect(typeof body.lock?.elapsedMinutes, "the lock reports elapsed minutes").toBe("number");
21
+ } finally {
22
+ if (token) {
23
+ await apiRequest(request, "POST", "/api/search/reindex/cancel", { token }).catch(() => void 0);
24
+ }
25
+ }
26
+ });
27
+ });
28
+ //# sourceMappingURL=TC-SEARCH-007.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-007.spec.ts"],
4
+ "sourcesContent": ["import { expect, test } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\n\ntype ReindexLock = {\n type?: string\n action?: string\n startedAt?: string\n elapsedMinutes?: number\n processedCount?: number | null\n totalCount?: number | null\n}\ntype ConflictBody = { error?: string; lock?: ReindexLock }\n\n/**\n * TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info.\n * Source: issue #2483.\n *\n * Route: POST /api/search/reindex (requireFeatures ['search.reindex']). The route\n * acquires a per-tenant DB lock BEFORE any indexing work and, in queue mode\n * (useQueue:true \u2014 the default), does NOT release it in `finally` (workers and\n * the heartbeat own it). So a first call holds the lock and a second call returns\n * 409 with the lock descriptor \u2014 independent of whether a fulltext backend is\n * configured, because the lock is taken before the strategy-availability check.\n * Integration specs run serially (workers:1), so no other test contends for the\n * shared lock; it is released in `finally` via the cancel endpoint.\n */\ntest.describe('TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info', () => {\n test('a second reindex while one is active is rejected with 409', async ({ request }) => {\n test.slow()\n\n let token: string | null = null\n\n try {\n token = await getAuthToken(request, 'admin')\n\n // Start from a clean lock state.\n await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)\n\n // First reindex acquires (and, in queue mode, holds) the fulltext lock.\n const first = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })\n expect(first.status(), 'first reindex must not hit a pre-existing lock').not.toBe(409)\n expect([200, 503], 'first reindex starts (200) or reports backend unavailable (503)').toContain(first.status())\n\n // Second reindex is rejected while the first holds the lock.\n const second = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })\n expect(second.status(), 'a concurrent reindex must be rejected with 409').toBe(409)\n const body = (await readJsonSafe<ConflictBody>(second)) ?? {}\n expect(body.lock?.type, 'the 409 lock descriptor identifies the fulltext lock').toBe('fulltext')\n expect(typeof body.lock?.action, 'the lock reports its action').toBe('string')\n expect(typeof body.lock?.startedAt, 'the lock reports when it started').toBe('string')\n expect(typeof body.lock?.elapsedMinutes, 'the lock reports elapsed minutes').toBe('number')\n } finally {\n if (token) {\n await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)\n }\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAY;AAC7B,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAyB7B,KAAK,SAAS,yEAAyE,MAAM;AAC3F,OAAK,6DAA6D,OAAO,EAAE,QAAQ,MAAM;AACvF,SAAK,KAAK;AAEV,QAAI,QAAuB;AAE3B,QAAI;AACF,cAAQ,MAAM,aAAa,SAAS,OAAO;AAG3C,YAAM,WAAW,SAAS,QAAQ,8BAA8B,EAAE,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AAGhG,YAAM,QAAQ,MAAM,WAAW,SAAS,QAAQ,uBAAuB,EAAE,OAAO,MAAM,EAAE,UAAU,KAAK,EAAE,CAAC;AAC1G,aAAO,MAAM,OAAO,GAAG,gDAAgD,EAAE,IAAI,KAAK,GAAG;AACrF,aAAO,CAAC,KAAK,GAAG,GAAG,iEAAiE,EAAE,UAAU,MAAM,OAAO,CAAC;AAG9G,YAAM,SAAS,MAAM,WAAW,SAAS,QAAQ,uBAAuB,EAAE,OAAO,MAAM,EAAE,UAAU,KAAK,EAAE,CAAC;AAC3G,aAAO,OAAO,OAAO,GAAG,gDAAgD,EAAE,KAAK,GAAG;AAClF,YAAM,OAAQ,MAAM,aAA2B,MAAM,KAAM,CAAC;AAC5D,aAAO,KAAK,MAAM,MAAM,sDAAsD,EAAE,KAAK,UAAU;AAC/F,aAAO,OAAO,KAAK,MAAM,QAAQ,6BAA6B,EAAE,KAAK,QAAQ;AAC7E,aAAO,OAAO,KAAK,MAAM,WAAW,kCAAkC,EAAE,KAAK,QAAQ;AACrF,aAAO,OAAO,KAAK,MAAM,gBAAgB,kCAAkC,EAAE,KAAK,QAAQ;AAAA,IAC5F,UAAE;AACA,UAAI,OAAO;AACT,cAAM,WAAW,SAAS,QAAQ,8BAA8B,EAAE,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAClG;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,77 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ import { createCompanyFixture, deleteEntityIfExists } from "@open-mercato/core/helpers/integration/crmFixtures";
5
+ const COMPANY_ENTITY = "customers:customer_company_profile";
6
+ async function getIndex(request, token, params) {
7
+ const qs = new URLSearchParams(params).toString();
8
+ const res = await apiRequest(request, "GET", `/api/search/index${qs ? `?${qs}` : ""}`, { token });
9
+ const body = res.ok() ? await readJsonSafe(res) ?? {} : {};
10
+ return { status: res.status(), body };
11
+ }
12
+ test.describe("TC-SEARCH-008: vector index list pagination & entityId filter", () => {
13
+ test("paginates entries and filters by entityId", async ({ request }) => {
14
+ test.slow();
15
+ let token = null;
16
+ const companyIds = [];
17
+ const stamp = Date.now();
18
+ try {
19
+ token = await getAuthToken(request, "admin");
20
+ const probe = await getIndex(request, token, {});
21
+ if (probe.status !== 200) {
22
+ test.skip(true, `vector index is not listable in this environment (status ${probe.status})`);
23
+ return;
24
+ }
25
+ for (let i = 0; i < 3; i += 1) {
26
+ companyIds.push(await createCompanyFixture(request, token, `QASRCH008-${stamp}-${i}`));
27
+ }
28
+ await apiRequest(request, "POST", "/api/search/embeddings/reindex", {
29
+ token,
30
+ data: { entityId: COMPANY_ENTITY }
31
+ }).catch(() => void 0);
32
+ let entries = [];
33
+ for (let attempt = 0; attempt < 20; attempt += 1) {
34
+ entries = (await getIndex(request, token, {})).body.entries ?? [];
35
+ if (entries.length >= 2) break;
36
+ await new Promise((resolve) => setTimeout(resolve, 1e3));
37
+ }
38
+ if (entries.length < 2) {
39
+ test.skip(true, "vector index did not reach 2 entries; the embedding pipeline does not produce rows here");
40
+ return;
41
+ }
42
+ const base = await getIndex(request, token, {});
43
+ expect(base.body.limit, "default limit is 50").toBe(50);
44
+ expect(base.body.offset, "default offset is 0").toBe(0);
45
+ expect((base.body.entries ?? []).length, "index has at least two entries to page over").toBeGreaterThanOrEqual(2);
46
+ const limited = await getIndex(request, token, { limit: "1", offset: "0" });
47
+ expect(limited.body.limit, "response echoes the requested limit").toBe(1);
48
+ expect(limited.body.entries?.length ?? 0, "limit=1 returns at most one entry").toBeLessThanOrEqual(1);
49
+ const pageOfTwo = await getIndex(request, token, { limit: "2", offset: "0" });
50
+ const twoIds = (pageOfTwo.body.entries ?? []).map((entry) => entry.recordId);
51
+ expect(twoIds.length, "a limit=2 page returns two rows").toBe(2);
52
+ expect(twoIds[0], "each paged entry exposes a recordId").toBeTruthy();
53
+ expect(twoIds[1], "the two paged entries are distinct records").not.toBe(twoIds[0]);
54
+ const page2 = await getIndex(request, token, { limit: "1", offset: "1" });
55
+ expect(page2.body.offset, "response echoes the requested offset").toBe(1);
56
+ const offset0Id = limited.body.entries?.[0]?.recordId;
57
+ const offset1Id = page2.body.entries?.[0]?.recordId;
58
+ expect(offset1Id, "offset=1 returns a record").toBeTruthy();
59
+ expect(offset1Id, "offset=1 returns a different record than offset=0").not.toBe(offset0Id);
60
+ const filtered = await getIndex(request, token, { entityId: COMPANY_ENTITY, limit: "50" });
61
+ expect((filtered.body.entries ?? []).length, "company entityId filter returns at least our fixtures").toBeGreaterThan(
62
+ 0
63
+ );
64
+ for (const entry of filtered.body.entries ?? []) {
65
+ expect(entry.entityId, "entityId filter returns only that entity type").toBe(COMPANY_ENTITY);
66
+ }
67
+ } finally {
68
+ if (token) {
69
+ await apiRequest(request, "POST", "/api/search/embeddings/reindex/cancel", { token }).catch(() => void 0);
70
+ }
71
+ for (const id of companyIds) {
72
+ await deleteEntityIfExists(request, token, "/api/customers/companies", id);
73
+ }
74
+ }
75
+ });
76
+ });
77
+ //# sourceMappingURL=TC-SEARCH-008.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-008.spec.ts"],
4
+ "sourcesContent": ["import { expect, test, type APIRequestContext } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport { createCompanyFixture, deleteEntityIfExists } from '@open-mercato/core/helpers/integration/crmFixtures'\n\ntype IndexEntry = { entityId?: string; recordId?: string }\ntype IndexResponse = { entries?: IndexEntry[]; limit?: number; offset?: number }\n\nconst COMPANY_ENTITY = 'customers:customer_company_profile'\n\nasync function getIndex(\n request: APIRequestContext,\n token: string,\n params: Record<string, string>,\n): Promise<{ status: number; body: IndexResponse }> {\n const qs = new URLSearchParams(params).toString()\n const res = await apiRequest(request, 'GET', `/api/search/index${qs ? `?${qs}` : ''}`, { token })\n const body = res.ok() ? ((await readJsonSafe<IndexResponse>(res)) ?? {}) : {}\n return { status: res.status(), body }\n}\n\n/**\n * TC-SEARCH-008: vector index list pagination & entityId filter.\n * Source: issue #2483.\n *\n * Route: GET /api/search/index (requireFeatures ['search.view']) returns the\n * vector-store entries (VectorIndexEntry: entityId, recordId, \u2026 \u2014 there is no\n * surrogate `id`) with limit/offset paging and an optional entityId filter.\n * Exercising it requires a working embedding pipeline (a provider key AND an\n * applied embedding config that produces indexed rows). When the index is not\n * listable \u2014 the endpoint returns 503 (vector strategy unavailable) or 500 (no\n * embedding config / vector table) \u2014 this test skips, mirroring how the\n * fulltext-dependent specs skip when Meilisearch is absent. The full pagination\n * contract runs only when the vector index is queryable and rows materialize.\n */\ntest.describe('TC-SEARCH-008: vector index list pagination & entityId filter', () => {\n test('paginates entries and filters by entityId', async ({ request }) => {\n test.slow()\n\n let token: string | null = null\n const companyIds: string[] = []\n const stamp = Date.now()\n\n try {\n token = await getAuthToken(request, 'admin')\n\n // The endpoint must be queryable (200). A 503 (vector strategy unavailable)\n // or 500 (no embedding config / vector table) means the index cannot be\n // paginated in this environment \u2014 skip rather than fail.\n const probe = await getIndex(request, token, {})\n if (probe.status !== 200) {\n test.skip(true, `vector index is not listable in this environment (status ${probe.status})`)\n return\n }\n\n for (let i = 0; i < 3; i += 1) {\n companyIds.push(await createCompanyFixture(request, token, `QASRCH008-${stamp}-${i}`))\n }\n\n // Trigger a (queued) vector reindex and wait for rows to materialize.\n await apiRequest(request, 'POST', '/api/search/embeddings/reindex', {\n token,\n data: { entityId: COMPANY_ENTITY },\n }).catch(() => undefined)\n\n let entries: IndexEntry[] = []\n for (let attempt = 0; attempt < 20; attempt += 1) {\n entries = (await getIndex(request, token, {})).body.entries ?? []\n if (entries.length >= 2) break\n await new Promise((resolve) => setTimeout(resolve, 1_000))\n }\n if (entries.length < 2) {\n test.skip(true, 'vector index did not reach 2 entries; the embedding pipeline does not produce rows here')\n return\n }\n\n // Default paging metadata, with enough rows to page over.\n const base = await getIndex(request, token, {})\n expect(base.body.limit, 'default limit is 50').toBe(50)\n expect(base.body.offset, 'default offset is 0').toBe(0)\n expect((base.body.entries ?? []).length, 'index has at least two entries to page over').toBeGreaterThanOrEqual(2)\n\n // limit caps the page size and is echoed back.\n const limited = await getIndex(request, token, { limit: '1', offset: '0' })\n expect(limited.body.limit, 'response echoes the requested limit').toBe(1)\n expect(limited.body.entries?.length ?? 0, 'limit=1 returns at most one entry').toBeLessThanOrEqual(1)\n\n // A two-row page returns two DISTINCT records \u2014 proves paging yields\n // distinct rows (keyed on recordId, the stable per-record identifier).\n const pageOfTwo = await getIndex(request, token, { limit: '2', offset: '0' })\n const twoIds = (pageOfTwo.body.entries ?? []).map((entry) => entry.recordId)\n expect(twoIds.length, 'a limit=2 page returns two rows').toBe(2)\n expect(twoIds[0], 'each paged entry exposes a recordId').toBeTruthy()\n expect(twoIds[1], 'the two paged entries are distinct records').not.toBe(twoIds[0])\n\n // offset advances the window to a different record and is echoed back.\n const page2 = await getIndex(request, token, { limit: '1', offset: '1' })\n expect(page2.body.offset, 'response echoes the requested offset').toBe(1)\n const offset0Id = limited.body.entries?.[0]?.recordId\n const offset1Id = page2.body.entries?.[0]?.recordId\n expect(offset1Id, 'offset=1 returns a record').toBeTruthy()\n expect(offset1Id, 'offset=1 returns a different record than offset=0').not.toBe(offset0Id)\n\n // entityId filter narrows to the requested entity type (and is non-empty,\n // so the uniformity assertion is not vacuous).\n const filtered = await getIndex(request, token, { entityId: COMPANY_ENTITY, limit: '50' })\n expect((filtered.body.entries ?? []).length, 'company entityId filter returns at least our fixtures').toBeGreaterThan(\n 0,\n )\n for (const entry of filtered.body.entries ?? []) {\n expect(entry.entityId, 'entityId filter returns only that entity type').toBe(COMPANY_ENTITY)\n }\n } finally {\n // Vector reindex acquires a lock that its route does NOT release (workers\n // own it), so explicitly cancel to avoid leaving a lock behind.\n if (token) {\n await apiRequest(request, 'POST', '/api/search/embeddings/reindex/cancel', { token }).catch(() => undefined)\n }\n for (const id of companyIds) {\n await deleteEntityIfExists(request, token, '/api/customers/companies', id)\n }\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAoC;AACrD,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB,4BAA4B;AAK3D,MAAM,iBAAiB;AAEvB,eAAe,SACb,SACA,OACA,QACkD;AAClD,QAAM,KAAK,IAAI,gBAAgB,MAAM,EAAE,SAAS;AAChD,QAAM,MAAM,MAAM,WAAW,SAAS,OAAO,oBAAoB,KAAK,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,MAAM,CAAC;AAChG,QAAM,OAA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AAO,MAAM,UAAU,+CAA+C,EAAE,KAAK,cAAc;AAAA,MAC7F;AAAA,IACF,UAAE;AAGA,UAAI,OAAO;AACT,cAAM,WAAW,SAAS,QAAQ,yCAAyC,EAAE,MAAM,CAAC,EAAE,MAAM,MAAM,MAAS;AAAA,MAC7G;AACA,iBAAW,MAAM,YAAY;AAC3B,cAAM,qBAAqB,SAAS,OAAO,4BAA4B,EAAE;AAAA,MAC3E;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
@@ -0,0 +1,54 @@
1
+ import { expect, test } from "@playwright/test";
2
+ import { apiRequest, getAuthToken } from "@open-mercato/core/helpers/integration/api";
3
+ import { readJsonSafe } from "@open-mercato/core/helpers/integration/generalFixtures";
4
+ import {
5
+ createCompanyFixture,
6
+ createPersonFixture,
7
+ deleteEntityIfExists
8
+ } from "@open-mercato/core/helpers/integration/crmFixtures";
9
+ const COMPANY_ENTITY = "customers:customer_company_profile";
10
+ const PERSON_ENTITY = "customers:customer_person_profile";
11
+ async function searchResults(request, token, query, entityTypes) {
12
+ const params = new URLSearchParams({ q: query, limit: "20", entityTypes });
13
+ const res = await apiRequest(request, "GET", `/api/search/search?${params.toString()}`, { token });
14
+ if (!res.ok()) return [];
15
+ const body = await readJsonSafe(res) ?? {};
16
+ return Array.isArray(body.results) ? body.results : [];
17
+ }
18
+ test.describe("TC-SEARCH-009: search entityTypes filter isolates entity types", () => {
19
+ test("filtering by company / person type returns only that type", async ({ request }) => {
20
+ test.slow();
21
+ const stamp = Date.now();
22
+ const unique = `QASRCH009${stamp}`;
23
+ let token = null;
24
+ let companyId = null;
25
+ let personId = null;
26
+ try {
27
+ token = await getAuthToken(request, "admin");
28
+ companyId = await createCompanyFixture(request, token, `${unique} Co`);
29
+ personId = await createPersonFixture(request, token, {
30
+ firstName: "QA",
31
+ lastName: `S9 ${stamp}`,
32
+ displayName: `${unique} Person`
33
+ });
34
+ await expect.poll(
35
+ async () => {
36
+ const results = await searchResults(request, token, unique, COMPANY_ENTITY);
37
+ return results.length > 0 && results.every((r) => r.entityId === COMPANY_ENTITY);
38
+ },
39
+ { timeout: 15e3 }
40
+ ).toBe(true);
41
+ await expect.poll(
42
+ async () => {
43
+ const results = await searchResults(request, token, unique, PERSON_ENTITY);
44
+ return results.length > 0 && results.every((r) => r.entityId === PERSON_ENTITY);
45
+ },
46
+ { timeout: 15e3 }
47
+ ).toBe(true);
48
+ } finally {
49
+ await deleteEntityIfExists(request, token, "/api/customers/people", personId);
50
+ await deleteEntityIfExists(request, token, "/api/customers/companies", companyId);
51
+ }
52
+ });
53
+ });
54
+ //# sourceMappingURL=TC-SEARCH-009.spec.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/modules/search/__integration__/TC-SEARCH-009.spec.ts"],
4
+ "sourcesContent": ["import { expect, test, type APIRequestContext } from '@playwright/test'\nimport { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'\nimport { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'\nimport {\n createCompanyFixture,\n createPersonFixture,\n deleteEntityIfExists,\n} from '@open-mercato/core/helpers/integration/crmFixtures'\n\ntype SearchResultItem = { entityId?: string; presenter?: { title?: string } | null }\ntype SearchResponse = { results?: SearchResultItem[] }\n\nconst COMPANY_ENTITY = 'customers:customer_company_profile'\nconst PERSON_ENTITY = 'customers:customer_person_profile'\n\nasync function searchResults(\n request: APIRequestContext,\n token: string,\n query: string,\n entityTypes: string,\n): Promise<SearchResultItem[]> {\n const params = new URLSearchParams({ q: query, limit: '20', entityTypes })\n const res = await apiRequest(request, 'GET', `/api/search/search?${params.toString()}`, { token })\n if (!res.ok()) return []\n const body = (await readJsonSafe<SearchResponse>(res)) ?? {}\n return Array.isArray(body.results) ? body.results : []\n}\n\n/**\n * TC-SEARCH-009: search entityTypes filter isolates entity types\n * Source: issue #2483.\n *\n * Creates a company and a person that share a unique token in their searchable\n * text, then asserts that filtering by entity type returns only that type. Token\n * search (PostgreSQL) is always available; indexing is asynchronous, so results\n * are polled. The unique query token only matches these two fixtures, so a\n * type-filtered response that is non-empty AND uniform proves the filter holds.\n */\ntest.describe('TC-SEARCH-009: search entityTypes filter isolates entity types', () => {\n test('filtering by company / person type returns only that type', async ({ request }) => {\n test.slow()\n\n const stamp = Date.now()\n const unique = `QASRCH009${stamp}`\n let token: string | null = null\n let companyId: string | null = null\n let personId: string | null = null\n\n try {\n token = await getAuthToken(request, 'admin')\n\n companyId = await createCompanyFixture(request, token, `${unique} Co`)\n personId = await createPersonFixture(request, token, {\n firstName: 'QA',\n lastName: `S9 ${stamp}`,\n displayName: `${unique} Person`,\n })\n\n // Company-type filter: results appear and every hit is a company.\n await expect\n .poll(\n async () => {\n const results = await searchResults(request, token!, unique, COMPANY_ENTITY)\n return results.length > 0 && results.every((r) => r.entityId === COMPANY_ENTITY)\n },\n { timeout: 15_000 },\n )\n .toBe(true)\n\n // Person-type filter: results appear and every hit is a person (no company leaks in).\n await expect\n .poll(\n async () => {\n const results = await searchResults(request, token!, unique, PERSON_ENTITY)\n return results.length > 0 && results.every((r) => r.entityId === PERSON_ENTITY)\n },\n { timeout: 15_000 },\n )\n .toBe(true)\n } finally {\n await deleteEntityIfExists(request, token, '/api/customers/people', personId)\n await deleteEntityIfExists(request, token, '/api/customers/companies', companyId)\n }\n })\n})\n"],
5
+ "mappings": "AAAA,SAAS,QAAQ,YAAoC;AACrD,SAAS,YAAY,oBAAoB;AACzC,SAAS,oBAAoB;AAC7B;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAKP,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;AAEtB,eAAe,cACb,SACA,OACA,OACA,aAC6B;AAC7B,QAAM,SAAS,IAAI,gBAAgB,EAAE,GAAG,OAAO,OAAO,MAAM,YAAY,CAAC;AACzE,QAAM,MAAM,MAAM,WAAW,SAAS,OAAO,sBAAsB,OAAO,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC;A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EACF,CAAC;AACH,CAAC;",
6
+ "names": []
7
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-mercato/search",
3
- "version": "0.6.5-develop.4516.1.88e6ab71a9",
3
+ "version": "0.6.5-develop.4544.1.71c003c861",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "exports": {
@@ -126,9 +126,9 @@
126
126
  "zod": "^4.4.3"
127
127
  },
128
128
  "peerDependencies": {
129
- "@open-mercato/core": "0.6.5-develop.4516.1.88e6ab71a9",
130
- "@open-mercato/queue": "0.6.5-develop.4516.1.88e6ab71a9",
131
- "@open-mercato/shared": "0.6.5-develop.4516.1.88e6ab71a9"
129
+ "@open-mercato/core": "0.6.5-develop.4544.1.71c003c861",
130
+ "@open-mercato/queue": "0.6.5-develop.4544.1.71c003c861",
131
+ "@open-mercato/shared": "0.6.5-develop.4544.1.71c003c861"
132
132
  },
133
133
  "devDependencies": {
134
134
  "@types/jest": "^30.0.0",
@@ -0,0 +1,102 @@
1
+ import { expect, test } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+ import {
5
+ createRoleFixture,
6
+ createUserFixture,
7
+ deleteRoleIfExists,
8
+ deleteUserIfExists,
9
+ setRoleAclFeatures,
10
+ } from '@open-mercato/core/helpers/integration/authFixtures'
11
+
12
+ /**
13
+ * TC-SEARCH-003: Search API requires authentication and feature gates (401/403)
14
+ * Source: issue #2483 (expand `search` integration coverage)
15
+ *
16
+ * Real routes (the `search` module id prefixes every route under /api/search):
17
+ * - GET /api/search/search requireAuth + requireFeatures ['search.view']
18
+ * - POST /api/search/reindex requireAuth + requireFeatures ['search.reindex']
19
+ *
20
+ * The framework route wrapper enforces requireAuth (401) and requireFeatures
21
+ * (403) BEFORE the handler body runs, so these gates hold independently of each
22
+ * route's own inline checks. Seeded role features: admin => search.* ,
23
+ * employee => vector.* only, superadmin => all. A user that holds search.view
24
+ * but NOT search.reindex must therefore be provisioned explicitly to prove the
25
+ * granular reindex gate (employee cannot stand in — it lacks search.view too).
26
+ */
27
+ const VALID_PASSWORD = 'Valid1!Pass'
28
+
29
+ test.describe('TC-SEARCH-003: search API auth & feature gates (401/403)', () => {
30
+ test('gates search.view and search.reindex by authentication and feature', async ({ request }) => {
31
+ test.slow()
32
+
33
+ const stamp = Date.now()
34
+ let adminToken: string | null = null
35
+ let superToken: string | null = null
36
+ let roleId: string | null = null
37
+ let viewerUserId: string | null = null
38
+ const roleName = `qa-search-003-viewer-${stamp}`
39
+ const viewerEmail = `qa-search-003-viewer-${stamp}@acme.com`
40
+
41
+ try {
42
+ // 1. Unauthenticated search => 401. q is non-empty, so only the auth gate
43
+ // can produce a 401 here (the handler's empty-query 400 is unreachable
44
+ // because the framework wrapper denies first).
45
+ const unauthSearch = await request.get('/api/search/search?q=test')
46
+ expect(unauthSearch.status(), 'unauthenticated GET /api/search/search must be 401').toBe(401)
47
+
48
+ // 2. Unauthenticated reindex => 401.
49
+ const unauthReindex = await request.post('/api/search/reindex', { data: {} })
50
+ expect(unauthReindex.status(), 'unauthenticated POST /api/search/reindex must be 401').toBe(401)
51
+
52
+ adminToken = await getAuthToken(request, 'admin')
53
+ const scope = getTokenScope(adminToken)
54
+
55
+ // 3. A user with search.view but NOT search.reindex: search is allowed
56
+ // (never 401/403), reindex is forbidden (403).
57
+ roleId = await createRoleFixture(request, adminToken, { name: roleName, tenantId: scope.tenantId })
58
+ await setRoleAclFeatures(request, adminToken, { roleId, features: ['search.view'] })
59
+ viewerUserId = await createUserFixture(request, adminToken, {
60
+ email: viewerEmail,
61
+ password: VALID_PASSWORD,
62
+ organizationId: scope.organizationId,
63
+ roles: [roleName],
64
+ name: 'QA Search 003 Viewer',
65
+ })
66
+ const viewerToken = await getAuthToken(request, viewerEmail, VALID_PASSWORD)
67
+
68
+ const viewerSearch = await apiRequest(request, 'GET', '/api/search/search?q=qa-search-003', { token: viewerToken })
69
+ expect(viewerSearch.status(), 'viewer with search.view must not be unauthorized on search').not.toBe(401)
70
+ expect(viewerSearch.status(), 'viewer with search.view must not be forbidden on search').not.toBe(403)
71
+ // The search route resolves searchService and returns 200 with results
72
+ // (empty when no strategy returns hits) — it does not 503 here — so a passing
73
+ // gate yields 200.
74
+ expect(viewerSearch.status(), 'search.view passes the gate, so the search succeeds with 200').toBe(200)
75
+
76
+ const viewerReindex = await apiRequest(request, 'POST', '/api/search/reindex', { token: viewerToken, data: {} })
77
+ expect(viewerReindex.status(), 'viewer lacking search.reindex must be forbidden on reindex').toBe(403)
78
+
79
+ // 4. Superadmin can initiate reindex — never blocked by auth/feature gates.
80
+ // useQueue:false makes the route clear its own lock in `finally`, so this
81
+ // leaves no lingering fulltext lock for other tests; scoping to a single
82
+ // entity keeps the synchronous reindex cheap.
83
+ superToken = await getAuthToken(request, 'superadmin')
84
+ const superReindex = await apiRequest(request, 'POST', '/api/search/reindex', {
85
+ token: superToken,
86
+ data: { entityId: 'customers:customer_company_profile', useQueue: false },
87
+ })
88
+ expect(superReindex.status(), 'superadmin reindex must not be unauthorized').not.toBe(401)
89
+ expect(superReindex.status(), 'superadmin reindex must not be forbidden').not.toBe(403)
90
+ expect([200, 503], 'superadmin reindex returns ok (200) or service-unavailable (503)').toContain(
91
+ superReindex.status(),
92
+ )
93
+ } finally {
94
+ // Best-effort: release any fulltext lock, then tear down fixtures.
95
+ if (superToken) {
96
+ await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token: superToken }).catch(() => undefined)
97
+ }
98
+ await deleteUserIfExists(request, adminToken, viewerUserId)
99
+ await deleteRoleIfExists(request, adminToken, roleId)
100
+ }
101
+ })
102
+ })
@@ -0,0 +1,135 @@
1
+ import { expect, test, type APIRequestContext } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { expectId, getTokenScope, readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+ import {
5
+ apiRequestWithSelectedOrg,
6
+ createRoleFixture,
7
+ createUserFixture,
8
+ deleteOrganizationIfExists,
9
+ deleteRoleIfExists,
10
+ deleteUserIfExists,
11
+ setRoleAclFeatures,
12
+ setUserAclVisibility,
13
+ } from '@open-mercato/core/helpers/integration/authFixtures'
14
+ import { createCompanyFixture, deleteEntityIfExists } from '@open-mercato/core/helpers/integration/crmFixtures'
15
+
16
+ type SearchResultItem = { entityId?: string; presenter?: { title?: string } | null }
17
+ type SearchResponse = { results?: SearchResultItem[] }
18
+
19
+ const COMPANY_ENTITY = 'customers:customer_company_profile'
20
+ const VALID_PASSWORD = 'Valid1!Pass'
21
+
22
+ function titleOf(item: SearchResultItem): string {
23
+ const presenter = item?.presenter
24
+ const title = presenter && typeof presenter === 'object' ? (presenter as { title?: unknown }).title : undefined
25
+ return typeof title === 'string' ? title : ''
26
+ }
27
+
28
+ async function searchTitles(request: APIRequestContext, token: string, query: string): Promise<string[]> {
29
+ const params = new URLSearchParams({ q: query, limit: '20', entityTypes: COMPANY_ENTITY })
30
+ const res = await apiRequest(request, 'GET', `/api/search/search?${params.toString()}`, { token })
31
+ if (!res.ok()) return []
32
+ const body = (await readJsonSafe<SearchResponse>(res)) ?? {}
33
+ return (Array.isArray(body.results) ? body.results : []).map(titleOf)
34
+ }
35
+
36
+ /**
37
+ * TC-SEARCH-004: search results are organization-scoped.
38
+ * Source: issue #2483 (P0 — cross-tenant/org isolation).
39
+ *
40
+ * A company created in the admin's home org (orgA) must be invisible to a user
41
+ * confined to a second organization (orgB) in the same tenant, while that user
42
+ * still sees a company that lives in their own org. This exercises the
43
+ * organization scope filter the search route applies. orgB, its scoped user, and
44
+ * orgB's company are provisioned via API as superadmin; the test skips if a
45
+ * second organization cannot be provisioned in this environment.
46
+ */
47
+ test.describe('TC-SEARCH-004: search results are organization-scoped', () => {
48
+ test('a restricted org-B user cannot see org-A companies via search', async ({ request }) => {
49
+ test.slow()
50
+
51
+ const stamp = Date.now()
52
+ const unique = `QASRCH004${stamp}`
53
+ let adminToken: string | null = null
54
+ let superToken: string | null = null
55
+ let orgBId: string | null = null
56
+ let roleId: string | null = null
57
+ let userBId: string | null = null
58
+ let companyAId: string | null = null
59
+ let companyBId: string | null = null
60
+ const roleName = `qa-search-004-${stamp}`
61
+ const userBEmail = `qa-search-004-${stamp}@acme.com`
62
+
63
+ try {
64
+ adminToken = await getAuthToken(request, 'admin')
65
+ superToken = await getAuthToken(request, 'superadmin')
66
+ const adminScope = getTokenScope(adminToken)
67
+
68
+ // Provision a second organization in the admin's tenant (superadmin bypasses
69
+ // the directory create command's tenant-selection enforcement).
70
+ const orgResp = await apiRequest(request, 'POST', '/api/directory/organizations', {
71
+ token: superToken,
72
+ data: { name: `QA Search 004 OrgB ${stamp}`, tenantId: adminScope.tenantId },
73
+ })
74
+ if (orgResp.status() !== 201) {
75
+ test.skip(true, `cannot provision a second organization in this environment (status ${orgResp.status()})`)
76
+ return
77
+ }
78
+ orgBId = expectId((await readJsonSafe<{ id?: string }>(orgResp))?.id, 'organization create returns an id')
79
+
80
+ // Company A in the admin's home org (orgA).
81
+ companyAId = await createCompanyFixture(request, adminToken, `${unique} A`)
82
+
83
+ // Company B placed into orgB via the selected-org cookie (superadmin).
84
+ const companyBResp = await apiRequestWithSelectedOrg(request, 'POST', '/api/customers/companies', {
85
+ token: superToken,
86
+ selectedOrgId: orgBId,
87
+ data: { displayName: `${unique} B` },
88
+ })
89
+ expect(companyBResp.status(), 'create company in orgB should return 201').toBe(201)
90
+ companyBId = expectId((await readJsonSafe<{ id?: string }>(companyBResp))?.id, 'company B returns an id')
91
+
92
+ // A user confined to orgB with search + customers read access.
93
+ roleId = await createRoleFixture(request, adminToken, { name: roleName, tenantId: adminScope.tenantId })
94
+ await setRoleAclFeatures(request, adminToken, { roleId, features: ['search.view', 'customers.*'] })
95
+ userBId = await createUserFixture(request, superToken, {
96
+ email: userBEmail,
97
+ password: VALID_PASSWORD,
98
+ organizationId: orgBId,
99
+ roles: [roleName],
100
+ name: 'QA Search 004 OrgB User',
101
+ })
102
+ await setUserAclVisibility(request, superToken, {
103
+ userId: userBId,
104
+ organizations: [orgBId],
105
+ features: ['search.view', 'customers.*'],
106
+ })
107
+ const userBToken = await getAuthToken(request, userBEmail, VALID_PASSWORD)
108
+ expect(getTokenScope(userBToken).organizationId, 'org-B user is scoped to orgB').toBe(orgBId)
109
+
110
+ // Admin (orgA) can find company A — confirms it is indexed and searchable.
111
+ await expect
112
+ .poll(async () => (await searchTitles(request, adminToken!, unique)).includes(`${unique} A`), {
113
+ timeout: 15_000,
114
+ })
115
+ .toBe(true)
116
+
117
+ // Org-B user can find company B (their own org) — confirms their search works.
118
+ await expect
119
+ .poll(async () => (await searchTitles(request, userBToken, unique)).includes(`${unique} B`), {
120
+ timeout: 15_000,
121
+ })
122
+ .toBe(true)
123
+
124
+ // Org-B user must NOT see company A (cross-org isolation — the P0 assertion).
125
+ const orgBTitles = await searchTitles(request, userBToken, unique)
126
+ expect(orgBTitles, 'org-B user must not see the org-A company').not.toContain(`${unique} A`)
127
+ } finally {
128
+ await deleteEntityIfExists(request, superToken, '/api/customers/companies', companyAId)
129
+ await deleteEntityIfExists(request, superToken, '/api/customers/companies', companyBId)
130
+ await deleteUserIfExists(request, superToken, userBId)
131
+ await deleteRoleIfExists(request, adminToken, roleId)
132
+ await deleteOrganizationIfExists(request, superToken, orgBId)
133
+ }
134
+ })
135
+ })
@@ -0,0 +1,45 @@
1
+ import { expect, test } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+
5
+ /**
6
+ * TC-SEARCH-005: Search validates the query parameter (400)
7
+ * Source: issue #2483.
8
+ *
9
+ * Route: GET /api/search/search (requireFeatures ['search.view']). The handler
10
+ * trims `q` and returns 400 { error: 'Missing query' } when it is empty; a
11
+ * non-empty query is accepted with 200 (empty results when no strategy matches),
12
+ * never 400. All cases authenticate as `admin`, which holds search.view, so the
13
+ * empty-query 400 is produced by the handler rather than the framework gate.
14
+ */
15
+ test.describe('TC-SEARCH-005: search validates the query parameter (400)', () => {
16
+ let token = ''
17
+
18
+ test.beforeAll(async ({ request }) => {
19
+ token = await getAuthToken(request, 'admin')
20
+ })
21
+
22
+ test('missing q returns 400', async ({ request }) => {
23
+ const res = await apiRequest(request, 'GET', '/api/search/search', { token })
24
+ expect(res.status()).toBe(400)
25
+ const body = await readJsonSafe<{ error?: string }>(res)
26
+ expect(typeof body?.error, 'a 400 response carries an error message').toBe('string')
27
+ })
28
+
29
+ test('empty q returns 400', async ({ request }) => {
30
+ const res = await apiRequest(request, 'GET', '/api/search/search?q=', { token })
31
+ expect(res.status()).toBe(400)
32
+ })
33
+
34
+ test('whitespace-only q returns 400', async ({ request }) => {
35
+ const res = await apiRequest(request, 'GET', '/api/search/search?q=%20%20%20', { token })
36
+ expect(res.status()).toBe(400)
37
+ })
38
+
39
+ test('non-empty q is accepted with 200 (not rejected as 400)', async ({ request }) => {
40
+ const res = await apiRequest(request, 'GET', `/api/search/search?q=qa-search-005-${Date.now()}`, { token })
41
+ // The route resolves searchService and returns 200 (empty results when no
42
+ // strategy matches); it does not 503 on this path. So a valid query is a 200.
43
+ expect(res.status(), 'a valid query is accepted with 200').toBe(200)
44
+ })
45
+ })
@@ -0,0 +1,73 @@
1
+ import { expect, test } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+
5
+ type GlobalSearchSettings = { enabledStrategies?: string[] }
6
+ type GlobalSearchUpdate = { ok?: boolean; enabledStrategies?: string[] }
7
+ type GlobalSearchResponse = { strategiesEnabled?: string[] }
8
+
9
+ const DEFAULT_STRATEGIES = ['fulltext', 'vector', 'tokens']
10
+
11
+ /**
12
+ * TC-SEARCH-006: global (Cmd+K) search honors the saved strategy config over a
13
+ * URL override. Source: issue #2483.
14
+ *
15
+ * Routes:
16
+ * - GET/POST /api/search/settings/global-search (POST requires search.manage)
17
+ * - GET /api/search/search/global (ignores any `strategies` URL param)
18
+ *
19
+ * Saves enabledStrategies = ['tokens'], then calls global search with a
20
+ * conflicting ?strategies=fulltext,vector and asserts the response's
21
+ * strategiesEnabled reflects the SAVED config, not the URL. The original config
22
+ * is restored in `finally`. `admin` holds both search.view and search.manage.
23
+ */
24
+ test.describe('TC-SEARCH-006: global search honors saved strategy config over URL override', () => {
25
+ test('persisted enabledStrategies wins over the strategies URL parameter', async ({ request }) => {
26
+ test.slow()
27
+
28
+ let token: string | null = null
29
+ let originalStrategies: string[] | null = null
30
+
31
+ try {
32
+ token = await getAuthToken(request, 'admin')
33
+
34
+ const currentRes = await apiRequest(request, 'GET', '/api/search/settings/global-search', { token })
35
+ expect(currentRes.ok(), 'GET global-search settings should succeed').toBeTruthy()
36
+ const current = (await readJsonSafe<GlobalSearchSettings>(currentRes)) ?? {}
37
+ expect(Array.isArray(current.enabledStrategies), 'settings expose an enabledStrategies array').toBe(true)
38
+ originalStrategies =
39
+ Array.isArray(current.enabledStrategies) && current.enabledStrategies.length > 0
40
+ ? current.enabledStrategies
41
+ : DEFAULT_STRATEGIES
42
+
43
+ const updateRes = await apiRequest(request, 'POST', '/api/search/settings/global-search', {
44
+ token,
45
+ data: { enabledStrategies: ['tokens'] },
46
+ })
47
+ expect(updateRes.status(), 'POST global-search settings should return 200').toBe(200)
48
+ const updated = (await readJsonSafe<GlobalSearchUpdate>(updateRes)) ?? {}
49
+ expect(updated.ok, 'update reports ok').toBe(true)
50
+ expect(updated.enabledStrategies, 'update echoes the saved strategies').toEqual(['tokens'])
51
+
52
+ const globalRes = await apiRequest(
53
+ request,
54
+ 'GET',
55
+ `/api/search/search/global?q=qa-search-006-${Date.now()}&strategies=fulltext,vector`,
56
+ { token },
57
+ )
58
+ expect(globalRes.ok(), 'GET global search should succeed').toBeTruthy()
59
+ const globalBody = (await readJsonSafe<GlobalSearchResponse>(globalRes)) ?? {}
60
+ expect(
61
+ globalBody.strategiesEnabled,
62
+ 'global search must use the saved config (tokens), ignoring the strategies URL override',
63
+ ).toEqual(['tokens'])
64
+ } finally {
65
+ if (token && originalStrategies) {
66
+ await apiRequest(request, 'POST', '/api/search/settings/global-search', {
67
+ token,
68
+ data: { enabledStrategies: originalStrategies },
69
+ }).catch(() => undefined)
70
+ }
71
+ }
72
+ })
73
+ })
@@ -0,0 +1,59 @@
1
+ import { expect, test } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+
5
+ type ReindexLock = {
6
+ type?: string
7
+ action?: string
8
+ startedAt?: string
9
+ elapsedMinutes?: number
10
+ processedCount?: number | null
11
+ totalCount?: number | null
12
+ }
13
+ type ConflictBody = { error?: string; lock?: ReindexLock }
14
+
15
+ /**
16
+ * TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info.
17
+ * Source: issue #2483.
18
+ *
19
+ * Route: POST /api/search/reindex (requireFeatures ['search.reindex']). The route
20
+ * acquires a per-tenant DB lock BEFORE any indexing work and, in queue mode
21
+ * (useQueue:true — the default), does NOT release it in `finally` (workers and
22
+ * the heartbeat own it). So a first call holds the lock and a second call returns
23
+ * 409 with the lock descriptor — independent of whether a fulltext backend is
24
+ * configured, because the lock is taken before the strategy-availability check.
25
+ * Integration specs run serially (workers:1), so no other test contends for the
26
+ * shared lock; it is released in `finally` via the cancel endpoint.
27
+ */
28
+ test.describe('TC-SEARCH-007: concurrent fulltext reindex returns 409 with lock info', () => {
29
+ test('a second reindex while one is active is rejected with 409', async ({ request }) => {
30
+ test.slow()
31
+
32
+ let token: string | null = null
33
+
34
+ try {
35
+ token = await getAuthToken(request, 'admin')
36
+
37
+ // Start from a clean lock state.
38
+ await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)
39
+
40
+ // First reindex acquires (and, in queue mode, holds) the fulltext lock.
41
+ const first = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })
42
+ expect(first.status(), 'first reindex must not hit a pre-existing lock').not.toBe(409)
43
+ expect([200, 503], 'first reindex starts (200) or reports backend unavailable (503)').toContain(first.status())
44
+
45
+ // Second reindex is rejected while the first holds the lock.
46
+ const second = await apiRequest(request, 'POST', '/api/search/reindex', { token, data: { useQueue: true } })
47
+ expect(second.status(), 'a concurrent reindex must be rejected with 409').toBe(409)
48
+ const body = (await readJsonSafe<ConflictBody>(second)) ?? {}
49
+ expect(body.lock?.type, 'the 409 lock descriptor identifies the fulltext lock').toBe('fulltext')
50
+ expect(typeof body.lock?.action, 'the lock reports its action').toBe('string')
51
+ expect(typeof body.lock?.startedAt, 'the lock reports when it started').toBe('string')
52
+ expect(typeof body.lock?.elapsedMinutes, 'the lock reports elapsed minutes').toBe('number')
53
+ } finally {
54
+ if (token) {
55
+ await apiRequest(request, 'POST', '/api/search/reindex/cancel', { token }).catch(() => undefined)
56
+ }
57
+ }
58
+ })
59
+ })
@@ -0,0 +1,124 @@
1
+ import { expect, test, type APIRequestContext } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+ import { createCompanyFixture, deleteEntityIfExists } from '@open-mercato/core/helpers/integration/crmFixtures'
5
+
6
+ type IndexEntry = { entityId?: string; recordId?: string }
7
+ type IndexResponse = { entries?: IndexEntry[]; limit?: number; offset?: number }
8
+
9
+ const COMPANY_ENTITY = 'customers:customer_company_profile'
10
+
11
+ async function getIndex(
12
+ request: APIRequestContext,
13
+ token: string,
14
+ params: Record<string, string>,
15
+ ): Promise<{ status: number; body: IndexResponse }> {
16
+ const qs = new URLSearchParams(params).toString()
17
+ const res = await apiRequest(request, 'GET', `/api/search/index${qs ? `?${qs}` : ''}`, { token })
18
+ const body = res.ok() ? ((await readJsonSafe<IndexResponse>(res)) ?? {}) : {}
19
+ return { status: res.status(), body }
20
+ }
21
+
22
+ /**
23
+ * TC-SEARCH-008: vector index list pagination & entityId filter.
24
+ * Source: issue #2483.
25
+ *
26
+ * Route: GET /api/search/index (requireFeatures ['search.view']) returns the
27
+ * vector-store entries (VectorIndexEntry: entityId, recordId, … — there is no
28
+ * surrogate `id`) with limit/offset paging and an optional entityId filter.
29
+ * Exercising it requires a working embedding pipeline (a provider key AND an
30
+ * applied embedding config that produces indexed rows). When the index is not
31
+ * listable — the endpoint returns 503 (vector strategy unavailable) or 500 (no
32
+ * embedding config / vector table) — this test skips, mirroring how the
33
+ * fulltext-dependent specs skip when Meilisearch is absent. The full pagination
34
+ * contract runs only when the vector index is queryable and rows materialize.
35
+ */
36
+ test.describe('TC-SEARCH-008: vector index list pagination & entityId filter', () => {
37
+ test('paginates entries and filters by entityId', async ({ request }) => {
38
+ test.slow()
39
+
40
+ let token: string | null = null
41
+ const companyIds: string[] = []
42
+ const stamp = Date.now()
43
+
44
+ try {
45
+ token = await getAuthToken(request, 'admin')
46
+
47
+ // The endpoint must be queryable (200). A 503 (vector strategy unavailable)
48
+ // or 500 (no embedding config / vector table) means the index cannot be
49
+ // paginated in this environment — skip rather than fail.
50
+ const probe = await getIndex(request, token, {})
51
+ if (probe.status !== 200) {
52
+ test.skip(true, `vector index is not listable in this environment (status ${probe.status})`)
53
+ return
54
+ }
55
+
56
+ for (let i = 0; i < 3; i += 1) {
57
+ companyIds.push(await createCompanyFixture(request, token, `QASRCH008-${stamp}-${i}`))
58
+ }
59
+
60
+ // Trigger a (queued) vector reindex and wait for rows to materialize.
61
+ await apiRequest(request, 'POST', '/api/search/embeddings/reindex', {
62
+ token,
63
+ data: { entityId: COMPANY_ENTITY },
64
+ }).catch(() => undefined)
65
+
66
+ let entries: IndexEntry[] = []
67
+ for (let attempt = 0; attempt < 20; attempt += 1) {
68
+ entries = (await getIndex(request, token, {})).body.entries ?? []
69
+ if (entries.length >= 2) break
70
+ await new Promise((resolve) => setTimeout(resolve, 1_000))
71
+ }
72
+ if (entries.length < 2) {
73
+ test.skip(true, 'vector index did not reach 2 entries; the embedding pipeline does not produce rows here')
74
+ return
75
+ }
76
+
77
+ // Default paging metadata, with enough rows to page over.
78
+ const base = await getIndex(request, token, {})
79
+ expect(base.body.limit, 'default limit is 50').toBe(50)
80
+ expect(base.body.offset, 'default offset is 0').toBe(0)
81
+ expect((base.body.entries ?? []).length, 'index has at least two entries to page over').toBeGreaterThanOrEqual(2)
82
+
83
+ // limit caps the page size and is echoed back.
84
+ const limited = await getIndex(request, token, { limit: '1', offset: '0' })
85
+ expect(limited.body.limit, 'response echoes the requested limit').toBe(1)
86
+ expect(limited.body.entries?.length ?? 0, 'limit=1 returns at most one entry').toBeLessThanOrEqual(1)
87
+
88
+ // A two-row page returns two DISTINCT records — proves paging yields
89
+ // distinct rows (keyed on recordId, the stable per-record identifier).
90
+ const pageOfTwo = await getIndex(request, token, { limit: '2', offset: '0' })
91
+ const twoIds = (pageOfTwo.body.entries ?? []).map((entry) => entry.recordId)
92
+ expect(twoIds.length, 'a limit=2 page returns two rows').toBe(2)
93
+ expect(twoIds[0], 'each paged entry exposes a recordId').toBeTruthy()
94
+ expect(twoIds[1], 'the two paged entries are distinct records').not.toBe(twoIds[0])
95
+
96
+ // offset advances the window to a different record and is echoed back.
97
+ const page2 = await getIndex(request, token, { limit: '1', offset: '1' })
98
+ expect(page2.body.offset, 'response echoes the requested offset').toBe(1)
99
+ const offset0Id = limited.body.entries?.[0]?.recordId
100
+ const offset1Id = page2.body.entries?.[0]?.recordId
101
+ expect(offset1Id, 'offset=1 returns a record').toBeTruthy()
102
+ expect(offset1Id, 'offset=1 returns a different record than offset=0').not.toBe(offset0Id)
103
+
104
+ // entityId filter narrows to the requested entity type (and is non-empty,
105
+ // so the uniformity assertion is not vacuous).
106
+ const filtered = await getIndex(request, token, { entityId: COMPANY_ENTITY, limit: '50' })
107
+ expect((filtered.body.entries ?? []).length, 'company entityId filter returns at least our fixtures').toBeGreaterThan(
108
+ 0,
109
+ )
110
+ for (const entry of filtered.body.entries ?? []) {
111
+ expect(entry.entityId, 'entityId filter returns only that entity type').toBe(COMPANY_ENTITY)
112
+ }
113
+ } finally {
114
+ // Vector reindex acquires a lock that its route does NOT release (workers
115
+ // own it), so explicitly cancel to avoid leaving a lock behind.
116
+ if (token) {
117
+ await apiRequest(request, 'POST', '/api/search/embeddings/reindex/cancel', { token }).catch(() => undefined)
118
+ }
119
+ for (const id of companyIds) {
120
+ await deleteEntityIfExists(request, token, '/api/customers/companies', id)
121
+ }
122
+ }
123
+ })
124
+ })
@@ -0,0 +1,85 @@
1
+ import { expect, test, type APIRequestContext } from '@playwright/test'
2
+ import { apiRequest, getAuthToken } from '@open-mercato/core/helpers/integration/api'
3
+ import { readJsonSafe } from '@open-mercato/core/helpers/integration/generalFixtures'
4
+ import {
5
+ createCompanyFixture,
6
+ createPersonFixture,
7
+ deleteEntityIfExists,
8
+ } from '@open-mercato/core/helpers/integration/crmFixtures'
9
+
10
+ type SearchResultItem = { entityId?: string; presenter?: { title?: string } | null }
11
+ type SearchResponse = { results?: SearchResultItem[] }
12
+
13
+ const COMPANY_ENTITY = 'customers:customer_company_profile'
14
+ const PERSON_ENTITY = 'customers:customer_person_profile'
15
+
16
+ async function searchResults(
17
+ request: APIRequestContext,
18
+ token: string,
19
+ query: string,
20
+ entityTypes: string,
21
+ ): Promise<SearchResultItem[]> {
22
+ const params = new URLSearchParams({ q: query, limit: '20', entityTypes })
23
+ const res = await apiRequest(request, 'GET', `/api/search/search?${params.toString()}`, { token })
24
+ if (!res.ok()) return []
25
+ const body = (await readJsonSafe<SearchResponse>(res)) ?? {}
26
+ return Array.isArray(body.results) ? body.results : []
27
+ }
28
+
29
+ /**
30
+ * TC-SEARCH-009: search entityTypes filter isolates entity types
31
+ * Source: issue #2483.
32
+ *
33
+ * Creates a company and a person that share a unique token in their searchable
34
+ * text, then asserts that filtering by entity type returns only that type. Token
35
+ * search (PostgreSQL) is always available; indexing is asynchronous, so results
36
+ * are polled. The unique query token only matches these two fixtures, so a
37
+ * type-filtered response that is non-empty AND uniform proves the filter holds.
38
+ */
39
+ test.describe('TC-SEARCH-009: search entityTypes filter isolates entity types', () => {
40
+ test('filtering by company / person type returns only that type', async ({ request }) => {
41
+ test.slow()
42
+
43
+ const stamp = Date.now()
44
+ const unique = `QASRCH009${stamp}`
45
+ let token: string | null = null
46
+ let companyId: string | null = null
47
+ let personId: string | null = null
48
+
49
+ try {
50
+ token = await getAuthToken(request, 'admin')
51
+
52
+ companyId = await createCompanyFixture(request, token, `${unique} Co`)
53
+ personId = await createPersonFixture(request, token, {
54
+ firstName: 'QA',
55
+ lastName: `S9 ${stamp}`,
56
+ displayName: `${unique} Person`,
57
+ })
58
+
59
+ // Company-type filter: results appear and every hit is a company.
60
+ await expect
61
+ .poll(
62
+ async () => {
63
+ const results = await searchResults(request, token!, unique, COMPANY_ENTITY)
64
+ return results.length > 0 && results.every((r) => r.entityId === COMPANY_ENTITY)
65
+ },
66
+ { timeout: 15_000 },
67
+ )
68
+ .toBe(true)
69
+
70
+ // Person-type filter: results appear and every hit is a person (no company leaks in).
71
+ await expect
72
+ .poll(
73
+ async () => {
74
+ const results = await searchResults(request, token!, unique, PERSON_ENTITY)
75
+ return results.length > 0 && results.every((r) => r.entityId === PERSON_ENTITY)
76
+ },
77
+ { timeout: 15_000 },
78
+ )
79
+ .toBe(true)
80
+ } finally {
81
+ await deleteEntityIfExists(request, token, '/api/customers/people', personId)
82
+ await deleteEntityIfExists(request, token, '/api/customers/companies', companyId)
83
+ }
84
+ })
85
+ })