API契约:收口回复规则与账号任务响应
This commit is contained in:
1 parent
fe6fc3adb9
commit
f76fb08cbe
9 files changed
+535
-60
No files matched your search
@@ -16,6 +16,9 @@
|
||||
| 卡券 | `/cards...` | `/api/v1/cards...` | 旧路径保留,CRUD/批量 DTO 已落地 |
|
||||
| 通知 | `/notification-channels...`、`/message-notifications...` | `/api/v1/notifications/...` | 旧路径保留,渠道/绑定/变更 DTO 已落地 |
|
||||
| 聊天 | `/api/chat...` | `/api/v1/chat...` | 旧路径保留,会话/消息 DTO 已落地 |
|
||||
| 关键词回复 | `/keywords...`、`/keywords-with-item-id...`、`/keywords-with-type...`、`/item-reply...` | `/api/v1/reply-rules...` | 旧路径保留,基础/商品/类型规则与指定商品回复 DTO 已落地 |
|
||||
| 默认回复 | `/default-replies...`、`/api/default-reply...` | `/api/v1/default-replies...` | 旧路径保留,单账号、列表和映射 DTO 已落地 |
|
||||
| 账号任务 | `/api/account-tasks...` | `/api/v1/account-tasks...` | 旧路径保留,设置、运行记录和执行摘要 DTO 已落地 |
|
||||
|
||||
## 迁移规则
|
||||
|
||||
@@ -34,6 +37,7 @@
|
||||
- 自动化规则分页、动作和异常列表使用 `automationRulePageResponse`、`automationRuleResponse`、`automationActionResponse` 与 `automationIssuesResponse`。
|
||||
- 订单列表、详情、刷新和批量外层结果使用 `orderListResponse`、`orderDetailResponse`、`orderRefreshResponse` 与 `manualShipResponse`/`importOrdersResponse`。
|
||||
- 设置、卡券和通知分别使用 `operationResponse`、`aiReplySettingsResponse`、`aiModelsResponse`、`userSettingResponse`、`cardResponse`、`cardBatchResponse`、`notificationChannelResponse`、`notificationBindingResponse` 与 `accountBindingsResponse`。
|
||||
- 关键词回复、默认回复和账号任务分别使用 `keywordBasicResponse`/`keywordItemResponse`/`keywordTypedResponse`、`itemReplyResponse`、`defaultReplyResponse`、`accountTaskSettingsResponse`、`accountTaskRunsResponse` 与 `accountTaskRunResponseEnvelope`。
|
||||
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
|
||||
- React `frontend/types.ts` 与 `frontend/services/api.ts` 已同步具名成功响应类型,同时保留旧字段归一逻辑。
|
||||
- 旧路径仍由现有路由提供,尚未宣称 `/api/v1` 已经可用。
|
||||
@@ -136,7 +136,8 @@ app shell / routes
|
||||
- 已完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备”:认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO,新增响应契约测试,并记录 `/api/v1` 兼容迁移边界;未提前切换旧路径,保持可回滚;
|
||||
- 已完成阶段 3 第七个 PR 切片“剩余业务成功响应 DTO 与客户端契约收口”:账号详情/设置、商品核心发布与同步、自动化规则/异常、订单详情/刷新/批量外层响应改用具名 DTO;React 客户端同步使用具名契约类型;新增跨领域成功响应契约测试;旧字段、旧路径和批处理逐行兼容字段保留;全量门禁通过并合并为一个可回滚提交;
|
||||
- 已完成阶段 3 第八个 PR 切片“剩余商品批量操作与设置/卡券/通知成功响应收口”:商品类目推荐、批量发布预检/任务、系统与用户设置、账号 AI 设置、卡券 CRUD/批量、通知渠道与账号绑定均改用具名 DTO;React 客户端同步具名契约类型;补充跨领域契约测试;保留动态设置键、旧路径和批量逐行字段;全量门禁通过并合并为一个可回滚提交;
|
||||
- 阶段 3 下一 PR 切片为“剩余关键词回复、默认回复与账号任务成功响应收口”:继续迁移尚未覆盖的回复规则、默认回复和账号任务接口,不拆分单个 handler 提交;
|
||||
- 已完成阶段 3 第九个 PR 切片“剩余关键词回复、默认回复与账号任务成功响应收口”:关键词基础/商品/类型规则、指定商品回复、默认回复、账号任务设置与运行记录均改用具名 DTO;React 客户端同步具名契约类型;新增跨领域契约测试;保留旧路径和兼容字段;全量门禁通过并合并为一个可回滚提交;
|
||||
- 阶段 3 下一 PR 切片为“分析统计、管理员与剩余公共成功响应收口”:继续迁移尚未覆盖的统计、管理员和公共业务成功响应,不拆分单个 handler 提交;
|
||||
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
|
||||
|
||||
## 6. 阶段 0:治理文档与强约束
|
||||
@@ -521,3 +522,4 @@ npm --prefix frontend run build
|
||||
| 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:剩余关键词回复、默认回复与账号任务成功响应收口 |
|
||||
| 2026-08-14 | 完成阶段 3 第九个 PR 切片“剩余关键词回复、默认回复与账号任务成功响应收口” | 关键词基础/商品/类型规则、指定商品回复、默认回复、账号任务设置与运行记录已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:分析统计、管理员与剩余公共成功响应收口 |
|
||||
+14
-14
@@ -3,8 +3,8 @@ import {
|
||||
LoginResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
|
||||
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, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse
|
||||
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage,
|
||||
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, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope
|
||||
} from '../types';
|
||||
import { formatLocalDate } from '../dateRange';
|
||||
|
||||
@@ -97,13 +97,13 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis
|
||||
}));
|
||||
};
|
||||
|
||||
export const getAccountTaskSettings = async (id: string): Promise<AccountTaskSettings> =>
|
||||
export const getAccountTaskSettings = async (id: string): Promise<AccountTaskSettingsResponse> =>
|
||||
get(`/api/account-tasks/${id}`);
|
||||
|
||||
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings): Promise<AccountTaskSettings> =>
|
||||
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings): Promise<AccountTaskSettingsResponse> =>
|
||||
put(`/api/account-tasks/${id}`, settings);
|
||||
|
||||
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish'): Promise<{success: boolean; summary: AccountTaskSummary}> =>
|
||||
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish'): Promise<AccountTaskRunResponseEnvelope> =>
|
||||
post(`/api/account-tasks/${id}/run`, { task_type: taskType }, { timeoutMs: 120_000 });
|
||||
|
||||
export interface ChatSessionPage { sessions: ChatSession[]; has_more: boolean; next_cursor?: number }
|
||||
@@ -841,7 +841,7 @@ const normalizeKeywordRow = (item: any): KeywordRowPayload => ({
|
||||
});
|
||||
|
||||
const getKeywordRowsWithType = async (cookieId: string): Promise<KeywordRowPayload[]> => {
|
||||
const existing = await get<any>(`/keywords-with-type/${cookieId}`);
|
||||
const existing = await get<KeywordTypedResponse[]>(`/keywords-with-type/${cookieId}`);
|
||||
return Array.isArray(existing) ? existing.map(normalizeKeywordRow) : [];
|
||||
};
|
||||
|
||||
@@ -860,7 +860,7 @@ export const getReplyRules = async (cookieId?: string): Promise<ReplyRule[]> =>
|
||||
}));
|
||||
}
|
||||
|
||||
export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string): Promise<any> => {
|
||||
export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string): Promise<OperationResponse> => {
|
||||
const type = rule.type || 'text';
|
||||
const payload = {
|
||||
keyword: rule.keyword || '',
|
||||
@@ -874,7 +874,7 @@ export const updateReplyRule = async (rule: Partial<ReplyRule>, cookieId: string
|
||||
: post(`/keywords-with-item-id/${cookieId}`, payload);
|
||||
}
|
||||
|
||||
export const deleteReplyRule = async (id: string, cookieId: string): Promise<any> => {
|
||||
export const deleteReplyRule = async (id: string, cookieId: string): Promise<OperationResponse> => {
|
||||
return del(`/keywords-with-type/${cookieId}/${id}`);
|
||||
}
|
||||
|
||||
@@ -1025,12 +1025,12 @@ export const testNotificationChannel = async (channelId: string): Promise<Operat
|
||||
}
|
||||
|
||||
// Default Reply
|
||||
export const getDefaultReplies = async (): Promise<Record<string, DefaultReply>> => {
|
||||
return get('/api/default-replies');
|
||||
export const getDefaultReplies = async (): Promise<Record<string, DefaultReplyResponse>> => {
|
||||
return get('/api/default-replies');
|
||||
};
|
||||
|
||||
export const getDefaultReply = async (cookieId: string): Promise<DefaultReply> => {
|
||||
const result = await get<any>(`/api/default-reply/${cookieId}`);
|
||||
const result = await get<DefaultReplyResponse>(`/api/default-reply/${cookieId}`);
|
||||
return {
|
||||
cookie_id: cookieId,
|
||||
enabled: result.enabled || false,
|
||||
@@ -1040,7 +1040,7 @@ export const getDefaultReply = async (cookieId: string): Promise<DefaultReply> =
|
||||
};
|
||||
};
|
||||
|
||||
export const updateDefaultReply = async (cookieId: string, data: Partial<DefaultReply>): Promise<ApiResponse> => {
|
||||
export const updateDefaultReply = async (cookieId: string, data: Partial<DefaultReply>): Promise<OperationResponse> => {
|
||||
return put(`/api/default-reply/${cookieId}`, {
|
||||
enabled: data.enabled ?? false,
|
||||
reply_content: data.reply_content || '',
|
||||
@@ -1049,10 +1049,10 @@ export const updateDefaultReply = async (cookieId: string, data: Partial<Default
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteDefaultReply = async (cookieId: string): Promise<ApiResponse> => {
|
||||
export const deleteDefaultReply = async (cookieId: string): Promise<OperationResponse> => {
|
||||
return del(`/api/default-reply/${cookieId}`);
|
||||
};
|
||||
|
||||
export const clearDefaultReplyRecords = async (cookieId: string): Promise<ApiResponse> => {
|
||||
export const clearDefaultReplyRecords = async (cookieId: string): Promise<OperationResponse> => {
|
||||
return post(`/api/default-reply/${cookieId}/clear-records`, {});
|
||||
};
|
||||
@@ -966,3 +966,113 @@ export interface CardListResponse {
|
||||
/** 当前用户卡券列表。 */
|
||||
cards: Card[];
|
||||
}
|
||||
|
||||
/** 传统关键词列表项响应。 */
|
||||
export interface KeywordBasicResponse {
|
||||
/** 匹配关键词。 */
|
||||
keyword: string;
|
||||
/** 文字回复内容。 */
|
||||
reply: string;
|
||||
}
|
||||
|
||||
/** 带商品范围的关键词列表项响应。 */
|
||||
export interface KeywordItemResponse extends KeywordBasicResponse {
|
||||
/** 限定的商品标识。 */
|
||||
item_id: string;
|
||||
}
|
||||
|
||||
/** 带类型和主键的关键词列表项响应。 */
|
||||
export interface KeywordTypedResponse extends KeywordItemResponse {
|
||||
/** 关键词规则主键。 */
|
||||
id: number;
|
||||
/** 回复类型。 */
|
||||
type: 'text' | 'image';
|
||||
/** 图片回复地址。 */
|
||||
image_url: string;
|
||||
}
|
||||
|
||||
/** 指定商品回复项响应。 */
|
||||
export interface ItemReplyResponse {
|
||||
/** 商品平台标识。 */
|
||||
item_id?: string;
|
||||
/** 账号稳定标识。 */
|
||||
cookie_id?: string;
|
||||
/** 指定商品的回复内容。 */
|
||||
reply_content: string;
|
||||
}
|
||||
|
||||
/** 默认回复查询响应。 */
|
||||
export interface DefaultReplyResponse extends DefaultReply {
|
||||
/** 账号稳定标识。 */
|
||||
cookie_id: string;
|
||||
}
|
||||
|
||||
/** 账号任务设置响应。 */
|
||||
export interface AccountTaskSettingsResponse {
|
||||
/** 账号稳定标识。 */
|
||||
account_id: string;
|
||||
/** 是否启用自动评价。 */
|
||||
auto_rate_enabled: boolean;
|
||||
/** 自动评价文案。 */
|
||||
rate_content: string;
|
||||
/** 是否启用自动擦亮。 */
|
||||
auto_polish_enabled: boolean;
|
||||
/** 自动擦亮本地时间。 */
|
||||
polish_time: string;
|
||||
/** 最近一次评价扫描时间。 */
|
||||
last_rate_scan_at: number;
|
||||
/** 最近一次擦亮日期。 */
|
||||
last_polish_date: string;
|
||||
/** 最近一次擦亮时间。 */
|
||||
last_polish_at: number;
|
||||
}
|
||||
|
||||
/** 账号任务执行记录响应。 */
|
||||
export interface AccountTaskRunResponse {
|
||||
/** 任务执行记录主键。 */
|
||||
id: number;
|
||||
/** 任务幂等键。 */
|
||||
run_key: string;
|
||||
/** 账号稳定标识。 */
|
||||
account_id: string;
|
||||
/** 任务类型。 */
|
||||
task_type: string;
|
||||
/** 任务目标标识。 */
|
||||
target_id: string;
|
||||
/** 任务业务日期。 */
|
||||
run_date: string;
|
||||
/** 任务执行状态。 */
|
||||
status: string;
|
||||
/** 任务成功数量。 */
|
||||
success_count: number;
|
||||
/** 任务失败数量。 */
|
||||
failed_count: number;
|
||||
/** 任务失败说明。 */
|
||||
error_message: string;
|
||||
/** 下一次重试时间。 */
|
||||
next_retry_at: number;
|
||||
/** 任务开始时间。 */
|
||||
started_at: number;
|
||||
/** 任务完成时间。 */
|
||||
finished_at: number;
|
||||
}
|
||||
|
||||
/** 账号任务执行记录列表响应。 */
|
||||
export interface AccountTaskRunsResponse {
|
||||
/** 当前账号的任务执行记录。 */
|
||||
runs: AccountTaskRunResponse[];
|
||||
}
|
||||
|
||||
/** 手动执行账号任务的统计响应。 */
|
||||
export interface AccountTaskSummaryResponse extends AccountTaskSummary {
|
||||
/** 任务结果说明。 */
|
||||
message?: string;
|
||||
}
|
||||
|
||||
/** 手动执行账号任务的成功响应。 */
|
||||
export interface AccountTaskRunResponseEnvelope {
|
||||
/** 任务请求是否成功完成。 */
|
||||
success: boolean;
|
||||
/** 账号任务执行统计。 */
|
||||
summary: AccountTaskSummaryResponse;
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func (s *Server) getAccountTaskSettings(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusInternalServerError, "读取账号任务配置失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, settings)
|
||||
writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(settings))
|
||||
}
|
||||
|
||||
func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -64,7 +64,7 @@ func (s *Server) updateAccountTaskSettings(w http.ResponseWriter, r *http.Reques
|
||||
return
|
||||
}
|
||||
stored, _ := s.Store.AccountTasks.Get(r.Context(), cid)
|
||||
writeJSON(w, http.StatusOK, stored)
|
||||
writeJSON(w, http.StatusOK, newAccountTaskSettingsResponse(stored))
|
||||
}
|
||||
|
||||
func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -78,7 +78,7 @@ func (s *Server) listAccountTaskRuns(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "读取任务记录失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"runs": runs})
|
||||
writeJSON(w, http.StatusOK, accountTaskRunsResponse{Runs: newAccountTaskRunResponses(runs)})
|
||||
}
|
||||
|
||||
func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -103,5 +103,5 @@ func (s *Server) runAccountTask(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadGateway, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "summary": summary})
|
||||
writeJSON(w, http.StatusOK, accountTaskRunResponseEnvelope{Success: true, Summary: newAccountTaskSummaryResponse(summary)})
|
||||
}
|
||||
@@ -45,30 +45,33 @@ func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
dr, err := s.Store.DefaultReps.Get(r.Context(), cid)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"enabled": false, "reply_content": "", "reply_once": false})
|
||||
writeJSON(w, http.StatusOK, defaultReplyResponse{Enabled: false, ReplyContent: "", ReplyOnce: false})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"enabled": dr.Enabled, "reply_content": dr.ReplyContent,
|
||||
"reply_image_url": dr.ReplyImageURL, "reply_once": dr.ReplyOnce,
|
||||
})
|
||||
// 已保存默认回复通过具名 DTO 返回,单账号查询不填充 cookie_id。
|
||||
writeJSON(w, http.StatusOK, newDefaultReplyResponse("", *dr))
|
||||
}
|
||||
|
||||
// setDefaultReply 保存指定账号的默认回复配置。
|
||||
func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
// cid 是当前操作的账号标识。
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.requireCookieOwnership(w, r, cid) {
|
||||
return
|
||||
}
|
||||
// req 是默认回复配置请求体。
|
||||
var req struct {
|
||||
Enabled bool `json:"enabled"`
|
||||
ReplyContent string `json:"reply_content"`
|
||||
ReplyImageURL string `json:"reply_image_url"`
|
||||
ReplyOnce bool `json:"reply_once"`
|
||||
}
|
||||
// err 是请求体解码错误。
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
// err 是默认回复写入错误。
|
||||
_, err := s.Store.DB.ExecContext(r.Context(),
|
||||
`INSERT INTO default_replies (cookie_id, enabled, reply_content, reply_image_url, reply_once, updated_at)
|
||||
VALUES (?,?,?,?,?,CURRENT_TIMESTAMP)`+db.DialectUpsert(s.Store.Dialect, []string{"cookie_id"}, map[string]string{
|
||||
@@ -83,11 +86,14 @@ func (s *Server) setDefaultReply(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})
|
||||
}
|
||||
|
||||
// listDefaultReplies 查询当前用户的默认回复列表。
|
||||
func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 是当前登录用户会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// err 是默认回复列表查询错误,rows 是查询结果游标。
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT dr.cookie_id, dr.enabled, COALESCE(dr.reply_content,''), dr.reply_once, COALESCE(dr.reply_image_url,'')
|
||||
FROM default_replies dr
|
||||
@@ -98,18 +104,24 @@ func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []map[string]any
|
||||
// out 是默认回复列表响应。
|
||||
var out []defaultReplyResponse
|
||||
for rows.Next() {
|
||||
// cid、content 和 imageURL 是当前默认回复的文本字段。
|
||||
var cid, content, imageURL string
|
||||
// enabled 和 replyOnce 是数据库中的布尔数值字段。
|
||||
var enabled, replyOnce int
|
||||
// err 是当前默认回复行扫描错误。
|
||||
if err := rows.Scan(&cid, &enabled, &content, &replyOnce, &imageURL); err != nil {
|
||||
continue
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"cookie_id": cid, "enabled": enabled != 0, "reply_content": content,
|
||||
"reply_once": replyOnce != 0, "reply_image_url": imageURL,
|
||||
out = append(out, defaultReplyResponse{
|
||||
CookieID: cid, Enabled: enabled != 0, ReplyContent: content, ReplyOnce: replyOnce != 0,
|
||||
ReplyImageURL: imageURL,
|
||||
// 列表 DTO 保留账号标识,前端可直接建立按账号索引。
|
||||
})
|
||||
}
|
||||
// err 是默认回复游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
@@ -117,8 +129,11 @@ func (s *Server) listDefaultReplies(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// listDefaultRepliesMap 查询按账号索引的默认回复映射。
|
||||
func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
|
||||
// sess 是当前登录用户会话。
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
// err 是默认回复映射查询错误,rows 是查询结果游标。
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT dr.cookie_id, dr.enabled, COALESCE(dr.reply_content, ''), dr.reply_once, COALESCE(dr.reply_image_url, '')
|
||||
FROM default_replies dr
|
||||
@@ -129,21 +144,27 @@ func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
out := make(map[string]any)
|
||||
// out 是按账号标识索引的默认回复映射。
|
||||
out := make(map[string]defaultReplyResponse)
|
||||
for rows.Next() {
|
||||
// cid、content 和 imageURL 是当前默认回复的文本字段。
|
||||
var cid, content, imageURL string
|
||||
// enabled 和 replyOnce 是数据库中的布尔数值字段。
|
||||
var enabled, replyOnce int
|
||||
// err 是当前默认回复行扫描错误。
|
||||
if err := rows.Scan(&cid, &enabled, &content, &replyOnce, &imageURL); err != nil {
|
||||
continue
|
||||
}
|
||||
out[cid] = map[string]any{
|
||||
"cookie_id": cid,
|
||||
"enabled": enabled != 0,
|
||||
"reply_content": content,
|
||||
"reply_once": replyOnce != 0,
|
||||
"reply_image_url": imageURL,
|
||||
out[cid] = defaultReplyResponse{
|
||||
CookieID: cid,
|
||||
Enabled: enabled != 0,
|
||||
ReplyContent: content,
|
||||
ReplyOnce: replyOnce != 0,
|
||||
ReplyImageURL: imageURL,
|
||||
// map 键与 cookie_id 同时保留,兼容旧前端索引方式。
|
||||
}
|
||||
}
|
||||
// err 是默认回复映射游标迭代错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
@@ -151,27 +172,33 @@ func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
// deleteDefaultReply 删除指定账号的默认回复配置。
|
||||
func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) {
|
||||
// cid 是当前操作的账号标识。
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.requireCookieOwnership(w, r, cid) {
|
||||
return
|
||||
}
|
||||
// err 是默认回复删除错误。
|
||||
_, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_replies WHERE cookie_id=?`, cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
// clearDefaultReplyRecords 清空指定账号的默认回复发送记录。
|
||||
func (s *Server) clearDefaultReplyRecords(w http.ResponseWriter, r *http.Request) {
|
||||
// cid 是当前操作的账号标识。
|
||||
cid := chi.URLParam(r, "cid")
|
||||
if !s.requireCookieOwnership(w, r, cid) {
|
||||
return
|
||||
}
|
||||
// err 是默认回复记录清理错误。
|
||||
if _, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_reply_records WHERE cookie_id=?`, cid); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "清空失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
@@ -34,9 +34,9 @@ func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
out := make([]map[string]any, 0, len(rows))
|
||||
out := make([]keywordBasicResponse, 0, len(rows))
|
||||
for _, k := range rows {
|
||||
out = append(out, map[string]any{"keyword": k.Keyword, "reply": k.Reply})
|
||||
out = append(out, keywordBasicResponse{Keyword: k.Keyword, Reply: k.Reply})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
@@ -51,9 +51,9 @@ func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
out := make([]map[string]any, 0, len(rows))
|
||||
out := make([]keywordItemResponse, 0, len(rows))
|
||||
for _, k := range rows {
|
||||
out = append(out, map[string]any{"keyword": k.Keyword, "reply": k.Reply, "item_id": k.ItemID})
|
||||
out = append(out, keywordItemResponse{Keyword: k.Keyword, Reply: k.Reply, ItemID: k.ItemID})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
@@ -68,11 +68,11 @@ func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
out := make([]map[string]any, 0, len(rows))
|
||||
out := make([]keywordTypedResponse, 0, len(rows))
|
||||
for _, k := range rows {
|
||||
out = append(out, map[string]any{
|
||||
"id": k.ID, "keyword": k.Keyword, "reply": k.Reply, "item_id": k.ItemID,
|
||||
"type": k.Type, "image_url": k.ImageURL,
|
||||
out = append(out, keywordTypedResponse{
|
||||
ID: k.ID, Keyword: k.Keyword, Reply: k.Reply, ItemID: k.ItemID,
|
||||
Type: k.Type, ImageURL: k.ImageURL,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
@@ -99,7 +99,7 @@ func (s *Server) addKeyword(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) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -166,7 +166,7 @@ func (s *Server) addKeywordWithItemID(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
|
||||
}
|
||||
if strings.TrimSpace(req.Keyword) == "" {
|
||||
@@ -199,7 +199,7 @@ func (s *Server) addKeywordWithItemID(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) updateKeywordByID(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -256,7 +256,7 @@ func (s *Server) updateKeywordByID(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) deleteKeywordByID(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -273,7 +273,7 @@ func (s *Server) deleteKeywordByID(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusNotFound, "关键字不存在")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -286,7 +286,7 @@ func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusNotFound, "关键字不存在")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
// ---- 指定商品回复 ----
|
||||
@@ -300,12 +300,12 @@ func (s *Server) mountItemRepliesReal(r chi.Router) {
|
||||
func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
cookieIDs, _ := s.Store.Cookies.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 是当前用户拥有的账号 ID。
|
||||
var result []map[string]any
|
||||
var result []itemReplyResponse
|
||||
for _, cid := range cookieIDs {
|
||||
rows, _ := s.Store.ItemReps.AllForUser(r.Context(), cid)
|
||||
for _, ir := range rows {
|
||||
result = append(result, map[string]any{
|
||||
"item_id": ir.ItemID, "cookie_id": ir.CookieID, "reply_content": ir.ReplyContent,
|
||||
result = append(result, itemReplyResponse{
|
||||
ItemID: ir.ItemID, CookieID: ir.CookieID, ReplyContent: ir.ReplyContent,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -320,11 +320,11 @@ func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
|
||||
itemID := chi.URLParam(r, "item_id")
|
||||
ir, err := s.Store.ItemReps.Get(r.Context(), cid, itemID)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"reply_content": ""})
|
||||
writeJSON(w, http.StatusOK, itemReplyResponse{ReplyContent: ""})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"item_id": ir.ItemID, "cookie_id": ir.CookieID, "reply_content": ir.ReplyContent,
|
||||
writeJSON(w, http.StatusOK, itemReplyResponse{
|
||||
ItemID: ir.ItemID, CookieID: ir.CookieID, ReplyContent: ir.ReplyContent,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -345,7 +345,7 @@ func (s *Server) setItemReply(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) deleteItemReply(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -358,5 +358,5 @@ func (s *Server) deleteItemReply(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})
|
||||
}
|
||||
@@ -370,3 +370,150 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
|
||||
t.Fatalf("batch response=%+v", batchResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReplyAndAccountTaskSuccessResponseContracts 验证回复规则、默认回复和账号任务成功响应的具名 DTO。
|
||||
func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
|
||||
// srv 是用于验证回复和账号任务响应的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
|
||||
// keywordReq 是创建带商品范围关键词的请求。
|
||||
keywordReq := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(`{"keyword":"契约关键词","reply":"契约回复","item_id":"contract-item"}`))
|
||||
keywordReq.Header.Set("Content-Type", "application/json")
|
||||
keywordReq.AddCookie(sessionCookie)
|
||||
// keywordRecorder 是捕获关键词创建响应的记录器。
|
||||
keywordRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(keywordRecorder, keywordReq)
|
||||
if keywordRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("keyword status=%d body=%s", keywordRecorder.Code, keywordRecorder.Body.String())
|
||||
}
|
||||
// keywordResponse 是关键词创建具名响应 DTO。
|
||||
var keywordResponse mutationIDResponse
|
||||
// keywordDecodeErr 是关键词创建响应 JSON 反序列化失败的原因。
|
||||
if keywordDecodeErr := json.Unmarshal(keywordRecorder.Body.Bytes(), &keywordResponse); keywordDecodeErr != nil {
|
||||
t.Fatalf("decode keyword response: %v", keywordDecodeErr)
|
||||
}
|
||||
if !keywordResponse.Success || keywordResponse.ID == 0 {
|
||||
t.Fatalf("keyword response=%+v", keywordResponse)
|
||||
}
|
||||
|
||||
// keywordListReq 是读取带类型关键词列表的请求。
|
||||
keywordListReq := httptest.NewRequest(http.MethodGet, "/keywords-with-type/acc1", nil)
|
||||
keywordListReq.AddCookie(sessionCookie)
|
||||
// keywordListRecorder 是捕获关键词列表响应的记录器。
|
||||
keywordListRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(keywordListRecorder, keywordListReq)
|
||||
if keywordListRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("keyword list status=%d body=%s", keywordListRecorder.Code, keywordListRecorder.Body.String())
|
||||
}
|
||||
// keywordListResponse 是关键词列表具名响应 DTO 列表。
|
||||
var keywordListResponse []keywordTypedResponse
|
||||
// keywordListDecodeErr 是关键词列表响应 JSON 反序列化失败的原因。
|
||||
if keywordListDecodeErr := json.Unmarshal(keywordListRecorder.Body.Bytes(), &keywordListResponse); keywordListDecodeErr != nil {
|
||||
t.Fatalf("decode keyword list response: %v", keywordListDecodeErr)
|
||||
}
|
||||
if len(keywordListResponse) != 1 || keywordListResponse[0].ItemID != "contract-item" {
|
||||
t.Fatalf("keyword list response=%+v", keywordListResponse)
|
||||
}
|
||||
|
||||
// itemReplyReq 是保存指定商品回复的请求。
|
||||
itemReplyReq := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/contract-item", strings.NewReader(`{"reply_content":"商品契约回复"}`))
|
||||
itemReplyReq.Header.Set("Content-Type", "application/json")
|
||||
itemReplyReq.AddCookie(sessionCookie)
|
||||
// itemReplyRecorder 是捕获指定商品回复响应的记录器。
|
||||
itemReplyRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(itemReplyRecorder, itemReplyReq)
|
||||
if itemReplyRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("item reply status=%d body=%s", itemReplyRecorder.Code, itemReplyRecorder.Body.String())
|
||||
}
|
||||
// itemReplyResponse 是指定商品回复变更具名响应 DTO。
|
||||
var itemReplyResponse operationResponse
|
||||
// itemReplyDecodeErr 是指定商品回复响应 JSON 反序列化失败的原因。
|
||||
if itemReplyDecodeErr := json.Unmarshal(itemReplyRecorder.Body.Bytes(), &itemReplyResponse); itemReplyDecodeErr != nil {
|
||||
t.Fatalf("decode item reply response: %v", itemReplyDecodeErr)
|
||||
}
|
||||
if !itemReplyResponse.Success {
|
||||
t.Fatalf("item reply response=%+v", itemReplyResponse)
|
||||
}
|
||||
|
||||
// defaultReplyReq 是保存默认回复的请求。
|
||||
defaultReplyReq := httptest.NewRequest(http.MethodPut, "/api/default-reply/acc1", strings.NewReader(`{"enabled":true,"reply_content":"默认契约回复","reply_once":true,"reply_image_url":""}`))
|
||||
defaultReplyReq.Header.Set("Content-Type", "application/json")
|
||||
defaultReplyReq.AddCookie(sessionCookie)
|
||||
// defaultReplyRecorder 是捕获默认回复响应的记录器。
|
||||
defaultReplyRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(defaultReplyRecorder, defaultReplyReq)
|
||||
if defaultReplyRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("default reply status=%d body=%s", defaultReplyRecorder.Code, defaultReplyRecorder.Body.String())
|
||||
}
|
||||
// defaultReplyResponseValue 是默认回复变更具名响应 DTO。
|
||||
var defaultReplyResponseValue operationResponse
|
||||
// defaultReplyDecodeErr 是默认回复响应 JSON 反序列化失败的原因。
|
||||
if defaultReplyDecodeErr := json.Unmarshal(defaultReplyRecorder.Body.Bytes(), &defaultReplyResponseValue); defaultReplyDecodeErr != nil {
|
||||
t.Fatalf("decode default reply response: %v", defaultReplyDecodeErr)
|
||||
}
|
||||
if !defaultReplyResponseValue.Success {
|
||||
t.Fatalf("default reply response=%+v", defaultReplyResponseValue)
|
||||
}
|
||||
|
||||
// defaultReplyGetReq 是读取默认回复的请求。
|
||||
defaultReplyGetReq := httptest.NewRequest(http.MethodGet, "/api/default-reply/acc1", nil)
|
||||
defaultReplyGetReq.AddCookie(sessionCookie)
|
||||
// defaultReplyGetRecorder 是捕获默认回复查询响应的记录器。
|
||||
defaultReplyGetRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(defaultReplyGetRecorder, defaultReplyGetReq)
|
||||
if defaultReplyGetRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("default reply get status=%d body=%s", defaultReplyGetRecorder.Code, defaultReplyGetRecorder.Body.String())
|
||||
}
|
||||
// defaultReplyGetResponse 是默认回复查询具名响应 DTO。
|
||||
var defaultReplyGetResponse defaultReplyResponse
|
||||
// defaultReplyGetDecodeErr 是默认回复查询响应 JSON 反序列化失败的原因。
|
||||
if defaultReplyGetDecodeErr := json.Unmarshal(defaultReplyGetRecorder.Body.Bytes(), &defaultReplyGetResponse); defaultReplyGetDecodeErr != nil {
|
||||
t.Fatalf("decode default reply get response: %v", defaultReplyGetDecodeErr)
|
||||
}
|
||||
if !defaultReplyGetResponse.Enabled || defaultReplyGetResponse.ReplyContent != "默认契约回复" {
|
||||
t.Fatalf("default reply get response=%+v", defaultReplyGetResponse)
|
||||
}
|
||||
|
||||
// taskSettingsReq 是读取账号任务设置的请求。
|
||||
taskSettingsReq := httptest.NewRequest(http.MethodGet, "/api/account-tasks/acc1", nil)
|
||||
taskSettingsReq.AddCookie(sessionCookie)
|
||||
// taskSettingsRecorder 是捕获账号任务设置响应的记录器。
|
||||
taskSettingsRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(taskSettingsRecorder, taskSettingsReq)
|
||||
if taskSettingsRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("task settings status=%d body=%s", taskSettingsRecorder.Code, taskSettingsRecorder.Body.String())
|
||||
}
|
||||
// taskSettingsResponse 是账号任务设置具名响应 DTO。
|
||||
var taskSettingsResponse accountTaskSettingsResponse
|
||||
// taskSettingsDecodeErr 是账号任务设置响应 JSON 反序列化失败的原因。
|
||||
if taskSettingsDecodeErr := json.Unmarshal(taskSettingsRecorder.Body.Bytes(), &taskSettingsResponse); taskSettingsDecodeErr != nil {
|
||||
t.Fatalf("decode task settings response: %v", taskSettingsDecodeErr)
|
||||
}
|
||||
if taskSettingsResponse.AccountID != "acc1" {
|
||||
t.Fatalf("task settings response=%+v", taskSettingsResponse)
|
||||
}
|
||||
|
||||
// taskRunsReq 是读取账号任务执行记录的请求。
|
||||
taskRunsReq := httptest.NewRequest(http.MethodGet, "/api/account-tasks/acc1/runs", nil)
|
||||
taskRunsReq.AddCookie(sessionCookie)
|
||||
// taskRunsRecorder 是捕获账号任务执行记录响应的记录器。
|
||||
taskRunsRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(taskRunsRecorder, taskRunsReq)
|
||||
if taskRunsRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("task runs status=%d body=%s", taskRunsRecorder.Code, taskRunsRecorder.Body.String())
|
||||
}
|
||||
// taskRunsResponse 是账号任务执行记录列表具名响应 DTO。
|
||||
var taskRunsResponse accountTaskRunsResponse
|
||||
// taskRunsDecodeErr 是账号任务执行记录响应 JSON 反序列化失败的原因。
|
||||
if taskRunsDecodeErr := json.Unmarshal(taskRunsRecorder.Body.Bytes(), &taskRunsResponse); taskRunsDecodeErr != nil {
|
||||
t.Fatalf("decode task runs response: %v", taskRunsDecodeErr)
|
||||
}
|
||||
if taskRunsResponse.Runs == nil {
|
||||
t.Fatalf("task runs response=%+v", taskRunsResponse)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
@@ -878,3 +879,187 @@ type itemPublishBatchListResponse struct {
|
||||
// Batches 是当前用户的商品批量任务列表。
|
||||
Batches []itemPublishBatchResponse `json:"batches"`
|
||||
}
|
||||
|
||||
// keywordBasicResponse 是传统关键词接口的基础响应 DTO。
|
||||
type keywordBasicResponse struct {
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
}
|
||||
|
||||
// keywordItemResponse 是带商品范围的关键词响应 DTO。
|
||||
type keywordItemResponse struct {
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
// ItemID 是限定的商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
}
|
||||
|
||||
// keywordTypedResponse 是支持文本/图片类型的关键词响应 DTO。
|
||||
type keywordTypedResponse struct {
|
||||
// ID 是关键词规则主键。
|
||||
ID int64 `json:"id"`
|
||||
// Keyword 是匹配关键词。
|
||||
Keyword string `json:"keyword"`
|
||||
// Reply 是文字回复内容。
|
||||
Reply string `json:"reply"`
|
||||
// ItemID 是限定的商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// Type 是回复类型。
|
||||
Type string `json:"type"`
|
||||
// ImageURL 是图片回复地址。
|
||||
ImageURL string `json:"image_url"`
|
||||
}
|
||||
|
||||
// itemReplyResponse 是指定商品回复接口的具名 DTO。
|
||||
type itemReplyResponse struct {
|
||||
// ItemID 是商品平台标识。
|
||||
ItemID string `json:"item_id,omitempty"`
|
||||
// CookieID 是账号稳定标识。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// ReplyContent 是指定商品的回复内容。
|
||||
ReplyContent string `json:"reply_content"`
|
||||
}
|
||||
|
||||
// defaultReplyResponse 是默认回复接口的具名 DTO。
|
||||
type defaultReplyResponse struct {
|
||||
// CookieID 是账号稳定标识;单账号查询响应可以省略。
|
||||
CookieID string `json:"cookie_id,omitempty"`
|
||||
// Enabled 表示默认回复是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// ReplyContent 是默认文字回复内容。
|
||||
ReplyContent string `json:"reply_content"`
|
||||
// ReplyImageURL 是默认图片回复地址。
|
||||
ReplyImageURL string `json:"reply_image_url,omitempty"`
|
||||
// ReplyOnce 表示是否只回复一次。
|
||||
ReplyOnce bool `json:"reply_once"`
|
||||
}
|
||||
|
||||
// newDefaultReplyResponse 将数据库默认回复转换为 HTTP DTO。
|
||||
func newDefaultReplyResponse(cookieID string, reply db.DefaultReply) defaultReplyResponse {
|
||||
return defaultReplyResponse{
|
||||
CookieID: cookieID, Enabled: reply.Enabled, ReplyContent: reply.ReplyContent,
|
||||
ReplyImageURL: reply.ReplyImageURL, ReplyOnce: reply.ReplyOnce,
|
||||
}
|
||||
}
|
||||
|
||||
// accountTaskSettingsResponse 是账号任务设置接口的具名 DTO。
|
||||
type accountTaskSettingsResponse struct {
|
||||
// AccountID 是账号稳定标识。
|
||||
AccountID string `json:"account_id"`
|
||||
// AutoRateEnabled 表示自动评价是否启用。
|
||||
AutoRateEnabled bool `json:"auto_rate_enabled"`
|
||||
// RateContent 是自动评价文案。
|
||||
RateContent string `json:"rate_content"`
|
||||
// AutoPolishEnabled 表示自动擦亮是否启用。
|
||||
AutoPolishEnabled bool `json:"auto_polish_enabled"`
|
||||
// PolishTime 是自动擦亮本地时间。
|
||||
PolishTime string `json:"polish_time"`
|
||||
// LastRateScanAt 是最近一次评价扫描时间。
|
||||
LastRateScanAt int64 `json:"last_rate_scan_at"`
|
||||
// LastPolishDate 是最近一次擦亮日期。
|
||||
LastPolishDate string `json:"last_polish_date"`
|
||||
// LastPolishAt 是最近一次擦亮时间。
|
||||
LastPolishAt int64 `json:"last_polish_at"`
|
||||
}
|
||||
|
||||
// newAccountTaskSettingsResponse 将账号任务数据库设置转换为 HTTP DTO。
|
||||
func newAccountTaskSettingsResponse(settings db.AccountTaskSettings) accountTaskSettingsResponse {
|
||||
return accountTaskSettingsResponse{
|
||||
AccountID: settings.CookieID, AutoRateEnabled: settings.AutoRateEnabled, RateContent: settings.RateContent,
|
||||
AutoPolishEnabled: settings.AutoPolishEnabled, PolishTime: settings.PolishTime,
|
||||
LastRateScanAt: settings.LastRateScanAt, LastPolishDate: settings.LastPolishDate, LastPolishAt: settings.LastPolishAt,
|
||||
}
|
||||
}
|
||||
|
||||
// accountTaskRunResponse 是账号任务执行记录的具名 DTO。
|
||||
type accountTaskRunResponse struct {
|
||||
// ID 是任务执行记录主键。
|
||||
ID int64 `json:"id"`
|
||||
// RunKey 是任务幂等键。
|
||||
RunKey string `json:"run_key"`
|
||||
// AccountID 是账号稳定标识。
|
||||
AccountID string `json:"account_id"`
|
||||
// TaskType 是任务类型。
|
||||
TaskType string `json:"task_type"`
|
||||
// TargetID 是任务目标标识。
|
||||
TargetID string `json:"target_id"`
|
||||
// RunDate 是任务业务日期。
|
||||
RunDate string `json:"run_date"`
|
||||
// Status 是任务执行状态。
|
||||
Status string `json:"status"`
|
||||
// SuccessCount 是任务成功数量。
|
||||
SuccessCount int `json:"success_count"`
|
||||
// FailedCount 是任务失败数量。
|
||||
FailedCount int `json:"failed_count"`
|
||||
// ErrorMessage 是任务失败说明。
|
||||
ErrorMessage string `json:"error_message"`
|
||||
// NextRetryAt 是下一次重试时间。
|
||||
NextRetryAt int64 `json:"next_retry_at"`
|
||||
// StartedAt 是任务开始时间。
|
||||
StartedAt int64 `json:"started_at"`
|
||||
// FinishedAt 是任务完成时间。
|
||||
FinishedAt int64 `json:"finished_at"`
|
||||
}
|
||||
|
||||
// newAccountTaskRunResponse 将账号任务执行记录转换为 HTTP DTO。
|
||||
func newAccountTaskRunResponse(run db.AccountTaskRun) accountTaskRunResponse {
|
||||
return accountTaskRunResponse{
|
||||
ID: run.ID, RunKey: run.RunKey, AccountID: run.CookieID, TaskType: run.TaskType,
|
||||
TargetID: run.TargetID, RunDate: run.RunDate, Status: run.Status, SuccessCount: run.SuccessCount,
|
||||
FailedCount: run.FailedCount, ErrorMessage: run.ErrorMessage, NextRetryAt: run.NextRetryAt,
|
||||
StartedAt: run.StartedAt, FinishedAt: run.FinishedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// newAccountTaskRunResponses 批量转换账号任务执行记录。
|
||||
func newAccountTaskRunResponses(runs []db.AccountTaskRun) []accountTaskRunResponse {
|
||||
// result 是账号任务执行记录 DTO 列表。
|
||||
result := make([]accountTaskRunResponse, 0, len(runs))
|
||||
// run 是当前待转换的账号任务执行记录。
|
||||
for _, run := range runs {
|
||||
result = append(result, newAccountTaskRunResponse(run))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// accountTaskSummaryResponse 是手动执行账号任务的统计 DTO。
|
||||
type accountTaskSummaryResponse struct {
|
||||
// TaskType 是任务类型。
|
||||
TaskType string `json:"task_type"`
|
||||
// Found 是发现的目标数量。
|
||||
Found int `json:"found"`
|
||||
// Success 是成功处理数量。
|
||||
Success int `json:"success"`
|
||||
// Failed 是失败处理数量。
|
||||
Failed int `json:"failed"`
|
||||
// Skipped 是跳过数量。
|
||||
Skipped int `json:"skipped"`
|
||||
// Message 是任务结果说明。
|
||||
Message string `json:"message,omitempty"`
|
||||
}
|
||||
|
||||
// accountTaskRunResponseEnvelope 是手动执行账号任务的具名响应 DTO。
|
||||
type accountTaskRunResponseEnvelope struct {
|
||||
// Success 表示任务请求是否成功完成。
|
||||
Success bool `json:"success"`
|
||||
// Summary 是账号任务执行统计。
|
||||
Summary accountTaskSummaryResponse `json:"summary"`
|
||||
}
|
||||
|
||||
// accountTaskRunsResponse 是账号任务执行记录列表的具名响应 DTO。
|
||||
type accountTaskRunsResponse struct {
|
||||
// Runs 是当前账号最近的任务执行记录。
|
||||
Runs []accountTaskRunResponse `json:"runs"`
|
||||
}
|
||||
|
||||
// newAccountTaskSummaryResponse 将自动化中心统计转换为 HTTP DTO。
|
||||
func newAccountTaskSummaryResponse(summary automation.AccountTaskSummary) accountTaskSummaryResponse {
|
||||
return accountTaskSummaryResponse{
|
||||
TaskType: summary.TaskType, Found: summary.Found, Success: summary.Success,
|
||||
Failed: summary.Failed, Skipped: summary.Skipped, Message: summary.Message,
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user