feat: full CoinMarketCap-style crypto portfolio (buy/sell log, 1h/24h/7d%, P&L)

Replaces the plain quantity field with a CryptoTransaction log (same
"record events, derive the total" shape as Goal/GoalContribution): quantity
and average buy price are now computed via weighted-average cost — a buy
blends into the running average, a sell reduces quantity but leaves the
average cost of what's still held unchanged.

Switches price fetching from /simple/price to CoinGecko's /coins/markets
(still one batched call for every coin), which also returns 1h/24h/7d %
change in the same request. Old PATCH /crypto/holdings/{id} is replaced by
POST .../transactions (buy/sell, rejects selling more than held), GET
.../transactions (history), and DELETE /crypto/transactions/{id}.

Frontend: CryptoHoldingsTable replaces the simple list with a real table
(Name/Price/1h%/24h%/7d%/Holdings/Avg Buy Price/Profit-Loss/Actions),
horizontally scrollable on mobile rather than dropping columns. New
CryptoTransactionModal (buy/sell) and CryptoTransactionHistoryModal.

Backend: 79/79 tests passing (13 in test_crypto.py, up from 9). Also
verified live end-to-end against the real CoinGecko API with the user's own
key — create, buy, sell, oversell rejection, history, manual refresh, all
against real BTC/ETH prices in EUR — test data cleaned up after.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01855PiW5Wd8n4aRW4n9kByY
This commit is contained in:
ZProger
2026-08-30 04:25:03 +03:00
parent 7e4508d1de
commit e8cd536584
24 changed files with 1154 additions and 374 deletions

View File

@@ -26,6 +26,8 @@ export function CryptoAddModal({ open, onClose }: CryptoAddModalProps) {
const [searchError, setSearchError] = useState<string | null>(null);
const [selected, setSelected] = useState<CryptoSearchResult | null>(null);
const [quantity, setQuantity] = useState("");
const [pricePerUnit, setPricePerUnit] = useState("");
const [date, setDate] = useState(() => new Date().toISOString().slice(0, 10));
const [saveError, setSaveError] = useState<string | null>(null);
useEffect(() => {
@@ -34,6 +36,8 @@ export function CryptoAddModal({ open, onClose }: CryptoAddModalProps) {
setResults([]);
setSelected(null);
setQuantity("");
setPricePerUnit("");
setDate(new Date().toISOString().slice(0, 10));
setSearchError(null);
setSaveError(null);
}, [open]);
@@ -74,6 +78,8 @@ export function CryptoAddModal({ open, onClose }: CryptoAddModalProps) {
name: selected.name,
thumb_url: selected.thumb_url,
quantity,
price_per_unit: pricePerUnit,
date,
});
onClose();
} catch {
@@ -139,17 +145,42 @@ export function CryptoAddModal({ open, onClose }: CryptoAddModalProps) {
</span>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label htmlFor="crypto-quantity">{t("crypto.form.quantityLabel")}</Label>
<Input
id="crypto-quantity"
type="number"
step="any"
min="0"
required
autoFocus
value={quantity}
onChange={(event) => setQuantity(event.target.value)}
/>
</div>
<div>
<Label htmlFor="crypto-price">{t("crypto.form.pricePerUnitLabel")}</Label>
<Input
id="crypto-price"
type="number"
step="any"
min="0"
required
value={pricePerUnit}
onChange={(event) => setPricePerUnit(event.target.value)}
/>
</div>
</div>
<div>
<Label htmlFor="crypto-quantity">{t("crypto.form.quantityLabel")}</Label>
<Label htmlFor="crypto-date">{t("crypto.form.dateLabel")}</Label>
<Input
id="crypto-quantity"
type="number"
step="any"
min="0"
id="crypto-date"
type="date"
required
autoFocus
value={quantity}
onChange={(event) => setQuantity(event.target.value)}
value={date}
onChange={(event) => setDate(event.target.value)}
/>
</div>

View File

@@ -1,75 +0,0 @@
import { type FormEvent, useEffect, useState } from "react";
import { Button } from "@/components/ui/Button";
import { Dialog } from "@/components/ui/Dialog";
import { Input, Label } from "@/components/ui/Input";
import { useUpdateCryptoHoldingQuantity } from "@/hooks/useCrypto";
import { useTranslation } from "@/lib/i18n";
import type { CryptoHolding } from "@/types";
interface CryptoEditModalProps {
open: boolean;
onClose: () => void;
holding: CryptoHolding | null;
}
/** Quantity only — editing never calls CoinGecko (see
* services/crypto_service.py's update_holding_quantity): the value is
* recomputed from the last known price instead. */
export function CryptoEditModal({ open, onClose, holding }: CryptoEditModalProps) {
const { t } = useTranslation();
const updateQuantity = useUpdateCryptoHoldingQuantity();
const [quantity, setQuantity] = useState("");
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open || !holding) return;
setQuantity(holding.quantity);
setError(null);
}, [open, holding]);
async function handleSubmit(event: FormEvent) {
event.preventDefault();
if (!holding) return;
setError(null);
try {
await updateQuantity.mutateAsync({ assetId: holding.asset_id, quantity });
onClose();
} catch {
setError(t("crypto.form.saveError"));
}
}
if (!holding) return null;
return (
<Dialog open={open} onClose={onClose} title={t("crypto.form.editTitle", { name: holding.name })}>
<form onSubmit={handleSubmit} className="space-y-3">
<div>
<Label htmlFor="crypto-edit-quantity">{t("crypto.form.quantityLabel")}</Label>
<Input
id="crypto-edit-quantity"
type="number"
step="any"
min="0"
required
autoFocus
value={quantity}
onChange={(event) => setQuantity(event.target.value)}
/>
</div>
{error && <p className="text-sm text-danger">{error}</p>}
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="ghost" onClick={onClose}>
{t("common.cancel")}
</Button>
<Button type="submit" disabled={updateQuantity.isPending}>
{updateQuantity.isPending ? t("common.saving") : t("common.save")}
</Button>
</div>
</form>
</Dialog>
);
}

