Download web/src/apps/ranking-diagnostic/AppView.tsx from fsanyoto/loopable: direct link, hf CLI and curl.
- Browser
- Download file 41.8 kB
-
https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/ranking-diagnostic/AppView.tsx
- Command line
-
hf download hf://spaces/fsanyoto/loopable/web/src/apps/ranking-diagnostic/AppView.tsx
-
curl -L -o AppView.tsx https://huggingface.co/spaces/fsanyoto/loopable/resolve/main/web/src/apps/ranking-diagnostic/AppView.tsx
41.8 kB
| import { useCallback, useEffect, useRef, useState } from "react"; | |
| import { API_V1, CREDENTIALS } from "../../apiContract"; | |
| import "../../viz/DashboardView.css"; | |
| import "../../styles/sdlc79/ranking-diagnostic.css"; | |
| import { ActionCadence } from "../actions/ActionCadence"; | |
| import { ActionList } from "../actions/ActionList"; | |
| import { SkuActions } from "../actions/SkuActions"; | |
| import type { SkuAction } from "../actions/actionsApi"; | |
| import Benchmark from "./Benchmark"; | |
| import Dashboard, { AppTabs, SourceTrend } from "./Dashboard"; | |
| // S79-T20 (C2, C4, R18): the Ranking diagnostic App screen. The dispatcher draws the App frame, so this | |
| // view draws only the week, the status tabs, the drop list, the ASIN list and the item drawer. No chat panel. | |
| export interface RankingDiagnosticApplication { | |
| id: string; | |
| name?: string; | |
| capabilities?: Record<string, boolean>; | |
| } | |
| const DEFAULT_STATUSES = ["Open", "In progress", "Fixed", "Ignored"]; | |
| const DROPS = "Drops"; | |
| const ASINS = "All ASINs"; | |
| const BENCHMARK = "Benchmark"; | |
| const DASHBOARD = "dashboard"; | |
| const tabLabel = (id: string) => id === DASHBOARD ? "Dashboard" : id; | |
| /** The one empty sentence per tab. */ | |
| const EMPTY: Record<string, string> = { | |
| [DROPS]: "No drops this week", Open: "No open drops", "In progress": "No drops in progress", | |
| Fixed: "No fixed drops", Ignored: "No ignored drops", [ASINS]: "No ASINs this week", | |
| }; | |
| type SignalKey = "sessions" | "buyBox" | "units" | "salesRank" | "searchShare" | "adSpend"; | |
| /** The six weekly signals, in card order. Rank is better when it is lower. */ | |
| const SIGNALS: { key: SignalKey; label: string; short: string }[] = [ | |
| { key: "sessions", label: "Sessions", short: "Sessions" }, | |
| { key: "buyBox", label: "Buy Box", short: "Buy Box" }, | |
| { key: "units", label: "Units", short: "Units" }, | |
| { key: "salesRank", label: "Sales rank", short: "Rank" }, | |
| { key: "searchShare", label: "Search-term share", short: "Search share" }, | |
| { key: "adSpend", label: "Ad spend", short: "Ad spend" }, | |
| ]; | |
| interface Drop { | |
| id: string; | |
| week: string; | |
| asin: string; | |
| sku: string; | |
| productTitle: string; | |
| causeKey: string; | |
| cause: string; | |
| fix: string; | |
| reason: string; | |
| signals: string[]; | |
| status: string; | |
| owner: string; | |
| due: string; | |
| rankNow: number | null; | |
| rankChange: number | null; | |
| rankTrend: { week: string; rank: number | null }[]; | |
| } | |
| /** Weekly points held against the two the diagnostic compares, and the day the next one can land. */ | |
| interface Readiness { held: number; needed: number; nextSync: string } | |
| interface Screen { | |
| canEdit: boolean; | |
| week: string; | |
| weeks: string[]; | |
| counts: Record<string, number>; | |
| items: Drop[]; | |
| cursor: string | null; | |
| problems: string[]; | |
| statuses: string[]; | |
| total: number; | |
| summedAsins: number | null; | |
| readiness: Readiness | null; | |
| } | |
| interface AsinRow { | |
| asin: string; | |
| title: string; | |
| skus: string[]; | |
| units: number | null; | |
| sales: number | null; | |
| causeLabel: string; | |
| itemId: string; | |
| } | |
| interface AsinPage { asins: AsinRow[]; cursor: string | null; total: number } | |
| type Point = { week: string } & Record<SignalKey, number | null>; | |
| interface HistoryEvent { at: string; by: string; status: string; owner: string; due: string; note: string } | |
| interface Detail { item: Drop; history: HistoryEvent[] } | |
| interface ContentChange { | |
| id: string; day: string; sku: string; field: string; label: string; before: string; after: string; | |
| rankDrop: { day: string; before: number; after: number } | null; | |
| } | |
| interface ContentPage { changes: ContentChange[]; cursor: string | null } | |
| /** What the drawer is open on: an ASIN, with its drop item when it has one. */ | |
| interface Opened { asin: string; title: string; itemId: string; week: string } | |
| type Row = Record<string, unknown>; | |
| type Load<T> = { phase: "loading" } | { phase: "error"; message: string } | { phase: "ready"; value: T }; | |
| const text = (value: unknown) => (typeof value === "string" ? value : typeof value === "number" ? String(value) : ""); | |
| const num = (value: unknown) => { | |
| if (typeof value === "number" && Number.isFinite(value)) return value; | |
| if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) return Number(value); | |
| return null; | |
| }; | |
| const rows = (raw: unknown): Row[] => (Array.isArray(raw) ? raw : []) | |
| .filter((row): row is Row => !!row && typeof row === "object" && !Array.isArray(row)); | |
| const strings = (raw: unknown) => (Array.isArray(raw) ? raw : []).map(text).filter(Boolean); | |
| async function readJson(response: Response, fallback: string): Promise<unknown> { | |
| const body: unknown = await response.json().catch(() => null); | |
| if (response.ok) return body; | |
| // main.py reshapes every refusal to a top-level `error`; a bare router answers under `detail`. | |
| const shaped = body as { error?: { message?: unknown }; detail?: { error?: { message?: unknown } } } | null; | |
| throw new Error(text(shaped?.error?.message) || text(shaped?.detail?.error?.message) || fallback); | |
| } | |
| const failure = (reason: unknown, fallback: string) => (reason instanceof Error && reason.message ? reason.message : fallback); | |
| function parseDrop(raw: unknown): Drop | null { | |
| const row = (raw ?? {}) as Row; | |
| const id = text(row.id); | |
| if (!id) return null; | |
| return { | |
| id, week: text(row.week), asin: text(row.asin), sku: text(row.sku), productTitle: text(row.productTitle), | |
| causeKey: text(row.causeKey), cause: text(row.cause), fix: text(row.fix), reason: text(row.reason), | |
| signals: strings(row.signals), status: text(row.status) || "Open", owner: text(row.owner), due: text(row.due), | |
| rankNow: num(row.rankNow), rankChange: num(row.rankChange), | |
| rankTrend: rows(row.rankTrend).map((point) => ({ week: text(point.week), rank: num(point.rank) })) | |
| .filter((point) => point.week), | |
| }; | |
| } | |
| /** Read readiness from the same scoped screen response as the rows. */ | |
| function parseReadiness(body: Row): Readiness | null { | |
| const sent = body.readiness as Row | null | undefined; | |
| if (sent && typeof sent === "object") { | |
| const held = num(sent.heldWeeks); | |
| if (held === null) return null; | |
| return { held, needed: num(sent.weeksNeeded) ?? 2, nextSync: text(sent.nextSync) }; | |
| } | |
| return null; | |
| } | |
| function parseScreen(raw: unknown): Screen { | |
| const body = (raw ?? {}) as Row; | |
| const counts: Record<string, number> = {}; | |
| for (const [key, value] of Object.entries((body.counts ?? {}) as Row)) counts[key] = num(value) ?? 0; | |
| const statuses = strings(body.statuses); | |
| return { | |
| canEdit: body.canEdit === true, week: text(body.week), weeks: strings(body.weeks), counts, | |
| items: (Array.isArray(body.items) ? body.items : []).map(parseDrop).filter((row): row is Drop => row !== null), | |
| cursor: text(body.cursor) || null, problems: strings(body.problems), | |
| statuses: statuses.length ? statuses : DEFAULT_STATUSES, | |
| total: num(body.total) ?? 0, | |
| summedAsins: num((body.sourceTotals as Row | null)?.summedAsins), | |
| readiness: parseReadiness(body), | |
| }; | |
| } | |
| function parseAsins(raw: unknown): AsinPage { | |
| const body = (raw ?? {}) as Row; | |
| const list = rows(body.asins).map((row) => ({ | |
| asin: text(row.asin), title: text(row.title), skus: strings(row.skus), units: num(row.units), | |
| sales: num(row.sales), causeLabel: text(row.causeLabel), itemId: text(row.itemId), | |
| })).filter((row) => row.asin); | |
| return { asins: list, cursor: text(body.cursor) || null, total: num(body.total) ?? list.length }; | |
| } | |
| function parsePoints(raw: unknown): Point[] { | |
| return rows((raw as Row | null)?.points).map((row) => ({ | |
| week: text(row.week), sessions: num(row.sessions), buyBox: num(row.buyBox), units: num(row.units), | |
| salesRank: num(row.salesRank), searchShare: num(row.searchShare), adSpend: num(row.adSpend), | |
| })).filter((point) => point.week).sort((a, b) => a.week.localeCompare(b.week)); | |
| } | |
| function parseDetail(raw: unknown): Detail | null { | |
| const body = (raw ?? {}) as Row; | |
| const item = parseDrop(body.item); | |
| if (!item) return null; | |
| return { | |
| item, history: rows(body.history).map((event) => ({ | |
| at: text(event.at), by: text(event.by), status: text(event.status), owner: text(event.owner), | |
| due: text(event.due), note: text(event.note), | |
| })), | |
| }; | |
| } | |
| function parseContent(raw: unknown): ContentPage { | |
| const body = (raw ?? {}) as Row; | |
| return { cursor: text(body.cursor) || null, changes: rows(body.changes).map((row) => { | |
| const drop = (row.rankDrop ?? {}) as Row; | |
| const before = num(drop.before), after = num(drop.after); | |
| return { id: text(row.id), day: text(row.day), sku: text(row.sku), field: text(row.field), | |
| label: text(row.label), before: text(row.before), after: text(row.after), | |
| rankDrop: text(drop.day) && before !== null && after !== null ? { day: text(drop.day), before, after } : null }; | |
| }) }; | |
| } | |
| /** "Oct 18, 2026" from an ISO day or stamp. A calendar day is read in UTC. */ | |
| function dayWords(raw: string) { | |
| const value = raw.trim(); | |
| const date = new Date(value.length === 10 ? value + "T00:00:00Z" : value); | |
| return Number.isNaN(date.getTime()) ? value | |
| : date.toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric", timeZone: "UTC" }); | |
| } | |
| const plural = (n: number, one: string, many: string) => `${n.toLocaleString()} ${n === 1 ? one : many}`; | |
| const whole = (value: number) => Math.round(value).toLocaleString(); | |
| const decimals = (value: number, places: number) => value.toLocaleString(undefined, { maximumFractionDigits: places }); | |
| const money = (value: number) => value.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }); | |
| /** One signal's value as a person reads it. */ | |
| function signalValue(key: SignalKey, value: number | null) { | |
| if (value === null) return "Not reported"; | |
| if (key === "buyBox") return `${decimals(value, 1)}%`; | |
| if (key === "salesRank") return `#${whole(value)}`; | |
| if (key === "searchShare") return decimals(value, 2); | |
| if (key === "adSpend") return money(value); | |
| return whole(value); | |
| } | |
| interface Delta { words: string; tone: "up" | "down" | "flat" } | |
| /** The change from the week before, toned by whether it is good for the ASIN. */ | |
| function signalDelta(key: SignalKey, before: number | null, now: number | null): Delta | null { | |
| if (before === null || now === null) return null; | |
| if (key === "buyBox") { | |
| const points = now - before; | |
| if (Math.abs(points) < 0.5) return { words: "No change", tone: "flat" }; | |
| return { words: `${points < 0 ? "Down" : "Up"} ${decimals(Math.abs(points), 0)} points`, tone: points < 0 ? "down" : "up" }; | |
| } | |
| if (before === 0) return now === 0 ? { words: "No change", tone: "flat" } : null; | |
| const pct = ((now - before) / Math.abs(before)) * 100; | |
| if (Math.abs(pct) < 0.5) return { words: "No change", tone: "flat" }; | |
| if (key === "salesRank") { | |
| return pct > 0 ? { words: `Worse by ${decimals(pct, 0)}%`, tone: "down" } | |
| : { words: `Better by ${decimals(-pct, 0)}%`, tone: "up" }; | |
| } | |
| return { words: `${pct < 0 ? "Down" : "Up"} ${decimals(Math.abs(pct), 0)}%`, tone: pct < 0 ? "down" : "up" }; | |
| } | |
| const fellWords = (signals: string[]) => signals | |
| .map((key) => SIGNALS.find((signal) => signal.key === key)?.short ?? key).join(", "); | |
| function Skeleton({ chart }: { chart?: boolean }) { | |
| return <div className="rd-skeleton-rows" aria-busy="true" aria-label="Loading"> | |
| {chart ? <div className="rd-skeleton is-chart" /> : <> | |
| <div className="rd-skeleton" /><div className="rd-skeleton" /><div className="rd-skeleton" /> | |
| </>} | |
| </div>; | |
| } | |
| function Failed({ message, onRetry }: { message: string; onRetry: () => void }) { | |
| return <p className="rd-error" role="alert">{message}{" "} | |
| <button type="button" className="rd-link" onClick={onRetry}>Retry</button></p>; | |
| } | |
| /** A small weekly rank line. Rank is better when lower, so a better week draws higher. */ | |
| function RankSpark({ points, asin }: { points: { week: string; rank: number | null }[]; asin: string }) { | |
| const held = points.filter((point): point is { week: string; rank: number } => point.rank !== null); | |
| if (held.length < 2) return <span className="rd-muted">No trend</span>; | |
| const ranks = held.map((point) => point.rank); | |
| const low = ranks.reduce((a, b) => Math.min(a, b)), high = ranks.reduce((a, b) => Math.max(a, b)), span = high - low || 1; | |
| const width = 96, height = 24, step = width / (points.length - 1); | |
| const segments: string[][] = [[]]; | |
| points.forEach((point, index) => { | |
| if (point.rank === null) { segments.push([]); return; } | |
| segments[segments.length - 1].push(`${(index * step).toFixed(1)},${(2 + ((point.rank - low) / span) * (height - 4)).toFixed(1)}`); | |
| }); | |
| const worse = ranks[ranks.length - 1] > ranks[0]; | |
| return <svg className={worse ? "rd-spark is-down" : "rd-spark is-up"} viewBox={`0 0 ${width} ${height}`} | |
| width={width} height={height} role="img" aria-label={`Weekly rank for ${asin}, ${held.length} weeks`} | |
| data-rank-trend={held.length}> | |
| <title>{points.map((point) => `${point.week}: ${point.rank === null ? "Not reported" : `#${whole(point.rank)}`}`).join(", ")}</title> | |
| {segments.filter((line) => line.length > 1).map((line, index) => <polyline key={index} points={line.join(" ")} | |
| fill="none" strokeWidth="1.5" strokeLinejoin="round" strokeLinecap="round" />)} | |
| {points.map((point, index) => point.rank === null ? null : <circle key={point.week} | |
| cx={index * step} cy={2 + ((point.rank - low) / span) * (height - 4)} r="1.5" />)} | |
| </svg>; | |
| } | |
| const STATUS_TONE: Record<string, string> = { Open: "is-open", "In progress": "is-progress", Fixed: "is-fixed", Ignored: "is-ignored" }; | |
| function StatusChip({ status }: { status: string }) { | |
| return <span className={`rd-chip ${STATUS_TONE[status] ?? "is-open"}`} data-status-chip={status}>{status}</span>; | |
| } | |
| function RankChange({ drop }: { drop: Drop }) { | |
| const before = drop.rankNow !== null && drop.rankChange !== null ? drop.rankNow - drop.rankChange : null; | |
| const delta = signalDelta("salesRank", before, drop.rankNow); | |
| return delta ? <span className={`rd-card-delta is-${delta.tone}`}>{delta.words}</span> : <span className="rd-muted">No comparison</span>; | |
| } | |
| function DropTable({ items, onOpen }: { items: Drop[]; onOpen: (drop: Drop) => void }) { | |
| return <table className="rd-table rd-drops"> | |
| <colgroup> | |
| <col className="rd-col-asin" /><col className="rd-col-rank" /><col className="rd-col-change" /> | |
| <col className="rd-col-trend" /><col className="rd-col-status" /> | |
| </colgroup> | |
| <thead> | |
| <tr> | |
| <th scope="col">Product</th><th scope="col" className="is-num">Rank now</th><th scope="col">Rank change</th> | |
| <th scope="col">Weekly rank</th><th scope="col">Status</th> | |
| </tr> | |
| </thead> | |
| <tbody> | |
| {items.map((drop) => <tr key={drop.id} className="rd-row" data-drop-asin={drop.asin}> | |
| <td className="rd-c-asin"> | |
| <button type="button" className="rd-open rd-product-title" title={drop.productTitle || drop.asin} | |
| onClick={() => onOpen(drop)}>{drop.productTitle || drop.asin}</button> | |
| <span className="rd-sub">{[drop.asin, drop.sku].filter(Boolean).join(" · ")}</span> | |
| <details className="rd-row-details"><summary>Details</summary> | |
| <span className="rd-sub">{drop.cause}</span> | |
| <span className="rd-sub">{fellWords(drop.signals)}</span> | |
| <span className="rd-sub">{drop.owner || "No owner"}</span> | |
| </details> | |
| </td> | |
| <td className="rd-c-rank is-num">{drop.rankNow === null ? <span className="rd-muted">Not reported</span> | |
| : signalValue("salesRank", drop.rankNow)}</td> | |
| <td className="rd-c-change"><RankChange drop={drop} /></td> | |
| <td className="rd-c-trend"><RankSpark points={drop.rankTrend} asin={drop.asin} /></td> | |
| <td className="rd-c-status"><StatusChip status={drop.status} /></td> | |
| </tr>)} | |
| </tbody> | |
| </table>; | |
| } | |
| const AMAZON_CONNECTOR = "#/connectors?connector=amazon_sp&tab=overview"; | |
| /** Shown until two weekly syncs are held: one action over three short steps, weeks held and the next sync. */ | |
| function FirstRun({ readiness }: { readiness: Readiness }) { | |
| const steps: [string, string][] = [ | |
| ["Connect Amazon", "Sales, traffic and catalog data"], | |
| ["Two weekly syncs", "Each week adds one rank point"], | |
| ["See each drop", "Rank, cause and a fix per ASIN"], | |
| ]; | |
| const held = Math.min(readiness.held, readiness.needed); | |
| return <section className="rd-first" data-first-run={readiness.held} aria-label="Ranking diagnostic first run"> | |
| <div className="rd-first-head"> | |
| <h2 className="rd-first-title">Two weekly syncs needed</h2> | |
| <p className="rd-first-held" role="status"> | |
| <span data-weeks-held={readiness.held}>{readiness.held} of {readiness.needed} weeks held</span> | |
| {readiness.nextSync && <> · Next weekly sync {dayWords(readiness.nextSync)}</>} | |
| </p> | |
| <div className="rd-first-meter" role="progressbar" aria-label="Weeks held" aria-valuemin={0} | |
| aria-valuemax={readiness.needed} aria-valuenow={held}> | |
| <span style={{ width: `${(held / Math.max(readiness.needed, 1)) * 100}%` }} /> | |
| </div> | |
| <a className="rd-button is-primary rd-first-action" href={AMAZON_CONNECTOR}>Open Amazon connector</a> | |
| </div> | |
| <ol className="rd-first-steps"> | |
| {steps.map(([title, line], index) => <li key={title} className="rd-first-step"> | |
| <span className="rd-first-number" aria-hidden="true">{index + 1}</span> | |
| <span className="rd-first-step-title">{title}</span> | |
| <span className="rd-first-step-line">{line}</span> | |
| </li>)} | |
| </ol> | |
| </section>; | |
| } | |
| function AsinTable({ list, onOpen }: { list: AsinRow[]; onOpen: (row: AsinRow) => void }) { | |
| return <table className="rd-table rd-asins"> | |
| <colgroup> | |
| <col className="rd-col-asin" /><col className="rd-col-units" /><col className="rd-col-sales" /> | |
| <col className="rd-col-drop" /> | |
| </colgroup> | |
| <thead> | |
| <tr> | |
| <th scope="col">ASIN</th><th scope="col" className="is-num">Units</th> | |
| <th scope="col" className="is-num">Sales</th><th scope="col">Drop</th> | |
| </tr> | |
| </thead> | |
| <tbody> | |
| {list.map((row) => <tr key={row.asin} className="rd-row"> | |
| <td className="rd-c-asin"> | |
| <button type="button" className="rd-open" onClick={() => onOpen(row)}>{row.asin}</button> | |
| {(row.title || row.skus[0]) && <span className="rd-sub">{row.title || row.skus[0]}</span>} | |
| </td> | |
| <td className="rd-c-units is-num">{row.units === null ? "" : whole(row.units)} | |
| {row.units !== null && <span className="rd-unit-word">{row.units === 1 ? " unit" : " units"}</span>}</td> | |
| <td className="rd-c-sales is-num">{row.sales === null ? "" : money(row.sales)}</td> | |
| <td className="rd-c-drop">{row.causeLabel || <span className="rd-muted">None</span>}</td> | |
| </tr>)} | |
| </tbody> | |
| </table>; | |
| } | |
| function SignalTrend({ points, signal, asin, week }: { points: Point[]; signal: SignalKey; asin: string; week: string }) { | |
| const meta = SIGNALS.find((row) => row.key === signal) ?? SIGNALS[0]; | |
| const held = points.filter((point) => point[signal] !== null).length; | |
| if (points.length < 2) return <p className="rd-note" role="status">The trend shows after two weekly syncs.</p>; | |
| if (held < 2) return <p className="rd-note" role="status">{meta.label} is not reported for two weeks yet.</p>; | |
| return <SourceTrend series={points.map((point) => ({ x: point.week, value: point[signal] }))} | |
| label={`${meta.label} by week for ${asin}`} reverse={signal === "salesRank"} | |
| format={signal === "salesRank" ? ",d" : undefined} selected={week} />; | |
| } | |
| /** The signal cards double as the chart's tabs: one card per signal, value over its weekly change. */ | |
| function SignalCards({ points, week, picked, onPick }: { | |
| points: Point[]; week: string; picked: SignalKey; onPick: (key: SignalKey) => void; | |
| }) { | |
| const index = points.findIndex((point) => point.week === week); | |
| const at = index >= 0 ? index : points.length - 1; | |
| const now = points[at] ?? null; | |
| const before = at > 0 ? points[at - 1] : null; | |
| return <>{before && <p className="rd-compare">Against the week of {dayWords(before.week)}</p>} | |
| <div className="rd-cards" role="tablist" aria-label="Signal"> | |
| {SIGNALS.map((signal) => { | |
| const delta = now && before ? signalDelta(signal.key, before[signal.key], now[signal.key]) : null; | |
| return <button key={signal.key} type="button" role="tab" aria-selected={picked === signal.key} | |
| className={picked === signal.key ? "rd-card is-active" : "rd-card"} onClick={() => onPick(signal.key)}> | |
| <span className="rd-card-label">{signal.label}</span> | |
| <span className="rd-card-value">{now ? signalValue(signal.key, now[signal.key]) : "Not reported"}</span> | |
| <span className={delta ? `rd-card-delta is-${delta.tone}` : "rd-card-delta"}> | |
| {delta ? delta.words : before ? "No comparison" : "First week"} | |
| </span> | |
| </button>; | |
| })} | |
| </div></>; | |
| } | |
| interface DrawerProps { | |
| appId: string; | |
| opened: Opened; | |
| url: (path: string, params?: Record<string, string>) => string; | |
| editable: boolean; | |
| statuses: string[]; | |
| onClose: () => void; | |
| onSaved: () => void; | |
| } | |
| function ContentTimeline({ changes }: { changes: ContentChange[] }) { | |
| if (!changes.length) return <p className="rd-note" role="status">No content changes</p>; | |
| return <ol className="rd-events">{changes.map((change) => <li key={change.id} className="rd-event" | |
| data-content-field={change.field} data-rank-drop-day={change.rankDrop?.day}> | |
| <time className="rd-event-when" dateTime={change.day}>{dayWords(change.day)}</time> | |
| <span className="rd-event-what">{change.label}{" · "}<span className="rd-muted">{change.sku}</span></span> | |
| <dl className="rd-facts"> | |
| <div className="rd-fact"><dt>Before</dt><dd style={{ whiteSpace: "pre-wrap" }}>{change.before || "Empty"}</dd></div> | |
| <div className="rd-fact"><dt>After</dt><dd style={{ whiteSpace: "pre-wrap" }}>{change.after || "Empty"}</dd></div> | |
| </dl> | |
| {change.rankDrop && <span className="rd-event-what" style={{ color: "var(--lp-yellow-deep)" }}> | |
| Before rank drop on {dayWords(change.rankDrop.day)}{" "} | |
| (#{whole(change.rankDrop.before)} to #{whole(change.rankDrop.after)}) | |
| </span>} | |
| </li>)}</ol>; | |
| } | |
| function ContentChanges({ asin, url, onRank }: { | |
| asin: string; url: DrawerProps["url"]; onRank: () => void; | |
| }) { | |
| const [result, setResult] = useState<Load<ContentPage>>({ phase: "loading" }); | |
| const [attempt, setAttempt] = useState(0); | |
| const [cursors, setCursors] = useState<string[]>([""]); | |
| const [page, setPage] = useState(0); | |
| const cursor = cursors[page] ?? ""; | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setResult({ phase: "loading" }); | |
| void fetch(url(`/content-history/${encodeURIComponent(asin)}`, { cursor, limit: "200" }), | |
| { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "Content changes could not be loaded.")) | |
| .then((body) => { if (!controller.signal.aborted) setResult({ phase: "ready", value: parseContent(body) }); }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setResult({ phase: "error", message: failure(reason, "Content changes could not be loaded.") }); | |
| }); | |
| return () => controller.abort(); | |
| }, [asin, url, cursor, attempt]); | |
| return <section className="rd-section" aria-label="Content changes" data-testid="listing-content-history"> | |
| <h3 className="rd-section-title">Content changes</h3> | |
| <button type="button" className="rd-link" style={{ alignSelf: "flex-start" }} onClick={onRank}>Show rank</button> | |
| {result.phase === "loading" && <Skeleton />} | |
| {result.phase === "error" && <Failed message={result.message} onRetry={() => setAttempt((n) => n + 1)} />} | |
| {result.phase === "ready" && <> | |
| <ContentTimeline changes={result.value.changes} /> | |
| {(page > 0 || result.value.cursor) && <div className="rd-foot" aria-label="Content history pages"> | |
| <span className="rd-results">Page {page + 1}</span> | |
| <button type="button" className="rd-button" disabled={page === 0} onClick={() => setPage((n) => n - 1)}>Previous</button> | |
| <button type="button" className="rd-button" disabled={!result.value.cursor} onClick={() => { | |
| const next = result.value.cursor; | |
| if (!next) return; | |
| setCursors((held) => [...held.slice(0, page + 1), next]); | |
| setPage((n) => n + 1); | |
| }}>Next</button> | |
| </div>} | |
| </>} | |
| </section>; | |
| } | |
| function Drawer({ appId, opened, url, editable, statuses, onClose, onSaved }: DrawerProps) { | |
| const [detail, setDetail] = useState<Load<Detail | null>>({ phase: "loading" }); | |
| const [detailAttempt, setDetailAttempt] = useState(0); | |
| const [trend, setTrend] = useState<Load<Point[]>>({ phase: "loading" }); | |
| const [trendAttempt, setTrendAttempt] = useState(0); | |
| const [signal, setSignal] = useState<SignalKey>("salesRank"); | |
| const [status, setStatus] = useState(""); | |
| const [saving, setSaving] = useState(false); | |
| const [saveError, setSaveError] = useState(""); | |
| const [saved, setSaved] = useState(false); | |
| useEffect(() => { | |
| if (!opened.itemId) { setDetail({ phase: "ready", value: null }); return; } | |
| const controller = new AbortController(); | |
| setDetail({ phase: "loading" }); | |
| void fetch(url(`/items/${encodeURIComponent(opened.itemId)}`), { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "This drop could not be loaded.")) | |
| .then((body) => { | |
| if (controller.signal.aborted) return; | |
| const value = parseDetail(body); | |
| if (!value) { setDetail({ phase: "error", message: "This drop could not be loaded." }); return; } | |
| setDetail({ phase: "ready", value }); | |
| setStatus(value.item.status); | |
| const first = value.item.signals.includes("salesRank") ? SIGNALS.find((row) => row.key === "salesRank") | |
| : SIGNALS.find((row) => value.item.signals.includes(row.key)); | |
| if (first && detailAttempt === 0) setSignal(first.key); | |
| }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setDetail({ phase: "error", message: failure(reason, "This drop could not be loaded.") }); | |
| }); | |
| return () => controller.abort(); | |
| }, [url, opened.itemId, detailAttempt]); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setTrend({ phase: "loading" }); | |
| void fetch(url(`/trend/${encodeURIComponent(opened.asin)}`), { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "The trend could not be loaded.")) | |
| .then((body) => { if (!controller.signal.aborted) setTrend({ phase: "ready", value: parsePoints(body) }); }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setTrend({ phase: "error", message: failure(reason, "The trend could not be loaded.") }); | |
| }); | |
| return () => controller.abort(); | |
| }, [url, opened.asin, trendAttempt]); | |
| const item = detail.phase === "ready" ? detail.value?.item ?? null : null; | |
| const changed = item !== null && status !== "" && status !== item.status; | |
| const save = async () => { | |
| if (!item || !changed) return; | |
| setSaving(true); | |
| setSaveError(""); | |
| setSaved(false); | |
| try { | |
| const response = await fetch(url(`/items/${encodeURIComponent(item.id)}`), { | |
| method: "PATCH", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" }, | |
| body: JSON.stringify({ status }), | |
| }); | |
| await readJson(response, "The status was not saved."); | |
| setSaved(true); | |
| setDetailAttempt((count) => count + 1); | |
| onSaved(); | |
| } catch (reason) { | |
| setSaveError(failure(reason, "The status was not saved.")); | |
| } finally { | |
| setSaving(false); | |
| } | |
| }; | |
| const history = detail.phase === "ready" ? detail.value?.history ?? [] : []; | |
| const week = item?.week || opened.week; | |
| // D-12061, D-12028: the shared SKU actions drawer holds this ASIN's detail, its action list and the App cadence. | |
| return <SkuActions appId={appId} appKind="ranking_diagnostic" grain="asin" entityKey={opened.asin} | |
| title={item?.productTitle || opened.title || opened.asin} canEdit={editable} canRead onClose={onClose}> | |
| <div className="rd-drawer-body" data-ranking-drawer={opened.asin}> | |
| {detail.phase === "loading" && <Skeleton />} | |
| {detail.phase === "error" && <Failed message={detail.message} onRetry={() => setDetailAttempt((count) => count + 1)} />} | |
| {detail.phase === "ready" && !item && <p className="rd-note" role="status">No drop this week</p>} | |
| {item && <section className="rd-cause" aria-label="Cause"> | |
| <p className="rd-cause-label">Cause</p> | |
| <p className="rd-cause-name">{item.cause}</p> | |
| {item.reason && <p className="rd-cause-reason">{item.reason}</p>} | |
| <p className="rd-cause-label">Fix</p> | |
| <p className="rd-cause-fix">{item.fix}</p> | |
| </section>} | |
| {item && (editable ? <form className="rd-status-form" onSubmit={(event) => { event.preventDefault(); void save(); }}> | |
| <div className="rd-status-row"> | |
| <label className="rd-field"> | |
| <span className="rd-field-label">Status</span> | |
| <select className="rd-select" value={status} disabled={saving} | |
| onChange={(event) => { setStatus(event.target.value); setSaved(false); }}> | |
| {statuses.map((option) => <option key={option} value={option}>{option}</option>)} | |
| </select> | |
| </label> | |
| <button type="submit" className="rd-button is-primary" disabled={saving || !changed}>{saving ? "Saving" : "Save"}</button> | |
| {saved && <span className="rd-saved" role="status">Saved</span>} | |
| </div> | |
| {saveError && <p className="rd-error" role="alert">{saveError}</p>} | |
| </form> : null)} | |
| <section className="rd-section" aria-label="Weekly trend"> | |
| <h3 className="rd-section-title">Weekly trend</h3> | |
| {trend.phase === "loading" && <Skeleton chart />} | |
| {trend.phase === "error" && <Failed message={trend.message} onRetry={() => setTrendAttempt((count) => count + 1)} />} | |
| {trend.phase === "ready" && <> | |
| <SignalCards points={trend.value} week={week} picked={signal} onPick={setSignal} /> | |
| <div className="rd-chart" role="tabpanel"> | |
| <SignalTrend points={trend.value} signal={signal} asin={opened.asin} week={week} /> | |
| </div> | |
| </>} | |
| </section> | |
| <ContentChanges asin={opened.asin} url={url} onRank={() => setSignal("salesRank")} /> | |
| {item && <dl className="rd-facts"> | |
| {!editable && <div className="rd-fact"><dt>Status</dt><dd>{item.status}</dd></div>} | |
| <div className="rd-fact"><dt>Owner</dt><dd>{item.owner || "No owner"}</dd></div> | |
| {item.due && <div className="rd-fact"><dt>Due</dt><dd className="is-num">{dayWords(item.due)}</dd></div>} | |
| <div className="rd-fact"><dt>Week of</dt><dd className="is-num">{dayWords(item.week)}</dd></div> | |
| </dl>} | |
| {history.length > 0 && <section className="rd-section" aria-label="History"> | |
| <h3 className="rd-section-title">History</h3> | |
| <ol className="rd-events">{history.map((event, index) => <li key={index} className="rd-event"> | |
| <span className="rd-event-what">{event.status}</span> | |
| <span className="rd-event-detail">{[event.by && `By ${event.by}`, event.owner && `Owner ${event.owner}`, | |
| event.due && `Due ${dayWords(event.due)}`, event.note].filter(Boolean).join(", ")}</span> | |
| <span className="rd-event-when">{event.at ? dayWords(event.at) : "Unknown date"}</span> | |
| </li>)}</ol> | |
| </section>} | |
| <ActionCadence appId={appId} appKind="ranking_diagnostic" canRead /> | |
| </div> | |
| </SkuActions>; | |
| } | |
| export default function RankingDiagnosticView({ application, canEdit }: { | |
| application: RankingDiagnosticApplication; canEdit?: boolean; | |
| }) { | |
| const appId = application.id; | |
| const url = useCallback((path: string, params: Record<string, string> = {}) => { | |
| const query = new URLSearchParams({ app: appId, ...params }); | |
| return `${API_V1}/app-kinds/ranking_diagnostic${path}?${query.toString()}`; | |
| }, [appId]); | |
| const [tab, setTab] = useState(DROPS); | |
| const [week, setWeek] = useState(""); | |
| const [search, setSearch] = useState(""); | |
| const [query, setQuery] = useState(""); | |
| const [page, setPage] = useState(0); | |
| const [screenCursors, setScreenCursors] = useState<string[]>([""]); | |
| const [asinCursors, setAsinCursors] = useState<string[]>([""]); | |
| const [screen, setScreen] = useState<Load<Screen>>({ phase: "loading" }); | |
| const [screenAttempt, setScreenAttempt] = useState(0); | |
| const [held, setHeld] = useState<{ week: string; weeks: string[]; counts: Record<string, number> | null; | |
| summedAsins: number | null; readiness?: Readiness | null }>({ week: "", weeks: [], counts: null, summedAsins: null }); | |
| const [statuses, setStatuses] = useState<string[]>(DEFAULT_STATUSES); | |
| const [problems, setProblems] = useState<string[]>([]); | |
| const [serverEdit, setServerEdit] = useState(false); | |
| const [asins, setAsins] = useState<Load<AsinPage>>({ phase: "loading" }); | |
| const [asinAttempt, setAsinAttempt] = useState(0); | |
| const [opened, setOpened] = useState<Opened | null>(null); | |
| const [listedAction, setListedAction] = useState<SkuAction | null>(null); | |
| const opener = useRef<HTMLElement | null>(null); | |
| const statusTab = statuses.includes(tab) ? tab : ""; | |
| const screenParams = useCallback((extra: Record<string, string> = {}) => { | |
| const params: Record<string, string> = { limit: "200", q: query, ...extra }; | |
| if (statusTab) params.status = statusTab; | |
| if (week) params.week = week; | |
| return params; | |
| }, [statusTab, week, query]); | |
| const screenCursor = screenCursors[page] ?? ""; | |
| const asinCursor = asinCursors[page] ?? ""; | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setScreen({ phase: "loading" }); | |
| void fetch(url("/screen", screenParams({ cursor: screenCursor })), { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "The drop list could not be loaded.")) | |
| .then((body) => { | |
| if (controller.signal.aborted) return; | |
| const value = parseScreen(body); | |
| setScreen({ phase: "ready", value }); | |
| setHeld({ week: value.week, weeks: value.weeks, counts: value.counts, summedAsins: value.summedAsins, | |
| readiness: value.readiness }); | |
| setStatuses(value.statuses); | |
| setProblems(value.problems); | |
| setServerEdit(value.canEdit); | |
| }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setScreen({ phase: "error", message: failure(reason, "The drop list could not be loaded.") }); | |
| }); | |
| return () => controller.abort(); | |
| }, [url, screenParams, screenAttempt, screenCursor]); | |
| useEffect(() => { | |
| const controller = new AbortController(); | |
| setAsins({ phase: "loading" }); | |
| const params: Record<string, string> = { limit: "200", q: query, cursor: asinCursor }; | |
| if (week) params.week = week; | |
| void fetch(url("/asins", params), { credentials: CREDENTIALS, signal: controller.signal }) | |
| .then((response) => readJson(response, "The ASIN list could not be loaded.")) | |
| .then((body) => { if (!controller.signal.aborted) setAsins({ phase: "ready", value: parseAsins(body) }); }) | |
| .catch((reason: unknown) => { | |
| if (!controller.signal.aborted) setAsins({ phase: "error", message: failure(reason, "The ASIN list could not be loaded.") }); | |
| }); | |
| return () => controller.abort(); | |
| }, [url, week, asinAttempt, query, asinCursor]); | |
| const editable = canEdit === true && serverEdit; | |
| const resetPages = () => { | |
| setPage(0); | |
| setScreenCursors([""]); | |
| setAsinCursors([""]); | |
| }; | |
| const nextPage = () => { | |
| if (!cursor) return; | |
| if (tab === ASINS) setAsinCursors((now) => [...now.slice(0, page + 1), cursor]); | |
| else setScreenCursors((now) => [...now.slice(0, page + 1), cursor]); | |
| setPage((now) => now + 1); | |
| }; | |
| const open = (next: Opened) => { | |
| opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null; | |
| setListedAction(null); | |
| setOpened(next); | |
| }; | |
| const closeDrawer = useCallback(() => { | |
| setOpened(null); | |
| opener.current?.focus(); | |
| }, []); | |
| const onSaved = useCallback(() => { setPage(0); setScreenCursors([""]); setAsinCursors([""]); | |
| setScreenAttempt((count) => count + 1); }, []); | |
| const counts = held.counts; | |
| const dropTotal = counts ? statuses.reduce((sum, status) => sum + (counts[status] ?? 0), 0) : null; | |
| const asinTotal = asins.phase === "ready" ? asins.value.total : null; | |
| const tabs: [string, number | null][] = [[DROPS, dropTotal], [DASHBOARD, null], | |
| ...statuses.map((status): [string, number | null] => [status, counts ? counts[status] ?? 0 : null]), | |
| [ASINS, asinTotal], [BENCHMARK, null]]; | |
| const state = tab === ASINS ? asins : screen; | |
| const retry = () => (tab === ASINS ? setAsinAttempt : setScreenAttempt)((count) => count + 1); | |
| const listed = tab === ASINS ? (asins.phase === "ready" ? asins.value.asins.length : 0) | |
| : (screen.phase === "ready" ? screen.value.items.length : 0); | |
| const total = tab === ASINS ? asinTotal ?? listed : screen.phase === "ready" ? screen.value.total : 0; | |
| const cursor = tab === ASINS ? (asins.phase === "ready" ? asins.value.cursor : null) | |
| : (screen.phase === "ready" ? screen.value.cursor : null); | |
| const shownWeek = week || held.week; | |
| const readiness = held.readiness ?? null; | |
| if (screen.phase === "ready" && readiness && readiness.held < readiness.needed) { | |
| return <div className="rd-app"><div className="rd-scroll"><FirstRun readiness={readiness} /></div></div>; | |
| } | |
| return <div className="rd-app"> | |
| <div className="rd-scroll"> | |
| {tab !== DASHBOARD && tab !== BENCHMARK && shownWeek && <div className="rd-toolbar"> | |
| {held.weeks.length > 1 ? <label className="rd-week"> | |
| <span className="rd-field-label">Week of</span> | |
| <select className="rd-select" value={shownWeek} | |
| onChange={(event) => { setWeek(event.target.value); resetPages(); setOpened(null); setListedAction(null); }}> | |
| {[...held.weeks].reverse().map((option) => <option key={option} value={option}>{dayWords(option)}</option>)} | |
| </select> | |
| </label> : <p className="rd-week-text">Week of {dayWords(shownWeek)}</p>} | |
| {held.summedAsins !== null && <span className="rd-results"> | |
| {plural(held.summedAsins, "summed ASIN", "summed ASINs")}</span>} | |
| </div>} | |
| {tab !== DASHBOARD && tab !== BENCHMARK && <form className="rd-toolbar" role="search" onSubmit={(event) => { | |
| event.preventDefault(); setQuery(search.trim()); resetPages(); setOpened(null); setListedAction(null); | |
| }}> | |
| <label className="rd-week"> | |
| <span className="rd-field-label">Search</span> | |
| <input type="search" className="rd-select" value={search} aria-label="Search ASINs" | |
| onChange={(event) => setSearch(event.target.value)} /> | |
| </label> | |
| <button type="submit" className="rd-button">Search</button> | |
| </form>} | |
| <AppTabs tabs={tabs.map(([id, count]) => ({ id, label: tabLabel(id), count }))} value={tab} | |
| aria-label="Ranking diagnostic tabs" onChange={(key) => { | |
| setTab(key); resetPages(); setOpened(null); setListedAction(null); | |
| }} /> | |
| {tab !== DASHBOARD && tab !== BENCHMARK && problems.length > 0 && <div className="rd-problems"> | |
| {problems.map((problem) => <p key={problem} className="rd-problem" role="status">{problem}</p>)} | |
| </div>} | |
| <div className="rd-body" role="tabpanel" aria-label={tabLabel(tab)}> | |
| {tab === DASHBOARD ? <Dashboard key={appId} appId={appId} /> : tab === BENCHMARK ? <Benchmark key={appId} url={url} /> : <> | |
| {state.phase === "loading" && <Skeleton />} | |
| {state.phase === "error" && <Failed message={state.message} onRetry={retry} />} | |
| {state.phase === "ready" && listed === 0 && <p className="rd-empty" role="status">{EMPTY[tab] ?? "Nothing here"}</p>} | |
| {tab !== ASINS && screen.phase === "ready" && listed > 0 && <DropTable items={screen.value.items} | |
| onOpen={(drop) => open({ asin: drop.asin, title: drop.productTitle, itemId: drop.id, week: drop.week })} />} | |
| {tab === ASINS && asins.phase === "ready" && listed > 0 && <AsinTable list={asins.value.asins} | |
| onOpen={(row) => open({ asin: row.asin, title: row.title, itemId: row.itemId, week: shownWeek })} />} | |
| {state.phase === "ready" && (listed > 0 || page > 0) && <div className="rd-foot"> | |
| <span className="rd-results">{tab === ASINS ? plural(total, "ASIN", "ASINs") : plural(total, "drop", "drops")}</span> | |
| <span className="rd-results">Page {page + 1}</span> | |
| <button type="button" className="rd-button" disabled={page === 0} | |
| onClick={() => setPage((now) => now - 1)}>Previous</button> | |
| <button type="button" className="rd-button" disabled={!cursor} onClick={nextPage}>Next</button> | |
| </div>} | |
| <ActionList appId={appId} canEdit={canEdit === true} onOpenEntity={action => { | |
| setOpened(null); setListedAction(action); | |
| }} /> | |
| </>} | |
| </div> | |
| </div> | |
| {opened && <Drawer key={`${opened.asin}:${opened.itemId}`} appId={appId} opened={opened} url={url} editable={editable} | |
| statuses={statuses} onClose={closeDrawer} onSaved={onSaved} />} | |
| {listedAction && <SkuActions appId={appId} appKind="ranking_diagnostic" grain={listedAction.grain} | |
| entityKey={listedAction.key} title={listedAction.key} canEdit={canEdit === true} | |
| onClose={() => setListedAction(null)} />} | |
| </div>; | |
| } | |