Files

251 lines
9.9 KiB
Python
Raw Permalink Normal View History

2026-09-09 21:55:37 +08:00
from typing import Any
from fastapi import APIRouter, Depends, Header, Path, Query, Response
from pydantic import BaseModel
from app.api.dependencies.auth import build_request_context
from app.api.dependencies.rate_limit import enforce_rate_limit
2026-09-09 21:55:37 +08:00
from app.api.schemas.admin import (
EmptyPayload,
EndpointPayload,
IntentPayload,
ItemPayload,
NegativePayload,
PromptPayload,
ReleasePayload,
ReplyPayload,
ReviewPayload,
RoutingPayload,
)
2026-09-11 14:59:16 +08:00
from app.core.advisor_backtest_contracts import AllocationBacktestQuery
2026-09-09 21:55:37 +08:00
from app.core.contracts import RequestContext
2026-09-11 16:42:31 +08:00
from app.core.profile_governance_contracts import ProfileDriftReviewRequest
2026-09-09 21:55:37 +08:00
from app.service.admin_service import AdminService
2026-09-11 14:59:16 +08:00
from app.service.allocation_backtest_service import AllocationBacktestService
2026-09-11 17:47:06 +08:00
from app.service.customer_profile_candidate_service import CustomerProfileCandidateService
from app.service.customer_service_handover_admin_service import CustomerServiceHandoverAdminService
2026-09-11 16:42:31 +08:00
from app.service.profile_governance_service import ProfileGovernanceService
2026-09-09 21:55:37 +08:00
2026-09-11 14:59:16 +08:00
router = APIRouter(
prefix="/api/v1/admin", tags=["platform-admin"], dependencies=[Depends(enforce_rate_limit)]
)
@router.post("/advisor/asset-allocation-backtests", status_code=201)
async def run_asset_allocation_backtest(
payload: AllocationBacktestQuery,
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, object]:
return await AllocationBacktestService().run(payload, context, key)
2026-09-09 21:55:37 +08:00
2026-09-11 16:42:31 +08:00
@router.get("/advisor/profile-tags")
async def list_profile_tags(
customer_id: int = Query(gt=0),
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, object]:
return await ProfileGovernanceService().tags(customer_id, context)
@router.get("/advisor/profile-drift-reviews")
async def list_profile_drift_reviews(
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, object]:
return await ProfileGovernanceService().pending_reviews(context)
@router.post("/advisor/profile-drift-reviews/{review_id}/reviews")
async def review_profile_drift(
payload: ProfileDriftReviewRequest,
review_id: int = Path(gt=0),
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, object]:
return await ProfileGovernanceService().review(review_id, payload, context, key)
2026-09-09 21:55:37 +08:00
def register_resource(
2026-09-11 14:59:16 +08:00
resource: str,
schema: type[BaseModel],
id_name: str,
*,
scoped: bool = False,
update: bool = True,
detail: bool = True,
2026-09-09 21:55:37 +08:00
) -> None:
prefix = f"/config-releases/{{release_id}}/{resource}" if scoped else f"/{resource}"
async def create(
2026-09-11 14:59:16 +08:00
payload: BaseModel,
response: Response,
release_id: int | None = None,
2026-09-09 21:55:37 +08:00
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
) -> dict[str, Any]:
2026-09-11 14:59:16 +08:00
result = await AdminService().mutate(
resource, context, payload.model_dump(mode="json"), key, None, release_id=release_id
)
2026-09-09 21:55:37 +08:00
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
return result
create.__annotations__["payload"] = schema
2026-09-11 14:59:16 +08:00
router.add_api_route(
prefix, create, methods=["POST"], status_code=201, operation_id=f"create_{resource}"
)
2026-09-09 21:55:37 +08:00
async def list_rows(
2026-09-11 14:59:16 +08:00
release_id: int | None = None,
limit: int = Query(default=20, ge=1, le=100),
cursor: str | None = Query(default=None),
2026-09-09 21:55:37 +08:00
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, Any]:
"""列表查询(文档 §3.8 统一游标)。游标校验在 Service 的权限闸门之后进行。"""
return await AdminService().query(
resource, context, release_id=release_id, limit=limit, cursor=cursor
)
2026-09-09 21:55:37 +08:00
router.add_api_route(prefix, list_rows, methods=["GET"], operation_id=f"list_{resource}")
async def get(
2026-09-11 14:59:16 +08:00
response: Response,
row_id: int = Path(alias=id_name, gt=0),
2026-09-09 21:55:37 +08:00
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, Any]:
result = await AdminService().query(resource, context, row_id=row_id)
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
return result
if detail:
2026-09-11 14:59:16 +08:00
router.add_api_route(
f"{prefix}/{{{id_name}}}", get, methods=["GET"], operation_id=f"get_{resource}"
)
2026-09-09 21:55:37 +08:00
async def put(
2026-09-11 14:59:16 +08:00
payload: BaseModel,
response: Response,
row_id: int = Path(alias=id_name, gt=0),
2026-09-09 21:55:37 +08:00
release_id: int | None = None,
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
if_match: str | None = Header(default=None, alias="If-Match"),
) -> dict[str, Any]:
2026-09-11 14:59:16 +08:00
result = await AdminService().mutate(
resource,
context,
payload.model_dump(mode="json"),
key,
if_match,
row_id=row_id,
release_id=release_id,
)
2026-09-09 21:55:37 +08:00
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
return result
put.__annotations__["payload"] = schema
if update:
2026-09-11 14:59:16 +08:00
router.add_api_route(
f"{prefix}/{{{id_name}}}", put, methods=["PUT"], operation_id=f"update_{resource}"
)
2026-09-09 21:55:37 +08:00
def register_transition(resource: str, id_name: str, action: str) -> None:
async def transition(
2026-09-11 14:59:16 +08:00
payload: BaseModel,
response: Response,
row_id: int = Path(alias=id_name, gt=0),
2026-09-09 21:55:37 +08:00
context: RequestContext = Depends(build_request_context), # noqa: B008
key: str | None = Header(default=None, alias="Idempotency-Key"),
if_match: str | None = Header(default=None, alias="If-Match"),
) -> dict[str, Any]:
2026-09-11 14:59:16 +08:00
result = await AdminService().mutate(
resource,
context,
payload.model_dump(mode="json"),
key,
if_match,
row_id=row_id,
action=action,
)
2026-09-09 21:55:37 +08:00
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
return result
transition.__annotations__["payload"] = ReviewPayload if action == "reviews" else EmptyPayload
2026-09-11 14:59:16 +08:00
router.add_api_route(
f"/{resource}/{{{id_name}}}/{action}",
transition,
methods=["POST"],
status_code=201 if action == "rollbacks" else 200,
operation_id=f"{action}_{resource}",
)
2026-09-09 21:55:37 +08:00
register_resource("config-releases", ReleasePayload, "release_id", update=False)
register_resource("platform-config-items", ItemPayload, "item_id", scoped=True, detail=False)
register_resource("model-endpoints", EndpointPayload, "endpoint_id")
register_resource("model-routing-rules", RoutingPayload, "rule_id", scoped=True, detail=False)
register_resource("prompt-templates", PromptPayload, "prompt_id", update=False)
register_resource("agent-intent-configs", IntentPayload, "config_id")
2026-09-09 21:55:37 +08:00
register_resource("reply-templates", ReplyPayload, "template_id", detail=False)
register_resource("negative-word-rules", NegativePayload, "rule_id", detail=False)
for action in ("validations", "reviews", "activations", "rollbacks"):
register_transition("config-releases", "release_id", action)
for action in ("reviews", "activations", "disablements"):
register_transition("model-endpoints", "endpoint_id", action)
# 意图配置沿用同一套"审核 → 生效 → 归档"流转;归档落 `archived`
# (该表 CHECK 约束只允许 draft/approved/active/archived,没有 disabled)。
for action in ("reviews", "activations", "archivals"):
register_transition("agent-intent-configs", "config_id", action)
2026-09-09 21:55:37 +08:00
@router.get("/audit-records")
async def audit_records(
limit: int = Query(default=20, ge=1, le=100),
cursor: str | None = Query(default=None),
2026-09-09 21:55:37 +08:00
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, Any]:
"""审计查询(文档 §9.6 支持游标过滤)。游标非法时返回 `400 INVALID_CURSOR`。"""
return await AdminService().query("audit-records", context, limit=limit, cursor=cursor)
@router.get("/customer-service/handover-tickets")
async def list_customer_service_handover_tickets(
limit: int = Query(default=20, ge=1, le=100),
cursor: str | None = Query(default=None),
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, Any]:
"""只读查看客服待转人工队列;不暴露原始会话或处理动作。"""
return await CustomerServiceHandoverAdminService().list_tickets(
context, limit=limit, cursor=cursor
)
@router.get("/customer-service/handover-tickets/{ticket_no}")
async def get_customer_service_handover_ticket(
ticket_no: str,
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, Any]:
"""只读查看单个工单的脱敏转接摘要。"""
return await CustomerServiceHandoverAdminService().get_ticket(ticket_no, context)
2026-09-11 17:47:06 +08:00
@router.get("/customer-profile-candidates")
async def list_customer_profile_candidates(
limit: int = Query(default=20, ge=1, le=100),
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, Any]:
"""管理员查看待确认或待审核的画像候选。"""
return await CustomerProfileCandidateService().list_for_admin(context, limit=limit)
@router.post("/customer-profile-candidates/{candidate_id}/reviews", status_code=200)
async def review_customer_profile_candidate(
candidate_id: int,
payload: ReviewPayload,
context: RequestContext = Depends(build_request_context), # noqa: B008
) -> dict[str, Any]:
"""管理员批准或驳回候选;批准会处理同键旧正式记忆。"""
return await CustomerProfileCandidateService().review_by_admin(
candidate_id, payload.decision, context, comment=payload.comment
)