Files
govoplan-notifications/webui/src/features/notifications/NotificationCenterPage.tsx
T

434 lines
18 KiB
TypeScript

import { useEffect, useMemo, useRef, useState } from "react";
import { Bell, Check, ExternalLink, Send, XCircle } from "lucide-react";
import {
ActionBlockerHint,
ActionToolbar,
Button,
ConfirmDialog,
CountBadge,
DismissibleAlert,
DocumentationHelpLink,
MultiSelectFilter,
SelectionList,
SelectionListItem,
StatePanel,
StatusBadge,
WorkspaceActionBar,
WorkspaceFrame,
WorkspaceLayout,
hasScope,
i18nMessage,
type ApiSettings,
type AuthInfo
} from "@govoplan/core-webui";
import { deliverPendingNotifications, listNotifications, updateNotification, type NotificationMessage } from "../../api/notifications";
import { safeNotificationActionUrl } from "../../security/actionUrl";
import {
NOTIFICATIONS_BLOCKER_LABELS,
NOTIFICATIONS_DELIVERY_DOCUMENTATION,
NOTIFICATIONS_DOCUMENTATION,
NOTIFICATIONS_I18N
} from "./interfacePatterns";
type StatusFilter =
| "pending"
| "queued"
| "sending"
| "accepted"
| "paused"
| "sent"
| "failed"
| "skipped"
| "cancelled";
const statusFilters: StatusFilter[] = [
"pending",
"queued",
"sending",
"accepted",
"paused",
"sent",
"failed",
"skipped",
"cancelled"
];
const cancellableStatuses = new Set(["pending", "queued", "paused", "failed"]);
export default function NotificationCenterPage({ settings, auth }: { settings: ApiSettings; auth: AuthInfo }) {
const scopeKey = JSON.stringify([settings.apiBaseUrl, settings.apiKey, settings.accessToken, auth.tenant.id, auth.user.id, auth.scopes]);
const currentScope = useRef(scopeKey);
const scopeGeneration = useRef(0);
if (currentScope.current !== scopeKey) {
currentScope.current = scopeKey;
scopeGeneration.current += 1;
}
const generation = scopeGeneration.current;
const isCurrentScope = () => currentScope.current === scopeKey && scopeGeneration.current === generation;
const operationScope = useRef<string | null>(null);
const [loadedScope, setLoadedScope] = useState(scopeKey);
const [loadedNotifications, setNotifications] = useState<NotificationMessage[]>([]);
const notifications = loadedScope === scopeKey ? loadedNotifications : [];
const [selectedId, setSelectedId] = useState("");
const [statusFilter, setStatusFilter] = useState<string[] | null>(null);
const loadRequest = useRef<AbortController | null>(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [confirmingAction, setConfirmingAction] = useState<"cancel" | "dispatch" | null>(null);
const canRead = hasScope(auth, "notifications:notification:read");
const canWrite = hasScope(auth, "notifications:notification:write");
const canDispatch = hasScope(auth, "notifications:delivery:dispatch");
const selected = useMemo(() => notifications.find((item) => item.id === selectedId) || notifications[0] || null, [notifications, selectedId]);
const unreadCount = notifications.filter((item) => !item.read_at && !["cancelled", "skipped"].includes(item.status)).length;
const commonSelectionReason = busy
? NOTIFICATIONS_I18N.actionActive
: loading
? "i18n:govoplan-notifications.loading_notifications"
: !selected
? NOTIFICATIONS_I18N.selectionRequired
: !canWrite
? NOTIFICATIONS_I18N.writePermissionRequired
: undefined;
const markReadDisabledReason = commonSelectionReason ?? (selected?.read_at ? NOTIFICATIONS_I18N.alreadyRead : undefined);
const acknowledgeDisabledReason = commonSelectionReason ?? (selected?.acknowledged_at ? NOTIFICATIONS_I18N.alreadyAcknowledged : undefined);
const cancelDisabledReason = commonSelectionReason ?? (selected && !cancellableStatuses.has(selected.status) ? NOTIFICATIONS_I18N.notCancellable : undefined);
const dispatchDisabledReason = busy
? NOTIFICATIONS_I18N.actionActive
: loading
? "i18n:govoplan-notifications.loading_notifications"
: !canDispatch
? NOTIFICATIONS_I18N.dispatchPermissionRequired
: undefined;
useEffect(() => {
operationScope.current = null;
setBusy(false);
setConfirmingAction(null);
}, [scopeKey]);
useEffect(() => {
if (!canRead) {
loadRequest.current?.abort();
setNotifications([]);
setSelectedId("");
setLoading(false);
return;
}
void load();
return () => loadRequest.current?.abort();
}, [canRead, scopeKey, statusFilter]);
async function load() {
if (!isCurrentScope() || !canRead) return;
loadRequest.current?.abort();
const request = new AbortController();
loadRequest.current = request;
setLoading(true);
setError("");
try {
const response = await listNotifications(settings, {
status: statusFilter ?? undefined,
limit: 200
}, request.signal);
if (request.signal.aborted || !isCurrentScope()) return;
setLoadedScope(scopeKey);
setNotifications(response.notifications);
setSelectedId((current) => current && response.notifications.some((item) => item.id === current) ? current : response.notifications[0]?.id ?? "");
} catch (err) {
if (!request.signal.aborted && isCurrentScope()) setError(errorMessage(err));
} finally {
if (!request.signal.aborted && isCurrentScope()) setLoading(false);
}
}
async function markSelected(status: "read" | "acknowledged" | "cancelled"): Promise<boolean> {
if (!selected || !canWrite || loading || operationScope.current === scopeKey) return false;
operationScope.current = scopeKey;
loadRequest.current?.abort();
setBusy(true);
setError("");
try {
const next = await updateNotification(settings, selected.id, { status });
if (!isCurrentScope()) return false;
setNotifications((items) => items.map((item) => item.id === next.id ? next : item)
.filter((item) => statusFilter === null || statusFilter.includes(item.status)));
notifyNotificationsChanged();
return true;
} catch (err) {
if (isCurrentScope()) setError(errorMessage(err));
return false;
} finally {
if (isCurrentScope()) {
operationScope.current = null;
setBusy(false);
}
}
}
async function runDelivery(): Promise<boolean> {
if (!canDispatch || loading || operationScope.current === scopeKey) return false;
operationScope.current = scopeKey;
loadRequest.current?.abort();
setBusy(true);
setError("");
try {
await deliverPendingNotifications(settings, 50);
if (!isCurrentScope()) return false;
await load();
if (!isCurrentScope()) return false;
notifyNotificationsChanged();
return true;
} catch (err) {
if (isCurrentScope()) setError(errorMessage(err));
return false;
} finally {
if (isCurrentScope()) {
operationScope.current = null;
setBusy(false);
}
}
}
async function confirmAction() {
const succeeded = confirmingAction === "cancel"
? await markSelected("cancelled")
: confirmingAction === "dispatch"
? await runDelivery()
: false;
if (succeeded) setConfirmingAction(null);
}
if (!canRead) {
return (
<WorkspaceFrame as="main" height="viewport" surface="plain" className="notifications-page" label="Notification center">
<div className="notifications-permission-state">
<ActionBlockerHint
tone="warning"
reason={{
summary: "i18n:govoplan-notifications.read_blocked_summary",
details: NOTIFICATIONS_I18N.readPermissionRequired,
requiredAction: "i18n:govoplan-notifications.permission_action",
actor: "i18n:govoplan-notifications.permission_actor",
target: "i18n:govoplan-notifications.permission_target"
}}
labels={NOTIFICATIONS_BLOCKER_LABELS}
documentation={NOTIFICATIONS_DOCUMENTATION}
/>
</div>
</WorkspaceFrame>
);
}
return (
<WorkspaceFrame as="main" height="viewport" surface="plain" className="notifications-page" label="Notification center">
<WorkspaceLayout
variant="split"
primarySize="default"
primaryScrollable={false}
contentScrollable={false}
surface="contained"
primaryClassName="notifications-sidebar"
contentClassName="notifications-workspace"
primaryLabel="i18n:govoplan-notifications.notifications"
contentLabel="i18n:govoplan-notifications.surface.center"
interfaceId="notifications.center.workspace"
helpContextId="notifications.page.center"
helpModuleId="notifications"
primary={<>
<WorkspaceActionBar
scope="collection-pane"
variant="collection"
refreshable
reloadAction={{ onReload: () => void load(), loading: loading || busy, label: "i18n:govoplan-notifications.refresh" }}
className="notifications-sidebar-bar"
contextActions={<div className="notifications-title">
<Bell size={17} />
<strong>i18n:govoplan-notifications.notifications</strong>
{unreadCount > 0 ? <CountBadge>{unreadCount}</CountBadge> : null}
</div>}
/>
<MultiSelectFilter
className="notifications-status-filter"
options={statusFilters.map((status) => ({ value: status, label: statusLabel(status) }))}
value={statusFilter}
onChange={setStatusFilter}
label="i18n:govoplan-notifications.notification_status"
disabled={busy}
/>
<div className="notifications-list">
{loading ? <div className="notifications-note">i18n:govoplan-notifications.loading_notifications</div> : null}
{!loading && notifications.length === 0 ? <div className="notifications-note">i18n:govoplan-notifications.no_notifications</div> : null}
{notifications.length > 0 ? (
<SelectionList variant="navigation" label="i18n:govoplan-notifications.notifications" className="notifications-selection-list">
{notifications.map((notification) => (
<SelectionListItem
key={notification.id}
selected={selected?.id === notification.id}
className={`notifications-list-item ${notification.read_at ? "is-read" : ""}`}
onClick={() => setSelectedId(notification.id)}
>
<span className="notifications-list-heading">
<strong>{notification.subject || notification.event_kind}</strong>
<small>{formatStatus(notification.status)}</small>
</span>
<span className="notifications-list-meta">
<span>{notification.source_module}</span>
<span>{formatDate(notification.created_at)}</span>
</span>
</SelectionListItem>
))}
</SelectionList>
) : null}
</div>
</>}
>
<WorkspaceActionBar
scope="detail-pane"
variant="detail"
className="notifications-topbar"
contextActions={<div className="notifications-title-line">
<Bell size={18} />
<strong>{selected?.subject || selected?.event_kind || "i18n:govoplan-notifications.surface.center"}</strong>
</div>}
helpAction={<DocumentationHelpLink reference={NOTIFICATIONS_DOCUMENTATION} />}
primaryActions={<div className="notifications-actions">
<Button onClick={() => void markSelected("read")} disabled={Boolean(markReadDisabledReason)} disabledReason={markReadDisabledReason}>
<Check size={16} /> i18n:govoplan-notifications.mark_read
</Button>
<Button onClick={() => void markSelected("acknowledged")} disabled={Boolean(acknowledgeDisabledReason)} disabledReason={acknowledgeDisabledReason}>
<Check size={16} /> i18n:govoplan-notifications.acknowledge
</Button>
<Button onClick={() => setConfirmingAction("dispatch")} disabled={Boolean(dispatchDisabledReason)} disabledReason={dispatchDisabledReason}>
<Send size={16} /> i18n:govoplan-notifications.dispatch_pending
</Button>
</div>}
destructiveActions={<Button variant="danger" onClick={() => setConfirmingAction("cancel")} disabled={Boolean(cancelDisabledReason)} disabledReason={cancelDisabledReason}>
<XCircle size={16} /> i18n:govoplan-notifications.cancel_delivery
</Button>}
/>
{error ? <DismissibleAlert tone="danger" compact resetKey={error}>{error}</DismissibleAlert> : null}
{selected && !canWrite ? (
<ActionBlockerHint
tone="info"
reason={{
summary: "i18n:govoplan-notifications.actions_read_only_summary",
details: NOTIFICATIONS_I18N.writePermissionRequired,
requiredAction: "i18n:govoplan-notifications.permission_action",
actor: "i18n:govoplan-notifications.permission_actor",
target: "i18n:govoplan-notifications.permission_target"
}}
labels={NOTIFICATIONS_BLOCKER_LABELS}
documentation={NOTIFICATIONS_DOCUMENTATION}
/>
) : null}
{selected ? <NotificationDetails notification={selected} /> : (
<StatePanel size="fill" icon={<Bell size={22} />} title="i18n:govoplan-notifications.notifications" description="i18n:govoplan-notifications.select_notification_help" />
)}
</WorkspaceLayout>
<ConfirmDialog
open={confirmingAction === "cancel"}
title="i18n:govoplan-notifications.cancel_delivery_title"
message={i18nMessage("i18n:govoplan-notifications.cancel_delivery_message", { value0: selected?.subject || selected?.event_kind || "i18n:govoplan-notifications.selected_notification" })}
confirmLabel="i18n:govoplan-notifications.cancel_delivery"
tone="danger"
busy={busy}
onCancel={() => setConfirmingAction(null)}
onConfirm={() => void confirmAction()}
/>
<ConfirmDialog
open={confirmingAction === "dispatch"}
title="i18n:govoplan-notifications.dispatch_pending_title"
message="i18n:govoplan-notifications.dispatch_pending_message"
confirmLabel="i18n:govoplan-notifications.dispatch_pending"
busy={busy}
onCancel={() => setConfirmingAction(null)}
onConfirm={() => void confirmAction()}
/>
</WorkspaceFrame>
);
}
function NotificationDetails({ notification }: { notification: NotificationMessage }) {
const actionUrl = safeNotificationActionUrl(notification.action_url);
return (
<div className="notifications-detail">
<section className="notifications-message">
<div className="notifications-message-meta">
<StatusBadge status={notification.status} label={formatStatus(notification.status)} />
<span>{notification.channel}</span>
<span>{formatDate(notification.created_at)}</span>
</div>
<h1>{notification.subject || notification.event_kind}</h1>
{notification.body_text ? <p>{notification.body_text}</p> : <p className="muted">i18n:govoplan-notifications.no_message_body</p>}
{actionUrl ? (
<a className="notifications-action-link" href={actionUrl}>
<ExternalLink size={16} /> i18n:govoplan-notifications.open_related_item
</a>
) : null}
</section>
<section className="notifications-properties">
<h2>i18n:govoplan-notifications.source_and_delivery</h2>
<dl>
<div><dt>i18n:govoplan-notifications.source</dt><dd>{notification.source_module} / {notification.source_resource_type}</dd></div>
<div><dt>i18n:govoplan-notifications.resource</dt><dd>{notification.source_resource_id || "i18n:govoplan-notifications.none"}</dd></div>
<div><dt>i18n:govoplan-notifications.recipient</dt><dd>{notification.recipient_label || notification.recipient || notification.recipient_id || "i18n:govoplan-notifications.none"}</dd></div>
<div><dt>i18n:govoplan-notifications.priority</dt><dd>{notification.priority}</dd></div>
<div><dt>i18n:govoplan-notifications.queued</dt><dd>{formatDate(notification.queued_at)}</dd></div>
<div><dt>i18n:govoplan-notifications.sent</dt><dd>{formatDate(notification.sent_at)}</dd></div>
<div><dt>i18n:govoplan-notifications.read</dt><dd>{formatDate(notification.read_at)}</dd></div>
<div><dt>i18n:govoplan-notifications.attempts</dt><dd>{notification.attempt_count}</dd></div>
</dl>
{notification.last_error ? <p className="notifications-error">{notification.last_error}</p> : null}
</section>
<section className="notifications-attempts">
<ActionToolbar surface="section-header" className="notifications-section-heading">
<h2>i18n:govoplan-notifications.delivery_attempts</h2>
<DocumentationHelpLink reference={NOTIFICATIONS_DELIVERY_DOCUMENTATION} />
</ActionToolbar>
{notification.attempts.length === 0 ? <p className="muted">i18n:govoplan-notifications.no_delivery_attempt</p> : null}
{notification.attempts.map((attempt) => (
<div className="notifications-attempt" key={attempt.id}>
<strong>{attempt.provider || attempt.channel}</strong>
<span>{formatStatus(attempt.status)}</span>
<small>{formatDate(attempt.started_at)} - {formatDate(attempt.finished_at)}</small>
{attempt.error ? <p>{attempt.error}</p> : null}
</div>
))}
</section>
</div>
);
}
function formatStatus(value: string): string {
return statusLabel(value);
}
function statusLabel(value: string): string {
return `i18n:govoplan-notifications.status.${value.replace(/[^a-z0-9]+/gi, "_").toLowerCase()}`;
}
function formatDate(value?: string | null): string {
if (!value) return "i18n:govoplan-notifications.not_set";
const date = new Date(value);
if (Number.isNaN(date.getTime())) return value;
return new Intl.DateTimeFormat(undefined, {
dateStyle: "medium",
timeStyle: "short"
}).format(date);
}
function errorMessage(error: unknown): string {
return error instanceof Error ? error.message : "i18n:govoplan-notifications.request_failed";
}
function notifyNotificationsChanged(): void {
window.dispatchEvent(new CustomEvent("govoplan:notifications-changed"));
}