90 lines
4.2 KiB
TypeScript
90 lines
4.2 KiB
TypeScript
import { type ActionFunctionArgs, type LoaderFunctionArgs, redirect, useActionData, useLoaderData, useNavigation, useSubmit } from "react-router";
|
|
import { buildLeadSourceAdminVM, type LeadSourceAdminVM } from "@hivegrid/view-models";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
import { badRequestResponse, leadActionErrorResponse, loadLeadContext, requireLeadPermission } from "~/utils/integrations/leads/leadAccess.server";
|
|
import { auditLeadEvent } from "~/utils/integrations/leads/leadAudit.server";
|
|
import { leadSourcesAdminPath, LEADS_MODULE_KEY } from "~/utils/integrations/leads/leadRoutePaths";
|
|
import { archiveLeadSource, listAssignableUsers, listLeadSources, upsertLeadSource } from "~/utils/integrations/leads/leadService.server";
|
|
import { LeadSourcesAdminPage } from "~/components/screens/leads/LeadSourcesAdminPage";
|
|
import ServerError from "~/components/ui/errors/ServerError";
|
|
import { useSaveToast } from "~/hooks/use-save-toast";
|
|
|
|
type LoaderData = { title: string; vm: LeadSourceAdminVM };
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
const { t } = await getTranslations(request);
|
|
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
|
requireLeadPermission(ctx, "leads.admin");
|
|
const [sources, assignableUsers] = await Promise.all([listLeadSources(ctx.tenantId), listAssignableUsers(ctx.tenantId)]);
|
|
const title = `${t("leads.sources.title")} | ${process.env.APP_NAME}`;
|
|
return Response.json({ title, vm: buildLeadSourceAdminVM({ rows: sources, assignableUsers, canWrite: true }) } satisfies LoaderData);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
const ctx = await loadLeadContext({ request, params, requireModule: true });
|
|
requireLeadPermission(ctx, "leads.admin");
|
|
const form = await request.formData();
|
|
const intent = form.get("intent")?.toString();
|
|
try {
|
|
if (intent === "upsert") {
|
|
const source = await upsertLeadSource({
|
|
tenantId: ctx.tenantId,
|
|
key: form.get("key")?.toString() ?? "",
|
|
name: form.get("name")?.toString() ?? "",
|
|
defaultZustaendigerUserId: form.get("defaultZustaendigerUserId")?.toString() || null,
|
|
});
|
|
await auditLeadEvent({ ctx, action: "lead.source_created", targetType: "lead_source", targetId: source.id });
|
|
return redirect(`${leadSourcesAdminPath(params.tenant ?? "")}?toast=${encodeURIComponent("leads.toast.sourceSaved")}`);
|
|
}
|
|
// "Delete" in the UI, archive in the data: leads captured through the
|
|
// source keep pointing at a row that still exists.
|
|
if (intent === "archive") {
|
|
const sourceId = form.get("sourceId")?.toString();
|
|
if (!sourceId) throw badRequestResponse();
|
|
await archiveLeadSource({ tenantId: ctx.tenantId, sourceId });
|
|
await auditLeadEvent({ ctx, action: "lead.source_archived", targetType: "lead_source", targetId: sourceId });
|
|
return redirect(`${leadSourcesAdminPath(params.tenant ?? "")}?toast=${encodeURIComponent("leads.toast.sourceArchived")}`);
|
|
}
|
|
throw badRequestResponse();
|
|
} catch (error) {
|
|
return leadActionErrorResponse(error);
|
|
}
|
|
};
|
|
|
|
export default function LeadSourcesRoute() {
|
|
const { vm } = useLoaderData<LoaderData>();
|
|
const actionData = useActionData<{ error?: string }>();
|
|
useSaveToast(actionData);
|
|
const submit = useSubmit();
|
|
const navigation = useNavigation();
|
|
return (
|
|
<LeadSourcesAdminPage
|
|
vm={vm}
|
|
submitting={navigation.state !== "idle"}
|
|
errorKey={actionData?.error ?? null}
|
|
actions={{
|
|
onUpsert: ({ key, name, defaultZustaendigerUserId }) => {
|
|
const form = new FormData();
|
|
form.set("intent", "upsert");
|
|
form.set("key", key);
|
|
form.set("name", name);
|
|
form.set("defaultZustaendigerUserId", defaultZustaendigerUserId);
|
|
submit(form, { method: "post" });
|
|
},
|
|
onDelete: (sourceId) => {
|
|
const form = new FormData();
|
|
form.set("intent", "archive");
|
|
form.set("sourceId", sourceId);
|
|
submit(form, { method: "post" });
|
|
},
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|
|
|
|
export const handle = { moduleKey: LEADS_MODULE_KEY };
|