View File

@@ -1,64 +0,0 @@
import { Bitcoin, Pencil, Trash2 } from "lucide-react";
import { formatCurrency } from "@/lib/format";
import { useTranslation } from "@/lib/i18n";
import type { CryptoHolding } from "@/types";
interface CryptoHoldingsListProps {
items: CryptoHolding[];
onEdit: (holding: CryptoHolding) => void;
onDelete: (holding: CryptoHolding) => void;
}
export function CryptoHoldingsList({ items, onEdit, onDelete }: CryptoHoldingsListProps) {
const { t } = useTranslation();
if (items.length === 0) {
return <p className="py-10 text-center text-sm text-text-muted">{t("crypto.empty")}</p>;
}
return (
<ul className="divide-y divide-gridline">
{items.map((holding) => (
<li key={holding.asset_id} className="flex items-center gap-3 py-3">
{holding.thumb_url ? (
<img src={holding.thumb_url} alt="" className="h-9 w-9 shrink-0 rounded-full" />
) : (
<span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-full bg-surface-2">
<Bitcoin size={16} className="text-text-secondary" />
</span>
)}
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-text-primary">{holding.name}</span>
<span className="block truncate text-xs text-text-muted">
{Number(holding.quantity)} {holding.symbol}
{holding.unit_price !== null && ` · ${formatCurrency(holding.unit_price)}`}
</span>
</span>
<span className="shrink-0 text-right">
<span className="block text-sm font-medium tabular-nums text-text-primary">
{holding.value !== null ? formatCurrency(holding.value) : t("crypto.pendingPrice")}
</span>
</span>
<span className="flex shrink-0 gap-1">
<button
type="button"
aria-label={t("common.edit")}
onClick={() => onEdit(holding)}
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
>
<Pencil size={15} />
</button>
<button
type="button"
aria-label={t("common.delete")}
onClick={() => onDelete(holding)}
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
>
<Trash2 size={15} />
</button>
</span>
</li>
))}
</ul>
);
}

View File

