做法:把前端 `api-client.js` 注册的端点**按前端完全相同的方式**(同样的路径、参数、
身份)逐个调用,再拿真实返回去核对前端 render 用到的字段。
**这类问题纯读代码看不出来** —— 只有把真实返回和期望字段摆在一起才会暴露。
## 1. 知识库功能实际是坏的(K002 / K003 是裸信封)
`K002` 的成功体是 `{knowledge_ids, filename, chunk_count}`、`K003` 是 `{items, count}`,
**都没有 `data` 信封**。而 `request()` 默认取 `payload.data`(undefined),于是:
- 上传后前端显示「已入库 **0** 块」,而库里其实切了 23 块;
- 列表永远显示「知识库为空」。
端点表里标 `raw: true` 后(与 `V001` 同一做法)两者都正常。
实测:上传 4805 字符的产品手册 → 切 23 块并出现在列表里。
## 2. 委托/成交详情页有 5 行永远显示「--」
前端按 `fin_sim_order` / `fin_transaction` 的**建表字段**写了 `quote_source`、
`nav`、`fee_rate_snapshot`、`confirmed_at`、`auto_confirmed` ——
但这些字段**接口的返回视图没有带**(表里有、返回里没有)。已按实际返回重写字段表,
并在注释里写明"以接口返回为准,不要照表写"。
## 3. 配置项与路由规则的**编辑功能不可能成功**(接口缺口)
`PUT` 硬性要求 `If-Match`,校验的是该行内容的 digest;而这两个资源是 `detail=False`
—— **没有任何端点能返回这个 digest**(列表的 `meta` 只有 trace_id)。
乐观并发在"读不到版本"的前提下等于死锁:**首次编辑必然 409**。
(配置发布能用,是因为它有详情端点 `A003`。)
- 新增详情端点 `A048` / `A049`(`detail=True`),已登记 `docs/05` §19;
- 前端编辑前先 GET 详情取 etag,再带 `If-Match` 提交。
- 实测:编辑配置项与路由规则均 200;**不带 `If-Match` 仍返回 409**,
说明乐观并发没有被削弱。
## 4. 路由规则表单**必然提交失败**
前端固定写 `max_attempts: 2` 且 `fallbacks: []`,而后端要求
`max_attempts ≤ 端点总数`(主 + 兜底)→ 422「重试次数超过端点数量」。
改为 `1` 并注明约束。
## 5. 主端点手填 ID 会 422
后端对不存在/未激活的 `primary_endpoint_id` 直接 422「模型端点不存在或未激活」。
把输入框改成**下拉**,只列 `status='active'` 的端点(数据复用已有的端点列表)。
## 顺带
- `apiClient` 增加 `del()` / `put()`:发出的方法一直由端点表决定,所以 `post('K004')`
也能发 DELETE —— 语义太绕,现在意图与行为一致。
- 清理了测试期间上传的 31 条知识残留(客服会检索到它们),库内恢复到 23 条产品手册。
## 关于"逐条核对"的方法论
前两轮跑出来的 9 个和 5 个"失败"里,**多数是我测试脚本自己的假设错了**,不是前端问题:
`T001` 是 `{account, summary}` 嵌套、`RK002` 的字段叫 `risk_level`、
`RK002/RK004/RK005` 的 limit 上限是 5/10/10(前端传的正是 5/10/10)、
`AD011/A002/A047` 的 data 是裸 list。每一处都回到前端源码确认后才下结论 ——
**先把"我以为"改成"代码里写的"**,否则报告出去的就是假 bug。
验证:unit+contract **1397 passed**;integration **110 passed**;ruff 通过;
mypy 251 文件 0 错;§19 现 93 个端点无重复;e2e 冒烟 **40/40**。
前端等价测试:只读 31 项全绿、写操作(含 ETag 链路)9 项 8 绿 1 项因测试数据过短。
257 lines
10 KiB
Python
257 lines
10 KiB
Python
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
|
||
from app.api.schemas.admin import (
|
||
EmptyPayload,
|
||
EndpointPayload,
|
||
IntentPayload,
|
||
ItemPayload,
|
||
NegativePayload,
|
||
PromptPayload,
|
||
ReleasePayload,
|
||
ReplyPayload,
|
||
ReviewPayload,
|
||
RoutingPayload,
|
||
)
|
||
from app.core.advisor_backtest_contracts import AllocationBacktestQuery
|
||
from app.core.contracts import RequestContext
|
||
from app.core.profile_governance_contracts import ProfileDriftReviewRequest
|
||
from app.service.admin_service import AdminService
|
||
from app.service.allocation_backtest_service import AllocationBacktestService
|
||
from app.service.customer_profile_candidate_service import CustomerProfileCandidateService
|
||
from app.service.customer_service_handover_admin_service import CustomerServiceHandoverAdminService
|
||
from app.service.profile_governance_service import ProfileGovernanceService
|
||
|
||
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)
|
||
|
||
|
||
@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)
|
||
|
||
|
||
def register_resource(
|
||
resource: str,
|
||
schema: type[BaseModel],
|
||
id_name: str,
|
||
*,
|
||
scoped: bool = False,
|
||
update: bool = True,
|
||
detail: bool = True,
|
||
) -> None:
|
||
prefix = f"/config-releases/{{release_id}}/{resource}" if scoped else f"/{resource}"
|
||
|
||
async def create(
|
||
payload: BaseModel,
|
||
response: Response,
|
||
release_id: int | None = None,
|
||
context: RequestContext = Depends(build_request_context), # noqa: B008
|
||
key: str | None = Header(default=None, alias="Idempotency-Key"),
|
||
) -> dict[str, Any]:
|
||
result = await AdminService().mutate(
|
||
resource, context, payload.model_dump(mode="json"), key, None, release_id=release_id
|
||
)
|
||
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
||
return result
|
||
|
||
create.__annotations__["payload"] = schema
|
||
router.add_api_route(
|
||
prefix, create, methods=["POST"], status_code=201, operation_id=f"create_{resource}"
|
||
)
|
||
|
||
async def list_rows(
|
||
release_id: int | None = None,
|
||
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]:
|
||
"""列表查询(文档 §3.8 统一游标)。游标校验在 Service 的权限闸门之后进行。"""
|
||
return await AdminService().query(
|
||
resource, context, release_id=release_id, limit=limit, cursor=cursor
|
||
)
|
||
|
||
router.add_api_route(prefix, list_rows, methods=["GET"], operation_id=f"list_{resource}")
|
||
|
||
async def get(
|
||
response: Response,
|
||
row_id: int = Path(alias=id_name, gt=0),
|
||
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:
|
||
router.add_api_route(
|
||
f"{prefix}/{{{id_name}}}", get, methods=["GET"], operation_id=f"get_{resource}"
|
||
)
|
||
|
||
async def put(
|
||
payload: BaseModel,
|
||
response: Response,
|
||
row_id: int = Path(alias=id_name, gt=0),
|
||
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]:
|
||
result = await AdminService().mutate(
|
||
resource,
|
||
context,
|
||
payload.model_dump(mode="json"),
|
||
key,
|
||
if_match,
|
||
row_id=row_id,
|
||
release_id=release_id,
|
||
)
|
||
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
||
return result
|
||
|
||
put.__annotations__["payload"] = schema
|
||
if update:
|
||
router.add_api_route(
|
||
f"{prefix}/{{{id_name}}}", put, methods=["PUT"], operation_id=f"update_{resource}"
|
||
)
|
||
|
||
|
||
def register_transition(resource: str, id_name: str, action: str) -> None:
|
||
async def transition(
|
||
payload: BaseModel,
|
||
response: Response,
|
||
row_id: int = Path(alias=id_name, gt=0),
|
||
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]:
|
||
result = await AdminService().mutate(
|
||
resource,
|
||
context,
|
||
payload.model_dump(mode="json"),
|
||
key,
|
||
if_match,
|
||
row_id=row_id,
|
||
action=action,
|
||
)
|
||
response.headers["ETag"] = f'"{result["meta"]["etag"]}"'
|
||
return result
|
||
|
||
transition.__annotations__["payload"] = ReviewPayload if action == "reviews" else EmptyPayload
|
||
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}",
|
||
)
|
||
|
||
|
||
register_resource("config-releases", ReleasePayload, "release_id", update=False)
|
||
# ⚠️ `platform-config-items` 与 `model-routing-rules` 必须是 `detail=True`:
|
||
# 它们的更新端点(PUT)**硬性要求 `If-Match`**,而校验用的是**该行内容的 digest**
|
||
# (`admin_service.mutate`:`if_match is None or if_match != digest(existing) → 409`)。
|
||
# 此前 `detail=False` 意味着**没有任何端点能返回这个 digest** —— 列表的 `meta` 只有
|
||
# trace_id、也没有详情端点,于是**首次编辑必然 409**:乐观并发成了死锁,
|
||
# 编辑功能实际不可用(2026-09-13 前端等价测试发现)。
|
||
register_resource("platform-config-items", ItemPayload, "item_id", scoped=True, detail=True)
|
||
register_resource("model-endpoints", EndpointPayload, "endpoint_id")
|
||
register_resource("model-routing-rules", RoutingPayload, "rule_id", scoped=True, detail=True)
|
||
register_resource("prompt-templates", PromptPayload, "prompt_id", update=False)
|
||
register_resource("agent-intent-configs", IntentPayload, "config_id")
|
||
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)
|
||
|
||
|
||
@router.get("/audit-records")
|
||
async def audit_records(
|
||
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]:
|
||
"""审计查询(文档 §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)
|
||
|
||
|
||
@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
|
||
)
|