API契约:收口设置卡券通知与批量响应

This commit is contained in:
Christ committed 2026-08-14 15:34:14 +08:00
1 parent 0ca52e43ad
commit fe6fc3adb9
12 files changed
+879 -143

No files matched your search

@@ -9,8 +9,12 @@
| 会话 | `/verify`、`/logout` | `/api/v1/session`、`/api/v1/session/logout` | 旧路径保留,待前端统一请求层后迁移 |
| 账号 | `/cookies/details`、`/cookies/{cid}/...` | `/api/v1/accounts/...` | 旧路径保留,详情/设置/资料/暂停 DTO 已落地 |
| 商品 | `/items...` | `/api/v1/items...` | 旧路径保留,发布/同步/列表/详情 DTO 已落地 |
| 商品批量 | `/items/publish-batches...` | `/api/v1/items/publish-batches...` | 旧路径保留,类目推荐/预检/任务 DTO 已落地 |
| 自动化 | `/automation-rules...` | `/api/v1/automation-rules...` | 旧路径保留,规则分页/异常 DTO 已落地 |
| 订单 | `/api/orders...` | `/api/v1/orders...` | 旧路径保留,列表/详情/刷新/批量外层 DTO 已落地 |
| 设置 | `/system-settings...`、`/user-settings...`、`/ai-reply-settings...` | `/api/v1/settings/...` | 旧路径保留,变更/查询 DTO 已落地;动态键仍由边界适配 |
| 卡券 | `/cards...` | `/api/v1/cards...` | 旧路径保留,CRUD/批量 DTO 已落地 |
| 通知 | `/notification-channels...`、`/message-notifications...` | `/api/v1/notifications/...` | 旧路径保留,渠道/绑定/变更 DTO 已落地 |
| 聊天 | `/api/chat...` | `/api/v1/chat...` | 旧路径保留,会话/消息 DTO 已落地 |
## 迁移规则
@@ -26,8 +30,10 @@
- 认证会话校验使用 `sessionVerificationResponse`。
- 账号详情、设置、资料刷新和暂停查询使用 `cookieDetailResponse`、`cookieSettingsResponse`、`cookieProfileResponse` 与 `pauseDurationResponse`。
- 商品发布、同步、列表和详情使用 `itemPublishResponse`、`itemSyncResponse`、`itemPageSyncResponse`、`itemListResponse` 与 `itemDetailResponse`。
- 商品批量发布使用 `categoryRecommendationResponse`、`itemPublishBatchPreviewResponse`、`batchIDResponse`、`batchCancelResponse`、`itemPublishBatchResponse` 与 `itemPublishBatchListResponse`。
- 自动化规则分页、动作和异常列表使用 `automationRulePageResponse`、`automationRuleResponse`、`automationActionResponse` 与 `automationIssuesResponse`。
- 订单列表、详情、刷新和批量外层结果使用 `orderListResponse`、`orderDetailResponse`、`orderRefreshResponse` 与 `manualShipResponse`/`importOrdersResponse`。
- 设置、卡券和通知分别使用 `operationResponse`、`aiReplySettingsResponse`、`aiModelsResponse`、`userSettingResponse`、`cardResponse`、`cardBatchResponse`、`notificationChannelResponse`、`notificationBindingResponse` 与 `accountBindingsResponse`。
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
- React `frontend/types.ts` 与 `frontend/services/api.ts` 已同步具名成功响应类型,同时保留旧字段归一逻辑。
- 旧路径仍由现有路由提供,尚未宣称 `/api/v1` 已经可用。
+3 -1
View File
@@ -135,7 +135,8 @@ app shell / routes
- 已完成阶段 3 第五个 PR 切片“二维码登录、密码登录和剩余公共业务错误响应迁移”:二维码生成、扫码状态持久化、风控验证失败和账号不匹配均改用正确的非 2xx 状态码与统一错误 DTO;历史密码登录入口返回明确的 `password_login_disabled` 未实现错误;新增二维码/密码登录契约测试并通过全量门禁;
- 已完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备”:认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO,新增响应契约测试,并记录 `/api/v1` 兼容迁移边界;未提前切换旧路径,保持可回滚;
- 已完成阶段 3 第七个 PR 切片“剩余业务成功响应 DTO 与客户端契约收口”:账号详情/设置、商品核心发布与同步、自动化规则/异常、订单详情/刷新/批量外层响应改用具名 DTO;React 客户端同步使用具名契约类型;新增跨领域成功响应契约测试;旧字段、旧路径和批处理逐行兼容字段保留;全量门禁通过并合并为一个可回滚提交;
- 阶段 3 下一 PR 切片为“剩余商品批量操作与设置/卡券/通知成功响应收口”:继续迁移尚未覆盖的商品批量操作、系统设置、卡券和通知接口,不拆分单个 handler 提交;
- 已完成阶段 3 第八个 PR 切片“剩余商品批量操作与设置/卡券/通知成功响应收口”:商品类目推荐、批量发布预检/任务、系统与用户设置、账号 AI 设置、卡券 CRUD/批量、通知渠道与账号绑定均改用具名 DTO;React 客户端同步具名契约类型;补充跨领域契约测试;保留动态设置键、旧路径和批量逐行字段;全量门禁通过并合并为一个可回滚提交;
- 阶段 3 下一 PR 切片为“剩余关键词回复、默认回复与账号任务成功响应收口”:继续迁移尚未覆盖的回复规则、默认回复和账号任务接口,不拆分单个 handler 提交;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -519,3 +520,4 @@ npm --prefix frontend run build
| 2026-08-14 | 完成阶段 3 第五个 PR 切片“二维码登录、密码登录和剩余公共业务错误响应迁移” | 二维码与密码登录遗留 HTTP 200 + `success:false` 已迁移为非 2xx 错误;账号不匹配保留 `scanned_account_id` 到 `details`;二维码/密码登录契约测试、全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:统一业务成功响应具名 DTO 与版本化路径准备 |
| 2026-08-14 | 完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备” | 认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO;新增响应契约测试和 `/api/v1` 迁移边界文档;全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:剩余业务成功响应 DTO 与客户端契约收口 |
| 2026-08-14 | 完成阶段 3 第七个 PR 切片“剩余业务成功响应 DTO 与客户端契约收口” | 账号详情/设置、商品发布/同步、自动化规则/异常、订单详情/刷新/批量外层响应已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:剩余商品批量操作与设置/卡券/通知成功响应收口 |
| 2026-08-14 | 完成阶段 3 第八个 PR 切片“剩余商品批量操作与设置/卡券/通知成功响应收口” | 商品类目推荐、批量发布预检/任务、系统与用户设置、账号 AI 设置、卡券 CRUD/批量、通知渠道与账号绑定已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:剩余关键词回复、默认回复与账号任务成功响应收口 |
+49 -49
View File
@@ -4,7 +4,7 @@ import {
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType, AccountTaskSettings, AccountTaskSummary, ChatSession, ChatMessage,
CookieSettingsResponse, CookieProfileResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, AutomationRuleResponse, AutomationRulePageResponse
CookieSettingsResponse, CookieProfileResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse
} from '../types';
import { formatLocalDate } from '../dateRange';
@@ -449,43 +449,43 @@ const cardPayload = (data: Partial<Card>): Record<string, unknown> => ({
});
export const getCards = async (): Promise<Card[]> => {
const res = await get<any>('/cards');
const res = await get<Card[] | CardListResponse>('/cards');
const cards = Array.isArray(res) ? res : (res.cards || []);
return cards.map(normalizeCard);
};
export const createCard = async (data: Partial<Card>): Promise<{ id: number; message: string }> => {
export const createCard = async (data: Partial<Card>): Promise<MutationIDResponse> => {
return post('/cards', cardPayload(data));
};
export const updateCard = async (cardId: string | number, data: Partial<Card>): Promise<ApiResponse> => {
export const updateCard = async (cardId: string | number, data: Partial<Card>): Promise<OperationResponse> => {
return put(`/cards/${cardId}`, cardPayload(data));
};
export const deleteCard = async (cardId: string | number): Promise<ApiResponse> => {
export const deleteCard = async (cardId: string | number): Promise<OperationResponse> => {
return del(`/cards/${cardId}`);
};
export const getCardDetails = async (cardId: string | number): Promise<any> => {
const card = await get<any>(`/cards/${cardId}/details`);
export const getCardDetails = async (cardId: string | number): Promise<Card> => {
const card = await get<Card>(`/cards/${cardId}/details`);
return normalizeCard(card);
};
// 批量创建卡密组(上传表格)
export const batchCreateCards = async (file: File): Promise<{
success: boolean;
total: number;
created: number;
failed: number;
rows: { row_no: number; success: boolean; id?: number; name: string; type?: string; error?: string }[];
}> => {
export const batchCreateCards = async (file: File): Promise<CardBatchResponse> => {
// 批量创建接口返回总行数、成功数、失败数和逐行结果。
// CardBatchResponse 保留旧字段名称,调用方无需转换统计字段。
// rows 中的 id 只在创建成功时返回。
// rows 中的 error 只在对应行失败时返回。
// 表单上传方式和接口路径保持不变。
// 此处只收紧 TypeScript 响应契约。
const body = new FormData();
body.append('file', file);
return postForm('/cards/batch', body);
};
// 往 data 类型卡密组批量追加卡密号
export const appendCardData = async (cardId: string | number, content: string): Promise<{ success: boolean; added: number }> => {
export const appendCardData = async (cardId: string | number, content: string): Promise<CardAppendResponse> => {
return post(`/cards/${cardId}/append-data`, { content });
};
@@ -556,15 +556,15 @@ export interface PublishLocation {
province: string;
}
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<{
success: boolean;
category: {
cat_id: string;
cat_name: string;
channel_cat_id: string;
tb_cat_id?: string;
};
}> => {
export const recommendPublishCategory = async (cookieId: string, keyword: string): Promise<CategoryRecommendationResponse> => {
// 类目推荐成功响应使用共享 CategoryRecommendationResponse。
// category 字段保留平台类目 ID、名称和频道类目 ID。
// tb_cat_id 继续保持可选,兼容电子资料类目。
// 请求仍携带账号 ID 和关键词。
// 失败响应由共享 HTTP 错误结构处理。
// 该类型收口不改变凭证刷新和错误处理。
// 前端批量发布流程可直接复用 category。
// 旧路径继续由现有 Vite 代理转发。
return post('/items/publish-categories/recommend', { cookie_id: cookieId, keyword });
};
@@ -579,7 +579,7 @@ export const previewItemPublishBatch = async (form: {
tbCatId?: string;
};
location?: PublishLocation;
}): Promise<any> => {
}): Promise<ItemPublishBatchPreviewResponse> => {
const body = new FormData();
body.set('file', form.file);
if (form.imagesZip) body.set('images_zip', form.imagesZip);
@@ -592,28 +592,28 @@ export const previewItemPublishBatch = async (form: {
return postForm('/items/publish-batches/preview', body);
}
export const startItemPublishBatch = async (previewId: string): Promise<any> => {
export const startItemPublishBatch = async (previewId: string): Promise<BatchIDResponse> => {
return post('/items/publish-batches', { preview_id: previewId });
}
export const getItemPublishBatch = async (batchId: string): Promise<any> => {
export const getItemPublishBatch = async (batchId: string): Promise<ItemPublishBatchResponse> => {
return get(`/items/publish-batches/${batchId}`);
}
export const getItemPublishBatches = async (limit = 20): Promise<any[]> => {
const res = await get<any>('/items/publish-batches', { limit });
export const getItemPublishBatches = async (limit = 20): Promise<ItemPublishBatchResponse[]> => {
const res = await get<ItemPublishBatchListResponse>('/items/publish-batches', { limit });
return Array.isArray(res) ? res : (res.batches || []);
}
export const deleteItemPublishBatch = async (batchId: string): Promise<any> => {
export const deleteItemPublishBatch = async (batchId: string): Promise<OperationResponse> => {
return del(`/items/publish-batches/${batchId}`);
}
export const cancelItemPublishBatch = async (batchId: string): Promise<any> => {
export const cancelItemPublishBatch = async (batchId: string): Promise<BatchCancelResponse> => {
return post(`/items/publish-batches/${batchId}/cancel`, {});
}
export const retryFailedItemPublishBatch = async (batchId: string): Promise<any> => {
export const retryFailedItemPublishBatch = async (batchId: string): Promise<BatchIDResponse> => {
return post(`/items/publish-batches/${batchId}/retry-failed`, {});
}
@@ -884,18 +884,18 @@ export const getSystemSettings = async (): Promise<SystemSettings> => {
return normalizeSettings(res.data || res); // handle {success:true, data: {...}} wrapper if exists
};
export const updateSystemSettings = async (settings: Partial<SystemSettings>): Promise<ApiResponse> => {
export const updateSystemSettings = async (settings: Partial<SystemSettings>): Promise<OperationResponse> => {
const payload = Object.fromEntries(
Object.entries(settings).filter(([, value]) => value !== undefined && value !== null),
);
return put('/system-settings', payload);
};
export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise<AIReplySettings> => {
export const getAccountAISettings = async (cookieId: string, options?: RequestControlOptions): Promise<AIReplySettingsResponse> => {
return get(`/ai-reply-settings/${cookieId}`, undefined, options);
}
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>): Promise<ApiResponse> => {
export const updateAccountAISettings = async (cookieId: string, settings: Partial<AIReplySettings>): Promise<OperationResponse> => {
const payload = {
ai_enabled: settings.ai_enabled ?? false,
max_discount_percent: settings.max_discount_percent ?? 10,
@@ -907,7 +907,7 @@ export const updateAccountAISettings = async (cookieId: string, settings: Partia
}
export const fetchAIModels = async (baseUrl: string, apiKey: string = ''): Promise<string[]> => {
const result = await post<{ models?: string[] }>('/ai-models', {
const result = await post<AIModelsResponse>('/ai-models', {
base_url: baseUrl,
api_key: apiKey,
});
@@ -933,7 +933,7 @@ const stringifyNotificationEventTypes = (events?: NotificationEventType[]): stri
};
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ success: boolean; data?: NotificationChannel[] }> => {
const result = await get<any[]>('/notification-channels', undefined, options);
const result = await get<NotificationChannelResponse[]>('/notification-channels', undefined, options);
const channels = (result || []).map((item: any) => {
let parsedConfig;
try {
@@ -955,7 +955,7 @@ export const getNotificationChannels = async (options?: RequestControlOptions):
return { success: true, data: channels };
}
export const createNotificationChannel = async (data: { name: string; type: string; config: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }): Promise<ApiResponse> => {
export const createNotificationChannel = async (data: { name: string; type: string; config: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }): Promise<MutationIDResponse> => {
return post('/notification-channels', {
...data,
config: JSON.stringify(data.config),
@@ -963,7 +963,7 @@ export const createNotificationChannel = async (data: { name: string; type: stri
});
}
export const updateNotificationChannel = async (channelId: string, data: { name?: string; type?: string; config?: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }): Promise<ApiResponse> => {
export const updateNotificationChannel = async (channelId: string, data: { name?: string; type?: string; config?: Record<string, unknown>; event_types?: NotificationEventType[]; enabled?: boolean }): Promise<OperationResponse> => {
const payload: Record<string, unknown> = { ...data };
if ('config' in data) {
payload.config = JSON.stringify(data.config);
@@ -974,14 +974,14 @@ export const updateNotificationChannel = async (channelId: string, data: { name?
return put(`/notification-channels/${channelId}`, payload);
}
export const deleteNotificationChannel = async (channelId: string): Promise<ApiResponse> => {
export const deleteNotificationChannel = async (channelId: string): Promise<OperationResponse> => {
return del(`/notification-channels/${channelId}`);
}
// Message Notifications
export const getMessageNotifications = async (): Promise<{ success: boolean; data?: any[] }> => {
const result = await get<Record<string, any[]>>('/message-notifications');
const notifications = [];
export const getMessageNotifications = async (): Promise<{ success: boolean; data?: NotificationBinding[] }> => {
const result = await get<Record<string, NotificationBinding[]>>('/message-notifications');
const notifications: NotificationBinding[] = [];
for (const [cookieId, channelList] of Object.entries(result || {})) {
if (Array.isArray(channelList)) {
for (const item of channelList) {
@@ -997,30 +997,30 @@ export const getMessageNotifications = async (): Promise<{ success: boolean; dat
return { success: true, data: notifications };
}
export const setMessageNotification = async (cookieId: string, channelId: number, enabled: boolean): Promise<ApiResponse> => {
export const setMessageNotification = async (cookieId: string, channelId: number, enabled: boolean): Promise<OperationResponse> => {
return post(`/message-notifications/${cookieId}`, { channel_id: channelId, enabled });
}
export const deleteMessageNotification = async (notificationId: string): Promise<ApiResponse> => {
export const deleteMessageNotification = async (notificationId: string): Promise<OperationResponse> => {
return del(`/message-notifications/${notificationId}`);
}
export const deleteAccountNotifications = async (cookieId: string): Promise<ApiResponse> => {
export const deleteAccountNotifications = async (cookieId: string): Promise<OperationResponse> => {
return del(`/message-notifications/account/${cookieId}`);
}
// 账号 ↔ 渠道 绑定(覆盖式)
export const getAccountBindings = async (cookieId: string, options?: RequestControlOptions): Promise<number[]> => {
const result = await get<{ cookie_id: string; channel_ids: number[] }>(`/message-notifications/${cookieId}`, undefined, options);
const result = await get<AccountBindingsResponse>(`/message-notifications/${cookieId}`, undefined, options);
return result?.channel_ids || [];
}
export const setAccountBindings = async (cookieId: string, channelIds: number[]): Promise<ApiResponse> => {
export const setAccountBindings = async (cookieId: string, channelIds: number[]): Promise<OperationResponse> => {
return post(`/message-notifications/${cookieId}`, { channel_ids: channelIds });
}
// 测试发送
export const testNotificationChannel = async (channelId: string): Promise<ApiResponse> => {
export const testNotificationChannel = async (channelId: string): Promise<OperationResponse> => {
return post(`/notification-channels/${channelId}/test`, {});
}
+271
View File
@@ -695,3 +695,274 @@ export interface OrderBatchResult {
/** 允许后端保留尚未结构化的扩展字段。 */
[key: string]: unknown;
}
/** 账号 AI 回复设置接口的具名响应。 */
export interface AIReplySettingsResponse {
/** 账号稳定标识;默认配置响应可能省略。 */
cookie_id?: string;
/** AI 回复是否启用。 */
ai_enabled: boolean;
/** 最大折扣比例。 */
max_discount_percent: number;
/** 最大折扣金额。 */
max_discount_amount: number;
/** 最大砍价轮次。 */
max_bargain_rounds: number;
/** 自定义提示词。 */
custom_prompts: string;
}
/** AI 模型发现接口的具名响应。 */
export interface AIModelsResponse {
/** 远端可用模型名称。 */
models: string[];
}
/** 单个用户设置查询接口的具名响应。 */
export interface UserSettingResponse {
/** 设置值文本。 */
value: string;
}
/** 卡券批量创建接口的逐行结果。 */
export interface CardBatchResult {
/** 表格中的原始行号。 */
row_no: number;
/** 当前行是否创建成功。 */
success: boolean;
/** 新建卡券组主键。 */
id?: number;
/** 卡券组名称。 */
name: string;
/** 卡券类型。 */
type?: string;
/** 当前行失败原因。 */
error?: string;
}
/** 卡券批量创建接口的具名响应。 */
export interface CardBatchResponse {
/** 批量处理流程是否完成。 */
success: boolean;
/** 解析出的总行数。 */
total: number;
/** 创建成功行数。 */
created: number;
/** 创建失败行数。 */
failed: number;
/** 逐行处理结果。 */
rows: CardBatchResult[];
}
/** 卡券追加数据接口的具名响应。 */
export interface CardAppendResponse {
/** 追加操作是否完成。 */
success: boolean;
/** 实际追加数量。 */
added: number;
}
/** 通知绑定列表中的单条记录。 */
export interface NotificationBinding {
/** 账号稳定标识,列表归一化后补充。 */
cookie_id?: string;
/** 绑定记录主键。 */
id?: number;
/** 通知渠道主键。 */
channel_id: number;
/** 通知渠道名称。 */
channel_name: string;
/** 绑定是否启用。 */
enabled: boolean;
}
/** 账号通知渠道绑定查询响应。 */
export interface AccountBindingsResponse {
/** 账号稳定标识。 */
cookie_id: string;
/** 已绑定通知渠道主键列表。 */
channel_ids: number[];
}
/** 商品类目推荐接口的具名响应。 */
export interface CategoryRecommendationResponse {
/** 类目推荐是否成功。 */
success: boolean;
/** 推荐商品类目。 */
category: {
/** 平台类目主键。 */
cat_id: string;
/** 平台类目名称。 */
cat_name: string;
/** 频道类目主键。 */
channel_cat_id: string;
/** 淘宝类目主键。 */
tb_cat_id?: string;
};
}
/** 商品批量发布预检逐行结果。 */
export interface ItemPublishBatchPreviewRow {
/** 上传表格行号。 */
row_no: number;
/** 当前行是否通过预检。 */
valid: boolean;
/** 当前行校验错误列表。 */
errors?: string[];
/** 发布目标账号标识。 */
cookie_id: string;
/** 商品标题。 */
title: string;
/** 商品价格文本。 */
price: string;
/** 商品库存数量。 */
quantity: number;
/** 商品图片引用列表。 */
images: string[];
/** 商品发布类目。 */
category: CategoryRecommendationResponse['category'];
/** 发布后自动化配置。 */
automation?: Record<string, unknown>;
}
/** 商品批量发布预检响应。 */
export interface ItemPublishBatchPreviewResponse {
/** 预检流程是否完成。 */
success: boolean;
/** 后续启动发布使用的预检批次标识。 */
preview_id: string;
/** 预检总行数。 */
total: number;
/** 通过预检行数。 */
valid: number;
/** 未通过预检行数。 */
invalid: number;
/** 逐行预检结果。 */
rows: ItemPublishBatchPreviewRow[];
}
/** 商品批量发布任务启动或重试响应。 */
export interface BatchIDResponse {
/** 任务操作是否完成。 */
success: boolean;
/** 商品批量任务标识。 */
batch_id: string;
}
/** 商品批量发布任务取消响应。 */
export interface BatchCancelResponse {
/** 取消请求是否完成。 */
success: boolean;
/** 取消后的任务状态。 */
status: string;
}
/** 商品批量发布任务逐行详情。 */
export interface ItemPublishBatchRowResponse {
/** 明细行主键。 */
id: number;
/** 导入表格行号。 */
row_no: number;
/** 发布目标账号标识。 */
cookie_id: string;
/** 商品标题。 */
title: string;
/** 商品价格文本。 */
price: string;
/** 商品库存数量。 */
quantity: number;
/** 商品图片引用列表。 */
images: string[];
/** 商品发布类目。 */
category: CategoryRecommendationResponse['category'];
/** 发布后自动化配置。 */
automation: Record<string, unknown>;
/** 明细行状态。 */
status: string;
/** 发布成功后的平台商品标识。 */
item_id: string;
/** 发布成功后的商品地址。 */
item_url: string;
/** 明细行失败原因。 */
error_message: string;
/** 明细行失败类型。 */
failure_kind: string;
}
/** 商品批量发布任务详情响应。 */
export interface ItemPublishBatchResponse {
/** 批量任务标识。 */
id: string;
/** 批量任务状态。 */
status: string;
/** 原始上传文件名。 */
filename: string;
/** 明细行总数。 */
total: number;
/** 成功发布数量。 */
success: number;
/** 失败数量。 */
failed: number;
/** 待处理数量。 */
pending: number;
/** 运行中数量。 */
running: number;
/** 可重试数量。 */
retryable: number;
/** 明细行结果。 */
rows: ItemPublishBatchRowResponse[];
/** 批次统一发货地。 */
location?: Record<string, unknown>;
/** 创建时间。 */
created_at: string;
/** 更新时间。 */
updated_at: string;
}
/** 商品批量发布任务列表响应。 */
export interface ItemPublishBatchListResponse {
/** 当前用户的批量任务列表。 */
batches: ItemPublishBatchResponse[];
}
/** 简单资源创建接口的数值主键响应。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
/** 通知渠道接口返回的原始具名 DTO。 */
export interface NotificationChannelResponse {
/** 通知渠道主键。 */
id: number;
/** 通知渠道名称。 */
name: string;
/** 通知渠道类型。 */
type: string;
/** 通知渠道配置 JSON。 */
config: string;
/** 订阅事件类型 JSON 或兼容文本。 */
event_types?: string;
/** 通知渠道是否启用。 */
enabled: boolean;
/** 所属用户主键。 */
user_id?: number;
}
/** 卡券列表接口的兼容包装响应。 */
export interface CardListResponse {
/** 当前用户卡券列表。 */
cards: Card[];
}
+8 -8
View File
@@ -131,13 +131,13 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
created++
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"total": len(maps),
"created": created,
"failed": failed,
"rows": results,
})
// 批量响应使用具名 DTO,但保留逐行结果供客户端展示失败原因。
// total、created 和 failed 的统计语义与旧接口保持一致。
// rows 中的 success 仅表示对应表格行是否创建成功。
// 卡券批量接口仍返回 HTTP 200,单行失败不改变批次级成功语义。
// 后续版本化迁移可直接复用该字段结构。
// 该 DTO 不暴露未使用的数据库用户字段。
writeJSON(w, http.StatusOK, cardBatchResponse{Success: true, Total: len(maps), Created: created, Failed: failed, Rows: results})
}
// appendCardData 往 data 类型卡密组追加卡密号(按行)。
@@ -178,5 +178,5 @@ func (s *Server) appendCardData(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "追加失败: "+err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "added": added})
writeJSON(w, http.StatusOK, cardAppendResponse{Success: true, Added: added})
}
+5 -5
View File
@@ -30,7 +30,7 @@ func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
writeJSON(w, http.StatusOK, cards)
writeJSON(w, http.StatusOK, newCardResponses(cards))
}
func (s *Server) getCard(w http.ResponseWriter, r *http.Request) {
@@ -43,7 +43,7 @@ func (s *Server) getCard(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
writeJSON(w, http.StatusOK, cf)
writeJSON(w, http.StatusOK, newCardResponse(*cf))
}
func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
@@ -63,7 +63,7 @@ func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "创建失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id})
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
@@ -91,7 +91,7 @@ func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) deleteCard(w http.ResponseWriter, r *http.Request) {
@@ -107,7 +107,7 @@ func (s *Server) deleteCard(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func decodeCard(r *http.Request) (*db.CardFull, error) {
+3 -3
View File
@@ -172,7 +172,7 @@ func TestPublicHTTPClient(t *testing.T) {
}
}
// TestPublishBatchToMap 批次转 map 序列化 + 状态计数。
// TestPublishBatchToMap 批次转具名 DTO 序列化并校验状态计数。
func TestPublishBatchToMap(t *testing.T) {
batch := &db.ItemPublishBatch{ID: "b1", Status: "running", Filename: "x.csv"}
rows := []db.ItemPublishBatchRow{
@@ -180,10 +180,10 @@ func TestPublishBatchToMap(t *testing.T) {
{ID: 2, RowNo: 2, CookieID: "c1", Title: "t2", Status: "running"},
}
m := publishBatchToMap(batch, rows)
if m["id"] != "b1" || m["status"] != "running" {
if m.ID != "b1" || m.Status != "running" {
t.Fatalf("batch 字段异常: %+v", m)
}
rs, _ := m["rows"].([]map[string]any)
rs := m.Rows
if len(rs) != 2 {
t.Fatalf("rows 数异常: %d", len(rs))
}
+30 -30
View File
@@ -166,7 +166,7 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "category": category})
writeJSON(w, http.StatusOK, categoryRecommendationResponse{Success: true, Category: category})
}
func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) {
@@ -348,14 +348,14 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
}
keepUpload = true
_ = s.Store.PublishBatches.Recount(r.Context(), batchID)
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"preview_id": batchID,
"total": len(rows),
"valid": valid,
"invalid": invalid,
"rows": previewRows,
})
// 预检响应保留逐行错误,客户端据此决定是否允许启动发布。
// preview_id 是后续启动、轮询和放弃预检的稳定标识。
// total、valid 和 invalid 继续使用旧统计口径。
// rows 保留类目和自动化配置,避免前端重复解析上传表格。
// 预检成功不代表远端商品已经发布。
// 远端发布失败仍由批次明细状态表达。
// 该 DTO 不改变上传目录清理和批次持久化时序。
writeJSON(w, http.StatusOK, itemPublishBatchPreviewResponse{Success: true, PreviewID: batchID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: previewRows})
}
func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
@@ -412,7 +412,7 @@ func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
return
}
s.startPublishBatchWorker(s.lifecycleContext(), sess.UserID, batch.ID, workerToken)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batch.ID})
writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: batch.ID})
}
func (s *Server) listItemPublishBatches(w http.ResponseWriter, r *http.Request) {
@@ -423,11 +423,11 @@ func (s *Server) listItemPublishBatches(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusInternalServerError, "读取批量任务失败")
return
}
result := make([]map[string]any, 0, len(batches))
result := make([]itemPublishBatchResponse, 0, len(batches))
for i := range batches {
result = append(result, publishBatchToMap(&batches[i], nil))
}
writeJSON(w, http.StatusOK, map[string]any{"batches": result})
writeJSON(w, http.StatusOK, itemPublishBatchListResponse{Batches: result})
}
func (s *Server) getItemPublishBatch(w http.ResponseWriter, r *http.Request) {
@@ -466,7 +466,7 @@ func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request)
if running {
s.cancelPublishBatch(batchID, workerToken)
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "status": map[bool]string{true: "canceling", false: "canceled"}[running]})
writeJSON(w, http.StatusOK, batchCancelResponse{Success: true, Status: map[bool]string{true: "canceling", false: "canceled"}[running]})
}
func (s *Server) deleteItemPublishBatch(w http.ResponseWriter, r *http.Request) {
@@ -488,7 +488,7 @@ func (s *Server) deleteItemPublishBatch(w http.ResponseWriter, r *http.Request)
if strings.TrimSpace(batch.UploadDir) != "" {
_ = os.RemoveAll(batch.UploadDir)
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Request) {
@@ -531,7 +531,7 @@ func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Requ
return
}
s.startPublishBatchWorker(s.lifecycleContext(), sess.UserID, batchID, workerToken)
writeJSON(w, http.StatusOK, map[string]any{"success": true, "batch_id": batchID})
writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: batchID})
}
func (s *Server) startPublishBatchWorker(parent context.Context, userID int64, batchID, workerToken string) {
@@ -1336,12 +1336,12 @@ func (s *Server) validatePublishAutomation(ctx context.Context, userID int64, cf
return errs
}
func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) map[string]any {
func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow) itemPublishBatchResponse {
locationJSON := strings.TrimSpace(batch.LocationJSON)
if locationJSON == "" {
locationJSON = "{}"
}
outRows := make([]map[string]any, 0, len(rows))
outRows := make([]itemPublishBatchRowResponse, 0, len(rows))
pending := 0
running := 0
for _, row := range rows {
@@ -1357,13 +1357,13 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow
_ = json.Unmarshal([]byte(row.CategoryJSON), &category)
var automationCfg publishAutomationConfig
_ = json.Unmarshal([]byte(row.AutomationJSON), &automationCfg)
outRows = append(outRows, map[string]any{
"id": row.ID, "row_no": row.RowNo, "cookie_id": row.CookieID, "title": row.Title,
"price": row.Price, "quantity": row.Quantity, "images": refs,
"category": category,
"automation": automationCfg,
"status": row.Status, "item_id": row.ItemID, "item_url": row.ItemURL,
"error_message": row.ErrorMessage, "failure_kind": row.FailureKind,
outRows = append(outRows, itemPublishBatchRowResponse{
ID: row.ID, RowNo: row.RowNo, CookieID: row.CookieID, Title: row.Title,
Price: row.Price, Quantity: row.Quantity, Images: refs,
Category: category,
Automation: automationCfg,
Status: row.Status, ItemID: row.ItemID, ItemURL: row.ItemURL,
ErrorMessage: row.ErrorMessage, FailureKind: row.FailureKind,
})
}
retryable := 0
@@ -1372,12 +1372,12 @@ func publishBatchToMap(batch *db.ItemPublishBatch, rows []db.ItemPublishBatchRow
retryable++
}
}
return map[string]any{
"id": batch.ID, "status": batch.Status, "filename": batch.Filename,
"total": batch.TotalCount, "success": batch.SuccessCount, "failed": batch.FailedCount,
"pending": pending, "running": running, "retryable": retryable, "rows": outRows,
"location": json.RawMessage(locationJSON),
"created_at": batch.CreatedAt, "updated_at": batch.UpdatedAt,
return itemPublishBatchResponse{
ID: batch.ID, Status: batch.Status, Filename: batch.Filename,
Total: batch.TotalCount, Success: batch.SuccessCount, Failed: batch.FailedCount,
Pending: pending, Running: running, Retryable: retryable, Rows: outRows,
Location: json.RawMessage(locationJSON),
CreatedAt: batch.CreatedAt, UpdatedAt: batch.UpdatedAt,
}
}
+16 -16
View File
@@ -32,7 +32,7 @@ func (s *Server) listChannels(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
writeJSON(w, http.StatusOK, chs)
writeJSON(w, http.StatusOK, newNotificationChannelResponses(chs))
}
func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
@@ -55,7 +55,7 @@ func (s *Server) createChannel(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "创建失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id})
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
@@ -112,7 +112,7 @@ func (s *Server) updateChannel(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
@@ -130,7 +130,7 @@ func (s *Server) deleteChannel(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// testChannel 向指定渠道发送一条测试通知,便于用户验证配置是否正确。
@@ -153,7 +153,7 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "发送失败: "+err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
@@ -166,7 +166,7 @@ func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"cookie_id": cid, "channel_ids": ids})
writeJSON(w, http.StatusOK, accountBindingsResponse{CookieID: cid, ChannelIDs: ids})
}
func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request) {
@@ -183,7 +183,7 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
return
}
defer rows.Close()
out := make(map[string][]map[string]any)
out := make(notificationBindingListResponse)
for rows.Next() {
var id, channelID int64
var cookieID, channelName string
@@ -192,11 +192,11 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
out[cookieID] = append(out[cookieID], map[string]any{
"id": id,
"channel_id": channelID,
"channel_name": channelName,
"enabled": enabled != 0,
out[cookieID] = append(out[cookieID], notificationBindingResponse{
ID: id,
ChannelID: channelID,
ChannelName: channelName,
Enabled: enabled != 0,
})
}
if err := rows.Err(); err != nil {
@@ -239,7 +239,7 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
return
}
for _, channelID := range req.ChannelIDs {
@@ -251,7 +251,7 @@ func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Request) {
@@ -269,7 +269,7 @@ func (s *Server) deleteMessageNotification(w http.ResponseWriter, r *http.Reques
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) deleteAccountNotifications(w http.ResponseWriter, r *http.Request) {
@@ -283,5 +283,5 @@ func (s *Server) deleteAccountNotifications(w http.ResponseWriter, r *http.Reque
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
+30 -30
View File
@@ -64,7 +64,7 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
if level, ok := values["log_level"]; ok {
_ = logging.SetLevel(level)
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
@@ -104,7 +104,7 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// ---- AI 回复设置 ----
@@ -129,7 +129,7 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
}
defer rows.Close()
result := make(map[string]any)
result := make(map[string]aiReplySettingsResponse)
for rows.Next() {
var cookieID, customPrompts string
var enabled, maxDiscountPercent, maxDiscountAmount, maxBargainRounds int
@@ -137,13 +137,13 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
result[cookieID] = map[string]any{
"cookie_id": cookieID,
"ai_enabled": enabled != 0,
"max_discount_percent": maxDiscountPercent,
"max_discount_amount": maxDiscountAmount,
"max_bargain_rounds": maxBargainRounds,
"custom_prompts": customPrompts,
result[cookieID] = aiReplySettingsResponse{
CookieID: cookieID, AIEnabled: enabled != 0, MaxDiscountPercent: maxDiscountPercent,
MaxDiscountAmount: maxDiscountAmount, MaxBargainRounds: maxBargainRounds, CustomPrompts: customPrompts,
// 账号标识和五项配置字段保持旧 JSON 名称。
// 布尔值继续由数据库整数转换得到。
// 自定义提示词不做额外格式化。
// DTO 转换不改变查询失败处理。
}
}
if err := rows.Err(); err != nil {
@@ -164,23 +164,23 @@ func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"ai_enabled": false,
"max_discount_percent": 10,
"max_discount_amount": 100,
"max_bargain_rounds": 3,
"custom_prompts": "",
})
// 未保存配置使用与旧接口一致的默认值。
// 默认响应不携带 cookie_id,避免误认为已持久化账号配置。
// max_discount_percent 保持默认 10 的业务约束。
// max_discount_amount 保持默认 100 的业务约束。
// max_bargain_rounds 保持默认 3 的业务约束。
// custom_prompts 为空表示未配置自定义提示词。
writeJSON(w, http.StatusOK, aiReplySettingsResponse{AIEnabled: false, MaxDiscountPercent: 10, MaxDiscountAmount: 100, MaxBargainRounds: 3, CustomPrompts: ""})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"cookie_id": cfg.CookieID,
"ai_enabled": cfg.AIEnabled,
"max_discount_percent": cfg.MaxDiscountPercent,
"max_discount_amount": cfg.MaxDiscountAmount,
"max_bargain_rounds": cfg.MaxBargainRounds,
"custom_prompts": cfg.CustomPrompts,
})
// 已保存配置返回账号标识,客户端可据此区分账号级设置。
// AIEnabled 表示账号 AI 回复开关。
// 折扣上限字段保持原有数值类型和命名。
// 砍价轮次字段保持原有校验范围。
// CustomPrompts 仍返回原始提示词文本。
// 该响应仅静态化 JSON 结构,不改变存储或校验逻辑。
// 旧客户端可以继续直接读取这些字段。
writeJSON(w, http.StatusOK, aiReplySettingsResponse{CookieID: cfg.CookieID, AIEnabled: cfg.AIEnabled, MaxDiscountPercent: cfg.MaxDiscountPercent, MaxDiscountAmount: cfg.MaxDiscountAmount, MaxBargainRounds: cfg.MaxBargainRounds, CustomPrompts: cfg.CustomPrompts})
}
func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
@@ -229,7 +229,7 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
@@ -268,7 +268,7 @@ func (s *Server) listAIModels(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadGateway, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"models": models})
writeJSON(w, http.StatusOK, aiModelsResponse{Models: models})
}
var newSettingsOutboundHTTPClient = func(baseURL string) (*http.Client, error) {
@@ -409,10 +409,10 @@ func (s *Server) getUserSetting(w http.ResponseWriter, r *http.Request) {
err := s.Store.DB.QueryRowContext(r.Context(),
`SELECT value FROM user_settings WHERE user_id=? AND `+keyCol+`=?`, sess.UserID, key).Scan(&v)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"value": ""})
writeJSON(w, http.StatusOK, userSettingResponse{Value: ""})
return
}
writeJSON(w, http.StatusOK, map[string]any{"value": v})
writeJSON(w, http.StatusOK, userSettingResponse{Value: v})
}
func (s *Server) setUserSetting(w http.ResponseWriter, r *http.Request) {
@@ -437,5 +437,5 @@ func (s *Server) setUserSetting(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "保存失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
@@ -5,6 +5,7 @@ import (
"encoding/json"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)
@@ -187,3 +188,185 @@ func TestRemainingSuccessResponseContracts(t *testing.T) {
t.Fatalf("order response=%+v", orderResponse)
}
}
// TestSettingsCardsNotificationsBatchContracts 验证设置、卡券、通知和商品批量接口的具名成功响应。
func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
// srv 是用于验证设置、卡券、通知和商品批量响应的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// settingReq 是更新单个系统设置的请求。
settingReq := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader(`{"value":"contract-blue"}`))
settingReq.AddCookie(sessionCookie)
// settingRecorder 是捕获系统设置响应的记录器。
settingRecorder := httptest.NewRecorder()
handler.ServeHTTP(settingRecorder, settingReq)
if settingRecorder.Code != http.StatusOK {
t.Fatalf("setting status=%d body=%s", settingRecorder.Code, settingRecorder.Body.String())
}
// settingResponse 是系统设置变更具名响应 DTO。
var settingResponse operationResponse
// settingDecodeErr 是系统设置响应 JSON 反序列化失败的原因。
if settingDecodeErr := json.Unmarshal(settingRecorder.Body.Bytes(), &settingResponse); settingDecodeErr != nil {
t.Fatalf("decode setting response: %v", settingDecodeErr)
}
if !settingResponse.Success {
t.Fatalf("setting response=%+v", settingResponse)
}
// aiReq 是更新账号 AI 回复设置的请求。
aiReq := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(`{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"契约测试"}`))
aiReq.AddCookie(sessionCookie)
// aiRecorder 是捕获账号 AI 设置响应的记录器。
aiRecorder := httptest.NewRecorder()
handler.ServeHTTP(aiRecorder, aiReq)
if aiRecorder.Code != http.StatusOK {
t.Fatalf("ai update status=%d body=%s", aiRecorder.Code, aiRecorder.Body.String())
}
// aiResponse 是账号 AI 设置变更具名响应 DTO。
var aiResponse operationResponse
// aiDecodeErr 是账号 AI 设置响应 JSON 反序列化失败的原因。
if aiDecodeErr := json.Unmarshal(aiRecorder.Body.Bytes(), &aiResponse); aiDecodeErr != nil {
t.Fatalf("decode ai update response: %v", aiDecodeErr)
}
if !aiResponse.Success {
t.Fatalf("ai update response=%+v", aiResponse)
}
// aiGetReq 是读取账号 AI 设置的请求。
aiGetReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
aiGetReq.AddCookie(sessionCookie)
// aiGetRecorder 是捕获账号 AI 设置查询响应的记录器。
aiGetRecorder := httptest.NewRecorder()
handler.ServeHTTP(aiGetRecorder, aiGetReq)
if aiGetRecorder.Code != http.StatusOK {
t.Fatalf("ai get status=%d body=%s", aiGetRecorder.Code, aiGetRecorder.Body.String())
}
// aiGetResponse 是账号 AI 设置查询具名响应 DTO。
var aiGetResponse aiReplySettingsResponse
// aiGetDecodeErr 是账号 AI 设置查询响应 JSON 反序列化失败的原因。
if aiGetDecodeErr := json.Unmarshal(aiGetRecorder.Body.Bytes(), &aiGetResponse); aiGetDecodeErr != nil {
t.Fatalf("decode ai get response: %v", aiGetDecodeErr)
}
if !aiGetResponse.AIEnabled || aiGetResponse.MaxDiscountPercent != 12 {
t.Fatalf("ai get response=%+v", aiGetResponse)
}
// cardReq 是创建文本卡券组的请求。
cardReq := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(`{"name":"契约卡","type":"text","text_content":"CARD","enabled":true}`))
cardReq.AddCookie(sessionCookie)
// cardRecorder 是捕获卡券创建响应的记录器。
cardRecorder := httptest.NewRecorder()
handler.ServeHTTP(cardRecorder, cardReq)
if cardRecorder.Code != http.StatusOK {
t.Fatalf("card status=%d body=%s", cardRecorder.Code, cardRecorder.Body.String())
}
// cardResponse 是卡券创建具名响应 DTO。
var cardCreateResponse mutationIDResponse
// cardDecodeErr 是卡券创建响应 JSON 反序列化失败的原因。
if cardDecodeErr := json.Unmarshal(cardRecorder.Body.Bytes(), &cardCreateResponse); cardDecodeErr != nil {
t.Fatalf("decode card response: %v", cardDecodeErr)
}
if !cardCreateResponse.Success || cardCreateResponse.ID == 0 {
t.Fatalf("card response=%+v", cardCreateResponse)
}
// cardGetReq 是读取卡券详情的请求。
cardGetReq := httptest.NewRequest(http.MethodGet, "/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil)
cardGetReq.AddCookie(sessionCookie)
// cardGetRecorder 是捕获卡券详情响应的记录器。
cardGetRecorder := httptest.NewRecorder()
handler.ServeHTTP(cardGetRecorder, cardGetReq)
if cardGetRecorder.Code != http.StatusOK {
t.Fatalf("card get status=%d body=%s", cardGetRecorder.Code, cardGetRecorder.Body.String())
}
// cardGetResponse 是卡券详情具名响应 DTO。
var cardGetResponse cardResponse
// cardGetDecodeErr 是卡券详情响应 JSON 反序列化失败的原因。
if cardGetDecodeErr := json.Unmarshal(cardGetRecorder.Body.Bytes(), &cardGetResponse); cardGetDecodeErr != nil {
t.Fatalf("decode card get response: %v", cardGetDecodeErr)
}
if cardGetResponse.ID != cardCreateResponse.ID || cardGetResponse.Name != "契约卡" {
t.Fatalf("card get response=%+v", cardGetResponse)
}
// channelReq 是创建通知渠道的请求。
channelReq := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(`{"name":"契约通知","type":"bark","config":"{}","enabled":true}`))
channelReq.AddCookie(sessionCookie)
// channelRecorder 是捕获通知渠道创建响应的记录器。
channelRecorder := httptest.NewRecorder()
handler.ServeHTTP(channelRecorder, channelReq)
if channelRecorder.Code != http.StatusOK {
t.Fatalf("channel status=%d body=%s", channelRecorder.Code, channelRecorder.Body.String())
}
// channelResponse 是通知渠道创建具名响应 DTO。
var channelResponse mutationIDResponse
// channelDecodeErr 是通知渠道创建响应 JSON 反序列化失败的原因。
if channelDecodeErr := json.Unmarshal(channelRecorder.Body.Bytes(), &channelResponse); channelDecodeErr != nil {
t.Fatalf("decode channel response: %v", channelDecodeErr)
}
if !channelResponse.Success || channelResponse.ID == 0 {
t.Fatalf("channel response=%+v", channelResponse)
}
// bindingReq 是将通知渠道绑定到测试账号的请求。
bindingReq := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(`{"channel_ids":[`+strconv.FormatInt(channelResponse.ID, 10)+`]}`))
bindingReq.AddCookie(sessionCookie)
// bindingRecorder 是捕获通知绑定响应的记录器。
bindingRecorder := httptest.NewRecorder()
handler.ServeHTTP(bindingRecorder, bindingReq)
if bindingRecorder.Code != http.StatusOK {
t.Fatalf("binding status=%d body=%s", bindingRecorder.Code, bindingRecorder.Body.String())
}
// bindingResponse 是通知绑定变更具名响应 DTO。
var bindingResponse operationResponse
// bindingDecodeErr 是通知绑定响应 JSON 反序列化失败的原因。
if bindingDecodeErr := json.Unmarshal(bindingRecorder.Body.Bytes(), &bindingResponse); bindingDecodeErr != nil {
t.Fatalf("decode binding response: %v", bindingDecodeErr)
}
if !bindingResponse.Success {
t.Fatalf("binding response=%+v", bindingResponse)
}
// bindingGetReq 是读取账号通知绑定的请求。
bindingGetReq := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil)
bindingGetReq.AddCookie(sessionCookie)
// bindingGetRecorder 是捕获账号通知绑定响应的记录器。
bindingGetRecorder := httptest.NewRecorder()
handler.ServeHTTP(bindingGetRecorder, bindingGetReq)
if bindingGetRecorder.Code != http.StatusOK {
t.Fatalf("binding get status=%d body=%s", bindingGetRecorder.Code, bindingGetRecorder.Body.String())
}
// bindingGetResponse 是账号通知绑定具名响应 DTO。
var bindingGetResponse accountBindingsResponse
// bindingGetDecodeErr 是账号通知绑定响应 JSON 反序列化失败的原因。
if bindingGetDecodeErr := json.Unmarshal(bindingGetRecorder.Body.Bytes(), &bindingGetResponse); bindingGetDecodeErr != nil {
t.Fatalf("decode binding get response: %v", bindingGetDecodeErr)
}
if bindingGetResponse.CookieID != "acc1" || len(bindingGetResponse.ChannelIDs) != 1 {
t.Fatalf("binding get response=%+v", bindingGetResponse)
}
// batchReq 是读取商品批量任务列表的请求。
batchReq := httptest.NewRequest(http.MethodGet, "/items/publish-batches?limit=10", nil)
batchReq.AddCookie(sessionCookie)
// batchRecorder 是捕获商品批量任务列表响应的记录器。
batchRecorder := httptest.NewRecorder()
handler.ServeHTTP(batchRecorder, batchReq)
if batchRecorder.Code != http.StatusOK {
t.Fatalf("batch status=%d body=%s", batchRecorder.Code, batchRecorder.Body.String())
}
// batchResponse 是商品批量任务列表具名响应 DTO。
var batchResponse itemPublishBatchListResponse
// batchDecodeErr 是商品批量任务列表响应 JSON 反序列化失败的原因。
if batchDecodeErr := json.Unmarshal(batchRecorder.Body.Bytes(), &batchResponse); batchDecodeErr != nil {
t.Fatalf("decode batch response: %v", batchDecodeErr)
}
if batchResponse.Batches == nil {
t.Fatalf("batch response=%+v", batchResponse)
}
}
+275 -1
View File
@@ -1,6 +1,9 @@
package server
import "xianyu-go/internal/db"
import (
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
// operationResponse 是密码、会话和设置变更接口共用的操作结果 DTO。
type operationResponse struct {
@@ -604,3 +607,274 @@ type importOrdersResponse struct {
// Results 是逐订单的兼容结果行。
Results []map[string]any `json:"results"`
}
// aiReplySettingsResponse 是账号 AI 回复设置接口的具名响应 DTO。
type aiReplySettingsResponse struct {
// CookieID 是账号稳定标识;默认配置响应省略该字段。
CookieID string `json:"cookie_id,omitempty"`
// AIEnabled 表示账号 AI 回复是否启用。
AIEnabled bool `json:"ai_enabled"`
// MaxDiscountPercent 是允许的最大折扣比例。
MaxDiscountPercent int `json:"max_discount_percent"`
// MaxDiscountAmount 是允许的最大折扣金额。
MaxDiscountAmount int `json:"max_discount_amount"`
// MaxBargainRounds 是允许的最大砍价轮次。
MaxBargainRounds int `json:"max_bargain_rounds"`
// CustomPrompts 是账号自定义提示词。
CustomPrompts string `json:"custom_prompts"`
}
// aiModelsResponse 是 AI 模型发现接口的具名响应 DTO。
type aiModelsResponse struct {
// Models 是远端可用模型名称列表。
Models []string `json:"models"`
}
// userSettingResponse 是单个用户设置查询接口的具名响应 DTO。
type userSettingResponse struct {
// Value 是设置值文本。
Value string `json:"value"`
}
// cardResponse 是卡券详情和列表接口的具名响应 DTO。
type cardResponse struct {
// ID 是卡券组稳定标识。
ID int64 `json:"id"`
// Name 是卡券组名称。
Name string `json:"name"`
// Type 是卡券类型。
Type string `json:"type"`
// APIConfig 是 API 卡券配置 JSON。
APIConfig string `json:"api_config"`
// TextContent 是文本卡券内容。
TextContent string `json:"text_content"`
// DataContent 是批量数据卡券内容。
DataContent string `json:"data_content"`
// ImageURL 是图片卡券地址。
ImageURL string `json:"image_url"`
// Description 是卡券组描述。
Description string `json:"description"`
// Enabled 表示卡券组是否启用。
Enabled bool `json:"enabled"`
// DelaySeconds 是自动发货延迟秒数。
DelaySeconds int `json:"delay_seconds"`
// IsMultiSpec 表示卡券组是否按规格区分。
IsMultiSpec bool `json:"is_multi_spec"`
// SpecName 是卡券规格名称。
SpecName string `json:"spec_name"`
// SpecValue 是卡券规格值。
SpecValue string `json:"spec_value"`
// UserID 是卡券所属用户标识,保留旧接口字段。
UserID int64 `json:"user_id,omitempty"`
}
// newCardResponse 将数据库卡券模型转换为 HTTP DTO。
func newCardResponse(card db.CardFull) cardResponse {
return cardResponse{
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig,
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds,
IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID,
}
}
// newCardResponses 批量转换卡券列表,避免直接暴露数据库模型。
func newCardResponses(cards []db.CardFull) []cardResponse {
// result 是转换后的卡券 DTO 列表。
result := make([]cardResponse, 0, len(cards))
// card 是当前待转换的卡券数据库模型。
for _, card := range cards {
result = append(result, newCardResponse(card))
}
return result
}
// cardBatchResponse 是卡券批量创建接口的具名响应 DTO。
type cardBatchResponse struct {
// Success 表示批量解析和处理流程已完成。
Success bool `json:"success"`
// Total 是表格中解析出的数据行数量。
Total int `json:"total"`
// Created 是成功创建的卡券组数量。
Created int `json:"created"`
// Failed 是创建失败的数据行数量。
Failed int `json:"failed"`
// Rows 是逐行处理结果。
Rows []cardBatchResultRow `json:"rows"`
}
// cardAppendResponse 是追加卡密接口的具名响应 DTO。
type cardAppendResponse struct {
// Success 表示追加操作是否完成。
Success bool `json:"success"`
// Added 是实际追加的卡密数量。
Added int `json:"added"`
}
// notificationChannelResponse 是通知渠道接口的具名响应 DTO。
type notificationChannelResponse struct {
// ID 是通知渠道稳定标识。
ID int64 `json:"id"`
// Name 是通知渠道名称。
Name string `json:"name"`
// Type 是通知渠道类型。
Type string `json:"type"`
// Config 是通知渠道配置 JSON。
Config string `json:"config"`
// EventTypes 是订阅事件类型 JSON 或兼容分隔文本。
EventTypes string `json:"event_types,omitempty"`
// Enabled 表示通知渠道是否启用。
Enabled bool `json:"enabled"`
// UserID 是渠道所属用户标识,保留旧接口字段。
UserID int64 `json:"user_id,omitempty"`
}
// newNotificationChannelResponse 将数据库通知渠道转换为 HTTP DTO。
func newNotificationChannelResponse(channel db.NotificationChannelRow) notificationChannelResponse {
return notificationChannelResponse{
ID: channel.ID, Name: channel.Name, Type: channel.Type, Config: channel.Config,
EventTypes: channel.EventTypes, Enabled: channel.Enabled, UserID: channel.UserID,
}
}
// newNotificationChannelResponses 批量转换通知渠道,保持数据库模型不穿透 HTTP 层。
func newNotificationChannelResponses(channels []db.NotificationChannelRow) []notificationChannelResponse {
// result 是转换后的通知渠道 DTO 列表。
result := make([]notificationChannelResponse, 0, len(channels))
// channel 是当前待转换的通知渠道数据库模型。
for _, channel := range channels {
result = append(result, newNotificationChannelResponse(channel))
}
return result
}
// notificationBindingResponse 是单条账号通知绑定的具名 DTO。
type notificationBindingResponse struct {
// ID 是绑定记录稳定标识。
ID int64 `json:"id"`
// ChannelID 是通知渠道标识。
ChannelID int64 `json:"channel_id"`
// ChannelName 是通知渠道名称。
ChannelName string `json:"channel_name"`
// Enabled 表示该账号绑定是否启用。
Enabled bool `json:"enabled"`
}
// notificationBindingListResponse 是按账号分组的通知绑定响应 DTO。
type notificationBindingListResponse map[string][]notificationBindingResponse
// accountBindingsResponse 是账号与通知渠道绑定查询接口的具名响应 DTO。
type accountBindingsResponse struct {
// CookieID 是账号稳定标识。
CookieID string `json:"cookie_id"`
// ChannelIDs 是当前账号绑定的通知渠道标识列表。
ChannelIDs []int64 `json:"channel_ids"`
}
// categoryRecommendationResponse 是商品类目推荐接口的具名响应 DTO。
type categoryRecommendationResponse struct {
// Success 表示类目推荐是否成功。
Success bool `json:"success"`
// Category 是推荐的商品类目。
Category mtop.PublishCategory `json:"category"`
}
// itemPublishBatchPreviewResponse 是商品批量发布预检接口的具名响应 DTO。
type itemPublishBatchPreviewResponse struct {
// Success 表示预检是否完成。
Success bool `json:"success"`
// PreviewID 是后续启动批量发布使用的预检批次标识。
PreviewID string `json:"preview_id"`
// Total 是预检数据行总数。
Total int `json:"total"`
// Valid 是通过预检的数据行数量。
Valid int `json:"valid"`
// Invalid 是未通过预检的数据行数量。
Invalid int `json:"invalid"`
// Rows 是逐行预检结果。
Rows []publishBatchPreviewRow `json:"rows"`
}
// batchIDResponse 是商品批量任务启动或重试接口的具名响应 DTO。
type batchIDResponse struct {
// Success 表示任务操作是否完成。
Success bool `json:"success"`
// BatchID 是商品批量任务标识。
BatchID string `json:"batch_id"`
}
// batchCancelResponse 是商品批量任务取消接口的具名响应 DTO。
type batchCancelResponse struct {
// Success 表示取消请求是否完成。
Success bool `json:"success"`
// Status 是任务取消后的状态。
Status string `json:"status"`
}
// itemPublishBatchRowResponse 是商品批量任务逐行详情 DTO。
type itemPublishBatchRowResponse struct {
// ID 是批量任务明细行主键。
ID int64 `json:"id"`
// RowNo 是导入表格中的行号。
RowNo int `json:"row_no"`
// CookieID 是商品发布目标账号标识。
CookieID string `json:"cookie_id"`
// Title 是商品标题。
Title string `json:"title"`
// Price 是商品价格文本。
Price string `json:"price"`
// Quantity 是商品库存数量。
Quantity int `json:"quantity"`
// Images 是商品图片引用列表。
Images []string `json:"images"`
// Category 是商品发布类目。
Category mtop.PublishCategory `json:"category"`
// Automation 是发布后自动化配置。
Automation publishAutomationConfig `json:"automation"`
// Status 是当前明细行状态。
Status string `json:"status"`
// ItemID 是发布成功后的平台商品标识。
ItemID string `json:"item_id"`
// ItemURL 是发布成功后的商品地址。
ItemURL string `json:"item_url"`
// ErrorMessage 是明细行失败原因。
ErrorMessage string `json:"error_message"`
// FailureKind 是失败类型。
FailureKind string `json:"failure_kind"`
}
// itemPublishBatchResponse 是商品批量任务详情接口的具名响应 DTO。
type itemPublishBatchResponse struct {
// ID 是商品批量任务标识。
ID string `json:"id"`
// Status 是批量任务状态。
Status string `json:"status"`
// Filename 是原始上传文件名。
Filename string `json:"filename"`
// Total 是明细行总数。
Total int `json:"total"`
// Success 是成功发布的明细行数量,保留旧字段名称。
Success int `json:"success"`
// Failed 是失败明细行数量。
Failed int `json:"failed"`
// Pending 是待处理明细行数量。
Pending int `json:"pending"`
// Running 是正在处理明细行数量。
Running int `json:"running"`
// Retryable 是可重试明细行数量。
Retryable int `json:"retryable"`
// Rows 是批量任务逐行结果。
Rows []itemPublishBatchRowResponse `json:"rows"`
// Location 是批次统一发货地对象。
Location any `json:"location"`
// CreatedAt 是任务创建时间。
CreatedAt string `json:"created_at"`
// UpdatedAt 是任务更新时间。
UpdatedAt string `json:"updated_at"`
}
// itemPublishBatchListResponse 是商品批量任务列表接口的具名响应 DTO。
type itemPublishBatchListResponse struct {
// Batches 是当前用户的商品批量任务列表。
Batches []itemPublishBatchResponse `json:"batches"`
}