@@ -0,0 +1,151 @@
import { Bitcoin, History, Plus, Trash2 } from "lucide-react";
import { formatCurrency } from "@/lib/format";
import { useTranslation } from "@/lib/i18n";
import type { CryptoHolding } from "@/types";
interface CryptoHoldingsTableProps {
items: CryptoHolding[];
onTrade: (holding: CryptoHolding) => void;
onViewHistory: (holding: CryptoHolding) => void;
onDelete: (holding: CryptoHolding) => void;
}
function PercentCell({ value }: { value: string | null }) {
if (value === null) return <span className="text-text-muted">—</span>;
const num = Number(value);
const color = num > 0 ? "var(--success)" : num < 0 ? "var(--danger)" : "var(--text-muted)";
return (
<span className="tabular-nums" style={{ color }}>
{num > 0 ? "+" : ""}
{num.toFixed(2)}%
</span>
);
}
export function CryptoHoldingsTable({ items, onTrade, onViewHistory, onDelete }: CryptoHoldingsTableProps) {
const { t } = useTranslation();
if (items.length === 0) {
return <p className="py-10 text-center text-sm text-text-muted">{t("crypto.empty")}</p>;
}
return (
<div className="overflow-x-auto">
<table className="w-full min-w-[860px] text-sm">
<thead>
<tr className="border-b border-border text-left text-xs text-text-muted">
<th className="py-2 pr-3 font-medium">{t("crypto.table.name")}</th>
<th className="py-2 pr-3 text-right font-medium">{t("crypto.table.price")}</th>
<th className="py-2 pr-3 text-right font-medium">{t("crypto.table.change1h")}</th>
<th className="py-2 pr-3 text-right font-medium">{t("crypto.table.change24h")}</th>
<th className="py-2 pr-3 text-right font-medium">{t("crypto.table.change7d")}</th>
<th className="py-2 pr-3 text-right font-medium">{t("crypto.table.holdings")}</th>
<th className="py-2 pr-3 text-right font-medium">{t("crypto.table.avgBuyPrice")}</th>
<th className="py-2 pr-3 text-right font-medium">{t("crypto.table.profitLoss")}</th>
<th className="py-2 pl-3 text-right font-medium">{t("crypto.table.actions")}</th>
</tr>
</thead>
<tbody className="divide-y divide-gridline">
{items.map((holding) => {
const profitColor =
holding.profit_loss === null
? undefined
: Number(holding.profit_loss) > 0
? "var(--success)"
: Number(holding.profit_loss) < 0
? "var(--danger)"
: "var(--text-muted)";
const sign = holding.profit_loss !== null && Number(holding.profit_loss) > 0 ? "+" : "";
return (
<tr key={holding.asset_id}>
<td className="py-3 pr-3">
<div className="flex items-center gap-2.5">
{holding.thumb_url ? (
<img src={holding.thumb_url} 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 bg-surface-2">
<Bitcoin size={14} className="text-text-secondary" />
</span>
)}
<span className="min-w-0">
<span className="block truncate text-sm font-medium text-text-primary">{holding.name}</span>
<span className="block text-xs text-text-muted">{holding.symbol}</span>
</span>
</div>
</td>
<td className="py-3 pr-3 text-right tabular-nums text-text-primary">
{holding.current_price !== null ? formatCurrency(holding.current_price) : t("crypto.pendingPrice")}
</td>
<td className="py-3 pr-3 text-right">
<PercentCell value={holding.price_change_1h} />
</td>
<td className="py-3 pr-3 text-right">
<PercentCell value={holding.price_change_24h} />
</td>
<td className="py-3 pr-3 text-right">
<PercentCell value={holding.price_change_7d} />
</td>
<td className="py-3 pr-3 text-right">
<span className="block tabular-nums text-text-primary">
{holding.value !== null ? formatCurrency(holding.value) : t("crypto.pendingPrice")}
</span>
<span className="block text-xs tabular-nums text-text-muted">
{Number(holding.quantity)} {holding.symbol}
</span>
</td>
<td className="py-3 pr-3 text-right tabular-nums text-text-primary">
{holding.avg_buy_price !== null ? formatCurrency(holding.avg_buy_price) : "—"}
</td>
<td className="py-3 pr-3 text-right">
{holding.profit_loss !== null && holding.profit_loss_percent !== null ? (
<>
<span className="block tabular-nums" style={{ color: profitColor }}>
{sign}
{formatCurrency(holding.profit_loss)}
</span>
<span className="block text-xs tabular-nums" style={{ color: profitColor }}>
{sign}
{holding.profit_loss_percent.toFixed(2)}%
</span>
</>
) : (
<span className="text-text-muted">—</span>
)}
</td>
<td className="py-3 pl-3">
<div className="flex justify-end gap-1">
<button
type="button"
aria-label={t("crypto.form.tradeButton")}
onClick={() => onTrade(holding)}
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
>
<Plus size={15} />
</button>
<button
type="button"
aria-label={t("crypto.history.viewButton")}
onClick={() => onViewHistory(holding)}
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-text-primary"
>
<History size={15} />
</button>
<button
type="button"
aria-label={t("common.delete")}
onClick={() => onDelete(holding)}
className="rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
>
<Trash2 size={15} />
</button>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}

View File

@@ -0,0 +1,69 @@
import { Trash2 } from "lucide-react";
import { Dialog } from "@/components/ui/Dialog";
import { useCryptoTransactions, useDeleteCryptoTransaction } from "@/hooks/useCrypto";
import { formatCurrency, formatTransactionDate } from "@/lib/format";
import { useTranslation } from "@/lib/i18n";
import type { CryptoHolding } from "@/types";
interface CryptoTransactionHistoryModalProps {
open: boolean;
onClose: () => void;
holding: CryptoHolding | null;
}
export function CryptoTransactionHistoryModal({ open, onClose, holding }: CryptoTransactionHistoryModalProps) {
const { t } = useTranslation();
const { data: transactions, isLoading } = useCryptoTransactions(holding ? holding.asset_id : null);
const deleteTransaction = useDeleteCryptoTransaction();
if (!holding) return null;
function handleDelete(transactionId: number) {
if (window.confirm(t("crypto.history.confirmDelete"))) {
deleteTransaction.mutate(transactionId);
}
}
return (
<Dialog open={open} onClose={onClose} title={t("crypto.history.title", { name: holding.name })}>
{isLoading ? (
<p className="py-6 text-center text-sm text-text-muted">{t("common.loading")}</p>
) : !transactions || transactions.length === 0 ? (
<p className="py-6 text-center text-sm text-text-muted">{t("crypto.history.empty")}</p>
) : (
<ul className="max-h-96 divide-y divide-gridline overflow-y-auto">
{transactions.map((tx) => (
<li key={tx.id} className="flex items-center gap-3 py-2.5">
<span
className="shrink-0 rounded px-1.5 py-0.5 text-xs font-medium"
style={{
color: tx.type === "buy" ? "var(--success)" : "var(--danger)",
backgroundColor: tx.type === "buy" ? "color-mix(in srgb, var(--success) 12%, transparent)" : "color-mix(in srgb, var(--danger) 12%, transparent)",
}}
>
{tx.type === "buy" ? t("crypto.form.buy") : t("crypto.form.sell")}
</span>
<span className="min-w-0 flex-1">
<span className="block text-sm text-text-primary">
{Number(tx.quantity)} {holding.symbol} · {formatCurrency(tx.price_per_unit)}
</span>
<span className="block text-xs text-text-muted">
{formatTransactionDate(tx.date, true)}
{tx.note && ` · ${tx.note}`}
</span>
</span>
<button
type="button"
aria-label={t("common.delete")}
onClick={() => handleDelete(tx.id)}
className="shrink-0 rounded-md p-1.5 text-text-muted hover:bg-surface-2 hover:text-danger"
>
<Trash2 size={15} />
</button>
</li>
))}
</ul>
)}
</Dialog>
);
}

View File

@@ -0,0 +1,138 @@
import { type FormEvent, useEffect, useState } from "react";
import { ApiError } from "@/api/client";
import { Button } from "@/components/ui/Button";
import { Dialog } from "@/components/ui/Dialog";
import { Input, Label } from "@/components/ui/Input";
import { useAddCryptoTransaction } from "@/hooks/useCrypto";
import { useTranslation } from "@/lib/i18n";
import { cn } from "@/lib/utils";
import type { CryptoHolding, CryptoTransactionType } from "@/types";
interface CryptoTransactionModalProps {
open: boolean;
onClose: () => void;
holding: CryptoHolding | null;
}
/** Buy more of, or sell some of, a coin already being tracked — the "+"
* action on the holdings table. Never calls CoinGecko (see
* services/crypto_service.py's add_transaction): value is recomputed from
* the last cached price. */
export function CryptoTransactionModal({ open, onClose, holding }: CryptoTransactionModalProps) {
const { t } = useTranslation();
const addTransaction = useAddCryptoTransaction();
const [type, setType] = useState<CryptoTransactionType>("buy");
const [quantity, setQuantity] = useState("");
const [pricePerUnit, setPricePerUnit] = useState("");
const [date, setDate] = useState(() => new Date().toISOString().slice(0, 10));
const [note, setNote] = useState("");
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
setType("buy");
setQuantity("");
setPricePerUnit("");
setDate(new Date().toISOString().slice(0, 10));
setNote("");
setError(null);
}, [open, holding]);
async function handleSubmit(event: FormEvent) {
event.preventDefault();
if (!holding) return;
setError(null);
try {
await addTransaction.mutateAsync({
assetId: holding.asset_id,
input: { type, quantity, price_per_unit: pricePerUnit, date, note: note || null },
});
onClose();
} catch (err) {
setError(
err instanceof ApiError && err.status === 400 ? t("crypto.form.errorSellTooMuch") : t("crypto.form.saveError")
);
}
}
if (!holding) return null;
return (
<Dialog open={open} onClose={onClose} title={t("crypto.form.tradeTitle", { name: holding.name })}>
<form onSubmit={handleSubmit} className="space-y-3">
<div className="grid grid-cols-2 gap-2">
<button
type="button"
onClick={() => setType("buy")}
className={cn(
"rounded-lg border px-3 py-2 text-sm font-medium transition-colors",
type === "buy" ? "border-success bg-success/10 text-success" : "border-border text-text-secondary"
)}
>
{t("crypto.form.buy")}
</button>
<button
type="button"
onClick={() => setType("sell")}
className={cn(
"rounded-lg border px-3 py-2 text-sm font-medium transition-colors",
type === "sell" ? "border-danger bg-danger/10 text-danger" : "border-border text-text-secondary"
)}
>
{t("crypto.form.sell")}
</button>
</div>
<div className="grid grid-cols-2 gap-3">
<div>
<Label htmlFor="tx-quantity">{t("crypto.form.quantityLabel")}</Label>
<Input
id="tx-quantity"
type="number"
step="any"
min="0"
required
autoFocus
value={quantity}
onChange={(event) => setQuantity(event.target.value)}
/>
</div>
<div>
<Label htmlFor="tx-price">{t("crypto.form.pricePerUnitLabel")}</Label>
<Input
id="tx-price"
type="number"
step="any"
min="0"
required
value={pricePerUnit}
onChange={(event) => setPricePerUnit(event.target.value)}
/>
</div>
</div>
<div>
<Label htmlFor="tx-date">{t("crypto.form.dateLabel")}</Label>
<Input id="tx-date" type="date" required value={date} onChange={(event) => setDate(event.target.value)} />
</div>
<div>
<Label htmlFor="tx-note">{t("crypto.form.noteLabel")}</Label>
<Input id="tx-note" value={note} onChange={(event) => setNote(event.target.value)} />
</div>
{error && <p className="text-sm text-danger">{error}</p>}
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="ghost" onClick={onClose}>
{t("common.cancel")}
</Button>
<Button type="submit" disabled={addTransaction.isPending}>
{addTransaction.isPending ? t("common.saving") : t("common.save")}
</Button>
</div>
</form>
</Dialog>
);
}