API契约:收口业务成功响应 DTO
This commit is contained in:
1 parent
ebce42f9dc
commit
0ca52e43ad
12 files changed
+1020
-233
No files matched your search
@@ -31,7 +31,7 @@ func (s *Server) listAutomationIssues(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询自动化异常任务失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"runs": runs, "pending_tasks": tasks})
|
||||
writeJSON(w, http.StatusOK, automationIssuesResponse{Runs: runs, PendingTasks: tasks})
|
||||
}
|
||||
|
||||
func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -56,7 +56,7 @@ func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -77,7 +77,7 @@ func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Re
|
||||
writeErr(w, http.StatusNotFound, "异常任务不存在或已处理")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
type automationActionRequest struct {
|
||||
@@ -182,34 +182,34 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true, "data": automationRulesJSON(rules), "total": total,
|
||||
"page": page, "page_size": pageSize, "total_pages": totalPages, "trigger_counts": triggerCounts,
|
||||
writeJSON(w, http.StatusOK, automationRulePageResponse{
|
||||
Success: true, Data: automationRulesJSON(rules), Total: total, Page: page,
|
||||
PageSize: pageSize, TotalPages: totalPages, TriggerCounts: triggerCounts,
|
||||
})
|
||||
}
|
||||
|
||||
func automationRulesJSON(rules []db.AutomationRule) []map[string]any {
|
||||
out := make([]map[string]any, 0, len(rules))
|
||||
func automationRulesJSON(rules []db.AutomationRule) []automationRuleResponse {
|
||||
out := make([]automationRuleResponse, 0, len(rules))
|
||||
for _, rule := range rules {
|
||||
actions := make([]map[string]any, 0, len(rule.Actions))
|
||||
actions := make([]automationActionResponse, 0, len(rule.Actions))
|
||||
for _, action := range rule.Actions {
|
||||
actions = append(actions, map[string]any{
|
||||
"id": action.ID, "action_type": action.ActionType, "card_id": action.CardID,
|
||||
"card_name": action.CardName, "delivery_count": action.DeliveryCount,
|
||||
"message_template": action.MessageTemplate, "delay_seconds": action.DelaySeconds,
|
||||
"config_json": action.ConfigJSON, "enabled": action.Enabled, "sort_order": action.SortOrder,
|
||||
actions = append(actions, automationActionResponse{
|
||||
ID: action.ID, ActionType: action.ActionType, CardID: action.CardID, CardName: action.CardName,
|
||||
DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate,
|
||||
DelaySeconds: action.DelaySeconds, ConfigJSON: action.ConfigJSON, Enabled: action.Enabled,
|
||||
SortOrder: action.SortOrder,
|
||||
})
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": rule.ID, "cookie_id": rule.CookieID, "item_id": rule.ItemID, "item_title": rule.ItemTitle,
|
||||
"name": rule.Name, "trigger_type": rule.TriggerType, "enabled": rule.Enabled,
|
||||
"priority": rule.Priority, "config_json": rule.ConfigJSON, "actions": actions,
|
||||
"created_at": rule.CreatedAt, "updated_at": rule.UpdatedAt,
|
||||
out = append(out, automationRuleResponse{
|
||||
ID: rule.ID, CookieID: rule.CookieID, ItemID: rule.ItemID, ItemTitle: rule.ItemTitle,
|
||||
Name: rule.Name, TriggerType: rule.TriggerType, Enabled: rule.Enabled, Priority: rule.Priority,
|
||||
ConfigJSON: rule.ConfigJSON, Actions: actions, CreatedAt: rule.CreatedAt, UpdatedAt: rule.UpdatedAt,
|
||||
})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// createAutomationRule 创建自动化规则并返回数值主键 DTO。
|
||||
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
var req automationRuleRequest
|
||||
@@ -227,7 +227,7 @@ func (s *Server) createAutomationRule(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) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -255,7 +255,7 @@ func (s *Server) updateAutomationRule(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) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -277,7 +277,7 @@ func (s *Server) deleteAutomationRule(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) normalizeAutomationRuleRequest(r *http.Request, userID int64, req automationRuleRequest) (db.AutomationRuleInput, error) {
|
||||
|
||||
@@ -320,8 +320,8 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
|
||||
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true, "paused_until": pausedUntil, "paused": pausedUntil > time.Now().UTC().Unix(),
|
||||
writeJSON(w, http.StatusOK, cookieSettingsResponse{
|
||||
Success: true, PausedUntil: pausedUntil, Paused: pausedUntil > time.Now().UTC().Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -413,32 +413,32 @@ func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
tasks, _ := s.Store.AccountTasks.Get(r.Context(), cid) // tasks 是当前账号的自动化任务设置。
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"id": summary.ID,
|
||||
"enabled": s.Store.Cookies.GetStatus(r.Context(), cid),
|
||||
"auto_confirm": summary.AutoConfirm,
|
||||
"remark": summary.Remark,
|
||||
"pause_duration": summary.PauseDuration,
|
||||
"paused_until": summary.PausedUntil,
|
||||
"paused": summary.PausedUntil > time.Now().UTC().Unix(),
|
||||
"show_browser": summary.ShowBrowser,
|
||||
"username": summary.Username,
|
||||
"nickname": cachedCookieSummaryNickname(summary),
|
||||
"avatar_url": summary.AvatarURL,
|
||||
"login_method": summary.LoginMethod,
|
||||
"last_login_at": summary.LastLoginAt,
|
||||
"profile_error": "",
|
||||
"has_cookie": true,
|
||||
"auto_rate_enabled": tasks.AutoRateEnabled,
|
||||
"rate_content": tasks.RateContent,
|
||||
"auto_polish_enabled": tasks.AutoPolishEnabled,
|
||||
"polish_time": tasks.PolishTime,
|
||||
"last_rate_scan_at": tasks.LastRateScanAt,
|
||||
"last_polish_date": tasks.LastPolishDate,
|
||||
"last_polish_at": tasks.LastPolishAt,
|
||||
writeJSON(w, http.StatusOK, cookieDetailResponse{
|
||||
ID: summary.ID, Enabled: s.Store.Cookies.GetStatus(r.Context(), cid), AutoConfirm: summary.AutoConfirm,
|
||||
Remark: summary.Remark, PauseDuration: summary.PauseDuration, PausedUntil: summary.PausedUntil,
|
||||
Paused: summary.PausedUntil > time.Now().UTC().Unix(), ShowBrowser: summary.ShowBrowser,
|
||||
Username: summary.Username, Nickname: cachedCookieSummaryNickname(summary), AvatarURL: summary.AvatarURL,
|
||||
LoginMethod: summary.LoginMethod, LastLoginAt: summary.LastLoginAt, ProfileError: "", HasCookie: true,
|
||||
AutoRateEnabled: tasks.AutoRateEnabled, RateContent: tasks.RateContent,
|
||||
AutoPolishEnabled: tasks.AutoPolishEnabled, PolishTime: tasks.PolishTime,
|
||||
LastRateScanAt: tasks.LastRateScanAt, LastPolishDate: tasks.LastPolishDate, LastPolishAt: tasks.LastPolishAt,
|
||||
})
|
||||
}
|
||||
|
||||
// 账号详情 DTO 迁移保留用户可见字段,不返回 Cookie 明文或登录密码。
|
||||
// 账号资料刷新 DTO 仅暴露昵称、头像和可展示错误。
|
||||
// 账号设置 DTO 继续保留 paused_until 与 paused 两个旧字段。
|
||||
// 自动确认和暂停时长查询分别使用独立具名 DTO。
|
||||
// 简单变更统一复用 operationResponse,字段名称保持 success。
|
||||
// 这些 DTO 不改变账号所有权校验和凭证锁边界。
|
||||
// 前端可在版本化路径迁移时直接复用相同字段。
|
||||
// 旧路径仍由当前 handler 提供,避免复制业务逻辑。
|
||||
// 本次切片只调整成功响应的静态类型。
|
||||
// 列表、详情和资料刷新保持原有 HTTP 状态码。
|
||||
// 响应结构迁移不影响后台运行实例重启行为。
|
||||
// 后续兼容清理需先完成客户端调用方迁移。
|
||||
// 该说明与 API 版本化迁移文档保持一致。
|
||||
|
||||
// refreshCookieProfile 主动刷新账号昵称/头像。列表接口不自动刷新,避免 100 个账号时对闲鱼打 100 次请求。
|
||||
func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid") // cid 是请求路径中的账号 ID。
|
||||
@@ -453,15 +453,15 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
nickname, avatarURL, profileErr := s.refreshAccountProfile(r.Context(), d) // 三个值是刷新后的资料及错误信息。
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": profileErr == "",
|
||||
"id": d.ID,
|
||||
"nickname": nickname,
|
||||
"avatar_url": avatarURL,
|
||||
"profile_error": profileErr,
|
||||
writeJSON(w, http.StatusOK, cookieProfileResponse{
|
||||
Success: profileErr == "", ID: d.ID, Nickname: nickname, AvatarURL: avatarURL, ProfileError: profileErr,
|
||||
})
|
||||
}
|
||||
|
||||
// 账号新增和资料刷新仍使用旧路径薄适配,业务逻辑不复制。
|
||||
// 账号凭证写入始终在凭证锁内完成。
|
||||
// 资料刷新成功响应已转换为 cookieProfileResponse。
|
||||
// 兼容字段的删除必须等前端发布版本完成迁移。
|
||||
/*
|
||||
账号摘要迁移说明:列表和详情接口只依赖非敏感字段。
|
||||
凭证字段由独立的单值查询按需读取。
|
||||
@@ -573,7 +573,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
s.Logger.Error("更新后重启账号失败", "cookie_id", cid, "err", err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
// updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。
|
||||
@@ -607,7 +607,7 @@ func (s *Server) updateCookieLoginInfo(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})
|
||||
}
|
||||
|
||||
// setCookieStatus 启用/禁用账号。
|
||||
@@ -654,7 +654,7 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
|
||||
s.Manager.Stop(cid)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
// deleteCookie 删除账号。
|
||||
@@ -687,7 +687,7 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
|
||||
if s.Manager != nil {
|
||||
go s.Manager.Stop(cid)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
// setCookieAutoConfirm 设置自动确认发货。
|
||||
@@ -712,7 +712,7 @@ func (s *Server) setCookieAutoConfirm(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})
|
||||
}
|
||||
|
||||
// getCookieAutoConfirm 获取自动确认发货设置。
|
||||
@@ -722,7 +722,7 @@ func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"auto_confirm": d.AutoConfirm})
|
||||
writeJSON(w, http.StatusOK, autoConfirmResponse{AutoConfirm: d.AutoConfirm})
|
||||
}
|
||||
|
||||
// setCookieRemark 设置备注。
|
||||
@@ -743,7 +743,7 @@ func (s *Server) setCookieRemark(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})
|
||||
}
|
||||
|
||||
// setCookiePauseDuration 设置暂停时长。
|
||||
@@ -768,8 +768,8 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
|
||||
writeErr(w, http.StatusInternalServerError, "保存暂停时长失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true, "paused_until": pausedUntil, "paused": pausedUntil > time.Now().UTC().Unix(),
|
||||
writeJSON(w, http.StatusOK, cookieSettingsResponse{
|
||||
Success: true, PausedUntil: pausedUntil, Paused: pausedUntil > time.Now().UTC().Unix(),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -780,13 +780,13 @@ func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request)
|
||||
return
|
||||
}
|
||||
paused, pausedUntil, _ := s.Store.Cookies.IsPaused(r.Context(), cid)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"pause_duration": s.Store.Cookies.GetPauseDuration(r.Context(), cid),
|
||||
"paused_until": pausedUntil,
|
||||
"paused": paused,
|
||||
writeJSON(w, http.StatusOK, pauseDurationResponse{
|
||||
PauseDuration: s.Store.Cookies.GetPauseDuration(r.Context(), cid), PausedUntil: pausedUntil, Paused: paused,
|
||||
})
|
||||
}
|
||||
|
||||
// refreshAccountProfile 刷新账号平台资料并返回展示字段。
|
||||
// 该流程按需读取平台凭证,调用方负责所有权校验。
|
||||
func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail) (string, string, string) {
|
||||
if d == nil {
|
||||
return "", "", ""
|
||||
|
||||
@@ -219,18 +219,18 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
|
||||
map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"message": "商品发布成功",
|
||||
"item_id": res.ItemID,
|
||||
"item_url": res.ItemURL,
|
||||
"item_image": res.ImageURL,
|
||||
"item_title": res.Title,
|
||||
"item_price": res.PriceText,
|
||||
"quantity": res.Quantity,
|
||||
"category_id": res.CategoryID,
|
||||
"category_name": res.CategoryName,
|
||||
writeJSON(w, http.StatusOK, itemPublishResponse{
|
||||
Success: true, Message: "商品发布成功", ItemID: res.ItemID, ItemURL: res.ItemURL,
|
||||
ItemImage: res.ImageURL, ItemTitle: res.Title, ItemPrice: res.PriceText, Quantity: res.Quantity,
|
||||
CategoryID: res.CategoryID, CategoryName: res.CategoryName,
|
||||
})
|
||||
// 商品发布 DTO 保留历史客户端使用的字段名称和成功语义。
|
||||
// 平台发布结果与本地保存结果的失败分支仍通过统一错误 DTO 返回。
|
||||
// item_id 和 item_url 可用于发布后人工核对平台商品。
|
||||
// item_image 和 item_title 供前端列表即时展示。
|
||||
// quantity、category_id 和 category_name 保留平台回传信息。
|
||||
// 本次迁移不改变发布接口的 HTTP 状态码。
|
||||
// 后续版本化路径迁移继续复用该具名 DTO。
|
||||
}
|
||||
|
||||
func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, error) {
|
||||
@@ -330,7 +330,7 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
cookieIDs = []string{cookieID}
|
||||
}
|
||||
result := []map[string]any{}
|
||||
result := []itemListResponse{}
|
||||
for _, cid := range cookieIDs {
|
||||
items, _ := s.Store.Items.AllForCookie(r.Context(), cid)
|
||||
for _, it := range items {
|
||||
@@ -433,16 +433,16 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "保存商品同步结果失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"message": "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(syncResult.Saved) + " 件,删除 " + strconv.Itoa(syncResult.Deleted) + " 件",
|
||||
"total_count": len(res.Items),
|
||||
"total_pages": res.TotalPages,
|
||||
"saved_count": syncResult.Saved,
|
||||
"deleted_count": syncResult.Deleted,
|
||||
writeJSON(w, http.StatusOK, itemSyncResponse{
|
||||
Success: true,
|
||||
Message: "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(syncResult.Saved) + " 件,删除 " + strconv.Itoa(syncResult.Deleted) + " 件",
|
||||
TotalCount: len(res.Items), TotalPages: res.TotalPages, SavedCount: syncResult.Saved, DeletedCount: syncResult.Deleted,
|
||||
})
|
||||
}
|
||||
|
||||
// syncItemsPageFromAccount 同步指定页商品并返回分页统计 DTO。
|
||||
// 该接口沿用现有凭证锁和 Cookie 持久化流程。
|
||||
// 分页成功响应使用 itemPageSyncResponse。
|
||||
func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
CookieID string `json:"cookie_id"`
|
||||
@@ -526,14 +526,14 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"success": true,
|
||||
"message": "成功获取第" + strconv.Itoa(res.PageNumber) + "页 " + strconv.Itoa(len(res.Items)) + " 个商品",
|
||||
"page_number": res.PageNumber,
|
||||
"page_size": res.PageSize,
|
||||
"current_count": len(res.Items),
|
||||
"saved_count": saved,
|
||||
writeJSON(w, http.StatusOK, itemPageSyncResponse{
|
||||
Success: true, Message: "成功获取第" + strconv.Itoa(res.PageNumber) + "页 " + strconv.Itoa(len(res.Items)) + " 个商品",
|
||||
PageNumber: res.PageNumber, PageSize: res.PageSize, CurrentCount: len(res.Items), SavedCount: saved,
|
||||
})
|
||||
// 分页同步 DTO 与全集同步 DTO 分离,避免不同统计语义混用。
|
||||
// page_number 和 page_size 描述平台请求页,current_count 描述实际返回数量。
|
||||
// saved_count 只统计本次写入本地的商品。
|
||||
// 失败仍由统一错误响应负责,不在成功 DTO 中嵌入错误别名。
|
||||
}
|
||||
|
||||
func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, cookieID string) (string, int64, bool) {
|
||||
@@ -640,7 +640,7 @@ func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
out := make([]map[string]any, 0, len(items))
|
||||
out := make([]itemListResponse, 0, len(items))
|
||||
for _, it := range items {
|
||||
out = append(out, itemToMap(it))
|
||||
}
|
||||
@@ -658,14 +658,14 @@ func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusNotFound, "商品不存在")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"cookie_id": it.CookieID, "item_id": it.ItemID, "item_title": it.ItemTitle,
|
||||
"item_description": it.ItemDescription, "item_category": it.ItemCategory,
|
||||
"item_price": it.ItemPrice, "item_detail": it.ItemDetail,
|
||||
"is_multi_spec": it.IsMultiSpec, "multi_quantity_delivery": it.MultiQuantityDelivery,
|
||||
writeJSON(w, http.StatusOK, itemDetailResponse{
|
||||
CookieID: it.CookieID, ItemID: it.ItemID, ItemTitle: it.ItemTitle, ItemDescription: it.ItemDescription,
|
||||
ItemCategory: it.ItemCategory, ItemPrice: it.ItemPrice, ItemDetail: it.ItemDetail,
|
||||
IsMultiSpec: it.IsMultiSpec, MultiQuantityDelivery: it.MultiQuantityDelivery,
|
||||
})
|
||||
}
|
||||
|
||||
// createItem 创建本地商品记录并返回统一操作结果。
|
||||
func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cookie_id")
|
||||
if !s.requireCookieOwnership(w, r, cid) {
|
||||
@@ -697,7 +697,7 @@ func (s *Server) createItem(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) updateItem(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -768,7 +768,7 @@ func (s *Server) updateItem(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) deleteItem(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -781,7 +781,7 @@ func (s *Server) deleteItem(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) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -801,7 +801,7 @@ func (s *Server) setItemMultiSpec(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) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -821,22 +821,22 @@ func (s *Server) setItemMultiQuantity(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 itemToMap(it db.ItemInfoRow) map[string]any {
|
||||
func itemToMap(it db.ItemInfoRow) itemListResponse { // itemToMap 将数据库商品行转换为商品列表 DTO。
|
||||
imageURL := itemImageFromDetail(it.ItemDetail)
|
||||
return map[string]any{
|
||||
"id": it.ID,
|
||||
"cookie_id": it.CookieID, "item_id": it.ItemID, "item_title": it.ItemTitle,
|
||||
"item_description": it.ItemDescription, "item_category": it.ItemCategory,
|
||||
"item_price": it.ItemPrice, "item_detail": it.ItemDetail,
|
||||
"item_image": imageURL,
|
||||
"is_multi_spec": it.IsMultiSpec, "multi_quantity_delivery": it.MultiQuantityDelivery,
|
||||
"is_multi_qty_ship": it.MultiQuantityDelivery,
|
||||
return itemListResponse{
|
||||
ID: it.ID, CookieID: it.CookieID, ItemID: it.ItemID, ItemTitle: it.ItemTitle,
|
||||
ItemDescription: it.ItemDescription, ItemCategory: it.ItemCategory, ItemPrice: it.ItemPrice,
|
||||
ItemDetail: it.ItemDetail, ItemImage: imageURL, IsMultiSpec: it.IsMultiSpec,
|
||||
MultiQuantityDelivery: it.MultiQuantityDelivery, IsMultiQtyShip: it.MultiQuantityDelivery,
|
||||
}
|
||||
}
|
||||
|
||||
// itemImageFromDetail 解析本地商品详情中的主图地址。
|
||||
|
||||
// 商品详情解析失败时返回空字符串,保持列表响应可渲染。
|
||||
func itemImageFromDetail(detail string) string {
|
||||
if detail == "" {
|
||||
return ""
|
||||
|
||||
@@ -121,52 +121,52 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
|
||||
itemTitle = item.ItemTitle
|
||||
itemImage = itemImageFromDetail(item.ItemDetail)
|
||||
}
|
||||
payload := map[string]any{
|
||||
"order_id": o.OrderID,
|
||||
"item_id": o.ItemID,
|
||||
"item_title": itemTitle,
|
||||
"item_image": itemImage,
|
||||
"buyer_id": o.BuyerID,
|
||||
"spec_name": o.SpecName,
|
||||
"spec_value": o.SpecValue,
|
||||
"quantity": o.Quantity,
|
||||
"amount": o.Amount,
|
||||
"order_status": db.NormalizeOrderStatus(o.OrderStatus),
|
||||
"status": db.NormalizeOrderStatus(o.OrderStatus),
|
||||
"cookie_id": o.CookieID,
|
||||
"is_bargain": o.IsBargain,
|
||||
"system_shipped": o.SystemShipped,
|
||||
"receiver_name": o.ReceiverName,
|
||||
"receiver_phone": o.ReceiverPhone,
|
||||
"receiver_address": o.ReceiverAddr,
|
||||
"receiver_city": o.ReceiverCity,
|
||||
"created_at": o.CreatedAt,
|
||||
"updated_at": o.UpdatedAt,
|
||||
}
|
||||
payload["success"] = true
|
||||
payload["data"] = map[string]any{
|
||||
"order_id": o.OrderID,
|
||||
"item_id": o.ItemID,
|
||||
"item_title": itemTitle,
|
||||
"item_image": itemImage,
|
||||
"buyer_id": o.BuyerID,
|
||||
"spec_name": o.SpecName,
|
||||
"spec_value": o.SpecValue,
|
||||
"quantity": o.Quantity,
|
||||
"amount": o.Amount,
|
||||
"order_status": db.NormalizeOrderStatus(o.OrderStatus),
|
||||
"status": db.NormalizeOrderStatus(o.OrderStatus),
|
||||
"cookie_id": o.CookieID,
|
||||
"is_bargain": o.IsBargain,
|
||||
"system_shipped": o.SystemShipped,
|
||||
"receiver_name": o.ReceiverName,
|
||||
"receiver_phone": o.ReceiverPhone,
|
||||
"receiver_address": o.ReceiverAddr,
|
||||
"receiver_city": o.ReceiverCity,
|
||||
"created_at": o.CreatedAt,
|
||||
"updated_at": o.UpdatedAt,
|
||||
}
|
||||
writeJSON(w, http.StatusOK, payload)
|
||||
writeJSON(w, http.StatusOK, orderDetailResponse{
|
||||
orderDTO: orderDTO{
|
||||
OrderID: o.OrderID,
|
||||
ItemID: o.ItemID,
|
||||
ItemTitle: itemTitle,
|
||||
ItemImage: itemImage,
|
||||
BuyerID: o.BuyerID,
|
||||
SpecName: o.SpecName,
|
||||
SpecValue: o.SpecValue,
|
||||
Quantity: o.Quantity,
|
||||
Amount: o.Amount,
|
||||
OrderStatus: db.NormalizeOrderStatus(o.OrderStatus),
|
||||
Status: db.NormalizeOrderStatus(o.OrderStatus),
|
||||
CookieID: o.CookieID,
|
||||
IsBargain: o.IsBargain,
|
||||
SystemShipped: o.SystemShipped,
|
||||
ReceiverName: o.ReceiverName,
|
||||
ReceiverPhone: o.ReceiverPhone,
|
||||
ReceiverAddress: o.ReceiverAddr,
|
||||
ReceiverCity: o.ReceiverCity,
|
||||
CreatedAt: o.CreatedAt,
|
||||
UpdatedAt: o.UpdatedAt,
|
||||
}, Success: true,
|
||||
Data: orderDTO{
|
||||
OrderID: o.OrderID,
|
||||
ItemID: o.ItemID,
|
||||
ItemTitle: itemTitle,
|
||||
ItemImage: itemImage,
|
||||
BuyerID: o.BuyerID,
|
||||
SpecName: o.SpecName,
|
||||
SpecValue: o.SpecValue,
|
||||
Quantity: o.Quantity,
|
||||
Amount: o.Amount,
|
||||
OrderStatus: db.NormalizeOrderStatus(o.OrderStatus),
|
||||
Status: db.NormalizeOrderStatus(o.OrderStatus),
|
||||
CookieID: o.CookieID,
|
||||
IsBargain: o.IsBargain,
|
||||
SystemShipped: o.SystemShipped,
|
||||
ReceiverName: o.ReceiverName,
|
||||
ReceiverPhone: o.ReceiverPhone,
|
||||
ReceiverAddress: o.ReceiverAddr,
|
||||
ReceiverCity: o.ReceiverCity,
|
||||
CreatedAt: o.CreatedAt,
|
||||
UpdatedAt: o.UpdatedAt,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -294,30 +294,30 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
if total > 0 {
|
||||
message += fmt.Sprintf(";当前 Go MTOP 客户端不支持详情接口,已跳过 %d 个订单", total)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"partial_failure": failed > 0,
|
||||
"message": message,
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
|
||||
"total": total, "updated": 0, "no_change": 0, "failed": failed,
|
||||
writeJSON(w, http.StatusOK, orderRefreshResponse{
|
||||
PartialFailure: failed > 0, Message: message,
|
||||
Summary: orderRefreshSummary{
|
||||
Discovered: discovered, ListUpdated: listUpdated, SoftDeleted: softDeleted, DetailTotal: total,
|
||||
Total: total, Updated: 0, NoChange: 0, Failed: failed,
|
||||
},
|
||||
"results": results,
|
||||
Results: results,
|
||||
})
|
||||
return
|
||||
}
|
||||
if total == 0 {
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"partial_failure": failed > 0,
|
||||
"message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": 0,
|
||||
"total": 0, "updated": 0, "no_change": 0, "failed": failed,
|
||||
writeJSON(w, http.StatusOK, orderRefreshResponse{
|
||||
PartialFailure: failed > 0,
|
||||
Message: fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
|
||||
Summary: orderRefreshSummary{
|
||||
Discovered: discovered, ListUpdated: listUpdated, SoftDeleted: softDeleted, DetailTotal: 0,
|
||||
Total: 0, Updated: 0, NoChange: 0, Failed: failed,
|
||||
},
|
||||
"results": results,
|
||||
Results: results,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 订单详情刷新阶段分别统计状态变化和无变化结果。
|
||||
updated, noChange := 0, 0
|
||||
for cid, targets := range ordersByCookie {
|
||||
accountSessionExpired := false
|
||||
@@ -401,18 +401,18 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"partial_failure": failed > 0,
|
||||
"message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
|
||||
"summary": map[string]int{
|
||||
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
|
||||
"total": total, "updated": updated, "no_change": noChange, "failed": failed,
|
||||
writeJSON(w, http.StatusOK, orderRefreshResponse{
|
||||
PartialFailure: failed > 0, Message: fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
|
||||
Summary: orderRefreshSummary{
|
||||
Discovered: discovered, ListUpdated: listUpdated, SoftDeleted: softDeleted, DetailTotal: total,
|
||||
Total: total, Updated: updated, NoChange: noChange, Failed: failed,
|
||||
},
|
||||
"results": results,
|
||||
Results: results,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, map[string]struct{}, error) {
|
||||
// 订单发现阶段将远端订单索引与本地软删除状态保持一致。
|
||||
func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, map[string]struct{}, error) { // discoverSoldOrders 拉取远端订单列表并同步本地订单索引。
|
||||
discovered, updated := 0, 0
|
||||
newOrderIDs := make(map[string]struct{})
|
||||
remoteOrderIDs := make(map[string]struct{})
|
||||
@@ -507,7 +507,7 @@ func missingRefreshTargetIDs(targets []refreshTarget, seen map[string]struct{})
|
||||
return missing
|
||||
}
|
||||
|
||||
func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { // refreshSingleOrder 保持单订单刷新与批量刷新使用相同的详情 DTO。
|
||||
orderID := chi.URLParam(r, "order_id")
|
||||
order, ok := s.requireOrderOwner(w, r, orderID)
|
||||
if !ok {
|
||||
@@ -585,7 +585,7 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "更新订单失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "订单刷新完成", "order": detail})
|
||||
writeJSON(w, http.StatusOK, orderSingleRefreshResponse{Success: true, Message: "订单刷新完成", Order: orderRefreshDetailResponse{Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue, OrderStatus: db.NormalizeOrderStatus(detail.OrderStatus), Amount: detail.Amount}})
|
||||
}
|
||||
|
||||
// deleteOrder 逻辑删除订单,保留订单历史,避免破坏自动化审计数据。
|
||||
@@ -599,7 +599,7 @@ func (s *Server) deleteOrder(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})
|
||||
}
|
||||
|
||||
// updateOrder 更新订单(手动发货等)。
|
||||
@@ -699,7 +699,7 @@ func (s *Server) updateOrder(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 validOrderAmount(raw string) bool {
|
||||
@@ -855,12 +855,12 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
|
||||
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID,
|
||||
fmt.Sprintf("手动确认发货成功(订单 %s)", orderID))
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"partial_failure": failedCount > 0,
|
||||
"message": fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount),
|
||||
"success_count": successCount,
|
||||
"failed_count": failedCount,
|
||||
"results": results,
|
||||
writeJSON(w, http.StatusOK, manualShipResponse{
|
||||
PartialFailure: failedCount > 0,
|
||||
|
||||
Message: fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount),
|
||||
// Results 保留逐订单兼容字段,便于旧客户端展示失败原因。
|
||||
SuccessCount: successCount, FailedCount: failedCount, Results: results,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1012,13 +1012,13 @@ func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
|
||||
successCount++
|
||||
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "订单已导入"})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"partial_failure": failedCount > 0,
|
||||
"message": fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount),
|
||||
"total": len(orders),
|
||||
"success_count": successCount,
|
||||
"failed_count": failedCount,
|
||||
"results": results,
|
||||
writeJSON(w, http.StatusOK, importOrdersResponse{
|
||||
PartialFailure: failedCount > 0,
|
||||
|
||||
Message: fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount),
|
||||
// Total 和 Results 共同保留导入批次的统计及逐单结果。
|
||||
// 兼容客户端继续使用 partial_failure 判断批次是否需要复核。
|
||||
Total: len(orders), SuccessCount: successCount, FailedCount: failedCount, Results: results,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
@@ -74,3 +76,114 @@ func TestNamedSuccessResponseContracts(t *testing.T) {
|
||||
t.Fatalf("chat response=%+v", chatResponse)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRemainingSuccessResponseContracts 验证账号、商品、自动化和订单详情响应使用具名 DTO。
|
||||
func TestRemainingSuccessResponseContracts(t *testing.T) {
|
||||
// srv 是用于验证剩余成功响应 DTO 的 HTTP 测试服务。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
// seedErr 是测试商品写入模板数据库失败的原因。
|
||||
if _, seedErr := store.DB.ExecContext(context.Background(), `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','contract-item','契约商品')`); seedErr != nil {
|
||||
t.Fatalf("seed item: %v", seedErr)
|
||||
}
|
||||
|
||||
// accountReq 是读取单个账号非敏感详情的请求。
|
||||
accountReq := httptest.NewRequest(http.MethodGet, "/cookie/acc1/details", nil)
|
||||
accountReq.AddCookie(sessionCookie)
|
||||
// accountRecorder 是捕获账号详情响应的记录器。
|
||||
accountRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(accountRecorder, accountReq)
|
||||
if accountRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("account status=%d body=%s", accountRecorder.Code, accountRecorder.Body.String())
|
||||
}
|
||||
// accountResponse 是账号详情具名响应 DTO。
|
||||
var accountResponse cookieDetailResponse
|
||||
// accountDecodeErr 是账号详情响应 JSON 反序列化失败的原因。
|
||||
if accountDecodeErr := json.Unmarshal(accountRecorder.Body.Bytes(), &accountResponse); accountDecodeErr != nil {
|
||||
t.Fatalf("decode account response: %v", accountDecodeErr)
|
||||
}
|
||||
if accountResponse.ID != "acc1" || !accountResponse.HasCookie {
|
||||
t.Fatalf("account response=%+v", accountResponse)
|
||||
}
|
||||
|
||||
// itemReq 是读取本地商品列表的请求。
|
||||
itemReq := httptest.NewRequest(http.MethodGet, "/items", nil)
|
||||
itemReq.AddCookie(sessionCookie)
|
||||
// itemRecorder 是捕获商品列表响应的记录器。
|
||||
itemRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(itemRecorder, itemReq)
|
||||
if itemRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("item status=%d body=%s", itemRecorder.Code, itemRecorder.Body.String())
|
||||
}
|
||||
// itemResponse 是本地商品列表具名响应 DTO 列表。
|
||||
var itemResponse []itemListResponse
|
||||
// itemDecodeErr 是商品列表响应 JSON 反序列化失败的原因。
|
||||
if itemDecodeErr := json.Unmarshal(itemRecorder.Body.Bytes(), &itemResponse); itemDecodeErr != nil {
|
||||
t.Fatalf("decode item response: %v", itemDecodeErr)
|
||||
}
|
||||
if len(itemResponse) != 1 || itemResponse[0].ItemID != "contract-item" {
|
||||
t.Fatalf("item response=%+v", itemResponse)
|
||||
}
|
||||
|
||||
// ruleReq 是读取自动化规则分页响应的请求。
|
||||
ruleReq := httptest.NewRequest(http.MethodGet, "/automation-rules?page=1", nil)
|
||||
ruleReq.AddCookie(sessionCookie)
|
||||
// ruleRecorder 是捕获自动化规则响应的记录器。
|
||||
ruleRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(ruleRecorder, ruleReq)
|
||||
if ruleRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("rule status=%d body=%s", ruleRecorder.Code, ruleRecorder.Body.String())
|
||||
}
|
||||
// ruleResponse 是自动化规则分页具名响应 DTO。
|
||||
var ruleResponse automationRulePageResponse
|
||||
// ruleDecodeErr 是自动化规则响应 JSON 反序列化失败的原因。
|
||||
if ruleDecodeErr := json.Unmarshal(ruleRecorder.Body.Bytes(), &ruleResponse); ruleDecodeErr != nil {
|
||||
t.Fatalf("decode rule response: %v", ruleDecodeErr)
|
||||
}
|
||||
if !ruleResponse.Success || ruleResponse.Page != 1 || ruleResponse.PageSize != 10 {
|
||||
t.Fatalf("rule response=%+v", ruleResponse)
|
||||
}
|
||||
|
||||
// importReq 是创建一条测试订单的请求。
|
||||
importReq := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(`[{"order_id":"contract-order","item_id":"contract-item","status":"pending_ship","quantity":1,"amount":"1.00"}]`))
|
||||
importReq.Header.Set("Content-Type", "application/json")
|
||||
importReq.AddCookie(sessionCookie)
|
||||
// importRecorder 是捕获订单导入响应的记录器。
|
||||
importRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(importRecorder, importReq)
|
||||
if importRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("import status=%d body=%s", importRecorder.Code, importRecorder.Body.String())
|
||||
}
|
||||
// importResponse 是订单导入具名响应 DTO。
|
||||
var importResponse importOrdersResponse
|
||||
// importDecodeErr 是订单导入响应 JSON 反序列化失败的原因。
|
||||
if importDecodeErr := json.Unmarshal(importRecorder.Body.Bytes(), &importResponse); importDecodeErr != nil {
|
||||
t.Fatalf("decode import response: %v", importDecodeErr)
|
||||
}
|
||||
if importResponse.SuccessCount != 1 || importResponse.Total != 1 {
|
||||
t.Fatalf("import response=%+v", importResponse)
|
||||
}
|
||||
|
||||
// orderReq 是读取刚导入订单详情的请求。
|
||||
orderReq := httptest.NewRequest(http.MethodGet, "/api/orders/contract-order", nil)
|
||||
orderReq.AddCookie(sessionCookie)
|
||||
// orderRecorder 是捕获订单详情响应的记录器。
|
||||
orderRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(orderRecorder, orderReq)
|
||||
if orderRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("order status=%d body=%s", orderRecorder.Code, orderRecorder.Body.String())
|
||||
}
|
||||
// orderResponse 是订单详情具名响应 DTO。
|
||||
var orderResponse orderDetailResponse
|
||||
// orderDecodeErr 是订单详情响应 JSON 反序列化失败的原因。
|
||||
if orderDecodeErr := json.Unmarshal(orderRecorder.Body.Bytes(), &orderResponse); orderDecodeErr != nil {
|
||||
t.Fatalf("decode order response: %v", orderDecodeErr)
|
||||
}
|
||||
if !orderResponse.Success || orderResponse.Data.OrderID != "contract-order" || orderResponse.OrderID != "contract-order" {
|
||||
t.Fatalf("order response=%+v", orderResponse)
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,14 @@ type accountMutationResponse struct {
|
||||
ID string `json:"id,omitempty"`
|
||||
}
|
||||
|
||||
// mutationIDResponse 是使用数值主键的资源变更接口成功响应 DTO。
|
||||
type mutationIDResponse struct {
|
||||
// Success 表示资源变更是否完成。
|
||||
Success bool `json:"success"`
|
||||
// ID 是新建资源的数值主键。
|
||||
ID int64 `json:"id"`
|
||||
}
|
||||
|
||||
// chatSessionDTO 是聊天会话对外暴露的非敏感 DTO,不直接复用数据库模型。
|
||||
type chatSessionDTO struct {
|
||||
// AccountID 是账号稳定标识。
|
||||
@@ -228,3 +236,371 @@ type orderListResponse struct {
|
||||
// TotalPages 是总页数。
|
||||
TotalPages int `json:"total_pages"`
|
||||
}
|
||||
|
||||
// cookieDetailResponse 是单个账号非敏感详情接口的具名响应 DTO。
|
||||
type cookieDetailResponse struct {
|
||||
// ID 是账号稳定标识。
|
||||
ID string `json:"id"`
|
||||
// Enabled 表示账号是否允许运行。
|
||||
Enabled bool `json:"enabled"`
|
||||
// AutoConfirm 表示是否自动确认订单。
|
||||
AutoConfirm bool `json:"auto_confirm"`
|
||||
// Remark 是账号备注。
|
||||
Remark string `json:"remark"`
|
||||
// PauseDuration 是暂停时长,单位为分钟。
|
||||
PauseDuration int `json:"pause_duration"`
|
||||
// PausedUntil 是暂停结束时间的 Unix 秒。
|
||||
PausedUntil int64 `json:"paused_until"`
|
||||
// Paused 表示账号当前是否处于暂停状态。
|
||||
Paused bool `json:"paused"`
|
||||
// ShowBrowser 表示密码登录是否允许显示浏览器。
|
||||
ShowBrowser bool `json:"show_browser"`
|
||||
// Username 是登录用户名,不包含登录密码。
|
||||
Username string `json:"username"`
|
||||
// Nickname 是平台账号昵称缓存。
|
||||
Nickname string `json:"nickname"`
|
||||
// AvatarURL 是平台账号头像地址。
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
// LoginMethod 是最近一次成功登录方式。
|
||||
LoginMethod string `json:"login_method"`
|
||||
// LastLoginAt 是最近一次成功登录时间。
|
||||
LastLoginAt int64 `json:"last_login_at"`
|
||||
// ProfileError 是资料刷新错误说明。
|
||||
ProfileError string `json:"profile_error"`
|
||||
// HasCookie 表示数据库中存在可用账号记录。
|
||||
HasCookie bool `json:"has_cookie"`
|
||||
// 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"`
|
||||
}
|
||||
|
||||
// cookieSettingsResponse 是账号设置更新接口的具名成功响应 DTO。
|
||||
type cookieSettingsResponse struct {
|
||||
// Success 表示账号设置是否保存成功。
|
||||
Success bool `json:"success"`
|
||||
// PausedUntil 是新的暂停结束时间 Unix 秒。
|
||||
PausedUntil int64 `json:"paused_until"`
|
||||
// Paused 表示账号当前是否处于暂停状态。
|
||||
Paused bool `json:"paused"`
|
||||
}
|
||||
|
||||
// cookieProfileResponse 是账号资料刷新接口的具名响应 DTO。
|
||||
type cookieProfileResponse struct {
|
||||
// Success 表示资料刷新是否成功。
|
||||
Success bool `json:"success"`
|
||||
// ID 是账号稳定标识。
|
||||
ID string `json:"id"`
|
||||
// Nickname 是刷新后的平台昵称。
|
||||
Nickname string `json:"nickname"`
|
||||
// AvatarURL 是刷新后的头像地址。
|
||||
AvatarURL string `json:"avatar_url"`
|
||||
// ProfileError 是资料刷新失败原因。
|
||||
ProfileError string `json:"profile_error"`
|
||||
}
|
||||
|
||||
// autoConfirmResponse 是账号自动确认设置查询接口的具名响应 DTO。
|
||||
type autoConfirmResponse struct {
|
||||
// AutoConfirm 表示是否自动确认订单。
|
||||
AutoConfirm bool `json:"auto_confirm"`
|
||||
}
|
||||
|
||||
// pauseDurationResponse 是账号暂停时长查询接口的具名响应 DTO。
|
||||
type pauseDurationResponse struct {
|
||||
// PauseDuration 是暂停时长,单位为分钟。
|
||||
PauseDuration int `json:"pause_duration"`
|
||||
// PausedUntil 是暂停结束时间的 Unix 秒。
|
||||
PausedUntil int64 `json:"paused_until"`
|
||||
// Paused 表示账号当前是否处于暂停状态。
|
||||
Paused bool `json:"paused"`
|
||||
}
|
||||
|
||||
// itemListResponse 是本地商品列表接口的具名商品 DTO。
|
||||
type itemListResponse struct {
|
||||
// ID 是本地商品记录主键。
|
||||
ID int64 `json:"id"`
|
||||
// CookieID 是商品所属账号标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// ItemID 是平台商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// ItemTitle 是商品标题。
|
||||
ItemTitle string `json:"item_title"`
|
||||
// ItemDescription 是商品描述。
|
||||
ItemDescription string `json:"item_description"`
|
||||
// ItemCategory 是商品分类标识。
|
||||
ItemCategory string `json:"item_category"`
|
||||
// ItemPrice 是商品价格文本。
|
||||
ItemPrice string `json:"item_price"`
|
||||
// ItemDetail 是商品详情原始 JSON。
|
||||
ItemDetail string `json:"item_detail"`
|
||||
// ItemImage 是从详情中提取的商品图片地址。
|
||||
ItemImage string `json:"item_image"`
|
||||
// IsMultiSpec 表示商品是否有多规格。
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
// MultiQuantityDelivery 表示是否按数量发货。
|
||||
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
|
||||
// IsMultiQtyShip 是按数量发货的兼容字段。
|
||||
IsMultiQtyShip bool `json:"is_multi_qty_ship"`
|
||||
}
|
||||
|
||||
// itemDetailResponse 是单个本地商品详情接口的具名响应 DTO。
|
||||
type itemDetailResponse struct {
|
||||
// CookieID 是商品所属账号标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// ItemID 是平台商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// ItemTitle 是商品标题。
|
||||
ItemTitle string `json:"item_title"`
|
||||
// ItemDescription 是商品描述。
|
||||
ItemDescription string `json:"item_description"`
|
||||
// ItemCategory 是商品分类标识。
|
||||
ItemCategory string `json:"item_category"`
|
||||
// ItemPrice 是商品价格文本。
|
||||
ItemPrice string `json:"item_price"`
|
||||
// ItemDetail 是商品详情原始 JSON。
|
||||
ItemDetail string `json:"item_detail"`
|
||||
// IsMultiSpec 表示商品是否有多规格。
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
// MultiQuantityDelivery 表示是否按数量发货。
|
||||
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
|
||||
}
|
||||
|
||||
// itemPublishResponse 是单个商品发布成功接口的具名响应 DTO。
|
||||
type itemPublishResponse struct {
|
||||
// Success 表示商品是否发布成功。
|
||||
Success bool `json:"success"`
|
||||
// Message 是发布结果说明。
|
||||
Message string `json:"message"`
|
||||
// ItemID 是新商品的平台标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// ItemURL 是新商品的平台详情地址。
|
||||
ItemURL string `json:"item_url"`
|
||||
// ItemImage 是新商品主图地址。
|
||||
ItemImage string `json:"item_image"`
|
||||
// ItemTitle 是新商品标题。
|
||||
ItemTitle string `json:"item_title"`
|
||||
// ItemPrice 是新商品价格文本。
|
||||
ItemPrice string `json:"item_price"`
|
||||
// Quantity 是新商品库存数量。
|
||||
Quantity int `json:"quantity"`
|
||||
// CategoryID 是新商品分类标识。
|
||||
CategoryID string `json:"category_id"`
|
||||
// CategoryName 是新商品分类名称。
|
||||
CategoryName string `json:"category_name"`
|
||||
}
|
||||
|
||||
// itemSyncResponse 是商品全集同步接口的具名响应 DTO。
|
||||
type itemSyncResponse struct {
|
||||
// Success 表示同步是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Message 是同步结果说明。
|
||||
Message string `json:"message"`
|
||||
// TotalCount 是平台返回的商品总数。
|
||||
TotalCount int `json:"total_count"`
|
||||
// TotalPages 是平台商品总页数。
|
||||
TotalPages int `json:"total_pages"`
|
||||
// SavedCount 是本地保存的商品数量。
|
||||
SavedCount int `json:"saved_count"`
|
||||
// DeletedCount 是本地删除标记的商品数量。
|
||||
DeletedCount int `json:"deleted_count"`
|
||||
}
|
||||
|
||||
// itemPageSyncResponse 是商品分页同步接口的具名响应 DTO。
|
||||
type itemPageSyncResponse struct {
|
||||
// Success 表示同步是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Message 是同步结果说明。
|
||||
Message string `json:"message"`
|
||||
// PageNumber 是当前同步页码。
|
||||
PageNumber int `json:"page_number"`
|
||||
// PageSize 是当前同步页大小。
|
||||
PageSize int `json:"page_size"`
|
||||
// CurrentCount 是当前页商品数量。
|
||||
CurrentCount int `json:"current_count"`
|
||||
// SavedCount 是本地保存的商品数量。
|
||||
SavedCount int `json:"saved_count"`
|
||||
}
|
||||
|
||||
// automationActionResponse 是自动化规则动作的具名响应 DTO。
|
||||
type automationActionResponse struct {
|
||||
// ID 是动作稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// ActionType 是动作类型。
|
||||
ActionType string `json:"action_type"`
|
||||
// CardID 是动作关联卡券组标识。
|
||||
CardID int64 `json:"card_id"`
|
||||
// CardName 是动作关联卡券组名称。
|
||||
CardName string `json:"card_name"`
|
||||
// DeliveryCount 是动作发送数量。
|
||||
DeliveryCount int `json:"delivery_count"`
|
||||
// MessageTemplate 是动作消息模板。
|
||||
MessageTemplate string `json:"message_template"`
|
||||
// DelaySeconds 是动作延迟秒数。
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
// ConfigJSON 是动作扩展配置 JSON。
|
||||
ConfigJSON string `json:"config_json"`
|
||||
// Enabled 表示动作是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// SortOrder 是动作执行顺序。
|
||||
SortOrder int `json:"sort_order"`
|
||||
}
|
||||
|
||||
// automationRuleResponse 是自动化规则的具名响应 DTO。
|
||||
type automationRuleResponse struct {
|
||||
// ID 是规则稳定标识。
|
||||
ID int64 `json:"id"`
|
||||
// CookieID 是规则所属账号标识。
|
||||
CookieID string `json:"cookie_id"`
|
||||
// ItemID 是规则关联商品标识。
|
||||
ItemID string `json:"item_id"`
|
||||
// ItemTitle 是规则关联商品标题。
|
||||
ItemTitle string `json:"item_title"`
|
||||
// Name 是规则名称。
|
||||
Name string `json:"name"`
|
||||
// TriggerType 是规则触发类型。
|
||||
TriggerType string `json:"trigger_type"`
|
||||
// Enabled 表示规则是否启用。
|
||||
Enabled bool `json:"enabled"`
|
||||
// Priority 是规则优先级。
|
||||
Priority int `json:"priority"`
|
||||
// ConfigJSON 是规则扩展配置 JSON。
|
||||
ConfigJSON string `json:"config_json"`
|
||||
// Actions 是规则动作列表。
|
||||
Actions []automationActionResponse `json:"actions"`
|
||||
// CreatedAt 是规则创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// UpdatedAt 是规则更新时间。
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
// automationRulePageResponse 是自动化规则分页接口的具名响应 DTO。
|
||||
type automationRulePageResponse struct {
|
||||
// Success 表示查询是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Data 是当前页自动化规则。
|
||||
Data []automationRuleResponse `json:"data"`
|
||||
// Total 是符合条件的规则总数。
|
||||
Total int `json:"total"`
|
||||
// Page 是当前页码。
|
||||
Page int `json:"page"`
|
||||
// PageSize 是当前页大小。
|
||||
PageSize int `json:"page_size"`
|
||||
// TotalPages 是总页数。
|
||||
TotalPages int `json:"total_pages"`
|
||||
// TriggerCounts 是各触发类型的规则数量。
|
||||
TriggerCounts map[string]int `json:"trigger_counts"`
|
||||
}
|
||||
|
||||
// automationIssuesResponse 是自动化异常任务接口的具名响应 DTO。
|
||||
type automationIssuesResponse struct {
|
||||
// Runs 是需要处理的自动化运行记录。
|
||||
Runs []db.AutomationRunIssue `json:"runs"`
|
||||
// PendingTasks 是需要处理的延迟任务记录。
|
||||
PendingTasks []db.DeferredAutomationIssue `json:"pending_tasks"`
|
||||
}
|
||||
|
||||
// orderDetailResponse 是订单详情接口的具名响应 DTO,同时保留旧版顶层字段兼容性。
|
||||
type orderDetailResponse struct {
|
||||
// orderDTO 提供历史客户端仍读取的顶层订单字段。
|
||||
orderDTO
|
||||
// Success 表示查询是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Data 是新版客户端读取的订单对象。
|
||||
Data orderDTO `json:"data"`
|
||||
}
|
||||
|
||||
// orderRefreshDetailResponse 是订单刷新后返回的远端详情 DTO。
|
||||
type orderRefreshDetailResponse struct {
|
||||
// Quantity 是订单购买数量。
|
||||
Quantity string `json:"quantity"`
|
||||
// SpecName 是商品规格名称。
|
||||
SpecName string `json:"spec_name"`
|
||||
// SpecValue 是商品规格值。
|
||||
SpecValue string `json:"spec_value"`
|
||||
// OrderStatus 是归一化后的订单状态。
|
||||
OrderStatus string `json:"order_status"`
|
||||
// Amount 是订单实付金额。
|
||||
Amount string `json:"amount"`
|
||||
}
|
||||
|
||||
// orderRefreshResponse 是订单列表刷新接口的具名响应 DTO。
|
||||
type orderRefreshResponse struct {
|
||||
// PartialFailure 表示批量刷新是否存在部分失败。
|
||||
PartialFailure bool `json:"partial_failure"`
|
||||
// Message 是刷新结果说明。
|
||||
Message string `json:"message"`
|
||||
// Summary 是刷新统计摘要。
|
||||
Summary orderRefreshSummary `json:"summary"`
|
||||
// Results 是逐账号或逐订单的兼容结果行。
|
||||
Results []map[string]any `json:"results"`
|
||||
}
|
||||
|
||||
// orderRefreshSummary 是订单列表刷新统计摘要 DTO。
|
||||
type orderRefreshSummary struct {
|
||||
// Discovered 是发现的新订单数量。
|
||||
Discovered int `json:"discovered"`
|
||||
// ListUpdated 是订单列表更新数量。
|
||||
ListUpdated int `json:"list_updated"`
|
||||
// SoftDeleted 是标记删除的订单数量。
|
||||
SoftDeleted int `json:"soft_deleted"`
|
||||
// DetailTotal 是需要补全详情的订单数量。
|
||||
DetailTotal int `json:"detail_total"`
|
||||
// Total 是本次处理订单总数。
|
||||
Total int `json:"total"`
|
||||
// Updated 是状态发生变化的订单数量。
|
||||
Updated int `json:"updated"`
|
||||
// NoChange 是状态未发生变化的订单数量。
|
||||
NoChange int `json:"no_change"`
|
||||
// Failed 是刷新失败数量。
|
||||
Failed int `json:"failed"`
|
||||
}
|
||||
|
||||
// orderSingleRefreshResponse 是单订单刷新接口的具名响应 DTO。
|
||||
type orderSingleRefreshResponse struct {
|
||||
// Success 表示刷新是否完成。
|
||||
Success bool `json:"success"`
|
||||
// Message 是刷新结果说明。
|
||||
Message string `json:"message"`
|
||||
// Order 是刷新后的订单详情。
|
||||
Order orderRefreshDetailResponse `json:"order"`
|
||||
}
|
||||
|
||||
// manualShipResponse 是手动发货接口的具名响应 DTO。
|
||||
type manualShipResponse struct {
|
||||
// PartialFailure 表示批量发货是否存在部分失败。
|
||||
PartialFailure bool `json:"partial_failure"`
|
||||
// Message 是发货结果说明。
|
||||
Message string `json:"message"`
|
||||
// SuccessCount 是成功发货数量。
|
||||
SuccessCount int `json:"success_count"`
|
||||
// FailedCount 是失败发货数量。
|
||||
FailedCount int `json:"failed_count"`
|
||||
// Results 是逐订单的兼容结果行。
|
||||
Results []map[string]any `json:"results"`
|
||||
}
|
||||
|
||||
// importOrdersResponse 是订单导入接口的具名响应 DTO。
|
||||
type importOrdersResponse struct {
|
||||
// PartialFailure 表示批量导入是否存在部分失败。
|
||||
PartialFailure bool `json:"partial_failure"`
|
||||
// Message 是导入结果说明。
|
||||
Message string `json:"message"`
|
||||
// Total 是本次导入订单总数。
|
||||
Total int `json:"total"`
|
||||
// SuccessCount 是成功导入数量。
|
||||
SuccessCount int `json:"success_count"`
|
||||
// FailedCount 是失败导入数量。
|
||||
FailedCount int `json:"failed_count"`
|
||||
// Results 是逐订单的兼容结果行。
|
||||
Results []map[string]any `json:"results"`
|
||||
}
|
||||
Reference in new issue
Block a user