Track HiveGrid Cloud planning reference
This commit is contained in:
1 parent
b3d5ea6764
commit
e341c5938a
5784 files changed
+1104929
-3
No files matched your search
@@ -0,0 +1,194 @@
|
||||
import { ActionFunctionArgs, LoaderFunctionArgs, useActionData, useLoaderData } from "react-router";
|
||||
import {
|
||||
getUserNotificationPreferences,
|
||||
upsertUserNotificationPreference,
|
||||
type NotificationPreferenceChannel,
|
||||
} from "@toolctrl/db/notifications.server";
|
||||
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";
|
||||
import { useTranslation } from "react-i18next";
|
||||
|
||||
const NOTIFICATION_SETTING_CATEGORIES = ["default", "billing", "team"] as const;
|
||||
const NOTIFICATION_SETTING_CHANNELS = ["IN_APP", "EMAIL"] as const;
|
||||
|
||||
type NotificationSettingCategory = (typeof NOTIFICATION_SETTING_CATEGORIES)[number];
|
||||
type NotificationSettingChannel = (typeof NOTIFICATION_SETTING_CHANNELS)[number];
|
||||
|
||||
type NotificationPreferenceRecord = {
|
||||
channel: NotificationPreferenceChannel | string;
|
||||
category: string;
|
||||
enabled: boolean;
|
||||
};
|
||||
|
||||
type LoaderData = {
|
||||
preferences: Record<NotificationSettingCategory, Record<NotificationSettingChannel, boolean>>;
|
||||
};
|
||||
|
||||
type ActionData = {
|
||||
ok?: true;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
function isAllowedCategory(value: string): value is NotificationSettingCategory {
|
||||
return NOTIFICATION_SETTING_CATEGORIES.includes(value as NotificationSettingCategory);
|
||||
}
|
||||
|
||||
function isAllowedChannel(value: string): value is NotificationSettingChannel {
|
||||
return NOTIFICATION_SETTING_CHANNELS.includes(value as NotificationSettingChannel);
|
||||
}
|
||||
|
||||
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 createDefaultPreferences(): LoaderData["preferences"] {
|
||||
return {
|
||||
default: { IN_APP: true, EMAIL: true },
|
||||
billing: { IN_APP: true, EMAIL: true },
|
||||
team: { IN_APP: true, EMAIL: true },
|
||||
};
|
||||
}
|
||||
|
||||
function toLoaderData(records: NotificationPreferenceRecord[]): LoaderData {
|
||||
const preferences = createDefaultPreferences();
|
||||
const explicitPreferences = new Set<string>();
|
||||
|
||||
for (const record of records) {
|
||||
const category = record.category.trim().toLowerCase();
|
||||
const channel = record.channel.trim().replace(/-/g, "_").toUpperCase();
|
||||
|
||||
if (isAllowedCategory(category) && isAllowedChannel(channel)) {
|
||||
preferences[category][channel] = record.enabled;
|
||||
explicitPreferences.add(`${category}:${channel}`);
|
||||
}
|
||||
}
|
||||
|
||||
for (const category of NOTIFICATION_SETTING_CATEGORIES) {
|
||||
if (category === "default") {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (const channel of NOTIFICATION_SETTING_CHANNELS) {
|
||||
if (!explicitPreferences.has(`${category}:${channel}`)) {
|
||||
preferences[category][channel] = preferences.default[channel];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { preferences };
|
||||
}
|
||||
|
||||
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 NotificationPreferenceRecord[];
|
||||
|
||||
return Response.json(toLoaderData(records));
|
||||
};
|
||||
|
||||
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");
|
||||
|
||||
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 (!isAllowedCategory(category)) {
|
||||
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceCategory") });
|
||||
}
|
||||
|
||||
if (!isAllowedChannel(channel)) {
|
||||
return badRequest({ error: t("settings.notifications.errors.invalidPreferenceChannel") });
|
||||
}
|
||||
|
||||
await upsertUserNotificationPreference({
|
||||
tenantId,
|
||||
userId: userInfo.userId,
|
||||
channel,
|
||||
category,
|
||||
enabled: formData.get("enabled") === "on" || formData.get("enabled") === "true",
|
||||
});
|
||||
|
||||
return Response.json({ ok: true });
|
||||
};
|
||||
|
||||
export default function WorkspaceNotificationSettingsRoute() {
|
||||
const { t } = useTranslation();
|
||||
const data = useLoaderData<LoaderData>();
|
||||
const actionData = useActionData<ActionData>();
|
||||
const rootData = useRootData();
|
||||
|
||||
return (
|
||||
<main data-ui-id="ui.settings.notifications.page" className="mx-auto grid max-w-3xl gap-5 px-4 py-5 sm:px-8">
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-semibold text-foreground">{t("settings.notifications.heading")}</h1>
|
||||
<p className="text-sm text-muted-foreground">{t("settings.notifications.description")}</p>
|
||||
</div>
|
||||
|
||||
{actionData?.error ? <p className="rounded-md border border-destructive/40 bg-destructive/10 p-3 text-sm text-destructive">{actionData.error}</p> : null}
|
||||
{actionData?.ok ? <p className="rounded-md border border-emerald-500/40 bg-emerald-500/10 p-3 text-sm text-emerald-700">{t("settings.notifications.saved")}</p> : null}
|
||||
|
||||
<div className="divide-y rounded-lg border bg-card">
|
||||
{NOTIFICATION_SETTING_CATEGORIES.map((category) => (
|
||||
<section
|
||||
key={category}
|
||||
data-ui-id={`ui.settings.notifications.category.${category}`}
|
||||
className="grid gap-3 p-4 sm:grid-cols-[1fr_auto] sm:items-center"
|
||||
>
|
||||
<div>
|
||||
<h2 className="text-sm font-medium text-foreground">{t(`settings.notifications.categories.${category}`)}</h2>
|
||||
<p className="text-sm text-muted-foreground">{t("settings.notifications.categoryDescription", { category: t(`settings.notifications.categories.${category}`).toLowerCase() })}</p>
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
{NOTIFICATION_SETTING_CHANNELS.map((channel) => {
|
||||
const inputId = `notification-${category}-${channel}`;
|
||||
return (
|
||||
<form
|
||||
key={channel}
|
||||
method="post"
|
||||
data-ui-id={`ui.settings.notifications.preference.${category}.${channel.toLowerCase()}`}
|
||||
className="flex items-center gap-2 rounded-md border px-3 py-2"
|
||||
>
|
||||
<input type="hidden" name="action" value="update-preference" />
|
||||
{rootData.csrf && <input type="hidden" name="csrf" value={rootData.csrf} />}
|
||||
<input type="hidden" name="category" value={category} />
|
||||
<input type="hidden" name="channel" value={channel} />
|
||||
<input id={inputId} name="enabled" type="checkbox" defaultChecked={data.preferences[category][channel]} />
|
||||
<label htmlFor={inputId} className="text-sm font-medium">
|
||||
{t(channel === "IN_APP" ? "settings.notifications.channels.inApp" : "settings.notifications.channels.email")}
|
||||
</label>
|
||||
<button type="submit" className="text-sm text-primary underline-offset-2 hover:underline">
|
||||
{t("shared.save")}
|
||||
</button>
|
||||
</form>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user