feat: REQ-001~018 Implemented 전환, REQ-010 GET /v1/assets admin catalog 재정의, REL-001 draft

- confirm-req-implemented: REQ-001~018 (17건, REQ-013 제외) Approved → Implemented
  - BAT-001(REQ-009/011/014), BAT-002(REQ-010/012/015), BAT-003(REQ-001/002/003/006)
  - BAT-004(REQ-004/005), BAT-005(REQ-007/008), BAT-006(REQ-016/017/018)
  - CHG-20260521-01 entry 각 REQ에 추가; SRS index Recent Change Log 갱신

- REQ-010 CHG-20260521-02: GET /v1/assets admin catalog 전용 재정의
  - 기존 token_type 분기 portfolio 조회 코드 제거, admin permission + list_assets() 호출로 대체
  - AssetCatalogListResponse 스키마 추가 (items/total)
  - REQ-010 Status: Implemented → Approved (재검증 필요)
  - 테스트 343건 전체 통과: service/user token 403, admin token 200 + catalog schema 검증

- migration 보강: portfolios_asset_migration market 컬럼 부재 fallback,
  portfolio_tags 빈 테이블 early-return, service_token index fix autocommit_block 정리

- docs/releases/rel-001: REL-001 draft 추가 (BAT-001~011 포함)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
2026-05-21 10:17:39 +00:00
co-authored by Claude Sonnet 4.6
parent 4bf6b554a7
commit 6add0ade29
28 changed files with 894 additions and 393 deletions
+21 -119
View File
@@ -1,40 +1,26 @@
"""v1 asset endpoints — portfolio list (service/user/admin) and admin catalog CRUD."""
"""v1 asset endpoints — admin asset catalog CRUD + tag apply/remove (REQ-010, REQ-005)."""
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.core.auth import AuthContext, require_admin
from app.repositories.factory import get_portfolio_repository_from_settings
from app.repositories.portfolio_repository import PortfolioRepository
from app.schemas.v1 import (
AssetCatalogCreateRequest,
AssetCatalogListResponse,
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())
@@ -52,123 +38,39 @@ def _asset_response(asset) -> AssetCatalogResponse:
)
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
_CATALOG_STATUS_FILTERS = {"active", "inactive", "all"}
# ---------------------------------------------------------------------------
# GET /v1/assets — token-type-branched portfolio list (REQ-013)
# GET /v1/assets — admin asset catalog list (REQ-010 CHG-20260521-02)
# ---------------------------------------------------------------------------
@router.get("/assets", response_model=AssetsResponse)
def list_assets(
status_filter: str | None = Query(default=None, alias="status"),
@router.get("/assets", response_model=AssetCatalogListResponse)
def list_catalog_assets(
status_filter: str = Query(default="active", 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":
auth: AuthContext = Depends(require_admin),
) -> AssetCatalogListResponse:
if status_filter not in _CATALOG_STATUS_FILTERS:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="DB token required",
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"status must be one of {sorted(_CATALOG_STATUS_FILTERS)}",
)
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)
assets = repo.list_assets()
finally:
if callable(getattr(type(repo), "close", None)):
repo.close()
return AssetsResponse(assets=items, total=len(items))
if status_filter != "all":
assets = [a for a in assets if a.status == status_filter]
if market is not None:
assets = [a for a in assets if market in (a.markets or [])]
items = [_asset_response(a) for a in assets]
return AssetCatalogListResponse(items=items, total=len(items))
# ---------------------------------------------------------------------------