CFG-04: benachrichtigungs-einstellungen-oberflaeche (handler+tests fuer notifyprefs, web/notifications next.js-frontend auf shl-01)

This commit is contained in:
sysops
2026-08-28 23:50:54 +02:00
parent 81ff8c18c3
commit b27a640116
11 changed files with 656 additions and 0 deletions
+30
View File
@@ -0,0 +1,30 @@
import { ThemeProvider, I18nProvider, ToastProvider, typography } from "@nexarch/shl";
export const metadata = {
title: "NEXARCH Benachrichtigungen",
};
export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="de">
<body
style={{
fontFamily: typography.fontFamily,
margin: 0,
background: "var(--shl-color-background, #ffffff)",
color: "var(--shl-color-text-primary, #14181f)",
}}
>
<ThemeProvider>
<I18nProvider initialLocale="de">
<ToastProvider>{children}</ToastProvider>
</I18nProvider>
</ThemeProvider>
</body>
</html>
);
}
+43
View File
@@ -0,0 +1,43 @@
"use client";
import { useEffect, useState } from "react";
import { Table } from "@nexarch/shl";
import type { TableColumn } from "@nexarch/shl";
import { Preference, fetchTenantOverview } from "../../lib/api";
// Akzeptanzkriterium 3: Tenant-Admin sieht eine Übersicht der
// Benachrichtigungs-Konfiguration seines Tenants. Zugriffsbeschränkung
// (nur Tenant-Admin) ist RBAC-02s Aufgabe vor diesem Endpunkt, siehe
// internal/notifyprefs/handler.go.
export default function OverviewPage() {
const [prefs, setPrefs] = useState<Preference[] | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
fetchTenantOverview()
.then(setPrefs)
.catch(() => setError("Übersicht konnte nicht geladen werden. Nur Tenant-Admins haben Zugriff."));
}, []);
const columns: TableColumn<Preference>[] = [
{ key: "user", header: "Benutzer-ID", render: (p) => p.UserID },
{ key: "event", header: "Ereignistyp", render: (p) => p.EventType },
{ key: "channel", header: "Kanal", render: (p) => p.Channel },
{ key: "enabled", header: "Aktiviert", render: (p) => (p.Enabled ? "Ja" : "Nein") },
];
return (
<main style={{ maxWidth: 800, margin: "40px auto", padding: "0 16px" }}>
<h1>Benachrichtigungs-Übersicht (Mandant)</h1>
{error && <p role="alert">{error}</p>}
{prefs && (
<Table
columns={columns}
rows={prefs}
rowKey={(p) => `${p.UserID}-${p.EventType}-${p.Channel}`}
caption="Von der Standardeinstellung abweichende Benachrichtigungspräferenzen aller Benutzer"
/>
)}
</main>
);
}
+5
View File
@@ -0,0 +1,5 @@
import { redirect } from "next/navigation";
export default function IndexPage() {
redirect("/settings");
}
+97
View File
@@ -0,0 +1,97 @@
"use client";
import { useEffect, useState } from "react";
import { CheckboxField, useToast } from "@nexarch/shl";
import {
ApiError,
KNOWN_CHANNELS,
KNOWN_EVENT_TYPES,
Preference,
fetchMyPreferences,
setPreference,
} from "../../lib/api";
const EVENT_LABELS: Record<string, string> = {
welcome: "Willkommen",
invoice_ready: "Rechnung verfügbar",
password_reset: "Passwort-Zurücksetzung",
security_alert: "Sicherheitshinweis",
};
const CHANNEL_LABELS: Record<string, string> = {
email: "E-Mail",
in_app: "In-App",
};
export default function SettingsPage() {
const { push } = useToast();
const [prefs, setPrefs] = useState<Preference[] | null>(null);
const [loadError, setLoadError] = useState<string | null>(null);
const [pending, setPending] = useState<string | null>(null);
useEffect(() => {
fetchMyPreferences()
.then(setPrefs)
.catch(() => setLoadError("Einstellungen konnten nicht geladen werden. Bitte melden Sie sich an."));
}, []);
// Default: aktiviert, solange keine explizite Praeferenz existiert
// (Akzeptanzkriterium 1) — gleicher Opt-out-Default wie im Backend.
function isEnabled(eventType: string, channel: string): boolean {
const explicit = prefs?.find((p) => p.EventType === eventType && p.Channel === channel);
return explicit ? explicit.Enabled : true;
}
async function onToggle(eventType: string, channel: string, nextEnabled: boolean) {
const key = `${eventType}:${channel}`;
setPending(key);
try {
// Akzeptanzkriterium 2: sofort speichern, kein Sammel-Speichern-Button —
// wirkt unmittelbar auf künftige Zustellungen (EnqueueIfAllowed prüft
// bei jedem Aufruf live, kein Cache dazwischen).
await setPreference(eventType, channel, nextEnabled);
setPrefs((current) => {
const withoutThis = (current ?? []).filter((p) => !(p.EventType === eventType && p.Channel === channel));
return [...withoutThis, { TenantSlug: "", UserID: "", EventType: eventType, Channel: channel, Enabled: nextEnabled }];
});
push(nextEnabled ? "Benachrichtigung aktiviert." : "Benachrichtigung deaktiviert.", "success");
} catch (err) {
push(err instanceof ApiError ? err.message : "Einstellung konnte nicht gespeichert werden.", "danger");
} finally {
setPending(null);
}
}
if (loadError) {
return (
<main style={{ maxWidth: 640, margin: "40px auto", padding: "0 16px" }}>
<p role="alert">{loadError}</p>
</main>
);
}
return (
<main style={{ maxWidth: 640, margin: "40px auto", padding: "0 16px" }}>
<h1>Benachrichtigungseinstellungen</h1>
<p>Wählen Sie je Ereignis, über welche Kanäle Sie benachrichtigt werden möchten.</p>
{KNOWN_EVENT_TYPES.map((eventType) => (
<fieldset key={eventType} style={{ marginBottom: 16 }}>
<legend>{EVENT_LABELS[eventType] ?? eventType}</legend>
{KNOWN_CHANNELS.map((channel) => {
const key = `${eventType}:${channel}`;
return (
<CheckboxField
key={key}
label={CHANNEL_LABELS[channel] ?? channel}
checked={isEnabled(eventType, channel)}
disabled={pending === key}
onChange={(e) => onToggle(eventType, channel, e.target.checked)}
/>
);
})}
</fieldset>
))}
</main>
);
}
+45
View File
@@ -0,0 +1,45 @@
const API_BASE = process.env.NEXT_PUBLIC_CORE_API_BASE ?? "";
export class ApiError extends Error {}
async function req<T>(path: string, init?: RequestInit): Promise<T> {
const res = await fetch(`${API_BASE}${path}`, {
credentials: "include",
headers: init?.body ? { "Content-Type": "application/json" } : undefined,
...init,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new ApiError(data.error ?? data.message ?? "Unbekannter Fehler");
}
return data as T;
}
export interface Preference {
TenantSlug: string;
UserID: string;
EventType: string;
Channel: string;
Enabled: boolean;
}
// Bekannte Ereignistypen/Kanäle — das Backend erzwingt keine feste Liste
// (jedes Modul kann eigene event_type-Werte an EnqueueIfAllowed übergeben),
// diese Liste ist der aktuell bekannte Stand fürs Frontend-Formular.
export const KNOWN_EVENT_TYPES = ["welcome", "invoice_ready", "password_reset", "security_alert"] as const;
export const KNOWN_CHANNELS = ["email", "in_app"] as const;
export function fetchMyPreferences(): Promise<Preference[]> {
return req("/notifications/preferences");
}
export function setPreference(eventType: string, channel: string, enabled: boolean): Promise<void> {
return req("/notifications/preferences", {
method: "POST",
body: JSON.stringify({ event_type: eventType, channel, enabled }),
});
}
export function fetchTenantOverview(): Promise<Preference[]> {
return req("/notifications/preferences/tenant");
}
+5
View File
@@ -0,0 +1,5 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
transpilePackages: ["@nexarch/shl"],
};
export default nextConfig;
+22
View File
@@ -0,0 +1,22 @@
{
"name": "nexarch-notifications",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"@nexarch/shl": "file:../shl",
"next": "14.2.35",
"react": "18.3.1",
"react-dom": "18.3.1"
},
"devDependencies": {
"@types/node": "20.14.9",
"@types/react": "18.3.3",
"@types/react-dom": "18.3.0",
"typescript": "5.5.3"
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [{ "name": "next" }],
"paths": { "@/*": ["./*"] }
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}