diff --git a/api/openapi.yaml b/api/openapi.yaml index 077fe6b..9115d41 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -1096,7 +1096,9 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + type: array + items: + $ref: '#/components/schemas/AdminCookie' '400': description: 统一错误响应 content: @@ -1222,7 +1224,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AdminStatsResponse' '400': description: 统一错误响应 content: @@ -1258,13 +1260,20 @@ paths: operationId: getApiV1AdminTasks summary: getApiV1AdminTasks security: [{cookieAuth: []}] + parameters: + - name: limit + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 128} responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + type: array + items: + $ref: '#/components/schemas/AdminTask' '400': description: 统一错误响应 content: @@ -1306,7 +1315,9 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + type: array + items: + $ref: '#/components/schemas/AdminUser' '400': description: 统一错误响应 content: @@ -1346,7 +1357,7 @@ paths: in: path required: true schema: - type: string + type: integer security: [{cookieAuth: []}] responses: '200': @@ -1354,7 +1365,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OperationResponse' '400': description: 统一错误响应 content: @@ -1396,7 +1407,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/DashboardStatsResponse' '400': description: 统一错误响应 content: @@ -1432,13 +1443,26 @@ paths: operationId: getApiV1AnalyticsOrders summary: getApiV1AnalyticsOrders security: [{cookieAuth: []}] + parameters: + - name: start_date + in: query + required: true + schema: {type: string, format: date} + - name: end_date + in: query + required: true + schema: {type: string, format: date} + - name: timezone_offset_minutes + in: query + required: false + schema: {type: integer} responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/AnalyticsResponse' '400': description: 统一错误响应 content: @@ -1474,13 +1498,34 @@ paths: operationId: getApiV1AnalyticsOrdersValid summary: getApiV1AnalyticsOrdersValid security: [{cookieAuth: []}] + parameters: + - name: start_date + in: query + required: true + schema: {type: string, format: date} + - name: end_date + in: query + required: true + schema: {type: string, format: date} + - name: timezone_offset_minutes + in: query + required: false + schema: {type: integer} + - name: page + in: query + required: false + schema: {type: integer, minimum: 1} + - name: page_size + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 500} responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ValidOrdersResponse' '400': description: 统一错误响应 content: @@ -1606,6 +1651,31 @@ paths: operationId: getApiV1AutomationRules summary: getApiV1AutomationRules security: [{cookieAuth: []}] + parameters: + - name: page + in: query + required: false + schema: {type: integer, minimum: 1} + - name: page_size + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 100} + - name: cookie_id + in: query + required: false + schema: {type: string} + - name: trigger_type + in: query + required: false + schema: {type: string} + - name: enabled + in: query + required: false + schema: {type: boolean} + - name: search + in: query + required: false + schema: {type: string} responses: '200': description: 成功 @@ -2195,13 +2265,29 @@ paths: operationId: postApiV1ChatImages summary: postApiV1ChatImages security: [{cookieAuth: []}] + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + required: [account_id, chat_id, buyer_id, image] + properties: + account_id: {type: string} + chat_id: {type: string} + buyer_id: {type: string} + buyer_name: {type: string} + buyer_avatar_url: {type: string} + item_id: {type: string} + item_title: {type: string} + image: {type: string, format: binary} responses: - '200': + '201': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ChatMessageEnvelope' '400': description: 统一错误响应 content: @@ -2237,13 +2323,34 @@ paths: operationId: getApiV1ChatMessages summary: getApiV1ChatMessages security: [{cookieAuth: []}] + parameters: + - name: account_id + in: query + required: true + schema: {type: string} + - name: chat_id + in: query + required: true + schema: {type: string} + - name: cursor + in: query + required: false + schema: {type: integer} + - name: before_id + in: query + required: false + schema: {type: integer} + - name: limit + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 200} responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ChatMessagePage' '400': description: 统一错误响应 content: @@ -2278,13 +2385,19 @@ paths: operationId: postApiV1ChatMessages summary: postApiV1ChatMessages security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ChatMessageRequest' responses: - '200': + '201': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ChatMessageEnvelope' '400': description: 统一错误响应 content: @@ -2320,13 +2433,19 @@ paths: operationId: postApiV1ChatRead summary: postApiV1ChatRead security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ChatReadRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OperationResponse' '400': description: 统一错误响应 content: @@ -2362,13 +2481,30 @@ paths: operationId: getApiV1ChatSessions summary: getApiV1ChatSessions security: [{cookieAuth: []}] + parameters: + - name: account_id + in: query + required: true + schema: {type: string} + - name: cursor + in: query + required: false + schema: {type: integer} + - name: refresh + in: query + required: false + schema: {type: integer, enum: [0, 1]} + - name: limit + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 200} responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/ChatSessionPage' '400': description: 统一错误响应 content: @@ -2404,6 +2540,8 @@ paths: operationId: getApiV1ChatWs summary: getApiV1ChatWs security: [{cookieAuth: []}] + x-websocket-message-schema: + $ref: '#/components/schemas/ChatWebSocketEvent' responses: '101': description: WebSocket 握手成功 @@ -2716,6 +2854,11 @@ paths: operationId: getApiV1Items summary: getApiV1Items security: [{cookieAuth: []}] + parameters: + - name: cookie_id + in: query + required: false + schema: {type: string} responses: '200': description: 成功 @@ -3243,6 +3386,11 @@ paths: operationId: getApiV1ItemsPublishBatches summary: getApiV1ItemsPublishBatches security: [{cookieAuth: []}] + parameters: + - name: limit + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 100} responses: '200': description: 成功 @@ -4151,13 +4299,34 @@ paths: operationId: getApiV1Orders summary: getApiV1Orders security: [{cookieAuth: []}] + parameters: + - name: cookie_id + in: query + required: false + schema: {type: string} + - name: status + in: query + required: false + schema: {type: string} + - name: search + in: query + required: false + schema: {type: string} + - name: page + in: query + required: false + schema: {type: integer, minimum: 1} + - name: page_size + in: query + required: false + schema: {type: integer, minimum: 1, maximum: 500} responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OrderListResponse' '400': description: 统一错误响应 content: @@ -4252,7 +4421,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OrderDetailResponse' '400': description: 统一错误响应 content: @@ -4293,13 +4462,19 @@ paths: schema: type: string security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OrderUpdateRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OperationResponse' '400': description: 统一错误响应 content: @@ -4347,7 +4522,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OrderSingleRefreshResponse' '400': description: 统一错误响应 content: @@ -4383,13 +4558,26 @@ paths: operationId: postApiV1OrdersImport summary: postApiV1OrdersImport security: [{cookieAuth: []}] + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + properties: + file: {type: string, format: binary} + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/OrderUpdateRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OrderBatchResponse' '400': description: 统一错误响应 content: @@ -4425,13 +4613,19 @@ paths: operationId: postApiV1OrdersManualShip summary: postApiV1OrdersManualShip security: [{cookieAuth: []}] + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/ManualShipRequest' responses: '200': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OrderBatchResponse' '400': description: 统一错误响应 content: @@ -4467,13 +4661,22 @@ paths: operationId: postApiV1OrdersRefresh summary: postApiV1OrdersRefresh security: [{cookieAuth: []}] + requestBody: + required: true + content: + multipart/form-data: + schema: + type: object + properties: + cookie_id: {type: string} + status: {type: string} responses: - '200': + '202': description: 成功 content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OrderRefreshJobStartResponse' '400': description: 统一错误响应 content: @@ -4521,7 +4724,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OrderRefreshJobCancelResponse' '400': description: 统一错误响应 content: @@ -4568,7 +4771,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/OrderRefreshJobStatusResponse' '400': description: 统一错误响应 content: @@ -6342,7 +6545,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/HealthResponse' '400': description: 统一错误响应 content: @@ -6373,6 +6576,12 @@ paths: application/json: schema: $ref: '#/components/schemas/ErrorResponse' + '503': + description: 数据库不可用 + content: + application/json: + schema: + $ref: '#/components/schemas/HealthDegradedResponse' components: securitySchemes: cookieAuth: @@ -6387,6 +6596,21 @@ components: success: type: boolean description: 统一响应的稳定字段;业务成功字段由各阶段 operation schema 收紧。 + HealthResponse: + type: object + required: [status, database, version, commit] + properties: + status: {type: string, enum: [ok]} + database: {type: string, enum: [ok]} + version: {type: string} + commit: {type: string} + build_time: {type: string} + HealthDegradedResponse: + type: object + required: [status, database] + properties: + status: {type: string, enum: [degraded]} + database: {type: string, enum: [unavailable]} SessionResponse: type: object required: [success, message, is_admin] @@ -6728,6 +6952,323 @@ components: - type: string - type: number - type: boolean + ChatSession: + type: object + required: [account_id, chat_id, buyer_id, buyer_name, last_message, last_message_at, unread_count] + properties: + account_id: {type: string} + chat_id: {type: string} + buyer_id: {type: string} + buyer_name: {type: string} + buyer_avatar_url: {type: string} + item_id: {type: string} + item_title: {type: string} + last_message: {type: string} + last_message_at: {type: integer} + unread_count: {type: integer} + ChatMessage: + type: object + required: [id, account_id, chat_id, message_key, direction, sender_id, sender_name, message_type, content, status, sent_at] + properties: + id: {type: integer} + account_id: {type: string} + chat_id: {type: string} + message_key: {type: string} + direction: {type: string, enum: [incoming, outgoing]} + sender_id: {type: string} + sender_name: {type: string} + message_type: {type: string, enum: [text, image, video, system]} + content: {type: string} + status: {type: string, enum: [received, sending, sent, failed]} + read_status: {type: integer} + read_at: {type: integer} + sent_at: {type: integer} + ChatSessionPage: + type: object + required: [sessions, has_more] + properties: + sessions: {type: array, items: {$ref: '#/components/schemas/ChatSession'}} + has_more: {type: boolean} + next_cursor: {type: integer} + ChatMessagePage: + type: object + required: [messages, has_more] + properties: + messages: {type: array, items: {$ref: '#/components/schemas/ChatMessage'}} + has_more: {type: boolean} + next_cursor: {type: integer} + session: {$ref: '#/components/schemas/ChatSession'} + ChatMessageEnvelope: + type: object + required: [message] + properties: + message: {$ref: '#/components/schemas/ChatMessage'} + ChatReadyEvent: + type: object + required: [type, at] + properties: + type: {type: string, enum: [ready]} + at: {type: integer} + ChatEvent: + type: object + required: [type] + properties: + type: {type: string, enum: [message.created, message.updated]} + message: {$ref: '#/components/schemas/ChatMessage'} + session: {$ref: '#/components/schemas/ChatSession'} + ChatWebSocketEvent: + anyOf: + - $ref: '#/components/schemas/ChatReadyEvent' + - $ref: '#/components/schemas/ChatEvent' + ChatMessageRequest: + type: object + required: [account_id, chat_id, buyer_id, text] + properties: + account_id: {type: string} + chat_id: {type: string} + buyer_id: {type: string} + buyer_name: {type: string} + item_id: {type: string} + item_title: {type: string} + text: {type: string, maxLength: 2000} + ChatReadRequest: + type: object + required: [account_id, chat_id] + properties: + account_id: {type: string} + chat_id: {type: string} + message_ids: {type: array, items: {type: object, additionalProperties: {oneOf: [{type: string}, {type: number}]}}} + OrderDTO: + type: object + required: [order_id, item_id, item_title, item_image, buyer_id, spec_name, spec_value, quantity, amount, order_status, status, cookie_id, is_bargain, system_shipped, receiver_name, receiver_phone, receiver_address, receiver_city, created_at, updated_at] + properties: + order_id: {type: string} + item_id: {type: string} + item_title: {type: string} + item_image: {type: string} + buyer_id: {type: string} + spec_name: {type: string} + spec_value: {type: string} + quantity: {type: string} + amount: {type: string} + order_status: {type: string} + status: {type: string} + cookie_id: {type: string} + is_bargain: {type: integer} + system_shipped: {type: boolean} + receiver_name: {type: string} + receiver_phone: {type: string} + receiver_address: {type: string} + receiver_city: {type: string} + created_at: {type: string} + updated_at: {type: string} + OrderListResponse: + type: object + required: [success, data, total, page, page_size, total_pages] + properties: + success: {type: boolean} + data: {type: array, items: {$ref: '#/components/schemas/OrderDTO'}} + total: {type: integer} + page: {type: integer} + page_size: {type: integer} + total_pages: {type: integer} + OrderDetailResponse: + allOf: + - {$ref: '#/components/schemas/OrderDTO'} + - type: object + required: [success, data] + properties: + success: {type: boolean} + data: {$ref: '#/components/schemas/OrderDTO'} + OrderUpdateRequest: + type: object + properties: + order_status: {type: string} + status: {type: string} + item_id: {type: string} + buyer_id: {type: string} + spec_name: {type: string} + spec_value: {type: string} + quantity: {oneOf: [{type: string}, {type: number}]} + amount: {oneOf: [{type: string}, {type: number}]} + receiver_name: {type: string} + receiver_phone: {type: string} + receiver_address: {type: string} + receiver_city: {type: string} + chat_id: {type: string} + system_shipped: {type: boolean} + item_title: {type: string} + OrderRefreshDetail: + type: object + required: [quantity, spec_name, spec_value, order_status, amount] + properties: + quantity: {type: string} + spec_name: {type: string} + spec_value: {type: string} + order_status: {type: string} + amount: {type: string} + OrderSingleRefreshResponse: + type: object + required: [success, message, order] + properties: + success: {type: boolean} + message: {type: string} + order: {$ref: '#/components/schemas/OrderRefreshDetail'} + OrderRefreshResult: + type: object + required: [success] + properties: + success: {type: boolean} + cookie_id: {type: string} + stage: {type: string} + message: {type: string} + error: {type: string} + discovered: {type: integer} + updated: {type: integer} + soft_deleted: {type: boolean} + order_id: {type: string} + old_status: {type: string} + new_status: {type: string} + OrderRefreshSummary: + type: object + required: [discovered, list_updated, soft_deleted, detail_total, total, updated, no_change, failed] + properties: + discovered: {type: integer} + list_updated: {type: integer} + soft_deleted: {type: integer} + detail_total: {type: integer} + total: {type: integer} + updated: {type: integer} + no_change: {type: integer} + failed: {type: integer} + OrderRefreshResponse: + type: object + required: [partial_failure, message, summary, results] + properties: + partial_failure: {type: boolean} + message: {type: string} + summary: {$ref: '#/components/schemas/OrderRefreshSummary'} + results: {type: array, items: {$ref: '#/components/schemas/OrderRefreshResult'}} + OrderRefreshJobStartResponse: + type: object + required: [success, job_id, status] + properties: + success: {type: boolean} + job_id: {type: string} + status: {type: string, enum: [queued, running]} + OrderRefreshJobStatusResponse: + type: object + required: [success, job_id, status] + properties: + success: {type: boolean} + job_id: {type: string} + status: {type: string, enum: [queued, running, succeeded, failed, cancelled]} + error_message: {type: string} + result: {$ref: '#/components/schemas/OrderRefreshResponse'} + OrderRefreshJobCancelResponse: + type: object + required: [success, job_id, status] + properties: + success: {type: boolean} + job_id: {type: string} + status: {type: string, enum: [cancelled]} + ManualShipRequest: + type: object + required: [order_ids, ship_mode] + properties: + order_ids: {type: array, items: {type: string}} + ship_mode: {type: string, enum: [status_only, full_delivery]} + OrderBatchResult: + type: object + required: [message] + properties: + order_id: {type: string} + status: {type: string} + success: {type: boolean} + message: {type: string} + cookie_id: {type: string} + reconciliation_id: {type: string} + reconciliation_warning: {type: string} + stage: {type: string} + OrderBatchResponse: + type: object + required: [partial_failure, message, success_count, failed_count, results] + properties: + partial_failure: {type: boolean} + message: {type: string} + total: {type: integer} + success_count: {type: integer} + failed_count: {type: integer} + results: {type: array, items: {$ref: '#/components/schemas/OrderBatchResult'}} + AdminStatsResponse: + type: object + required: [total_users, total_cookies, active_cookies, total_cards, total_keywords, total_orders] + properties: + total_users: {type: integer} + total_cookies: {type: integer} + active_cookies: {type: integer} + total_cards: {type: integer} + total_keywords: {type: integer} + total_orders: {type: integer} + AdminUser: + type: object + required: [id, username, email, is_active, is_admin, created_at, cookie_count] + properties: + id: {type: integer} + username: {type: string} + email: {type: string} + is_active: {type: boolean} + is_admin: {type: boolean} + created_at: {type: string} + cookie_count: {type: integer} + AdminCookie: + type: object + required: [id, user_id, remark, created_at, owner, enabled] + properties: + id: {type: string} + user_id: {type: integer} + remark: {type: string} + created_at: {type: string} + owner: {type: string} + enabled: {type: boolean} + AdminTask: + type: object + required: [id, name, state, started_at] + properties: + id: {type: string} + name: {type: string} + state: {type: string, enum: [running, succeeded, failed, canceled, timed_out]} + started_at: {type: string, format: date-time} + finished_at: {type: string, format: date-time} + deadline_at: {type: string, format: date-time} + DashboardStatsResponse: + type: object + required: [total_cookies, active_cookies, total_cards, available_card_stock, total_keywords, total_orders] + properties: + total_cookies: {type: integer} + active_cookies: {type: integer} + total_cards: {type: integer} + available_card_stock: {type: integer} + total_keywords: {type: integer} + total_orders: {type: integer} + AnalyticsResponse: + type: object + required: [revenue_stats, daily_stats, status_stats, city_stats, item_stats] + properties: + revenue_stats: {type: object, required: [total_orders, total_amount, avg_amount, unique_buyers, unique_items], properties: {total_orders: {type: integer}, total_amount: {type: number}, avg_amount: {type: number}, unique_buyers: {type: integer}, unique_items: {type: integer}}} + daily_stats: {type: array, items: {type: object, required: [date, order_count, amount], properties: {date: {type: string}, order_count: {type: integer}, amount: {type: number}}}} + status_stats: {type: array, items: {type: object, required: [status, count, amount], properties: {status: {type: string}, count: {type: integer}, amount: {type: number}}}} + city_stats: {type: array, items: {type: object, required: [city, order_count, total_amount], properties: {city: {type: string}, order_count: {type: integer}, total_amount: {type: number}}}} + item_stats: {type: array, items: {type: object, required: [item_id, order_count, total_amount, avg_amount], properties: {item_id: {type: string}, order_count: {type: integer}, total_amount: {type: number}, avg_amount: {type: number}}}} + ValidOrdersResponse: + type: object + required: [orders, total, page, page_size, truncated] + properties: + orders: {type: array, items: {$ref: '#/components/schemas/OrderDTO'}} + total: {type: integer} + page: {type: integer} + page_size: {type: integer} + truncated: {type: boolean} SessionStatusResponse: type: object required: [authenticated, initialized, is_admin] diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index f44ce5b..6f9f36c 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -21,8 +21,8 @@ | 既有架构基线:稳定性、组合根、生命周期、React、DB、质量收口 | 已完成(不可回退) | 历史实现和证据留在 `refactoring-progress.md`,不重做、不改写历史。 | | 1. 契约基础设施与全路由登记 | 已完成 | OpenAPI、生成漂移和真实 Router 双向门禁已建立,未改变业务运行时形状。 | | 2. 类型化客户端与登录账号主链路 | 已完成 | session、system、accounts、QR 风控和永久关闭的 password-login 已迁移并完成真实响应校验。 | -| 3. 查询、聊天与订单主链路 | 当前阶段 | 迁移 dashboard、admin、chat、orders、刷新任务和 WebSocket 消息。 | -| 4. 商品、卡券和文件传输 | 待执行 | 迁移 items、批量发布、cards、上传与 CSV。 | +| 3. 查询、聊天与订单主链路 | 已完成 | dashboard、实际消费的 admin 摘要、chat、orders、刷新任务和 WebSocket 消息均已迁移并完成真实契约校验。 | +| 4. 商品、卡券和文件传输 | 当前阶段 | 迁移 items、批量发布、cards、上传与 CSV。 | | 5. 自动化、设置和通知动态契约 | 待执行 | 迁移 rules、automation、settings、notifications 和账号绑定。 | | 6. 全量封闭与旧手写契约退场 | 待执行 | 关闭原始 HTTP client 旁路,删除手写 transport DTO 和名单式门禁。 | diff --git a/docs/architecture/refactoring-progress.md b/docs/architecture/refactoring-progress.md index 8385b11..7a13eb7 100644 --- a/docs/architecture/refactoring-progress.md +++ b/docs/architecture/refactoring-progress.md @@ -437,3 +437,10 @@ architecturecheck: 通过;git diff --check 无输出。 - 解析边界:门禁会展开 TypeScript `extends` 字段和 Go 匿名嵌入 DTO 字段,避免订单详情等兼容顶层字段产生误报;嵌套对象字段单独属于其行 DTO,不被错误归入外层响应。动态键、feature 归一化和脱敏模型必须逐项写明理由,不能静默跳过。 - 修复结果:二维码风控状态已补齐 `verification_screenshot` 和 `face_qr_url`;删除卡券时间字段、账号 AI 模型/密钥字段、通知渠道配置与时间字段等服务端从未提供且前端不消费的历史契约。通知渠道列表继续不返回配置,避免 SMTP 等秘密穿透摘要 DTO;编辑器用空配置初始化。 - 回归保护:新增真实临时仓库夹具测试,确认遗漏后端字段会触发门禁;新增匿名嵌入解析测试。冻结滑块验证码实现及其调用语义未修改。 + +### 2026-08-20 OpenAPI 契约阶段三:查询、聊天与订单主链路 + +- 交付范围:dashboard、订单分析、有效订单、订单分页/详情/更新/删除、异步刷新任务、聊天会话/消息/已读/图片/文本与管理员用户、账号、任务摘要均通过生成的 `/api/v1` operation 调用;UI 继续只消费 feature adapter 输出的派生模型。 +- WebSocket:`/api/v1/chat/ws` 以 `x-websocket-message-schema` 引用 `ChatWebSocketEvent`。服务端实际 `ready` 和聊天事件 DTO 由同一 OpenAPI component 校验;原生 WebSocket 仍只由聊天通知 owner 使用。 +- 契约修正:订单刷新项的 `soft_deleted` 由历史错误的整数收紧为真实 handler 输出的布尔值;管理员账号摘要 schema 不包含 Cookie、密码或其他凭证字段。 +- 验收:`make api-check`、`go run ./tools/architecturecheck`、`go test ./internal/server -count=1`、`npm run typecheck --prefix frontend`、`npm test --prefix frontend`、`make comments` 与 `git diff --check` 均通过。未修改冻结 CAPTCHA 实现,未执行真实账号或外部平台调用。 diff --git a/frontend/app/features/chat/api.ts b/frontend/app/features/chat/api.ts index d056d97..63356bf 100644 --- a/frontend/app/features/chat/api.ts +++ b/frontend/app/features/chat/api.ts @@ -4,26 +4,59 @@ ChatMessage, ChatSession, OperationResponse } from '../../../shared/api-contract/chat'; -import { get,post,postForm,type RequestControlOptions } from '../../../shared/http/client'; -import { objectFrom } from '../../../shared/http/contract'; +import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; +import { type RequestControlOptions } from '../../../shared/http/client'; export type * from '../../../shared/api-contract/chat'; import type { ChatReadReceipt } from './types'; +/** ChatImageFormContract 描述图片发送 operation 的 multipart 字段,仅用于将原生 FormData 交给生成客户端。 */ +type ChatImageFormContract = { + /** 账号标识。 */ account_id: string; + /** 会话标识。 */ chat_id: string; + /** 买家标识。 */ buyer_id: string; + /** 买家展示名称。 */ buyer_name?: string; + /** 买家头像地址。 */ buyer_avatar_url?: string; + /** 关联商品标识。 */ item_id?: string; + /** 关联商品标题。 */ item_title?: string; + /** 二进制图片字段。 */ image: string; +}; + /** 聊天账号选择器读取非敏感账号摘要。 */ -export const getAccountDetails = async (options?: RequestControlOptions): Promise => get('/api/v1/accounts/details', undefined, options); +export const getAccountDetails = async (options?: RequestControlOptions): Promise => { + // response 是账号摘要 transport DTO 集合,转换后只向聊天 UI 暴露非敏感字段。 + const response = await runContractRequest(/* signal 是本次聊天账号摘要请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options); + return response.map(/* item 是当前待转换的账号摘要 DTO。 */ item => ({ + id: item.id, + enabled: item.enabled, + auto_confirm: item.auto_confirm, + remark: item.remark, + pause_duration: item.pause_duration, + paused_until: item.paused_until, + paused: item.paused, + username: item.username, + show_browser: item.show_browser, + nickname: item.nickname, + avatar_url: item.avatar_url, + profile_error: item.profile_error, + })); +}; /** 聊天运行提示读取账号连接状态索引。 */ -export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise; /** 状态说明。 */ message?: string; /** 是否已连接。 */ connected: boolean; /** 连续失败次数。 */ failures: number; /** 最近更新时间。 */ updated_at: string }>> => get('/api/v1/accounts/runtime-status', undefined, options); +export const getAccountRuntimeStatuses = async (options?: RequestControlOptions): Promise; /** 状态说明。 */ message?: string; /** 是否已连接。 */ connected: boolean; /** 连续失败次数。 */ failures: number; /** 最近更新时间。 */ updated_at: string }>> => + runContractRequest(/* signal 是本次聊天运行状态请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/runtime-status', { signal }), options); export interface ChatSessionPage { /** sessions 表示聊天会话列表。 */ sessions: ChatSession[]; /** has_more 表示是否存在更多数据。 */ has_more: boolean; /** next_cursor 表示下一页游标。 */ next_cursor?: number } // getChatSessionPage 分页读取聊天会话。 export const getChatSessionPage = async (accountId: string, cursor?: number, options?: RequestControlOptions, refresh = false): Promise => { // result 接口响应结果,用于当前 API 处理流程。 - const response = await get('/api/v1/chat/sessions', { account_id: accountId, cursor, refresh: refresh ? 1 : undefined }, - refresh ? { timeoutMs: 60_000, ...options } : options); - // result 是兼容直接分页对象和 data 包裹后的聊天会话分页。 - const result = objectFrom>(response, ['data', 'result']) || {}; - return { sessions: result.sessions || [], has_more: result.has_more === true, next_cursor: result.next_cursor }; + const response = await runContractRequest( + /* signal 是本次聊天会话分页请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/chat/sessions', { + params: { query: { account_id: accountId, cursor, refresh: refresh ? 1 : undefined } }, + signal, + }), + { timeoutMs: refresh ? 60_000 : options?.timeoutMs, signal: options?.signal }, + ); + return response; }; // getChatSessions 读取聊天会话列表。 @@ -40,12 +73,11 @@ export interface ChatMessagePage { // getChatMessagePage 分页读取聊天消息。 export const getChatMessagePage = async (accountId: string, chatId: string, cursor?: number, beforeId?: number, options?: RequestControlOptions): Promise => { // result 接口响应结果,用于当前 API 处理流程。 - const response = await get('/api/v1/chat/messages', { - account_id: accountId, chat_id: chatId, cursor, before_id: beforeId, - }, options); - // result 是兼容直接分页对象和 data 包裹后的聊天消息分页。 - const result = objectFrom>(response, ['data', 'result']) || {}; - return { messages: result.messages || [], has_more: result.has_more === true, next_cursor: result.next_cursor, session: result.session }; + const response = await runContractRequest(/* signal 是本次聊天消息分页请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/chat/messages', { + params: { query: { account_id: accountId, chat_id: chatId, cursor, before_id: beforeId } }, + signal, + }), options); + return response; }; // getChatMessages 读取聊天消息列表。 @@ -56,7 +88,8 @@ export const getChatMessages = async (accountId: string, chatId: string, beforeI export const sendChatMessage = async (input: { /** account_id 表示账号标识。 */ account_id: string; /** chat_id 表示聊天标识。 */ chat_id: string; /** buyer_id 表示买家标识。 */ buyer_id: string; /** buyer_name 表示买家名称。 */ buyer_name?: string; /** item_id 表示商品标识。 */ item_id?: string; /** item_title 表示商品标题。 */ item_title?: string; /** text 表示文本。 */ text: string; -}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => post('/api/v1/chat/messages', input, options); +}, options?: RequestControlOptions): Promise<{/** message 表示消息数据。 */ message: ChatMessage}> => + runContractRequest(/* signal 是本次聊天文本发送请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/chat/messages', { body: input, signal }), options); // sendChatImage 发送聊天图片消息。 export const sendChatImage = async (input: { @@ -66,9 +99,16 @@ export const sendChatImage = async (input: { // form 消息表单,用于当前 API 处理流程。 const form = new FormData(); Object.entries(input).forEach(/* 当前回调用于处理集合元素或接口响应。 */ ([key, value]) => form.append(key, value)); - return postForm('/api/v1/chat/images', form, { timeoutMs: 120_000, ...options }); + return runContractRequest(/* signal 是本次聊天图片发送请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/chat/images', { + // body 保持原生 FormData;类型转换只把 multipart 运行时载荷交给生成 operation。 + body: form as unknown as ChatImageFormContract, + signal, + }), { timeoutMs: 120_000, ...options }); }; /** 向平台确认指定会话中的入站消息已读。 */ export const markChatRead = async (accountId: string, chatId: string, messageIDs: ChatReadReceipt[], options?: RequestControlOptions): Promise => - post('/api/v1/chat/read', { account_id: accountId, chat_id: chatId, message_ids: messageIDs }, options); + runContractRequest(/* signal 是本次聊天已读上报请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/chat/read', { + body: { account_id: accountId, chat_id: chatId, message_ids: messageIDs.map(/* receipt 是当前待序列化的平台已读回执。 */ receipt => ({ messageId: receipt.messageId, sessionId: receipt.sessionId, cid: receipt.cid, conversationType: receipt.conversationType })) }, + signal, + }), options); diff --git a/frontend/app/features/dashboard/api.ts b/frontend/app/features/dashboard/api.ts index eaaf980..79accda 100644 --- a/frontend/app/features/dashboard/api.ts +++ b/frontend/app/features/dashboard/api.ts @@ -1,7 +1,8 @@ import { formatLocalDate } from '../../../dateRange'; import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from '../../../shared/api-contract/admin'; -import { get,type RequestControlOptions } from '../../../shared/http/client'; -import { collectionFrom,objectFrom } from '../../../shared/http/contract'; +import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; +import { type RequestControlOptions } from '../../../shared/http/client'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; export type * from '../../../shared/api-contract/admin'; /** 仪表盘订单明细接口转换后的分页结果。 */ @@ -23,12 +24,13 @@ const normalizeOrderStatus = (value: unknown): OrderStatus => { }; /** 读取仪表盘概览统计。 */ -export const getDashboardStats = async (options?: RequestControlOptions): Promise => get('/api/v1/analytics/dashboard', undefined, options); +export const getDashboardStats = async (options?: RequestControlOptions): Promise => + runContractRequest(/* signal 是本次仪表盘统计请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/analytics/dashboard', { signal }), options); /** 读取仪表盘商品索引,兼容历史 items 包装。 */ export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise => { // response 是商品列表的原始 transport 响应。 - const response = await get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options); + const response = await runContractRequest(/* signal 控制仪表盘商品读取的取消和超时。 */ signal => contractClient.GET('/api/v1/items', { params: { query: { cookie_id: accountID } }, signal }), options) as unknown as Item[] | ItemListEnvelope; // items 是从直接数组或历史包装中取出的商品集合。 const items = collectionFrom(response, ['items', 'data', 'results']); return items.map(/* item 是当前需要兼容布尔标记的商品传输记录。 */ item => ({ ...item, id: item.id || `${item.cookie_id}-${item.item_id}`, is_multi_spec: item.is_multi_spec === true || item.is_multi_spec === 1, multi_quantity_delivery: item.multi_quantity_delivery === true || item.multi_quantity_delivery === 1 })); @@ -48,17 +50,23 @@ export const getOrderAnalytics = async (range: number | { /** 统计起始日期 } else { dateRange = range; } - return get('/api/v1/analytics/orders', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options); + return runContractRequest(/* signal 是本次订单分析请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/analytics/orders', { + params: { query: { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() } }, + signal, + }), options); }; /** 读取可参与仪表盘统计的订单并适配历史响应形状。 */ export const getValidOrders = async (dateRange: { /** 统计起始日期。 */ start_date: string; /** 统计结束日期。 */ end_date: string }, options?: RequestControlOptions): Promise => { // response 是有效订单接口的未知兼容响应。 - const response = await get('/api/v1/analytics/orders/valid', { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() }, options); - // page 是移除历史 transport 包装后的分页元数据。 - const page = objectFrom>(response, ['data', 'result']) || {}; - // rows 是直接数组或历史 orders 包装中的原始订单。 - const rows = collectionFrom(response, ['orders', 'data', 'items']); + const response = await runContractRequest(/* signal 是本次有效订单查询请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/analytics/orders/valid', { + params: { query: { ...dateRange, timezone_offset_minutes: -new Date().getTimezoneOffset() } }, + signal, + }), options); + // page 是生成契约或历史 data/result 包装后的有效订单分页元数据。 + const page = objectFrom>(response as unknown, ['data', 'result']) || {}; + // rows 是当前分页或兼容包装中的有效订单 transport DTO。 + const rows = collectionFrom(response as unknown, ['orders', 'data', 'items']); // orders 是转换状态、数量和稳定标识后的仪表盘订单模型。 const orders = rows.map(/* row 是当前需要归一化状态与数量的有效订单 DTO。 */ row => ({ ...row, id: row.order_id, status: normalizeOrderStatus(row.status || row.order_status), order_status: normalizeOrderStatus(row.order_status), quantity: Number(row.quantity || 1) })); return { orders, total: Number(page.total ?? orders.length), truncated: page.truncated === true }; diff --git a/frontend/app/features/orders/api.ts b/frontend/app/features/orders/api.ts index a65f9d2..ef78041 100644 --- a/frontend/app/features/orders/api.ts +++ b/frontend/app/features/orders/api.ts @@ -5,15 +5,15 @@ Item, OperationResponse, Order, OrderBatchResponse, -OrderDTOResponse,OrderDetailResponse, -OrderRefreshJobCancelResponse, -OrderRefreshJobStartResponse,OrderRefreshJobStatusResponse, +OrderDTOResponse, +OrderRefreshJobCancelResponse,OrderRefreshJobStatusResponse, OrderRefreshResponse, OrderSingleRefreshResponse, PaginatedResponse } from '../../../shared/api-contract/orders'; -import { del,get,post,postForm,put,type RequestControlOptions } from '../../../shared/http/client'; -import { collectionFrom,objectFrom } from '../../../shared/http/contract'; +import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; +import { type RequestControlOptions } from '../../../shared/http/client'; +import { collectionFrom, objectFrom } from '../../../shared/http/contract'; export type * from '../../../shared/api-contract/orders'; /** 订单刷新前端最多轮询约 90 秒,超过该预算必须请求取消后端 worker。 */ @@ -21,6 +21,45 @@ const orderRefreshPollLimit = 180; /** 订单刷新取消和终态复查使用独立五秒网络预算,不能复用已超时或已 Abort 的主信号。 */ const orderRefreshCancelTimeoutMs = 5_000; +/** OrderListQuery 描述订单列表 operation 可传递的筛选和分页参数。 */ +type OrderListQuery = { + /** 账号筛选标识。 */ cookie_id?: string; + /** 订单状态筛选值。 */ status?: string; + /** 用户输入的文本搜索条件。 */ search?: string; + /** 页码,从一开始。 */ page: number; + /** 每页最大行数。 */ page_size: number; +}; + +/** OrderImportFormContract 描述订单文件导入 operation 的 multipart 字段。 */ +type OrderImportFormContract = { + /** 二进制导入文件字段。 */ file?: string; +}; + +/** OrderRefreshFormContract 描述订单刷新 operation 的 multipart 筛选字段。 */ +type OrderRefreshFormContract = { + /** 可选的账号筛选标识。 */ cookie_id?: string; + /** 可选的订单状态筛选值。 */ status?: string; +}; + +/** OrderBatchTransportResponse 描述生成 operation 返回、尚未归一化状态枚举的批量订单结果。 */ +type OrderBatchTransportResponse = { + /** 批次是否包含失败项。 */ partial_failure: boolean; + /** 可展示的批次执行说明。 */ message: string; + /** 可选的输入订单总数。 */ total?: number; + /** 已成功处理的订单数量。 */ success_count: number; + /** 已失败处理的订单数量。 */ failed_count: number; + /** 每个订单的 transport 结果。 */ results: Array<{ + /** 平台订单标识。 */ order_id?: string; + /** 服务端返回的处理状态。 */ status?: string; + /** 单项是否成功。 */ success?: boolean; + /** 单项处理说明。 */ message: string; + /** 所属账号标识。 */ cookie_id?: string; + /** 不确定远端结果的补偿记录标识。 */ reconciliation_id?: string; + /** 本地补偿警告。 */ reconciliation_warning?: string; + /** 当前业务处理阶段。 */ stage?: string; + }>; +}; + /** 订单刷新轮询选项仅控制前端等待行为;不改变后端任务、HTTP 路径或请求体契约。 */ export interface OrderRefreshPollOptions extends RequestControlOptions { /** pollLimit 是本次前端最多读取任务状态的次数;省略时保持九十秒默认预算。 */ @@ -30,13 +69,31 @@ export interface OrderRefreshPollOptions extends RequestControlOptions { } /** 订单筛选器读取非敏感账号摘要。 */ -export const getAccountDetails = async (options?: RequestControlOptions): Promise => get('/api/v1/accounts/details', undefined, options); +export const getAccountDetails = async (options?: RequestControlOptions): Promise => { + // response 是账号摘要 transport DTO 集合,转换后只向订单 UI 暴露非敏感字段。 + const response = await runContractRequest(/* signal 是本次订单账号摘要请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options); + return response.map(/* item 是当前待转换的账号摘要 DTO。 */ item => ({ + id: item.id, + enabled: item.enabled, + auto_confirm: item.auto_confirm, + remark: item.remark, + pause_duration: item.pause_duration, + paused_until: item.paused_until, + paused: item.paused, + username: item.username, + show_browser: item.show_browser, + nickname: item.nickname, + avatar_url: item.avatar_url, + profile_error: item.profile_error, + })); +}; /** 订单关联商品展示读取当前商品索引。 */ -export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise => get('/api/v1/items', accountID ? { cookie_id: accountID } : undefined, options); +export const getItems = async (accountID?: string, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制订单页商品读取的取消和超时。 */ signal => contractClient.GET('/api/v1/items', { params: { query: { cookie_id: accountID } }, signal }), options) as unknown as Promise; /** 管理员统计仍由订单域兼容 API 提供给历史管理页面。 */ -export const getAdminStats = async (): Promise => get('/api/v1/admin/stats'); +export const getAdminStats = async (): Promise => + runContractRequest(/* signal 是本次管理员统计请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/admin/stats', { signal })); // Orders // normalizeOrderStatus 归一化订单状态。 const normalizeOrderStatus = (value: unknown): Order['status'] => { @@ -58,40 +115,48 @@ export const getOrders = async ( options?: RequestControlOptions, ): Promise> => { // params 请求参数,用于当前 API 处理流程。 - const params: any = { page, page_size: pageSize }; + // params 是生成契约约束的订单筛选与分页查询参数。 + const params: OrderListQuery = { page, page_size: pageSize }; if (cookieId) params.cookie_id = cookieId; if (status && status !== 'all') params.status = status; if (search?.trim()) params.search = search.trim(); - // res 接口响应结果,用于当前 API 处理流程。 - const response = await get('/api/v1/orders', params, options); - // res 是兼容直接分页对象、orders 别名和 data 包裹后的订单响应。 - const res = objectFrom> & { /** orders 是历史订单列表字段别名。 */ orders?: Order[] }>(response, ['data', 'result']) || {}; - - // Handle backend response variations - // rawOrders 原始订单列表,用于当前 API 处理流程。 - const rawOrders = Array.isArray(res.orders) ? res.orders : collectionFrom(res.data, ['data', 'orders', 'items']); + // response 是生成契约约束的订单分页 transport DTO。 + const response = await runContractRequest(/* signal 是本次订单分页请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/orders', { + params: { query: params }, + signal, + }), options); + // legacyResponse 是保留给旧 handler 包装和测试夹具的适配视图,不扩散到 UI model。 + const legacyResponse = response as unknown; + // pageResponse 是直接分页对象或 data/result 包装后的页面元数据。 + const pageResponse = objectFrom> & { /** orders 是历史订单列表字段别名。 */ orders?: Order[] }>(legacyResponse, ['data', 'result']) || {}; + // rawOrders 是当前分页中的订单 transport DTO;兼容归一只在 adapter 内完成。 + const rawOrders = Array.isArray(pageResponse.orders) ? pageResponse.orders : collectionFrom(pageResponse.data, ['data', 'orders', 'items']); // orders 订单列表,用于当前 API 处理流程。 - const orders = rawOrders.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ + const orders = rawOrders.map(/* item 是当前需要归一化状态与数量的订单 DTO。 */ item => ({ ...item, - id: item.id || item.order_id, + id: item.order_id, + order_status: normalizeOrderStatus(item.order_status), status: normalizeOrderStatus(item.status || item.order_status), quantity: Number(item.quantity || 1), })); return { success: true, data: orders, - total: res.total || orders.length, - page: res.page || page, - page_size: res.page_size || pageSize, - total_pages: res.total_pages || 1 + total: pageResponse.total || orders.length, + page: pageResponse.page || page, + page_size: pageResponse.page_size || pageSize, + total_pages: pageResponse.total_pages || 1 }; }; // getOrderDetail 读取订单详情。 export const getOrderDetail = async (orderId: string): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: OrderDTOResponse }> => { // result 接口响应结果,用于当前 API 处理流程。 - const result = await get(`/api/v1/orders/${orderId}`); + const result = await runContractRequest(/* signal 是本次订单详情请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/orders/{order_id}', { + params: { path: { order_id: orderId } }, + signal, + })); return { success: true, data: result.data @@ -100,12 +165,19 @@ export const getOrderDetail = async (orderId: string): Promise<{ /** success 表 // updateOrder 更新订单。 export const updateOrder = async (orderId: string, data: Partial): Promise => { - return put(`/api/v1/orders/${orderId}`, data); + return runContractRequest(/* signal 是本次订单更新请求的超时与取消控制信号。 */ signal => contractClient.PUT('/api/v1/orders/{order_id}', { + params: { path: { order_id: orderId } }, + body: data, + signal, + })); }; // deleteOrder 删除订单。 export const deleteOrder = async (orderId: string): Promise => { - return del(`/api/v1/orders/${orderId}`); + return runContractRequest(/* signal 是本次订单删除请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/orders/{order_id}', { + params: { path: { order_id: orderId } }, + signal, + })); }; // syncOrders 同步订单。 @@ -116,7 +188,10 @@ export const syncOrders = async (cookieId?: string, status?: string, options?: O if (status) formData.append('status', status); // start 表示后台订单刷新任务创建响应。 - const start = await postForm('/api/v1/orders/refresh', formData, options); + const start = await runContractRequest(/* signal 是本次订单刷新任务创建请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/refresh', { + body: formData as unknown as OrderRefreshFormContract, + signal, + }), options); // cancelOnAbort 在调用方取消轮询时通知服务端停止同一后台任务;取消命令使用独立信号,主请求已取消也能发出。 const cancelOnAbort = () => { void cancelOrderRefreshJob(start.job_id, { timeoutMs: orderRefreshCancelTimeoutMs }).catch(/* 取消请求失败时忽略网络错误,主请求仍按取消语义结束。 */ () => undefined); @@ -131,7 +206,10 @@ export const syncOrders = async (cookieId?: string, status?: string, options?: O try { while (pollIndex < pollLimit) { // job 表示当前轮询得到的后台任务状态。 - const job = await get(`/api/v1/orders/refresh/${start.job_id}`, undefined, options); + const job = await runContractRequest(/* signal 是本次订单刷新状态轮询请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/orders/refresh/{job_id}', { + params: { path: { job_id: start.job_id } }, + signal, + }), options); if (job.status === 'succeeded' && job.result) { return job.result; } @@ -178,30 +256,70 @@ const cancelAndReadOrderRefreshJob = async (jobId: string): Promise(`/api/v1/orders/refresh/${jobId}`, undefined, { timeoutMs: orderRefreshCancelTimeoutMs }); + return runContractRequest(/* signal 是本次订单刷新终态查询请求的超时与取消控制信号。 */ signal => contractClient.GET('/api/v1/orders/refresh/{job_id}', { + params: { path: { job_id: jobId } }, + signal, + }), { timeoutMs: orderRefreshCancelTimeoutMs }); }; // cancelOrderRefreshJob 请求取消当前用户的订单刷新后台任务。 export const cancelOrderRefreshJob = async (jobId: string, options?: RequestControlOptions): Promise => { - return del(`/api/v1/orders/refresh/${jobId}`, undefined, options); + return runContractRequest(/* signal 是本次订单刷新取消请求的超时与取消控制信号。 */ signal => contractClient.DELETE('/api/v1/orders/refresh/{job_id}', { + params: { path: { job_id: jobId } }, + signal, + }), options); }; // syncSingleOrder 同步单个订单。 export const syncSingleOrder = async (orderId: string): Promise => { - return post(`/api/v1/orders/${orderId}/refresh`); + return runContractRequest(/* signal 是本次单订单刷新请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/{order_id}/refresh', { + params: { path: { order_id: orderId } }, + signal, + })); }; // manualShipOrder 手动发货订单。 export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise => { - return post('/api/v1/orders/manual-ship', { + // response 是生成契约约束的批量发货 transport DTO,随后归一化为旧 UI 模型。 + const response = await runContractRequest(/* signal 是本次批量发货请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/manual-ship', { + body: { order_ids: orderIds, ship_mode: shipMode, - }); + }, + signal, + })); + return normalizeOrderBatchResponse(response); } // importOrders 导入订单。 export const importOrders = async (data: Partial[] | FormData, options?: RequestControlOptions): Promise => { // isFormData 是否为表单请求,用于当前 API 处理流程。 const isFormData = data instanceof FormData; - return isFormData ? postForm('/api/v1/orders/import', data, options) : post('/api/v1/orders/import', data, options); + if (isFormData) { + // response 是生成契约约束的文件导入 transport DTO。 + const response = await runContractRequest(/* signal 是本次订单表格导入请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/import', { + body: data as unknown as OrderImportFormContract, + signal, + }), options); + return normalizeOrderBatchResponse(response); + } + // response 是生成契约约束的 JSON 导入 transport DTO。 + const response = await runContractRequest(/* signal 是本次订单 JSON 导入请求的超时与取消控制信号。 */ signal => contractClient.POST('/api/v1/orders/import', { + body: data, + signal, + }), options); + return normalizeOrderBatchResponse(response); } + +// normalizeOrderBatchResponse 将生成 transport DTO 转为兼容历史订单页面的受限结果状态。 +const normalizeOrderBatchResponse = (response: OrderBatchTransportResponse): OrderBatchResponse => ({ + partial_failure: response.partial_failure, + message: response.message, + total: response.total, + success_count: response.success_count, + failed_count: response.failed_count, + results: (response.results || []).map(/* item 是当前待归一化的批量订单结果 DTO。 */ item => ({ + ...item, + status: item.status === 'failed' || item.status === 'succeeded' || item.status === 'reconciliation_required' ? item.status : undefined, + })), +}); diff --git a/frontend/app/features/system/api.ts b/frontend/app/features/system/api.ts index d502f1d..873193d 100644 --- a/frontend/app/features/system/api.ts +++ b/frontend/app/features/system/api.ts @@ -1,7 +1,8 @@ -import { get,type RequestControlOptions } from '../../../shared/http/client'; +import { type RequestControlOptions } from '../../../shared/http/client'; +import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import type { BuildInfo } from './types'; /** 读取服务健康检查与构建标识;请求支持随壳层卸载取消。 */ -export const getHealth = async (options?: RequestControlOptions): Promise => get('/health', undefined, options); +export const getHealth = async (options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制健康检查请求的取消和超时。 */ signal => contractClient.GET('/health', { signal }), options); export type { BuildInfo } from './types'; diff --git a/frontend/app/features/system/types.ts b/frontend/app/features/system/types.ts index 93f8aca..7e06d9f 100644 --- a/frontend/app/features/system/types.ts +++ b/frontend/app/features/system/types.ts @@ -4,4 +4,10 @@ export interface BuildInfo { version: string; // commit 是当前服务对应的提交标识。 commit: string; + /** status 表示服务总体健康状态。 */ + status?: string; + /** database 表示数据库连接状态。 */ + database?: string; + /** build_time 表示构建时间。 */ + build_time?: string; } diff --git a/frontend/shared/api-contract/client.ts b/frontend/shared/api-contract/client.ts index 210f67e..cde2ec3 100644 --- a/frontend/shared/api-contract/client.ts +++ b/frontend/shared/api-contract/client.ts @@ -30,8 +30,13 @@ const contractFetch: typeof fetch = async (input, init) => { const requestURL = new URL(typeof input === 'string' ? input : input instanceof URL ? input.toString() : input.url); // request 是合并 openapi-fetch 已构造请求与可选 init 后的完整请求对象。 const request = input instanceof Request ? input : new Request(input, init); - // body 是恢复为文本的 JSON 请求载荷;GET/HEAD 不能携带请求体。 - const body = request.method === 'GET' || request.method === 'HEAD' ? undefined : await request.clone().text(); + // body 是按内容类型恢复的请求载荷;GET/HEAD 无请求体,multipart 必须保留原始 FormData 边界。 + const contentType = request.headers.get('content-type') || ''; + const body: BodyInit | undefined = request.method === 'GET' || request.method === 'HEAD' + ? undefined + : contentType.includes('multipart/form-data') + ? await request.clone().formData() + : await request.clone().text(); // fetchInput 是测试环境还原后的相对 API 地址,浏览器环境继续保留绝对 origin。 const fetchInput = requestURL.origin === 'http://localhost' ? `${requestURL.pathname}${requestURL.search}` : input; // response 是使用旧 client 等价方法、请求体、取消信号和 Cookie 策略发出的 HTTP 响应。 diff --git a/frontend/shared/api-contract/generated/schema.ts b/frontend/shared/api-contract/generated/schema.ts index 7eb6589..5fc959f 100644 --- a/frontend/shared/api-contract/generated/schema.ts +++ b/frontend/shared/api-contract/generated/schema.ts @@ -1813,6 +1813,21 @@ export interface components { ApiResponse: { success: boolean; }; + HealthResponse: { + /** @enum {string} */ + status: "ok"; + /** @enum {string} */ + database: "ok"; + version: string; + commit: string; + build_time?: string; + }; + HealthDegradedResponse: { + /** @enum {string} */ + status: "degraded"; + /** @enum {string} */ + database: "unavailable"; + }; SessionResponse: { success: boolean; token?: string | null; @@ -1982,6 +1997,295 @@ export interface components { SystemSettingsResponse: { [key: string]: string | number | boolean; }; + ChatSession: { + account_id: string; + chat_id: string; + buyer_id: string; + buyer_name: string; + buyer_avatar_url?: string; + item_id?: string; + item_title?: string; + last_message: string; + last_message_at: number; + unread_count: number; + }; + ChatMessage: { + id: number; + account_id: string; + chat_id: string; + message_key: string; + /** @enum {string} */ + direction: "incoming" | "outgoing"; + sender_id: string; + sender_name: string; + /** @enum {string} */ + message_type: "text" | "image" | "video" | "system"; + content: string; + /** @enum {string} */ + status: "received" | "sending" | "sent" | "failed"; + read_status?: number; + read_at?: number; + sent_at: number; + }; + ChatSessionPage: { + sessions: components["schemas"]["ChatSession"][]; + has_more: boolean; + next_cursor?: number; + }; + ChatMessagePage: { + messages: components["schemas"]["ChatMessage"][]; + has_more: boolean; + next_cursor?: number; + session?: components["schemas"]["ChatSession"]; + }; + ChatMessageEnvelope: { + message: components["schemas"]["ChatMessage"]; + }; + ChatReadyEvent: { + /** @enum {string} */ + type: "ready"; + at: number; + }; + ChatEvent: { + /** @enum {string} */ + type: "message.created" | "message.updated"; + message?: components["schemas"]["ChatMessage"]; + session?: components["schemas"]["ChatSession"]; + }; + ChatWebSocketEvent: components["schemas"]["ChatReadyEvent"] | components["schemas"]["ChatEvent"]; + ChatMessageRequest: { + account_id: string; + chat_id: string; + buyer_id: string; + buyer_name?: string; + item_id?: string; + item_title?: string; + text: string; + }; + ChatReadRequest: { + account_id: string; + chat_id: string; + message_ids?: { + [key: string]: string | number; + }[]; + }; + OrderDTO: { + order_id: string; + item_id: string; + item_title: string; + item_image: string; + buyer_id: string; + spec_name: string; + spec_value: string; + quantity: string; + amount: string; + order_status: string; + status: string; + cookie_id: string; + is_bargain: number; + system_shipped: boolean; + receiver_name: string; + receiver_phone: string; + receiver_address: string; + receiver_city: string; + created_at: string; + updated_at: string; + }; + OrderListResponse: { + success: boolean; + data: components["schemas"]["OrderDTO"][]; + total: number; + page: number; + page_size: number; + total_pages: number; + }; + OrderDetailResponse: components["schemas"]["OrderDTO"] & { + success: boolean; + data: components["schemas"]["OrderDTO"]; + }; + OrderUpdateRequest: { + order_status?: string; + status?: string; + item_id?: string; + buyer_id?: string; + spec_name?: string; + spec_value?: string; + quantity?: string | number; + amount?: string | number; + receiver_name?: string; + receiver_phone?: string; + receiver_address?: string; + receiver_city?: string; + chat_id?: string; + system_shipped?: boolean; + item_title?: string; + }; + OrderRefreshDetail: { + quantity: string; + spec_name: string; + spec_value: string; + order_status: string; + amount: string; + }; + OrderSingleRefreshResponse: { + success: boolean; + message: string; + order: components["schemas"]["OrderRefreshDetail"]; + }; + OrderRefreshResult: { + success: boolean; + cookie_id?: string; + stage?: string; + message?: string; + error?: string; + discovered?: number; + updated?: number; + soft_deleted?: boolean; + order_id?: string; + old_status?: string; + new_status?: string; + }; + OrderRefreshSummary: { + discovered: number; + list_updated: number; + soft_deleted: number; + detail_total: number; + total: number; + updated: number; + no_change: number; + failed: number; + }; + OrderRefreshResponse: { + partial_failure: boolean; + message: string; + summary: components["schemas"]["OrderRefreshSummary"]; + results: components["schemas"]["OrderRefreshResult"][]; + }; + OrderRefreshJobStartResponse: { + success: boolean; + job_id: string; + /** @enum {string} */ + status: "queued" | "running"; + }; + OrderRefreshJobStatusResponse: { + success: boolean; + job_id: string; + /** @enum {string} */ + status: "queued" | "running" | "succeeded" | "failed" | "cancelled"; + error_message?: string; + result?: components["schemas"]["OrderRefreshResponse"]; + }; + OrderRefreshJobCancelResponse: { + success: boolean; + job_id: string; + /** @enum {string} */ + status: "cancelled"; + }; + ManualShipRequest: { + order_ids: string[]; + /** @enum {string} */ + ship_mode: "status_only" | "full_delivery"; + }; + OrderBatchResult: { + order_id?: string; + status?: string; + success?: boolean; + message: string; + cookie_id?: string; + reconciliation_id?: string; + reconciliation_warning?: string; + stage?: string; + }; + OrderBatchResponse: { + partial_failure: boolean; + message: string; + total?: number; + success_count: number; + failed_count: number; + results: components["schemas"]["OrderBatchResult"][]; + }; + AdminStatsResponse: { + total_users: number; + total_cookies: number; + active_cookies: number; + total_cards: number; + total_keywords: number; + total_orders: number; + }; + AdminUser: { + id: number; + username: string; + email: string; + is_active: boolean; + is_admin: boolean; + created_at: string; + cookie_count: number; + }; + AdminCookie: { + id: string; + user_id: number; + remark: string; + created_at: string; + owner: string; + enabled: boolean; + }; + AdminTask: { + id: string; + name: string; + /** @enum {string} */ + state: "running" | "succeeded" | "failed" | "canceled" | "timed_out"; + /** Format: date-time */ + started_at: string; + /** Format: date-time */ + finished_at?: string; + /** Format: date-time */ + deadline_at?: string; + }; + DashboardStatsResponse: { + total_cookies: number; + active_cookies: number; + total_cards: number; + available_card_stock: number; + total_keywords: number; + total_orders: number; + }; + AnalyticsResponse: { + revenue_stats: { + total_orders: number; + total_amount: number; + avg_amount: number; + unique_buyers: number; + unique_items: number; + }; + daily_stats: { + date: string; + order_count: number; + amount: number; + }[]; + status_stats: { + status: string; + count: number; + amount: number; + }[]; + city_stats: { + city: string; + order_count: number; + total_amount: number; + }[]; + item_stats: { + item_id: string; + order_count: number; + total_amount: number; + avg_amount: number; + }[]; + }; + ValidOrdersResponse: { + orders: components["schemas"]["OrderDTO"][]; + total: number; + page: number; + page_size: number; + truncated: boolean; + }; SessionStatusResponse: { authenticated: boolean; initialized: boolean; @@ -3553,7 +3857,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AdminCookie"][]; }; }; /** @description 统一错误响应 */ @@ -3748,7 +4052,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AdminStatsResponse"]; }; }; /** @description 统一错误响应 */ @@ -3800,7 +4104,9 @@ export interface operations { }; getApiV1AdminTasks: { parameters: { - query?: never; + query?: { + limit?: number; + }; header?: never; path?: never; cookie?: never; @@ -3813,7 +4119,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AdminTask"][]; }; }; /** @description 统一错误响应 */ @@ -3878,7 +4184,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AdminUser"][]; }; }; /** @description 统一错误响应 */ @@ -3933,7 +4239,7 @@ export interface operations { query?: never; header?: never; path: { - user_id: string; + user_id: number; }; cookie?: never; }; @@ -3945,7 +4251,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OperationResponse"]; }; }; /** @description 统一错误响应 */ @@ -4010,7 +4316,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["DashboardStatsResponse"]; }; }; /** @description 统一错误响应 */ @@ -4062,7 +4368,11 @@ export interface operations { }; getApiV1AnalyticsOrders: { parameters: { - query?: never; + query: { + start_date: string; + end_date: string; + timezone_offset_minutes?: number; + }; header?: never; path?: never; cookie?: never; @@ -4075,7 +4385,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["AnalyticsResponse"]; }; }; /** @description 统一错误响应 */ @@ -4127,7 +4437,13 @@ export interface operations { }; getApiV1AnalyticsOrdersValid: { parameters: { - query?: never; + query: { + start_date: string; + end_date: string; + timezone_offset_minutes?: number; + page?: number; + page_size?: number; + }; header?: never; path?: never; cookie?: never; @@ -4140,7 +4456,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ValidOrdersResponse"]; }; }; /** @description 统一错误响应 */ @@ -4324,7 +4640,14 @@ export interface operations { }; getApiV1AutomationRules: { parameters: { - query?: never; + query?: { + page?: number; + page_size?: number; + cookie_id?: string; + trigger_type?: string; + enabled?: boolean; + search?: string; + }; header?: never; path?: never; cookie?: never; @@ -5190,15 +5513,29 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "multipart/form-data": { + account_id: string; + chat_id: string; + buyer_id: string; + buyer_name?: string; + buyer_avatar_url?: string; + item_id?: string; + item_title?: string; + /** Format: binary */ + image: string; + }; + }; + }; responses: { /** @description 成功 */ - 200: { + 201: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ChatMessageEnvelope"]; }; }; /** @description 统一错误响应 */ @@ -5250,7 +5587,13 @@ export interface operations { }; getApiV1ChatMessages: { parameters: { - query?: never; + query: { + account_id: string; + chat_id: string; + cursor?: number; + before_id?: number; + limit?: number; + }; header?: never; path?: never; cookie?: never; @@ -5263,7 +5606,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ChatMessagePage"]; }; }; /** @description 统一错误响应 */ @@ -5320,15 +5663,19 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["ChatMessageRequest"]; + }; + }; responses: { /** @description 成功 */ - 200: { + 201: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ChatMessageEnvelope"]; }; }; /** @description 统一错误响应 */ @@ -5385,7 +5732,11 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["ChatReadRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -5393,7 +5744,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OperationResponse"]; }; }; /** @description 统一错误响应 */ @@ -5445,7 +5796,12 @@ export interface operations { }; getApiV1ChatSessions: { parameters: { - query?: never; + query: { + account_id: string; + cursor?: number; + refresh?: 0 | 1; + limit?: number; + }; header?: never; path?: never; cookie?: never; @@ -5458,7 +5814,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["ChatSessionPage"]; }; }; /** @description 统一错误响应 */ @@ -5971,7 +6327,9 @@ export interface operations { }; getApiV1Items: { parameters: { - query?: never; + query?: { + cookie_id?: string; + }; header?: never; path?: never; cookie?: never; @@ -6705,7 +7063,9 @@ export interface operations { }; getApiV1ItemsPublishBatches: { parameters: { - query?: never; + query?: { + limit?: number; + }; header?: never; path?: never; cookie?: never; @@ -8029,7 +8389,13 @@ export interface operations { }; getApiV1Orders: { parameters: { - query?: never; + query?: { + cookie_id?: string; + status?: string; + search?: string; + page?: number; + page_size?: number; + }; header?: never; path?: never; cookie?: never; @@ -8042,7 +8408,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OrderListResponse"]; }; }; /** @description 统一错误响应 */ @@ -8109,7 +8475,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OrderDetailResponse"]; }; }; /** @description 统一错误响应 */ @@ -8168,7 +8534,11 @@ export interface operations { }; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["OrderUpdateRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -8176,7 +8546,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OperationResponse"]; }; }; /** @description 统一错误响应 */ @@ -8310,7 +8680,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OrderSingleRefreshResponse"]; }; }; /** @description 统一错误响应 */ @@ -8367,7 +8737,15 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "multipart/form-data": { + /** Format: binary */ + file?: string; + }; + "application/json": components["schemas"]["OrderUpdateRequest"][]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -8375,7 +8753,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OrderBatchResponse"]; }; }; /** @description 统一错误响应 */ @@ -8432,7 +8810,11 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "application/json": components["schemas"]["ManualShipRequest"]; + }; + }; responses: { /** @description 成功 */ 200: { @@ -8440,7 +8822,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OrderBatchResponse"]; }; }; /** @description 统一错误响应 */ @@ -8497,15 +8879,22 @@ export interface operations { path?: never; cookie?: never; }; - requestBody?: never; + requestBody: { + content: { + "multipart/form-data": { + cookie_id?: string; + status?: string; + }; + }; + }; responses: { /** @description 成功 */ - 200: { + 202: { headers: { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OrderRefreshJobStartResponse"]; }; }; /** @description 统一错误响应 */ @@ -8572,7 +8961,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OrderRefreshJobStatusResponse"]; }; }; /** @description 统一错误响应 */ @@ -8639,7 +9028,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["OrderRefreshJobCancelResponse"]; }; }; /** @description 统一错误响应 */ @@ -11155,7 +11544,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["HealthResponse"]; }; }; /** @description 统一错误响应 */ @@ -11203,6 +11592,15 @@ export interface operations { "application/json": components["schemas"]["ErrorResponse"]; }; }; + /** @description 数据库不可用 */ + 503: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HealthDegradedResponse"]; + }; + }; }; }; } diff --git a/frontend/shared/api-contract/transport.ts b/frontend/shared/api-contract/transport.ts index 0a54d68..9893b8b 100644 --- a/frontend/shared/api-contract/transport.ts +++ b/frontend/shared/api-contract/transport.ts @@ -1532,7 +1532,8 @@ export interface OrderRefreshResultResponse { /** 更新的订单数量。 */ updated?: number; /** 标记删除的订单数量。 */ - soft_deleted?: number; + /** soft_deleted 表示该订单是否已被本次刷新标记为软删除。 */ + soft_deleted?: boolean; /** 订单平台标识。 */ order_id?: string; /** 结果错误说明。 */ diff --git a/internal/server/openapi_response_contract_test.go b/internal/server/openapi_response_contract_test.go index 185f65c..6475302 100644 --- a/internal/server/openapi_response_contract_test.go +++ b/internal/server/openapi_response_contract_test.go @@ -59,6 +59,15 @@ func assertOpenAPISuccessResponse(t *testing.T, request *http.Request, recorder assertOpenAPIResponse(t, request, recorder) } +// assertOpenAPIExpectedStatusResponse 验证非 200 成功状态的真实响应仍符合 operation 契约。 +func assertOpenAPIExpectedStatusResponse(t *testing.T, request *http.Request, recorder *httptest.ResponseRecorder, wantStatus int) { + t.Helper() + if recorder.Code != wantStatus { + t.Fatalf("成功响应状态错误: %s %s status=%d want=%d body=%s", request.Method, request.URL.Path, recorder.Code, wantStatus, recorder.Body.String()) + } + assertOpenAPIResponse(t, request, recorder) +} + // TestOpenAPISessionAndQRResponses 验证阶段二会话与二维码主链路的成功、未认证和风控响应均满足真实契约。 func TestOpenAPISessionAndQRResponses(t *testing.T) { // srv、store、cleanup 分别是测试 Server、持久化夹具和资源释放函数。 @@ -206,3 +215,88 @@ func TestOpenAPIAccountAndSystemResponses(t *testing.T) { handler.ServeHTTP(updateSystemRecorder, updateSystemRequest) assertOpenAPISuccessResponse(t, updateSystemRequest, updateSystemRecorder) } + +// TestOpenAPIQueryChatAndOrderResponses 验证阶段三仪表盘、聊天、订单查询和异步刷新任务符合真实 OpenAPI 响应契约。 +func TestOpenAPIQueryChatAndOrderResponses(t *testing.T) { + // srv、_、cleanup 分别是测试 Server、无需直接访问的存储和测试资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是包含阶段三版本化路由的真实 chi Router。 + handler := srv.Router() + // sessionCookie 是管理员会话 Cookie,用于受保护查询成功场景。 + sessionCookie := loginHelper(t, handler) + // unauthenticatedRequest 是缺少会话的订单查询,必须保持统一错误 envelope。 + unauthenticatedRequest := httptest.NewRequest(http.MethodGet, "/api/v1/orders", nil) + // unauthenticatedRecorder 是捕获未认证订单查询响应的记录器。 + unauthenticatedRecorder := httptest.NewRecorder() + handler.ServeHTTP(unauthenticatedRecorder, unauthenticatedRequest) + assertOpenAPIResponse(t, unauthenticatedRequest, unauthenticatedRecorder) + + // dashboardRequest 是读取当前用户仪表盘统计的成功请求。 + dashboardRequest := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/dashboard", nil) + dashboardRequest.AddCookie(sessionCookie) + // dashboardRecorder 是捕获仪表盘统计响应的记录器。 + dashboardRecorder := httptest.NewRecorder() + handler.ServeHTTP(dashboardRecorder, dashboardRequest) + assertOpenAPISuccessResponse(t, dashboardRequest, dashboardRecorder) + + // analyticsRequest 是带日期和时区参数的订单分析成功请求。 + analyticsRequest := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/orders?start_date=2026-01-01&end_date=2026-01-31&timezone_offset_minutes=480", nil) + analyticsRequest.AddCookie(sessionCookie) + // analyticsRecorder 是捕获订单分析响应的记录器。 + analyticsRecorder := httptest.NewRecorder() + handler.ServeHTTP(analyticsRecorder, analyticsRequest) + assertOpenAPISuccessResponse(t, analyticsRequest, analyticsRecorder) + + // orderListRequest 是带稳定分页参数的订单查询成功请求。 + orderListRequest := httptest.NewRequest(http.MethodGet, "/api/v1/orders?page=1&page_size=20", nil) + orderListRequest.AddCookie(sessionCookie) + // orderListRecorder 是捕获订单分页响应的记录器。 + orderListRecorder := httptest.NewRecorder() + handler.ServeHTTP(orderListRecorder, orderListRequest) + assertOpenAPISuccessResponse(t, orderListRequest, orderListRecorder) + + // chatSessionsRequest 是带账号和游标参数的聊天会话分页成功请求。 + chatSessionsRequest := httptest.NewRequest(http.MethodGet, "/api/v1/chat/sessions?account_id=acc1&cursor=0", nil) + chatSessionsRequest.AddCookie(sessionCookie) + // chatSessionsRecorder 是捕获聊天会话分页响应的记录器。 + chatSessionsRecorder := httptest.NewRecorder() + handler.ServeHTTP(chatSessionsRecorder, chatSessionsRequest) + assertOpenAPISuccessResponse(t, chatSessionsRequest, chatSessionsRecorder) + + // refreshRequest 是创建订单刷新后台任务的 multipart 成功请求。 + refreshRequest := httptest.NewRequest(http.MethodPost, "/api/v1/orders/refresh", strings.NewReader("--openapi\r\nContent-Disposition: form-data; name=\"cookie_id\"\r\n\r\nacc1\r\n--openapi--\r\n")) + refreshRequest.Header.Set("Content-Type", "multipart/form-data; boundary=openapi") + refreshRequest.AddCookie(sessionCookie) + // refreshRecorder 是捕获异步刷新任务创建响应的记录器。 + refreshRecorder := httptest.NewRecorder() + handler.ServeHTTP(refreshRecorder, refreshRequest) + assertOpenAPIExpectedStatusResponse(t, refreshRequest, refreshRecorder, http.StatusAccepted) + + // adminUsersRequest 是管理员读取用户摘要的成功请求。 + adminUsersRequest := httptest.NewRequest(http.MethodGet, "/api/v1/admin/users", nil) + adminUsersRequest.AddCookie(sessionCookie) + // adminUsersRecorder 捕获管理员用户摘要响应。 + adminUsersRecorder := httptest.NewRecorder() + handler.ServeHTTP(adminUsersRecorder, adminUsersRequest) + assertOpenAPISuccessResponse(t, adminUsersRequest, adminUsersRecorder) + + // adminCookiesRequest 是管理员读取账号非敏感摘要的成功请求。 + adminCookiesRequest := httptest.NewRequest(http.MethodGet, "/api/v1/admin/cookies", nil) + adminCookiesRequest.AddCookie(sessionCookie) + // adminCookiesRecorder 捕获管理员账号摘要响应。 + adminCookiesRecorder := httptest.NewRecorder() + handler.ServeHTTP(adminCookiesRecorder, adminCookiesRequest) + assertOpenAPISuccessResponse(t, adminCookiesRequest, adminCookiesRecorder) + if strings.Contains(adminCookiesRecorder.Body.String(), "cookie_value") || strings.Contains(adminCookiesRecorder.Body.String(), "password") { + t.Fatalf("管理员账号摘要泄漏敏感字段: %s", adminCookiesRecorder.Body.String()) + } + + // adminTasksRequest 是管理员读取后台任务状态的成功请求。 + adminTasksRequest := httptest.NewRequest(http.MethodGet, "/api/v1/admin/tasks?limit=1", nil) + adminTasksRequest.AddCookie(sessionCookie) + // adminTasksRecorder 捕获后台任务状态响应。 + adminTasksRecorder := httptest.NewRecorder() + handler.ServeHTTP(adminTasksRecorder, adminTasksRequest) + assertOpenAPISuccessResponse(t, adminTasksRequest, adminTasksRecorder) +} diff --git a/internal/server/success_contract_test.go b/internal/server/success_contract_test.go index c6fb7ca..1475c92 100644 --- a/internal/server/success_contract_test.go +++ b/internal/server/success_contract_test.go @@ -2,8 +2,11 @@ package server import ( "encoding/json" + "path/filepath" "testing" + "github.com/getkin/kin-openapi/openapi3" + chatapp "xianyu-go/internal/application/chat" ) @@ -28,7 +31,7 @@ func TestChatEventDTOUsesFrontendContract(t *testing.T) { // event 保存带消息与会话的应用层实时事件。 event := chatapp.Event{ Type: "message.created", - Message: &chatapp.Message{AccountID: "account-1", ChatID: "chat-1", MessageKey: "message-1", Direction: "incoming", Status: "received", SentAt: 9}, + Message: &chatapp.Message{AccountID: "account-1", ChatID: "chat-1", MessageKey: "message-1", Direction: "incoming", SenderID: "buyer-1", SenderName: "买家", MessageType: "text", Status: "received", SentAt: 9}, Session: &chatapp.Session{AccountID: "account-1", ChatID: "chat-1", BuyerID: "buyer-1", BuyerName: "买家"}, } // encoded、marshalErr 分别保存 DTO 编码结果和编码错误。 @@ -52,4 +55,26 @@ func TestChatEventDTOUsesFrontendContract(t *testing.T) { if !sessionOK || session["account_id"] != "account-1" || session["chat_id"] != "chat-1" || session["AccountID"] != nil { t.Fatalf("会话 WebSocket 契约错误: %#v", payload["session"]) } + // specPath 是测试包相对仓库根目录的唯一 OpenAPI 契约位置。 + specPath := filepath.Join("..", "..", "api", "openapi.yaml") + // document、loadErr 分别保存加载后的 OpenAPI 文档和读取失败原因。 + document, loadErr := openapi3.NewLoader().LoadFromFile(specPath) + if loadErr != nil { + t.Fatalf("加载 OpenAPI WebSocket 契约: %v", loadErr) + } + // eventSchemaRef 保存 WebSocket 推送帧的具名 schema 引用。 + eventSchemaRef := document.Components.Schemas["ChatWebSocketEvent"] + if eventSchemaRef == nil || eventSchemaRef.Value == nil { + t.Fatal("OpenAPI 缺少 ChatWebSocketEvent schema") + } + // validationErr 确保真实聊天 DTO 的字段名与类型由同一 OpenAPI schema 约束。 + if validationErr := eventSchemaRef.Value.VisitJSON(payload, openapi3.EnableJSONSchema2020()); validationErr != nil { + t.Fatalf("聊天 WebSocket 事件不符合 OpenAPI: %v", validationErr) + } + // readyPayload 保存服务端在握手完成后立即发送的就绪帧。 + readyPayload := map[string]any{"type": "ready", "at": int64(9)} + // readyValidationErr 确保握手后的第一条实时消息也被同一 OpenAPI schema 覆盖。 + if readyValidationErr := eventSchemaRef.Value.VisitJSON(readyPayload, openapi3.EnableJSONSchema2020()); readyValidationErr != nil { + t.Fatalf("聊天 WebSocket 就绪事件不符合 OpenAPI: %v", readyValidationErr) + } } diff --git a/tools/apicheck/main.go b/tools/apicheck/main.go index a6afd78..fd1b877 100644 --- a/tools/apicheck/main.go +++ b/tools/apicheck/main.go @@ -66,7 +66,7 @@ func check(root string) ([]string, error) { if operation.OperationID == "" { violations = append(violations, fmt.Sprintf("%s %s 缺少 operationId", strings.ToUpper(method), path)) } - if operation.Responses == nil || operation.Responses.Value("200") == nil && operation.Responses.Value("101") == nil { + if operation.Responses == nil || !hasSuccessResponse(operation.Responses) { violations = append(violations, fmt.Sprintf("%s %s 缺少成功响应", strings.ToUpper(method), path)) } if operation.Responses == nil || operation.Responses.Value("400") == nil || operation.Responses.Value("401") == nil { @@ -105,6 +105,20 @@ func check(root string) ([]string, error) { return violations, nil } +// hasSuccessResponse 判断 operation 是否声明了至少一个合法成功或协议升级状态。 +func hasSuccessResponse(responses *openapi3.Responses) bool { + if responses == nil { + return false + } + // status 是当前允许声明为操作成功的 HTTP 或协议升级状态码。 + for _, status := range []string{"200", "201", "202", "204", "101"} { + if responses.Value(status) != nil { + return true + } + } + return false +} + // sourceRoutes 从版本化 route 文件和动态订单刷新挂载点收集真实路由。 func sourceRoutes(serverDir string) (map[routeKey]struct{}, error) { // methodPattern 匹配版本化文件中的静态 chi 方法调用。