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; 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 | undefined): boolean { return pick?.inApp === true; } function savedWebhooks(pick: Partial | 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 (
{reasons.map((item) => (

{item.source === "lastAttempt" ? "Last attempt: " : ""}{reasonText(item.reason, item.message, email, channel)}

))}
); } export function NotifyDestinations({ onConnect }: { onConnect?: () => void } = {}) { const id = useId(); const [editor, setEditor] = useState({ server: null, drafts: {} }); const [collapsedCategories, setCollapsedCategories] = useState>({}); const [channels, setChannels] = useState([]); const [slackConfigured, setSlackConfigured] = useState(null); const [loading, setLoading] = useState(true); const [channelsLoading, setChannelsLoading] = useState(true); const [readError, setReadError] = useState(""); const [channelsError, setChannelsError] = useState(""); const [writeErrors, setWriteErrors] = useState>({}); const [saving, setSaving] = useState(false); const [needsRefresh, setNeedsRefresh] = useState(false); const [feedback, setFeedback] = useState(""); const [noPermission, setNoPermission] = useState(false); const emailDrafts = useRef>({}); const scope = useRef(null); const flight = useRef(false); const saved = useRef({}); 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(); 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(); 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( (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) { 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) { 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 = {}; 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 (

Notifications

{noPermission ?

You do not have permission to view notifications

: readError ? (

{readError}

) : null} {!editor.server && loading ? (
{Array.from({ length: 6 }, (_, index) => )}
) : editor.server && !noPermission ? (
void save(event)}>
{slackConfigured === false ? (

Slack is not connected. Connect

) : channelsLoading ? (
) : !channelsError && slackConfigured === true && channels.length === 0 ?

No Slack channels available

: null} {channelsError ? (

{channelsError}

) : null}
{showInApp ? : null} {showEmail ? : null} {channelIds.map((channelId) => )} {webhookIds.map((hookId) => )} {[...groups].map(([name, rows]) => { // Reveal invalid drafts before native form validation moves focus. if (collapsedCategories[name]) flushSync(() => setCollapsedCategories((previous) => ({ ...previous, [name]: false }))); }}> {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 ( {showInApp ? : null} {showEmail ? : 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 ( ); })} {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 ( ); })} ); })} )} {kinds.length === 0 ? : null}
Notification typeIn-appEmail Slack{channelLabel(options.get(channelId), channelId)} Webhook{webhookOptions.get(hookId)?.label || hookId}
No notifications available
{columnCount === 1 && kinds.length > 0 && !channelsLoading && !channelsError ?

No notification channels connected

: null}

{feedback || (loading ? "Refreshing destinations" : "")}

) : null}
); } export default NotifyDestinations;