import { Component, useEffect, useId, useRef, useState } from "react"; import type { ComponentType, ReactNode } from "react"; import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract"; import type { AppViewProps } from "../../customer-grid/seam"; import { dataPathHash, BodyPortal, useOverlayLayer } from "../../customer-grid/seam"; import { ActionCadence } from "../actions/ActionCadence"; import "../../styles/sdlc81/amazon-dashboard.css"; export type DashboardCompare = "prior" | "yoy"; export interface DashboardPeriod { start: string; end: string } export interface DashboardFigure { id: string; label: string; value: number | null; unit: string; series: { key: string; label: string; points: { x: string; y: number | null; total?: boolean }[] }[]; source_table: string; source_tables: string[]; source_databases: string[]; validated: boolean; reason: string | null; scope?: Record; noPrior: boolean; change: { previous: number | null; absolute: number | null; percent: number | null; reason: string | null }; } /** Lane L supplies this controlled surface through AppDashboard and its shared chart kit. */ export interface AmazonDashboardSurfaceProps { figures: DashboardFigure[]; charts: { id: string; kind: "line" | "stackedArea" | "bar" | "waterfall" }[]; onFigureClick: (figure: DashboardFigure) => void; formatValue: (figure: DashboardFigure) => string; formatChange: (figure: DashboardFigure) => string; } export interface AmazonDashboardTabsProps { tabs: { id: string; label: string }[]; active: string; onChange: (id: string) => void; } type DashboardModule = { default?: ComponentType; AppDashboard?: ComponentType }; type TabsModule = { default?: ComponentType; AppTabs?: ComponentType }; type Shared = { Dashboard: ComponentType; Tabs: ComponentType }; // Optional until lane L lands. Missing shared modules must not create a second chart kit. const dashboardModules = import.meta.glob("../AppDashboard.tsx"); const tabsModules = import.meta.glob("../AppTabs.tsx"); const CHARTS: AmazonDashboardSurfaceProps["charts"] = [ { id: "sales_trend", kind: "line" }, { id: "organic_ad_sales", kind: "stackedArea" }, { id: "sales_mix", kind: "bar" }, { id: "pnl_waterfall", kind: "waterfall" }, ]; const LABELS: Record = { sales: "Sales", net_profit: "Net profit", ad_spend: "Ad spend", acos: "ACoS", tacos: "TACoS", units: "Units", return_rate: "Return rate", sales_trend: "Sales over time", organic_ad_sales: "Sales sources", sales_mix: "Sales mix", pnl_waterfall: "Profit and loss", }; const SOURCES: Record = { ut_amzn_order_metrics: { label: "Order sales", date: "interval" }, ut_amzn_order_items: { label: "Order items", date: "purchase_date" }, ut_amzn_fba_customer_returns: { label: "Amazon fulfilled returns", date: "return_date" }, ut_amzn_fba_shipped_sales: { label: "Amazon fulfilled shipments", date: "shipment_date" }, ut_amzn_mfn_returns: { label: "Merchant fulfilled returns", date: "return_request_date" }, ut_amzn_settlements: { label: "Settlements", date: "posted_date" }, ut_amzn_transactions: { label: "Transactions", date: "posted_date" }, ut_amzn_ads_sp_campaigns: { label: "Sponsored product ads", date: "date" }, ut_amzn_ads_sb_campaigns: { label: "Sponsored brand ads", date: "date" }, ut_amzn_ads_sd_campaigns: { label: "Sponsored display ads", date: "date" }, product_data: { label: "Product costs" }, }; const object = (value: unknown): Record => value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; const words = (value: unknown): string[] => Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : []; const finite = (value: unknown): number | null => typeof value === "number" && Number.isFinite(value) ? value : null; const string = (value: unknown): string => typeof value === "string" ? value : ""; function initialPeriod(): DashboardPeriod { const today = new Date(); const start = new Date(today); start.setUTCDate(start.getUTCDate() - 29); return { start: start.toISOString().slice(0, 10), end: today.toISOString().slice(0, 10) }; } function validPeriod(period: DashboardPeriod): boolean { const days = [period.start, period.end]; if (days.some((day) => !/^\d{4}-\d{2}-\d{2}$/.test(day) || !Number.isFinite(Date.parse(day)) || new Date(day).toISOString().slice(0, 10) !== day)) return false; const span = (Date.parse(period.end) - Date.parse(period.start)) / 86_400_000; return span >= 0 && span < 366; } function reasonFor(id: string, reason: string): string { if (!reason) return "No data for this period"; if (id === "net_profit" || id === "pnl_waterfall") return "Product costs need matching"; if (/access|permission|cannot read/i.test(reason)) return "Source access is limited"; if (/MFN|merchant|shipment/i.test(reason)) return "Shipment details are unavailable"; if (/currency|scope|marketplace|profile|connection/i.test(reason)) return "Account details need matching"; if (/cover|days|period/i.test(reason)) return "Source dates do not match"; return "Source data is unavailable"; } /** Reject unvalidated values and series before handing them to the shared renderer. */ function figuresFrom(raw: unknown): DashboardFigure[] { const incoming = Array.isArray(raw) ? raw.map(object) : []; return Object.entries(LABELS).map(([id, label]) => { const row = incoming.find((figure) => figure.id === id) ?? {}; const value = finite(row.value); const unit = string(row.unit); let usable = row.validated === true && value !== null && !row.reason && (unit === "percent" || unit === "units" || /^[A-Z]{3}$/.test(unit)); if (unit === "units" && value !== null && !Number.isInteger(value)) usable = false; const series = (Array.isArray(row.series) ? row.series : []).map((entry) => { const series = object(entry); return { key: string(series.key), label: string(series.label), points: (Array.isArray(series.points) ? series.points : []).map((entry) => { const point = object(entry); if (typeof point.x !== "string" || finite(point.y) === null) usable = false; return { x: string(point.x), y: finite(point.y), ...(typeof point.total === "boolean" ? { total: point.total } : {}) }; }) }; }); if (CHARTS.some((chart) => chart.id === id) && !series.some((part) => part.points.length)) usable = false; const change = object(row.change); const noPrior = row.noPrior !== false || finite(change.previous) === null; return { id, label, value: usable ? value : null, unit, series: usable ? series : [], source_table: string(row.source_table), source_tables: words(row.source_tables), source_databases: words(row.source_databases).filter((source) => Object.hasOwn(SOURCES, source)), validated: usable, reason: usable ? null : reasonFor(id, string(row.reason)), scope: object(row.scope), noPrior, change: { previous: usable && !noPrior ? finite(change.previous) : null, absolute: usable && !noPrior ? finite(change.absolute) : null, percent: usable && !noPrior ? finite(change.percent) : null, reason: noPrior ? "No comparison data" : change.reason ? "No percentage comparison" : null } }; }); } export function formatDashboardValue(figure: DashboardFigure): string { if (!figure.validated || figure.value === null) return "Unavailable"; if (figure.unit === "percent") return `${new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(figure.value)}%`; if (figure.unit === "units") return new Intl.NumberFormat(undefined, { maximumFractionDigits: 0 }).format(figure.value); if (/^[A-Z]{3}$/.test(figure.unit)) return new Intl.NumberFormat(undefined, { style: "currency", currency: figure.unit, currencyDisplay: "code" }).format(figure.value); return "Unavailable"; } function formatChange(figure: DashboardFigure): string { if (!figure.validated || figure.value === null) return ""; if (figure.noPrior) return "No comparison data"; const percent = figure.change.percent; if (percent === null) return "No percentage comparison"; return `${new Intl.NumberFormat(undefined, { maximumFractionDigits: 1, signDisplay: "exceptZero" }).format(percent)}%`; } function sourceHref(database: string, figure: DashboardFigure, period: DashboardPeriod): string { const date = database === "ut_amzn_order_items" && figure.id === "return_rate" ? "shipment_date" : SOURCES[database].date; return dataPathHash({ database, ...(date ? { filters: { conj: "and", nodes: [ { colId: date, op: "between", value: period.start, value2: period.end }, ] } } : {}) }); } function SourceRows({ figure, period, onClose }: { figure: DashboardFigure; period: DashboardPeriod; onClose: () => void }) { const panelRef = useRef(null); const title = useId(); useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false, restoreFocus: true, trapFocus: true, initialFocus: "[data-overlay-autofocus]" }); return

