订单响应:收口 DTO 映射与错误分类
This commit is contained in:
1 parent
4a1546f2aa
commit
06ca978a32
5 files changed
+2744
-2637
No files matched your search
+2385
-2313
File diff suppressed because it is too large.
Load diff
@@ -153,8 +153,9 @@ app shell / routes
|
||||
- 已完成阶段 3 第二十四个 PR 切片“二维码登录 API 版本化兼容入口迁移”:新增二维码生成、状态查询、状态持久化和验证完成 `/api/v1/qr-login...` 薄适配入口,复用既有认证、会话所有权和敏感字段过滤 handler;React 二维码生成、轮询和验证完成调用已迁移,旧路径保留;新增二维码新旧入口契约测试并保持独立可回滚提交;
|
||||
- 已完成阶段 3 第二十五个 PR 切片“密码登录及剩余公共调用方 API 版本化兼容入口迁移”:新增会话密码/凭证、账号删除、密码登录禁用、自动化规则/异常处理、订单删除和商品创建 `/api/v1/...` 薄适配入口,复用既有认证、权限和业务 handler;React 对应调用已迁移,旧路径保留;新增剩余公共调用方 Go/React 契约测试并保持独立可回滚提交;
|
||||
- 已完成阶段 3 第二十六个 PR 切片“版本化入口最终审计与旧调用方清零”:前端生产调用和批量结果下载已无业务旧路径;Vite 代理收敛为 `/api` 与健康检查;服务端剩余商品兼容入口已补齐;新增旧代理别名和商品遗漏入口审计证据,阶段 3 完成条件满足并保持独立可回滚提交;
|
||||
- 已完成阶段 4 第一个 PR 切片“订单应用服务边界提取”的核心部分:订单列表、详情、更新、删除、批量导入、手动发货和批量刷新已由不依赖 `net/http` 的 `orderApplicationService` 编排;handler 仅保留 HTTP 解析、鉴权上下文和 DTO 编码;保留订单所有权、事务回滚、MTOP 凭证锁、Cookie Jar 持久化、Session 续期和逐单部分失败语义;新增服务层直接调用测试并通过 Go 全量门禁与 server race;
|
||||
- 阶段 4 下一 PR 切片为“订单响应 DTO 映射收口”:把订单列表/详情 DTO 映射从 handler 移入应用服务返回模型,统一错误分类并继续保持旧/版本化入口响应契约,不拆分单个 handler 提交;
|
||||
- 已完成阶段 4 第一个 PR 切片“订单应用服务边界提取”:订单列表、详情、更新、删除、批量导入、手动发货和批量刷新已由不依赖 `net/http` 的 `orderApplicationService` 编排;handler 仅保留 HTTP 解析、鉴权上下文和 DTO 编码;保留订单所有权、事务回滚、MTOP 凭证锁、Cookie Jar 持久化、Session 续期和逐单部分失败语义;新增服务层直接调用测试并通过 Go 全量门禁与 server race;
|
||||
- 已完成阶段 4 第二个 PR 切片“订单响应 DTO 映射收口”:订单列表状态/图片映射、详情商品补全、单订单刷新和批量刷新响应均由应用服务返回稳定视图;更新校验改用业务错误分类,HTTP 层不再依赖错误文本判断状态码;旧/版本化入口契约测试和全量门禁通过;
|
||||
- 阶段 4 下一 PR 切片为“商品发布应用服务边界提取”:围绕单商品发布、预检、批量任务、恢复、取消、重试和关联自动化规则提取不依赖 `net/http` 的应用服务,保留 worker、锁、cancel map 和事务不变量,不拆分单个 handler 提交;
|
||||
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
|
||||
|
||||
## 6. 阶段 0:治理文档与强约束
|
||||
@@ -557,3 +558,5 @@ npm --prefix frontend run build
|
||||
| 2026-08-14 | 完成阶段 3 第二十四个 PR 切片“二维码登录 API 版本化兼容入口迁移” | 新增二维码生成、状态查询、状态持久化和验证完成 `/api/v1/qr-login...` 薄适配入口,复用既有认证、会话所有权和敏感字段过滤 handler;React 二维码生成、轮询和验证完成调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:密码登录及剩余公共调用方 API 版本化兼容入口迁移 |
|
||||
| 2026-08-14 | 完成阶段 3 第二十五个 PR 切片“密码登录及剩余公共调用方 API 版本化兼容入口迁移” | 新增会话密码/凭证、账号删除、密码登录禁用、自动化规则/异常处理、订单删除和商品创建 `/api/v1/...` 薄适配入口,复用既有认证、权限和业务 handler;React 对应调用已迁移;Go/React 契约测试确认新旧入口兼容;全量门禁通过并合并为一个可回滚提交 | 阶段 3:版本化入口最终审计与旧调用方清零 |
|
||||
| 2026-08-14 | 完成阶段 3 第二十六个 PR 切片“版本化入口最终审计与旧调用方清零” | 前端生产调用和批量结果下载已无业务旧路径;Vite 代理收敛为 `/api` 与健康检查;服务端补齐商品按账号列表、多规格和多数量兼容入口;Go/React/Vite 审计测试、全量测试、race、vet、lint、注释和构建门禁通过并合并为一个可回滚提交 | 阶段 4:订单应用服务边界提取 |
|
||||
| 2026-08-14 | 完成阶段 4 第一个 PR 切片“订单应用服务边界提取” | 新增不依赖 `net/http` 的订单应用服务,覆盖列表、详情、更新、删除、导入、手动发货、批量刷新和单订单刷新;保留权限、事务、凭证锁、Cookie Jar 和 Session 续期语义;服务层测试、全量测试、race、vet、lint、注释门禁通过并合并为一个可回滚提交 | 阶段 4:订单响应 DTO 映射收口 |
|
||||
| 2026-08-14 | 完成阶段 4 第二个 PR 切片“订单响应 DTO 映射收口” | 列表/详情/刷新响应视图由应用服务统一生成;错误分类模型替代 HTTP handler 中的错误文本判断;旧/版本化订单契约、全量测试、race、vet、lint、注释和 diff 门禁通过,合并为一个可回滚提交 | 阶段 4:商品发布应用服务边界提取 |
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
@@ -56,35 +55,9 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
orders := make([]orderDTO, 0, len(result.Rows))
|
||||
for _, o := range result.Rows {
|
||||
st := db.NormalizeOrderStatus(o.OrderStatus)
|
||||
orders = append(orders, orderDTO{
|
||||
OrderID: o.OrderID,
|
||||
ItemID: o.ItemID,
|
||||
ItemTitle: o.ItemTitle,
|
||||
ItemImage: itemImageFromDetail(o.ItemDetail),
|
||||
BuyerID: o.BuyerID,
|
||||
SpecName: o.SpecName,
|
||||
SpecValue: o.SpecValue,
|
||||
Quantity: o.Quantity,
|
||||
Amount: o.Amount,
|
||||
OrderStatus: st,
|
||||
Status: st,
|
||||
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,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, orderListResponse{
|
||||
Success: true,
|
||||
Data: orders,
|
||||
Data: result.Orders,
|
||||
Total: result.Total,
|
||||
Page: result.Page,
|
||||
PageSize: result.PageSize,
|
||||
@@ -96,7 +69,7 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
|
||||
orderID := chi.URLParam(r, "order_id")
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
o, err := s.orders().Get(r.Context(), sess.UserID, orderID)
|
||||
result, err := s.orders().GetView(r.Context(), sess.UserID, orderID)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作此订单")
|
||||
@@ -105,56 +78,8 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
return
|
||||
}
|
||||
itemTitle, itemImage := "", ""
|
||||
if item, itemErr := s.Store.Items.Get(r.Context(), o.CookieID, o.ItemID); itemErr == nil {
|
||||
itemTitle = item.ItemTitle
|
||||
itemImage = itemImageFromDetail(item.ItemDetail)
|
||||
}
|
||||
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,
|
||||
},
|
||||
orderDTO: result.Order, Success: true, Data: result.Order,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -173,243 +98,6 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, result)
|
||||
}
|
||||
|
||||
// Refresh 同步订单索引与订单详情,返回逐账号和逐订单的兼容结果。
|
||||
func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderRefreshResponse, error) {
|
||||
|
||||
cookieIDs, err := a.server.Store.Cookies.ListOwnedIDs(ctx, userID)
|
||||
if err != nil {
|
||||
return orderRefreshResponse{}, err
|
||||
}
|
||||
if cookieID != "" {
|
||||
if !a.server.cookieOwnedByUser(ctx, userID, cookieID) {
|
||||
return orderRefreshResponse{}, db.ErrForbidden
|
||||
}
|
||||
cookieIDs = []string{cookieID}
|
||||
}
|
||||
|
||||
discovered, listUpdated, softDeleted, failed := 0, 0, 0, 0
|
||||
results := []map[string]any{}
|
||||
newOrderIDs := make(map[string]struct{})
|
||||
sessionExpiredAccounts := make(map[string]struct{})
|
||||
if fetcher, ok := a.server.mtopClient().(mtop.SoldOrderFetcher); ok {
|
||||
for _, cid := range cookieIDs { // cid 是当前待刷新的账号 ID。
|
||||
credentialUnlock := a.server.Store.LockAccountCredentials(cid)
|
||||
latest, latestErr := a.server.loadCookiePlatformDetail(ctx, cid)
|
||||
if latestErr != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
|
||||
credentialUnlock()
|
||||
if latestErr == nil {
|
||||
latestErr = errors.New("账号凭证已变化")
|
||||
}
|
||||
failed++
|
||||
results = append(results, map[string]any{
|
||||
"cookie_id": cid, "stage": "discover", "success": false, "message": latestErr.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
// latest.Value 仅用于当前账号的凭证调用,不需要写回账号列表。
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
|
||||
accountDiscovered, accountUpdated, accountNewIDs, accountRemoteIDs, discoveryErr := a.server.discoverSoldOrders(mtopCtx, fetcher, cid, latest.Value)
|
||||
value, valueChanged, _, persistErr := a.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
if persistErr != nil {
|
||||
discoveryErr = errors.Join(discoveryErr, fmt.Errorf("保存订单列表响应 Cookie Jar: %w", persistErr))
|
||||
}
|
||||
// value 通过运行时更新路径继续传递,不需要写回账号列表。
|
||||
// 账号筛选列表只保存 ID,不承载刷新后的凭证值。
|
||||
credentialUnlock()
|
||||
if persistErr == nil && valueChanged {
|
||||
a.server.updateRunningCookie(ctx, cid, value)
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(discoveryErr) {
|
||||
sessionExpiredAccounts[cid] = struct{}{}
|
||||
a.server.recoverExpiredMTOPSession(ctx, cid, discoveryErr)
|
||||
}
|
||||
discovered += accountDiscovered
|
||||
listUpdated += accountUpdated
|
||||
for orderID := range accountNewIDs {
|
||||
newOrderIDs[orderID] = struct{}{}
|
||||
}
|
||||
result := map[string]any{
|
||||
"cookie_id": cid, "stage": "discover", "success": discoveryErr == nil,
|
||||
"discovered": accountDiscovered, "updated": accountUpdated,
|
||||
}
|
||||
if discoveryErr == nil {
|
||||
deleted, deleteErr := a.server.Store.Orders.SoftDeleteMissingForCookie(ctx, cid, accountRemoteIDs)
|
||||
if deleteErr != nil {
|
||||
discoveryErr = fmt.Errorf("标记缺失订单失败: %w", deleteErr)
|
||||
result["success"] = false
|
||||
} else {
|
||||
softDeleted += deleted
|
||||
result["soft_deleted"] = deleted
|
||||
}
|
||||
}
|
||||
if discoveryErr != nil {
|
||||
failed++
|
||||
result["error"] = discoveryErr.Error()
|
||||
}
|
||||
results = append(results, result)
|
||||
}
|
||||
} else {
|
||||
failed++
|
||||
results = append(results, map[string]any{"stage": "discover", "success": false, "message": "当前 MTop 客户端不支持订单列表发现"})
|
||||
}
|
||||
|
||||
ordersByCookie := map[string][]refreshTarget{}
|
||||
for _, cid := range cookieIDs { // cid 是当前需要补充订单的账号 ID。
|
||||
if _, blocked := sessionExpiredAccounts[cid]; blocked {
|
||||
continue
|
||||
}
|
||||
for offset := 0; ; offset += 500 {
|
||||
rows, err := a.server.Store.Orders.ByCookiePage(ctx, cid, 500, offset)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
for _, row := range rows {
|
||||
currentStatus := db.NormalizeOrderStatus(row.OrderStatus)
|
||||
if status != "" && status != "all" && currentStatus != status {
|
||||
continue
|
||||
}
|
||||
// 稳定状态无需反复抓取;但历史订单若缺少实付金额,仍需补全详情。
|
||||
_, isNewOrder := newOrderIDs[row.OrderID]
|
||||
if !isNewOrder && isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" {
|
||||
continue
|
||||
}
|
||||
ordersByCookie[cid] = append(ordersByCookie[cid], refreshTarget{OrderID: row.OrderID, CurrentStatus: currentStatus})
|
||||
}
|
||||
if len(rows) < 500 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
total := 0
|
||||
for _, targets := range ordersByCookie {
|
||||
total += len(targets)
|
||||
}
|
||||
detailFetcher, detailSupported := a.server.mtopClient().(orderDetailMTop)
|
||||
if !detailSupported {
|
||||
message := "订单列表同步完成"
|
||||
if discovered > 0 {
|
||||
message = fmt.Sprintf("订单列表同步完成,发现并导入 %d 个新订单", discovered)
|
||||
}
|
||||
if total > 0 {
|
||||
message += fmt.Sprintf(";当前 Go MTOP 客户端不支持详情接口,已跳过 %d 个订单", total)
|
||||
}
|
||||
return 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,
|
||||
}, nil
|
||||
}
|
||||
if total == 0 {
|
||||
return 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,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 订单详情刷新阶段分别统计状态变化和无变化结果。
|
||||
updated, noChange := 0, 0
|
||||
for cid, targets := range ordersByCookie {
|
||||
accountSessionExpired := false
|
||||
for _, chunk := range chunkRefreshTargets(targets, refreshOrderChunkSize) {
|
||||
credentialUnlock := a.server.Store.LockAccountCredentials(cid)
|
||||
latest, latestErr := a.server.loadCookiePlatformDetail(ctx, cid)
|
||||
if latestErr != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
|
||||
credentialUnlock()
|
||||
failed += len(chunk)
|
||||
results = append(results, map[string]any{"cookie_id": cid, "success": false, "message": "账号凭证已变化"})
|
||||
continue
|
||||
}
|
||||
detailCtx, cancel := context.WithTimeout(ctx, 3*time.Minute)
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(detailCtx, latest)
|
||||
var sessionErr error
|
||||
for _, target := range chunk {
|
||||
detail, fetchErr := detailFetcher.FetchOrderDetail(mtopCtx, latest.Value, target.OrderID)
|
||||
if fetchErr != nil || detail == nil {
|
||||
failed++
|
||||
message := "订单详情接口未返回结果"
|
||||
if fetchErr != nil {
|
||||
message = fetchErr.Error()
|
||||
}
|
||||
results = append(results, map[string]any{
|
||||
"order_id": target.OrderID,
|
||||
"success": false,
|
||||
"message": message,
|
||||
})
|
||||
if mtop.IsSessionExpiredErr(fetchErr) {
|
||||
sessionErr = fetchErr
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
newStatus := db.NormalizeOrderStatus(detail.OrderStatus)
|
||||
if !validEditableOrderStatus(newStatus) {
|
||||
newStatus = target.CurrentStatus
|
||||
}
|
||||
err := a.server.Store.Orders.Upsert(ctx, target.OrderID, db.OrderUpsertOpts{
|
||||
CookieID: cid,
|
||||
OrderStatus: newStatus,
|
||||
SpecName: detail.SpecName,
|
||||
SpecValue: detail.SpecValue,
|
||||
Quantity: detail.Quantity,
|
||||
Amount: detail.Amount,
|
||||
})
|
||||
if err != nil {
|
||||
failed++
|
||||
results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "message": "更新数据库失败"})
|
||||
continue
|
||||
}
|
||||
changed := newStatus != "" && newStatus != target.CurrentStatus
|
||||
if changed {
|
||||
updated++
|
||||
} else {
|
||||
noChange++
|
||||
}
|
||||
results = append(results, map[string]any{
|
||||
"order_id": target.OrderID,
|
||||
"success": true,
|
||||
"old_status": target.CurrentStatus,
|
||||
"new_status": newStatus,
|
||||
})
|
||||
}
|
||||
cancel()
|
||||
value, valueChanged, _, persistErr := a.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
credentialUnlock()
|
||||
if persistErr != nil {
|
||||
failed++
|
||||
results = append(results, map[string]any{"cookie_id": cid, "stage": "persist_cookie", "success": false, "message": persistErr.Error()})
|
||||
} else if valueChanged {
|
||||
a.server.updateRunningCookie(ctx, cid, value)
|
||||
}
|
||||
if sessionErr != nil {
|
||||
a.server.recoverExpiredMTOPSession(ctx, cid, sessionErr)
|
||||
accountSessionExpired = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if accountSessionExpired {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return 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,
|
||||
}, nil
|
||||
|
||||
}
|
||||
|
||||
// 订单发现阶段将远端订单索引与本地软删除状态保持一致。
|
||||
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
|
||||
@@ -611,7 +299,7 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
|
||||
ReceiverName: req.ReceiverName, ReceiverPhone: req.ReceiverPhone, ReceiverAddress: req.ReceiverAddress,
|
||||
ReceiverCity: req.ReceiverCity, ChatID: req.ChatID, SystemShipped: req.SystemShipped, ItemTitle: req.ItemTitle,
|
||||
}); err != nil {
|
||||
if strings.Contains(err.Error(), "不支持的订单状态") || strings.Contains(err.Error(), "订单金额") || strings.Contains(err.Error(), "商品标题不能为空") {
|
||||
if kind, classified := orderErrorKindOf(err); classified && kind == orderErrorBadRequest {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
} else if errors.Is(err, db.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "无权操作此订单")
|
||||
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。
|
||||
@@ -672,6 +674,19 @@ func stringPtrForOrderTest(value string) *string {
|
||||
return &value
|
||||
}
|
||||
|
||||
// TestOrderResponseMappingAndErrorClassification 验证订单响应映射和业务错误分类不依赖 HTTP。
|
||||
func TestOrderResponseMappingAndErrorClassification(t *testing.T) {
|
||||
row := db.OrderRow{OrderID: "mapped-order", ItemID: "mapped-item", ItemTitle: "测试商品", ItemDetail: `{"pic_info":{"picUrl":"https://img.example/mapped.png"}}`, OrderStatus: "2"}
|
||||
view := orderDTOFromRow(row)
|
||||
if view.OrderStatus != "pending_ship" || view.Status != "pending_ship" || view.ItemImage != "https://img.example/mapped.png" {
|
||||
t.Fatalf("订单响应映射异常: %+v", view)
|
||||
}
|
||||
validationErr := newOrderBadRequest("不支持的订单状态")
|
||||
if kind, ok := orderErrorKindOf(validationErr); !ok || kind != orderErrorBadRequest {
|
||||
t.Fatalf("订单错误分类异常: kind=%v ok=%v", kind, ok)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAtoiDefault atoiDefault 表驱动。
|
||||
func TestAtoiDefault(t *testing.T) {
|
||||
cases := map[string]int{"": 5, "abc": 5, "3": 3, "12": 12}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// orderApplicationService 承载订单用例的业务编排,不依赖 HTTP 请求或响应对象。
|
||||
@@ -21,6 +22,42 @@ type orderApplicationService struct {
|
||||
var errOrderDetailUnsupported = errors.New("当前 Go MTOP 客户端不支持订单详情接口")
|
||||
var errOrderCredentialChanged = errors.New("账号凭证已变化,请重试")
|
||||
|
||||
// orderErrorKind 标识应用服务错误的业务分类,避免 HTTP 层依赖错误文本判断状态码。
|
||||
type orderErrorKind uint8
|
||||
|
||||
const (
|
||||
// orderErrorBadRequest 表示请求字段不满足订单业务约束。
|
||||
orderErrorBadRequest orderErrorKind = iota + 1
|
||||
)
|
||||
|
||||
// orderApplicationError 是带业务分类的订单应用服务错误。
|
||||
type orderApplicationError struct {
|
||||
// kind 是错误所属的业务分类。
|
||||
kind orderErrorKind
|
||||
// err 是底层可读错误。
|
||||
err error
|
||||
}
|
||||
|
||||
// Error 返回订单应用服务错误文本。
|
||||
func (e *orderApplicationError) Error() string { return e.err.Error() }
|
||||
|
||||
// Unwrap 暴露底层错误,保留 errors.Is/As 的兼容能力。
|
||||
func (e *orderApplicationError) Unwrap() error { return e.err }
|
||||
|
||||
// newOrderBadRequest 创建订单字段校验错误。
|
||||
func newOrderBadRequest(message string) error {
|
||||
return &orderApplicationError{kind: orderErrorBadRequest, err: errors.New(message)}
|
||||
}
|
||||
|
||||
// orderErrorKindOf 读取订单应用服务错误分类。
|
||||
func orderErrorKindOf(err error) (orderErrorKind, bool) {
|
||||
var applicationErr *orderApplicationError
|
||||
if !errors.As(err, &applicationErr) {
|
||||
return 0, false
|
||||
}
|
||||
return applicationErr.kind, true
|
||||
}
|
||||
|
||||
// orders 返回当前 Server 绑定的订单应用服务。
|
||||
func (s *Server) orders() *orderApplicationService {
|
||||
return &orderApplicationService{server: s}
|
||||
@@ -44,8 +81,8 @@ type orderListQuery struct {
|
||||
|
||||
// orderListResult 返回订单列表及分页统计。
|
||||
type orderListResult struct {
|
||||
// Rows 是订单列表行。
|
||||
Rows []db.OrderRow
|
||||
// Orders 是已经完成状态归一和商品图片映射的订单视图。
|
||||
Orders []orderDTO
|
||||
// Total 是符合条件的订单总数。
|
||||
Total int
|
||||
// Page 是规范化后的页码。
|
||||
@@ -56,6 +93,46 @@ type orderListResult struct {
|
||||
TotalPages int
|
||||
}
|
||||
|
||||
// orderDTOFromRow 把数据库订单列表行转换为稳定的订单响应视图。
|
||||
func orderDTOFromRow(row db.OrderRow) orderDTO {
|
||||
status := db.NormalizeOrderStatus(row.OrderStatus)
|
||||
return orderDTO{
|
||||
OrderID: row.OrderID, ItemID: row.ItemID, ItemTitle: row.ItemTitle,
|
||||
ItemImage: itemImageFromDetail(row.ItemDetail), BuyerID: row.BuyerID,
|
||||
SpecName: row.SpecName, SpecValue: row.SpecValue, Quantity: row.Quantity,
|
||||
Amount: row.Amount, OrderStatus: status, Status: status, CookieID: row.CookieID,
|
||||
IsBargain: row.IsBargain, SystemShipped: row.SystemShipped,
|
||||
ReceiverName: row.ReceiverName, ReceiverPhone: row.ReceiverPhone,
|
||||
ReceiverAddress: row.ReceiverAddr, ReceiverCity: row.ReceiverCity,
|
||||
CreatedAt: row.CreatedAt, UpdatedAt: row.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// orderDTOFromOrder 把订单实体和关联商品信息转换为详情响应视图。
|
||||
func orderDTOFromOrder(order *db.Order, item *db.ItemInfo) orderDTO {
|
||||
itemTitle, itemImage := "", ""
|
||||
if item != nil {
|
||||
itemTitle = item.ItemTitle
|
||||
itemImage = itemImageFromDetail(item.ItemDetail)
|
||||
}
|
||||
status := db.NormalizeOrderStatus(order.OrderStatus)
|
||||
return orderDTO{
|
||||
OrderID: order.OrderID, ItemID: order.ItemID, ItemTitle: itemTitle, ItemImage: itemImage,
|
||||
BuyerID: order.BuyerID, SpecName: order.SpecName, SpecValue: order.SpecValue,
|
||||
Quantity: order.Quantity, Amount: order.Amount, OrderStatus: status, Status: status,
|
||||
CookieID: order.CookieID, IsBargain: order.IsBargain, SystemShipped: order.SystemShipped,
|
||||
ReceiverName: order.ReceiverName, ReceiverPhone: order.ReceiverPhone,
|
||||
ReceiverAddress: order.ReceiverAddr, ReceiverCity: order.ReceiverCity,
|
||||
CreatedAt: order.CreatedAt, UpdatedAt: order.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// orderDetailResult 返回订单详情的统一响应视图。
|
||||
type orderDetailResult struct {
|
||||
// Order 是已经完成商品信息补全的订单视图。
|
||||
Order orderDTO
|
||||
}
|
||||
|
||||
// List 查询当前用户可见的订单,并集中处理分页和账号所有权规则。
|
||||
func (a *orderApplicationService) List(ctx context.Context, query orderListQuery) (orderListResult, error) {
|
||||
if query.Page < 1 {
|
||||
@@ -78,8 +155,12 @@ func (a *orderApplicationService) List(ctx context.Context, query orderListQuery
|
||||
if err != nil {
|
||||
return orderListResult{}, err
|
||||
}
|
||||
orders := make([]orderDTO, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
orders = append(orders, orderDTOFromRow(row))
|
||||
}
|
||||
return orderListResult{
|
||||
Rows: rows, Total: total, Page: query.Page, PageSize: query.PageSize,
|
||||
Orders: orders, Total: total, Page: query.Page, PageSize: query.PageSize,
|
||||
TotalPages: (total + query.PageSize - 1) / query.PageSize,
|
||||
}, nil
|
||||
}
|
||||
@@ -102,6 +183,19 @@ func (a *orderApplicationService) Get(ctx context.Context, userID int64, orderID
|
||||
return order, nil
|
||||
}
|
||||
|
||||
// GetView 查询订单并补全商品标题和主图,供详情 handler 直接编码。
|
||||
func (a *orderApplicationService) GetView(ctx context.Context, userID int64, orderID string) (orderDetailResult, error) {
|
||||
order, err := a.Get(ctx, userID, orderID)
|
||||
if err != nil {
|
||||
return orderDetailResult{}, err
|
||||
}
|
||||
item, itemErr := a.server.Store.Items.Get(ctx, order.CookieID, order.ItemID)
|
||||
if itemErr != nil {
|
||||
item = nil
|
||||
}
|
||||
return orderDetailResult{Order: orderDTOFromOrder(order, item)}, nil
|
||||
}
|
||||
|
||||
// Delete 逻辑删除订单,保留历史记录供审计使用。
|
||||
func (a *orderApplicationService) Delete(ctx context.Context, userID int64, orderID string) error {
|
||||
if _, err := a.Get(ctx, userID, orderID); err != nil {
|
||||
@@ -152,14 +246,14 @@ func (a *orderApplicationService) Update(ctx context.Context, userID int64, orde
|
||||
if request.OrderStatus != nil {
|
||||
normalized := db.NormalizeOrderStatus(strings.TrimSpace(*request.OrderStatus))
|
||||
if !validEditableOrderStatus(normalized) {
|
||||
return fmt.Errorf("不支持的订单状态")
|
||||
return newOrderBadRequest("不支持的订单状态")
|
||||
}
|
||||
request.OrderStatus = &normalized
|
||||
}
|
||||
if request.Amount != nil {
|
||||
normalized, ok := normalizeOrderAmount(*request.Amount)
|
||||
if !ok {
|
||||
return fmt.Errorf("订单金额必须是普通格式的非负有限数字")
|
||||
return newOrderBadRequest("订单金额必须是普通格式的非负有限数字")
|
||||
}
|
||||
request.Amount = &normalized
|
||||
}
|
||||
@@ -172,7 +266,7 @@ func (a *orderApplicationService) Update(ctx context.Context, userID int64, orde
|
||||
if request.ItemTitle != nil {
|
||||
itemTitle = strings.TrimSpace(*request.ItemTitle)
|
||||
if itemTitle == "" || finalItemID == "" {
|
||||
return fmt.Errorf("商品标题不能为空且订单必须关联商品")
|
||||
return newOrderBadRequest("商品标题不能为空且订单必须关联商品")
|
||||
}
|
||||
}
|
||||
tx, err := a.server.Store.DB.BeginTx(ctx, nil)
|
||||
@@ -485,3 +579,238 @@ func (a *orderApplicationService) RefreshSingle(ctx context.Context, userID int6
|
||||
}
|
||||
return orderSingleRefreshResponse{Success: true, Message: "订单刷新完成", Order: orderRefreshDetailResponse{Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue, OrderStatus: db.NormalizeOrderStatus(detail.OrderStatus), Amount: detail.Amount}}, nil
|
||||
}
|
||||
func (a *orderApplicationService) Refresh(ctx context.Context, userID int64, cookieID, status string) (orderRefreshResponse, error) {
|
||||
|
||||
cookieIDs, err := a.server.Store.Cookies.ListOwnedIDs(ctx, userID)
|
||||
if err != nil {
|
||||
return orderRefreshResponse{}, err
|
||||
}
|
||||
if cookieID != "" {
|
||||
if !a.server.cookieOwnedByUser(ctx, userID, cookieID) {
|
||||
return orderRefreshResponse{}, db.ErrForbidden
|
||||
}
|
||||
cookieIDs = []string{cookieID}
|
||||
}
|
||||
|
||||
discovered, listUpdated, softDeleted, failed := 0, 0, 0, 0
|
||||
results := []map[string]any{}
|
||||
newOrderIDs := make(map[string]struct{})
|
||||
sessionExpiredAccounts := make(map[string]struct{})
|
||||
if fetcher, ok := a.server.mtopClient().(mtop.SoldOrderFetcher); ok {
|
||||
for _, cid := range cookieIDs { // cid 是当前待刷新的账号 ID。
|
||||
credentialUnlock := a.server.Store.LockAccountCredentials(cid)
|
||||
latest, latestErr := a.server.loadCookiePlatformDetail(ctx, cid)
|
||||
if latestErr != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
|
||||
credentialUnlock()
|
||||
if latestErr == nil {
|
||||
latestErr = errors.New("账号凭证已变化")
|
||||
}
|
||||
failed++
|
||||
results = append(results, map[string]any{
|
||||
"cookie_id": cid, "stage": "discover", "success": false, "message": latestErr.Error(),
|
||||
})
|
||||
continue
|
||||
}
|
||||
// latest.Value 仅用于当前账号的凭证调用,不需要写回账号列表。
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
|
||||
accountDiscovered, accountUpdated, accountNewIDs, accountRemoteIDs, discoveryErr := a.server.discoverSoldOrders(mtopCtx, fetcher, cid, latest.Value)
|
||||
value, valueChanged, _, persistErr := a.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
if persistErr != nil {
|
||||
discoveryErr = errors.Join(discoveryErr, fmt.Errorf("保存订单列表响应 Cookie Jar: %w", persistErr))
|
||||
}
|
||||
// value 通过运行时更新路径继续传递,不需要写回账号列表。
|
||||
// 账号筛选列表只保存 ID,不承载刷新后的凭证值。
|
||||
credentialUnlock()
|
||||
if persistErr == nil && valueChanged {
|
||||
a.server.updateRunningCookie(ctx, cid, value)
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(discoveryErr) {
|
||||
sessionExpiredAccounts[cid] = struct{}{}
|
||||
a.server.recoverExpiredMTOPSession(ctx, cid, discoveryErr)
|
||||
}
|
||||
discovered += accountDiscovered
|
||||
listUpdated += accountUpdated
|
||||
for orderID := range accountNewIDs {
|
||||
newOrderIDs[orderID] = struct{}{}
|
||||
}
|
||||
result := map[string]any{
|
||||
"cookie_id": cid, "stage": "discover", "success": discoveryErr == nil,
|
||||
"discovered": accountDiscovered, "updated": accountUpdated,
|
||||
}
|
||||
if discoveryErr == nil {
|
||||
deleted, deleteErr := a.server.Store.Orders.SoftDeleteMissingForCookie(ctx, cid, accountRemoteIDs)
|
||||
if deleteErr != nil {
|
||||
discoveryErr = fmt.Errorf("标记缺失订单失败: %w", deleteErr)
|
||||
result["success"] = false
|
||||
} else {
|
||||
softDeleted += deleted
|
||||
result["soft_deleted"] = deleted
|
||||
}
|
||||
}
|
||||
if discoveryErr != nil {
|
||||
failed++
|
||||
result["error"] = discoveryErr.Error()
|
||||
}
|
||||
results = append(results, result)
|
||||
}
|
||||
} else {
|
||||
failed++
|
||||
results = append(results, map[string]any{"stage": "discover", "success": false, "message": "当前 MTop 客户端不支持订单列表发现"})
|
||||
}
|
||||
|
||||
ordersByCookie := map[string][]refreshTarget{}
|
||||
for _, cid := range cookieIDs { // cid 是当前需要补充订单的账号 ID。
|
||||
if _, blocked := sessionExpiredAccounts[cid]; blocked {
|
||||
continue
|
||||
}
|
||||
for offset := 0; ; offset += 500 {
|
||||
rows, err := a.server.Store.Orders.ByCookiePage(ctx, cid, 500, offset)
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
for _, row := range rows {
|
||||
currentStatus := db.NormalizeOrderStatus(row.OrderStatus)
|
||||
if status != "" && status != "all" && currentStatus != status {
|
||||
continue
|
||||
}
|
||||
// 稳定状态无需反复抓取;但历史订单若缺少实付金额,仍需补全详情。
|
||||
_, isNewOrder := newOrderIDs[row.OrderID]
|
||||
if !isNewOrder && isStableOrderStatus(currentStatus) && strings.TrimSpace(row.Amount) != "" {
|
||||
continue
|
||||
}
|
||||
ordersByCookie[cid] = append(ordersByCookie[cid], refreshTarget{OrderID: row.OrderID, CurrentStatus: currentStatus})
|
||||
}
|
||||
if len(rows) < 500 {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
total := 0
|
||||
for _, targets := range ordersByCookie {
|
||||
total += len(targets)
|
||||
}
|
||||
detailFetcher, detailSupported := a.server.mtopClient().(orderDetailMTop)
|
||||
if !detailSupported {
|
||||
message := "订单列表同步完成"
|
||||
if discovered > 0 {
|
||||
message = fmt.Sprintf("订单列表同步完成,发现并导入 %d 个新订单", discovered)
|
||||
}
|
||||
if total > 0 {
|
||||
message += fmt.Sprintf(";当前 Go MTOP 客户端不支持详情接口,已跳过 %d 个订单", total)
|
||||
}
|
||||
return 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,
|
||||
}, nil
|
||||
}
|
||||
if total == 0 {
|
||||
return 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,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 订单详情刷新阶段分别统计状态变化和无变化结果。
|
||||
updated, noChange := 0, 0
|
||||
for cid, targets := range ordersByCookie {
|
||||
accountSessionExpired := false
|
||||
for _, chunk := range chunkRefreshTargets(targets, refreshOrderChunkSize) {
|
||||
credentialUnlock := a.server.Store.LockAccountCredentials(cid)
|
||||
latest, latestErr := a.server.loadCookiePlatformDetail(ctx, cid)
|
||||
if latestErr != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
|
||||
credentialUnlock()
|
||||
failed += len(chunk)
|
||||
results = append(results, map[string]any{"cookie_id": cid, "success": false, "message": "账号凭证已变化"})
|
||||
continue
|
||||
}
|
||||
detailCtx, cancel := context.WithTimeout(ctx, 3*time.Minute)
|
||||
mtopCtx, cookieSession := withMTopCookieSnapshot(detailCtx, latest)
|
||||
var sessionErr error
|
||||
for _, target := range chunk {
|
||||
detail, fetchErr := detailFetcher.FetchOrderDetail(mtopCtx, latest.Value, target.OrderID)
|
||||
if fetchErr != nil || detail == nil {
|
||||
failed++
|
||||
message := "订单详情接口未返回结果"
|
||||
if fetchErr != nil {
|
||||
message = fetchErr.Error()
|
||||
}
|
||||
results = append(results, map[string]any{
|
||||
"order_id": target.OrderID,
|
||||
"success": false,
|
||||
"message": message,
|
||||
})
|
||||
if mtop.IsSessionExpiredErr(fetchErr) {
|
||||
sessionErr = fetchErr
|
||||
break
|
||||
}
|
||||
continue
|
||||
}
|
||||
newStatus := db.NormalizeOrderStatus(detail.OrderStatus)
|
||||
if !validEditableOrderStatus(newStatus) {
|
||||
newStatus = target.CurrentStatus
|
||||
}
|
||||
err := a.server.Store.Orders.Upsert(ctx, target.OrderID, db.OrderUpsertOpts{
|
||||
CookieID: cid,
|
||||
OrderStatus: newStatus,
|
||||
SpecName: detail.SpecName,
|
||||
SpecValue: detail.SpecValue,
|
||||
Quantity: detail.Quantity,
|
||||
Amount: detail.Amount,
|
||||
})
|
||||
if err != nil {
|
||||
failed++
|
||||
results = append(results, map[string]any{"order_id": target.OrderID, "success": false, "message": "更新数据库失败"})
|
||||
continue
|
||||
}
|
||||
changed := newStatus != "" && newStatus != target.CurrentStatus
|
||||
if changed {
|
||||
updated++
|
||||
} else {
|
||||
noChange++
|
||||
}
|
||||
results = append(results, map[string]any{
|
||||
"order_id": target.OrderID,
|
||||
"success": true,
|
||||
"old_status": target.CurrentStatus,
|
||||
"new_status": newStatus,
|
||||
})
|
||||
}
|
||||
cancel()
|
||||
value, valueChanged, _, persistErr := a.server.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
credentialUnlock()
|
||||
if persistErr != nil {
|
||||
failed++
|
||||
results = append(results, map[string]any{"cookie_id": cid, "stage": "persist_cookie", "success": false, "message": persistErr.Error()})
|
||||
} else if valueChanged {
|
||||
a.server.updateRunningCookie(ctx, cid, value)
|
||||
}
|
||||
if sessionErr != nil {
|
||||
a.server.recoverExpiredMTOPSession(ctx, cid, sessionErr)
|
||||
accountSessionExpired = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if accountSessionExpired {
|
||||
continue
|
||||
}
|
||||
}
|
||||
return 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,
|
||||
}, nil
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user