import { useCallback, useEffect, useRef, useState } from "react"; import type { HTMLAttributes } from "react"; import { API_V1, CREDENTIALS } from "../../apiContract"; import { ModeIcon, useOverlayLayer } from "../../customer-grid/seam"; import "../../styles/sdlc81/operator-wasted.css"; interface Term { id: string; term: string; spend: number; clicks: number; campaign_id: string; campaign?: string; ad_type: string; profile_id: string; connection_id?: string; ad_group_id: string; outcome: { status: string; cause: string | null } | null; } interface Group { id: string; label: string; cost: number; term_count: number; reason: string | null; digest: string; status: string; decided_by: string | null; decided_at: string | null; terms: Term[]; terms_cursor: string | null; } interface Report { digest: string | null; state: string; reason: string | null; groups: Group[]; cursor: string | null; total_spend: number | null; group_count: number; term_count: number; window_days?: number; } type Load = { phase: "loading" } | { phase: "error"; message: string; denied: boolean } | { phase: "ready"; report: Report }; type GridHook = () => { selected: string; table: HTMLAttributes }; const money = (value: number | null) => value === null ? "Unavailable" : new Intl.NumberFormat(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }).format(value); const statusLabel = (status: string) => ({ proposed: "Proposed", sending: "Sending", sent: "Sent", refused: "Refused", partial: "Partly sent", unknown: "Outcome unknown" })[status] || status; async function request(url: string, options: RequestInit = {}) { const response = await fetch(url, { credentials: CREDENTIALS, ...options }); const body = await response.json().catch(() => null); if (!response.ok) throw Object.assign(new Error(body?.detail?.error?.message || "Wasted spend could not be loaded."), { denied: response.status === 403 || response.status === 404 }); return body; } function TermGrid({ group, useGridSelection }: { group: Group; useGridSelection: GridHook }) { const grid = useGridSelection(); return
{group.terms.map((term, index) => )}
#TermSpendClicks CampaignAd groupProfile Match typeOutcome
{index + 1}{term.term}{money(term.spend)} {term.clicks}{term.campaign || term.campaign_id}{term.campaign_id} {term.ad_group_id}{term.profile_id || "Unavailable"}{term.ad_type} {term.connection_id && {term.connection_id}} Negative exact {statusLabel(term.outcome?.status || "proposed")}{term.outcome?.cause && {term.outcome.cause}}
; } function GroupDetail({ initial, endpoint, useGridSelection, onClose }: { initial: Group; endpoint: (params: Record) => string; useGridSelection: GridHook; onClose: () => void; }) { const [group, setGroup] = useState(initial); const [busy, setBusy] = useState(false), [error, setError] = useState(""); const panel = useRef(null); const alive = useRef(true); useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); useOverlayLayer({ panelRef: panel, onDismiss: onClose, dismissOnOutside: false, trapFocus: true, restoreFocus: true }); const more = async () => { if (!group.terms_cursor || busy) return; setBusy(true); setError(""); try { const report: Report = await request(endpoint({ group_id: group.id, terms_cursor: group.terms_cursor })); const next = report.groups[0]; if (!next || next.digest !== group.digest) throw new Error("These groups changed. Close details and reload wasted spend."); if (alive.current) setGroup({ ...next, terms: [...group.terms, ...next.terms] }); } catch (reason) { if (alive.current) setError(reason instanceof Error ? reason.message : "Terms could not be loaded."); } finally { if (alive.current) setBusy(false); } }; return ; } export default function WastedSpend({ appId, editable, useGridSelection, onDecided }: { appId: string; editable: boolean; useGridSelection: GridHook; onDecided: () => void; }) { const [load, setLoad] = useState({ phase: "loading" }); const [attempt, setAttempt] = useState(0), [cursors, setCursors] = useState<(string | null)[]>([null]); const [opened, setOpened] = useState(null), [sending, setSending] = useState(""); const [error, setError] = useState(""); const pending = useRef(false), alive = useRef(true); const grid = useGridSelection(); useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []); const endpoint = useCallback((params: Record = {}) => `${API_V1}/app-kinds/amazon_operator/wasted?${new URLSearchParams({ app: appId, limit: "50", ...params })}`, [appId]); const cursor = cursors[cursors.length - 1]; useEffect(() => { const controller = new AbortController(); setLoad({ phase: "loading" }); void request(endpoint(cursor ? { cursor } : {}), { signal: controller.signal }).then((report: Report) => { if (!report || !Array.isArray(report.groups)) throw new Error("Wasted spend is unavailable."); if (!controller.signal.aborted) setLoad({ phase: "ready", report }); }).catch((reason: unknown) => { if (!controller.signal.aborted) setLoad({ phase: "error", message: reason instanceof Error ? reason.message : "Wasted spend could not be loaded.", denied: (reason as { denied?: boolean })?.denied === true }); }); return () => controller.abort(); }, [endpoint, cursor, attempt]); const approve = async (group: Group) => { if (!editable || pending.current || group.status !== "proposed") return; pending.current = true; setSending(group.id); setError(""); try { await request(`${API_V1}/app-kinds/amazon_operator/wasted/${encodeURIComponent(group.id)}/approve?${new URLSearchParams({ app: appId })}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ digest: group.digest }) }); } catch (reason) { if (alive.current) setError(reason instanceof Error ? reason.message : "Approval outcome is unavailable. Reload wasted spend."); } finally { pending.current = false; if (alive.current) { setSending(""); setAttempt((value) => value + 1); onDecided(); } } }; return
Grid view Wasted spend
{error &&

{error}

} {load.phase === "loading" ?
: load.phase === "error" ?

{load.denied ? "You do not have access to wasted spend." : load.message}

: <>
{money(load.report.total_spend)}Wasted spend {load.report.term_count} {load.report.term_count === 1 ? "term" : "terms"} · {load.report.group_count} {load.report.group_count === 1 ? "group" : "groups"} {load.report.window_days && {load.report.window_days} {load.report.window_days === 1 ? "day" : "days"}}
{load.report.reason &&

{load.report.reason}

} {!load.report.groups.length ?

{load.report.state === "empty" ? "No wasted spend" : load.report.reason || "No wasted spend"}

:
{editable && }{load.report.groups.map((group, index) => {editable && } )}
#GroupSpendTerms Proposed negativesMatch typeOutcomeApproval
{(cursors.length - 1) * 50 + index + 1} {money(group.cost)}{group.term_count} Negative exact{statusLabel(group.status)}{group.decided_by && by {group.decided_by}} {group.terms.filter((term) => term.outcome && term.outcome.status !== "sent").map((term) => {term.term}: {term.outcome!.cause})}{group.status === "proposed" && }
} } {opened && setOpened(null)} />}
; }