diff --git a/api/openapi.yaml b/api/openapi.yaml index 56b5626..1be4dba 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -3903,7 +3903,9 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + type: array + items: + $ref: '#/components/schemas/NotificationChannelResponse' '400': description: 统一错误响应 content: @@ -4129,7 +4131,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/ApiResponse' + $ref: '#/components/schemas/NotificationBindingsByAccount' '400': description: 统一错误响应 content: @@ -6649,6 +6651,30 @@ components: is_multi_spec: {type: boolean} multi_quantity_delivery: {type: boolean} is_multi_qty_ship: {type: boolean} + NotificationChannelResponse: + type: object + required: [id, name, type, enabled] + properties: + id: {type: integer} + name: {type: string} + type: {type: string} + event_types: {type: string} + enabled: {type: boolean} + user_id: {type: integer} + NotificationBinding: + type: object + required: [id, channel_id, channel_name, enabled] + properties: + id: {type: integer} + channel_id: {type: integer} + channel_name: {type: string} + enabled: {type: boolean} + NotificationBindingsByAccount: + type: object + additionalProperties: + type: array + items: + $ref: '#/components/schemas/NotificationBinding' SessionResponse: type: object required: [success, message, is_admin] diff --git a/docs/architecture/refactoring-master-plan.md b/docs/architecture/refactoring-master-plan.md index 03e17cf..609687d 100644 --- a/docs/architecture/refactoring-master-plan.md +++ b/docs/architecture/refactoring-master-plan.md @@ -23,8 +23,8 @@ | 2. 类型化客户端与登录账号主链路 | 已完成 | session、system、accounts、QR 风控和永久关闭的 password-login 已迁移并完成真实响应校验。 | | 3. 查询、聊天与订单主链路 | 已完成 | dashboard、实际消费的 admin 摘要、chat、orders、刷新任务和 WebSocket 消息均已迁移并完成真实契约校验。 | | 4. 商品、卡券和文件传输 | 已完成 | items、批量发布、cards 和上传 adapter 已迁移;原生 FormData、取消、重试和批次隔离均保留。 | -| 5. 自动化、设置和通知动态契约 | 当前阶段 | 迁移 rules、automation、settings、notifications 和账号绑定。 | -| 6. 全量封闭与旧手写契约退场 | 待执行 | 关闭原始 HTTP client 旁路,删除手写 transport DTO 和名单式门禁。 | +| 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 72a0450..beec76f 100644 --- a/docs/architecture/refactoring-progress.md +++ b/docs/architecture/refactoring-progress.md @@ -449,3 +449,9 @@ architecturecheck: 通过;git diff --check 无输出。 - 交付范围:items、发布批次、卡券和表格上传全部改由 feature adapter 通过生成 operation 发起;FormData 在共享运行时按 multipart Content-Type 原样重建,未引入 Base64。 - 回归保护:真实 Router 测试覆盖商品、卡券列表的成功和未认证响应,以及卡券文件上传的格式错误 envelope;原有批次取消、重试、代次隔离和 CSV 下载行为保持不变。 + +### 2026-08-20 OpenAPI 契约阶段五:自动化、设置和通知动态契约 + +- 交付范围:自动化规则、回复规则、默认回复、账号计划任务、账号 AI 设置、系统设置与通知渠道/绑定均通过生成 operation 访问;UI 归一化和秘密表单状态仍留在 feature adapter。 +- 动态值:`NotificationBindingsByAccount` 使用 `additionalProperties` 限定每个账号键对应 `NotificationBinding[]`;通知渠道摘要不返回 SMTP 密码、Token 或完整秘密配置。 +- 回归保护:真实 Router 响应测试验证渠道列表与动态账号绑定映射;`make api-check`、architecturecheck、前端 typecheck/tests 与注释门禁通过。 diff --git a/frontend/app/features/accounts/accountAutomationApi.ts b/frontend/app/features/accounts/accountAutomationApi.ts index de572be..eb18c70 100644 --- a/frontend/app/features/accounts/accountAutomationApi.ts +++ b/frontend/app/features/accounts/accountAutomationApi.ts @@ -1,11 +1,2 @@ -import type { AccountTaskRunResponseEnvelope,AccountTaskSettings,AccountTaskSettingsResponse } from './api'; -import { get,post,put,type RequestControlOptions } from '../../../shared/http/client'; - -/** 获取指定账号的自动评价与自动擦亮设置。 */ -export const getAccountTaskSettings = async (accountID: string, options?: RequestControlOptions): Promise => get(`/api/v1/account-tasks/${accountID}`, undefined, options); - -/** 保存指定账号的自动评价与自动擦亮设置。 */ -export const updateAccountTaskSettings = async (accountID: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise => put(`/api/v1/account-tasks/${accountID}`, settings, options); - -/** 立即发起账号级计划任务,并使用较长超时覆盖平台执行窗口。 */ -export const runAccountTask = async (accountID: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise => post(`/api/v1/account-tasks/${accountID}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options }); +/** 账号任务 Hook 沿用历史模块路径,但全部请求实现只存在于本 feature 的 api adapter。 */ +export { getAccountTaskSettings, runAccountTask, updateAccountTaskSettings } from './api'; diff --git a/frontend/app/features/accounts/api.ts b/frontend/app/features/accounts/api.ts index 990130f..ee05eac 100644 --- a/frontend/app/features/accounts/api.ts +++ b/frontend/app/features/accounts/api.ts @@ -15,7 +15,7 @@ OperationResponse, QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse } from '../../../shared/api-contract/accounts'; import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; -import { get,post,put,type RequestControlOptions } from '../../../shared/http/client'; +import { type RequestControlOptions } from '../../../shared/http/client'; import { collectionFrom,objectFrom } from '../../../shared/http/contract'; export type * from '../../../shared/api-contract/accounts'; @@ -88,15 +88,15 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis // getAccountTaskSettings 读取账号计划任务设置。 export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise => - get(`/api/v1/account-tasks/${id}`, undefined, options); + runContractRequest(/* signal 控制账号计划任务读取的取消和超时。 */ signal => contractClient.GET('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, signal }), options) as unknown as Promise; // updateAccountTaskSettings 更新账号计划任务设置。 export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise => - put(`/api/v1/account-tasks/${id}`, settings, options); + runContractRequest(/* signal 控制账号计划任务更新的取消和超时。 */ signal => contractClient.PUT('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, body: settings as never, signal }), options) as unknown as Promise; // runAccountTask 立即执行账号计划任务。 export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise => - post(`/api/v1/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000, ...options }); + runContractRequest(/* signal 控制账号计划任务立即执行的取消和长超时。 */ signal => contractClient.POST('/api/v1/account-tasks/{cid}/run', { params: { path: { cid: id } }, body: { task_type: taskType } as never, signal }), { timeoutMs: 120_000, ...options }) as unknown as Promise; export interface AccountRuntimeStatus { @@ -322,7 +322,7 @@ export const updateAccountLoginInfo = async (id: string, data: { // getAllAISettings 读取全部人工智能设置。 export const getAllAISettings = async (options?: RequestControlOptions): Promise> => { - const response = await get('/api/v1/settings/ai-reply', undefined, options); + const response = await runContractRequest(/* signal 控制全部账号 AI 设置读取的取消和超时。 */ signal => contractClient.GET('/api/v1/settings/ai-reply', { signal }), options) as unknown; // settings 是兼容直接映射、data 包裹和 null 的账号 AI 设置索引。 return objectFrom>(response, ['settings', 'data', 'result']) || {}; }; @@ -330,7 +330,7 @@ export const getAllAISettings = async (options?: RequestControlOptions): Promise // getAccountAISettings 读取账号人工智能设置。 export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise => { - return get(`/api/v1/settings/ai-reply/${cookieId}`, undefined, options); + return runContractRequest(/* signal 控制账号 AI 设置读取的取消和超时。 */ signal => contractClient.GET('/api/v1/settings/ai-reply/{cookie_id}', { params: { path: { cookie_id: cookieId } }, signal }), options) as unknown as Promise; } // updateAccountAISettings 更新账号人工智能设置。 @@ -343,7 +343,7 @@ export const updateAccountAISettings = async (cookieId: string, settings: Partia max_bargain_rounds: settings.max_bargain_rounds ?? 3, custom_prompts: settings.custom_prompts ?? '' }; - return put(`/api/v1/settings/ai-reply/${cookieId}`, payload, options); + return runContractRequest(/* signal 控制账号 AI 设置更新的取消和超时。 */ signal => contractClient.PUT('/api/v1/settings/ai-reply/{cookie_id}', { params: { path: { cookie_id: cookieId } }, body: payload as never, signal }), options); } @@ -364,7 +364,7 @@ const parseNotificationEventTypes = (raw: unknown): NotificationEventType[] => { // getNotificationChannels 读取通知渠道。 export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** success 表示是否成功。 */ success: boolean; /** data 表示数据。 */ data?: NotificationChannel[] }> => { // result 接口响应结果,用于当前 API 处理流程。 - const result = await get('/api/v1/notifications/channels', undefined, options); + const result = await runContractRequest(/* signal 控制账号页通知渠道读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/channels', { signal }), options) as unknown; // channels 通知渠道列表,用于当前 API 处理流程。 const channels = collectionFrom(result, ['data', 'channels', 'items']).map(/* 当前回调用于处理集合元素或接口响应。 */ (item: NotificationChannelResponse) => { // parsedConfig 是列表摘要刻意不返回渠道秘密时使用的空编辑初始值。 @@ -387,7 +387,7 @@ export const getNotificationChannels = async (options?: RequestControlOptions): // 账号 ↔ 渠道 绑定(覆盖式) export const getAccountBindings = async (cookieId: string, options?: RequestControlOptions): Promise => { // response 是兼容直接绑定对象、data 包裹和 null 的通知绑定响应。 - const response = await get(`/api/v1/notifications/accounts/${cookieId}/bindings`, undefined, options); + const response = await runContractRequest(/* signal 控制账号页通知绑定读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: cookieId } }, signal }), options) as unknown; // result 是去除历史包裹后的账号通知绑定对象。 const result = objectFrom>(response, ['data', 'result']) || {}; return Array.isArray(result.channel_ids) ? result.channel_ids : []; diff --git a/frontend/app/features/notifications/api.ts b/frontend/app/features/notifications/api.ts index 717f9f7..b50c21e 100644 --- a/frontend/app/features/notifications/api.ts +++ b/frontend/app/features/notifications/api.ts @@ -1,5 +1,6 @@ import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from '../../../shared/api-contract/notifications'; -import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client'; +import { type RequestControlOptions } from '../../../shared/http/client'; +import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; export type * from '../../../shared/api-contract/notifications'; /** 通知渠道写入时使用的具名请求 DTO。 */ @@ -49,14 +50,14 @@ const toNotificationChannel = (channel: NotificationChannelResponse): Notificati /** 获取全部通知渠道并转换为编辑器模型。 */ export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** 操作是否完成。 */ success: boolean; /** 渠道列表。 */ data: NotificationChannel[] }> => { // response 是渠道列表的原始传输响应。 - const response = await get('/api/v1/notifications/channels', undefined, options); + const response = await runContractRequest(/* signal 控制通知渠道列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/channels', { signal }), options) as unknown as NotificationChannelResponse[] | { /** channels 是后端包装的渠道列表。 */ data?: NotificationChannelResponse[]; /** channels 是兼容字段。 */ channels?: NotificationChannelResponse[] }; // channels 是兼容直接数组与包装数组后的原始渠道列表。 const channels = Array.isArray(response) ? response : response.data || response.channels || []; return { success: true, data: channels.map(toNotificationChannel) }; }; /** 创建通知渠道,并在传输边界序列化配置与事件。 */ -export const createNotificationChannel = async (data: Required> & NotificationChannelRequest, options?: RequestControlOptions): Promise => post('/api/v1/notifications/channels', { ...data, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types) }, options); +export const createNotificationChannel = async (data: Required> & NotificationChannelRequest, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制通知渠道创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels', { body: { ...data, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types) } as never, signal }), options) as unknown as Promise; /** 更新通知渠道的可编辑字段。 */ export const updateNotificationChannel = async (channelID: string, data: NotificationChannelRequest, options?: RequestControlOptions): Promise => { @@ -64,16 +65,16 @@ export const updateNotificationChannel = async (channelID: string, data: Notific const payload: Record = { ...data }; if ('config' in data) payload.config = JSON.stringify(data.config); if ('event_types' in data) payload.event_types = stringifyNotificationEventTypes(data.event_types); - return put(`/api/v1/notifications/channels/${channelID}`, payload, options); + return runContractRequest(/* signal 控制通知渠道更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/notifications/channels/{channel_id}', { params: { path: { channel_id: channelID } }, body: payload as never, signal }), options) as unknown as Promise; }; /** 删除指定通知渠道。 */ -export const deleteNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise => del(`/api/v1/notifications/channels/${channelID}`, undefined, options); +export const deleteNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制通知渠道删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/notifications/channels/{channel_id}', { params: { path: { channel_id: channelID } }, signal }), options); /** 获取并展平按账号分组存储的消息通知绑定。 */ export const getMessageNotifications = async (): Promise<{ /** 操作是否完成。 */ success: boolean; /** 展平后的绑定列表。 */ data: NotificationBinding[] }> => { // response 是按账号 ID 分组的通知绑定响应。 - const response = await get>('/api/v1/notifications/messages'); + const response = await runContractRequest(/* signal 控制消息通知列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/messages', { signal })) as unknown as Record; // bindings 是供页面直接渲染的扁平绑定集合。 const bindings: NotificationBinding[] = []; for (const /* accountID、channelBindings 是当前账号及其原始渠道绑定列表。 */ [accountID, channelBindings] of Object.entries(response || {})) { @@ -84,26 +85,26 @@ export const getMessageNotifications = async (): Promise<{ /** 操作是否完 }; /** 设置单个账号与渠道之间的启用状态。 */ -export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_id: channelID, enabled }); +export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise => runContractRequest(/* signal 控制单账号通知开关更新请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_id: channelID, enabled } as never, signal })); /** 删除单个消息通知绑定。 */ -export const deleteMessageNotification = async (notificationID: string): Promise => del(`/api/v1/notifications/messages/${notificationID}`); +export const deleteMessageNotification = async (notificationID: string): Promise => runContractRequest(/* signal 控制单条通知删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/notifications/messages/{notification_id}', { params: { path: { notification_id: notificationID } }, signal })); /** 删除指定账号的全部消息通知绑定。 */ -export const deleteAccountNotifications = async (accountID: string): Promise => del(`/api/v1/notifications/messages/account/${accountID}`); +export const deleteAccountNotifications = async (accountID: string): Promise => runContractRequest(/* signal 控制账号通知清理请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/notifications/messages/account/{cid}', { params: { path: { cid: accountID } }, signal })); /** 读取指定账号已绑定的通知渠道主键。 */ export const getAccountBindings = async (accountID: string, options?: RequestControlOptions): Promise => { // response 是账号渠道绑定的具名响应。 - const response = await get<{ /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[]; /** data 是兼容包装。 */ data?: { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[] } }>(`/api/v1/notifications/accounts/${accountID}/bindings`, undefined, options); + const response = await runContractRequest(/* signal 控制账号通知绑定读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, signal }), options) as unknown as { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[]; /** data 是兼容包装。 */ data?: { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[] } }; return Array.isArray(response.channel_ids) ? response.channel_ids : Array.isArray(response.data?.channel_ids) ? response.data.channel_ids : []; }; /** 覆盖保存指定账号的通知渠道绑定。 */ -export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise => post(`/api/v1/notifications/accounts/${accountID}/bindings`, { channel_ids: channelIDs }); +export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise => runContractRequest(/* signal 控制账号通知绑定覆盖请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_ids: channelIDs } as never, signal })); /** 向单一通知渠道发送测试投递。 */ -export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise => post(`/api/v1/notifications/channels/${channelID}/test`, {}, options); +export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制通知渠道测试投递的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels/{channel_id}/test', { params: { path: { channel_id: channelID } }, body: {} as never, signal }), options); /** 将系统配置响应转换为通知 SMTP 表单使用的状态模型。 */ const normalizeSystemSettings = (settings: Record): SystemSettings => { @@ -120,9 +121,9 @@ const normalizeSystemSettings = (settings: Record): SystemSetti /** 获取通知 SMTP 编辑器需要的系统设置。 */ export const getSystemSettings = async (options?: RequestControlOptions): Promise => { // response 是服务端可能以 data 包装的系统设置响应。 - const response = await get<{ /** data 是当前服务端系统设置。 */ data?: Record; /** settings 是兼容字段。 */ settings?: Record } & Record>('/api/v1/settings/system', undefined, options); + const response = await runContractRequest(/* signal 控制系统设置读取的取消和超时。 */ signal => contractClient.GET('/api/v1/settings/system', { signal }), options) as unknown as { /** data 是当前服务端系统设置。 */ data?: Record; /** settings 是兼容字段。 */ settings?: Record } & Record; return normalizeSystemSettings(response.data || response.settings || response); }; /** 保存通知 SMTP 编辑器提交的系统设置。 */ -export const updateSystemSettings = async (settings: Partial, options?: RequestControlOptions): Promise => put('/api/v1/settings/system', settings, options); +export const updateSystemSettings = async (settings: Partial, options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制系统设置更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/settings/system', { body: settings as never, signal }), options); diff --git a/frontend/app/features/rules/api.ts b/frontend/app/features/rules/api.ts index 5108cca..060be16 100644 --- a/frontend/app/features/rules/api.ts +++ b/frontend/app/features/rules/api.ts @@ -15,18 +15,19 @@ PaginatedResponse, ReplyRule, ShippingRule } from '../../../shared/api-contract/automation'; -import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client'; +import { type RequestControlOptions } from '../../../shared/http/client'; +import { contractClient, runContractRequest } from '../../../shared/api-contract/client'; import { collectionFrom,objectFrom } from '../../../shared/http/contract'; export type * from '../../../shared/api-contract/automation'; /** 自动化规则筛选器读取非敏感账号摘要。 */ -export const getAccountDetails = async (options?: RequestControlOptions): Promise => get('/api/v1/accounts/details', undefined, options); +export const getAccountDetails = async (options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制规则页账号摘要读取的取消和超时。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options); /** 自动化动作编辑器读取可选卡券组。 */ -export const getCards = async (options?: RequestControlOptions): Promise => get('/api/v1/cards', undefined, options); +export const getCards = async (options?: RequestControlOptions): Promise => runContractRequest(/* signal 控制规则页卡券读取的取消和超时。 */ signal => contractClient.GET('/api/v1/cards', { signal }), options) as unknown as Promise; /** 自动化规则商品选择器读取商品索引。 */ -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; // Rules - 自动化规则 const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map(/* 当前回调用于处理集合元素或接口响应。 */ (item: any) => ({ id: String(item.id), @@ -77,7 +78,7 @@ const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map(/* // getShippingRules 读取发货规则列表。 export const getShippingRules = async (): Promise => { // res 接口响应结果,用于当前 API 处理流程。 - const res = await get('/api/v1/automation-rules'); + const res = await runContractRequest(/* signal 控制自动化规则列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/automation-rules', { signal })) as unknown; // rules 规则列表,用于当前 API 处理流程。 const rules = collectionFrom(res, ['data', 'rules', 'items']); return normalizeShippingRules(rules); @@ -102,14 +103,7 @@ export const getShippingRulesPage = async ({ pageSize = 10, }: ShippingRuleListParams = {}): Promise> => { // res 接口响应结果,用于当前 API 处理流程。 - const response = await get('/api/v1/automation-rules', { - page: requestedPage, - page_size: pageSize, - cookie_id: cookieId || undefined, - trigger_type: triggerType || undefined, - enabled, - search: search?.trim() || undefined, - }); + const response = await runContractRequest(/* signal 控制自动化规则分页读取的取消和超时。 */ signal => contractClient.GET('/api/v1/automation-rules', { params: { query: { page: requestedPage, page_size: pageSize, cookie_id: cookieId, trigger_type: triggerType, enabled, search: search?.trim() } }, signal })) as unknown; // rules 规则列表,用于当前 API 处理流程。 // page 是兼容直接分页对象和 data 包裹后的分页元数据。 const pageMeta = objectFrom>(response, ['data', 'result']) || {}; @@ -207,11 +201,13 @@ export const updateShippingRule = async (rule: Partial): Promise contractClient.PUT('/api/v1/automation-rules/{rule_id}', { params: { path: { rule_id: String(rule.id) } }, body: payload as never, signal })) + : runContractRequest(/* signal 控制自动化规则创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/automation-rules', { body: payload as never, signal })); } // deleteShippingRule 删除发货规则。 -export const deleteShippingRule = async (id: string): Promise => del(`/api/v1/automation-rules/${id}`); +export const deleteShippingRule = async (id: string): Promise => runContractRequest(/* signal 控制自动化规则删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/automation-rules/{rule_id}', { params: { path: { rule_id: id } }, signal })); export interface AutomationRunIssue { /** id 表示标识。 */ id: number; @@ -238,7 +234,7 @@ export interface DeferredAutomationIssue { // getAutomationIssues 读取自动化问题列表。 export const getAutomationIssues = async (): Promise<{ /** runs 表示运行记录。 */ runs: AutomationRunIssue[]; /** pending_tasks 表示待处理任务列表。 */ pending_tasks: DeferredAutomationIssue[] }> => { // response 是兼容直接问题对象、data 包裹和 null 的自动化问题响应。 - const response = await get('/api/v1/automation-issues'); + const response = await runContractRequest(/* signal 控制自动化问题读取的取消和超时。 */ signal => contractClient.GET('/api/v1/automation-issues', { signal })) as unknown; // result 是去除历史包裹后的自动化问题对象。 const result = objectFrom>(response, ['data', 'result']) || {}; return { @@ -249,11 +245,11 @@ export const getAutomationIssues = async (): Promise<{ /** runs 表示运行记 // resolveAutomationRun 处理自动化运行记录。 export const resolveAutomationRun = async (id: number, resolution: 'continue' | 'retry' | 'cancel'): Promise => - post(`/api/v1/automation-runs/${id}/resolve`, { resolution }); + runContractRequest(/* signal 控制自动化运行处理请求的取消和超时。 */ signal => contractClient.POST('/api/v1/automation-runs/{run_id}/resolve', { params: { path: { run_id: String(id) } }, body: { resolution } as never, signal })); // resolveDeferredAutomationTask 处理延迟自动化任务。 export const resolveDeferredAutomationTask = async (id: number, resolution: 'retry' | 'dismiss'): Promise => - post(`/api/v1/automation-pending-tasks/${id}/resolve`, { resolution }); + runContractRequest(/* signal 控制待处理自动化任务请求的取消和超时。 */ signal => contractClient.POST('/api/v1/automation-pending-tasks/{task_id}/resolve', { params: { path: { task_id: String(id) } }, body: { resolution } as never, signal })); // Rules - 关键词回复规则 (使用关键词API) type KeywordRowPayload = { @@ -278,7 +274,7 @@ const normalizeKeywordRow = (item: any): KeywordRowPayload => ({ // getKeywordRowsWithType 读取带类型的关键词规则。 const getKeywordRowsWithType = async (cookieId: string): Promise => { // existing 已有规则,用于当前 API 处理流程。 - const existing = await get(`/api/v1/reply-rules/${cookieId}/typed`); + const existing = await runContractRequest(/* signal 控制关键词规则读取的取消和超时。 */ signal => contractClient.GET('/api/v1/reply-rules/{cid}/typed', { params: { path: { cid: cookieId } }, signal })) as unknown; return collectionFrom(existing, ['data', 'items', 'rules']).map(normalizeKeywordRow); }; @@ -312,20 +308,20 @@ export const updateReplyRule = async (rule: Partial, cookieId: string image_url: type === 'image' ? (rule.image_url || '') : '', }; return rule.id - ? put(`/api/v1/reply-rules/${cookieId}/typed/${rule.id}`, payload) - : post(`/api/v1/reply-rules/${cookieId}/items`, payload); + ? runContractRequest(/* signal 控制关键词规则更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/reply-rules/{cid}/typed/{id}', { params: { path: { cid: cookieId, id: String(rule.id) } }, body: payload as never, signal })) + : runContractRequest(/* signal 控制关键词规则创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/reply-rules/{cid}/items', { params: { path: { cid: cookieId } }, body: payload as never, signal })); } // deleteReplyRule 删除回复规则。 export const deleteReplyRule = async (id: string, cookieId: string): Promise => { - return del(`/api/v1/reply-rules/${cookieId}/typed/${id}`); + return runContractRequest(/* signal 控制关键词规则删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/reply-rules/{cid}/typed/{id}', { params: { path: { cid: cookieId, id } }, signal })); } // Default Reply // getDefaultReplies 读取默认回复列表。 export const getDefaultReplies = async (): Promise> => { - const response = await get('/api/v1/default-replies'); + const response = await runContractRequest(/* signal 控制默认回复列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/default-replies', { signal })) as unknown; // replies 是兼容直接映射、data 包裹和 null 的默认回复索引。 return objectFrom>(response, ['data', 'replies', 'items']) || {}; }; @@ -333,7 +329,7 @@ export const getDefaultReplies = async (): Promise => { // result 接口响应结果,用于当前 API 处理流程。 - const response = await get(`/api/v1/default-replies/${cookieId}`); + const response = await runContractRequest(/* signal 控制默认回复读取的取消和超时。 */ signal => contractClient.GET('/api/v1/default-replies/{cid}', { params: { path: { cid: cookieId } }, signal })) as unknown; // result 是兼容直接默认回复和 data 包裹后的对象。 const result = objectFrom>(response, ['data', 'result']) || {}; return { @@ -347,20 +343,20 @@ export const getDefaultReply = async (cookieId: string): Promise = // updateDefaultReply 更新默认回复。 export const updateDefaultReply = async (cookieId: string, data: Partial): Promise => { - return put(`/api/v1/default-replies/${cookieId}`, { + return runContractRequest(/* signal 控制默认回复更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/default-replies/{cid}', { params: { path: { cid: cookieId }, }, body: { enabled: data.enabled ?? false, reply_content: data.reply_content || '', reply_once: data.reply_once ?? false, reply_image_url: data.reply_image_url || '' - }); + } as never, signal })); }; // deleteDefaultReply 删除默认回复。 export const deleteDefaultReply = async (cookieId: string): Promise => { - return del(`/api/v1/default-replies/${cookieId}`); + return runContractRequest(/* signal 控制默认回复删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/default-replies/{cid}', { params: { path: { cid: cookieId } }, signal })); }; // clearDefaultReplyRecords 清理默认回复记录。 export const clearDefaultReplyRecords = async (cookieId: string): Promise => { - return post(`/api/v1/default-replies/${cookieId}/clear-records`, {}); + return runContractRequest(/* signal 控制默认回复记录清理请求的取消和超时。 */ signal => contractClient.POST('/api/v1/default-replies/{cid}/clear-records', { params: { path: { cid: cookieId } }, body: {} as never, signal })); }; diff --git a/frontend/shared/api-contract/generated/schema.ts b/frontend/shared/api-contract/generated/schema.ts index cb084ad..641a62d 100644 --- a/frontend/shared/api-contract/generated/schema.ts +++ b/frontend/shared/api-contract/generated/schema.ts @@ -1859,6 +1859,23 @@ export interface components { multi_quantity_delivery: boolean; is_multi_qty_ship: boolean; }; + NotificationChannelResponse: { + id: number; + name: string; + type: string; + event_types?: string; + enabled: boolean; + user_id?: number; + }; + NotificationBinding: { + id: number; + channel_id: number; + channel_name: string; + enabled: boolean; + }; + NotificationBindingsByAccount: { + [key: string]: components["schemas"]["NotificationBinding"][]; + }; SessionResponse: { success: boolean; token?: string | null; @@ -7838,7 +7855,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["NotificationChannelResponse"][]; }; }; /** @description 统一错误响应 */ @@ -8169,7 +8186,7 @@ export interface operations { [name: string]: unknown; }; content: { - "application/json": components["schemas"]["ApiResponse"]; + "application/json": components["schemas"]["NotificationBindingsByAccount"]; }; }; /** @description 统一错误响应 */ diff --git a/internal/server/openapi_response_contract_test.go b/internal/server/openapi_response_contract_test.go index 193b487..edc47f9 100644 --- a/internal/server/openapi_response_contract_test.go +++ b/internal/server/openapi_response_contract_test.go @@ -342,3 +342,32 @@ func TestOpenAPIItemAndCardResponses(t *testing.T) { handler.ServeHTTP(invalidUploadRecorder, invalidUploadRequest) assertOpenAPIResponse(t, invalidUploadRequest, invalidUploadRecorder) } + +// TestOpenAPINotificationResponses 验证阶段五通知摘要和动态账号绑定键符合 OpenAPI 约束。 +func TestOpenAPINotificationResponses(t *testing.T) { + // srv、_、cleanup 分别是测试 Server、无需直接访问的存储和资源释放函数。 + srv, _, cleanup := newTestServer(t) + defer cleanup() + // handler 是包含通知版本化路由的真实 chi Router。 + handler := srv.Router() + // sessionCookie 是管理员会话 Cookie,用于读取当前用户通知资源。 + sessionCookie := loginHelper(t, handler) + // channelsRequest 是读取非敏感通知渠道摘要的成功请求。 + channelsRequest := httptest.NewRequest(http.MethodGet, "/api/v1/notifications/channels", nil) + channelsRequest.AddCookie(sessionCookie) + // channelsRecorder 捕获通知渠道摘要响应。 + channelsRecorder := httptest.NewRecorder() + handler.ServeHTTP(channelsRecorder, channelsRequest) + assertOpenAPISuccessResponse(t, channelsRequest, channelsRecorder) + if strings.Contains(channelsRecorder.Body.String(), "smtp_password") || strings.Contains(channelsRecorder.Body.String(), "token") { + t.Fatalf("通知渠道摘要泄漏秘密配置: %s", channelsRecorder.Body.String()) + } + + // bindingsRequest 是读取按账号动态键组织的通知绑定成功请求。 + bindingsRequest := httptest.NewRequest(http.MethodGet, "/api/v1/notifications/messages", nil) + bindingsRequest.AddCookie(sessionCookie) + // bindingsRecorder 捕获动态账号键通知绑定响应。 + bindingsRecorder := httptest.NewRecorder() + handler.ServeHTTP(bindingsRecorder, bindingsRequest) + assertOpenAPISuccessResponse(t, bindingsRequest, bindingsRecorder) +}