import { createContext, useContext, useEffect, useRef, useState } from "react"; import type { ComponentType, KeyboardEvent } from "react"; import { SortAscending } from "@phosphor-icons/react"; import { ModeIcon } from "../../customer-grid/seam"; import { Popover, SortBuilder, runPipeline } from "../../filter-kit"; import type { Field, FilterTree, SortSpec } from "../../filter-kit"; import { API_V1, CREDENTIALS } from "../../apiContract"; import ByHour from "./ByHour"; import WeeklySummary from "./WeeklySummary"; import "../../styles/sdlc81/operator-dashboard.css"; export type OperatorTab = "dashboard" | "today" | "history" | "wasted" | "schedule" | "changes" | "pacing"; export interface OperatorTabsProps { tabs: [OperatorTab, string, number | null][]; value: OperatorTab; onChange: (value: OperatorTab) => void; } export interface DashboardFigure { id: string; label: string; value: number | null; unit: string; series: { date: string; value: number | null }[]; source_table: string; validated: boolean; reason: string | null; } export const OPERATOR_FIGURE_GROUPS = [ { id: "efficiency", label: "ACoS and TACoS", figures: ["acos", "tacos"] }, { id: "spend", label: "Spend and ad sales", figures: ["spend", "ad_sales"] }, { id: "sales", label: "Organic and ad sales", figures: ["organic_sales", "ad_sales"] }, { id: "proposals", label: "Proposals per week", figures: ["proposals_approved", "proposals_refused", "proposals_sent"] }, ]; export interface OperatorDashboardProps { figures: DashboardFigure[]; comparison: DashboardFigure[]; groups: typeof OPERATOR_FIGURE_GROUPS; start: string; end: string; comparisonLabel: string; } /** Integrate supplies wrappers around S81-T81 exports. No substitute chart kit ships here. */ export interface OperatorDashboardAdapter { AppTabs: ComponentType; AppDashboard: ComponentType; } export const OperatorDashboardContext = createContext(null); interface Overview { start: string; end: string; state: string; reason: string | null; noPrior: boolean; campaigns: { items: Campaign[]; total: number; cursor: string | null }; } interface Campaign { ad_type: string; connection_id: string; profile_id: string; campaign_id: string; campaign: string; spend: number | null; sales: number | null; orders: number | null; acos: number | null; } type Load = { phase: "loading" } | { phase: "error"; message: string; denied: boolean } | { phase: "ready"; value: unknown }; type Comparison = "prior" | "year"; type Sort = "spend" | "sales" | "orders" | "acos" | "campaign"; const CAMPAIGN_COLUMNS: [Sort, string][] = [["campaign", "Campaign"], ["spend", "Spend"], ["sales", "Ad sales"], ["orders", "Orders"], ["acos", "ACoS"]]; const CAMPAIGN_FIELDS: Field[] = CAMPAIGN_COLUMNS.map(([key, label]) => ({ key, label, source: "overlay", type: key === "campaign" ? "text" : key === "orders" ? "int" : key === "acos" ? "pct" : "currency" })); /** The first sort retains the overview endpoint's existing ordering and cursor contract. */ export function campaignSortRequest(sorts: SortSpec): { sort: Sort; descending: boolean } { const first = sorts.find(rule => CAMPAIGN_COLUMNS.some(([key]) => key === rule.colId)); return { sort: (first?.colId as Sort | undefined) ?? "spend", descending: first ? first.dir === "desc" : true }; } const NO_ADS = "The Amazon Ads connector is not installed."; const number = (value: unknown) => typeof value === "number" && Number.isFinite(value) ? value : null; const words = (value: unknown) => typeof value === "string" ? value : ""; const record = (value: unknown): Record => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; const day = (value: Date) => value.toISOString().slice(0, 10); export function comparisonWindow(start: string, end: string, mode: Comparison) { const first = new Date(`${start}T00:00:00Z`), last = new Date(`${end}T00:00:00Z`); if (mode === "prior") { const length = (last.getTime() - first.getTime()) / 86400000 + 1; first.setUTCDate(first.getUTCDate() - length); last.setUTCDate(last.getUTCDate() - length); } else { for (const date of [first, last]) { const month = date.getUTCMonth(); date.setUTCFullYear(date.getUTCFullYear() - 1); if (date.getUTCMonth() !== month) date.setUTCDate(0); } } return { start: day(first), end: day(last) }; } function useRead(endpoint: string | null, attempt: number): Load { const [state, setState] = useState<{ endpoint: string | null; load: Load }>({ endpoint, load: { phase: "loading" } }); useEffect(() => { if (!endpoint) return; const controller = new AbortController(); const timer = window.setTimeout(() => controller.abort(), 20000); let active = true; setState({ endpoint, load: { phase: "loading" } }); void fetch(endpoint, { credentials: CREDENTIALS, signal: controller.signal }).then(async (response) => { const body: unknown = await response.json().catch(() => null); if (!response.ok) { const message = words(record(record(record(body).detail).error).message) || "Dashboard unavailable"; if (active) setState({ endpoint, load: { phase: "error", message, denied: response.status === 401 || response.status === 403 } }); } else if (active) setState({ endpoint, load: { phase: "ready", value: body } }); }).catch(() => { if (active) setState({ endpoint, load: { phase: "error", message: "Dashboard could not be loaded", denied: false } }); }).finally(() => window.clearTimeout(timer)); return () => { active = false; window.clearTimeout(timer); controller.abort(); }; }, [endpoint, attempt]); return endpoint === state.endpoint ? state.load : { phase: "loading" }; } function overview(value: unknown): Overview | null { const body = record(value), page = record(body.campaigns); if (!words(body.start) || !words(body.end) || typeof body.noPrior !== "boolean" || !["ready", "partial", "unavailable"].includes(words(body.state)) || !Array.isArray(page.items) || number(page.total) === null || !(page.cursor === null || typeof page.cursor === "string")) return null; return { start: words(body.start), end: words(body.end), state: words(body.state), reason: words(body.reason) || null, noPrior: body.noPrior, campaigns: { total: number(page.total)!, cursor: page.cursor as string | null, items: page.items.map((value) => { const row = record(value); return { ad_type: words(row.ad_type), connection_id: words(row.connection_id), profile_id: words(row.profile_id), campaign_id: words(row.campaign_id), campaign: words(row.campaign), spend: number(row.spend), sales: number(row.sales), orders: number(row.orders), acos: number(row.acos) }; }) } }; } /** Only validated figures enter the shared renderer, including comparison figures. */ export function dashboardFigures(value: unknown): DashboardFigure[] { const body = record(value); if (!Array.isArray(body.figures)) return []; return body.figures.map((value) => { const row = record(value); const valid = row.validated === true && number(row.value) !== null && !!words(row.source_table) && Array.isArray(row.series) && row.series.every((point) => words(record(point).date) && (record(point).value === null || number(record(point).value) !== null)); return { id: words(row.id), label: words(row.label), unit: words(row.unit), source_table: words(row.source_table), value: valid ? number(row.value) : null, series: valid ? row.series as DashboardFigure["series"] : [], validated: valid, reason: valid ? null : words(row.reason) || "Figure unavailable" }; }); } function Loading() { return
; } function Failure({ state, retry }: { state: Extract; retry: () => void }) { return
{state.denied ? "No permission to view this Dashboard" : state.message} {!state.denied && }
; } function CampaignGrid({ page, sort, descending, sorts, onSorts, busy, onSort, onPage, previous, onHour }: { page: Overview["campaigns"]; sort: Sort; descending: boolean; busy: boolean; sorts: SortSpec; onSorts: (sorts: SortSpec) => void; onSort: (value: Sort) => void; onPage: (cursor: string | null) => void; previous: string | null | undefined; onHour: (campaign: Campaign) => void; }) { const [selected, setSelected] = useState(""); const [filters, setFilters] = useState({ conj: "and", nodes: [] }); const rows = runPipeline({ rawRows: page.items.map((row, index) => ({ pid: index + 1, campaign: row.campaign, spend: row.spend, sales: row.sales, orders: row.orders, acos: row.acos })), fields: CAMPAIGN_FIELDS, sorts, filters: filters.nodes, filterConj: filters.conj, search: "", groupBy: null, collapsed: new Set() }).visibleRows.flatMap(row => row.kind === "data" ? [page.items[row.record.pid - 1]] : []); const ref = useRef(null); const navigate = (event: KeyboardEvent) => { const target = event.target as HTMLElement; if (target.closest("button")) return; const cells = Array.from(ref.current?.querySelectorAll("tbody td") ?? []); const index = cells.indexOf(target as HTMLTableCellElement); const jump = { ArrowRight: 1, ArrowLeft: -1, ArrowDown: 6, ArrowUp: -6 }[event.key]; if (jump !== undefined || event.key === "Home" || event.key === "End") { event.preventDefault(); cells[event.key === "Home" ? 0 : event.key === "End" ? cells.length - 1 : Math.max(0, Math.min(cells.length - 1, index < 0 ? 0 : index + jump!))]?.focus(); } else if (event.key === " ") { event.preventDefault(); setSelected(target.closest("tr")?.dataset.rowId || ""); } }; const format = (value: number | null, key: Sort) => value === null ? "Unavailable" : value.toLocaleString(undefined, { maximumFractionDigits: key === "orders" ? 0 : 2 }) + (key === "acos" ? "%" : ""); return
Grid view

Campaigns

{CAMPAIGN_COLUMNS.map(([key, label]) => )}{rows.map((row, index) => { const id = JSON.stringify([row.ad_type, row.connection_id, row.profile_id, row.campaign_id]); return {(["spend", "sales", "orders", "acos"] as const).map((key) => )} ; })}
#
{index + 1} {row.campaign || row.campaign_id} {row.ad_type === "sp" && row.connection_id && row.profile_id && }{format(row[key], key)}
{!rows.length &&

No campaigns in this period

}
; } export default function AdsOverview({ appId, end: fixedEnd }: { appId: string; end?: string }) { const adapter = useContext(OperatorDashboardContext); const [days, setDays] = useState(30); const [compare, setCompare] = useState("prior"); const [sorts, setSorts] = useState([{ colId: "spend", dir: "desc" }]); const { sort, descending } = campaignSortRequest(sorts); const [cursors, setCursors] = useState<(string | null)[]>([null]); const [attempt, setAttempt] = useState(0); const [hourly, setHourly] = useState(null); const [defaultEnd] = useState(() => day(new Date(Date.now() - 86400000))); const end = fixedEnd ?? defaultEnd; const first = new Date(`${end}T00:00:00Z`); first.setUTCDate(first.getUTCDate() - days + 1); const start = day(first), prior = comparisonWindow(start, end, compare); const endpoint = (path: string, from: string, to: string, extra = {}) => `${API_V1}/app-kinds/amazon_operator/${path}?` + new URLSearchParams({ app: appId, start: from, end: to, ...extra }).toString(); const current = useRead(endpoint("overview", start, end, { sort, descending: String(descending), limit: "50", ...(cursors.at(-1) ? { cursor: cursors.at(-1)! } : {}) }), attempt); const comparison = useRead(endpoint("overview", prior.start, prior.end, { limit: "1" }), attempt); const figures = useRead(endpoint("dashboard", start, end), attempt); const previousOverview = comparison.phase === "ready" ? overview(comparison.value) : null; const previousFigures = useRead(previousOverview && !previousOverview.noPrior && previousOverview.state !== "unavailable" ? endpoint("dashboard", prior.start, prior.end) : null, attempt); const report = current.phase === "ready" ? overview(current.value) : null; const retry = () => setAttempt((value) => value + 1); const Dashboard = adapter?.AppDashboard; const groups = OPERATOR_FIGURE_GROUPS; const checked = figures.phase === "ready" ? dashboardFigures(figures.value) : []; return
{([["prior", "Prior window"], ["year", "Year ago"]] as const).map(([value, label]) => )}
{current.phase === "loading" ? : current.phase === "error" ? : !report ?

Dashboard unavailable

: report.reason === NO_ADS ? Connect Amazon Ads : <> {report.reason &&

{report.reason}

}
{previousOverview?.noPrior ?

No prior data

: comparison.phase === "error" ? : comparison.phase === "loading" ? Loading comparison : previousOverview?.state === "unavailable" || !previousOverview ? Comparison unavailable : null} {previousFigures.phase === "error" && previousOverview && !previousOverview.noPrior && }
{figures.phase === "loading" ? : figures.phase === "error" ? : !checked.length ?

Figures unavailable

: Dashboard ? :
Charts unavailable
} {checked.filter((figure) => !figure.validated).map((figure) =>

{figure.label}: {figure.reason}

)} { setSorts(value); setCursors([null]); }} onSort={(value) => { setSorts([{ colId: value, dir: value === sort && descending ? "asc" : "desc" }]); setCursors([null]); }} previous={cursors.length > 1 ? cursors[cursors.length - 2] : undefined} onPage={(cursor) => setCursors((stack) => cursor === stack[stack.length - 2] ? stack.slice(0, -1) : [...stack, cursor])} /> } {hourly && setHourly(null)} />}
; }