{figure.label}

{new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeZone: "UTC" }).format(new Date(period.start))} to {new Intl.DateTimeFormat(undefined, { dateStyle: "medium", timeZone: "UTC" }).format(new Date(period.end))}

Source rows

{figure.source_databases.length ? :

Source rows are unavailable

}
; } type State = { key: string; phase: "loading" | "ready" | "error" | "forbidden" | "connect"; figures: DashboardFigure[] }; const TABS = [{ id: "dashboard", label: "Dashboard" }]; class DashboardBoundary extends Component<{ children: ReactNode }, { failed: boolean }> { state = { failed: false }; static getDerivedStateFromError() { return { failed: true }; } render() { return this.state.failed ?

Dashboard is unavailable

: this.props.children; } } export default function AppView({ application }: AppViewProps) { const [period, setPeriod] = useState(initialPeriod); const [draft, setDraft] = useState(period); const [compare, setCompare] = useState("prior"); const [attempt, setAttempt] = useState(0); const [shared, setShared] = useState(null); const [sharedFailed, setSharedFailed] = useState(false); const [picked, setPicked] = useState(null); const [state, setState] = useState(null); const availability = application.availability?.state; const connected = availability !== "not_connected"; const forbidden = availability === "no_grant" || !application.id; const key = JSON.stringify([application.id, period.start, period.end, compare, availability, attempt]); const current = state?.key === key ? state : null; const busy = connected && !forbidden && (!current || current.phase === "loading"); const draftValid = validPeriod(draft); const changed = draft.start !== period.start || draft.end !== period.end; useEffect(() => { let active = true; setShared(null); setSharedFailed(false); const timeout = window.setTimeout(() => { active = false; setSharedFailed(true); }, 12_000); const load = async () => { const dashboard = dashboardModules["../AppDashboard.tsx"]; const tabs = tabsModules["../AppTabs.tsx"]; if (!dashboard || !tabs) throw new Error("Unavailable"); const [surface, tab] = await Promise.all([dashboard(), tabs()]); const Dashboard = surface.AppDashboard ?? surface.default; const Tabs = tab.AppTabs ?? tab.default; if (!Dashboard || !Tabs) throw new Error("Unavailable"); if (active) setShared({ Dashboard, Tabs }); }; void load().catch(() => { if (active) setSharedFailed(true); }).finally(() => window.clearTimeout(timeout)); return () => { active = false; window.clearTimeout(timeout); }; }, [attempt]); useEffect(() => { setPicked(null); if (!connected || forbidden) return; const controller = new AbortController(); let active = true; const settle = (phase: State["phase"], figures: DashboardFigure[] = []) => { if (active) setState({ key, phase, figures }); }; settle("loading"); const timeout = window.setTimeout(() => { settle("error"); active = false; controller.abort(); }, 20_000); const read = async () => { const query = new URLSearchParams({ start: period.start, end: period.end, compare, app: application.id }); const response = await fetch(`${API_V1}/app-kinds/amazon_dashboard/dashboard?${query}`, { credentials: CREDENTIALS, signal: controller.signal, }); if (checkTenant(response)) { settle("forbidden"); return; } if (response.status === 401) { signal(UNAUTHORIZED_EVENT); settle("forbidden"); return; } const raw: unknown = await response.json().catch(() => null); const body = object(raw); if (!response.ok) { const detail = object(body.detail); const error = object(body.error ?? detail.error); const code = string(error.code ?? detail.code ?? body.code); if (["not_connected", "amazon_not_connected", "connector_not_connected"].includes(code)) settle("connect"); else settle(response.status === 403 || response.status === 404 ? "forbidden" : "error"); return; } if (body.kind !== "amazon_dashboard" || body.start !== period.start || body.end !== period.end || body.compare !== compare || !Array.isArray(body.figures)) throw new Error("Unavailable"); settle("ready", figuresFrom(body.figures)); }; void read().catch(() => settle("error")).finally(() => window.clearTimeout(timeout)); return () => { active = false; window.clearTimeout(timeout); controller.abort(); }; }, [key, connected, forbidden, application.id, period.start, period.end, compare]); const openFigure = (figure: DashboardFigure) => { const live = current?.phase === "ready" ? current.figures.find((item) => item.id === figure.id) : null; if (!live) return; if (live.source_databases.length === 1) window.location.hash = sourceHref(live.source_databases[0], live, period); else setPicked(live); }; const needsConnection = !connected || current?.phase === "connect"; const denied = forbidden || current?.phase === "forbidden"; return
{shared && {}} />}
{ event.preventDefault(); if (draftValid && changed) setPeriod({ ...draft }); }}> {!draftValid && Choose up to 366 days}
{needsConnection ?

Connect Amazon to see your account Connect

: denied ?

You do not have access to this dashboard

: busy ?
: current?.phase === "error" ?

Dashboard could not load

: sharedFailed ?

Dashboard is unavailable

: !shared ?
: current?.phase === "ready" ? <> {!current.figures.some((figure) => figure.validated) &&

No figures for this period

}
: null} {!needsConnection && !denied && current?.phase === "ready" && } {picked && current?.phase === "ready" && setPicked(null)} />}
; }