Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/app.$tenant/contacts.admin.duplicates.tsx
T
2026-07-08 16:15:37 +02:00

138 lines
6.2 KiB
TypeScript

// 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<string>();
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<LoaderData>();
if (!moduleActive) {
return (
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.crm.admin.duplicates">
<div className="mt-10 text-center">
<p className="text-foreground font-medium">{t("crm.locked.headline")}</p>
<p className="text-muted-foreground mt-1 text-sm">{t("crm.locked.body")}</p>
</div>
</main>
);
}
return (
<main className="mx-auto max-w-5xl px-4 py-10" data-ui-id="ui.crm.admin.duplicates">
<h1 className="text-foreground text-xl font-semibold">{t("crm.admin.duplicates.title")}</h1>
<p className="text-muted-foreground mt-1 text-sm">{t("crm.admin.duplicates.subtitle")}</p>
{vm.status !== "ready" || !vm.data || vm.data.pairs.length === 0 ? (
<p className="text-muted-foreground mt-6 text-sm" data-ui-id="ui.crm.admin.duplicates.empty">
{t("crm.admin.duplicates.empty")}
</p>
) : (
<ul className="mt-6 space-y-4" data-ui-id="ui.crm.admin.duplicates.list">
{vm.data.pairs.map((pair, index) => (
<li key={`${pair.a.id}-${pair.b.id}-${index}`} className="border-border rounded border p-3" data-row-id={`${pair.a.id}-${pair.b.id}`}>
<p className="text-muted-foreground text-xs">
{t(`crm.duplicate.matchType.${pair.matchType}`)} · {t(pair.matchReasonKey)}
</p>
<div className="mt-2 grid gap-3 sm:grid-cols-2">
{[pair.a, pair.b].map((card) => (
<div key={card.id} className="border-border rounded border p-2 text-sm">
<a href={contactDetailPath(tenantSlug, card.id)} className="text-theme-600 font-medium">
{card.displayName}
</a>
<p className="text-muted-foreground text-xs">{t(card.statusLabelKey)}</p>
{card.primaerEmail ? <p>{card.primaerEmail}</p> : null}
{card.primaerTelefon ? <p>{card.primaerTelefon}</p> : null}
{card.zustaendigerLabel ? <p className="text-muted-foreground text-xs">{card.zustaendigerLabel}</p> : null}
</div>
))}
</div>
</li>
))}
</ul>
)}
</main>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: CRM_MODULE_KEY };