165 lines
7.3 KiB
TypeScript
165 lines
7.3 KiB
TypeScript
// R-P7 (P7 Lead-Inbox) Interim-UI (AD-28) — incoming-leads Kanban board
|
|
// (`/:tenant/leads/board`). Loader builds the LeadBoardVM server-side from the
|
|
// same leadService list path the inbox uses (spam/quarantine excluded by the VM);
|
|
// action runs a single status change via the existing setLeadStatus. Module off ->
|
|
// 404; missing leads.read_own -> 404. UI is the interim LeadBoardPage on top of the
|
|
// shared SortableKanbanBoard. Reachable via the list/board toggle on the inbox.
|
|
|
|
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, useNavigate, useNavigation, useParams, useSearchParams, useSubmit } from "react-router";
|
|
import { buildLeadBoardVM, type LeadBoardStatus, type LeadBoardVM } 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 { leadBoardPath, leadDetailPath, leadNewPath, leadsPath, LEADS_MODULE_KEY } from "~/utils/integrations/leads/leadRoutePaths";
|
|
import { listLeadsForBoard, resolveUserLabels, setLeadStatus, type LeadStatus } from "~/utils/integrations/leads/leadService.server";
|
|
import { LeadBoardPage } from "~/components/screens/leads/LeadBoardPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
|
|
type LoaderData = {
|
|
title: string;
|
|
/** Shell breadcrumb: the leads workspace in front of this screen's own crumb. */
|
|
vm: LeadBoardVM;
|
|
search: string;
|
|
includeSpam: boolean;
|
|
};
|
|
|
|
// The board shows the four non-spam statuses; the VM drops any spam/quarantine row.
|
|
const BOARD_STATUSES: LeadStatus[] = ["new", "qualified", "converted", "lost"];
|
|
const STATUS_VALUES = new Set<LeadStatus>(["new", "qualified", "converted", "lost", "spam"]);
|
|
const BOARD_LIMIT_PER_STATUS = 50;
|
|
|
|
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 tenantSlug = params.tenant ?? "";
|
|
// Breadcrumb: <tenant> > Leads > Lead-Board. The board is its own view of the
|
|
// leads workspace, so it carries its own crumb behind the workspace label the
|
|
// shell cannot inject here (the nav entry points at /leads, not at this view).
|
|
const title = `${t("leads.board.title")} | ${process.env.APP_NAME}`;
|
|
const url = new URL(request.url);
|
|
const search = url.searchParams.get("q")?.trim() ?? "";
|
|
// Same opt-in as the inbox: spam stays hidden unless explicitly asked for.
|
|
const includeSpam = url.searchParams.get("spam") === "1";
|
|
const result = await listLeadsForBoard({
|
|
tenantId: ctx.tenantId,
|
|
ctx,
|
|
statuses: includeSpam ? [...BOARD_STATUSES, "spam"] : BOARD_STATUSES,
|
|
search,
|
|
limitPerStatus: BOARD_LIMIT_PER_STATUS,
|
|
});
|
|
const userLabels = await resolveUserLabels(result.rows.map((row) => row.zustaendigerUserId).filter((id): id is string => Boolean(id)));
|
|
const vm = buildLeadBoardVM({
|
|
rows: result.rows,
|
|
countsByStatus: result.countsByStatus,
|
|
userLabels,
|
|
perms: { canWrite: ctx.permissions.includes("leads.write") },
|
|
includeSpam,
|
|
listHref: leadsPath(tenantSlug),
|
|
buildDetailHref: (leadId) => leadDetailPath(tenantSlug, leadId),
|
|
generatedAtIso: new Date().toISOString(),
|
|
});
|
|
return Response.json({ title, vm, search, includeSpam } satisfies LoaderData);
|
|
};
|
|
|
|
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 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: "activity.runtime.leads.statusChanged",
|
|
});
|
|
// Keep the caller's view: dropping ?spam would silently close the column.
|
|
const next = new URLSearchParams();
|
|
const query = form.get("q")?.toString().trim();
|
|
if (query) next.set("q", query);
|
|
if (form.get("spam")?.toString() === "1") next.set("spam", "1");
|
|
next.set("toast", "leads.toast.statusChanged");
|
|
return redirect(`${leadBoardPath(tenantSlug)}?${next.toString()}`);
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
return leadActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
export default function LeadBoardRoute() {
|
|
const { vm, search, includeSpam } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<{ error?: string }>();
|
|
const params = useParams();
|
|
const navigate = useNavigate();
|
|
const submit = useSubmit();
|
|
const navigation = useNavigation();
|
|
const [searchParams, setSearchParams] = useSearchParams();
|
|
const data = vm.status === "ready" ? vm.data : null;
|
|
|
|
if (!data) {
|
|
return <div className="flex w-full flex-col gap-6 p-6" data-ui-id="ui.leads.board" />;
|
|
}
|
|
|
|
return (
|
|
<LeadBoardPage
|
|
data={data}
|
|
submitting={navigation.state !== "idle"}
|
|
errorKey={actionData?.error ?? null}
|
|
search={search}
|
|
actions={{
|
|
onSetStatus: (leadId: string, status: LeadBoardStatus) => {
|
|
const form = new FormData();
|
|
form.set("intent", "setStatus");
|
|
form.set("leadId", leadId);
|
|
form.set("status", status);
|
|
if (search) form.set("q", search);
|
|
if (includeSpam) form.set("spam", "1");
|
|
submit(form, { method: "post" });
|
|
},
|
|
onOpenList: () => navigate(leadsPath(params.tenant ?? "")),
|
|
onNew: () => navigate(leadNewPath(params.tenant ?? "")),
|
|
onSearch: (value) => {
|
|
const next = new URLSearchParams(searchParams);
|
|
if (value) next.set("q", value);
|
|
else next.delete("q");
|
|
setSearchParams(next);
|
|
},
|
|
onToggleSpam: (checked) => {
|
|
const next = new URLSearchParams(searchParams);
|
|
if (checked) next.set("spam", "1");
|
|
else next.delete("spam");
|
|
setSearchParams(next);
|
|
},
|
|
// One navigation for both params: onSearch and onToggleSpam each build
|
|
// from this render's snapshot, so chaining them would put back what the
|
|
// other just removed.
|
|
onResetFilters: () => {
|
|
const next = new URLSearchParams(searchParams);
|
|
next.delete("q");
|
|
next.delete("spam");
|
|
setSearchParams(next);
|
|
},
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: LEADS_MODULE_KEY };
|