Asset Catalog Model Implementation (BAT-001): - Introduce assets table with UUID PK, symbol UNIQUE, markets TEXT[] array - Define MarketCode enum (KRX, NXT, SOR, NASDAQ, NYSE, UPBIT, BITHUMB) - Add Asset domain model with catalog properties - Implement asset CRUD protocols in portfolio_repository - Add PostgreSQL asset CRUD operations with GIN index on markets Portfolio Model Refactoring (REQ-011): - Add portfolios.asset_id UUID FK to assets(asset_id) ON DELETE RESTRICT - Remove portfolios.symbol and portfolios.market columns - Update Portfolio domain model to reference asset_id instead of symbol/market - Refactor all portfolio queries to JOIN assets catalog - Update all repository methods to use asset references Data Migration (REQ-014): - Create 20260519_0017 Alembic revision for assets table creation - Create 20260519_0018 Alembic revision for atomic data migration: * Extract unique symbol combinations from portfolios * Aggregate markets using ARRAY_AGG(DISTINCT market) * Populate assets catalog with extracted data * Update portfolios.asset_id to reference new assets * Remove legacy symbol/market columns in single transaction - Implement migration with rollback support Requirements Approved (REQ-001~008): - REQ-001~008 transitioned from Proposed to Approved - Complete tag model requirement set with implementation readiness New Requirements Approved (REQ-009~015): - REQ-009: assets table schema (approved, included in BAT-001) - REQ-010: admin asset catalog CRUD (approved, future BAT-002) - REQ-011: portfolios asset_id FK (approved, included in BAT-001) - REQ-012: portfolio create catalog validation (approved, future BAT-002) - REQ-013: GET /v1/assets token branching (approved, future BAT-002) - REQ-014: portfolios data migration (approved, included in BAT-001) - REQ-015: asset catalog baseline docs (approved) Code Changes: - app/domain/models.py: Add Asset model, MarketCode enum, Portfolio asset_id FK - app/repositories/portfolio_repository.py: Define asset CRUD protocol - app/repositories/postgres.py: Implement asset operations with full CRUD - app/api/v1_assets.py: Remove symbol/market direct references - app/cli/commands/portfolio.py: Update portfolio commands for asset references - app/schemas/portfolio.py: Update portfolio schema with asset_id - All portfolio operations throughout codebase: Use asset references Testing: - Add test_asset_catalog.py for asset CRUD operations - Verify REQ-009 AC-1~5 (asset catalog creation, lookup, uniqueness) - Verify REQ-011 AC-1~5 (FK constraint, portfolio asset reference) - Verify REQ-014 AC-1~6 (migration atomicity, data correctness, rollback) - Update existing tests for asset model usage Documentation: - Create BAT-001 batch documents (planning, design, implementation, verification) - Update dcy-001 with implementation details and confirmed architecture - Add 8 new requirement documents (REQ-009~015) - Update docs/discovery/index.md with batch entry Impact: - Database: assets catalog table, portfolios refactored to reference assets - Migration: 2 new Alembic revisions (0017 assets, 0018 portfolio migration) - API: Symbol/market now accessed through asset references - CLI: Portfolio commands require asset reference pattern - All existing portfolio data preserved and correctly migrated
105 lines
3.6 KiB
Python
105 lines
3.6 KiB
Python
"""GET /v1/assets — service-token authenticated asset list endpoint."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import logging
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
|
|
|
from app.core.auth import AuthContext, 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
|
|
|
|
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 {}
|
|
try:
|
|
parsed = json.loads(strategy_set_config)
|
|
return parsed if isinstance(parsed, dict) else {}
|
|
except (json.JSONDecodeError, TypeError):
|
|
return {}
|
|
|
|
|
|
@router.get("/assets", response_model=AssetsResponse)
|
|
def list_assets(
|
|
status_filter: str | None = Query(default=None, alias="status"),
|
|
auth: AuthContext = Depends(_require_service_token),
|
|
) -> AssetsResponse:
|
|
if auth.daemon_id is None:
|
|
raise HTTPException(
|
|
status_code=status.HTTP_403_FORBIDDEN,
|
|
detail="daemon_id not assigned to this token",
|
|
)
|
|
|
|
from app.core.config import get_settings
|
|
|
|
settings = get_settings()
|
|
repo = get_portfolio_repository_from_settings(settings)
|
|
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,
|
|
)
|
|
)
|
|
finally:
|
|
if callable(getattr(type(repo), "close", None)):
|
|
repo.close()
|
|
|
|
return AssetsResponse(assets=items, total=len(items))
|