370 lines
16 KiB
TypeScript
370 lines
16 KiB
TypeScript
// R-P6 (P6 CRM core, Variante A) — shared loader/action for the contact detail
|
|
// (`/contacts/:id`) and the organisation detail (`/contacts/companies/:id`).
|
|
// Both render the SAME server-built KontaktDetailVM + ActivityStreamVM and share
|
|
// the inline-edit intents (DoD 3); the only per-route difference is the back
|
|
// link / breadcrumb root. Server-only (.server) — never imported by a component.
|
|
//
|
|
// Every write intent is audited (DoD 13, via crmAudit.auditCrmEvent) and, when
|
|
// contact-relevant, appends an Activity-Stream entry (DoD 14, logKontaktActivity).
|
|
|
|
import { redirect } from "react-router";
|
|
import type { JsonValue } from "@hivegrid/foundation";
|
|
import {
|
|
buildActivityStreamVM,
|
|
buildKontaktDetailVM,
|
|
datentypLabelKey,
|
|
type ActivityStreamVM,
|
|
type KontaktDetailVM,
|
|
} from "@hivegrid/view-models";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { withTenantRLS } from "~/utils/db/.server/tenantRls.server";
|
|
import {
|
|
badRequestResponse,
|
|
crmActionErrorResponse,
|
|
loadCrmContext,
|
|
notFoundResponse,
|
|
requireCrmPermission,
|
|
type CrmRouteContext,
|
|
} from "./crmAccess.server";
|
|
import {
|
|
addKontaktEmail,
|
|
addKontaktRelation,
|
|
addKontaktTelefon,
|
|
archiveKontakt,
|
|
getKontaktDetail,
|
|
getVisibleKontaktOrThrow,
|
|
hardDeleteKontakt,
|
|
listAssignableUsers,
|
|
reactivateKontakt,
|
|
reassignKontakt,
|
|
removeKontaktEmail,
|
|
removeKontaktRelation,
|
|
removeKontaktTelefon,
|
|
resolveUserLabels,
|
|
setPrimaryEmail,
|
|
setPrimaryTelefon,
|
|
updateKontakt,
|
|
type KontaktArt,
|
|
type KontaktRow,
|
|
type KontaktStatus,
|
|
type OrgMerkmal,
|
|
} from "./crmService.server";
|
|
import { getCustomFieldValues, listCustomFieldDefinitions, setCustomFieldValue } from "./customFieldService.server";
|
|
import { assignTag, listTags, listTagsForEntity, unassignTag } from "./tagService.server";
|
|
import { auditCrmEvent, logKontaktActivity } from "./crmAudit.server";
|
|
import { companiesPath, contactDetailPath, contactsPath, companyDetailPath } from "./crmRoutePaths";
|
|
import { maskEmailActivitiesForViewer } from "~/modules/emailInbox/services/emailActivityMasking.server";
|
|
|
|
const KONTAKT_CUSTOM_FIELD_ENTITY = "kontakt";
|
|
const KONTAKT_TAG_ENTITY_TYPE = "kontakt";
|
|
const ACTIVITY_LIMIT = 50;
|
|
|
|
export type KontaktDetailVariant = "contacts" | "companies";
|
|
|
|
export type CustomFieldDefOption = { id: string; key: string; label: string; datentyp: string; datentypLabelKey: string };
|
|
|
|
export type KontaktDetailLoaderData = {
|
|
title: string;
|
|
variant: KontaktDetailVariant;
|
|
backHref: string;
|
|
listLabelKey: string;
|
|
detailVM: KontaktDetailVM;
|
|
activityVM: ActivityStreamVM;
|
|
allTags: { id: string; name: string; farbe: string }[];
|
|
customFieldDefs: CustomFieldDefOption[];
|
|
ownerOptions: { id: string; label: string }[];
|
|
};
|
|
|
|
type ActivityDbRow = {
|
|
id: string;
|
|
createdAt: Date;
|
|
actorUserId: string | null;
|
|
actorKind: string;
|
|
activityType: string;
|
|
summaryText: string;
|
|
metadata?: unknown;
|
|
};
|
|
|
|
async function loadKontaktActivities(tenantId: string, subjectType: "contact" | "company", subjectId: string): Promise<ActivityDbRow[]> {
|
|
// No read helper is exported from @hivegrid/activity yet — load the per-entity
|
|
// timeline tenant-scoped (RLS GUC set by withTenantRLS), newest first.
|
|
// `metadata` is selected ONLY for the email-visibility masking (VA-P23) and
|
|
// never reaches the VM.
|
|
const rows = await withTenantRLS(tenantId, (tx) =>
|
|
tx.activity.findMany({
|
|
where: { tenantId, subjectType, subjectId },
|
|
orderBy: { createdAt: "desc" },
|
|
take: ACTIVITY_LIMIT + 1,
|
|
select: { id: true, createdAt: true, actorUserId: true, actorKind: true, activityType: true, summaryText: true, metadata: true },
|
|
}),
|
|
);
|
|
return rows as ActivityDbRow[];
|
|
}
|
|
|
|
export async function loadKontaktDetailData(args: {
|
|
request: Request;
|
|
params: Record<string, string | undefined>;
|
|
variant: KontaktDetailVariant;
|
|
}): Promise<KontaktDetailLoaderData> {
|
|
const { t } = await getTranslations(args.request);
|
|
const ctx = await loadCrmContext({ request: args.request, params: args.params });
|
|
const tenantSlug = args.params.tenant ?? "";
|
|
const kontaktId = args.params.id ?? "";
|
|
|
|
if (!ctx.hasModule) {
|
|
throw notFoundResponse();
|
|
}
|
|
try {
|
|
requireCrmPermission(ctx, "crm.read_own");
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
|
|
let detail;
|
|
try {
|
|
detail = await getKontaktDetail(ctx.tenantId, kontaktId, ctx);
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
const subjectType = detail.kontakt.kontaktTyp === "organisation" ? "company" : "contact";
|
|
|
|
const [customFields, tags, definitions, allTags, ownerOptions, activityRows] = await Promise.all([
|
|
getCustomFieldValues({ tenantId: ctx.tenantId, entityType: KONTAKT_CUSTOM_FIELD_ENTITY, entityId: kontaktId }),
|
|
listTagsForEntity({ tenantId: ctx.tenantId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId }),
|
|
listCustomFieldDefinitions({ tenantId: ctx.tenantId, entityType: KONTAKT_CUSTOM_FIELD_ENTITY }),
|
|
listTags(ctx.tenantId),
|
|
listAssignableUsers(ctx.tenantId),
|
|
loadKontaktActivities(ctx.tenantId, subjectType, kontaktId),
|
|
]);
|
|
|
|
const actorIds = activityRows.map((row) => row.actorUserId).filter((id): id is string => Boolean(id));
|
|
const userLabels = await resolveUserLabels([detail.kontakt.zustaendigerUserId, ...actorIds].filter((id): id is string => Boolean(id)));
|
|
|
|
const detailVM = buildKontaktDetailVM({
|
|
detail: {
|
|
kontakt: detail.kontakt,
|
|
emails: detail.emails.map((e) => ({ id: e.id, email: e.email, primaer: e.primaer })),
|
|
telefone: detail.telefone.map((p) => ({ id: p.id, telefon: p.telefon, primaer: p.primaer })),
|
|
relationen: detail.relationen.map((r) => ({ id: r.id, vonKontaktId: r.vonKontaktId, zuKontaktId: r.zuKontaktId, rolle: r.rolle, kontext: r.kontext })),
|
|
adresse: detail.adresse
|
|
? { strasse: detail.adresse.strasse, hausnummer: detail.adresse.hausnummer, plz: detail.adresse.plz, ort: detail.adresse.ort, land: detail.adresse.land }
|
|
: null,
|
|
},
|
|
customFields: customFields.map((cf) => ({
|
|
definition: { id: cf.definition.id, key: cf.definition.key, label: cf.definition.label, datentyp: cf.definition.datentyp, optionen: cf.definition.optionen },
|
|
wert: cf.wert,
|
|
})),
|
|
tags: tags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
|
userLabels,
|
|
perms: { canWrite: ctx.permissions.includes("crm.write"), canDelete: ctx.permissions.includes("crm.delete") },
|
|
tenantSlug,
|
|
});
|
|
|
|
// VA-P23 (M09 Block H): email activities are permission-masked — without
|
|
// email.read_all only the viewer's OWN mailbox activities show details.
|
|
const maskedActivityRows = await maskEmailActivitiesForViewer({
|
|
tenantId: ctx.tenantId,
|
|
userId: ctx.userId,
|
|
permissions: ctx.permissions,
|
|
rows: activityRows,
|
|
maskedText: t("emailInbox.activity.masked"),
|
|
});
|
|
|
|
const activityVM = buildActivityStreamVM({
|
|
rows: maskedActivityRows.slice(0, ACTIVITY_LIMIT).map((row) => ({
|
|
id: row.id,
|
|
createdAt: row.createdAt,
|
|
actorUserId: row.actorUserId,
|
|
actorKind: row.actorKind as never,
|
|
activityType: row.activityType as never,
|
|
summaryText: row.summaryText,
|
|
})),
|
|
userLabels,
|
|
hasMore: activityRows.length > ACTIVITY_LIMIT,
|
|
});
|
|
|
|
const backHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
|
|
|
return {
|
|
title: `${detailVM.data?.displayName ?? t("crm.detail.title")} | ${process.env.APP_NAME}`,
|
|
variant: args.variant,
|
|
backHref,
|
|
listLabelKey: args.variant === "companies" ? "crm.companies.title" : "crm.contacts.title",
|
|
detailVM,
|
|
activityVM,
|
|
allTags: allTags.map((tag) => ({ id: tag.id, name: tag.name, farbe: tag.farbe })),
|
|
customFieldDefs: definitions.map((def) => ({
|
|
id: def.id,
|
|
key: def.key,
|
|
label: def.label,
|
|
datentyp: def.datentyp,
|
|
datentypLabelKey: datentypLabelKey(def.datentyp),
|
|
})),
|
|
ownerOptions,
|
|
};
|
|
}
|
|
|
|
function field(form: FormData, name: string): string {
|
|
return form.get(name)?.toString().trim() ?? "";
|
|
}
|
|
|
|
function optionalField(form: FormData, name: string): string | null {
|
|
const value = form.get(name)?.toString().trim();
|
|
return value ? value : null;
|
|
}
|
|
|
|
export async function handleKontaktDetailAction(args: {
|
|
request: Request;
|
|
params: Record<string, string | undefined>;
|
|
variant: KontaktDetailVariant;
|
|
}): Promise<Response> {
|
|
const ctx: CrmRouteContext = await loadCrmContext({ request: args.request, params: args.params, requireModule: true });
|
|
const tenantSlug = args.params.tenant ?? "";
|
|
const kontaktId = args.params.id ?? "";
|
|
const form = await args.request.formData();
|
|
const intent = form.get("intent")?.toString();
|
|
const detailHref = args.variant === "companies" ? companyDetailPath(tenantSlug, kontaktId) : contactDetailPath(tenantSlug, kontaktId);
|
|
const listHref = args.variant === "companies" ? companiesPath(tenantSlug) : contactsPath(tenantSlug);
|
|
|
|
try {
|
|
// Visibility + type are needed by almost every branch (activity subject).
|
|
const kontakt: KontaktRow = await getVisibleKontaktOrThrow(ctx.tenantId, kontaktId, ctx);
|
|
const typ = kontakt.kontaktTyp;
|
|
|
|
if (intent === "delete") {
|
|
requireCrmPermission(ctx, "crm.delete");
|
|
await hardDeleteKontakt({ tenantId: ctx.tenantId, kontaktId });
|
|
await auditCrmEvent({ ctx, action: "kontakt.deleted", targetType: "kontakt", targetId: kontaktId });
|
|
return redirect(listHref);
|
|
}
|
|
|
|
requireCrmPermission(ctx, "crm.write");
|
|
|
|
switch (intent) {
|
|
case "updateBasics": {
|
|
await updateKontakt({
|
|
tenantId: ctx.tenantId,
|
|
kontaktId,
|
|
kontaktStatus: (optionalField(form, "kontaktStatus") as KontaktStatus | null) ?? undefined,
|
|
vorname: form.has("vorname") ? optionalField(form, "vorname") : undefined,
|
|
nachname: form.has("nachname") ? optionalField(form, "nachname") : undefined,
|
|
orgName: form.has("orgName") ? optionalField(form, "orgName") : undefined,
|
|
orgMerkmal: form.has("orgMerkmal") ? (optionalField(form, "orgMerkmal") as OrgMerkmal | null) : undefined,
|
|
});
|
|
await auditCrmEvent({ ctx, action: "kontakt.updated", targetType: "kontakt", targetId: kontaktId });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Stammdaten aktualisiert" });
|
|
break;
|
|
}
|
|
case "addEmail": {
|
|
await addKontaktEmail({ tenantId: ctx.tenantId, kontaktId, email: field(form, "email"), primaer: form.get("primaer") === "1" });
|
|
await auditCrmEvent({ ctx, action: "kontakt.email_added", targetType: "kontakt", targetId: kontaktId });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "E-Mail hinzugefügt" });
|
|
break;
|
|
}
|
|
case "setPrimaryEmail": {
|
|
await setPrimaryEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
|
|
await auditCrmEvent({ ctx, action: "kontakt.email_primary_set", targetType: "kontakt", targetId: kontaktId });
|
|
break;
|
|
}
|
|
case "removeEmail": {
|
|
await removeKontaktEmail({ tenantId: ctx.tenantId, emailId: field(form, "emailId") });
|
|
await auditCrmEvent({ ctx, action: "kontakt.email_removed", targetType: "kontakt", targetId: kontaktId });
|
|
break;
|
|
}
|
|
case "addTelefon": {
|
|
await addKontaktTelefon({ tenantId: ctx.tenantId, kontaktId, telefon: field(form, "telefon"), primaer: form.get("primaer") === "1" });
|
|
await auditCrmEvent({ ctx, action: "kontakt.telefon_added", targetType: "kontakt", targetId: kontaktId });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Telefonnummer hinzugefügt" });
|
|
break;
|
|
}
|
|
case "setPrimaryTelefon": {
|
|
await setPrimaryTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
|
|
await auditCrmEvent({ ctx, action: "kontakt.telefon_primary_set", targetType: "kontakt", targetId: kontaktId });
|
|
break;
|
|
}
|
|
case "removeTelefon": {
|
|
await removeKontaktTelefon({ tenantId: ctx.tenantId, telefonId: field(form, "telefonId") });
|
|
await auditCrmEvent({ ctx, action: "kontakt.telefon_removed", targetType: "kontakt", targetId: kontaktId });
|
|
break;
|
|
}
|
|
case "addRelation": {
|
|
await addKontaktRelation({
|
|
tenantId: ctx.tenantId,
|
|
vonKontaktId: kontaktId,
|
|
zuKontaktId: field(form, "zuKontaktId"),
|
|
rolle: (field(form, "rolle") || "hauptkontakt") as KontaktArt,
|
|
kontext: optionalField(form, "kontext"),
|
|
});
|
|
await auditCrmEvent({ ctx, action: "kontakt.relation_added", targetType: "kontakt", targetId: kontaktId });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Verknüpfung hinzugefügt" });
|
|
break;
|
|
}
|
|
case "removeRelation": {
|
|
await removeKontaktRelation({ tenantId: ctx.tenantId, relationId: field(form, "relationId") });
|
|
await auditCrmEvent({ ctx, action: "kontakt.relation_removed", targetType: "kontakt", targetId: kontaktId });
|
|
break;
|
|
}
|
|
case "reassign": {
|
|
const owner = field(form, "zustaendigerUserId");
|
|
if (!owner) {
|
|
throw badRequestResponse();
|
|
}
|
|
await reassignKontakt({ tenantId: ctx.tenantId, kontaktId, zustaendigerUserId: owner });
|
|
await auditCrmEvent({ ctx, action: "kontakt.reassigned", targetType: "kontakt", targetId: kontaktId, metadata: { zustaendigerUserId: owner } });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "assignee_changed", summaryText: "Verantwortlicher geändert" });
|
|
break;
|
|
}
|
|
case "addTag": {
|
|
const tagId = field(form, "tagId");
|
|
await assignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
|
|
await auditCrmEvent({ ctx, action: "tag_assignment.assigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_added", summaryText: "Tag zugewiesen" });
|
|
break;
|
|
}
|
|
case "removeTag": {
|
|
const tagId = field(form, "tagId");
|
|
await unassignTag({ tenantId: ctx.tenantId, tagId, entityType: KONTAKT_TAG_ENTITY_TYPE, entityId: kontaktId });
|
|
await auditCrmEvent({ ctx, action: "tag_assignment.unassigned", targetType: "tag_assignment", targetId: kontaktId, metadata: { tagId } });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "tag_removed", summaryText: "Tag entfernt" });
|
|
break;
|
|
}
|
|
case "setCustomField": {
|
|
const wert: JsonValue = field(form, "wert");
|
|
await setCustomFieldValue({ tenantId: ctx.tenantId, definitionId: field(form, "definitionId"), entityType: KONTAKT_CUSTOM_FIELD_ENTITY, entityId: kontaktId, wert });
|
|
await auditCrmEvent({ ctx, action: "custom_field_value.set", targetType: "custom_field_value", targetId: kontaktId, metadata: { definitionId: field(form, "definitionId") } });
|
|
break;
|
|
}
|
|
case "addNote": {
|
|
const note = field(form, "note");
|
|
if (!note) {
|
|
throw badRequestResponse();
|
|
}
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "note_added", summaryText: note });
|
|
await auditCrmEvent({ ctx, action: "kontakt.updated", targetType: "kontakt", targetId: kontaktId, metadata: { note: true } });
|
|
break;
|
|
}
|
|
case "archive": {
|
|
await archiveKontakt({ tenantId: ctx.tenantId, kontaktId });
|
|
await auditCrmEvent({ ctx, action: "kontakt.archived", targetType: "kontakt", targetId: kontaktId });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_archived", summaryText: "Kontakt archiviert" });
|
|
break;
|
|
}
|
|
case "reactivate": {
|
|
await reactivateKontakt({ tenantId: ctx.tenantId, kontaktId });
|
|
await auditCrmEvent({ ctx, action: "kontakt.reactivated", targetType: "kontakt", targetId: kontaktId });
|
|
await logKontaktActivity({ ctx, kontaktId, kontaktTyp: typ, activityType: "contact_updated", summaryText: "Kontakt reaktiviert" });
|
|
break;
|
|
}
|
|
default:
|
|
throw badRequestResponse();
|
|
}
|
|
|
|
return redirect(detailHref);
|
|
} catch (error) {
|
|
if (error instanceof Response) {
|
|
throw error;
|
|
}
|
|
return crmActionErrorResponse(error);
|
|
}
|
|
}
|