Files
genichinandClaude Sonnet 4.6 c5288a8c42 feat(bat-019): REQ-044 GET /v1/assets require_read + REQ-045 GET /v1/daemons caller-scope
REQ-044: list_catalog_assets 의존성을 require_admin → require_read로 완화.
asset 쓰기(POST/PATCH/DELETE)는 require_admin 유지.

REQ-045: GET /v1/daemons 신규 엔드포인트 — caller 소유 데몬만 반환(require_read).
user_id=None(env 토큰)은 빈 목록 200. DaemonResponse/DaemonListResponse 스키마 추가.

기존 테스트(test_v1.py, test_asset_catalog.py, test_daemon_assignment.py, test_tags_master.py)
REQ-044 권한 완화에 맞게 업데이트. test_v1_daemons.py 신규 추가(13 케이스).

pytest 472 passed, 0 failed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VHtM5Ws1HKCKQ4JGi6GRb5
2026-06-27 10:36:04 +09:00

229 lines
8.1 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, require_read
from app.repositories.factory import get_portfolio_repository_from_settings
from app.schemas.v1 import (
AssetCatalogCreateRequest,
AssetCatalogListResponse,
AssetCatalogResponse,
AssetCatalogUpdateRequest,
TagApplyRequest,
TagApplyResponse,
TagRefItem,
)
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 _build_tag_refs(tag_ids: list[str], tag_active_map: dict[str, bool]) -> list[TagRefItem]:
"""Convert raw tag_id list into TagRefItem array with archived flag synthesized.
tag_ids not present in tag_active_map are surfaced as archived=True so the array
is never silently pruned (REQ-002 Intent: "조용히 제거하지 않고 archived 상태로 반환").
"""
refs: list[TagRefItem] = []
for tid in tag_ids:
active = tag_active_map.get(tid, False)
refs.append(TagRefItem(tag_id=tid, archived=not active))
return refs
def _asset_response(asset, tag_active_map: dict[str, bool] | None = None) -> AssetCatalogResponse:
tag_ids = getattr(asset, "tag_ids", []) or []
if tag_active_map is None and tag_ids:
# 단일 응답 경로: 필요한 tag_ids만 1회 조회
repo = _get_repo()
try:
tags = repo.get_tags_by_ids(tag_ids)
finally:
if callable(getattr(type(repo), "close", None)):
repo.close()
tag_active_map = {tid: t.is_active for tid, t in tags.items()}
elif tag_active_map is None:
tag_active_map = {}
return AssetCatalogResponse(
asset_id=asset.asset_id,
symbol=asset.symbol,
markets=asset.markets,
display_name=asset.display_name,
status=asset.status,
tag_ids=_build_tag_refs(tag_ids, tag_active_map),
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_read),
) -> 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()
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 [])]
all_tag_ids: list[str] = []
seen: set[str] = set()
for a in assets:
for tid in (getattr(a, "tag_ids", []) or []):
if tid not in seen:
seen.add(tid)
all_tag_ids.append(tid)
tag_active_map: dict[str, bool] = {}
if all_tag_ids:
tags = repo.get_tags_by_ids(all_tag_ids)
tag_active_map = {tid: t.is_active for tid, t in tags.items()}
finally:
if callable(getattr(type(repo), "close", None)):
repo.close()
items = [_asset_response(a, tag_active_map) 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_asset_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_asset_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)