import { useEffect, useState } from "react";
import { agent } from "../lib/agent";
import { screenError, yen } from "../lib/format";
import { groupKey, productLabel, rangeStart, sortGroups, type LedgerBy, type LedgerV2 } from "../lib/ledger";
import { Empty, Meter, Panel, Row, RowName, Seg } from "./ui";
// Earned and spent from the hub's ledger, by product or by day
// (`GET /v2/ledger`, zak-marketplace#769).
type Range = "7" | "30";
export function Ledger() {
const [by, setBy] = useState<Exclude<LedgerBy, "node">>("product");
const [range, setRange] = useState<Range>("30");
const [data, setData] = useState<LedgerV2 | null>(null);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
let live = true;
agent.ledger(by, rangeStart(Number(range))).then(
(d) => {
if (!live) return;
setData(d);
setError(null);
},
(e) => {
if (!live) return;
setData(null);
setError(e?.status === 404 ? "The hub has no ledger breakdown yet." : (screenError(e) ?? "No answer from the agent."));
},
);
return () => {
live = false;
};
}, [by, range]);
const rows = sortGroups(data?.groups ?? null, by);
const max = Math.max(1, ...rows.map((g) => Math.max(g.earned, g.spent)));
return (
<Panel
title="Earned and spent"
aside={
<span className="flex flex-wrap items-center gap-2">
<Seg<Exclude<LedgerBy, "node">>
value={by}
onChange={setBy}
options={[
{ value: "product", label: "By product" },
{ value: "day", label: "By day" },
]}
/>
<Seg<Range>
value={range}
onChange={setRange}
options={[
{ value: "7", label: "7 d" },
{ value: "30", label: "30 d" },
]}
/>
</span>
}
>
{error ? (
<Empty>{error}</Empty>
) : !data ? (
<Empty>Waiting for the hub's ledger.</Empty>
) : rows.length === 0 ? (
<Empty>Nothing earned or spent in this range.</Empty>
) : (
<>
{rows.map((g, i) => {
const k = groupKey(g, by);
return (
<Row key={`${k}-${i}`} cols="1fr 90px 90px 90px">
<RowName name={by === "product" ? productLabel(g.product) : k} />
<Meter parts={[{ pct: (g.earned / max) * 100 }]} />
<span className="tnum text-right font-semibold" title="Earned">
{yen(g.earned)}
</span>
<span className="tnum text-right text-fg-dim" title="Spent">
{g.spent ? `−${yen(g.spent)}` : "—"}
</span>
</Row>
);
})}
<Row cols="1fr 90px 90px 90px">
<RowName name="Total" sub={data.tz} />
<span />
<span className="tnum text-right font-semibold">{yen(data.totals?.earned)}</span>
<span className="tnum text-right text-fg-dim">{data.totals?.spent ? `−${yen(data.totals.spent)}` : "—"}</span>
</Row>
</>
)}
</Panel>
);
}