Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/app.$tenant/leads.$id.tsx
T

295 lines
13 KiB
TypeScript

import { type ActionFunctionArgs, type LoaderFunctionArgs, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
import { buildLeadDetailVM, type ClickToCallVM, type LeadConvertOptions, type LeadDetailVM } from "@hivegrid/view-models";
import { getTranslations } from "~/locale/i18next.server";
import { loadCrmContext } from "~/utils/integrations/crm/crmAccess.server";
import { listKontakteForBrowser } from "~/utils/integrations/crm/crmService.server";
import { loadProjectContext } from "~/utils/integrations/projects/projectAccess.server";
import { listPipelines } from "~/utils/integrations/projects/projectService.server";
import { loadTelephonyContext } from "~/modules/telephony/routes/telephonyAccess.server";
import { loadTelephonyClickToCallVM, startTelephonyEntityCall, TelephonyServiceError } from "~/modules/telephony/services/TelephonyService.server";
import {
badRequestResponse,
leadActionErrorResponse,
loadLeadContext,
notFoundResponse,
requireLeadPermission,
} from "~/utils/integrations/leads/leadAccess.server";
import { auditLeadEvent, logLeadActivity } from "~/utils/integrations/leads/leadAudit.server";
import { canTransitionLeadStatus } from "~/utils/integrations/leads/leadListQuery";
import { leadsPath, LEADS_MODULE_KEY } from "~/utils/integrations/leads/leadRoutePaths";
import {
completeLeadProjectConversion,
getVisibleLeadOrThrow,
requestLeadProjectConversion,
resolveUserLabels,
setLeadStatus,
updateLead,
type LeadStatus,
type LeadWeiterverarbeitungFreigabe,
} from "~/utils/integrations/leads/leadService.server";
import { createProjectFromQualifiedLead, leadProjectName, ProjectServiceError } from "~/utils/integrations/projects/projectService.server";
import { LeadDetailPage } from "~/components/screens/leads/LeadDetailPage";
import ServerError from "~/components/ui/errors/ServerError";
import { appendCSRFToken } from "~/utils/csrf";
import { validateCSRFToken } from "~/utils/session.server";
import { useSaveToast } from "~/hooks/use-save-toast";
type LoaderData = {
title?: string;
/** Names the inbox the lead was opened from, so the crumb reads "Lead-Inbox"
* and links back there instead of the generic "Leads" nav section. */
breadcrumbAncestors?: { label: string; href: string }[];
vm: LeadDetailVM;
clickToCallVM: ClickToCallVM;
};
const STATUS_VALUES = new Set<LeadStatus>(["new", "qualified", "converted", "lost", "spam"]);
const FREIGABE_VALUES = new Set<LeadWeiterverarbeitungFreigabe>(["ja", "nein", "unklar"]);
/** Contacts offered in the convert dialog. The cap is surfaced in the UI rather
* than quietly hiding the rest. */
const CONVERT_CONTACT_LIMIT = 200;
function kontaktLabel(row: { vorname: string | null; nachname: string | null; orgName: string | null; primaerEmail: string | null }): string {
const person = `${row.vorname ?? ""} ${row.nachname ?? ""}`.trim();
const name = row.orgName?.trim() || person || row.primaerEmail || "";
return row.primaerEmail && name !== row.primaerEmail ? `${name} · ${row.primaerEmail}` : name;
}
/**
* Boards + contacts for the convert dialog. Both live in other modules, so each
* is best-effort: a missing module or permission means fewer options, never a
* broken lead detail page. Without any board the dialog says so — the schema
* cannot create a Projekt without one.
*/
async function loadConvertOptions(args: {
request: Request;
params: Record<string, string | undefined>;
tenantId: string;
lead: { vorname: string | null; nachname: string | null; email: string | null; telefon: string | null };
}): Promise<LeadConvertOptions> {
let pipelines: LeadConvertOptions["pipelines"] = [];
try {
const projectCtx = await loadProjectContext({ request: args.request, params: args.params, requireModule: false });
if (projectCtx.hasModule) {
const rows = await listPipelines({ tenantId: args.tenantId, ctx: projectCtx });
pipelines = rows.map((pipeline) => ({
id: pipeline.id,
label: pipeline.name,
// Only open stages: a project must not start in a won/lost column.
stages: pipeline.stages.filter((stage) => stage.stageKind === "offen").map((stage) => ({ id: stage.id, label: stage.name })),
}));
}
} catch {
pipelines = [];
}
let contacts: LeadConvertOptions["contacts"] = [];
let contactsTruncated = false;
let suggestedKontaktId: string | null = null;
try {
const crmCtx = await loadCrmContext({ request: args.request, params: args.params, requireModule: false });
if (crmCtx.hasModule) {
const result = await listKontakteForBrowser({ tenantId: args.tenantId, ctx: crmCtx, limit: CONVERT_CONTACT_LIMIT });
contacts = result.rows.map((row) => ({ id: row.id, label: kontaktLabel(row) }));
contactsTruncated = result.total > result.rows.length;
const email = args.lead.email?.trim().toLowerCase();
// Same match the service falls back to, shown up front so the user can
// see and override it instead of being surprised by it.
suggestedKontaktId = email ? (result.rows.find((row) => row.primaerEmail?.toLowerCase() === email)?.id ?? null) : null;
}
} catch {
contacts = [];
}
return {
defaultProjektname: leadProjectName(args.lead),
pipelines: pipelines.filter((pipeline) => pipeline.stages.length > 0),
contacts,
suggestedKontaktId,
contactsTruncated,
};
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
const { t } = await getTranslations(request);
const ctx = await loadLeadContext({ request, params, requireModule: true });
try {
requireLeadPermission(ctx, "leads.read_own");
} catch {
throw notFoundResponse();
}
const leadId = params.id;
if (!leadId) throw notFoundResponse();
const lead = await getVisibleLeadOrThrow(ctx.tenantId, leadId, ctx);
const userLabels = await resolveUserLabels(lead.zustaendigerUserId ? [lead.zustaendigerUserId] : []);
const canWrite = ctx.permissions.includes("leads.write");
// Only pay for the board/contact lookups when the lead can actually convert.
const convertible = canWrite && !lead.konvertiertProjektId && lead.status !== "converted" && canTransitionLeadStatus(lead.status, "qualified");
const convert = convertible ? await loadConvertOptions({ request, params, tenantId: ctx.tenantId, lead }) : null;
const vm = buildLeadDetailVM({
lead,
userLabels,
perms: { canWrite },
tenantSlug: params.tenant ?? "",
convert,
});
const telephonyCtx = await loadTelephonyContext({ request, params, requireModule: false });
const clickToCallVM = await loadTelephonyClickToCallVM(
telephonyCtx,
vm.status === "ready" && vm.data?.telefon ? [{ id: `lead:${vm.data.id}`, label: vm.data.displayName, e164: vm.data.telefon, primary: true }] : []
);
return Response.json({
title: vm.status === "ready" ? vm.data?.displayName : undefined,
breadcrumbAncestors: [{ label: t("leads.list.title"), href: leadsPath(params.tenant ?? "") }],
vm,
clickToCallVM,
} satisfies LoaderData);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
const ctx = await loadLeadContext({ request, params, requireModule: true });
const leadId = params.id;
if (!leadId) throw notFoundResponse();
const form = await request.formData();
const intent = form.get("intent")?.toString();
if (intent === "startTelephonyCall") {
try {
await validateCSRFToken(request, { formData: form });
await getVisibleLeadOrThrow(ctx.tenantId, leadId, ctx);
const telephonyCtx = await loadTelephonyContext({ request, params, requireModule: true });
await startTelephonyEntityCall(telephonyCtx, {
entityType: "lead",
entityId: leadId,
numberId: form.get("numberId")?.toString() ?? "",
destination: form.get("destination")?.toString() ?? "",
});
return Response.json({ ok: true, intent, messageKey: "leads.toast.callStarted" });
} catch (error) {
if (error instanceof TelephonyServiceError) {
return Response.json({ intent, error: error.messageKey }, { status: 400 });
}
return leadActionErrorResponse(error);
}
}
requireLeadPermission(ctx, "leads.write");
try {
// One save for everything that is a plain field edit. The status rides along
// instead of having its own submit, so the screen needs a single button.
if (intent === "save") {
const freigabe = form.get("weiterverarbeitungFreigabe")?.toString() as LeadWeiterverarbeitungFreigabe | undefined;
if (freigabe && !FREIGABE_VALUES.has(freigabe)) throw badRequestResponse();
const status = form.get("status")?.toString() as LeadStatus | undefined;
if (status && !STATUS_VALUES.has(status)) throw badRequestResponse();
// Validate the transition before touching anything: a rejected status must
// not leave the master-data edit half-applied.
const current = await getVisibleLeadOrThrow(ctx.tenantId, leadId, ctx);
const statusChanged = Boolean(status && status !== current.status);
if (statusChanged && !canTransitionLeadStatus(current.status, status!)) {
return Response.json({ intent, error: "leads.error.invalidStatusTransition" }, { status: 400 });
}
await updateLead({
tenantId: ctx.tenantId,
ctx,
leadId,
vorname: form.get("vorname")?.toString(),
nachname: form.get("nachname")?.toString(),
email: form.get("email")?.toString(),
telefon: form.get("telefon")?.toString(),
message: form.get("message")?.toString(),
weiterverarbeitungFreigabe: freigabe,
});
await auditLeadEvent({ ctx, action: "lead.updated", targetType: "lead", targetId: leadId });
await logLeadActivity({ ctx, leadId, activityType: "lead_updated", summaryText: "leads.activity.updated" });
if (statusChanged) {
await setLeadStatus({ tenantId: ctx.tenantId, leadId, status: status!, ctx });
await auditLeadEvent({
ctx,
action: status === "qualified" ? "lead.qualified" : "lead.status_changed",
targetType: "lead",
targetId: leadId,
metadata: { status: status! },
});
await logLeadActivity({
ctx,
leadId,
activityType: status === "qualified" ? "lead_qualified" : "status_changed",
summaryText: "activity.runtime.leads.statusChanged",
});
}
return Response.json({ ok: true, intent, messageKey: "leads.toast.saved" });
}
if (intent === "convert") {
const projektId = form.get("projektId")?.toString().trim();
const kontaktId = form.get("kontaktId")?.toString().trim() || null;
if (projektId) {
await completeLeadProjectConversion({ tenantId: ctx.tenantId, leadId, projektId, kontaktId, ctx });
} else {
await requestLeadProjectConversion({ tenantId: ctx.tenantId, leadId, kontaktId, ctx });
await createProjectFromQualifiedLead({
tenantId: ctx.tenantId,
leadId,
userId: ctx.userId,
pipelineId: form.get("pipelineId")?.toString().trim() || null,
stageId: form.get("stageId")?.toString().trim() || null,
projektname: form.get("projektname")?.toString() || null,
kontaktId,
});
}
await auditLeadEvent({ ctx, action: "lead.convert_requested", targetType: "lead", targetId: leadId });
await logLeadActivity({ ctx, leadId, activityType: "lead_qualified", summaryText: "leads.activity.convertRequested" });
return Response.json({ ok: true, intent, messageKey: "leads.toast.converted" });
}
throw badRequestResponse();
} catch (error) {
if (error instanceof ProjectServiceError) {
return Response.json({ intent, error: error.messageKey }, { status: 400 });
}
return leadActionErrorResponse(error);
}
};
export default function LeadDetailRoute() {
const { vm, clickToCallVM } = useLoaderData<LoaderData>();
const actionData = useActionData<{ intent?: string; ok?: boolean; error?: string; messageKey?: string }>();
useSaveToast(actionData);
const submit = useSubmit();
const navigation = useNavigation();
return (
<LeadDetailPage
vm={vm}
submitting={navigation.state !== "idle"}
errorKey={actionData?.error ?? null}
clickToCall={{
vm: clickToCallVM,
busy: navigation.state !== "idle",
onCall: (number, mode) => {
if (mode === "tel-fallback") {
window.location.assign(`tel:${number.e164}`);
return;
}
const form = new FormData();
form.set("intent", "startTelephonyCall");
form.set("numberId", number.id);
form.set("destination", number.e164);
submit(appendCSRFToken(form), { method: "post" });
},
}}
actions={{
onSubmit: (intent, fields) => {
const form = new FormData();
form.set("intent", intent);
if (fields) for (const [key, value] of Object.entries(fields)) form.set(key, value);
submit(form, { method: "post" });
},
}}
/>
);
}
export function ErrorBoundary() {
return <ServerError />;
}
export const handle = { moduleKey: LEADS_MODULE_KEY, breadcrumbKey: "leads.detail.title" };