"""Alpha 归因路由。""" from fastapi import APIRouter, Depends, Query from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.core.database import get_db from app.core.dependencies import get_current_user from app.models.company import Company from app.models.intervention import InterventionEvent, InterventionResult from app.models.user import User from app.schemas.common import ApiResponse, success from app.services.alpha_attribution import attribute_alpha router = APIRouter(prefix="/alpha", tags=["alpha"]) @router.get("", response_model=ApiResponse[list]) async def list_interventions( company_id: str | None = Query(default=None), db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user), ): """获取干预事件列表。""" query = ( select(InterventionEvent) .join(Company, InterventionEvent.company_id == Company.id) .where(Company.tenant_id == user.tenant_id) ) if company_id: query = query.where(InterventionEvent.company_id == company_id) result = await db.execute(query.order_by(InterventionEvent.executed_at.desc())) items = result.scalars().all() return success(data=[ { "id": str(i.id), "company_id": str(i.company_id), "intervention_type": i.intervention_type, "title": i.title, "description": i.description, "executed_at": i.executed_at.isoformat(), } for i in items ]) @router.post("", response_model=ApiResponse[dict]) async def create_intervention(req: dict, db: AsyncSession = Depends(get_db), user: User = Depends(get_current_user)): """记录干预事件。""" event = InterventionEvent( company_id=req.get("company_id"), intervention_type=req.get("intervention_type"), title=req.get("title"), description=req.get("description"), executed_by=str(user.id), ) db.add(event) await db.flush() return success(data={"id": str(event.id)}, message="创建成功") @router.post("/{intervention_id}/attribute", response_model=ApiResponse[dict]) async def attribute(intervention_id: str, req: dict, user: User = Depends(get_current_user)): """AI Alpha 归因分析。""" result = await attribute_alpha(req.get("intervention", {}), req.get("metric_changes", {})) return success(data=result)