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 }; 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; waterfall: { components: Array; 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 }; export type AccountPayload = ComparedWindow & { empty: false; currency: string; monthToDate: ComparedWindow; previousMonths: ComparedWindow[]; paceForecast: { metrics: Record; 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 & { 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; AppDashboard: ComponentType; Kpi: ComponentType; KpiStrip: ComponentType; TrendChart: ComponentType; }; /** Load the canonical frame and kit with their published prop types. */ export async function loadAccountDashboardComponents(): Promise { 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
{props.tabs.map((tab, index) => )}
; } 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 = { 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
{missing.map((row, index) =>
{row.label}
{row.display}
{row.reason && row.reason !== row.display &&
{row.reason}
}
)}
; } 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(); 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

{title}

{children}
{value.validated ? :
{value.display} {value.reason && value.reason !== value.display && {value.reason}}
} {value.validated && onSelect &&
{value.series .filter((row) => row.validated && row.value !== null && Number.isFinite(row.value) && row.sku && !row.isOther) .map((row) => )}
}
; } 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(() => initialPeriod || lastMonth()); const [comparison, setComparison] = useState("prior"); const [monthlyMetric, setMonthlyMetric] = useState("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({ 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
; if (load.phase === "denied") return

You do not have permission to view account totals

; if (load.phase === "error") return

{plain(load.message)}

; if (load.phase !== "ready") return null; if (load.data.empty === true) return

{plain(load.data.reason)}

; if (shared.pending) return
; if (!shared.components) return

Dashboard unavailable

; const data = load.data; if (!data.sourceRows) return

No prior data

; 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

{comparison === "prior" ? "Prior window" : "Year ago"}

{values.kpis.map((item) => )}

Forecast is an estimate

setSearch(event.target.value)} /> {search.trim() &&
    {data.skus.filter((row) => `${row.sku} ${row.asin ?? ""}`.toLowerCase().includes(search.trim().toLowerCase())) .map((record) =>
  • )}
}
; }; return

Account profit

{content()} {selectedSku?.key === key && !pending && load.phase === "ready" && !load.data.empty && setSelectedSku(null)} />}
; }