// R-P6 (P6 CRM core, Variante A) — duplicate tool (`/contacts/admin/duplicates`). // Scans the tenant's contacts and renders the duplicate candidate pairs // side-by-side (DoD 4 surface). Read-only here — the actual merge lands in a later // phase (the VM exposes `canMerge`, kept false). Gated on crm.admin (missing -> 404). import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useLoaderData, useNavigation, useSubmit } from "react-router"; import { buildDuplicateVM, type DuplicatePairSource, type DuplicateVM } from "@hivegrid/view-models"; import { getTranslations } from "~/locale/i18next.server"; import { badRequestResponse, crmActionErrorResponse, loadCrmContext, notFoundResponse, requireCrmPermission, type CrmVisibilityContext, } from "~/utils/integrations/crm/crmAccess.server"; import { findDuplicateKontakte, getVisibleKontaktOrThrow, hardDeleteKontakt, listKontakteForCsv, resolveUserLabels, type KontaktRow } from "~/utils/integrations/crm/crmService.server"; import { auditCrmEvent } from "~/utils/integrations/crm/crmAudit.server"; import { contactDetailPath, contactsPath, CRM_MODULE_KEY, duplicatesAdminPath } from "~/utils/integrations/crm/crmRoutePaths"; import { DuplicateToolPage } from "~/components/screens/crm/DuplicateToolPage"; import ServerError from "~/components/ui/errors/ServerError"; const MAX_SCAN = 200; type BreadcrumbAncestor = { label: string; href: string }; type LoaderData = { title: string; moduleActive: boolean; vm: DuplicateVM; tenantSlug: string; canDelete: boolean; breadcrumbAncestors: BreadcrumbAncestor[]; }; function hardReason(a: KontaktRow, b: KontaktRow): string { if (a.primaerEmail && b.primaerEmail && a.primaerEmail.toLowerCase() === b.primaerEmail.toLowerCase()) { return "email"; } if (a.primaerTelefon && b.primaerTelefon && a.primaerTelefon === b.primaerTelefon) { return "telefon"; } return "email"; } export const loader = async ({ request, params }: LoaderFunctionArgs) => { const { t } = await getTranslations(request); const ctx = await loadCrmContext({ request, params }); const tenantSlug = params.tenant ?? ""; const title = `${t("crm.admin.duplicates.title")} | ${process.env.APP_NAME}`; // Flat routes give this admin page no shared "Kontakte" layout to hang a crumb // on, so name the list page it is reached through explicitly. const breadcrumbAncestors = [{ label: t("crm.contacts.title"), href: contactsPath(tenantSlug) }]; if (!ctx.hasModule) { return Response.json({ title, moduleActive: false, vm: buildDuplicateVM({ pairs: [], userLabels: new Map(), canMerge: false, tenantSlug }), tenantSlug, canDelete: false, breadcrumbAncestors } satisfies LoaderData); } try { requireCrmPermission(ctx, "crm.admin"); } catch { throw notFoundResponse(); } const canDelete = ctx.permissions.includes("crm.delete"); // The duplicate tool is tenant-wide: an admin scans every contact, so the scan // runs with read_all visibility (findDuplicateKontakte itself is not owner-scoped). const adminCtx: CrmVisibilityContext = { userId: ctx.userId, permissions: [...ctx.permissions, "crm.read_all"] }; const contacts = (await listKontakteForCsv({ tenantId: ctx.tenantId, ctx: adminCtx, sort: { field: "createdAt", dir: "desc" } })).slice(0, MAX_SCAN); const seen = new Set(); const pairs: DuplicatePairSource[] = []; for (const a of contacts) { const { hard, soft } = await findDuplicateKontakte({ tenantId: ctx.tenantId, email: a.primaerEmail, telefon: a.primaerTelefon, vorname: a.vorname, nachname: a.nachname, orgName: a.orgName, excludeKontaktId: a.id, }); for (const b of hard) { const key = [a.id, b.id].sort().join("|"); if (seen.has(key)) continue; seen.add(key); pairs.push({ matchType: "hard", matchReason: hardReason(a, b), a, b }); } for (const b of soft) { const key = [a.id, b.id].sort().join("|"); if (seen.has(key)) continue; seen.add(key); pairs.push({ matchType: "soft", matchReason: a.kontaktTyp === "organisation" ? "orgName" : "name", a, b }); } } const allIds = pairs.flatMap((pair) => [pair.a.zustaendigerUserId, pair.b.zustaendigerUserId]).filter((id): id is string => Boolean(id)); const userLabels = await resolveUserLabels(allIds); const vm = buildDuplicateVM({ pairs, userLabels, canMerge: false, tenantSlug }); return Response.json({ title, moduleActive: true, vm, tenantSlug, canDelete, breadcrumbAncestors } satisfies LoaderData); }; export const action = async ({ request, params }: ActionFunctionArgs) => { const ctx = await loadCrmContext({ request, params, requireModule: true }); const tenantSlug = params.tenant ?? ""; const form = await request.formData(); const intent = form.get("intent")?.toString(); try { if (intent === "delete") { // Hard delete is the most destructive CRM op, so it needs crm.delete on top // of the crm.admin gate that guards the whole duplicate tool. requireCrmPermission(ctx, "crm.delete"); const kontaktId = form.get("kontaktId")?.toString().trim(); if (!kontaktId) { throw badRequestResponse(); } // Enforce owner visibility (404 for a contact the operator cannot see). await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx); await hardDeleteKontakt({ tenantId: ctx.tenantId, kontaktId }); await auditCrmEvent({ ctx, action: "kontakt.deleted", targetType: "kontakt", targetId: kontaktId, metadata: { source: "duplicates" } }); return redirect(`${duplicatesAdminPath(tenantSlug)}?toast=${encodeURIComponent("crm.toast.duplicateDeleted")}`); } throw badRequestResponse(); } catch (error) { if (error instanceof Response) { throw error; } return crmActionErrorResponse(error); } }; export default function DuplicatesAdminRoute() { const { moduleActive, vm, tenantSlug, canDelete } = useLoaderData(); const submit = useSubmit(); const navigation = useNavigation(); return ( contactDetailPath(tenantSlug, kontaktId)} canDelete={canDelete} submitting={navigation.state !== "idle"} actions={{ onDelete: (kontaktId) => { const formData = new FormData(); formData.set("intent", "delete"); formData.set("kontaktId", kontaktId); submit(formData, { method: "post" }); }, }} /> ); } export function ErrorBoundary() { return ; } export const handle = { moduleKey: CRM_MODULE_KEY };