Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/apps/amazon-operator/ByHour.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 10.2 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/amazon-operator/ByHour.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/apps/amazon-operator/ByHour.tsx
-
curl -L -o ByHour.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/amazon-operator/ByHour.tsx
10.2 kB
| import { useEffect, useRef, useState } from "react"; | |
| import type { KeyboardEvent } from "react"; | |
| import { API_V1, CREDENTIALS } from "../../apiContract"; | |
| import { ModeIcon, useOverlayLayer } from "../../customer-grid/seam"; | |
| import type { DashboardFigure, OperatorDashboardAdapter } from "./AdsOverview"; | |
| import "../../styles/sdlc81/operator-hourly.css"; | |
| export interface HourlyCampaign { | |
| ad_type: string; connection_id: string; profile_id: string; campaign_id: string; campaign: string; | |
| } | |
| interface Hour { | |
| date: string; hour: number; spend: number | null; clicks: number | null; orders: number | null; | |
| sales: number | null; acos: number | null; observed: boolean; reason: string | null; | |
| } | |
| interface Report { | |
| state: "ready" | "partial" | "empty" | "unavailable" | "unsupported"; | |
| reason: string | null; timezone: string | null; currency: string | null; source_table: string; | |
| rows: Hour[]; totals: Record<string, number | null>; | |
| validation: { ok: boolean; days: { date: string; ok: boolean; hourly_spend: number | null; | |
| daily_spend: number | null; reasons: string[] }[] }; | |
| } | |
| type Load = { phase: "loading" } | { phase: "error"; denied: boolean } | |
| | { phase: "ready"; report: Report }; | |
| const COLUMNS = [["spend", "Spend"], ["clicks", "Clicks"], ["orders", "Orders"], ["acos", "ACoS"]] as const; | |
| const GROUPS = COLUMNS.map(([id, label]) => ({ id, label, figures: [id] })); | |
| const format = (value: number | null, metric = "spend") => value === null ? "Unavailable" | |
| : value.toLocaleString(undefined, { maximumFractionDigits: metric === "orders" || metric === "clicks" ? 0 : 2 }) | |
| + (metric === "acos" ? "%" : ""); | |
| 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 metric = (value: unknown) => value === null || typeof value === "number" && Number.isFinite(value); | |
| function parse(value: unknown, campaign: HourlyCampaign, day: string): Report { | |
| const body = record(value), validation = record(body.validation); | |
| if (body.campaign_id !== campaign.campaign_id || body.ad_type !== "sp" || body.connection_id !== campaign.connection_id | |
| || body.profile_id !== campaign.profile_id || body.start !== day || body.end !== day | |
| || !["ready", "partial", "empty", "unavailable", "unsupported"].includes(words(body.state)) | |
| || !Array.isArray(body.rows) || body.rows.length !== 24 || typeof validation.ok !== "boolean" | |
| || !Array.isArray(validation.days) || validation.days.length !== 1 | |
| || !body.rows.every((value, index) => { | |
| const row = record(value); | |
| return row.date === day && row.hour === index && typeof row.observed === "boolean" | |
| && (row.reason === null || typeof row.reason === "string") | |
| && ["spend", "clicks", "orders", "sales", "acos"].every((key) => metric(row[key])); | |
| }) || !COLUMNS.every(([key]) => metric(record(body.totals)[key])) | |
| || !validation.days.every((value) => { | |
| const row = record(value); | |
| return row.date === day && typeof row.ok === "boolean" && metric(row.hourly_spend) && metric(row.daily_spend) | |
| && Array.isArray(row.reasons) && row.reasons.every((reason) => typeof reason === "string"); | |
| })) throw new Error("Hourly report unavailable"); | |
| return body as unknown as Report; | |
| } | |
| function HourGrid({ rows }: { rows: Hour[] }) { | |
| const ref = useRef<HTMLTableElement>(null); | |
| const [selected, setSelected] = useState(-1); | |
| const navigate = (event: KeyboardEvent<HTMLTableElement>) => { | |
| const cells = Array.from(ref.current?.querySelectorAll<HTMLTableCellElement>("tbody td") ?? []); | |
| const target = event.target as HTMLTableCellElement; | |
| const index = cells.indexOf(target); | |
| const jump = { ArrowDown: 5, ArrowUp: -5, ArrowRight: 1, ArrowLeft: -1 }[event.key]; | |
| if (jump !== undefined || event.key === "Home" || event.key === "End") { | |
| event.preventDefault(); | |
| const next = cells[event.key === "Home" ? 0 : event.key === "End" ? cells.length - 1 | |
| : Math.max(0, Math.min(cells.length - 1, index < 0 ? 0 : index + jump!))]; | |
| next?.focus(); next?.scrollIntoView({ block: "nearest", inline: "nearest" }); | |
| } else if (event.key === " " || event.key === "Enter") { | |
| event.preventDefault(); setSelected(Number(target.closest("tr")?.dataset.hour ?? -1)); | |
| } | |
| }; | |
| return <section className="ao-grid-shell ao-hour-grid" data-surface="operator-hourly-grid"> | |
| <div className="ao-grid-toolbar"><span className="ao-grid-view"><ModeIcon mode="grid" />Grid view</span></div> | |
| <div className="ao-grid-viewport"><table ref={ref} role="grid" tabIndex={0} onKeyDown={navigate} | |
| className="ao-table" aria-label="Hourly performance grid"> | |
| <thead><tr><th scope="col">Hour</th>{COLUMNS.map(([key, label]) => | |
| <th key={key} scope="col" className="is-num">{label}</th>)}</tr></thead> | |
| <tbody>{rows.map((row) => <tr key={row.hour} data-hour={row.hour} className="ao-row" | |
| aria-selected={selected === row.hour} title={row.reason || undefined}> | |
| <td tabIndex={-1}>{String(row.hour).padStart(2, "0")}:00{row.reason && <small>{row.reason}</small>}</td> | |
| {COLUMNS.map(([key]) => <td key={key} tabIndex={-1} className="is-num" data-metric={key}>{format(row[key], key)}</td>)} | |
| </tr>)}</tbody> | |
| </table></div> | |
| <div className="ao-grid-footer">24 local-hour slots</div> | |
| </section>; | |
| } | |
| export default function ByHour({ appId, campaign, start, end, adapter, onClose }: { | |
| appId: string; campaign: HourlyCampaign; start: string; end: string; | |
| adapter: OperatorDashboardAdapter | null; onClose: () => void; | |
| }) { | |
| const [day, setDay] = useState(end), [attempt, setAttempt] = useState(0); | |
| const [load, setLoad] = useState<Load>({ phase: "loading" }); | |
| const panel = useRef<HTMLElement | null>(null); | |
| useOverlayLayer({ panelRef: panel, onDismiss: onClose, dismissOnOutside: false, trapFocus: true, restoreFocus: true }); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| const timer = window.setTimeout(() => controller.abort(), 20000); | |
| let active = true; | |
| setLoad({ phase: "loading" }); | |
| const params = new URLSearchParams({ app: appId, campaign_id: campaign.campaign_id, ad_type: campaign.ad_type, | |
| connection_id: campaign.connection_id, profile_id: campaign.profile_id, start: day, end: day }); | |
| void fetch(`${API_V1}/app-kinds/amazon_operator/by-hour?${params}`, { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then(async (response) => { | |
| if (!response.ok) throw Object.assign(new Error("Hourly report unavailable"), | |
| { denied: [401, 403, 404].includes(response.status) }); | |
| const report = parse(await response.json(), campaign, day); | |
| if (active) setLoad({ phase: "ready", report }); | |
| }).catch((error: unknown) => { | |
| if (active) setLoad({ phase: "error", denied: record(error).denied === true }); | |
| }).finally(() => window.clearTimeout(timer)); | |
| return () => { active = false; controller.abort(); window.clearTimeout(timer); }; | |
| }, [appId, campaign, day, attempt]); | |
| const report = load.phase === "ready" ? load.report : null; | |
| const Dashboard = adapter?.AppDashboard; | |
| const figures: DashboardFigure[] = report ? COLUMNS.map(([id, label]) => ({ id, label, | |
| value: report.validation.ok ? report.totals[id] : null, unit: id === "acos" ? "%" : id === "spend" ? report.currency || "" : "", | |
| source_table: report.source_table, validated: report.validation.ok, | |
| reason: report.validation.ok ? null : "Hourly coverage or daily spend needs review", | |
| series: report.validation.ok ? report.rows.map((row) => ({ date: `${row.date}T${String(row.hour).padStart(2, "0")}:00:00`, | |
| value: row[id] })) : [] })) : []; | |
| return <aside ref={panel} role="dialog" aria-modal="true" aria-label="Campaign by hour" | |
| className="ao-drawer ao-hourly" data-surface="operator-hourly"> | |
| <div className="ao-drawer-head"><h2 className="ao-drawer-title">By hour</h2> | |
| <button type="button" className="ao-button is-quiet" onClick={onClose}>Close</button></div> | |
| <p className="ao-hourly-campaign" title={campaign.campaign || campaign.campaign_id}>{campaign.campaign || campaign.campaign_id}</p> | |
| <label className="ao-field ao-hourly-day"><span>Day</span><input className="ao-select" type="date" value={day} | |
| min={start} max={end} onChange={(event) => { if (event.target.value >= start && event.target.value <= end) setDay(event.target.value); }} /></label> | |
| {load.phase === "loading" ? <div className="ao-dashboard-loading"><span className="lp-spin lp-spin--lg" | |
| role="status" aria-label="Loading hourly report" /></div> | |
| : load.phase === "error" ? <div className="ao-dashboard-notice" role="status"> | |
| <span>{load.denied ? "No permission to view hourly data" : "Hourly report could not be loaded"}</span> | |
| {!load.denied && <button type="button" className="ao-button" onClick={() => setAttempt((value) => value + 1)}>Retry</button>}</div> | |
| : report && <> | |
| <p className="ao-hourly-scope">{report.timezone || "Profile timezone unavailable"} 路 {report.currency || "Currency unavailable"} 路 14 day attribution</p> | |
| {report.reason && <p className="ao-dashboard-notice" role="status">{report.reason}</p>} | |
| {report.validation.days.map((check) => <div key={check.date} className="ao-hourly-check" data-valid={check.ok} | |
| data-surface="operator-hourly-validation" role="status"> | |
| <span>{check.date}: Hourly spend {format(check.hourly_spend)} 路 Daily spend {format(check.daily_spend)}</span> | |
| {check.ok ? <span>Within 2%</span> : check.reasons.map((reason) => <span key={reason}>{reason}</span>)} | |
| </div>)} | |
| {report.state !== "empty" && report.state !== "unsupported" && <> | |
| {Dashboard ? <Dashboard figures={figures} comparison={[]} groups={GROUPS} start={day} end={day} comparisonLabel="" /> | |
| : <p role="status">Charts unavailable</p>} | |
| <HourGrid key={day} rows={report.rows} /> | |
| </>} | |
| </>} | |
| </aside>; | |
| } | |