200 lines
9.3 KiB
TypeScript
200 lines
9.3 KiB
TypeScript
import { randomUUID } from "node:crypto";
|
|
|
|
import { buildPortalLifecycleVM } from "@hivegrid/view-models";
|
|
import { useFetcher, useLoaderData, useNavigate, useRouteLoaderData, type ActionFunctionArgs, type LoaderFunctionArgs } from "react-router";
|
|
|
|
import { CustomerPortalSettingsPage } from "~/components/screens/customer-portal/CustomerPortalInterimPages";
|
|
import { validatePortalCsrfToken } from "~/services/customer-portal/portal-csrf.server";
|
|
import { portalNotFound, requirePortalSessionContext } from "~/services/customer-portal/portal-data.server";
|
|
import {
|
|
cancelPortalAccountDeletion,
|
|
loadPortalLifecycle,
|
|
PortalLifecycleError,
|
|
requestPortalAccountDeletion,
|
|
requestPortalGdprExport,
|
|
updatePortalNotificationPreference,
|
|
type PortalLifecyclePreference,
|
|
} from "~/services/customer-portal/portal-lifecycle.server";
|
|
import { portalPublicPath } from "~/services/customer-portal/portal-origin.server";
|
|
import type { PortalRootData } from "~/services/customer-portal/portal-root";
|
|
|
|
const NOTIFICATION_EVENT_TYPES = ["status_mail", "lifecycle"] as const satisfies readonly PortalLifecyclePreference["eventType"][];
|
|
|
|
type LifecycleActionData = {
|
|
readonly ok: boolean;
|
|
readonly messageKey?: string;
|
|
readonly errorKey?: string;
|
|
};
|
|
|
|
export async function loader({ request, params }: LoaderFunctionArgs): Promise<Response> {
|
|
const session = await requirePortalSessionContext(request, params.tenant);
|
|
const snapshot = await loadPortalLifecycle(session);
|
|
const preferences = new Map(snapshot.notificationPreferences.map((preference) => [preference.eventType, preference]));
|
|
const vm = buildPortalLifecycleVM({
|
|
frozen: session.identity.tenantFrozen,
|
|
profile: {
|
|
name: `${snapshot.profile.firstName} ${snapshot.profile.lastName}`.trim() || snapshot.profile.email,
|
|
email: snapshot.profile.email,
|
|
phone: snapshot.profile.phone,
|
|
locale: snapshot.profile.locale,
|
|
},
|
|
notificationPreferences: NOTIFICATION_EVENT_TYPES.map((eventType) => {
|
|
const stored = preferences.get(eventType);
|
|
return {
|
|
eventType,
|
|
emailEnabled: stored?.emailEnabled ?? true,
|
|
mutedUntil: stored?.mutedUntil?.toISOString() ?? null,
|
|
};
|
|
}),
|
|
exportJobs: snapshot.exportJobs.map((job) => ({
|
|
id: job.id,
|
|
status: job.status,
|
|
progressPercent: job.progressPercent,
|
|
requestedAt: job.createdAt.toISOString(),
|
|
expiresAt: job.resultExpiresAt?.toISOString() ?? null,
|
|
downloadHref: job.status === "ready" ? portalPublicPath(session.origin, `exports/${job.id}`) : null,
|
|
})),
|
|
deletionRequest: snapshot.deletionRequest
|
|
? {
|
|
id: snapshot.deletionRequest.id,
|
|
status: snapshot.deletionRequest.status,
|
|
requestedAt: snapshot.deletionRequest.requestedAt.toISOString(),
|
|
cancellableUntil: snapshot.deletionRequest.cancellableUntil.toISOString(),
|
|
}
|
|
: null,
|
|
});
|
|
const baseHref = portalPublicPath(session.origin);
|
|
const responseHeaders = new Headers(session.responseHeaders);
|
|
responseHeaders.set("Cache-Control", "private, no-store");
|
|
return Response.json(
|
|
{
|
|
vm,
|
|
portalName: session.identity.portalTitle,
|
|
viewerLabel: `${session.identity.viewerFirstName} ${session.identity.viewerLastName}`.trim() || session.identity.portalTitle,
|
|
brandingLogoHref: portalPublicPath(session.origin, "branding/logo"),
|
|
paths: {
|
|
dashboard: baseHref,
|
|
projects: portalPublicPath(session.origin, "projects"),
|
|
upload: portalPublicPath(session.origin, "upload"),
|
|
settings: portalPublicPath(session.origin, "settings"),
|
|
logout: portalPublicPath(session.origin, "logout"),
|
|
},
|
|
},
|
|
{ headers: responseHeaders }
|
|
);
|
|
}
|
|
|
|
export async function action({ request, params }: ActionFunctionArgs): Promise<Response> {
|
|
if (request.method !== "POST") throw portalNotFound();
|
|
const session = await requirePortalSessionContext(request, params.tenant);
|
|
if (session.identity.tenantFrozen) throw portalNotFound();
|
|
const form = await request.formData();
|
|
await validatePortalCsrfToken(request, form);
|
|
const intent = form.get("intent")?.toString();
|
|
try {
|
|
if (intent === "preference") {
|
|
const eventType = parseNotificationEventType(form.get("eventType"));
|
|
const emailEnabled = parseBoolean(form.get("enabled"));
|
|
await updatePortalNotificationPreference(session, { eventType, emailEnabled });
|
|
return success("customerPortal.lifecycle.messages.preferenceSaved", session.responseHeaders);
|
|
}
|
|
if (intent === "request_export") {
|
|
await requestPortalGdprExport(session, { idempotencyKey: form.get("idempotencyKey")?.toString() || randomUUID(), request });
|
|
return success("customerPortal.lifecycle.messages.exportRequested", session.responseHeaders, 202);
|
|
}
|
|
if (intent === "request_deletion") {
|
|
await requestPortalAccountDeletion(session, {
|
|
password: form.get("password")?.toString() ?? "",
|
|
idempotencyKey: form.get("idempotencyKey")?.toString() || randomUUID(),
|
|
request,
|
|
});
|
|
return success("customerPortal.lifecycle.messages.deletionRequested", session.responseHeaders, 202);
|
|
}
|
|
if (intent === "cancel_deletion") {
|
|
await cancelPortalAccountDeletion(session, {
|
|
deletionRequestId: form.get("deletionRequestId")?.toString() ?? "",
|
|
request,
|
|
});
|
|
return success("customerPortal.lifecycle.messages.deletionCancelled", session.responseHeaders);
|
|
}
|
|
throw new PortalLifecycleError("INVALID_REQUEST");
|
|
} catch (error) {
|
|
if (error instanceof PortalLifecycleError) return lifecycleFailure(error, session.responseHeaders);
|
|
return failure("customerPortal.lifecycle.errors.unavailable", 503, session.responseHeaders);
|
|
}
|
|
}
|
|
|
|
export default function CustomerPortalSettingsRoute(): React.JSX.Element {
|
|
const data = useLoaderData<typeof loader>();
|
|
const root = useRouteLoaderData<PortalRootData>("root");
|
|
const navigate = useNavigate();
|
|
const lifecycle = useFetcher<LifecycleActionData>();
|
|
const logout = useFetcher();
|
|
|
|
function submitLifecycle(intent: string, values: Readonly<Record<string, string>> = {}): void {
|
|
const form = new FormData();
|
|
form.set("intent", intent);
|
|
if (root?.csrf) form.set("csrf", root.csrf);
|
|
for (const [key, value] of Object.entries(values)) form.set(key, value);
|
|
void lifecycle.submit(form, { method: "post", action: data.paths.settings });
|
|
}
|
|
|
|
return (
|
|
<CustomerPortalSettingsPage
|
|
vm={data.vm}
|
|
portalName={data.portalName}
|
|
viewerLabel={data.viewerLabel}
|
|
brandingLogoHref={data.brandingLogoHref}
|
|
busy={lifecycle.state !== "idle"}
|
|
messageKey={lifecycle.data?.ok ? lifecycle.data.messageKey : null}
|
|
errorKey={lifecycle.data?.ok === false ? lifecycle.data.errorKey : null}
|
|
actions={{
|
|
onDashboard: () => navigate(data.paths.dashboard),
|
|
onProjects: () => navigate(data.paths.projects),
|
|
onUpload: () => navigate(data.paths.upload),
|
|
onSettings: () => navigate(data.paths.settings),
|
|
onUpdatePreference: (eventType, enabled) => submitLifecycle("preference", { eventType, enabled: String(enabled) }),
|
|
onRequestExport: () => submitLifecycle("request_export", { idempotencyKey: crypto.randomUUID() }),
|
|
onDownloadExport: (href) => window.location.assign(href),
|
|
onRequestDeletion: (password) => submitLifecycle("request_deletion", { password, idempotencyKey: crypto.randomUUID() }),
|
|
onCancelDeletion: (deletionRequestId) => submitLifecycle("cancel_deletion", { deletionRequestId }),
|
|
onLogout: () => {
|
|
const form = new FormData();
|
|
if (root?.csrf) form.set("csrf", root.csrf);
|
|
void logout.submit(form, { method: "post", action: data.paths.logout });
|
|
},
|
|
}}
|
|
/>
|
|
);
|
|
}
|
|
|
|
function parseNotificationEventType(value: FormDataEntryValue | null): PortalLifecyclePreference["eventType"] {
|
|
if (typeof value !== "string" || !NOTIFICATION_EVENT_TYPES.includes(value as PortalLifecyclePreference["eventType"])) {
|
|
throw new PortalLifecycleError("INVALID_REQUEST");
|
|
}
|
|
return value as PortalLifecyclePreference["eventType"];
|
|
}
|
|
|
|
function parseBoolean(value: FormDataEntryValue | null): boolean {
|
|
if (value === "true") return true;
|
|
if (value === "false") return false;
|
|
throw new PortalLifecycleError("INVALID_REQUEST");
|
|
}
|
|
|
|
function success(messageKey: string, headers: Headers, status = 200): Response {
|
|
return Response.json({ ok: true, messageKey } satisfies LifecycleActionData, { status, headers });
|
|
}
|
|
|
|
function lifecycleFailure(error: PortalLifecycleError, headers: Headers): Response {
|
|
if (error.code === "PASSWORD_REQUIRED") return failure("customerPortal.lifecycle.errors.passwordRequired", 400, headers);
|
|
if (error.code === "PASSWORD_INVALID") return failure("customerPortal.lifecycle.errors.passwordInvalid", 422, headers);
|
|
if (error.code === "DELETE_ALREADY_PENDING") return failure("customerPortal.lifecycle.errors.deleteAlreadyPending", 409, headers);
|
|
if (error.code === "DELETE_NOT_CANCELLABLE") return failure("customerPortal.lifecycle.errors.deleteNotCancellable", 409, headers);
|
|
if (error.code === "EXPORT_NOT_AVAILABLE") return failure("customerPortal.lifecycle.errors.unavailable", 404, headers);
|
|
return failure("customerPortal.lifecycle.errors.invalidInput", 400, headers);
|
|
}
|
|
|
|
function failure(errorKey: string, status: number, headers: Headers): Response {
|
|
return Response.json({ ok: false, errorKey } satisfies LifecycleActionData, { status, headers });
|
|
}
|