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; 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 => value && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; 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(null); const [selected, setSelected] = useState(-1); const navigate = (event: KeyboardEvent) => { const cells = Array.from(ref.current?.querySelectorAll("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
Grid view
{COLUMNS.map(([key, label]) => )}{rows.map((row) => {COLUMNS.map(([key]) => )} )}
Hour{label}
{String(row.hour).padStart(2, "0")}:00{row.reason && {row.reason}}{format(row[key], key)}
24 local-hour slots
; } 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({ phase: "loading" }); const panel = useRef(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 ; }