140 lines
5.0 KiB
TypeScript
140 lines
5.0 KiB
TypeScript
// AK-P3 — Notification-Settings route (`/app/:tenant/settings/notifications`).
|
|
// The category registry + default-inheritance merge live in the pure
|
|
// notification-settings VM (@hivegrid/view-models); the loader builds the VM
|
|
// once and the route injects it plus fetcher-backed action callbacks into the
|
|
// interim <NotificationSettingsPage /> screen (AD-28).
|
|
|
|
import { ActionFunctionArgs, LoaderFunctionArgs, useFetcher, useLoaderData } from "react-router";
|
|
import { upsertUserNotificationPreference, getUserNotificationPreferences } from "@hivegrid/db/notifications.server";
|
|
import {
|
|
buildNotificationSettingsVM,
|
|
isAllowedNotificationCategory,
|
|
isAllowedNotificationChannel,
|
|
NOTIFICATION_SETTING_CATEGORIES,
|
|
type NotificationPreferenceInput,
|
|
type NotificationSettingsVM,
|
|
} from "@hivegrid/view-models";
|
|
import { NotificationSettingsPage } from "~/components/screens/notifications/NotificationSettingsPage";
|
|
import { requireAuth } from "~/utils/loaders.middleware";
|
|
import { getTenantIdFromUrl } from "~/utils/services/.server/urlService";
|
|
import { getUserInfo, validateCSRFToken } from "~/utils/session.server";
|
|
import { useRootData } from "~/utils/data/useRootData";
|
|
import { getTranslations } from "~/locale/i18next.server";
|
|
|
|
type LoaderData = {
|
|
vm: NotificationSettingsVM;
|
|
};
|
|
|
|
type ActionData = {
|
|
ok?: true;
|
|
error?: string;
|
|
};
|
|
|
|
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;
|
|
}
|
|
|
|
function isCheckboxOn(formData: FormData, key: string): boolean {
|
|
const value = formData.get(key);
|
|
return value === "on" || value === "true";
|
|
}
|
|
|
|
const badRequest = (data: ActionData) => Response.json(data, { status: 400 });
|
|
|
|
export const loader = async ({ request, params }: LoaderFunctionArgs) => {
|
|
await requireAuth({ request, params });
|
|
const tenantId = await getTenantIdFromUrl(params);
|
|
const userInfo = await getUserInfo(request);
|
|
const records = (await getUserNotificationPreferences({ tenantId, userId: userInfo.userId })) as NotificationPreferenceInput[];
|
|
|
|
const data: LoaderData = { vm: buildNotificationSettingsVM(records) };
|
|
return Response.json(data);
|
|
};
|
|
|
|
export const action = async ({ request, params }: ActionFunctionArgs) => {
|
|
await requireAuth({ request, params });
|
|
const { t } = await getTranslations(request);
|
|
await validateCSRFToken(request);
|
|
const tenantId = await getTenantIdFromUrl(params);
|
|
const userInfo = await getUserInfo(request);
|
|
const formData = await request.formData();
|
|
const actionName = getRequiredFormValue(formData, "action");
|
|
|
|
// Master "turn all emails off" switch: write the EMAIL preference for every
|
|
// known category so explicit per-category overrides cannot leak emails back in.
|
|
if (actionName === "set-email-master") {
|
|
const emailsEnabled = !isCheckboxOn(formData, "disableAllEmails");
|
|
|
|
for (const category of NOTIFICATION_SETTING_CATEGORIES) {
|
|
await upsertUserNotificationPreference({
|
|
tenantId,
|
|
userId: userInfo.userId,
|
|
channel: "EMAIL",
|
|
category,
|
|
enabled: emailsEnabled,
|
|
});
|
|
}
|
|
|
|
return Response.json({ ok: true });
|
|
}
|
|
|
|
if (actionName !== "update-preference") {
|
|
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceAction") });
|
|
}
|
|
|
|
const category = getRequiredFormValue(formData, "category")?.toLowerCase() ?? "";
|
|
const channel = getRequiredFormValue(formData, "channel")?.replace(/-/g, "_").toUpperCase() ?? "";
|
|
|
|
if (!isAllowedNotificationCategory(category)) {
|
|
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceCategory") });
|
|
}
|
|
|
|
if (!isAllowedNotificationChannel(channel)) {
|
|
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceChannel") });
|
|
}
|
|
|
|
await upsertUserNotificationPreference({
|
|
tenantId,
|
|
userId: userInfo.userId,
|
|
channel,
|
|
category,
|
|
enabled: isCheckboxOn(formData, "enabled"),
|
|
});
|
|
|
|
return Response.json({ ok: true });
|
|
};
|
|
|
|
export default function WorkspaceNotificationSettingsRoute() {
|
|
const data = useLoaderData<LoaderData>();
|
|
const rootData = useRootData();
|
|
const fetcher = useFetcher<ActionData>();
|
|
|
|
const saveState = fetcher.data ? { ok: fetcher.data.ok === true, errorText: fetcher.data.error } : null;
|
|
|
|
function submit(form: Record<string, string>) {
|
|
fetcher.submit({ ...form, ...(rootData.csrf ? { csrf: rootData.csrf } : {}) }, { method: "post" });
|
|
}
|
|
|
|
return (
|
|
<main className="relative z-0 flex-1 pb-8">
|
|
<NotificationSettingsPage
|
|
vm={data.vm}
|
|
saveState={saveState}
|
|
actions={{
|
|
onTogglePreference: ({ category, channel, enabled }) =>
|
|
submit({ action: "update-preference", category, channel, enabled: enabled ? "true" : "false" }),
|
|
onSetEmailMaster: (disableAllEmails) =>
|
|
submit({ action: "set-email-master", ...(disableAllEmails ? { disableAllEmails: "true" } : {}) }),
|
|
}}
|
|
/>
|
|
</main>
|
|
);
|
|
}
|