Files
aurum/backend/app/api/routes/crypto.py
ZProger e8cd536584 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
2026-08-30 04:25:03 +03:00

71 lines
2.7 KiB
Python

from fastapi import APIRouter, Depends, Query
from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_session
from app.schemas.crypto import (
CryptoHoldingCreate,
CryptoHoldingRead,
CryptoSearchResult,
CryptoSyncResult,
CryptoTransactionCreate,
CryptoTransactionRead,
)
from app.services.crypto_service import (
add_transaction,
create_holding,
delete_transaction,
list_transactions,
refresh_prices,
search_coins,
)
router = APIRouter(prefix="/crypto", tags=["crypto"])
@router.get("/holdings", response_model=CryptoSyncResult)
async def read_holdings(session: AsyncSession = Depends(get_session)) -> CryptoSyncResult:
"""Opening the Crypto tab lands here — this is also where the lazy
once-a-day auto-refresh happens (see services/crypto_service.py):
prices only actually get re-fetched from CoinGecko if 24h have passed
since the last sync, otherwise this just reads the current cache."""
return await refresh_prices(session, force=False)
@router.post("/refresh", response_model=CryptoSyncResult)
async def refresh_holdings(session: AsyncSession = Depends(get_session)) -> CryptoSyncResult:
"""The "Refresh prices" button — always hits CoinGecko regardless of
the once-a-day window."""
return await refresh_prices(session, force=True)
@router.post("/holdings", response_model=CryptoHoldingRead, status_code=201)
async def create_holding_route(
payload: CryptoHoldingCreate, session: AsyncSession = Depends(get_session)
) -> CryptoHoldingRead:
return await create_holding(session, payload)
@router.post("/holdings/{asset_id}/transactions", response_model=CryptoHoldingRead, status_code=201)
async def add_transaction_route(
asset_id: int, payload: CryptoTransactionCreate, session: AsyncSession = Depends(get_session)
) -> CryptoHoldingRead:
"""Buy more of, or sell some of, a coin already being tracked."""
return await add_transaction(session, asset_id, payload)
@router.get("/holdings/{asset_id}/transactions", response_model=list[CryptoTransactionRead])
async def list_transactions_route(
asset_id: int, session: AsyncSession = Depends(get_session)
) -> list[CryptoTransactionRead]:
return await list_transactions(session, asset_id)
@router.delete("/transactions/{transaction_id}", status_code=204)
async def delete_transaction_route(transaction_id: int, session: AsyncSession = Depends(get_session)) -> None:
await delete_transaction(session, transaction_id)
@router.get("/search", response_model=list[CryptoSearchResult])
async def search_coins_route(q: str = Query(min_length=1, max_length=100)) -> list[CryptoSearchResult]:
return await search_coins(q)