"""v1 asset endpoints — portfolio list (service/user/admin) and admin catalog CRUD.""" from __future__ import annotations import json import logging from fastapi import APIRouter, Depends, HTTPException, Query, status 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 ( AssetCatalogCreateRequest, AssetCatalogResponse, AssetCatalogUpdateRequest, AssetItem, AssetsResponse, TagApplyRequest, TagApplyResponse, TagRefItem, ) logger = logging.getLogger(__name__) router = APIRouter(prefix="/v1", tags=["v1"]) def _parse_strategy_params(strategy_set_config: str | None) -> dict: if not strategy_set_config: return {} try: parsed = json.loads(strategy_set_config) return parsed if isinstance(parsed, dict) else {} except (json.JSONDecodeError, TypeError): 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"), market: str | None = Query(default=None), user_id: str | None = Query(default=None), auth: AuthContext = Depends(require_read), ) -> AssetsResponse: if auth.token_source != "db": raise HTTPException( status_code=status.HTTP_403_FORBIDDEN, detail="DB token required", ) repo = _get_repo() try: 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.post("/assets/{asset_id}/tags", response_model=TagApplyResponse) def apply_asset_tag( asset_id: str, body: TagApplyRequest, auth: AuthContext = Depends(require_admin), ) -> TagApplyResponse: if auth.token_source != "db": raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="DB token required") repo = _get_repo() try: try: repo.get(asset_id) except ValueError: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"asset을 찾을 수 없습니다: {asset_id}") tag = repo.get_tag_by_id(body.tag_id) if tag is None: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"태그를 찾을 수 없습니다: {body.tag_id}") if not tag.is_admin_tag: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="admin 생성 태그만 asset에 적용할 수 있습니다") if not tag.is_active: raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="비활성화된 태그는 적용할 수 없습니다") repo.append_portfolio_tag_id(asset_id, body.tag_id) except HTTPException: raise except ValueError as exc: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc finally: if callable(getattr(type(repo), "close", None)): repo.close() return TagApplyResponse(tag_id=body.tag_id, status="applied") @router.delete("/assets/{asset_id}/tags/{tag_id}", response_model=TagApplyResponse) def remove_asset_tag( asset_id: str, tag_id: str, auth: AuthContext = Depends(require_admin), ) -> TagApplyResponse: if auth.token_source != "db": raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="DB token required") repo = _get_repo() try: try: repo.get(asset_id) except ValueError: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f"asset을 찾을 수 없습니다: {asset_id}") repo.remove_portfolio_tag_id(asset_id, tag_id) except HTTPException: raise except ValueError as exc: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc finally: if callable(getattr(type(repo), "close", None)): repo.close() return TagApplyResponse(tag_id=tag_id, status="removed") @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)