feat: add a Crypto tab with live CoinGecko prices synced into Net Worth

Track individual coins (identity + quantity) in a dedicated tab, backed by
CoinGecko's Demo API (AURUM_COINGECKO_API_KEY). A holding is just another
Asset under the hood (asset_class=crypto) with its value written as a
regular AssetValuation — the existing Net Worth aggregation needs zero
changes to pick it up.

Prices never refresh in the background (no scheduler in this stack, same
reasoning as recurring transactions): a "Refresh prices" button forces a
sync, and GET /crypto/holdings lazily re-syncs at most once every 24h.
CoinGecko outages leave existing values untouched (error_key: "unreachable")
instead of failing the request. Backup/restore now carries CryptoHolding
rows too, so a restore doesn't silently strip a holding's coin identity.

Backend: 75/75 tests passing (9 new), including a real identity-map
staleness bug the tests caught in the raw-Core-upsert + ORM re-read pattern,
fixed via populate_existing=True.

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 03:58:04 +03:00
parent f74305f0be
commit 7e4508d1de
27 changed files with 1327 additions and 0 deletions

View File

@@ -0,0 +1,170 @@
import { type FormEvent, useEffect, useState } from "react";
import { ApiError } from "@/api/client";
import { searchCryptoCoins } from "@/api/crypto";
import { Button } from "@/components/ui/Button";
import { Dialog } from "@/components/ui/Dialog";
import { Input, Label } from "@/components/ui/Input";
import { useCreateCryptoHolding } from "@/hooks/useCrypto";
import { useTranslation } from "@/lib/i18n";
import type { CryptoSearchResult } from "@/types";
interface CryptoAddModalProps {
open: boolean;
onClose: () => void;
}
/** Two phases in one dialog: search CoinGecko for a coin, then pick one and
* enter how much of it is held. No separate multi-step wizard — unlike CSV
* import, there's nothing here worth a dedicated page for. */
export function CryptoAddModal({ open, onClose }: CryptoAddModalProps) {
const { t } = useTranslation();
const createHolding = useCreateCryptoHolding();
const [query, setQuery] = useState("");
const [results, setResults] = useState<CryptoSearchResult[]>([]);
const [searching, setSearching] = useState(false);
const [searchError, setSearchError] = useState<string | null>(null);
const [selected, setSelected] = useState<CryptoSearchResult | null>(null);
const [quantity, setQuantity] = useState("");
const [saveError, setSaveError] = useState<string | null>(null);
useEffect(() => {
if (open) return;
setQuery("");
setResults([]);
setSelected(null);
setQuantity("");
setSearchError(null);
setSaveError(null);
}, [open]);
useEffect(() => {
if (!open || selected) return;
const trimmed = query.trim();
if (trimmed.length < 2) {
setResults([]);
setSearchError(null);
return;
}
setSearching(true);
setSearchError(null);
const timer = setTimeout(async () => {
try {
setResults(await searchCryptoCoins(trimmed));
} catch (error) {
setResults([]);
setSearchError(
error instanceof ApiError && error.status === 400 ? t("crypto.search.noApiKey") : t("crypto.form.saveError")
);
} finally {
setSearching(false);
}
}, 400);
return () => clearTimeout(timer);
}, [query, open, selected, t]);
async function handleSave(event: FormEvent) {
event.preventDefault();
if (!selected) return;
setSaveError(null);
try {
await createHolding.mutateAsync({
coingecko_id: selected.coingecko_id,
symbol: selected.symbol,
name: selected.name,
thumb_url: selected.thumb_url,
quantity,
});
onClose();
} catch {
setSaveError(t("crypto.form.saveError"));
}
}
return (
<Dialog
open={open}
onClose={onClose}
title={selected ? t("crypto.form.addTitle", { name: selected.name }) : t("crypto.addButton")}
>
{!selected ? (
<div className="space-y-3">
<Input
autoFocus
placeholder={t("crypto.search.placeholder")}
value={query}
onChange={(event) => setQuery(event.target.value)}
/>
{searchError && <p className="text-sm text-danger">{searchError}</p>}
{!searchError && query.trim().length < 2 && (
<p className="text-sm text-text-muted">{t("crypto.search.hint")}</p>
)}
{searching && <p className="text-sm text-text-muted">{t("common.loading")}</p>}
{!searching && !searchError && query.trim().length >= 2 && results.length === 0 && (
<p className="text-sm text-text-muted">{t("crypto.search.empty")}</p>
)}
<ul className="max-h-72 space-y-1 overflow-y-auto">
{results.map((coin) => (
<li key={coin.coingecko_id}>
<button
type="button"
onClick={() => setSelected(coin)}
className="flex w-full items-center gap-3 rounded-lg p-2 text-left hover:bg-surface-2"
>
{coin.thumb_url ? (
<img src={coin.thumb_url} alt="" className="h-6 w-6 shrink-0 rounded-full" />
) : (
<span className="h-6 w-6 shrink-0 rounded-full bg-surface-2" />
)}
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-text-primary">{coin.name}</span>
<span className="block text-xs text-text-muted">{coin.symbol}</span>
</span>
</button>
</li>
))}
</ul>
</div>
) : (
<form onSubmit={handleSave} className="space-y-3">
<div className="flex items-center gap-3 rounded-lg bg-surface-2 p-2">
{selected.thumb_url ? (
<img src={selected.thumb_url} alt="" className="h-6 w-6 shrink-0 rounded-full" />
) : (
<span className="h-6 w-6 shrink-0 rounded-full bg-surface-1" />
)}
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-text-primary">{selected.name}</span>
<span className="block text-xs text-text-muted">{selected.symbol}</span>
</span>
</div>
<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>
{saveError && <p className="text-sm text-danger">{saveError}</p>}
<div className="flex justify-end gap-2 pt-2">
<Button type="button" variant="ghost" onClick={() => setSelected(null)}>
{t("common.back")}
</Button>
<Button type="submit" disabled={createHolding.isPending}>
{createHolding.isPending ? t("common.saving") : t("common.save")}
</Button>
</div>
</form>
)}
</Dialog>
);
}

View File

@@ -0,0 +1,75 @@
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

@@ -0,0 +1,64 @@
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>
);
}