loopable / web /src /apps /amazon-profit /AccountView.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
3a021ea verified
Raw History Blame Contribute Delete
24.6 kB
import { useEffect, useId, useState } from "react";
import type { ComponentType, ReactNode } from "react";
import type { Icon } from "@phosphor-icons/react";
import type { AppTabsProps } from "../AppTabs";
import type { AppDashboardProps } from "../AppDashboard";
import type { ChartSeries, KpiProps, KpiStripProps, TrendChartProps } from "../../viz/kit";
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant, signal } from "../../apiContract";
import { refusalMessage } from "../../customer-grid/seam";
import WhatIf from "./WhatIf";
import "../../styles/sdlc81/amazon-account.css";
export type AccountPeriod = { key: string; start: string; end: string; days: number };
export type AccountMetric = {
value: number | null;
validated: boolean;
reason: string | null;
noPrior: boolean;
sourceTables: string[];
};
type Proof = { ok: boolean; reason?: string | null; checks?: Array<Proof & { check: string }> };
type MetricKey = "netSales" | "netProceeds" | "cogs" | "netProfit";
export type AccountSku = {
sku: string; asin: string | null; units: number;
netSales: AccountMetric; netProceeds: AccountMetric; cogs: AccountMetric; netProfit: AccountMetric;
};
type Attribution = {
daily: Array<{ day: string; netSales: AccountMetric; adSales: AccountMetric; organicSales: AccountMetric }>;
adSales: AccountMetric; organicSales: AccountMetric; validate: Proof;
};
type AccountWindow = {
period: AccountPeriod; noPrior: boolean; sourceRows: number;
metrics: Record<MetricKey, AccountMetric>;
waterfall: { components: Array<AccountMetric & { key: string; label: string; included: boolean }>;
netProfit: AccountMetric; validate: Proof };
skus: AccountSku[];
salesMix: Array<{ sku: string; isOther?: boolean; sales: AccountMetric }>;
salesMixValidate: Proof;
attribution: Attribution;
validate: Proof;
validated: boolean;
};
type ComparedWindow = AccountWindow & { comparisons: Record<AccountComparison, AccountWindow> };
export type AccountPayload = ComparedWindow & {
empty: false; currency: string; monthToDate: ComparedWindow; previousMonths: ComparedWindow[];
paceForecast: { metrics: Record<MetricKey, AccountMetric>; validate: Proof; basis: string };
};
type EmptyAccount = { empty: true; reason: string; validated: false };
export type AccountComparison = "prior" | "yearAgo";
/** Command Center tabs: one Grid per grain, the Projects Grid, then the SKU dashboard. */
export type AccountTab = "sku" | "asin" | "parent" | "projects" | "dashboard" | "data_entry";
export type AccountSkuSelection = { sku: string; period: string; record: AccountSku };
// C6 keeps unavailable values null before they reach a shared renderer.
export type AccountFigurePoint = {
label: string; value: number | null; validated: boolean; reason: string | null;
noPrior: boolean; display: string; source_table: string; sourceTables: string[];
sourcePeriod?: AccountPeriod;
series?: string; date?: string; comparisonDate?: string; sku?: string; isOther?: boolean; total?: boolean;
};
export type AccountFigure = Omit<AccountFigurePoint, "series"> & {
id: string; unit: string; series: AccountFigurePoint[];
kind: "kpi" | "waterfall" | "bar" | "line";
orientation?: "horizontal" | "vertical";
comparison?: AccountFigurePoint;
};
export type AccountTabsProps = {
tabs: Array<{ id: AccountTab; label: string; icon?: Icon }>;
activeTab: AccountTab; onTabChange: (tab: AccountTab) => void;
};
export type AccountChartProps = {
figure: AccountFigure; currency: string;
onSelect?: (point: AccountFigurePoint) => void;
};
export type AccountDashboardComponents = {
AppTabs: ComponentType<AppTabsProps>;
AppDashboard: ComponentType<AppDashboardProps>;
Kpi: ComponentType<KpiProps>;
KpiStrip: ComponentType<KpiStripProps>;
TrendChart: ComponentType<TrendChartProps>;
};
/** Load the canonical frame and kit with their published prop types. */
export async function loadAccountDashboardComponents(): Promise<AccountDashboardComponents> {
const [tabs, frame, kit] = await Promise.all([
import("../AppTabs"), import("../AppDashboard"), import("../../viz/kit"),
]);
return {
AppTabs: tabs.AppTabs, AppDashboard: frame.AppDashboard,
Kpi: kit.Kpi, KpiStrip: kit.KpiStrip, TrendChart: kit.TrendChart,
};
}
export function useAccountDashboardComponents(override?: AccountDashboardComponents, revision = 0) {
const [result, setResult] = useState<{ components?: AccountDashboardComponents; pending: boolean }>({ pending: true });
useEffect(() => {
if (override) return;
let current = true;
setResult({ pending: true });
void loadAccountDashboardComponents().then(
(components) => { if (current) setResult({ components, pending: false }); },
() => { if (current) setResult({ pending: false }); },
);
return () => { current = false; };
}, [override, revision]);
return override ? { components: override, pending: false } : result;
}
/** One strip in the given order. The shared AppTabs always moves Dashboard first, so it is not used here. */
export function AccountTabs(props: AccountTabsProps & { components?: AccountDashboardComponents }) {
const id = useId();
return <div className={props.components ? "lp-app-tabs ap-command-tabs" : "ap-tabs ap-command-tabs"}
role="tablist" aria-label="Command Center">
{props.tabs.map((tab, index) => <button type="button" role="tab" key={tab.id}
id={`${id}-${tab.id}`} data-tab={tab.id} aria-selected={props.activeTab === tab.id}
tabIndex={props.activeTab === tab.id ? 0 : -1}
onClick={() => props.onTabChange(tab.id)}
onKeyDown={(event) => {
const next = event.key === "Home" ? 0 : event.key === "End" ? props.tabs.length - 1
: event.key === "ArrowRight" ? (index + 1) % props.tabs.length
: event.key === "ArrowLeft" ? (index + props.tabs.length - 1) % props.tabs.length : null;
if (next === null) return;
event.preventDefault();
props.onTabChange(props.tabs[next].id);
document.getElementById(`${id}-${props.tabs[next].id}`)?.focus();
}}>{tab.icon && <tab.icon size="1.1em" weight={props.activeTab === tab.id ? "fill" : "regular"}
aria-hidden="true" data-tab-icon="" style={{ marginInlineEnd: "0.4em", verticalAlign: "-0.15em" }} />}
{tab.label}</button>)}
</div>;
}
function plain(value: string | null | undefined) {
return value?.replace(/[\u2013\u2014]/g, ",") ?? null;
}
/** Missing history has its own display branch even when a source sends a numeric value. */
export function metricText(metric: AccountMetric, currency: string): string {
if (metric.noPrior) return "No prior data";
if (!metric.validated || metric.value === null || !Number.isFinite(metric.value)) return "Unavailable";
return new Intl.NumberFormat("en-US", { style: "currency", currency, maximumFractionDigits: 2 }).format(metric.value);
}
function point(label: string, metric: AccountMetric, currency: string, proof: boolean | Proof = true): AccountFigurePoint {
const proofOk = typeof proof === "boolean" ? proof : proof.ok;
const proofReason = typeof proof === "boolean" || proof.ok ? null
: proof.reason ?? proof.checks?.find((check) => !check.ok)?.reason ?? "Figure does not reconcile";
const validated = proofOk && metric.validated && !metric.noPrior && metric.value !== null && Number.isFinite(metric.value);
const safe = { ...metric, validated, value: validated ? metric.value : null };
return { label, value: safe.value, validated, noPrior: metric.noPrior,
reason: plain(metric.reason ?? proofReason) ?? (validated ? null : metric.noPrior ? "No prior data" : "Figure unavailable"),
display: metricText(safe, currency),
source_table: metric.sourceTables.find((table) => !table.startsWith("_")) ?? "ut_amazon_sku_profit",
sourceTables: metric.sourceTables };
}
const metricLabels: Record<MetricKey, string> = {
netSales: "Net sales", netProceeds: "Net proceeds", cogs: "Cost of goods", netProfit: "Net profit",
};
function metricProof(window: AccountWindow, key: MetricKey): Proof {
if (key === "netSales") return window.salesMixValidate;
if (key === "netProceeds") {
const checks = window.validate.checks?.filter((item) => item.check === "SKU net proceeds equal independent economics total"
|| item.check === "Net proceeds tie to settlements within 2%");
return { ok: checks?.length === 2 && checks.every((item) => item.ok), checks };
}
return window.validate;
}
function metricPoint(window: AccountWindow, key: MetricKey, currency: string, label = metricLabels[key]) {
return { ...point(label, { ...window.metrics[key], noPrior: window.noPrior || window.metrics[key].noPrior }, currency, metricProof(window, key)),
sourcePeriod: window.period };
}
function figure(id: string, kind: AccountFigure["kind"], value: AccountFigurePoint,
currency: string, series: AccountFigurePoint[] = []): AccountFigure {
return { ...value, id, kind, unit: currency, series };
}
function periodLabel(period: AccountPeriod) {
const format = (value: string) => new Intl.DateTimeFormat("en-US", { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" })
.format(new Date(`${value}T00:00:00Z`));
return `${format(period.start)} to ${format(period.end)}`;
}
/** Adapt only T45's account response, including each figure's independent validation. */
export function accountFigures(data: AccountPayload, comparison: AccountComparison, monthlyMetric: MetricKey = "netSales") {
const currency = data.currency;
const previous = data.comparisons[comparison];
const kpis = (Object.keys(metricLabels) as MetricKey[]).map((key) => ({
...figure(key, "kpi", metricPoint(data, key, currency), currency),
comparison: metricPoint(previous, key, currency, `${comparison === "prior" ? "Prior window" : "Year ago"}: ${periodLabel(previous.period)}`),
}));
const waterfall = figure("waterfall", "waterfall", point("Profit breakdown", data.waterfall.netProfit,
currency, { ...data.validate, ok: data.waterfall.validate.ok && data.validate.ok }), currency,
[...data.waterfall.components.filter((part) => part.included).map((part) =>
({ ...point(part.key === "cogs" ? "Cost of goods" : part.label, part, currency, data.waterfall.validate), sourcePeriod: data.period })),
{ ...metricPoint(data, "netProfit", currency), total: true }]);
// A failed bridge cannot leave numeric chart rows behind a failed total.
if (!waterfall.validated) waterfall.series = waterfall.series.map((row) => ({ ...row, value: null, validated: false,
display: row.noPrior ? "No prior data" : "Unavailable", reason: row.reason ?? waterfall.reason }));
const monthRows = [
metricPoint(data.monthToDate, monthlyMetric, currency, `Month to date: ${periodLabel(data.monthToDate.period)}`),
{ ...point("Forecast", data.paceForecast.metrics[monthlyMetric], currency, { ...data.paceForecast.validate,
ok: data.paceForecast.validate.ok
&& data.paceForecast.validate.checks?.some((check) => check.ok && check.check.startsWith(`${monthlyMetric} pace `)) === true }),
sourcePeriod: data.monthToDate.period },
...data.previousMonths.map((month) => metricPoint(month, monthlyMetric, currency, periodLabel(month.period))),
];
const monthly = figure("monthly", "bar", metricPoint(data.monthToDate, monthlyMetric, currency, "Monthly comparison"), currency, monthRows);
// Each monthly bar has its own proof, so an unavailable current cost does not hide a tied prior month.
monthly.validated = monthRows.some((row) => row.validated);
monthly.noPrior = monthRows.every((row) => row.noPrior);
monthly.value = null;
if (monthly.validated) monthly.reason = null;
const daily: AccountFigurePoint[] = [];
const unavailable: AccountFigurePoint[] = [];
for (const [window, prefix] of [[data, "Selected"], [previous, comparison === "prior" ? "Prior window" : "Year ago"]] as const) {
for (const [key, label] of [["organicSales", "Organic sales"], ["adSales", "Ad sales"]] as const) {
const summary = point(`${prefix} ${label.toLowerCase()}`, window.attribution[key], currency, window.attribution.validate);
if (!summary.validated) unavailable.push(summary);
for (const row of window.attribution.daily) {
const offset = Math.round((Date.parse(row.day) - Date.parse(window.period.start)) / 86400000);
const date = new Date(Date.parse(data.period.start) + offset * 86400000).toISOString().slice(0, 10);
daily.push({ ...point(summary.label, row[key], currency,
{ ...window.attribution.validate, ok: window.attribution.validate.ok && summary.validated, reason: summary.reason }),
series: summary.label, date, comparisonDate: row.day, sourcePeriod: window.period });
}
}
}
const attribution = figure("attribution", "line", point("Organic and ad sales", data.metrics.netSales, currency,
data.attribution.validate), currency, daily);
const mix = figure("salesMix", "bar", point("Sales mix", data.metrics.netSales, currency, data.salesMixValidate), currency,
data.salesMix.map((row) => ({ ...point(row.sku, row.sales, currency, data.salesMixValidate),
sku: row.sku, isOther: row.isOther, sourcePeriod: data.period })));
mix.orientation = "horizontal";
const excluded = data.waterfall.components.filter((part) => !part.included).map((part) => point(part.label, part, currency));
return { kpis, waterfall, monthly, attribution, mix, unavailable, excluded };
}
function MissingFigures({ points }: { points: AccountFigurePoint[] }) {
const missing = [...new Map(points.filter((row) => !row.validated)
.map((row) => [`${row.label}:${row.display}:${row.reason}`, row])).values()];
if (!missing.length) return null;
return <dl className="ap-missing" aria-label="Unavailable figures">{missing.map((row, index) =>
<div key={`${row.label}-${index}`} title={row.reason ?? undefined}>
<dt>{row.label}</dt><dd>{row.display}</dd>
{row.reason && row.reason !== row.display && <dd className="ap-reason">{row.reason}</dd>}
</div>)}</dl>;
}
function ChartSection({ title, value, components, currency, children, onSelect, unavailable }: {
title: string; value: AccountFigure; components: AccountDashboardComponents;
currency: string; children?: ReactNode; onSelect?: AccountChartProps["onSelect"]; unavailable?: AccountFigurePoint[];
}) {
const Chart = components.TrendChart;
const groups = new Map<string, ChartSeries>();
for (const row of value.series) {
const label = row.series && row.sourcePeriod ? `${row.series}: ${periodLabel(row.sourcePeriod)}` : row.series ?? value.label;
const group = groups.get(label) ?? { label, points: [] };
group.points.push({ ...row, x: row.date ?? row.label,
date: row.comparisonDate ?? row.sourcePeriod?.start,
period_end: row.date ? undefined : row.sourcePeriod?.end,
value: row.validated && row.value !== null && Number.isFinite(row.value) ? row.value : null });
groups.set(label, group);
}
return <section className="ap-chart-section" aria-label={title} data-figure={value.id}>
<div className="ap-chart-heading"><h3>{title}</h3>{children}</div>
{value.validated ? <Chart label={value.label} series={[...groups.values()]} unit={currency} kind={value.kind === "kpi" ? "bar" : value.kind} />
: <div className="ap-state" role="status"><span>{value.display}</span>
{value.reason && value.reason !== value.display && <span className="ap-reason">{value.reason}</span>}</div>}
<MissingFigures points={[...value.series, ...(unavailable ?? [])]} />
{value.validated && onSelect && <div role="group" aria-label="Select SKU">{value.series
.filter((row) => row.validated && row.value !== null && Number.isFinite(row.value) && row.sku && !row.isOther)
.map((row) => <button key={row.sku} type="button" className="ap-button" onClick={() => onSelect(row)}>{row.label}</button>)}</div>}
</section>;
}
function lastMonth() {
const today = new Date();
return new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth() - 1, 1)).toISOString().slice(0, 7);
}
type Load = { key: string; phase: "loading" }
| { key: string; phase: "ready"; data: AccountPayload | EmptyAccount }
| { key: string; phase: "error" | "denied"; message: string };
export type AccountViewProps = {
/** The stored table period. The Dashboard has no Period control of its own. */
initialPeriod?: string;
components?: AccountDashboardComponents;
onSelectSku?: (selection: AccountSkuSelection) => void;
};
export default function AccountView({ initialPeriod, components: supplied, onSelectSku }: AccountViewProps) {
const [period] = useState<string>(() => initialPeriod || lastMonth());
const [comparison, setComparison] = useState<AccountComparison>("prior");
const [monthlyMetric, setMonthlyMetric] = useState<MetricKey>("netSales");
const [search, setSearch] = useState("");
const [selectedSku, setSelectedSku] = useState<{ selection: AccountSkuSelection; currency: string; key: string } | null>(null);
const [revision, setRevision] = useState(0);
const key = `${period}:${comparison}:${revision}`;
const [load, setLoad] = useState<Load>({ key, phase: "loading" });
const shared = useAccountDashboardComponents(supplied, revision);
useEffect(() => {
const controller = new AbortController();
let current = true;
const timeout = window.setTimeout(() => controller.abort(), 20000);
setLoad({ key, phase: "loading" });
const query = new URLSearchParams({ period, comparison });
void (async () => {
try {
const response = await fetch(`${API_V1}/amazon-profit/account?${query}`, {
credentials: CREDENTIALS, cache: "no-store", signal: controller.signal,
});
if (!current || checkTenant(response)) return;
if (response.status === 401) signal(UNAUTHORIZED_EVENT);
const body: unknown = await response.json().catch(() => null);
if (!current) return;
if (!response.ok) {
setLoad({ key, phase: response.status === 403 ? "denied" : "error",
message: refusalMessage(body, response.status, "Account figures could not be loaded.") });
return;
}
const data = body as AccountPayload | EmptyAccount | null;
if (!data || (data.empty !== true && (!data.period || !data.metrics || !data.comparisons
|| !data.monthToDate || !data.paceForecast || !Array.isArray(data.salesMix)))) {
throw new Error("Account figures could not be loaded.");
}
setLoad({ key, phase: "ready", data });
} catch {
if (current) setLoad({ key, phase: "error", message: "Account figures could not be loaded." });
} finally {
window.clearTimeout(timeout);
}
})();
return () => { current = false; window.clearTimeout(timeout); controller.abort(); };
}, [period, comparison, revision, key]);
const retry = () => { setSelectedSku(null); setRevision((value) => value + 1); };
const pending = load.key !== key || load.phase === "loading";
const id = useId();
const content = () => {
if (pending) return <div className="ap-state" role="status" aria-label="Loading account figures"><span className="lp-spin lp-spin--lg" /></div>;
if (load.phase === "denied") return <p className="ap-state" role="status" data-testid="amazon-account-no-permission"
title={plain(load.message) ?? undefined}>You do not have permission to view account totals</p>;
if (load.phase === "error") return <div className="ap-state" role="alert"><p>{plain(load.message)}</p>
<button type="button" className="ap-button" onClick={retry}>Retry</button></div>;
if (load.phase !== "ready") return null;
if (load.data.empty === true) return <p className="ap-state" role="status">{plain(load.data.reason)}</p>;
if (shared.pending) return <div className="ap-state" role="status" aria-label="Loading dashboard"><span className="lp-spin lp-spin--lg" /></div>;
if (!shared.components) return <div className="ap-state" role="status"><p>Dashboard unavailable</p>
<button type="button" className="ap-button" onClick={retry}>Retry</button></div>;
const data = load.data;
if (!data.sourceRows) return <p className="ap-state" role="status">No prior data</p>;
const values = accountFigures(data, comparison, monthlyMetric);
const { AppDashboard, Kpi, KpiStrip } = shared.components;
const openSku = (record: AccountSku) => setSelectedSku({ selection: { sku: record.sku, period, record }, currency: data.currency, key });
const select = (row: AccountFigurePoint) => {
if (row.isOther || !row.sku) return;
const record = data.skus.find((item) => item.sku === row.sku);
if (record) {
openSku(record);
onSelectSku?.({ sku: record.sku, period, record });
}
};
const previous = data.comparisons[comparison];
const comparisonLabel = `${comparison === "prior" ? "Prior window" : "Year ago"}: ${periodLabel(previous.period)}`;
const kpis = values.kpis.map((item) => ({ ...item, change: { previous: item.comparison.value,
reason: item.comparison.validated ? comparisonLabel : item.comparison.reason ?? item.comparison.display } }));
return <AppDashboard figures={kpis} charts={[]} period={data.period}>
<section aria-label={comparisonLabel}>
<h3>{comparison === "prior" ? "Prior window" : "Year ago"}</h3>
<KpiStrip label={comparisonLabel}>{values.kpis.map((item) => <Kpi key={item.id} label={item.label}
value={item.comparison.value} unit={data.currency} validated={item.comparison.validated}
reason={item.comparison.reason} noPrior={item.comparison.noPrior} period={periodLabel(previous.period)}
change={{ reason: "Comparison period" }} />)}</KpiStrip>
</section>
<ChartSection title="Profit breakdown" value={values.waterfall} components={shared.components} currency={data.currency} />
<MissingFigures points={values.excluded} />
<ChartSection title="Monthly comparison" value={values.monthly} components={shared.components} currency={data.currency}>
<select aria-label="Monthly figure" className="ap-select" value={monthlyMetric}
onChange={(event) => setMonthlyMetric(event.target.value as MetricKey)}>
{(Object.keys(metricLabels) as MetricKey[]).map((name) => <option value={name} key={name}>{metricLabels[name]}</option>)}
</select>
</ChartSection>
<p className="ap-note" title={plain(data.paceForecast.basis) ?? undefined}>Forecast is an estimate</p>
<ChartSection title="Organic and ad sales" value={values.attribution} components={shared.components} currency={data.currency}
unavailable={values.unavailable} />
<ChartSection title="Sales mix" value={values.mix} components={shared.components} currency={data.currency}
onSelect={select} />
<section className="ap-sku-search" aria-label="Find a SKU">
<label htmlFor={`${id}-sku`}>Find a SKU</label>
<input id={`${id}-sku`} className="ap-select" type="search" value={search} placeholder="Search SKU or ASIN"
onChange={(event) => setSearch(event.target.value)} />
{search.trim() && <ul>{data.skus.filter((row) => `${row.sku} ${row.asin ?? ""}`.toLowerCase().includes(search.trim().toLowerCase()))
.map((record) => <li key={record.sku}><button type="button" className="ap-button"
onClick={() => { openSku(record); onSelectSku?.({ sku: record.sku, period, record }); }}>{record.sku}</button></li>)}</ul>}
</section>
</AppDashboard>;
};
return <div className="ap-account" data-testid="amazon-profit-account" data-period={period} data-comparison={comparison}
role="tabpanel" aria-label="Dashboard" aria-busy={pending}>
<header className="ap-account-head"><h2>Account profit</h2>
<label className="ap-control" htmlFor={`${id}-comparison`}>Compare
<select id={`${id}-comparison`} className="ap-select" value={comparison}
onChange={(event) => { setSelectedSku(null); setComparison(event.target.value as AccountComparison); }}>
<option value="prior">Prior window</option><option value="yearAgo">Year ago</option>
</select>
</label>
</header>
{content()}
{selectedSku?.key === key && !pending && load.phase === "ready" && !load.data.empty
&& <WhatIf key={`${selectedSku.selection.sku}:${selectedSku.selection.period}`} selection={selectedSku.selection}
currency={selectedSku.currency} onClose={() => setSelectedSku(null)} />}
</div>;
}