Refresh HiveGrid Cloud reference snapshot
This commit is contained in:
1 parent
5e99e14772
commit
7f88026f79
5955 files changed
+1177325
-188362
No files matched your search
+220
-68
@@ -1,27 +1,118 @@
|
||||
import { type ActionFunctionArgs, type LoaderFunctionArgs, Form, redirect, useActionData, useLoaderData } from "react-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { badRequestResponse, leadActionErrorResponse, loadLeadContext, notFoundResponse, requireLeadPermission } from "~/utils/integrations/leads/leadAccess.server";
|
||||
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 { leadDetailPath, leadsPath, LEADS_MODULE_KEY } from "~/utils/integrations/leads/leadRoutePaths";
|
||||
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 LeadRow,
|
||||
type LeadStatus,
|
||||
type LeadWeiterverarbeitungFreigabe,
|
||||
} from "~/utils/integrations/leads/leadService.server";
|
||||
import { createProjectFromQualifiedLead, ProjectServiceError } from "~/utils/integrations/projects/projectService.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 = { lead: LeadRow; listHref: string; canWrite: boolean };
|
||||
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");
|
||||
@@ -31,21 +122,72 @@ export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
||||
const leadId = params.id;
|
||||
if (!leadId) throw notFoundResponse();
|
||||
const lead = await getVisibleLeadOrThrow(ctx.tenantId, leadId, ctx);
|
||||
return Response.json({ lead, listHref: leadsPath(params.tenant ?? ""), canWrite: ctx.permissions.includes("leads.write") } satisfies LoaderData);
|
||||
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 });
|
||||
requireLeadPermission(ctx, "leads.write");
|
||||
const tenantSlug = params.tenant ?? "";
|
||||
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 {
|
||||
if (intent === "update") {
|
||||
// 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,
|
||||
@@ -58,80 +200,90 @@ export const action = async ({ request, params }: ActionFunctionArgs) => {
|
||||
weiterverarbeitungFreigabe: freigabe,
|
||||
});
|
||||
await auditLeadEvent({ ctx, action: "lead.updated", targetType: "lead", targetId: leadId });
|
||||
await logLeadActivity({ ctx, leadId, activityType: "lead_updated", summaryText: "lead.activity.updated" });
|
||||
return redirect(leadDetailPath(tenantSlug, leadId));
|
||||
}
|
||||
if (intent === "setStatus") {
|
||||
const status = form.get("status")?.toString() as LeadStatus | undefined;
|
||||
if (!status || !STATUS_VALUES.has(status)) throw badRequestResponse();
|
||||
await setLeadStatus({ tenantId: ctx.tenantId, leadId, status, ctx });
|
||||
await auditLeadEvent({ ctx, action: status === "qualified" ? "lead.qualified" : "lead.status_changed", targetType: "lead", targetId: leadId, metadata: { status } });
|
||||
await logLeadActivity({ ctx, leadId, activityType: status === "qualified" ? "lead_qualified" : "status_changed", summaryText: `lead.status.${status}` });
|
||||
return redirect(leadDetailPath(tenantSlug, 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: form.get("kontaktId")?.toString() || null, ctx });
|
||||
await completeLeadProjectConversion({ tenantId: ctx.tenantId, leadId, projektId, kontaktId, ctx });
|
||||
} else {
|
||||
await requestLeadProjectConversion({ tenantId: ctx.tenantId, leadId, kontaktId: form.get("kontaktId")?.toString() || null, ctx });
|
||||
await createProjectFromQualifiedLead({ tenantId: ctx.tenantId, leadId, userId: ctx.userId });
|
||||
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: "lead.activity.convertRequested" });
|
||||
return redirect(leadDetailPath(tenantSlug, 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({ error: error.messageKey }, { status: 400 });
|
||||
return Response.json({ intent, error: error.messageKey }, { status: 400 });
|
||||
}
|
||||
return leadActionErrorResponse(error);
|
||||
}
|
||||
};
|
||||
|
||||
export default function LeadDetailRoute() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { lead, listHref, canWrite } = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<{ error?: string }>();
|
||||
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium", timeStyle: "short" });
|
||||
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 (
|
||||
<main className="mx-auto max-w-4xl px-4 py-10" data-ui-id="ui.leads.detail">
|
||||
<a href={listHref} className="text-theme-600 text-sm font-medium">{t("leads.actions.backToList")}</a>
|
||||
<div className="mt-4 flex items-start justify-between gap-4">
|
||||
<div>
|
||||
<h1 className="text-foreground text-xl font-semibold">{`${lead.vorname ?? ""} ${lead.nachname ?? ""}`.trim() || lead.email || lead.telefon || t(`leads.quelle.${lead.quelle}`)}</h1>
|
||||
<p className="text-muted-foreground mt-1 text-sm">{dateFormatter.format(new Date(lead.createdAt))}</p>
|
||||
</div>
|
||||
<span className="rounded border px-2 py-1 text-sm">{t(`leads.status.${lead.status}`)}</span>
|
||||
</div>
|
||||
{actionData?.error ? <p className="mt-4 text-sm text-red-600">{t(actionData.error)}</p> : null}
|
||||
<Form method="post" className="mt-6 grid gap-4 rounded-md border p-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<label className="grid gap-1 text-sm">{t("leads.field.vorname")}<input name="vorname" defaultValue={lead.vorname ?? ""} disabled={!canWrite} className="rounded border px-3 py-2" /></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.field.nachname")}<input name="nachname" defaultValue={lead.nachname ?? ""} disabled={!canWrite} className="rounded border px-3 py-2" /></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.field.email")}<input name="email" defaultValue={lead.email ?? ""} disabled={!canWrite} className="rounded border px-3 py-2" /></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.field.telefon")}<input name="telefon" defaultValue={lead.telefon ?? ""} disabled={!canWrite} className="rounded border px-3 py-2" /></label>
|
||||
</div>
|
||||
<label className="grid gap-1 text-sm">{t("leads.field.freigabe")}<select name="weiterverarbeitungFreigabe" defaultValue={lead.weiterverarbeitungFreigabe} disabled={!canWrite} className="rounded border px-3 py-2">{Array.from(FREIGABE_VALUES).map((value) => <option key={value} value={value}>{t(`leads.freigabe.${value}`)}</option>)}</select></label>
|
||||
<label className="grid gap-1 text-sm">{t("leads.field.message")}<textarea name="message" defaultValue={lead.message ?? ""} disabled={!canWrite} className="min-h-32 rounded border px-3 py-2" /></label>
|
||||
{canWrite ? <button type="submit" name="intent" value="update" className="bg-foreground text-background rounded px-4 py-2 text-sm font-medium">{t("leads.actions.save")}</button> : null}
|
||||
</Form>
|
||||
{canWrite ? (
|
||||
<Form method="post" className="mt-4 flex flex-wrap items-center gap-3 rounded-md border p-4">
|
||||
<select name="status" defaultValue={lead.status} className="rounded border px-2 py-1 text-sm">
|
||||
{Array.from(STATUS_VALUES).map((status) => <option key={status} value={status}>{t(`leads.status.${status}`)}</option>)}
|
||||
</select>
|
||||
<button type="submit" name="intent" value="setStatus" className="text-theme-600 text-sm font-medium">{t("leads.actions.setStatus")}</button>
|
||||
<button type="submit" name="intent" value="convert" className="text-theme-600 text-sm font-medium">{t("leads.actions.convertToProject")}</button>
|
||||
</Form>
|
||||
) : null}
|
||||
<section className="mt-4 rounded-md border p-4 text-sm" data-ui-id="ui.leads.detail.spam">
|
||||
<h2 className="font-medium">{t("leads.detail.spam.title")}</h2>
|
||||
<p className="text-muted-foreground mt-1">{t("leads.detail.spam.score", { score: lead.spamScore })}</p>
|
||||
{lead.spamReason ? <p className="text-muted-foreground mt-1">{lead.spamReason}</p> : null}
|
||||
</section>
|
||||
</main>
|
||||
<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" });
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -139,4 +291,4 @@ export function ErrorBoundary() {
|
||||
return <ServerError />;
|
||||
}
|
||||
|
||||
export const handle = { moduleKey: LEADS_MODULE_KEY };
|
||||
export const handle = { moduleKey: LEADS_MODULE_KEY, breadcrumbKey: "leads.detail.title" };
|
||||
Reference in new issue
Block a user