143 lines
8.7 KiB
TypeScript
143 lines
8.7 KiB
TypeScript
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 { auditLeadEvent, logLeadActivity } from "~/utils/integrations/leads/leadAudit.server";
|
|
import { leadDetailPath, leadsPath, LEADS_MODULE_KEY } from "~/utils/integrations/leads/leadRoutePaths";
|
|
import {
|
|
completeLeadProjectConversion,
|
|
getVisibleLeadOrThrow,
|
|
requestLeadProjectConversion,
|
|
setLeadStatus,
|
|
updateLead,
|
|
type LeadRow,
|
|
type LeadStatus,
|
|
type LeadWeiterverarbeitungFreigabe,
|
|
} from "~/utils/integrations/leads/leadService.server";
|
|
import { createProjectFromQualifiedLead, ProjectServiceError } from "~/utils/integrations/projects/projectService.server";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
|
|
type LoaderData = { lead: LeadRow; listHref: string; canWrite: boolean };
|
|
|
|
const STATUS_VALUES = new Set<LeadStatus>(["new", "qualified", "converted", "lost", "spam"]);
|
|
const FREIGABE_VALUES = new Set<LeadWeiterverarbeitungFreigabe>(["ja", "nein", "unklar"]);
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
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);
|
|
return Response.json({ lead, listHref: leadsPath(params.tenant ?? ""), canWrite: ctx.permissions.includes("leads.write") } 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();
|
|
try {
|
|
if (intent === "update") {
|
|
const freigabe = form.get("weiterverarbeitungFreigabe")?.toString() as LeadWeiterverarbeitungFreigabe | undefined;
|
|
if (freigabe && !FREIGABE_VALUES.has(freigabe)) throw badRequestResponse();
|
|
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: "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));
|
|
}
|
|
if (intent === "convert") {
|
|
const projektId = form.get("projektId")?.toString().trim();
|
|
if (projektId) {
|
|
await completeLeadProjectConversion({ tenantId: ctx.tenantId, leadId, projektId, kontaktId: form.get("kontaktId")?.toString() || null, 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 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));
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
if (error instanceof ProjectServiceError) {
|
|
return Response.json({ 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" });
|
|
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>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: LEADS_MODULE_KEY };
|