mirror of
https://github.com/Zproger/Aurum.git
synced 2026-11-18 08:02:49 +07:00
feat: crypto portfolio analytics (history chart, allocation, P&L, cost basis)
Adds the analytics half of the CoinMarketCap reference: a value-over-time chart (GET /crypto/history, forward-filled from AssetValuation like Net Worth's own series but scoped to crypto assets), an allocation breakdown by coin, and stat tiles for all-time profit, total invested (cost basis), and best/worst performer. Deliberately no "24h" range — history is only as dense as the sync cadence (button or once/day), so a 24h chart would be one or two points, not a smooth intraday line. Cost basis / all-time profit / best-worst performer aren't separate endpoints: they're trivial to derive client-side from fields already in GET /crypto/holdings, so no redundant backend logic. Allocation card follows the dataviz skill's categorical rule: top 7 coins by value get a fixed-order color from the app's already-validated 8-slot ramp, an 8th+ folds into "Other" rather than generating a new hue. 82/82 backend tests passing (3 new for /crypto/history). Verified live against the real CoinGecko API — and caught a real holding the user had already added directly through the UI between messages, which the smoke test correctly left untouched while cleaning up only its own test data. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01855PiW5Wd8n4aRW4n9kByY
This commit is contained in:
119
frontend/src/components/crypto/CryptoAllocationCard.tsx
Normal file
119
frontend/src/components/crypto/CryptoAllocationCard.tsx
Normal file
@@ -0,0 +1,119 @@
|
||||
import { Bitcoin } from "lucide-react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { CryptoHolding } from "@/types";
|
||||
|
||||
interface CryptoAllocationCardProps {
|
||||
holdings: CryptoHolding[];
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
// Fixed categorical order, same 8-slot ramp the rest of the app already
|
||||
// validated (see net_worth_service.py's _CLASS_META comment) — a coin never
|
||||
// gets a freshly generated hue. Only the first 7 get their own color; an 8th+
|
||||
// coin folds into "Other" (--series-other) rather than cycling back through
|
||||
// the ramp, per the dataviz skill's categorical-color rule.
|
||||
const SERIES_COLORS = [
|
||||
"var(--series-1)",
|
||||
"var(--series-2)",
|
||||
"var(--series-3)",
|
||||
"var(--series-4)",
|
||||
"var(--series-5)",
|
||||
"var(--series-6)",
|
||||
"var(--series-7)",
|
||||
];
|
||||
const OTHER_COLOR = "var(--series-other)";
|
||||
const MAX_SLICES = SERIES_COLORS.length;
|
||||
|
||||
interface Slice {
|
||||
key: string;
|
||||
name: string;
|
||||
symbol: string | null;
|
||||
thumbUrl: string | null;
|
||||
amount: number;
|
||||
color: string;
|
||||
}
|
||||
|
||||
function buildSlices(holdings: CryptoHolding[]): Slice[] {
|
||||
const priced = holdings
|
||||
.filter((h) => h.value !== null && Number(h.value) > 0)
|
||||
.map((h) => ({ key: String(h.asset_id), name: h.name, symbol: h.symbol, thumbUrl: h.thumb_url, amount: Number(h.value) }))
|
||||
.sort((a, b) => b.amount - a.amount);
|
||||
|
||||
const top = priced.slice(0, MAX_SLICES).map((item, index) => ({ ...item, color: SERIES_COLORS[index] }));
|
||||
const rest = priced.slice(MAX_SLICES);
|
||||
if (rest.length === 0) return top;
|
||||
|
||||
const otherTotal = rest.reduce((sum, item) => sum + item.amount, 0);
|
||||
return [...top, { key: "other", name: "Other", symbol: null, thumbUrl: null, amount: otherTotal, color: OTHER_COLOR }];
|
||||
}
|
||||
|
||||
export function CryptoAllocationCard({ holdings, isLoading }: CryptoAllocationCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const slices = buildSlices(holdings);
|
||||
const total = slices.reduce((sum, slice) => sum + slice.amount, 0);
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>{t("crypto.allocation.title")}</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoading ? (
|
||||
<p className="py-10 text-center text-sm text-text-muted">{t("common.loading")}</p>
|
||||
) : slices.length === 0 ? (
|
||||
<p className="py-10 text-center text-sm text-text-muted">{t("crypto.empty")}</p>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex h-2.5 w-full overflow-hidden rounded-full bg-surface-2">
|
||||
{slices.map((slice) => (
|
||||
<div
|
||||
key={slice.key}
|
||||
style={{ width: `${(slice.amount / total) * 100}%`, backgroundColor: slice.color }}
|
||||
className="h-full first:rounded-l-full last:rounded-r-full"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<ul className="mt-4 divide-y divide-gridline border-t border-gridline">
|
||||
{slices.map((slice) => {
|
||||
const percent = (slice.amount / total) * 100;
|
||||
return (
|
||||
<li key={slice.key} className="flex items-center gap-3 py-2.5 first:pt-3">
|
||||
{slice.thumbUrl ? (
|
||||
<img src={slice.thumbUrl} alt="" className="h-7 w-7 shrink-0 rounded-full" />
|
||||
) : (
|
||||
<span
|
||||
className="flex h-7 w-7 shrink-0 items-center justify-center rounded-full"
|
||||
style={{ backgroundColor: `${slice.color}26` }}
|
||||
>
|
||||
<Bitcoin size={14} style={{ color: slice.color }} />
|
||||
</span>
|
||||
)}
|
||||
<span className="min-w-0 flex-1 truncate text-sm text-text-primary">
|
||||
{slice.key === "other" ? t("crypto.allocation.other") : slice.name}
|
||||
{slice.symbol && <span className="text-text-muted"> · {slice.symbol}</span>}
|
||||
</span>
|
||||
<span className="hidden w-24 shrink-0 items-center gap-2 sm:flex">
|
||||
<span className="h-1.5 flex-1 overflow-hidden rounded-full bg-surface-2">
|
||||
<span className="block h-full rounded-full" style={{ width: `${percent}%`, backgroundColor: slice.color }} />
|
||||
</span>
|
||||
<span className="w-9 shrink-0 text-right text-xs text-text-muted tabular-nums">{percent.toFixed(0)}%</span>
|
||||
</span>
|
||||
<span className="w-14 shrink-0 text-right text-xs text-text-muted tabular-nums sm:hidden">
|
||||
{percent.toFixed(0)}%
|
||||
</span>
|
||||
<span className="shrink-0 text-sm font-medium tabular-nums text-text-primary">
|
||||
{formatCurrency(slice.amount)}
|
||||
</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
108
frontend/src/components/crypto/CryptoHistoryChart.tsx
Normal file
108
frontend/src/components/crypto/CryptoHistoryChart.tsx
Normal file
@@ -0,0 +1,108 @@
|
||||
import { useState } from "react";
|
||||
import { Area, AreaChart, ResponsiveContainer, Tooltip, YAxis } from "recharts";
|
||||
import { ArrowDown, ArrowUp, Eye, EyeOff } from "lucide-react";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/Card";
|
||||
import { CryptoRangeSelector } from "@/components/crypto/CryptoRangeSelector";
|
||||
import { formatCurrency, formatSignedCurrency, getIntlLocale } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { CryptoHistoryResponse, CryptoRange } from "@/types";
|
||||
|
||||
interface CryptoHistoryChartProps {
|
||||
history: CryptoHistoryResponse | undefined;
|
||||
isLoading: boolean;
|
||||
range: CryptoRange;
|
||||
onRangeChange: (range: CryptoRange) => void;
|
||||
}
|
||||
|
||||
function formatAxisDate(iso: string): string {
|
||||
return new Intl.DateTimeFormat(getIntlLocale(), { month: "short", day: "numeric" }).format(new Date(`${iso}T00:00:00`));
|
||||
}
|
||||
|
||||
function ChartTooltip({ active, payload }: { active?: boolean; payload?: Array<{ payload: { date: string; value: number } }> }) {
|
||||
if (!active || !payload?.length) return null;
|
||||
const point = payload[0].payload;
|
||||
return (
|
||||
<div className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm shadow-md">
|
||||
<p className="text-text-muted">{formatAxisDate(point.date)}</p>
|
||||
<p className="font-medium text-text-primary">{formatCurrency(point.value)}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** The Crypto tab's headline chart — same recipe as NetWorthChart, plus an
|
||||
* eye toggle to mask the big number (screen-over-someone's-shoulder
|
||||
* privacy, doesn't hide anything else on the page). */
|
||||
export function CryptoHistoryChart({ history, isLoading, range, onRangeChange }: CryptoHistoryChartProps) {
|
||||
const { t } = useTranslation();
|
||||
const [hidden, setHidden] = useState(false);
|
||||
const isPositive = history ? Number(history.change_amount) >= 0 : true;
|
||||
const trendColor = isPositive ? "var(--success)" : "var(--danger)";
|
||||
const chartData = history?.series.map((point) => ({ date: point.date, value: Number(point.value) })) ?? [];
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="flex-col items-stretch gap-3 sm:flex-row sm:items-start">
|
||||
<div>
|
||||
<CardTitle>{t("nav.crypto")}</CardTitle>
|
||||
<p className="mt-1.5 flex items-center gap-2 text-2xl font-semibold tabular-nums text-text-primary sm:text-[28px]">
|
||||
{isLoading ? "…" : hidden ? "••••••" : formatCurrency(history?.current ?? 0)}
|
||||
<button
|
||||
type="button"
|
||||
aria-label={hidden ? t("crypto.chart.show") : t("crypto.chart.hide")}
|
||||
onClick={() => setHidden((prev) => !prev)}
|
||||
className="text-text-muted hover:text-text-primary"
|
||||
>
|
||||
{hidden ? <EyeOff size={18} /> : <Eye size={18} />}
|
||||
</button>
|
||||
</p>
|
||||
{history && !hidden && (
|
||||
<p className="mt-1 flex items-center gap-1 text-sm font-medium" style={{ color: trendColor }}>
|
||||
{isPositive ? <ArrowUp size={14} /> : <ArrowDown size={14} />}
|
||||
{formatSignedCurrency(history.change_amount)}
|
||||
{history.change_percent !== null && ` (${isPositive ? "+" : ""}${history.change_percent.toFixed(1)}%)`}
|
||||
<span className="font-normal text-text-muted">{t("netWorth.periodSuffix")}</span>
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<CryptoRangeSelector value={range} onChange={onRangeChange} />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="h-56 w-full sm:h-64">
|
||||
{isLoading || chartData.length === 0 ? (
|
||||
<div className="flex h-full items-center justify-center text-sm text-text-muted">
|
||||
{isLoading ? t("common.loading") : t("netWorth.noChartData")}
|
||||
</div>
|
||||
) : (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<AreaChart data={chartData} margin={{ top: 8, right: 4, bottom: 0, left: 4 }}>
|
||||
<defs>
|
||||
<linearGradient id="cryptoHistoryFill" x1="0" y1="0" x2="0" y2="1">
|
||||
<stop offset="0%" stopColor={trendColor} stopOpacity={0.18} />
|
||||
<stop offset="100%" stopColor={trendColor} stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<YAxis hide domain={["auto", "auto"]} />
|
||||
<Tooltip content={<ChartTooltip />} cursor={{ stroke: "var(--gridline)", strokeWidth: 1 }} />
|
||||
<Area
|
||||
type="monotone"
|
||||
dataKey="value"
|
||||
stroke={trendColor}
|
||||
strokeWidth={2}
|
||||
fill="url(#cryptoHistoryFill)"
|
||||
isAnimationActive={false}
|
||||
activeDot={{ r: 4, strokeWidth: 0 }}
|
||||
/>
|
||||
</AreaChart>
|
||||
</ResponsiveContainer>
|
||||
)}
|
||||
</div>
|
||||
{chartData.length > 1 && (
|
||||
<div className="mt-2 flex justify-between text-xs text-text-muted">
|
||||
<span>{formatAxisDate(chartData[0].date)}</span>
|
||||
<span>{formatAxisDate(chartData[chartData.length - 1].date)}</span>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
20
frontend/src/components/crypto/CryptoRangeSelector.tsx
Normal file
20
frontend/src/components/crypto/CryptoRangeSelector.tsx
Normal file
@@ -0,0 +1,20 @@
|
||||
import { PillSelector } from "@/components/layout/PillSelector";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { CryptoRange } from "@/types";
|
||||
|
||||
interface CryptoRangeSelectorProps {
|
||||
value: CryptoRange;
|
||||
onChange: (value: CryptoRange) => void;
|
||||
}
|
||||
|
||||
export function CryptoRangeSelector({ value, onChange }: CryptoRangeSelectorProps) {
|
||||
const { t } = useTranslation();
|
||||
const ranges: Array<{ value: CryptoRange; label: string }> = [
|
||||
{ value: "7d", label: "7D" },
|
||||
{ value: "30d", label: "30D" },
|
||||
{ value: "90d", label: "90D" },
|
||||
{ value: "all", label: t("common.allShort") },
|
||||
];
|
||||
|
||||
return <PillSelector options={ranges} value={value} onChange={onChange} />;
|
||||
}
|
||||
117
frontend/src/components/crypto/CryptoStatsRow.tsx
Normal file
117
frontend/src/components/crypto/CryptoStatsRow.tsx
Normal file
@@ -0,0 +1,117 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Card, CardContent } from "@/components/ui/Card";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { useTranslation } from "@/lib/i18n";
|
||||
import type { CryptoHolding } from "@/types";
|
||||
|
||||
interface CryptoStatsRowProps {
|
||||
holdings: CryptoHolding[];
|
||||
isLoading: boolean;
|
||||
}
|
||||
|
||||
interface Totals {
|
||||
totalValue: number;
|
||||
totalCostBasis: number;
|
||||
totalProfitLoss: number;
|
||||
totalProfitLossPercent: number | null;
|
||||
best: CryptoHolding | null;
|
||||
worst: CryptoHolding | null;
|
||||
}
|
||||
|
||||
function computeTotals(holdings: CryptoHolding[]): Totals {
|
||||
let totalValue = 0;
|
||||
let totalCostBasis = 0;
|
||||
let best: CryptoHolding | null = null;
|
||||
let worst: CryptoHolding | null = null;
|
||||
|
||||
for (const holding of holdings) {
|
||||
if (holding.value !== null) totalValue += Number(holding.value);
|
||||
if (holding.cost_basis !== null) totalCostBasis += Number(holding.cost_basis);
|
||||
if (holding.profit_loss_percent === null) continue;
|
||||
if (best === null || holding.profit_loss_percent > best.profit_loss_percent!) best = holding;
|
||||
if (worst === null || holding.profit_loss_percent < worst.profit_loss_percent!) worst = holding;
|
||||
}
|
||||
|
||||
const totalProfitLoss = totalValue - totalCostBasis;
|
||||
const totalProfitLossPercent = totalCostBasis > 0 ? (totalProfitLoss / totalCostBasis) * 100 : null;
|
||||
|
||||
return { totalValue, totalCostBasis, totalProfitLoss, totalProfitLossPercent, best, worst };
|
||||
}
|
||||
|
||||
function StatTile({ label, children }: { label: string; children: ReactNode }) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="p-3.5 sm:p-4">
|
||||
<p className="text-xs uppercase tracking-wide text-text-muted">{label}</p>
|
||||
<div className="mt-1.5">{children}</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function PerformerTile({ label, holding }: { label: string; holding: CryptoHolding | null }) {
|
||||
const { t } = useTranslation();
|
||||
if (holding === null || holding.profit_loss_percent === null) {
|
||||
return (
|
||||
<StatTile label={label}>
|
||||
<p className="text-lg font-semibold text-text-muted">—</p>
|
||||
</StatTile>
|
||||
);
|
||||
}
|
||||
const percent = holding.profit_loss_percent;
|
||||
const color = percent >= 0 ? "var(--success)" : "var(--danger)";
|
||||
return (
|
||||
<StatTile label={label}>
|
||||
<div className="flex items-center gap-2">
|
||||
{holding.thumb_url ? (
|
||||
<img src={holding.thumb_url} alt="" className="h-5 w-5 shrink-0 rounded-full" />
|
||||
) : (
|
||||
<span className="h-5 w-5 shrink-0 rounded-full bg-surface-2" />
|
||||
)}
|
||||
<p className="truncate text-lg font-semibold text-text-primary">{holding.symbol}</p>
|
||||
</div>
|
||||
<p className="mt-0.5 text-sm font-medium tabular-nums" style={{ color }}>
|
||||
{percent >= 0 ? "+" : ""}
|
||||
{percent.toFixed(2)}%
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-text-muted">{t("crypto.stats.since", { name: holding.name })}</p>
|
||||
</StatTile>
|
||||
);
|
||||
}
|
||||
|
||||
export function CryptoStatsRow({ holdings, isLoading }: CryptoStatsRowProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (isLoading) {
|
||||
return <p className="py-4 text-center text-sm text-text-muted">{t("common.loading")}</p>;
|
||||
}
|
||||
if (holdings.length === 0) return null;
|
||||
|
||||
const totals = computeTotals(holdings);
|
||||
const profitColor = totals.totalProfitLoss >= 0 ? "var(--success)" : "var(--danger)";
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-4">
|
||||
<StatTile label={t("crypto.stats.allTimeProfit")}>
|
||||
<p className="text-lg font-semibold tabular-nums" style={{ color: profitColor }}>
|
||||
{totals.totalProfitLoss >= 0 ? "+" : ""}
|
||||
{formatCurrency(totals.totalProfitLoss)}
|
||||
</p>
|
||||
{totals.totalProfitLossPercent !== null && (
|
||||
<p className="mt-0.5 text-sm font-medium tabular-nums" style={{ color: profitColor }}>
|
||||
{totals.totalProfitLossPercent >= 0 ? "+" : ""}
|
||||
{totals.totalProfitLossPercent.toFixed(2)}%
|
||||
</p>
|
||||
)}
|
||||
</StatTile>
|
||||
|
||||
<StatTile label={t("crypto.stats.costBasis")}>
|
||||
<p className="text-lg font-semibold tabular-nums text-text-primary">{formatCurrency(totals.totalCostBasis)}</p>
|
||||
<p className="mt-0.5 text-xs text-text-muted">{t("crypto.stats.costBasisHint")}</p>
|
||||
</StatTile>
|
||||
|
||||
<PerformerTile label={t("crypto.stats.bestPerformer")} holding={totals.best} />
|
||||
<PerformerTile label={t("crypto.stats.worstPerformer")} holding={totals.worst} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user