- 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>
190 lines
6.4 KiB
Python
190 lines
6.4 KiB
Python
"""v1 asset endpoints — admin asset catalog CRUD + tag apply/remove (REQ-010, REQ-005)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
|
|
from app.core.auth import AuthContext, require_admin
|
|
from app.repositories.factory import get_portfolio_repository_from_settings
|
|
from app.schemas.v1 import (
|
|
AssetCatalogCreateRequest,
|
|
AssetCatalogListResponse,
|
|
AssetCatalogResponse,
|
|
AssetCatalogUpdateRequest,
|
|
TagApplyRequest,
|
|
TagApplyResponse,
|
|
)
|
|
|
|
logger = logging.getLogger(__name__)
|
|
router = APIRouter(prefix="/v1", tags=["v1"])
|
|
|
|
|
|
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,
|
|
)
|
|
|
|
|
|
_CATALOG_STATUS_FILTERS = {"active", "inactive", "all"}
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GET /v1/assets — admin asset catalog list (REQ-010 CHG-20260521-02)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
@router.get("/assets", response_model=AssetCatalogListResponse)
|
|
def list_catalog_assets(
|
|
status_filter: str = Query(default="active", alias="status"),
|
|
market: str | None = Query(default=None),
|
|
auth: AuthContext = Depends(require_admin),
|
|
) -> AssetCatalogListResponse:
|
|
if status_filter not in _CATALOG_STATUS_FILTERS:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
|
detail=f"status must be one of {sorted(_CATALOG_STATUS_FILTERS)}",
|
|
)
|
|
|
|
repo = _get_repo()
|
|
try:
|
|
assets = repo.list_assets()
|
|
finally:
|
|
if callable(getattr(type(repo), "close", None)):
|
|
repo.close()
|
|
|
|
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))
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# 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)
|