202 lines
7.5 KiB
TypeScript
202 lines
7.5 KiB
TypeScript
// R-P7 (P7 Lead-Inbox) — lead triage inbox route (`/leads`). Loader builds the
|
|
// LeadListVM server-side (filter/sort/cursor, SSE realtime); action runs the
|
|
// single/bulk status changes. Module off -> locked; missing leads.read_own -> 404.
|
|
// UI is the AD-28 interim LeadInboxPage (composed from ~/ui); the route owns
|
|
// navigation (filter/page) + the status POSTs.
|
|
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, useNavigate, useNavigation, useParams, useSubmit } from "react-router";
|
|
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, type LeadListQuery } from "~/utils/integrations/leads/leadListQuery";
|
|
import {
|
|
leadBoardPath,
|
|
leadEventsPath,
|
|
leadNewPath,
|
|
leadsPath,
|
|
LEADS_MODULE_KEY,
|
|
} from "~/utils/integrations/leads/leadRoutePaths";
|
|
import {
|
|
bulkSetLeadStatus,
|
|
getVisibleLeadOrThrow,
|
|
listLeadsForBrowser,
|
|
resolveUserLabels,
|
|
setLeadStatus,
|
|
type LeadStatus,
|
|
} from "~/utils/integrations/leads/leadService.server";
|
|
import { LeadInboxPage } from "~/components/screens/leads/LeadInboxPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
/** Shell breadcrumb: the leads workspace in front of this screen's own crumb. */
|
|
moduleActive: boolean;
|
|
vm: LeadListVM;
|
|
query: LeadListQuery;
|
|
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 ?? "";
|
|
// Breadcrumb: <tenant> > Leads > Lead-Inbox, like the sibling leads screens.
|
|
// The shell only injects the responsible nav entry when it is NOT the current
|
|
// page, and here it is — so the workspace crumb is provided explicitly.
|
|
const title = `${t("leads.list.title")} | ${process.env.APP_NAME}`;
|
|
const url = new URL(request.url);
|
|
const query = parseLeadListQuery(url.searchParams);
|
|
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),
|
|
}),
|
|
query,
|
|
nextHref: null,
|
|
sseHref: null,
|
|
} satisfies LoaderData);
|
|
}
|
|
try {
|
|
requireLeadPermission(ctx, "leads.read_own");
|
|
} catch {
|
|
throw notFoundResponse();
|
|
}
|
|
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),
|
|
});
|
|
const nextHref = result.nextCursor ? `${leadsPath(tenantSlug)}?${leadListQueryToParams({ ...query, cursor: result.nextCursor }).toString()}` : null;
|
|
return Response.json({
|
|
title,
|
|
moduleActive: true,
|
|
vm,
|
|
query,
|
|
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();
|
|
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: "activity.runtime.leads.statusChanged",
|
|
});
|
|
return redirect(`${leadsPath(tenantSlug)}?toast=${encodeURIComponent("leads.toast.statusChanged")}`);
|
|
}
|
|
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)}?toast=${encodeURIComponent("leads.toast.bulkStatusChanged")}`);
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
return leadActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
export default function LeadsIndexRoute() {
|
|
const { moduleActive, vm, query, nextHref, sseHref } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<{ error?: string }>();
|
|
const params = useParams();
|
|
const navigate = useNavigate();
|
|
const submit = useSubmit();
|
|
const navigation = useNavigation();
|
|
|
|
const statusForm = (leadId: string | string[], status: LeadStatus, intent: "setStatus" | "bulkStatus") => {
|
|
const form = new FormData();
|
|
form.set("intent", intent);
|
|
form.set("status", status);
|
|
(Array.isArray(leadId) ? leadId : [leadId]).forEach((id) => form.append("leadId", id));
|
|
submit(form, { method: "post" });
|
|
};
|
|
|
|
return (
|
|
<LeadInboxPage
|
|
vm={vm}
|
|
moduleActive={moduleActive}
|
|
query={query}
|
|
hasNextPage={Boolean(nextHref)}
|
|
sseHref={sseHref}
|
|
submitting={navigation.state !== "idle"}
|
|
errorKey={actionData?.error ?? null}
|
|
actions={{
|
|
onApplyFilter: (nextQuery) => {
|
|
const qs = leadListQueryToParams(nextQuery).toString();
|
|
navigate(qs ? `?${qs}` : ".");
|
|
},
|
|
onNextPage: () => nextHref && navigate(nextHref),
|
|
onSetStatus: (leadId, status) => statusForm(leadId, status, "setStatus"),
|
|
onBulkStatus: (leadIds, status) => statusForm(leadIds, status, "bulkStatus"),
|
|
onOpenBoard: () => navigate(leadBoardPath(params.tenant ?? "")),
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: LEADS_MODULE_KEY };
|