203 lines
6.5 KiB
TypeScript
203 lines
6.5 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 } from "react-router";
|
|
import {
|
|
getNotificationDeliveryDiagnostics,
|
|
markAllInAppNotificationDeliveriesRead,
|
|
markInAppNotificationDeliveryRead,
|
|
redactNotificationDiagnosticText,
|
|
type NotificationDeliveryStatus,
|
|
} from "@hivegrid/db/notifications.server";
|
|
import {
|
|
buildNotificationCenterVM,
|
|
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";
|
|
|
|
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 = {
|
|
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): NotificationCenterItemInput {
|
|
return {
|
|
id: record.id,
|
|
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 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 = {
|
|
csrf: userInfo.csrf,
|
|
vm: buildNotificationCenterVM({
|
|
items: records.filter(isUserVisibleInAppDelivery).map(toItemInput),
|
|
streamAvailable: true,
|
|
}),
|
|
streamUrl: UrlUtils.getModulePath(params, "notifications/stream"),
|
|
};
|
|
|
|
return Response.json(data);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
await requireAuth({ request, params });
|
|
const { t } = await getTranslations(request);
|
|
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({ ok: true, cleared });
|
|
}
|
|
|
|
if (actionName !== "mark-read") {
|
|
return Response.json({ error: t("notifications.errors.invalidAction") }, { status: 400 });
|
|
}
|
|
|
|
const deliveryId = getRequiredFormValue(formData, "deliveryId");
|
|
|
|
if (!deliveryId) {
|
|
return Response.json({ error: t("notifications.errors.deliveryRequired") }, { status: 400 });
|
|
}
|
|
|
|
await markInAppNotificationDeliveryRead({
|
|
id: deliveryId,
|
|
tenantId,
|
|
userId: userInfo.userId,
|
|
readAt: new Date(),
|
|
});
|
|
|
|
return Response.json({ ok: true });
|
|
};
|
|
|
|
export default function NotificationsRoute() {
|
|
const data = useLoaderData<LoaderData>();
|
|
const fetcher = useFetcher();
|
|
|
|
const initialItems = data.vm.status === "ready" && data.vm.data ? data.vm.data.items : [];
|
|
const stream = useNotificationsStream(data.streamUrl, initialItems);
|
|
|
|
// 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 (
|
|
<main className="relative z-0 flex-1 pb-8">
|
|
<div className="mx-auto max-w-5xl">
|
|
<NotificationCenterPage
|
|
vm={liveVm}
|
|
connectionStatusKey={stream.connectionStatusKey}
|
|
actions={{
|
|
onMarkRead: (deliveryId) => submit({ action: "mark-read", deliveryId }),
|
|
onMarkAllRead: () => submit({ action: "mark-all-read" }),
|
|
}}
|
|
/>
|
|
</div>
|
|
</main>
|
|
);
|
|
}
|
|
|
|
export function ErrorBoundary() {
|
|
return <ServerError />;
|
|
}
|