File size: 9,694 Bytes
fcf8749 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | """
Phase 3 Admin-facing API endpoints.
Handles admin operations: health, allocation runs, assignments, metrics, appeals, overrides, config.
"""
from datetime import date
from fastapi import APIRouter, Depends, HTTPException, Query, status
from sqlalchemy.ext.asyncio import AsyncSession
from uuid import UUID
from app.database import get_db
from app.schemas.admin import (
HealthResponse,
AllocationRunsListResponse,
AdminAssignmentsListResponse,
FairnessMetricsResponse,
WorkloadHeatmapResponse,
DriverHistoryResponse,
AppealsListResponse,
AppealDecisionRequest,
AppealDecisionResponse,
ManualOverrideRequest,
ManualOverrideResponse,
FairnessConfigRequest,
FairnessConfigResponse,
AgentTimelineResponse,
DriverAllocationStoryResponse,
)
from app.services.admin_service import (
get_system_health,
get_allocation_runs,
get_assignments_paginated,
get_fairness_metrics_series,
get_workload_heatmap,
get_driver_history,
list_appeals,
decide_appeal,
perform_manual_override,
get_active_fairness_config,
create_fairness_config,
get_agent_timeline,
get_driver_allocation_story,
)
router = APIRouter(prefix="/admin", tags=["Admin"])
@router.get(
"/health",
response_model=HealthResponse,
summary="System health check",
description="Get system health status including database and latest allocation run.",
)
async def health_check(
db: AsyncSession = Depends(get_db),
) -> HealthResponse:
"""Check system health."""
return await get_system_health(db)
@router.get(
"/allocation_runs",
response_model=AllocationRunsListResponse,
summary="List allocation runs",
description="Get allocation runs for a specific date.",
)
async def get_allocation_runs_endpoint(
date: date = Query(..., description="Date to query"),
db: AsyncSession = Depends(get_db),
) -> AllocationRunsListResponse:
"""List allocation runs for date."""
return await get_allocation_runs(db, date)
@router.get(
"/assignments",
response_model=AdminAssignmentsListResponse,
summary="List assignments",
description="Get paginated list of assignments with filters.",
)
async def get_assignments_endpoint(
date: date = Query(..., description="Date to query"),
driver_id: UUID = Query(default=None, description="Filter by driver"),
min_fairness: float = Query(default=None, ge=0, le=1, description="Minimum fairness score"),
max_fairness: float = Query(default=None, ge=0, le=1, description="Maximum fairness score"),
page: int = Query(default=1, ge=1, description="Page number"),
page_size: int = Query(default=50, ge=1, le=100, description="Items per page"),
db: AsyncSession = Depends(get_db),
) -> AdminAssignmentsListResponse:
"""Get paginated assignments."""
return await get_assignments_paginated(
db, date, driver_id, min_fairness, max_fairness, page, page_size
)
@router.get(
"/metrics/fairness",
response_model=FairnessMetricsResponse,
summary="Fairness metrics time series",
description="Get fairness metrics over a date range.",
)
async def get_fairness_metrics_endpoint(
start_date: date = Query(..., description="Start date"),
end_date: date = Query(..., description="End date"),
db: AsyncSession = Depends(get_db),
) -> FairnessMetricsResponse:
"""Get fairness metrics time series."""
return await get_fairness_metrics_series(db, start_date, end_date)
@router.get(
"/workload_heatmap",
response_model=WorkloadHeatmapResponse,
summary="Workload heatmap",
description="Get workload heatmap data for visualization.",
)
async def get_heatmap_endpoint(
start_date: date = Query(..., description="Start date"),
end_date: date = Query(..., description="End date"),
db: AsyncSession = Depends(get_db),
) -> WorkloadHeatmapResponse:
"""Get workload heatmap data."""
return await get_workload_heatmap(db, start_date, end_date)
@router.get(
"/driver/{driver_id}/history",
response_model=DriverHistoryResponse,
summary="Driver history",
description="Get detailed driver history including appeals and overrides.",
)
async def get_driver_history_endpoint(
driver_id: UUID,
window_days: int = Query(default=30, ge=1, le=365, description="Days to look back"),
db: AsyncSession = Depends(get_db),
) -> DriverHistoryResponse:
"""Get driver history."""
result = await get_driver_history(db, driver_id, window_days)
if not result:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Driver not found",
)
return result
@router.get(
"/appeals",
response_model=AppealsListResponse,
summary="List appeals",
description="Get list of appeals with optional status filter.",
)
async def get_appeals_endpoint(
status: str = Query(default=None, description="Filter by status (PENDING, APPROVED, REJECTED, RESOLVED)"),
db: AsyncSession = Depends(get_db),
) -> AppealsListResponse:
"""List appeals."""
return await list_appeals(db, status)
@router.post(
"/appeals/{appeal_id}/decision",
response_model=AppealDecisionResponse,
summary="Decide appeal",
description="Update appeal status with admin decision.",
)
async def decide_appeal_endpoint(
appeal_id: UUID,
request: AppealDecisionRequest,
db: AsyncSession = Depends(get_db),
) -> AppealDecisionResponse:
"""Make decision on an appeal."""
try:
result = await decide_appeal(db, appeal_id, request.status, request.admin_note)
if not result:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Appeal not found",
)
await db.commit()
return result
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
)
@router.post(
"/manual_override",
response_model=ManualOverrideResponse,
summary="Manual override",
description="Manually reassign a route from one driver to another.",
)
async def manual_override_endpoint(
request: ManualOverrideRequest,
db: AsyncSession = Depends(get_db),
) -> ManualOverrideResponse:
"""Perform manual route override."""
try:
result = await perform_manual_override(
db=db,
allocation_run_id=request.allocation_run_id,
old_driver_id=request.old_driver_id,
new_driver_id=request.new_driver_id,
route_id=request.route_id,
reason=request.reason,
)
await db.commit()
return result
except ValueError as e:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=str(e),
)
@router.get(
"/fairness_config",
response_model=FairnessConfigResponse,
summary="Get fairness config",
description="Get the currently active fairness configuration.",
)
async def get_fairness_config_endpoint(
db: AsyncSession = Depends(get_db),
) -> FairnessConfigResponse:
"""Get active fairness config."""
result = await get_active_fairness_config(db)
if not result:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No active fairness config found",
)
return result
@router.post(
"/fairness_config",
response_model=FairnessConfigResponse,
status_code=status.HTTP_201_CREATED,
summary="Create fairness config",
description="Create new fairness config and deactivate existing ones.",
)
async def create_fairness_config_endpoint(
request: FairnessConfigRequest,
db: AsyncSession = Depends(get_db),
) -> FairnessConfigResponse:
"""Create new fairness config."""
result = await create_fairness_config(
db=db,
workload_weight_packages=request.workload_weight_packages,
workload_weight_weight_kg=request.workload_weight_weight_kg,
workload_weight_difficulty=request.workload_weight_difficulty,
workload_weight_time=request.workload_weight_time,
gini_threshold=request.gini_threshold,
stddev_threshold=request.stddev_threshold,
max_gap_threshold=request.max_gap_threshold,
recovery_mode_enabled=request.recovery_mode_enabled,
)
await db.commit()
return result
@router.get(
"/agent_timeline",
response_model=AgentTimelineResponse,
summary="Agent timeline",
description="Get agent decision logs for an allocation run.",
)
async def get_agent_timeline_endpoint(
allocation_run_id: UUID = Query(..., description="Allocation run ID"),
db: AsyncSession = Depends(get_db),
) -> AgentTimelineResponse:
"""Get agent timeline for allocation run."""
return await get_agent_timeline(db, allocation_run_id)
@router.get(
"/driver_allocation_story",
response_model=DriverAllocationStoryResponse,
summary="Driver allocation story",
description="Get complete allocation story for a driver on a specific date.",
)
async def get_driver_allocation_story_endpoint(
driver_id: UUID = Query(..., description="Driver ID"),
date: date = Query(..., description="Date to query (ISO format)"),
db: AsyncSession = Depends(get_db),
) -> DriverAllocationStoryResponse:
"""Get driver allocation story for a specific date."""
result = await get_driver_allocation_story(db, driver_id, date)
if not result:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="No assignment found for driver on given date",
)
return result
|