Spaces:
Running on CPU Upgrade
Running on CPU Upgrade
Download web/src/apps/amazon-dashboard/AppView.tsx from fsanyoto/runloopable: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/amazon-dashboard/AppView.tsx
- Command line
-
hf download hf://spaces/fsanyoto/runloopable/web/src/apps/amazon-dashboard/AppView.tsx
-
curl -L -o AppView.tsx https://huggingface.co/spaces/fsanyoto/runloopable/resolve/main/web/src/apps/amazon-dashboard/AppView.tsx
18.4 kB
| 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<string, unknown>; | |
| 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<AmazonDashboardSurfaceProps>; AppDashboard?: ComponentType<AmazonDashboardSurfaceProps> }; | |
| type TabsModule = { default?: ComponentType<AmazonDashboardTabsProps>; AppTabs?: ComponentType<AmazonDashboardTabsProps> }; | |
| type Shared = { Dashboard: ComponentType<AmazonDashboardSurfaceProps>; Tabs: ComponentType<AmazonDashboardTabsProps> }; | |
| // Optional until lane L lands. Missing shared modules must not create a second chart kit. | |
| const dashboardModules = import.meta.glob<DashboardModule>("../AppDashboard.tsx"); | |
| const tabsModules = import.meta.glob<TabsModule>("../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<string, string> = { | |
| 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<string, { label: string; date?: string }> = { | |
| 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<string, unknown> => | |
| value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {}; | |
| 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<HTMLDivElement>(null); | |
| const title = useId(); | |
| useOverlayLayer({ panelRef, onDismiss: onClose, dismissOnOutside: false, | |
| restoreFocus: true, trapFocus: true, initialFocus: "[data-overlay-autofocus]" }); | |
| return <BodyPortal> | |
| <div className="lp-dialog-scrim amd-source-scrim"> | |
| <div className="amd-source" ref={panelRef} role="dialog" aria-modal="true" aria-labelledby={title}> | |
| <header className="amd-source-head"> | |
| <h2 id={title}>{figure.label}</h2> | |
| <button type="button" className="amd-button" data-overlay-autofocus onClick={onClose}>Close</button> | |
| </header> | |
| <p className="amd-source-period">{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))}</p> | |
| <h3>Source rows</h3> | |
| {figure.source_databases.length ? <ul className="amd-source-list"> | |
| {figure.source_databases.map((database) => <li key={database}> | |
| <a href={sourceHref(database, figure, period)} onClick={onClose}>{SOURCES[database].label}</a> | |
| </li>)} | |
| </ul> : <p role="status">Source rows are unavailable</p>} | |
| </div> | |
| </div> | |
| </BodyPortal>; | |
| } | |
| 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 ? <p className="amd-notice" role="status">Dashboard is unavailable</p> : this.props.children; | |
| } | |
| } | |
| export default function AppView({ application }: AppViewProps) { | |
| const [period, setPeriod] = useState(initialPeriod); | |
| const [draft, setDraft] = useState(period); | |
| const [compare, setCompare] = useState<DashboardCompare>("prior"); | |
| const [attempt, setAttempt] = useState(0); | |
| const [shared, setShared] = useState<Shared | null>(null); | |
| const [sharedFailed, setSharedFailed] = useState(false); | |
| const [picked, setPicked] = useState<DashboardFigure | null>(null); | |
| const [state, setState] = useState<State | null>(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 <section className="amd" data-testid="amazon-dashboard-app" aria-label="Amazon dashboard"> | |
| {shared && <DashboardBoundary key={`tabs:${attempt}`}><shared.Tabs tabs={TABS} active="dashboard" onChange={() => {}} /></DashboardBoundary>} | |
| <form className="amd-controls" aria-label="Dashboard period" onSubmit={(event) => { | |
| event.preventDefault(); | |
| if (draftValid && changed) setPeriod({ ...draft }); | |
| }}> | |
| <label>From<input type="date" value={draft.start} max={draft.end} required | |
| onChange={(event) => setDraft({ ...draft, start: event.target.value })} /></label> | |
| <label>To<input type="date" value={draft.end} min={draft.start} required | |
| onChange={(event) => setDraft({ ...draft, end: event.target.value })} /></label> | |
| <button type="submit" className="amd-button amd-apply" disabled={!draftValid || !changed}>Apply</button> | |
| <label className="amd-comparison">Compare<select value={compare} aria-label="Compare" | |
| onChange={(event) => setCompare(event.target.value === "yoy" ? "yoy" : "prior")}> | |
| <option value="prior">Previous period</option><option value="yoy">Previous year</option> | |
| </select></label> | |
| {!draftValid && <span className="amd-period-error" role="status">Choose up to 366 days</span>} | |
| </form> | |
| {needsConnection ? <p className="amd-notice" role="status">Connect Amazon to see your account <a href="#/connectors">Connect</a></p> | |
| : denied ? <p className="amd-notice" role="status">You do not have access to this dashboard</p> | |
| : busy ? <div className="amd-loading" aria-busy="true"><span className="lp-spin lp-spin--lg" role="status" aria-label="Loading dashboard" /></div> | |
| : current?.phase === "error" ? <p className="amd-notice" role="status">Dashboard could not load <button className="amd-button" type="button" onClick={() => setAttempt(attempt + 1)}>Retry</button></p> | |
| : sharedFailed ? <p className="amd-notice" role="status">Dashboard is unavailable <button className="amd-button" type="button" onClick={() => setAttempt(attempt + 1)}>Retry</button></p> | |
| : !shared ? <div className="amd-loading" aria-busy="true"><span className="lp-spin lp-spin--lg" role="status" aria-label="Loading dashboard" /></div> | |
| : current?.phase === "ready" ? <> | |
| {!current.figures.some((figure) => figure.validated) && <p className="amd-notice" role="status">No figures for this period</p>} | |
| <div className="amd-figures" data-period={`${period.start}/${period.end}`} data-compare={compare}> | |
| <DashboardBoundary key={key}> | |
| <shared.Dashboard figures={current.figures} charts={CHARTS} onFigureClick={openFigure} | |
| formatValue={formatDashboardValue} formatChange={formatChange} /> | |
| </DashboardBoundary> | |
| </div> | |
| </> : null} | |
| {!needsConnection && !denied && current?.phase === "ready" && <ActionCadence canRead />} | |
| {picked && current?.phase === "ready" && <SourceRows key={picked.id} figure={picked} period={period} onClose={() => setPicked(null)} />} | |
| </section>; | |
| } | |