feat: asset catalog API, 태그 DB 기초, 마이그레이션 3건 및 도메인/테스트 갱신 (2026-05-19)
This commit is contained in:
+185
-63
@@ -1,4 +1,4 @@
|
||||
"""GET /v1/assets — service-token authenticated asset list endpoint."""
|
||||
"""v1 asset endpoints — portfolio list (service/user/admin) and admin catalog CRUD."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,24 +7,22 @@ import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
|
||||
from app.core.auth import AuthContext, require_read
|
||||
from app.core.auth import AuthContext, require_admin, require_read
|
||||
from app.repositories.factory import get_portfolio_repository_from_settings
|
||||
from app.repositories.portfolio_repository import PortfolioRepository
|
||||
from app.schemas.v1 import AssetItem, AssetsResponse
|
||||
from app.schemas.v1 import (
|
||||
AssetCatalogCreateRequest,
|
||||
AssetCatalogResponse,
|
||||
AssetCatalogUpdateRequest,
|
||||
AssetItem,
|
||||
AssetsResponse,
|
||||
TagRefItem,
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/v1", tags=["v1"])
|
||||
|
||||
|
||||
def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthContext:
|
||||
if auth.token_source != "db" or auth.token_type != "service":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Service token required",
|
||||
)
|
||||
return auth
|
||||
|
||||
|
||||
def _parse_strategy_params(strategy_set_config: str | None) -> dict:
|
||||
if not strategy_set_config:
|
||||
return {}
|
||||
@@ -35,70 +33,194 @@ def _parse_strategy_params(strategy_set_config: str | None) -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def _get_repo(settings=None):
|
||||
from app.core.config import get_settings
|
||||
return get_portfolio_repository_from_settings(settings or get_settings())
|
||||
|
||||
|
||||
def _asset_response(asset) -> AssetCatalogResponse:
|
||||
return AssetCatalogResponse(
|
||||
asset_id=asset.asset_id,
|
||||
symbol=asset.symbol,
|
||||
markets=asset.markets,
|
||||
display_name=asset.display_name,
|
||||
status=asset.status,
|
||||
created_at=asset.created_at,
|
||||
updated_at=asset.updated_at,
|
||||
)
|
||||
|
||||
|
||||
def _build_tag_refs(tag_ids: list[str] | None, active_map: dict[str, bool]) -> list[TagRefItem] | None:
|
||||
if not tag_ids:
|
||||
return None
|
||||
return [
|
||||
TagRefItem(tag_id=tid, archived=not active_map.get(tid, True))
|
||||
for tid in tag_ids
|
||||
]
|
||||
|
||||
|
||||
def _build_asset_items(portfolios, status_filter: str | None, repo) -> list[AssetItem]:
|
||||
# Batch-fetch tag active status for all tag_ids across all portfolios
|
||||
all_tag_ids: list[str] = [
|
||||
tid for p in portfolios for tid in (p.tag_ids or [])
|
||||
]
|
||||
tag_active_map: dict[str, bool] = {}
|
||||
if all_tag_ids:
|
||||
try:
|
||||
tags_by_id = repo.get_tags_by_ids(all_tag_ids)
|
||||
tag_active_map = {tid: t.is_active for tid, t in tags_by_id.items()}
|
||||
except Exception:
|
||||
logger.warning("tag active status lookup failed")
|
||||
|
||||
items = []
|
||||
for p in portfolios:
|
||||
if status_filter is not None and p.status != status_filter:
|
||||
continue
|
||||
strategy_params: dict = {}
|
||||
strategy_type: str | None = None
|
||||
if p.active_strategy_id:
|
||||
try:
|
||||
ss = repo.get_strategy_set(p.active_strategy_id)
|
||||
if ss is not None:
|
||||
strategy_params = _parse_strategy_params(ss.config)
|
||||
strategy_type = ss.name
|
||||
except Exception:
|
||||
logger.warning("strategy_set lookup failed for %s", p.active_strategy_id)
|
||||
items.append(
|
||||
AssetItem(
|
||||
asset_id=p.portfolio_id,
|
||||
symbol=p.symbol,
|
||||
status=p.status,
|
||||
cash=p.cash_balance,
|
||||
quantity=p.asset_quantity,
|
||||
broker_type=p.broker,
|
||||
strategy_id=p.active_strategy_id,
|
||||
strategy_type=strategy_type,
|
||||
strategy_params=strategy_params,
|
||||
updated_at=p.updated_at,
|
||||
name=p.name,
|
||||
price=p.price,
|
||||
profit_buffer=p.profit_buffer,
|
||||
tags=p.tags,
|
||||
tag_ids=_build_tag_refs(p.tag_ids, tag_active_map),
|
||||
owner_user_id=p.owner_user_id,
|
||||
created_at=p.created_at,
|
||||
last_trade_at=p.last_trade_at,
|
||||
)
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# GET /v1/assets — token-type-branched portfolio list (REQ-013)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.get("/assets", response_model=AssetsResponse)
|
||||
def list_assets(
|
||||
status_filter: str | None = Query(default=None, alias="status"),
|
||||
auth: AuthContext = Depends(_require_service_token),
|
||||
market: str | None = Query(default=None),
|
||||
user_id: str | None = Query(default=None),
|
||||
auth: AuthContext = Depends(require_read),
|
||||
) -> AssetsResponse:
|
||||
if auth.daemon_id is None:
|
||||
if auth.token_source != "db":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="daemon_id not assigned to this token",
|
||||
detail="DB token required",
|
||||
)
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
repo = get_portfolio_repository_from_settings(settings)
|
||||
repo = _get_repo()
|
||||
try:
|
||||
portfolios = repo.list_portfolios_with_strategies(
|
||||
owner_user_id=auth.user_id,
|
||||
include_disabled=False,
|
||||
managed_by_daemon_id=auth.daemon_id,
|
||||
)
|
||||
|
||||
# Fetch strategy_params per portfolio
|
||||
items = []
|
||||
for p in portfolios:
|
||||
# Optional status filter
|
||||
if status_filter is not None and p.status != status_filter:
|
||||
continue
|
||||
|
||||
strategy_params: dict = {}
|
||||
strategy_type: str | None = None
|
||||
if p.active_strategy_id:
|
||||
try:
|
||||
ss = repo.get_strategy_set(p.active_strategy_id)
|
||||
if ss is not None:
|
||||
strategy_params = _parse_strategy_params(ss.config)
|
||||
strategy_type = ss.name
|
||||
except Exception:
|
||||
logger.warning("strategy_set lookup failed for %s", p.active_strategy_id)
|
||||
strategy_params = {}
|
||||
|
||||
items.append(
|
||||
AssetItem(
|
||||
asset_id=p.portfolio_id,
|
||||
symbol=p.symbol,
|
||||
status=p.status,
|
||||
cash=p.cash_balance,
|
||||
quantity=p.asset_quantity,
|
||||
broker_type=p.broker,
|
||||
strategy_id=p.active_strategy_id,
|
||||
strategy_type=strategy_type,
|
||||
strategy_params=strategy_params,
|
||||
updated_at=p.updated_at,
|
||||
name=p.name,
|
||||
price=p.price,
|
||||
profit_buffer=p.profit_buffer,
|
||||
tags=p.tags,
|
||||
owner_user_id=p.owner_user_id,
|
||||
created_at=p.created_at,
|
||||
last_trade_at=p.last_trade_at,
|
||||
if auth.token_type == "service":
|
||||
if auth.daemon_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="daemon_id not assigned to this token",
|
||||
)
|
||||
portfolios = repo.list_portfolios_with_strategies(
|
||||
owner_user_id=auth.user_id,
|
||||
include_disabled=False,
|
||||
managed_by_daemon_id=auth.daemon_id,
|
||||
market=market,
|
||||
)
|
||||
elif auth.token_type == "user":
|
||||
portfolios = repo.list_portfolios_with_strategies(
|
||||
owner_user_id=auth.user_id,
|
||||
include_disabled=True,
|
||||
market=market,
|
||||
)
|
||||
elif auth.token_type == "admin":
|
||||
filter_user_id = user_id if user_id is not None else auth.user_id
|
||||
portfolios = repo.list_portfolios_with_strategies(
|
||||
owner_user_id=filter_user_id,
|
||||
include_disabled=True,
|
||||
market=market,
|
||||
)
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Unsupported token type",
|
||||
)
|
||||
|
||||
items = _build_asset_items(portfolios, status_filter, repo)
|
||||
finally:
|
||||
if callable(getattr(type(repo), "close", None)):
|
||||
repo.close()
|
||||
|
||||
return AssetsResponse(assets=items, total=len(items))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Admin asset catalog CRUD (REQ-010)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@router.post("/assets", response_model=AssetCatalogResponse, status_code=201)
|
||||
def create_catalog_asset(
|
||||
body: AssetCatalogCreateRequest,
|
||||
auth: AuthContext = Depends(require_admin),
|
||||
) -> AssetCatalogResponse:
|
||||
repo = _get_repo()
|
||||
try:
|
||||
asset = repo.insert_asset(
|
||||
symbol=body.symbol,
|
||||
markets=body.markets,
|
||||
display_name=body.display_name,
|
||||
status=body.status,
|
||||
)
|
||||
finally:
|
||||
if callable(getattr(type(repo), "close", None)):
|
||||
repo.close()
|
||||
return _asset_response(asset)
|
||||
|
||||
|
||||
@router.patch("/assets/{asset_id}/deactivate", response_model=AssetCatalogResponse)
|
||||
def deactivate_catalog_asset(
|
||||
asset_id: str,
|
||||
auth: AuthContext = Depends(require_admin),
|
||||
) -> AssetCatalogResponse:
|
||||
repo = _get_repo()
|
||||
try:
|
||||
asset = repo.update_asset(asset_id, status="inactive")
|
||||
finally:
|
||||
if callable(getattr(type(repo), "close", None)):
|
||||
repo.close()
|
||||
return _asset_response(asset)
|
||||
|
||||
|
||||
@router.patch("/assets/{asset_id}", response_model=AssetCatalogResponse)
|
||||
def update_catalog_asset(
|
||||
asset_id: str,
|
||||
body: AssetCatalogUpdateRequest,
|
||||
auth: AuthContext = Depends(require_admin),
|
||||
) -> AssetCatalogResponse:
|
||||
repo = _get_repo()
|
||||
try:
|
||||
asset = repo.update_asset(
|
||||
asset_id,
|
||||
markets=body.markets,
|
||||
display_name=body.display_name,
|
||||
status=body.status,
|
||||
)
|
||||
finally:
|
||||
if callable(getattr(type(repo), "close", None)):
|
||||
repo.close()
|
||||
return _asset_response(asset)
|
||||
|
||||
Reference in New Issue
Block a user