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 { 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(null); const request = appUrl(appId, "/sku", period, { key: rowKey, ...(cursor ? { cursor } : {}) }); const { state, retry } = useRead(request); const { panel, changePage } = usePageFocus(state.phase === "ready", request); return
{state.phase === "loading" && } {state.phase === "error" && } {state.phase === "ready" && <>
Repeat share
{percent(state.value.repeatShare)}
Repeat revenue
{money(state.value.repeatRevenue, state.value.currency)}

Frequently bought together

{state.value.boughtWith === null ?

Unknown: the basket report is unavailable

: state.value.boughtWith.length === 0 ?

No basket rows for this ASIN

: {state.value.boughtWith.map(row => )}
ASINRankShare
{row.asin} {number(row.rank)}{percent(row.combinationPct)}
} {state.value.repeatMonths.length > 0 && <>

Repeat months

    {state.value.repeatMonths.map(month =>
  • {month}
  • )}
} changePage(next, setCursor)} /> }
; } 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(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(null); const close = useCallback(() => { setOpened(null); opener.current?.focus(); }, []); const summary = useRead(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>({ 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
{(summary.state.phase === "loading" || page.phase === "loading") && } {summary.state.phase === "error" && } {page.phase === "error" && setPageAttempt(value => value + 1)} />} {summary.state.phase === "ready" &&
Repeat share{percent(summary.state.value.repeatShare)}Selected period
Repeat revenue{money(summary.state.value.repeatRevenue, summary.state.value.currency)}Selected period
}

Repeat buyers

setSearch(event.target.value)} />
{page.phase === "ready" && <> {page.value.rows.length === 0 ?

{!page.value.sources.repeat ? "Unknown: the repeat purchase report is unavailable" : q ? "No matching ASIN" : "No repeat purchases in this period"}

:
{page.value.rows.map(row => )}
ASIN Repeat shareRepeat revenue
{percent(row.repeatShare)}{money(row.repeatRevenue, row.currency)}
} { setNavigation({ scope, cursor: next }); setOpened(null); }} /> } {opened && }
; } export default function RepeatBuyersView({ application, canEdit }: { application: Application; canEdit: boolean }) { const [tab, setTab] = useState("repeat"); const [days, setDays] = useState(90); const [custom, setCustom] = useState(null); const [listed, setListed] = useState(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
({ id, label }))} active={tab} ariaLabel="Repeat buyers tabs" onChange={value => setTab(value as Tab)} />
{[30, 90].map(value => )}
{tab !== "dashboard" && <> }
key === tab)?.[1]}> {invalid ?

Choose a start date on or before the end date

: tab === "dashboard" ? : tab === "subscribe-save" ? : }
{tab === "repeat" && <> } {listed && setListed(null)}> {listed.grain === "asin" && !invalid && } }
; }