Files
portfolio-hub/app/api/v1_assets.py
T
genichin a5b5e7a93c fix: resolve SRS conflicts from batch verification analysis (CONFLICT-1~4)
Conflict Resolutions:
- CONFLICT-1 (High): Fix REQ-006 ownership scope — implement owner_user_id filtering
  * Change app/api/v1_assets.py: owner_user_id=None → owner_user_id=auth.user_id
  * Update docs/runtime-flows.md to reflect service-token owner-scoped portfolio filtering
  * Add regression test in tests/test_v1.py for ownership boundary

- CONFLICT-2 (Medium): Transition REQ-001/002/003 to Implemented
  * REQ-001: local-db-validation-scenarios (via confirm-req-implemented bat-007)
  * REQ-002: alembic-runtime-schema-ownership (via confirm-req-implemented bat-007)
  * REQ-003: local-db-operations-runbook-and-baseline-updates (via confirm-req-implemented bat-007)
  * Update docs/srs/index.md with status transitions

- CONFLICT-3 (Low): Document REQ-012 rotate lifecycle
  * Add rotate lifecycle notes to REQ-012 (change-req req-012)
  * Clarify runtime_id change behavior and trex-basic reconnection requirements

- CONFLICT-4 (Low): Clarify REQ-005 AC-2 endpoint path
  * Change REQ-005 AC-2: 'POST /auth/tokens or equivalent' → 'POST /auth/service-tokens'
  * Update docs/srs/index.md change log with change-req entries

Documentation Updates:
- Update BAT-001 verification status with conflict resolution evidence
- Update release rel-001 with verified status confirmation
- Add change log entries for all conflict resolutions with dates and references

Testing:
- Add ownership boundary test to test_v1.py
- Verify filter works with auth.user_id context
2026-05-11 11:57:21 +00:00

99 lines
3.4 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:
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,
)
# 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,
market=p.market,
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))