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

158 lines
4.9 KiB
TypeScript

import { ActionFunctionArgs, LoaderFunctionArgs, useLoaderData } from "react-router";
import {
getNotificationDeliveryDiagnostics,
markInAppNotificationDeliveryRead,
redactNotificationDiagnosticText,
type NotificationDeliveryStatus,
} from "@toolctrl/db/notifications.server";
import {
NotificationCenter,
type NotificationCenterItem,
} from "~/components/notifications/NotificationCenter";
import ServerError from "~/components/ui/errors/ServerError";
import { useTranslation } from "react-i18next";
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;
createdAt?: Date | string | null;
updatedAt?: Date | string | null;
sentAt?: Date | string | null;
readAt?: Date | string | null;
};
type LoaderData = {
csrf?: string;
items: NotificationCenterItem[];
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 toNotificationCenterItem(record: NotificationDeliveryDiagnosticRecord): NotificationCenterItem {
return {
id: record.id,
messageKey: record.messageKey,
category: record.category,
channel: record.channel,
status: record.status,
attemptsMade: record.attemptsMade,
lastError: record.lastError ? redactNotificationDiagnosticText(record.lastError) : null,
createdAt: serializeTimestamp(record.createdAt),
updatedAt: serializeTimestamp(record.updatedAt),
sentAt: serializeTimestamp(record.sentAt),
readAt: 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,
items: records.filter(isUserVisibleInAppDelivery).map(toNotificationCenterItem),
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-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 { t } = useTranslation();
return (
<main className="relative z-0 flex-1 pb-8">
<div className="mx-auto grid max-w-5xl gap-5 px-4 py-5 sm:px-8">
<div className="space-y-2">
<h1 className="text-2xl font-semibold text-foreground">{t("notifications.title")}</h1>
<p className="text-muted-foreground text-sm">{t("notifications.description")}</p>
</div>
<NotificationCenter
csrf={data.csrf}
items={data.items}
streamUrl={data.streamUrl}
title={t("notifications.center.title")}
emptyMessage={t("notifications.center.empty")}
/>
</div>
</main>
);
}
export function ErrorBoundary() {
return <ServerError />;
}