Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/apps/web/app/routes/app.$tenant/notifications.tsx
T

220 lines
7.7 KiB
TypeScript

// AK-P3 — Notification-Center route (`/app/:tenant/notifications`).
// Loader builds the NotificationCenterVM once (deeplink from payloadMetadata,
// M002 bounce keys); the route hosts the SSE subscription (useNotificationsStream)
// and injects the live-merged VM + action callbacks into the interim
// <NotificationCenterPage /> screen (AD-28).
import { useMemo } from "react";
import { ActionFunctionArgs, LoaderFunctionArgs, useFetcher, useLoaderData, useNavigate } from "react-router";
import {
getNotificationDeliveryDiagnostics,
markAllInAppNotificationDeliveriesRead,
markInAppNotificationDeliveryRead,
redactNotificationDiagnosticText,
type NotificationDeliveryStatus,
} from "@hivegrid/db/notifications.server";
import {
buildNotificationCenterVM,
deriveAutomationFallbackDeeplink,
mergeNotificationCenterItems,
type NotificationCenterItemInput,
type NotificationCenterVM,
} from "@hivegrid/view-models";
import { NotificationCenterPage } from "~/components/screens/notifications/NotificationCenterPage";
import { useNotificationsStream } from "~/components/notifications/useNotificationsStream";
import ServerError from "~/components/ui/errors/ServerError";
import { getTranslations } from "~/locale/i18next.server";
import { requireAuth } from "~/utils/loaders.middleware";
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
import UrlUtils from "~/utils/app/UrlUtils";
import { useSaveToast, type SaveActionResult } from "~/hooks/use-save-toast";
type NotificationDeliveryDiagnosticRecord = {
id: string;
messageKey: string;
category: string;
channel: string;
status: NotificationDeliveryStatus | string;
attemptsMade: number;
lastError?: string | null;
payloadMetadata?: unknown;
createdAt?: Date | string | null;
updatedAt?: Date | string | null;
sentAt?: Date | string | null;
readAt?: Date | string | null;
};
type LoaderData = {
/** Page title consumed by the shell breadcrumb (useTitleData). */
title: string;
csrf?: string;
vm: NotificationCenterVM;
streamUrl: string;
};
const USER_VISIBLE_IN_APP_DELIVERY_STATUSES = new Set(["SENT", "READ"]);
function isUserVisibleInAppDelivery(record: NotificationDeliveryDiagnosticRecord) {
return USER_VISIBLE_IN_APP_DELIVERY_STATUSES.has(record.status.toString().trim().toUpperCase());
}
function serializeTimestamp(value: Date | string | null | undefined): string | null {
if (!value) {
return null;
}
return value instanceof Date ? value.toISOString() : value;
}
function toItemInput(record: NotificationDeliveryDiagnosticRecord, tenantSlug: string | null): NotificationCenterItemInput {
return {
id: record.id,
// Consulted by the VM only when the record carries no stored deeplink,
// which is the case for automation notifications written before the
// producers started setting one.
deeplink: deriveAutomationFallbackDeeplink(record.payloadMetadata, tenantSlug),
messageKey: record.messageKey,
category: record.category,
channel: record.channel,
status: String(record.status),
attemptsMade: record.attemptsMade,
lastError: record.lastError ? redactNotificationDiagnosticText(record.lastError) : null,
payloadMetadata: record.payloadMetadata,
createdAtIso: serializeTimestamp(record.createdAt),
updatedAtIso: serializeTimestamp(record.updatedAt),
sentAtIso: serializeTimestamp(record.sentAt),
readAtIso: serializeTimestamp(record.readAt),
};
}
function getRequiredFormValue(formData: FormData, key: string): string | null {
const value = formData.get(key);
if (typeof value !== "string") {
return null;
}
const normalized = value.trim();
return normalized.length > 0 ? normalized : null;
}
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
await requireAuth({ request, params });
const { t } = await getTranslations(request);
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
const records = (await getNotificationDeliveryDiagnostics({
tenantId,
userId: userInfo.userId,
channel: "IN_APP",
statuses: ["SENT", "READ"],
take: 50,
})) as NotificationDeliveryDiagnosticRecord[];
const data: LoaderData = {
title: t("notifications.center.title"),
csrf: userInfo.csrf,
vm: buildNotificationCenterVM({
items: records.filter(isUserVisibleInAppDelivery).map((record) => toItemInput(record, params.tenant ?? null)),
streamAvailable: true,
}),
streamUrl: UrlUtils.getModulePath(params, "notifications/stream"),
};
return Response.json(data);
};
export const action = async ({ request, params }: ActionFunctionArgs) => {
await requireAuth({ request, params });
const tenantId = await getTenantIdFromUrl(params);
const userInfo = await getUserInfo(request);
await validateCSRFToken(request);
const formData = await request.formData();
const actionName = getRequiredFormValue(formData, "action");
if (actionName === "mark-all-read") {
const cleared = await markAllInAppNotificationDeliveriesRead({
tenantId,
userId: userInfo.userId,
readAt: new Date(),
});
return Response.json({ intent: actionName, ok: true, cleared });
}
if (actionName !== "mark-read") {
return Response.json({ intent: actionName, error: "notifications.errors.invalidAction" }, { status: 400 });
}
const deliveryId = getRequiredFormValue(formData, "deliveryId");
if (!deliveryId) {
return Response.json({ intent: actionName, error: "notifications.errors.deliveryRequired" }, { status: 400 });
}
await markInAppNotificationDeliveryRead({
id: deliveryId,
tenantId,
userId: userInfo.userId,
readAt: new Date(),
});
return Response.json({ intent: actionName, ok: true });
};
export default function NotificationsRoute() {
const data = useLoaderData<LoaderData>();
const fetcher = useFetcher();
const navigate = useNavigate();
const initialItems = data.vm.status === "ready" && data.vm.data ? data.vm.data.items : [];
const stream = useNotificationsStream(data.streamUrl, initialItems);
useSaveToast(fetcher.data as SaveActionResult, { reportSuccess: false });
// Live-merge: the screen renders one VM; SSE updates flow in through the hook.
const liveVm = useMemo<NotificationCenterVM>(() => {
if (data.vm.status !== "ready" || !data.vm.data) return data.vm;
const items = mergeNotificationCenterItems(data.vm.data.items, stream.items);
return {
status: "ready",
data: {
...data.vm.data,
items,
totalCount: items.length,
unreadCount: items.filter((item) => !item.isRead).length,
},
};
}, [data.vm, stream.items]);
function submit(form: Record<string, string>) {
fetcher.submit({ ...form, ...(data.csrf ? { csrf: data.csrf } : {}) }, { method: "post" });
}
return (
// Full width so the screen's page header bar sits flush; the screen centers its own body.
<main className="relative z-0 w-full flex-1 pb-8">
<NotificationCenterPage
vm={liveVm}
connectionStatusKey={stream.connectionStatusKey}
actions={{
onMarkRead: (deliveryId) => submit({ action: "mark-read", deliveryId }),
onMarkAllRead: () => submit({ action: "mark-all-read" }),
onOpen: (item) => {
// Fire-and-forget mark-read (fetchers persist across the client-side
// navigation), then follow the deeplink.
if (!item.isRead) submit({ action: "mark-read", deliveryId: item.id });
if (item.deeplinkHref) navigate(item.deeplinkHref);
},
}}
/>
</main>
);
}
export function ErrorBoundary() {
return <ServerError />;
}