File size: 18,424 Bytes
f462120
 
 
8729c1d
 
f462120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
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>;
}