feat(REQ-005): implement TrEx Basic V1 API contract with auth, assets, ledger, and user endpoints
- Add V1 API routes for assets, ledger, and user info with complete CRUD operations - Implement authentication scopes and request validation via auth_routes.py - Extend schemas with V1-specific models for accounts, holdings, and positions - Add database queries and aggregations for P&L, performance, and account data - Include comprehensive test coverage for all V1 endpoints and integration flows - Update batch and release documentation with implementation and verification evidence - Sync project structure and runtime flows per V1 API contract requirements Closes implementation phase of BAT-001 (TrEx Basic V1 API Contract)
This commit is contained in:
+25
-1
@@ -12,6 +12,8 @@ from app.schemas.auth import (
|
||||
AuthTokenResponse,
|
||||
CreateClientTokenRequest,
|
||||
IssuedClientTokenResponse,
|
||||
IssueServiceTokenRequest,
|
||||
IssueServiceTokenApiResponse,
|
||||
LoginRequest,
|
||||
TokenResponse,
|
||||
)
|
||||
@@ -117,4 +119,26 @@ def revoke_token(
|
||||
service.revoke_token(auth_context, token_id)
|
||||
except ValueError as exc:
|
||||
_raise_auth_error(exc)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.post("/service-tokens", response_model=IssueServiceTokenApiResponse, status_code=status.HTTP_201_CREATED, dependencies=[Depends(require_admin)])
|
||||
def issue_service_token(
|
||||
payload: IssueServiceTokenRequest,
|
||||
service: AuthService = Depends(get_auth_service),
|
||||
) -> IssueServiceTokenApiResponse:
|
||||
try:
|
||||
result = service.issue_service_token(
|
||||
payload.name,
|
||||
payload.username,
|
||||
permission=payload.permission,
|
||||
expires_in_days=payload.expires_in_days,
|
||||
no_expiry=payload.no_expiry,
|
||||
)
|
||||
except ValueError as exc:
|
||||
_raise_auth_error(exc)
|
||||
return IssueServiceTokenApiResponse(
|
||||
token=result.token,
|
||||
runtime_id=result.auth_token.runtime_id,
|
||||
auth_token=_to_auth_token_response(result.auth_token),
|
||||
)
|
||||
+58
-24
@@ -2,13 +2,17 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
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"])
|
||||
|
||||
|
||||
@@ -21,8 +25,21 @@ def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthCon
|
||||
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(auth: AuthContext = Depends(_require_service_token)) -> 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()
|
||||
@@ -32,30 +49,47 @@ def list_assets(auth: AuthContext = Depends(_require_service_token)) -> AssetsRe
|
||||
owner_user_id=None,
|
||||
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 = {}
|
||||
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)
|
||||
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_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()
|
||||
|
||||
items = [
|
||||
AssetItem(
|
||||
asset_id=p.portfolio_id,
|
||||
broker=p.broker,
|
||||
market=p.market,
|
||||
symbol=p.symbol,
|
||||
name=p.name,
|
||||
status=p.status,
|
||||
cash_balance=p.cash_balance,
|
||||
asset_quantity=p.asset_quantity,
|
||||
price=p.price,
|
||||
profit_buffer=p.profit_buffer,
|
||||
active_strategy_id=p.active_strategy_id,
|
||||
available_strategies=p.avabile_strategies,
|
||||
tags=p.tags,
|
||||
owner_user_id=p.owner_user_id,
|
||||
created_at=p.created_at,
|
||||
updated_at=p.updated_at,
|
||||
last_trade_at=p.last_trade_at,
|
||||
)
|
||||
for p in portfolios
|
||||
]
|
||||
return AssetsResponse(assets=items, total=len(items))
|
||||
|
||||
+38
-2
@@ -2,7 +2,9 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from decimal import Decimal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Response, status
|
||||
|
||||
from app.core.auth import AuthContext, require_read
|
||||
from app.repositories.factory import get_portfolio_repository_from_settings
|
||||
@@ -20,6 +22,17 @@ def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthCon
|
||||
return auth
|
||||
|
||||
|
||||
def _payloads_match(existing, body: LedgerTradeRequest) -> bool:
|
||||
"""Return True when the existing trade's payload matches the request body."""
|
||||
return (
|
||||
existing.side == body.side
|
||||
and abs(existing.quantity - float(body.quantity)) < 1e-9
|
||||
and abs(existing.price - float(body.price)) < 1e-9
|
||||
and abs(existing.fee_amount - float(body.fee_amount)) < 1e-9
|
||||
and abs(existing.tax_amount - float(body.tax_amount)) < 1e-9
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/assets/{asset_id}/ledger/trades",
|
||||
response_model=LedgerTradeResponse,
|
||||
@@ -28,6 +41,7 @@ def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthCon
|
||||
def record_ledger_trade(
|
||||
asset_id: str,
|
||||
body: LedgerTradeRequest,
|
||||
response: Response,
|
||||
auth: AuthContext = Depends(_require_service_token),
|
||||
) -> LedgerTradeResponse:
|
||||
from app.core.config import get_settings
|
||||
@@ -35,6 +49,15 @@ def record_ledger_trade(
|
||||
settings = get_settings()
|
||||
repo = get_portfolio_repository_from_settings(settings)
|
||||
try:
|
||||
# B-9: Validate asset_id (portfolio) existence
|
||||
try:
|
||||
repo.get(asset_id)
|
||||
except Exception:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Asset not found: {asset_id}",
|
||||
)
|
||||
|
||||
trade, created = repo.insert_ledger_trade(
|
||||
asset_id=asset_id,
|
||||
order_id=body.order_id,
|
||||
@@ -50,6 +73,19 @@ def record_ledger_trade(
|
||||
if callable(getattr(type(repo), "close", None)):
|
||||
repo.close()
|
||||
|
||||
if not created:
|
||||
# B-8: Check payload conflict → 409
|
||||
if not _payloads_match(trade, body):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Duplicate key with different payload",
|
||||
)
|
||||
# B-7: Same payload duplicate → 200 + status="duplicate"
|
||||
response.status_code = status.HTTP_200_OK
|
||||
trade_status = "duplicate"
|
||||
else:
|
||||
trade_status = "new"
|
||||
|
||||
return LedgerTradeResponse(
|
||||
ledger_entry_id=trade.ledger_entry_id,
|
||||
asset_id=trade.asset_id,
|
||||
@@ -62,5 +98,5 @@ def record_ledger_trade(
|
||||
tax_amount=trade.tax_amount,
|
||||
executed_at=trade.executed_at,
|
||||
recorded_at=trade.recorded_at,
|
||||
created=created,
|
||||
status=trade_status,
|
||||
)
|
||||
|
||||
+41
-8
@@ -2,12 +2,18 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
|
||||
from app.core.auth import AuthContext, require_read
|
||||
from app.core.config import Settings, get_settings
|
||||
from app.core.encryption import InvalidToken, decrypt_payload
|
||||
from app.repositories.factory import get_portfolio_repository_from_settings
|
||||
from app.schemas.v1 import UserInfoResponse
|
||||
from app.schemas.v1 import BrokerItem, UserInfoResponse
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix="/v1", tags=["v1"])
|
||||
|
||||
|
||||
@@ -21,19 +27,45 @@ def _require_service_token(auth: AuthContext = Depends(require_read)) -> AuthCon
|
||||
|
||||
|
||||
@router.get("/user_info", response_model=UserInfoResponse)
|
||||
def get_user_info(auth: AuthContext = Depends(_require_service_token)) -> UserInfoResponse:
|
||||
def get_user_info(
|
||||
auth: AuthContext = Depends(_require_service_token),
|
||||
settings: Settings = Depends(get_settings),
|
||||
) -> UserInfoResponse:
|
||||
if not auth.runtime_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="runtime_id not assigned to this token",
|
||||
)
|
||||
|
||||
from app.core.config import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
repo = get_portfolio_repository_from_settings(settings)
|
||||
try:
|
||||
user = repo.get_user(auth.user_id) # type: ignore[arg-type]
|
||||
|
||||
# Fetch broker credentials and decrypt
|
||||
brokers: list[BrokerItem] = []
|
||||
try:
|
||||
credentials = repo.list_broker_credentials(auth.user_id) # type: ignore[arg-type]
|
||||
enc_key: str | None = None
|
||||
for cred in credentials:
|
||||
credential_payload = None
|
||||
try:
|
||||
if enc_key is None:
|
||||
enc_key = settings.require_credential_encryption_key()
|
||||
raw = decrypt_payload(enc_key, cred.encrypted_payload)
|
||||
credential_payload = json.loads(raw)
|
||||
except (InvalidToken, RuntimeError, Exception) as exc:
|
||||
logger.warning("credential decryption failed for broker %s: %s", cred.broker, exc)
|
||||
brokers.append(BrokerItem(
|
||||
broker=cred.broker,
|
||||
account_ref=cred.account_ref,
|
||||
credential_payload=credential_payload,
|
||||
credential_version=cred.credential_version,
|
||||
last_rotated_at=cred.last_rotated_at,
|
||||
))
|
||||
except AttributeError:
|
||||
# repo does not implement list_broker_credentials yet (mock or older impl)
|
||||
pass
|
||||
|
||||
finally:
|
||||
if callable(getattr(type(repo), "close", None)):
|
||||
repo.close()
|
||||
@@ -43,11 +75,12 @@ def get_user_info(auth: AuthContext = Depends(_require_service_token)) -> UserIn
|
||||
disabled_reason = "account_inactive"
|
||||
|
||||
return UserInfoResponse(
|
||||
runtime_id=auth.runtime_id,
|
||||
trading_enabled=user.is_active,
|
||||
disabled_reason=disabled_reason,
|
||||
brokers=brokers,
|
||||
user_id=user.id,
|
||||
username=user.username,
|
||||
email=user.email,
|
||||
permission=user.permission,
|
||||
is_active=user.is_active,
|
||||
disabled_reason=disabled_reason,
|
||||
runtime_id=auth.runtime_id,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user