// WF-P8 S02 "Bestehende Firma / Kontakt durchsuchen" — loader-only JSON resource // behind the search field of the add-contact dialog. // // Its own resource route on purpose: the detail loader assembles the whole // project (contacts, addresses, members, KWP, documents), and re-running that on // every keystroke to look up a name would be absurd. The dialog fetches here // instead, so the search costs one contact query. // // Reads go through the CRM's own context and permission, not the project's: the // result is contact data, and who may see which contact is P6's rule // (`crm.read_all` vs. the owner scope inside listKontakteForBrowser). import type { LoaderFunctionArgs } from "react-router"; import { buildKontaktDisplayName } from "@hivegrid/view-models"; import { loadCrmContext, notFoundResponse, requireCrmPermission } from "~/utils/integrations/crm/crmAccess.server"; import { listKontakteForBrowser } from "~/utils/integrations/crm/crmService.server"; /** Enough rows to pick from, few enough to stay a single cheap query. */ const RESULT_LIMIT = 20; export async function loader({ request, params }: LoaderFunctionArgs): Promise { const ctx = await loadCrmContext({ request, params }); // Same gate the contact list uses: `crm.read_own` is the base read permission, // and the owner scope inside listKontakteForBrowser narrows the rows from there. // A missing permission reads as "not found", like everywhere else (A.5.3). try { requireCrmPermission(ctx, "crm.read_own"); } catch { throw notFoundResponse(); } const url = new URL(request.url); const search = url.searchParams.get("q")?.trim() ?? ""; // An empty query returns the newest contacts rather than nothing: opening the // dialog should show something to click, not an empty box. const result = await listKontakteForBrowser({ tenantId: ctx.tenantId, ctx, filter: { search: search || null, includeDemoData: true }, limit: RESULT_LIMIT, }); return Response.json( { rows: result.rows.map((kontakt) => ({ id: kontakt.id, label: buildKontaktDisplayName(kontakt), kontaktTyp: kontakt.kontaktTyp, email: kontakt.primaerEmail ?? null, })), total: result.total, }, { headers: { "Cache-Control": "private, no-store" } } ); }