Download web/src/apps/amazon-operator/AdsOverview.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 18.8 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/9291c0100f4e7b8da2efcbbf1ebdea72ee1663e7/web/src/apps/amazon-operator/AdsOverview.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable@9291c0100f4e7b8da2efcbbf1ebdea72ee1663e7/web/src/apps/amazon-operator/AdsOverview.tsx
-
curl -L -o AdsOverview.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/9291c0100f4e7b8da2efcbbf1ebdea72ee1663e7/web/src/apps/amazon-operator/AdsOverview.tsx
18.8 kB
| 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<OperatorTabsProps>; | |
| AppDashboard: ComponentType<OperatorDashboardProps>; | |
| } | |
| export const OperatorDashboardContext = createContext<OperatorDashboardAdapter | null>(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<string, unknown> => value && typeof value === "object" | |
| && !Array.isArray(value) ? value as Record<string, unknown> : {}; | |
| 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 <div className="ao-dashboard-loading"><span className="lp-spin lp-spin--lg" role="status" | |
| aria-label="Loading dashboard" /></div>; | |
| } | |
| function Failure({ state, retry }: { state: Extract<Load, { phase: "error" }>; retry: () => void }) { | |
| return <div className="ao-dashboard-notice" role="status"> | |
| <span>{state.denied ? "No permission to view this Dashboard" : state.message}</span> | |
| {!state.denied && <button type="button" className="ao-button" onClick={retry}>Retry</button>} | |
| </div>; | |
| } | |
| 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<FilterTree>({ 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<HTMLTableElement>(null); | |
| const navigate = (event: KeyboardEvent<HTMLTableElement>) => { | |
| const target = event.target as HTMLElement; | |
| if (target.closest("button")) return; | |
| const cells = Array.from(ref.current?.querySelectorAll<HTMLTableCellElement>("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 <section className="ao-grid-shell ao-campaign-grid" data-surface="operator-campaign-grid" aria-busy={busy}> | |
| <div className="ao-grid-toolbar"><span className="ao-grid-view"><ModeIcon mode="grid" />Grid view</span> | |
| <h3>Campaigns</h3> | |
| <Popover label="Sort" icon={<SortAscending size={16} aria-hidden="true" />} active={sorts.length > 0} tone="sort" wide> | |
| {() => <div role="group" aria-label="Sort campaigns"><SortBuilder fields={CAMPAIGN_FIELDS} | |
| fieldByKey={new Map(CAMPAIGN_FIELDS.map(field => [field.key, field]))} sorts={sorts} onSorts={onSorts} | |
| filters={filters} onFilters={setFilters} grouped={false} /></div>} | |
| </Popover> | |
| </div> | |
| <div className="ao-grid-viewport"><table ref={ref} role="grid" tabIndex={0} onKeyDown={navigate} | |
| className="ao-table" aria-label="Campaigns grid"> | |
| <thead><tr><th scope="col" aria-label="Row">#</th>{CAMPAIGN_COLUMNS.map(([key, label]) => | |
| <th key={key} scope="col" className={key === "campaign" ? "" : "is-num"} | |
| aria-sort={sort === key ? descending ? "descending" : "ascending" : "none"}> | |
| <button type="button" className="ao-campaign-sort" disabled={busy} aria-label={`Sort by ${label.toLowerCase()}`} | |
| onClick={() => onSort(key)}>{label}{sort === key ? descending ? " ↓" : " ↑" : ""}</button></th>)}</tr></thead> | |
| <tbody>{rows.map((row, index) => { | |
| const id = JSON.stringify([row.ad_type, row.connection_id, row.profile_id, row.campaign_id]); | |
| return <tr key={id} className="ao-row" data-row-id={id} aria-selected={selected === id}> | |
| <td tabIndex={-1} className="ao-grid-marker">{index + 1}</td> | |
| <td tabIndex={-1} title={`${row.campaign || row.campaign_id} (${row.ad_type})`}>{row.campaign || row.campaign_id} | |
| {row.ad_type === "sp" && row.connection_id && row.profile_id && <button type="button" className="ao-link ao-campaign-hour" | |
| aria-label={`By hour for ${row.campaign || row.campaign_id}`} onClick={() => onHour(row)}>By hour</button>}</td> | |
| {(["spend", "sales", "orders", "acos"] as const).map((key) => | |
| <td key={key} tabIndex={-1} className="is-num">{format(row[key], key)}</td>)} | |
| </tr>; | |
| })}</tbody> | |
| </table>{!rows.length && <p className="ao-empty" role="status">No campaigns in this period</p>}</div> | |
| <nav className="ao-bar ao-grid-footer" aria-label="Campaign pages"> | |
| <button type="button" className="ao-button" disabled={busy || previous === undefined} | |
| onClick={() => onPage(previous ?? null)}>Previous</button><span>{page.total.toLocaleString()} campaigns</span> | |
| <button type="button" className="ao-button" disabled={busy || page.cursor === null} | |
| onClick={() => onPage(page.cursor)}>Next</button> | |
| </nav> | |
| </section>; | |
| } | |
| export default function AdsOverview({ appId, end: fixedEnd }: { appId: string; end?: string }) { | |
| const adapter = useContext(OperatorDashboardContext); | |
| const [days, setDays] = useState(30); | |
| const [compare, setCompare] = useState<Comparison>("prior"); | |
| const [sorts, setSorts] = useState<SortSpec>([{ 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<Campaign | null>(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 <div className="ao-dashboard" data-surface="operator-dashboard"> | |
| <WeeklySummary key={appId} appId={appId} /> | |
| <div className="ao-bar ao-dashboard-controls"><label className="ao-field"><span>Period</span> | |
| <select className="ao-select" aria-label="Dashboard period" value={days} | |
| onChange={(event) => { setDays(Number(event.target.value)); setCursors([null]); }}> | |
| {[7, 30, 90].map((value) => <option key={value} value={value}>Last {value} days</option>)} | |
| </select></label> | |
| <div className="ao-comparison" role="group" aria-label="Compare with"> | |
| {([["prior", "Prior window"], ["year", "Year ago"]] as const).map(([value, label]) => | |
| <button key={value} type="button" className="ao-tab" aria-pressed={compare === value} | |
| onClick={() => setCompare(value)}>{label}</button>)} | |
| </div> | |
| </div> | |
| {current.phase === "loading" ? <Loading /> : current.phase === "error" ? <Failure state={current} retry={retry} /> | |
| : !report ? <p role="status">Dashboard unavailable</p> | |
| : report.reason === NO_ADS ? <a className="ao-link" href="#/connectors">Connect Amazon Ads</a> | |
| : <> | |
| {report.reason && <p className="ao-dashboard-notice" role="status">{report.reason}</p>} | |
| <div data-surface="operator-comparison" aria-live="polite"> | |
| {previousOverview?.noPrior ? <p role="status">No prior data</p> | |
| : comparison.phase === "error" ? <Failure state={comparison} retry={retry} /> | |
| : comparison.phase === "loading" ? <span role="status">Loading comparison</span> | |
| : previousOverview?.state === "unavailable" || !previousOverview | |
| ? <span role="status">Comparison unavailable</span> : null} | |
| {previousFigures.phase === "error" && previousOverview && !previousOverview.noPrior | |
| && <Failure state={previousFigures} retry={retry} />} | |
| </div> | |
| {figures.phase === "loading" ? <Loading /> : figures.phase === "error" ? <Failure state={figures} retry={retry} /> | |
| : !checked.length ? <p role="status">Figures unavailable</p> | |
| : Dashboard ? <Dashboard figures={checked} comparison={previousOverview?.noPrior ? [] | |
| : previousFigures.phase === "ready" ? dashboardFigures(previousFigures.value) : []} | |
| groups={groups} start={start} end={end} comparisonLabel={compare === "prior" ? "Prior window" : "Year ago"} /> | |
| : <div data-surface="operator-dashboard-unavailable" role="status">Charts unavailable</div>} | |
| {checked.filter((figure) => !figure.validated).map((figure) => | |
| <p key={figure.id} className="ao-dashboard-notice" role="status">{figure.label}: {figure.reason}</p>)} | |
| <CampaignGrid page={report.campaigns} sort={sort} descending={descending} sorts={sorts} busy={false} onHour={setHourly} | |
| onSorts={value => { 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 && <ByHour key={JSON.stringify([hourly, start, end])} appId={appId} campaign={hourly} start={start} end={end} | |
| adapter={adapter} onClose={() => setHourly(null)} />} | |
| </div>; | |
| } | |