loopable / web /src /apps /repeat-buyers /AppView.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
b2aa446 verified
Raw History Blame Contribute Delete
12.3 kB
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { API_V1, CREDENTIALS } from "../../apiContract";
import { ActionCadence } from "../actions/ActionCadence";
import { ActionList } from "../actions/ActionList";
import { SkuActions } from "../actions/SkuActions";
import SubscribeSave, { appUrl, Failure, Loading, number, Pager, percent, useRead, usePageFocus } from "./SubscribeSave";
import type { Navigation, Period, Remote } from "./SubscribeSave";
import type { SkuAction } from "../actions/actionsApi";
import Dashboard, { DashboardTabs } from "./Dashboard";
interface Application { id: string; name: string }
interface RepeatRow { key: string; asin: string; repeatShare: number | null; repeatRevenue: number | null; currency: string | null }
interface RepeatPage extends Navigation { rows: RepeatRow[]; sources: { repeat: boolean } }
interface Summary { repeatShare: number | null; repeatRevenue: number | null; currency: string | null; emptyMessage: string | null }
interface Detail extends Navigation {
asin: string; repeatShare: number | null; repeatRevenue: number | null;
currency?: string | null;
repeatMonths: string[];
boughtWith: { asin: string; rank: number | null; combinationPct: number | null }[] | null;
}
const TABS = [["repeat", "Repeat buyers"], ["dashboard", "Dashboard"], ["subscribe-save", "Subscribe & Save"]] as const;
type Tab = typeof TABS[number][0];
const SEARCH_DELAY_MS = 250;
async function readJson(response: Response, fallback: string): Promise<unknown> {
const body = await response.json().catch(() => null);
if (!response.ok) throw new Error(body?.error?.message || body?.detail?.error?.message || fallback);
return body;
}
const failure = (reason: unknown, fallback: string) => reason instanceof Error ? reason.message : fallback;
const parsePage = (body: unknown) => body as RepeatPage;
function shift(end: string, days: number) {
const date = new Date(`${end}T00:00:00Z`);
date.setUTCDate(date.getUTCDate() - days);
return date.toISOString().slice(0, 10);
}
function money(value: number | null, currency?: string | null) {
if (value === null || !currency || !/^[A-Z]{3}$/.test(currency)) return "Unknown";
try { return value.toLocaleString(undefined, { style: "currency", currency, currencyDisplay: "code", maximumFractionDigits: 0 }); }
catch { return "Unknown"; }
}
/** The ASIN detail body inside the shared action drawer. */
function RepeatDetail({ appId, rowKey, period }: { appId: string; rowKey: string; period: Period }) {
const [cursor, setCursor] = useState<string | null>(null);
const request = appUrl(appId, "/sku", period, { key: rowKey, ...(cursor ? { cursor } : {}) });
const { state, retry } = useRead<Detail>(request);
const { panel, changePage } = usePageFocus(state.phase === "ready", request);
return <section ref={panel} className="rb-detail" aria-label={rowKey}>
{state.phase === "loading" && <Loading />}
{state.phase === "error" && <Failure message={state.message} retry={retry} />}
{state.phase === "ready" && <>
<dl className="rb-facts"><dt>Repeat share</dt><dd>{percent(state.value.repeatShare)}</dd>
<dt>Repeat revenue</dt><dd>{money(state.value.repeatRevenue, state.value.currency)}</dd></dl>
<h3 className="rb-heading">Frequently bought together</h3>
{state.value.boughtWith === null ? <p className="rb-notice">Unknown: the basket report is unavailable</p>
: state.value.boughtWith.length === 0 ? <p className="rb-notice">No basket rows for this ASIN</p>
: <table className="rb-table"><thead><tr><th scope="col">ASIN</th><th scope="col">Rank</th><th scope="col">Share</th></tr></thead>
<tbody>{state.value.boughtWith.map(row => <tr key={row.asin}><th scope="row">{row.asin}</th>
<td>{number(row.rank)}</td><td>{percent(row.combinationPct)}</td></tr>)}</tbody></table>}
{state.value.repeatMonths.length > 0 && <><h3 className="rb-heading">Repeat months</h3>
<ul className="rb-muted">{state.value.repeatMonths.map(month => <li key={month}>{month}</li>)}</ul></>}
<Pager page={state.value} onPage={next => changePage(next, setCursor)} />
</>}
</section>;
}
function RepeatOverview({ appId, period, canEdit = false, onChanged }: { appId: string; period: Period; canEdit?: boolean;
onChanged?: () => void }) {
const [search, setSearch] = useState("");
const [q, setQ] = useState("");
const [navigation, setNavigation] = useState<{ scope: string; cursor: string | null }>({ scope: "", cursor: null });
const [opened, setOpened] = useState<string | null>(null);
const trimmedSearch = search.trim();
useEffect(() => {
if (trimmedSearch === q) return;
const timer = window.setTimeout(() => {
setQ(trimmedSearch);
setNavigation({ scope: "", cursor: null });
setOpened(null);
}, SEARCH_DELAY_MS);
return () => window.clearTimeout(timer);
}, [trimmedSearch, q]);
const opener = useRef<HTMLElement | null>(null);
const close = useCallback(() => { setOpened(null); opener.current?.focus(); }, []);
const summary = useRead<Summary>(appUrl(appId, "/summary", period));
const scope = `${appId}:${period.start}:${period.end}:repeat:${q}`;
const cursor = navigation.scope === scope ? navigation.cursor : null;
const params = new URLSearchParams({ ...period, segment: "repeat", limit: "100", q, ...(cursor ? { cursor } : {}) });
const requestUrl = `${API_V1}/app-kinds/repeat_buyers/${encodeURIComponent(appId)}/skus?${params}`;
const latestRequest = useRef(requestUrl);
latestRequest.current = requestUrl;
const previousScope = useRef("");
const [page, setPage] = useState<Remote<RepeatPage>>({ phase: "loading" });
const [pageBusy, setPageBusy] = useState(false);
const [pageAttempt, setPageAttempt] = useState(0);
useEffect(() => {
const controller = new AbortController();
if (previousScope.current !== scope) setPage({ phase: "loading" });
previousScope.current = scope;
setPageBusy(true);
void fetch(requestUrl, { credentials: CREDENTIALS, signal: controller.signal })
.then(response => readJson(response, "The repeat buyers could not be read"))
.then(body => { if (!controller.signal.aborted && latestRequest.current === requestUrl)
setPage({ phase: "ready", value: parsePage(body) }); })
.catch((reason: unknown) => {
if (!controller.signal.aborted && latestRequest.current === requestUrl)
setPage({ phase: "error", message: failure(reason, "The repeat buyers could not be read") });
}).finally(() => { if (!controller.signal.aborted && latestRequest.current === requestUrl) setPageBusy(false); });
return () => controller.abort();
}, [requestUrl, scope, pageAttempt]);
return <section className="rb-overview" aria-label="Repeat buyers">
{(summary.state.phase === "loading" || page.phase === "loading") && <Loading />}
{summary.state.phase === "error" && <Failure message={summary.state.message} retry={summary.retry} />}
{page.phase === "error" && <Failure message={page.message} retry={() => setPageAttempt(value => value + 1)} />}
{summary.state.phase === "ready" && <div className="rb-kpis">
<div className="rb-kpi"><span>Repeat share</span><strong>{percent(summary.state.value.repeatShare)}</strong><small>Selected period</small></div>
<div className="rb-kpi"><span>Repeat revenue</span><strong>{money(summary.state.value.repeatRevenue, summary.state.value.currency)}</strong><small>Selected period</small></div>
</div>}
<div className="rb-toolbar"><h2 className="rb-heading">Repeat buyers</h2>
<input type="search" className="rb-input" aria-label="Search ASIN" placeholder="Search ASIN"
value={search} onChange={event => setSearch(event.target.value)} /></div>
{page.phase === "ready" && <>
{page.value.rows.length === 0 ? <p className="rb-notice" role="status">
{!page.value.sources.repeat ? "Unknown: the repeat purchase report is unavailable"
: q ? "No matching ASIN" : "No repeat purchases in this period"}</p>
: <div className="rb-table-wrap"><table className="rb-table"><thead><tr><th scope="col">ASIN</th>
<th scope="col">Repeat share</th><th scope="col">Repeat revenue</th></tr></thead>
<tbody>{page.value.rows.map(row => <tr key={row.key}><th scope="row">
<button type="button" className="rb-link" onClick={() => {
opener.current = document.activeElement instanceof HTMLElement ? document.activeElement : null;
setOpened(row.key);
}}>{row.asin}</button></th><td>{percent(row.repeatShare)}</td><td>{money(row.repeatRevenue, row.currency)}</td></tr>)}</tbody>
</table></div>}
<Pager page={page.value} busy={pageBusy} onPage={next => {
setNavigation({ scope, cursor: next }); setOpened(null);
}} />
</>}
{opened && <SkuActions appId={appId} appKind="repeat_buyers" grain="asin" entityKey={opened} title={opened}
canEdit={canEdit} onChanged={onChanged} onClose={close}>
<RepeatDetail key={`${appId}:${opened}:${period.start}:${period.end}`} appId={appId} rowKey={opened} period={period} />
</SkuActions>}
</section>;
}
export default function RepeatBuyersView({ application, canEdit }: { application: Application; canEdit: boolean }) {
const [tab, setTab] = useState<Tab>("repeat");
const [days, setDays] = useState(90);
const [custom, setCustom] = useState<Period | null>(null);
const [listed, setListed] = useState<SkuAction | null>(null);
const [revision, setRevision] = useState(0);
const changed = useCallback(() => setRevision(value => value + 1), []);
const period = useMemo(() => {
const end = new Date().toISOString().slice(0, 10);
return custom || { start: shift(end, days - 1), end };
}, [days, custom]);
const invalid = period.start > period.end || !period.start || !period.end;
return <div className="rb-app" data-app-kind="repeat_buyers" data-proof="repeat-buyers">
<DashboardTabs tabs={TABS.map(([id, label]) => ({ id, label }))} active={tab}
ariaLabel="Repeat buyers tabs" onChange={value => setTab(value as Tab)} />
<div className="rb-scroll">
<div className="rb-toolbar rb-period">
<div className="rb-period-options" role="group" aria-label="Period">
{[30, 90].map(value => <button key={value} type="button" className="rb-button" aria-pressed={!custom && days === value}
onClick={() => { setDays(value); setCustom(null); }}>Last {value} days</button>)}
</div>
{tab !== "dashboard" && <><label className="rb-date">From<input type="date" className="rb-input" value={period.start}
onChange={event => setCustom({ ...period, start: event.target.value })} /></label>
<label className="rb-date">To<input type="date" className="rb-input" value={period.end}
onChange={event => setCustom({ ...period, end: event.target.value })} /></label></>}
</div>
<div id="rb-panel" role="tabpanel" aria-label={TABS.find(([key]) => key === tab)?.[1]}>
{invalid ? <p className="rb-notice" role="alert">Choose a start date on or before the end date</p>
: tab === "dashboard" ? <Dashboard appId={application.id} period={period} onPeriodChange={setCustom} />
: tab === "subscribe-save" ? <SubscribeSave key={application.id} appId={application.id} period={period} />
: <RepeatOverview key={`${application.id}:${period.start}:${period.end}:${tab}`} appId={application.id}
period={period} canEdit={canEdit} onChanged={changed} />}
</div>
{tab === "repeat" && <>
<ActionList key={revision} appId={application.id} canEdit={canEdit} onOpenEntity={setListed} />
<ActionCadence appId={application.id} appKind="repeat_buyers" canRead />
</>}
{listed && <SkuActions appId={application.id} appKind="repeat_buyers" grain={listed.grain} entityKey={listed.key}
title={listed.key} canEdit={canEdit} onChanged={changed} onClose={() => setListed(null)}>
{listed.grain === "asin" && !invalid && <RepeatDetail key={`${application.id}:${listed.key}:${period.start}:${period.end}`}
appId={application.id} rowKey={listed.key} period={period} />}
</SkuActions>}
</div>
</div>;
}