loopable / web /src /settings /NotifyDestinations.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
85f794d verified
Raw History Blame Contribute Delete
28.1 kB
import { useCallback, useEffect, useId, useRef, useState } from "react";
import type { FormEvent } from "react";
import { flushSync } from "react-dom";
import { CaretRight } from "@phosphor-icons/react";
import { Busy } from "../ui/Busy";
import { TOAST_EVENT } from "../apiContract";
import { connectorSetupRoute } from "./permsModel";
import {
getNotificationDestinations,
getNotificationSlackChannels,
saveNotificationDestinations,
} from "./settingsApi";
import type {
NotificationDestination,
NotificationDestinationPick,
NotificationDestinationsPayload,
NotificationReadiness,
NotificationSlackChannel,
NotificationWebhookDestination,
} from "./settingsApi";
import "../styles/sdlc81/notify-destinations.css";
import "./channels/channels.css";
type Picks = Record<string, NotificationDestinationPick>;
type Editor = { server: NotificationDestinationsPayload | null; drafts: Picks };
type Reason = { reason: string; message: string };
type SourcedReason = Reason & { source: "current" | "lastAttempt" };
function category(kind: string): string {
if (kind === "account_health_new_items" || kind === "amazon_operator_weekly") return "Account";
if (kind === "restock_digest") return "Inventory";
if (kind === "fixture") return "Testing";
return "Workspace";
}
function channelLabel(channel: NotificationSlackChannel | undefined, channelId: string): string {
return channel?.channelName
? (channel.channelName.startsWith("#") ? channel.channelName : `#${channel.channelName}`)
: channel?.label || channelId;
}
function deliveryState(row: NotificationDestination, destination: string, selected: boolean, pending: boolean,
reasons: SourcedReason[]): string {
if (!selected) return "Off";
if (pending) return "Save to check delivery";
if (reasons.some((reason) => reason.source === "current")) return "Unavailable";
if (row.delivery[destination]?.state === "refused") return "Last attempt refused";
if (row.delivery[destination]?.state === "sent") return "Last attempt sent";
return "No delivery yet";
}
// An older server row or draft can omit in-app and webhooks. Absent reads as off.
function inAppPicked(pick: Partial<NotificationDestinationPick> | undefined): boolean {
return pick?.inApp === true;
}
function savedWebhooks(pick: Partial<NotificationDestinationPick> | undefined): string[] {
return pick && Array.isArray(pick.webhooks) ? pick.webhooks : [];
}
function picks(row: NotificationDestinationPick): NotificationDestinationPick {
return {
slackChannels: [...row.slackChannels],
email: row.email?.trim() || null,
inApp: inAppPicked(row),
webhooks: [...savedWebhooks(row)],
};
}
function sameChannels(a: readonly string[], b: readonly string[]): boolean {
return JSON.stringify([...a].sort()) === JSON.stringify([...b].sort());
}
function samePicks(a: NotificationDestinationPick, b: NotificationDestinationPick): boolean {
return sameChannels(a.slackChannels, b.slackChannels) && (a.email?.trim() || null) === (b.email?.trim() || null)
&& inAppPicked(a) === inAppPicked(b) && sameChannels(savedWebhooks(a), savedWebhooks(b));
}
function refreshEditor(previous: Editor, server: NotificationDestinationsPayload, saved: Picks): Editor {
const drafts = { ...previous.drafts };
for (const row of server.destinations) {
const draft = drafts[row.kind];
const baseline = previous.server?.destinations.find((item) => item.kind === row.kind);
// Refresh clean or acknowledged drafts. Every other edit belongs to the user.
if (!draft || (baseline && samePicks(draft, baseline)) || (saved[row.kind] && samePicks(draft, saved[row.kind]))) {
drafts[row.kind] = picks(row);
}
}
return { server, drafts };
}
function reasonText(reason: string | null, message: string, email: boolean, channel = "Slack"): string {
if (reason === "not_configured") return "Slack is not connected.";
if (reason === "email_not_configured") return "Email is not available for this workspace.";
if (reason === "email_configuration_invalid") return "Email setup needs attention.";
if (reason === "in_app_unavailable") return "In-app is unavailable for this workspace.";
if (reason === "webhook_not_configured") return "Webhook is not set up.";
if (!message || /smtp|AIOS_[A-Z0-9_]+/i.test(message)) {
return email ? "Email delivery is unavailable." : `${channel} delivery is unavailable.`;
}
return message.replace(/[\u2013\u2014]/g, ", ");
}
function destinationReasons(
row: NotificationDestination,
destination: string,
readiness: NotificationReadiness | undefined,
extra?: Reason,
): SourcedReason[] {
const reasons: SourcedReason[] = [];
if (extra) reasons.push({ ...extra, source: "current" });
if (readiness?.available === false) {
const reason = readiness.reason || "unavailable";
if (!reasons.some((item) => item.reason === reason)) reasons.push({ reason, message: readiness.message, source: "current" });
}
const delivery = row.delivery[destination];
if (delivery?.state === "refused") {
const reason = delivery.reason || "delivery_failed";
if (!reasons.some((item) => item.reason === reason)) reasons.push({ reason, message: delivery.message || "", source: "lastAttempt" });
}
return reasons;
}
function DestinationReasons({ id, reasons, email = false, channel }: {
id: string; reasons: SourcedReason[]; email?: boolean; channel?: string;
}) {
return (
<div id={id} className="notify-destination-reasons">
{reasons.map((item) => (
<p key={item.reason} className="notify-destination-reason" data-reason={item.reason}>
{item.source === "lastAttempt" ? "Last attempt: " : ""}{reasonText(item.reason, item.message, email, channel)}
</p>
))}
</div>
);
}
export function NotifyDestinations({ onConnect }: { onConnect?: () => void } = {}) {
const id = useId();
const [editor, setEditor] = useState<Editor>({ server: null, drafts: {} });
const [collapsedCategories, setCollapsedCategories] = useState<Record<string, boolean>>({});
const [channels, setChannels] = useState<NotificationSlackChannel[]>([]);
const [slackConfigured, setSlackConfigured] = useState<boolean | null>(null);
const [loading, setLoading] = useState(true);
const [channelsLoading, setChannelsLoading] = useState(true);
const [readError, setReadError] = useState("");
const [channelsError, setChannelsError] = useState("");
const [writeErrors, setWriteErrors] = useState<Record<string, string>>({});
const [saving, setSaving] = useState(false);
const [needsRefresh, setNeedsRefresh] = useState(false);
const [feedback, setFeedback] = useState("");
const [noPermission, setNoPermission] = useState(false);
const emailDrafts = useRef<Record<string, string>>({});
const scope = useRef<AbortController | null>(null);
const flight = useRef(false);
const saved = useRef<Picks>({});
const refresh = useCallback(async (signal: AbortSignal) => {
setLoading(true);
setReadError("");
const result = await getNotificationDestinations(signal);
if (signal.aborted) return false;
setLoading(false);
if (result.ok === false) {
setNoPermission(result.status === 401 || result.status === 403);
setReadError("Notifications could not be loaded.");
return false;
}
setNoPermission(false);
const acknowledged = saved.current;
setEditor((previous) => refreshEditor(previous, result.data, acknowledged));
saved.current = {};
setNeedsRefresh(false);
return true;
}, []);
const loadChannels = useCallback(async (signal: AbortSignal) => {
setChannelsLoading(true);
setChannelsError("");
const options = new Map<string, NotificationSlackChannel>();
let after = "";
while (!signal.aborted) {
const result = await getNotificationSlackChannels(after, signal);
if (signal.aborted) return;
if (result.ok === false) {
setChannelsError(result.status === 403 ? "You do not have permission to view Slack channels." : "Slack channels could not be loaded.");
setChannelsLoading(false);
return;
}
const page = result.data;
for (const channel of page.channels) options.set(channel.channel, channel);
if (!page.configured || !page.nextCursor) {
setSlackConfigured(page.configured);
setChannels(page.configured ? [...options.values()] : []);
setChannelsLoading(false);
return;
}
if (page.nextCursor <= after) {
setChannelsError("Slack channels could not be loaded.");
setChannelsLoading(false);
return;
}
after = page.nextCursor;
}
}, []);
useEffect(() => {
const controller = new AbortController();
scope.current = controller;
void refresh(controller.signal);
void loadChannels(controller.signal);
return () => {
controller.abort();
scope.current = null;
};
}, [loadChannels, refresh]);
const kinds = editor.server?.destinations ?? [];
const changed = kinds.filter((row) => editor.drafts[row.kind] && !samePicks(row, editor.drafts[row.kind]));
const groups = new Map<string, NotificationDestination[]>();
for (const row of kinds) {
const name = category(row.kind);
groups.set(name, [...(groups.get(name) ?? []), row]);
}
const options = new Map(channels.map((channel) => [channel.channel, channel]));
// Saved destinations remain removable when their connection or discovery is unavailable.
const channelIds = [...new Set([
...(slackConfigured === true ? options.keys() : []),
...kinds.flatMap((row) => [...row.slackChannels, ...(editor.drafts[row.kind]?.slackChannels ?? [])]),
])];
const showEmail = !!editor.server && (editor.server.email.available
|| editor.server.email.reason !== "email_not_configured"
|| kinds.some((row) => row.email !== null || editor.drafts[row.kind]?.email != null));
const inApp = editor.server?.inApp;
const inAppDestination = inApp?.destination || "in-app:";
// A saved in-app pick or webhook id stays removable, the same rule the Slack ids follow.
const showInApp = !!editor.server && (inApp?.configured === true
|| kinds.some((row) => inAppPicked(row) || inAppPicked(editor.drafts[row.kind])));
const webhookOptions = new Map<string, NotificationWebhookDestination>(
(editor.server?.webhooks?.destinations ?? []).map((hook) => [hook.id, hook]));
const webhookIds = [...new Set([
...webhookOptions.keys(),
...kinds.flatMap((row) => [...savedWebhooks(row), ...savedWebhooks(editor.drafts[row.kind])]),
])];
const columnCount = 1 + Number(showInApp) + Number(showEmail) + channelIds.length + webhookIds.length;
function edit(kind: string, patch: Partial<NotificationDestinationPick>) {
setEditor((previous) => ({
...previous,
drafts: { ...previous.drafts, [kind]: { ...previous.drafts[kind], ...patch } },
}));
setWriteErrors((previous) => {
const next = { ...previous };
delete next[kind];
return next;
});
setFeedback("");
}
async function save(event: FormEvent<HTMLFormElement>) {
event.preventDefault();
const signal = scope.current?.signal;
if (!signal || signal.aborted || flight.current || loading || noPermission || needsRefresh || !changed.length) return;
flight.current = true;
setSaving(true);
setFeedback("");
setWriteErrors({});
let failed = false;
try {
for (const row of changed) {
const draft = picks(editor.drafts[row.kind]);
const patch: Partial<NotificationDestinationPick> = {};
if (!sameChannels(row.slackChannels, draft.slackChannels)) patch.slackChannels = draft.slackChannels;
if (row.email !== draft.email) patch.email = draft.email;
if (inAppPicked(row) !== draft.inApp) patch.inApp = draft.inApp;
if (!sameChannels(savedWebhooks(row), draft.webhooks)) patch.webhooks = draft.webhooks;
const result = await saveNotificationDestinations(row.kind, patch, signal);
if (signal.aborted) return;
if (result.ok === false) {
setWriteErrors({ [row.kind]: result.message });
failed = true;
break;
}
// The write response has no projection. Only a fresh GET can replace server state.
saved.current[row.kind] = draft;
setNeedsRefresh(true);
}
if (Object.keys(saved.current).length) {
const refreshed = await refresh(signal);
if (!signal.aborted) {
setFeedback(refreshed ? "" : "Saved picks need a status refresh.");
if (refreshed && !failed) window.dispatchEvent(new CustomEvent(TOAST_EVENT, {
detail: { text: "Notification preferences saved", tone: "info" },
}));
}
}
} finally {
if (!signal.aborted) {
flight.current = false;
setSaving(false);
}
}
}
return (
<div className="set-pane notify-destinations" aria-busy={loading || saving}>
<h3 className="set-title set-h">Notifications</h3>
{noPermission ? <p className="notify-empty" role="status">You do not have permission to view notifications</p> : readError ? (
<div className="notify-error" role="alert">
<p>{readError}</p>
<button type="button" className="set-secondary notify-retry" disabled={loading || saving}
onClick={() => { if (scope.current) void refresh(scope.current.signal); }}>Retry</button>
</div>
) : null}
{!editor.server && loading ? (
<div className="set-skeleton notify-matrix-skeleton" role="status" aria-label="Loading notifications">
{Array.from({ length: 6 }, (_, index) => <div className="notify-skeleton-row" key={index} aria-hidden="true">
<span className="set-skeleton-line" /><span className="set-skeleton-line" /><span className="set-skeleton-line" />
</div>)}
</div>
) : editor.server && !noPermission ? (
<form className="notify-form" onSubmit={(event) => void save(event)}>
<div className="notify-slack-status">
{slackConfigured === false ? (
<p className="notify-slack-connect">Slack is not connected. <a href={connectorSetupRoute("slack")} onClick={onConnect}>Connect</a></p>
) : channelsLoading ? (
<div className="set-skeleton notify-channel-loading" role="status" aria-label="Loading Slack channels">
<span className="set-skeleton-line" aria-hidden="true" />
</div>
) : !channelsError && slackConfigured === true && channels.length === 0 ? <p>No Slack channels available</p> : null}
{channelsError ? (
<div className="notify-error" role="alert">
<p>{channelsError}</p>
<button type="button" className="set-secondary notify-channels-retry" disabled={channelsLoading || saving}
onClick={() => { if (scope.current) void loadChannels(scope.current.signal); }}>Retry</button>
</div>
) : null}
</div>
<div className="notify-matrix-scroll" role="region" aria-label="Notification preferences" tabIndex={0}>
<table className="set-table notify-matrix" aria-label="Notification preferences by channel">
<thead><tr>
<th scope="col">Notification type</th>
{showInApp ? <th scope="col" className="notify-channel-heading">In-app</th> : null}
{showEmail ? <th scope="col" className="notify-channel-heading">Email</th> : null}
{channelIds.map((channelId) => <th scope="col" className="notify-channel-heading" key={channelId}>
Slack<span className="notify-channel-name">{channelLabel(options.get(channelId), channelId)}</span>
</th>)}
{webhookIds.map((hookId) => <th scope="col" className="notify-channel-heading" key={`webhook:${hookId}`}>
Webhook<span className="notify-channel-name">{webhookOptions.get(hookId)?.label || hookId}</span>
</th>)}
</tr></thead>
{[...groups].map(([name, rows]) => <tbody key={name} onInvalidCapture={() => {
// Reveal invalid drafts before native form validation moves focus.
if (collapsedCategories[name]) flushSync(() => setCollapsedCategories((previous) => ({ ...previous, [name]: false })));
}}>
<tr className="notify-category"><th scope="rowgroup" colSpan={columnCount}>
<button type="button" className="notify-category-toggle"
aria-expanded={!collapsedCategories[name]}
aria-controls={rows.map((row) => `${id}-${row.kind}-row`).join(" ")}
onClick={() => setCollapsedCategories((previous) => ({ ...previous, [name]: !previous[name] }))}>
<CaretRight size={16} className="notify-category-caret" aria-hidden="true" />
{name}
</button>
</th></tr>
{rows.map((row) => {
const draft = editor.drafts[row.kind] ?? picks(row);
const kindId = `${id}-${row.kind}`;
const emailDestination = `email:${draft.email?.trim() || ""}`;
const emailReadiness = row.readiness[emailDestination] ?? editor.server?.email;
const emailReasons = destinationReasons(row, emailDestination, emailReadiness);
const emailState = deliveryState(row, emailDestination, draft.email !== null,
draft.email !== row.email, emailReasons);
const inAppSelected = inAppPicked(draft);
const inAppReasons = destinationReasons(row, inAppDestination, row.readiness[inAppDestination] ?? inApp);
const inAppState = deliveryState(row, inAppDestination, inAppSelected, !inAppPicked(row), inAppReasons);
const draftWebhooks = savedWebhooks(draft);
return (
<tr key={row.kind} id={`${kindId}-row`} data-kind={row.kind} hidden={!!collapsedCategories[name]}>
<th scope="row" id={`${kindId}-title`} className="notify-event">
{row.label}
{writeErrors[row.kind] ? <p className="notify-write-error" role="alert">{writeErrors[row.kind]}</p> : null}
</th>
{showInApp ? <td className="notify-matrix-cell" data-destination={inAppDestination}>
<div className="notify-cell-content">
<label className="notify-choice">
<input type="checkbox" className="notify-channel-pick" checked={inAppSelected}
disabled={saving || loading || needsRefresh || (!inAppSelected && inApp?.available !== true)}
aria-label={`${row.label}: in-app`}
aria-describedby={`${kindId}-in-app-state${inAppReasons.length ? ` ${kindId}-in-app-reason` : ""}`}
onChange={(event) => edit(row.kind, { inApp: event.target.checked })} />
</label>
<span id={`${kindId}-in-app-state`} className="notify-delivery-state"
data-state={inAppState === "Last attempt sent" ? "sent" : undefined}>{inAppState}</span>
<DestinationReasons id={`${kindId}-in-app-reason`} reasons={inAppReasons} channel="In-app" />
</div>
</td> : null}
{showEmail ? <td className="notify-matrix-cell" data-destination={emailDestination}>
<div className="notify-cell-content">
<label className="notify-choice">
<input type="checkbox" className="notify-channel-pick" checked={draft.email !== null}
disabled={saving || loading || needsRefresh || (draft.email === null && !editor.server?.email.available)}
aria-label={`${row.label}: email`}
aria-describedby={`${kindId}-email-state${emailReasons.length ? ` ${kindId}-email-reason` : ""}`}
onChange={(event) => {
if (draft.email) emailDrafts.current[row.kind] = draft.email;
edit(row.kind, { email: event.target.checked ? emailDrafts.current[row.kind] || row.email || "" : null });
}} />
</label>
{draft.email !== null ? <input id={`${kindId}-email`} className="notify-email" type="email"
aria-label={`${row.label}: email address`} placeholder="Email address" autoComplete="email" required
maxLength={254} value={draft.email} disabled={saving || loading || needsRefresh}
aria-describedby={`${kindId}-email-state${emailReasons.length ? ` ${kindId}-email-reason` : ""}`}
onChange={(event) => edit(row.kind, { email: event.target.value })} /> : null}
<span id={`${kindId}-email-state`} className="notify-delivery-state"
data-state={emailState === "Last attempt sent" ? "sent" : undefined}>
{draft.email === "" ? "Enter an email address" : emailState}
</span>
<DestinationReasons id={`${kindId}-email-reason`} reasons={emailReasons} email />
</div>
</td> : null}
{channelIds.map((channelId) => {
const option = options.get(channelId);
const selected = draft.slackChannels.includes(channelId);
const unavailable = slackConfigured !== true || !option?.active;
const destination = `slack:${channelId}`;
let extra: Reason | undefined;
if (slackConfigured === false) extra = { reason: "not_configured", message: "" };
else if (option?.active === false) extra = { reason: "channel_inactive", message: "This channel is inactive." };
else if (!option) extra = channelsLoading || channelsError
? { reason: "channel_unchecked", message: "Channel availability could not be checked." }
: { reason: "channel_unavailable", message: "This channel is no longer available." };
const reasons = destinationReasons(row, destination, row.readiness[destination], extra);
const reasonId = `${kindId}-${channelId}-reason`;
const label = channelLabel(option, channelId);
const state = deliveryState(row, destination, selected, !row.slackChannels.includes(channelId), reasons);
return (
<td key={channelId} className="notify-matrix-cell">
<ul className="notify-channel-list">
<li className="notify-channel notify-cell-content" data-destination={destination}>
<label className="notify-choice">
<input type="checkbox" className="notify-channel-pick" value={channelId}
checked={selected} disabled={saving || loading || needsRefresh || (!selected && unavailable)}
aria-label={`${row.label}: Slack ${label}`}
aria-describedby={`${kindId}-${channelId}-state${reasons.length ? ` ${reasonId}` : ""}`}
onChange={(event) => edit(row.kind, {
slackChannels: event.target.checked
? [...draft.slackChannels, channelId]
: draft.slackChannels.filter((value) => value !== channelId),
})} />
</label>
<span id={`${kindId}-${channelId}-state`} className="notify-delivery-state"
data-state={state === "Last attempt sent" ? "sent" : undefined}>{state}</span>
<DestinationReasons id={reasonId} reasons={reasons} />
</li>
</ul>
</td>
);
})}
{webhookIds.map((hookId) => {
const hook = webhookOptions.get(hookId);
const selected = draftWebhooks.includes(hookId);
const destination = `webhook:${hookId}`;
const readiness = row.readiness[destination]
?? hook ?? { available: false, reason: "webhook_not_configured", message: "" };
const reasons = destinationReasons(row, destination, readiness);
const cellId = `${kindId}-webhook-${hookId}`;
const label = hook?.label || hookId;
const state = deliveryState(row, destination, selected, !savedWebhooks(row).includes(hookId), reasons);
return (
<td key={destination} className="notify-matrix-cell" data-destination={destination}>
<div className="notify-cell-content">
<label className="notify-choice">
<input type="checkbox" className="notify-channel-pick" value={hookId}
checked={selected} disabled={saving || loading || needsRefresh || (!selected && !hook)}
aria-label={`${row.label}: webhook ${label}`}
aria-describedby={`${cellId}-state${reasons.length ? ` ${cellId}-reason` : ""}`}
onChange={(event) => edit(row.kind, {
webhooks: event.target.checked
? [...draftWebhooks, hookId]
: draftWebhooks.filter((value) => value !== hookId),
})} />
</label>
<span id={`${cellId}-state`} className="notify-delivery-state"
data-state={state === "Last attempt sent" ? "sent" : undefined}>{state}</span>
<DestinationReasons id={`${cellId}-reason`} reasons={reasons} channel="Webhook" />
</div>
</td>
);
})}
</tr>
);
})}
</tbody>)}
{kinds.length === 0 ? <tbody><tr><td colSpan={columnCount} className="notify-empty">No notifications available</td></tr></tbody> : null}
</table>
</div>
{columnCount === 1 && kinds.length > 0 && !channelsLoading && !channelsError
? <p className="notify-empty" role="status">No notification channels connected</p> : null}
<div className="set-actions notify-actions">
<button type="submit" className="set-primary notify-save"
disabled={saving || loading || needsRefresh || changed.length === 0}>
<Busy busy={saving} idle={Object.keys(writeErrors).length ? "Retry save" : "Save"} doing="Saving" />
</button>
<p className="notify-save-status" role="status">{feedback || (loading ? "Refreshing destinations" : "")}</p>
</div>
</form>
) : null}
</div>
);
}
export default NotifyDestinations;