// 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 LoaderFunctionArgs, useLoaderData } from "react-router"; import { useTranslation } from "react-i18next"; import { buildDuplicateVM, type DuplicatePairSource, type DuplicateVM } from "@hivegrid/view-models"; import { getTranslations } from "~/locale/i18next.server"; import { loadCrmContext, notFoundResponse, requireCrmPermission, type CrmVisibilityContext } from "~/utils/integrations/crm/crmAccess.server"; import { findDuplicateKontakte, listKontakteForCsv, resolveUserLabels, type KontaktRow } from "~/utils/integrations/crm/crmService.server"; import { contactDetailPath, CRM_MODULE_KEY } from "~/utils/integrations/crm/crmRoutePaths"; import ServerError from "~/components/ui/errors/ServerError"; const MAX_SCAN = 200; type LoaderData = { title: string; moduleActive: boolean; vm: DuplicateVM; tenantSlug: string }; 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}`; if (!ctx.hasModule) { return Response.json({ title, moduleActive: false, vm: buildDuplicateVM({ pairs: [], userLabels: new Map(), canMerge: false, tenantSlug }), tenantSlug } satisfies LoaderData); } try { requireCrmPermission(ctx, "crm.admin"); } catch { throw notFoundResponse(); } // 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 } satisfies LoaderData); }; export default function DuplicatesAdminRoute() { const { t } = useTranslation(); const { moduleActive, vm, tenantSlug } = useLoaderData(); if (!moduleActive) { return (

{t("crm.locked.headline")}

{t("crm.locked.body")}

); } return (

{t("crm.admin.duplicates.title")}

{t("crm.admin.duplicates.subtitle")}

{vm.status !== "ready" || !vm.data || vm.data.pairs.length === 0 ? (

{t("crm.admin.duplicates.empty")}

) : (
    {vm.data.pairs.map((pair, index) => (
  • {t(`crm.duplicate.matchType.${pair.matchType}`)} · {t(pair.matchReasonKey)}

    {[pair.a, pair.b].map((card) => (
    {card.displayName}

    {t(card.statusLabelKey)}

    {card.primaerEmail ?

    {card.primaerEmail}

    : null} {card.primaerTelefon ?

    {card.primaerTelefon}

    : null} {card.zustaendigerLabel ?

    {card.zustaendigerLabel}

    : null}
    ))}
  • ))}
)}
); } export function ErrorBoundary() { return ; } export const handle = { moduleKey: CRM_MODULE_KEY };