API契约:迁移订单与账号业务错误

This commit is contained in:
Christ committed 2026-08-14 14:05:32 +08:00
1 parent 1efe44e921
commit 4d92e8e919
6 files changed
+87 -31

No files matched your search

+3 -1
View File
@@ -130,7 +130,8 @@ app shell / routes
- 已完成阶段 2 最终审计:生产代码中的 `GetDetails` 仅保留登录设置和登录信息更新两条完整详情白名单;平台流程统一使用 `GetCookiePlatformRuntimeData`,所有权流程统一使用摘要查询,凭证读取继续由 `LockAccountCredentials` 保护;新增 `TestMultiDB_CookieCredentialScope` 覆盖 SQLite,并在提供环境变量时覆盖 MySQL/Postgres,验证三种方言的 Cookie、metadata、平台视图和所有权摘要一致;阶段 2 全量门禁通过并合并为一个可回滚提交;
- 已完成阶段 3 第一个 PR 切片“HTTP 错误结构盘点与第一批契约测试”:新增共享 `httpapi.ErrorResponse`,统一 `code`/`message`/`request_id` 错误边界;认证失败改用 401 和稳定 `authentication_failed`,健康检查和账号列表改用具名 DTO;React 请求层移除 `detail/msg` 错误依赖并为账号列表补充具名类型;新增健康检查、认证失败和账号列表契约测试,Go/React 全量门禁通过并合并为一个可回滚提交;
- 已完成阶段 3 第二个 PR 切片“剩余认证与公共 API 错误迁移”:初始化冲突、管理员/用户密码修改、登录凭据校验、用户名冲突、公开设置故障和 SPA API 404 均返回统一错误 DTO 与正确状态码;新增状态码/错误码契约测试,Go 全量门禁通过并合并为一个可回滚提交;
- 阶段 3 下一 PR 切片为“业务 API 错误响应迁移”:按订单、账号、聊天、商品和自动化领域批量收敛遗留 `success:false`、`error`/`detail` 响应,先处理订单与账号两个领域并补充契约测试,不拆分单个 handler 提交;
- 已完成阶段 3 第三个 PR 切片“订单与账号业务 API 错误响应迁移”:订单刷新、手动发货和订单导入不再返回顶层 HTTP 200 + `success:false`,批量结果改用 `partial_failure`,刷新明细错误统一使用 `message`;账号任务的 502 错误改用统一错误 DTO;新增订单/账号契约测试并通过全量门禁,逐项结果中的 `success` 仅保留为批处理行状态;
- 阶段 3 下一 PR 切片为“聊天、商品与自动化业务 API 错误响应迁移”:继续按业务域批量收敛遗留 `success:false`、`error`/`detail` 响应,不拆分单个 handler 提交;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -509,3 +510,4 @@ npm --prefix frontend run build
| 2026-08-14 | 完成阶段 2 最终审计 PR 切片 | 生产 `GetDetails` 白名单仅保留登录设置与登录信息更新;新增跨数据库 Cookie/metadata/平台视图/所有权窄查询回归;全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:HTTP 错误结构盘点与第一批契约测试 |
| 2026-08-14 | 完成阶段 3 第一个 PR 切片“HTTP 错误结构盘点与第一批契约测试” | 共享错误 DTO、认证 401、健康检查和账号列表具名 DTO 已落地;React 请求层完成错误契约迁移;Go/React 全量测试、vet、lint、注释和前端构建通过 | 阶段 3:剩余认证与公共 API 错误迁移 |
| 2026-08-14 | 完成阶段 3 第二个 PR 切片“剩余认证与公共 API 错误迁移” | 初始化、密码修改、凭据校验、用户名冲突、公开设置故障和 SPA API 404 的状态码/错误码契约已统一;契约测试、全量测试、vet、lint、注释和 diff 门禁通过 | 阶段 3:订单与账号业务 API 错误响应迁移 |
| 2026-08-14 | 完成阶段 3 第三个 PR 切片“订单与账号业务 API 错误响应迁移” | 订单批量接口移除顶层 HTTP 200 + `success:false`,逐项失败保留行级状态并统一为 `message`;账号任务 502 改用统一错误 DTO;订单/账号契约测试、全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:聊天、商品与自动化业务 API 错误响应迁移 |
+1 -1
View File
@@ -100,7 +100,7 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
}
summary, err := s.automation.RunAccountTask(r.Context(), cid, input.TaskType)
if err != nil {
writeJSON(w, http.StatusBadGateway, map[string]any{"summary": summary, "error": err.Error()})
writeErr(w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "summary": summary})
+54
View File
@@ -144,6 +144,9 @@ func assertUnifiedAPIError(t *testing.T, handler http.Handler, method, path, bod
if requireRequestID && response.RequestID == "" {
t.Fatalf("%s %s 缺少 request_id: %+v", method, path, response)
}
if strings.Contains(rec.Body.String(), `"detail"`) || strings.Contains(rec.Body.String(), `"msg"`) || strings.Contains(rec.Body.String(), `"error"`) {
t.Fatalf("%s %s 包含旧错误字段: %s", method, path, rec.Body.String())
}
}
// TestAPIContractRemainingAuthenticationErrors 验证初始化和密码凭据错误统一使用非 2xx 响应。
@@ -181,3 +184,54 @@ func TestAPIContractPublicAndSPAErrors(t *testing.T) {
assertUnifiedAPIError(t, handler, http.MethodGet, "/system-settings/public", "", nil, http.StatusInternalServerError, httpapi.CodeInternalError, "查询失败", false)
assertUnifiedAPIError(t, handler, http.MethodGet, "/api/not-found", "", nil, http.StatusNotFound, httpapi.CodeNotFound, "接口不存在", true)
}
// TestAPIContractOrderAndAccountErrors 验证订单和账号业务错误使用统一状态码及错误字段。
func TestAPIContractOrderAndAccountErrors(t *testing.T) {
// srv 是用于验证订单和账号业务错误的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
assertUnifiedAPIError(t, handler, http.MethodGet, "/api/orders/not-found", "", sessionCookie, http.StatusNotFound, httpapi.CodeNotFound, "订单不存在", false)
assertUnifiedAPIError(t, handler, http.MethodPost, "/api/orders/manual-ship", `{"order_ids":["order-1"],"ship_mode":"invalid"}`, sessionCookie, http.StatusBadRequest, httpapi.CodeBadRequest, "发货模式必须是 status_only 或 full_delivery", false)
assertUnifiedAPIError(t, handler, http.MethodGet, "/cookie/not-found/details", "", sessionCookie, http.StatusForbidden, httpapi.CodeForbidden, "无权限操作该Cookie", false)
assertUnifiedAPIError(t, handler, http.MethodGet, "/api/account-tasks/not-found", "", sessionCookie, http.StatusForbidden, httpapi.CodeForbidden, "无权访问该账号", false)
}
// TestAPIContractOrderBatchPartialFailure 验证订单批量接口用 partial_failure 表示逐项失败,不再返回顶层 success=false。
func TestAPIContractOrderBatchPartialFailure(t *testing.T) {
// srv 是用于验证订单批量失败响应的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// req 是包含不存在订单的手动发货请求。
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(`{"order_ids":["not-found"],"ship_mode":"status_only"}`))
req.AddCookie(sessionCookie)
// rec 是捕获批量操作响应的测试记录器。
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("batch status=%d body=%s", rec.Code, rec.Body.String())
}
// response 是批量操作的兼容响应对象。
var response map[string]any
// decodeErr 表示批量响应 JSON 反序列化失败的原因。
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("decode batch response: %v", decodeErr)
}
if response["partial_failure"] != true {
t.Fatalf("batch response=%+v", response)
}
// exists 表示兼容响应是否仍暴露顶层 success 字段。
if _, exists := response["success"]; exists {
t.Fatalf("batch response must not expose top-level success: %s", rec.Body.String())
}
if strings.Contains(rec.Body.String(), `"error"`) {
t.Fatalf("batch response contains legacy error field: %s", rec.Body.String())
}
}
+4 -4
View File
@@ -363,14 +363,14 @@ func TestOrderImportReportsPartialFailure(t *testing.T) {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var result struct {
Success bool `json:"success"`
SuccessCount int `json:"success_count"`
FailedCount int `json:"failed_count"`
PartialFailure bool `json:"partial_failure"`
SuccessCount int `json:"success_count"`
FailedCount int `json:"failed_count"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result.Success || result.SuccessCount != 1 || result.FailedCount != 1 {
if !result.PartialFailure || result.SuccessCount != 1 || result.FailedCount != 1 {
t.Fatalf("result=%+v", result)
}
}
+23 -23
View File
@@ -202,7 +202,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
}
failed++
results = append(results, map[string]any{
"cookie_id": cid, "stage": "discover", "success": false, "error": latestErr.Error(),
"cookie_id": cid, "stage": "discover", "success": false, "message": latestErr.Error(),
})
continue
}
@@ -250,7 +250,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
}
} else {
failed++
results = append(results, map[string]any{"stage": "discover", "success": false, "error": "当前 MTop 客户端不支持订单列表发现"})
results = append(results, map[string]any{"stage": "discover", "success": false, "message": "当前 MTop 客户端不支持订单列表发现"})
}
ordersByCookie := map[string][]refreshTarget{}
@@ -295,8 +295,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
message += fmt.Sprintf(";当前 Go MTOP 客户端不支持详情接口,已跳过 %d 个订单", total)
}
writeJSON(w, http.StatusOK, map[string]any{
"success": failed == 0,
"message": message,
"partial_failure": failed > 0,
"message": message,
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
"total": total, "updated": 0, "no_change": 0, "failed": failed,
@@ -307,8 +307,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
}
if total == 0 {
writeJSON(w, http.StatusOK, map[string]any{
"success": failed == 0,
"message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
"partial_failure": failed > 0,
"message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": 0,
"total": 0, "updated": 0, "no_change": 0, "failed": failed,
@@ -327,7 +327,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
if latestErr != nil || latest == nil || latest.UserID != sess.UserID || !hasStoredCookieCredential(latest) {
credentialUnlock()
failed += len(chunk)
results = append(results, map[string]any{"cookie_id": cid, "success": false, "error": "账号凭证已变化"})
results = append(results, map[string]any{"cookie_id": cid, "success": false, "message": "账号凭证已变化"})
continue
}
ctx, cancel := context.WithTimeout(r.Context(), 3*time.Minute)
@@ -344,7 +344,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
results = append(results, map[string]any{
"order_id": target.OrderID,
"success": false,
"error": message,
"message": message,
})
if mtop.IsSessionExpiredErr(fetchErr) {
sessionErr = fetchErr
@@ -366,7 +366,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
})
if err != nil {
failed++
results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "error": "更新数据库失败"})
results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "message": "更新数据库失败"})
continue
}
changed := newStatus != "" && newStatus != target.CurrentStatus
@@ -387,7 +387,7 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
credentialUnlock()
if persistErr != nil {
failed++
results = append(results, map[string]any{"cookie_id": cid, "stage": "persist_cookie", "success": false, "error": persistErr.Error()})
results = append(results, map[string]any{"cookie_id": cid, "stage": "persist_cookie", "success": false, "message": persistErr.Error()})
} else if valueChanged {
s.updateRunningCookie(r.Context(), cid, value)
}
@@ -402,8 +402,8 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
}
}
writeJSON(w, http.StatusOK, map[string]any{
"success": failed == 0,
"message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
"partial_failure": failed > 0,
"message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
"total": total, "updated": updated, "no_change": noChange, "failed": failed,
@@ -856,11 +856,11 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
fmt.Sprintf("手动确认发货成功(订单 %s)", orderID))
}
writeJSON(w, http.StatusOK, map[string]any{
"success": failedCount == 0,
"message": fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount),
"success_count": successCount,
"failed_count": failedCount,
"results": results,
"partial_failure": failedCount > 0,
"message": fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount),
"success_count": successCount,
"failed_count": failedCount,
"results": results,
})
}
@@ -1013,12 +1013,12 @@ func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "订单已导入"})
}
writeJSON(w, http.StatusOK, map[string]any{
"success": failedCount == 0,
"message": fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount),
"total": len(orders),
"success_count": successCount,
"failed_count": failedCount,
"results": results,
"partial_failure": failedCount > 0,
"message": fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount),
"total": len(orders),
"success_count": successCount,
"failed_count": failedCount,
"results": results,
})
}
+2 -2
View File
@@ -448,7 +448,7 @@ func TestManualShipOrdersStatusOnlySuccess(t *testing.T) {
}
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != true {
if res["partial_failure"] != false {
t.Fatalf("应成功: %+v", res)
}
results, _ := res["results"].([]any)
@@ -511,7 +511,7 @@ func TestManualShipOrdersConsignFail(t *testing.T) {
}
var res map[string]any
json.Unmarshal(rec.Body.Bytes(), &res)
if res["success"] != false {
if res["partial_failure"] != true {
t.Fatalf("整体应失败: %+v", res)
}
}