179 lines
9.3 KiB
TypeScript
179 lines
9.3 KiB
TypeScript
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData } from "react-router";
|
|
import { useTranslation } from "react-i18next";
|
|
import { buildLeadListVM, type LeadListVM } from "@hivegrid/view-models";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { badRequestResponse, leadActionErrorResponse, loadLeadContext, notFoundResponse, requireLeadPermission } from "~/utils/integrations/leads/leadAccess.server";
|
|
import { auditLeadEvent, logLeadActivity } from "~/utils/integrations/leads/leadAudit.server";
|
|
import { leadListQueryToParams, parseLeadListQuery } from "~/utils/integrations/leads/leadListQuery";
|
|
import { leadDetailPath, leadEventsPath, leadNewPath, leadStatisticsPath, leadsPath, LEADS_MODULE_KEY } from "~/utils/integrations/leads/leadRoutePaths";
|
|
import { bulkSetLeadStatus, getVisibleLeadOrThrow, listLeadsForBrowser, resolveUserLabels, setLeadStatus, type LeadStatus } from "~/utils/integrations/leads/leadService.server";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
|
|
type LoaderData = { title: string; moduleActive: boolean; vm: LeadListVM; nextHref: string | null; sseHref: string | null };
|
|
|
|
const STATUS_VALUES = new Set<LeadStatus>(["new", "qualified", "converted", "lost", "spam"]);
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { t } = await getTranslations(request);
|
|
const ctx = await loadLeadContext({ request, params });
|
|
const tenantSlug = params.tenant ?? "";
|
|
const title = `${t("leads.list.title")} | ${process.env.APP_NAME}`;
|
|
if (!ctx.hasModule) {
|
|
return Response.json({
|
|
title,
|
|
moduleActive: false,
|
|
vm: buildLeadListVM({
|
|
rows: [],
|
|
userLabels: new Map(),
|
|
total: 0,
|
|
nextCursor: null,
|
|
perms: { canWrite: false, canDelete: false, canReadAll: false },
|
|
tenantSlug,
|
|
createHref: leadNewPath(tenantSlug),
|
|
statisticsHref: leadStatisticsPath(tenantSlug),
|
|
}),
|
|
nextHref: null,
|
|
sseHref: null,
|
|
} satisfies LoaderData);
|
|
}
|
|
try {
|
|
requireLeadPermission(ctx, "leads.read_own");
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
const url = new URL(request.url);
|
|
const query = parseLeadListQuery(url.searchParams);
|
|
const result = await listLeadsForBrowser({ tenantId: ctx.tenantId, ctx, filter: query.filter, sort: query.sort, cursor: query.cursor });
|
|
const userLabels = await resolveUserLabels(result.rows.map((row) => row.zustaendigerUserId).filter((id): id is string => Boolean(id)));
|
|
const vm = buildLeadListVM({
|
|
rows: result.rows,
|
|
userLabels,
|
|
total: result.total,
|
|
nextCursor: result.nextCursor,
|
|
perms: {
|
|
canWrite: ctx.permissions.includes("leads.write"),
|
|
canDelete: ctx.permissions.includes("leads.delete"),
|
|
canReadAll: ctx.permissions.includes("leads.read_all"),
|
|
},
|
|
tenantSlug,
|
|
createHref: leadNewPath(tenantSlug),
|
|
statisticsHref: leadStatisticsPath(tenantSlug),
|
|
});
|
|
const nextHref = result.nextCursor
|
|
? `${leadsPath(tenantSlug)}?${leadListQueryToParams({ ...query, cursor: result.nextCursor }).toString()}`
|
|
: null;
|
|
return Response.json({ title, moduleActive: true, vm, nextHref, sseHref: leadEventsPath(tenantSlug) } satisfies LoaderData);
|
|
};
|
|
|
|
function parseIds(form: FormData): string[] {
|
|
return [...new Set(form.getAll("leadId").map((value) => value.toString().trim()).filter(Boolean))];
|
|
}
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
|
const tenantSlug = params.tenant ?? "";
|
|
const form = await request.formData();
|
|
const intent = form.get("intent")?.toString();
|
|
try {
|
|
if (intent === "setStatus") {
|
|
requireLeadPermission(ctx, "leads.write");
|
|
const leadId = form.get("leadId")?.toString().trim();
|
|
const status = form.get("status")?.toString() as LeadStatus | undefined;
|
|
if (!leadId || !status || !STATUS_VALUES.has(status)) throw badRequestResponse();
|
|
const lead = await getVisibleLeadOrThrow(ctx.tenantId, leadId, ctx);
|
|
await setLeadStatus({ tenantId: ctx.tenantId, leadId, status, ctx });
|
|
await auditLeadEvent({ ctx, action: "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, lead.id));
|
|
}
|
|
if (intent === "bulkStatus") {
|
|
requireLeadPermission(ctx, "leads.write");
|
|
const status = form.get("status")?.toString() as LeadStatus | undefined;
|
|
if (!status || !STATUS_VALUES.has(status)) throw badRequestResponse();
|
|
const ids = parseIds(form);
|
|
const count = await bulkSetLeadStatus({ tenantId: ctx.tenantId, ctx, leadIds: ids, status });
|
|
if (ids[0]) {
|
|
await auditLeadEvent({ ctx, action: "lead.bulk_updated", targetType: "lead", targetId: ids[0], metadata: { status, count } });
|
|
}
|
|
return redirect(leadsPath(tenantSlug));
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
return leadActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
export default function LeadsIndexRoute() {
|
|
const { t, i18n } = useTranslation();
|
|
const { moduleActive, vm, nextHref, sseHref } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<{ error?: string }>();
|
|
const rows = vm.status === "ready" && vm.data ? vm.data.rows : [];
|
|
const dateFormatter = new Intl.DateTimeFormat(i18n.language, { dateStyle: "medium", timeStyle: "short" });
|
|
return (
|
|
<main className="mx-auto max-w-6xl px-4 py-10" data-ui-id="ui.leads.list" data-sse-href={sseHref ?? undefined}>
|
|
<div className="flex items-start justify-between gap-4">
|
|
<div>
|
|
<h1 className="text-foreground text-xl font-semibold">{t("leads.list.title")}</h1>
|
|
<p className="text-muted-foreground mt-1 text-sm">{t(moduleActive ? "leads.list.subtitle" : "leads.list.locked")}</p>
|
|
</div>
|
|
<div className="flex gap-3 text-sm">
|
|
{vm.status === "ready" && vm.data?.canWrite ? <a className="text-theme-600 font-medium" href={vm.data.createHref}>{t("leads.actions.new")}</a> : null}
|
|
{vm.status === "ready" && vm.data ? <a className="text-theme-600 font-medium" href={vm.data.statisticsHref}>{t("leads.statistics.title")}</a> : null}
|
|
</div>
|
|
</div>
|
|
{actionData?.error ? <p className="mt-4 text-sm text-red-600">{t(actionData.error)}</p> : null}
|
|
{rows.length === 0 ? (
|
|
<section className="mt-10 rounded-md border p-6 text-center" data-ui-id="ui.leads.list.empty">
|
|
<p className="font-medium">{t(vm.status === "ready" && vm.data ? vm.data.emptyHeadlineKey : "leads.list.empty.headline")}</p>
|
|
<p className="text-muted-foreground mt-1 text-sm">{t(vm.status === "ready" && vm.data ? vm.data.emptyBodyKey : "leads.list.empty.body")}</p>
|
|
</section>
|
|
) : (
|
|
<form method="post" className="mt-6" data-ui-id="ui.leads.list.table">
|
|
<table className="w-full text-left text-sm">
|
|
<thead>
|
|
<tr className="text-muted-foreground border-b">
|
|
<th className="py-2">{t("leads.list.column.select")}</th>
|
|
<th className="py-2">{t("leads.list.column.identity")}</th>
|
|
<th className="py-2">{t("leads.list.column.source")}</th>
|
|
<th className="py-2">{t("leads.list.column.status")}</th>
|
|
<th className="py-2">{t("leads.list.column.owner")}</th>
|
|
<th className="py-2">{t("leads.list.column.createdAt")}</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{rows.map((row) => (
|
|
<tr key={row.id} className="border-b" data-row-id={row.id} data-markers={row.markers.join(",")}>
|
|
<td className="py-2"><input type="checkbox" name="leadId" value={row.id} aria-label={t("leads.list.column.select")} /></td>
|
|
<td className="py-2">
|
|
<a href={row.detailHref} className="text-theme-600 font-medium">{row.displayName}</a>
|
|
{row.preview ? <p className="text-muted-foreground mt-1 line-clamp-1">{row.preview}</p> : null}
|
|
</td>
|
|
<td className="py-2">{t(row.quelleLabelKey)}</td>
|
|
<td className="py-2">{t(row.statusLabelKey)}</td>
|
|
<td className="py-2">{row.zustaendigerLabel ?? ""}</td>
|
|
<td className="py-2">{dateFormatter.format(new Date(row.createdAtIso))}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
{vm.status === "ready" && vm.data?.canWrite ? (
|
|
<div className="mt-4 flex items-center gap-3">
|
|
<select name="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="bulkStatus" className="text-theme-600 text-sm font-medium">{t("leads.actions.applyBulk")}</button>
|
|
</div>
|
|
) : null}
|
|
</form>
|
|
)}
|
|
{nextHref ? <a className="text-theme-600 mt-4 inline-block text-sm font-medium" href={nextHref}>{t("leads.actions.nextPage")}</a> : null}
|
|
</main>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: LEADS_MODULE_KEY };
|