商品发布应用服务:提取发布核心用例边界

This commit is contained in:
Christ committed 2026-08-14 19:39:18 +08:00
1 parent 06ca978a32
commit de723ee306
6 files changed
+1666 -1666

No files matched your search

File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -155,7 +155,8 @@ app shell / routes
- 已完成阶段 3 第二十六个 PR 切片“版本化入口最终审计与旧调用方清零”:前端生产调用和批量结果下载已无业务旧路径;Vite 代理收敛为 `/api` 与健康检查;服务端剩余商品兼容入口已补齐;新增旧代理别名和商品遗漏入口审计证据,阶段 3 完成条件满足并保持独立可回滚提交;
- 已完成阶段 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 提交;
- 已完成阶段 4 第三个 PR 切片“商品发布应用服务边界提取”:新增不依赖 `net/http` 的商品发布应用服务,覆盖单商品发布、类目推荐、批量预检持久化、批次启动/查询/取消/删除/失败重试;HTTP 层仅保留请求解析、鉴权和契约映射,保留 worker、锁、cancel map、租约和远端发布顺序;新增服务层直接调用测试并通过全量门禁,合并为一个可回滚提交;
- 阶段 4 下一 PR 切片为“账号登录应用服务边界提取”:围绕二维码会话所有权、结果持久化、资料刷新、Cookie 合并、账号重启和登录审计提取不依赖 `net/http` 的应用服务,保持持久化锁和生命周期不变量,不拆分单个 handler 提交;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -560,3 +561,4 @@ npm --prefix frontend run build
| 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:商品发布应用服务边界提取 |
| 2026-08-14 | 完成阶段 4 第三个 PR 切片“商品发布应用服务边界提取” | 新增不依赖 `net/http` 的商品发布应用服务,覆盖单商品发布、类目推荐、批量预检持久化、批次启动/查询/取消/删除/失败重试;保留 worker、凭证锁、cancel map、租约、远端发布与自动化规则时序;新增服务层测试,Go 全量测试、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:账号登录应用服务边界提取 |
+51 -12
View File
@@ -41,6 +41,7 @@ func (s *Server) mountItemsReal(r chi.Router) {
r.Put("/items/{cookie_id}/{item_id}/multi-quantity-delivery", s.setItemMultiQuantity)
}
// publishItem 解析 HTTP 发布请求并调用商品发布应用服务完成单商品发布。
func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
// 最多 9 张 10 MiB 图片,额外预留 multipart 元数据空间。
r.Body = http.MaxBytesReader(w, r.Body, maxItemPublishBytes)
@@ -98,19 +99,57 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
}
selectedLocation = &location
}
credentialUnlock := s.Store.LockAccountCredentials(cookieID)
latest, err := s.loadCookiePlatformDetail(r.Context(), cookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
credentialUnlock()
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
outcome, callErr := s.itemPublishApplication().PublishSingle(r.Context(), itemPublishInput{
UserID: userID, CookieID: cookieID, Title: title, Description: description,
PriceCents: priceCents, OriginalPriceCents: origCents, Quantity: quantity,
PostageMode: postageMode, PostageCents: postageCents, Location: selectedLocation, Images: images,
})
res := outcome.Result
if callErr != nil {
var perr *mtop.PublishError
if errors.As(callErr, &perr) {
status := http.StatusBadGateway
msg := perr.Error()
if perr.Code == mtop.PublishErrorStockPermissionMissing {
status = http.StatusForbidden
msg = "该账号没有库存发布权限,无法按库存数量发布商品"
}
writeErrCode(w, status, string(perr.Code), msg, "")
return
}
if strings.Contains(callErr.Error(), "账号凭证已变化") {
writeErr(w, http.StatusConflict, callErr.Error())
return
}
writeErr(w, http.StatusBadGateway, callErr.Error())
return
}
cookieValue := latest.Value
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
defer cancel()
client := s.mtopClient()
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
res, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
if res == nil || strings.TrimSpace(res.ItemID) == "" {
writeErrCode(w, http.StatusBadGateway, "publish_result_missing_item_id", "平台返回发布成功,但缺少商品 ID,无法确认发布结果", "")
return
}
if outcome.LocalSaveErr != nil {
if s.Logger != nil {
s.Logger.Error("平台已发布但保存本地商品失败", "cookie_id", cookieID, "item_id", res.ItemID, "err", outcome.LocalSaveErr)
}
writeErrDetails(w, http.StatusInternalServerError, "remote_published_local_save_failed", "商品已在平台发布,但本地保存失败,请勿重复发布并根据商品 ID 人工核对", "", map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL})
return
}
if outcome.ResponseCookieErr != nil {
writeErrDetails(w, http.StatusInternalServerError, "remote_published_cookie_save_failed", "商品已在平台发布并保存到本地,但登录凭证更新保存失败,请勿重复发布并尽快重新登录", "", map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL})
return
}
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,
})
/*
旧实现保留在版本控制历史中,当前单商品发布由 itemPublishService 统一处理。
服务边界保证 MTOP 调用、Cookie 更新和本地商品落库的顺序不变。
*/
/*res, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
Title: title,
Description: description,
PriceCents: priceCents,
@@ -223,7 +262,7 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
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 可用于发布后人工核对平台商品。
+156 -215
View File
@@ -98,6 +98,7 @@ type publishCategoryRecommender interface {
RecommendPublishCategory(ctx context.Context, cookiesStr, keyword string) (mtop.PublishCategory, string, error)
}
// recommendItemPublishCategory 解析类目关键词并返回平台推荐类目。
func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Request) {
var req struct {
CookieID string `json:"cookie_id"`
@@ -121,44 +122,20 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req
if !ok {
return
}
recommender, ok := s.mtopClient().(publishCategoryRecommender)
if !ok {
writeErr(w, http.StatusNotImplemented, "当前 MTOP 客户端不支持类目推荐")
return
}
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
runtimeCookie := ""
defer func() {
credentialUnlock()
if runtimeCookie != "" {
s.updateRunningCookie(context.Background(), req.CookieID, runtimeCookie)
category, callErr := s.itemPublishApplication().RecommendCategory(r.Context(), userID, req.CookieID, req.Keyword)
if callErr != nil {
if strings.Contains(callErr.Error(), "当前 MTOP 客户端不支持") {
writeErr(w, http.StatusNotImplemented, callErr.Error())
return
}
}()
latest, err := s.loadCookiePlatformDetail(r.Context(), req.CookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
writeErr(w, http.StatusConflict, "账号凭证已变化,请重试")
return
}
ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second)
defer cancel()
mtopCtx, cookieSession := withMTopCookieSnapshot(ctx, latest)
category, updatedCookies, callErr := recommender.RecommendPublishCategory(mtopCtx, latest.Value, req.Keyword)
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(r.Context(), latest, cookieSession)
if persistErr != nil {
writeErr(w, http.StatusInternalServerError, "保存账号登录状态失败")
return
}
if !handled && updatedCookies != "" && updatedCookies != latest.Value {
if err := s.Store.Cookies.UpdateValueOwned(r.Context(), req.CookieID, updatedCookies, userID); err != nil {
writeErr(w, http.StatusInternalServerError, "保存账号登录状态失败")
if strings.Contains(callErr.Error(), "账号凭证已变化") {
writeErr(w, http.StatusConflict, callErr.Error())
return
}
if strings.Contains(callErr.Error(), "保存账号登录状态") {
writeErr(w, http.StatusInternalServerError, callErr.Error())
return
}
runtimeCookie = updatedCookies
} else if handled && valueChanged {
runtimeCookie = value
}
if callErr != nil {
if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) {
writeErr(w, http.StatusNotFound, "没有匹配到可发布类目,请换一个关键词")
return
@@ -169,6 +146,7 @@ func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Req
writeJSON(w, http.StatusOK, categoryRecommendationResponse{Success: true, Category: category})
}
// previewItemPublishBatch 处理表格上传、图片归档和批量发布预检。
func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
s.cleanupExpiredPublishUploads(r.Context())
@@ -202,7 +180,6 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
return
}
}
locationBytes, _ := json.Marshal(batchLocation)
hasDefaultCategory := fallbackCategory.CatID != "" || fallbackCategory.CatName != "" || fallbackCategory.ChannelCatID != "" || fallbackCategory.TBCatID != ""
if hasDefaultCategory && (fallbackCategory.CatID == "" || fallbackCategory.CatName == "" || fallbackCategory.ChannelCatID == "") {
writeErr(w, http.StatusBadRequest, "默认类目信息不完整,请重新通过关键词获取")
@@ -279,85 +256,101 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
return
}
parsed := s.parsePublishRows(r.Context(), sess.UserID, defaultCookieID, uploadDir, fallbackCategory, maps)
rows := make([]db.ItemPublishBatchRow, 0, len(parsed))
previewRows := make([]publishBatchPreviewRow, 0, len(parsed))
valid, invalid := 0, 0
for _, p := range parsed {
isValid := len(p.Errors) == 0
if isValid {
valid++
preview, err := s.itemPublishApplication().PersistPreview(r.Context(), itemPublishPreviewInput{
UserID: sess.UserID, BatchID: batchID, DefaultCookieID: defaultCookieID,
Filename: sourceName, UploadDir: uploadDir, Location: batchLocation, Rows: parsed,
})
if err != nil {
if errors.Is(err, errItemPublishBatchNoRows) {
writeErr(w, http.StatusBadRequest, "表格中没有有效数据行")
} else {
invalid++
writeErr(w, http.StatusInternalServerError, "保存预检结果失败")
}
imagesJSON, _ := json.Marshal(p.Images)
categoryJSON, _ := json.Marshal(p.Category)
automationJSON, _ := json.Marshal(p.Automation)
rawJSON, _ := json.Marshal(p.Raw)
status := "pending"
errMsg := ""
if !isValid {
status = "failed"
errMsg = strings.Join(p.Errors, ";")
}
rows = append(rows, db.ItemPublishBatchRow{
RowNo: p.RowNo,
CookieID: p.CookieID,
Title: p.Title,
Description: p.Description,
Price: p.Price,
OriginalPrice: p.OriginalPrice,
Quantity: p.Quantity,
PostageMode: p.PostageMode,
Postage: p.Postage,
ImagesJSON: string(imagesJSON),
CategoryJSON: string(categoryJSON),
AutomationJSON: string(automationJSON),
Status: status,
ErrorMessage: errMsg,
FailureKind: map[bool]string{true: "", false: "validation"}[isValid],
RawJSON: string(rawJSON),
})
previewRows = append(previewRows, publishBatchPreviewRow{
RowNo: p.RowNo,
Valid: isValid,
Errors: p.Errors,
CookieID: p.CookieID,
Title: p.Title,
Price: p.Price,
Quantity: p.Quantity,
Images: p.Images,
Category: p.Category,
Automation: p.Automation,
})
}
if len(rows) == 0 {
writeErr(w, http.StatusBadRequest, "表格中没有有效数据行")
return
}
if err := s.Store.PublishBatches.Create(r.Context(), &db.ItemPublishBatch{
ID: batchID,
UserID: sess.UserID,
DefaultCookieID: defaultCookieID,
Filename: sourceName,
UploadDir: uploadDir,
LocationJSON: string(locationBytes),
Status: "preview",
}, rows); err != nil {
writeErr(w, http.StatusInternalServerError, "保存预检结果失败")
return
}
keepUpload = true
_ = s.Store.PublishBatches.Recount(r.Context(), batchID)
// 预检响应保留逐行错误,客户端据此决定是否允许启动发布。
// preview_id 是后续启动、轮询和放弃预检的稳定标识。
// total、valid 和 invalid 继续使用旧统计口径。
// rows 保留类目和自动化配置,避免前端重复解析上传表格。
// 预检成功不代表远端商品已经发布。
// 远端发布失败仍由批次明细状态表达。
// 该 DTO 不改变上传目录清理和批次持久化时序。
writeJSON(w, http.StatusOK, itemPublishBatchPreviewResponse{Success: true, PreviewID: batchID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: previewRows})
writeJSON(w, http.StatusOK, preview)
/*
rows := make([]db.ItemPublishBatchRow, 0, len(parsed))
previewRows := make([]publishBatchPreviewRow, 0, len(parsed))
valid, invalid := 0, 0
for _, p := range parsed {
isValid := len(p.Errors) == 0
if isValid {
valid++
} else {
invalid++
}
imagesJSON, _ := json.Marshal(p.Images)
categoryJSON, _ := json.Marshal(p.Category)
automationJSON, _ := json.Marshal(p.Automation)
rawJSON, _ := json.Marshal(p.Raw)
status := "pending"
errMsg := ""
if !isValid {
status = "failed"
errMsg = strings.Join(p.Errors, ";")
}
rows = append(rows, db.ItemPublishBatchRow{
RowNo: p.RowNo,
CookieID: p.CookieID,
Title: p.Title,
Description: p.Description,
Price: p.Price,
OriginalPrice: p.OriginalPrice,
Quantity: p.Quantity,
PostageMode: p.PostageMode,
Postage: p.Postage,
ImagesJSON: string(imagesJSON),
CategoryJSON: string(categoryJSON),
AutomationJSON: string(automationJSON),
Status: status,
ErrorMessage: errMsg,
FailureKind: map[bool]string{true: "", false: "validation"}[isValid],
RawJSON: string(rawJSON),
})
previewRows = append(previewRows, publishBatchPreviewRow{
RowNo: p.RowNo,
Valid: isValid,
Errors: p.Errors,
CookieID: p.CookieID,
Title: p.Title,
Price: p.Price,
Quantity: p.Quantity,
Images: p.Images,
Category: p.Category,
Automation: p.Automation,
})
}
if len(rows) == 0 {
writeErr(w, http.StatusBadRequest, "表格中没有有效数据行")
return
}
if err := s.Store.PublishBatches.Create(r.Context(), &db.ItemPublishBatch{
ID: batchID,
UserID: sess.UserID,
DefaultCookieID: defaultCookieID,
Filename: sourceName,
UploadDir: uploadDir,
LocationJSON: string(locationBytes),
Status: "preview",
}, rows); err != nil {
writeErr(w, http.StatusInternalServerError, "保存预检结果失败")
return
}
keepUpload = true
_ = s.Store.PublishBatches.Recount(r.Context(), batchID)
// 预检响应保留逐行错误,客户端据此决定是否允许启动发布。
// preview_id 是后续启动、轮询和放弃预检的稳定标识。
// total、valid 和 invalid 继续使用旧统计口径。
// rows 保留类目和自动化配置,避免前端重复解析上传表格。
// 预检成功不代表远端商品已经发布。
// 远端发布失败仍由批次明细状态表达。
// 该 DTO 不改变上传目录清理和批次持久化时序。
writeJSON(w, http.StatusOK, itemPublishBatchPreviewResponse{Success: true, PreviewID: batchID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: previewRows})*/
}
// startItemPublishBatch 启动指定批次的后台发布 worker。
func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
var req struct {
@@ -376,162 +369,110 @@ func (s *Server) startItemPublishBatch(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "缺少 preview_id")
return
}
batch, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID)
startedID, err := s.itemPublishApplication().StartBatch(r.Context(), sess.UserID, batchID)
if err != nil {
writeErr(w, http.StatusNotFound, "批量任务不存在")
switch {
case errors.Is(err, errItemPublishBatchNotFound):
writeErr(w, http.StatusNotFound, "批量任务不存在")
case errors.Is(err, errItemPublishBatchConflict):
writeErr(w, http.StatusConflict, "任务正在由其他 worker 运行")
case errors.Is(err, errItemPublishBatchInvalidState):
writeErr(w, http.StatusBadRequest, "当前任务状态不能开始发布")
case errors.Is(err, errItemPublishBatchNoRows):
writeErr(w, http.StatusBadRequest, "没有可发布的商品行")
default:
writeErr(w, http.StatusInternalServerError, "启动任务失败")
}
return
}
activeRunning := batch.Status == "running" && batch.LeaseExpiresAt > time.Now().UTC().Unix()
if activeRunning {
writeErr(w, http.StatusConflict, "任务正在由其他 worker 运行")
return
}
if batch.Status != "preview" && batch.Status != "pending" && batch.Status != "completed" && batch.Status != "running" {
writeErr(w, http.StatusBadRequest, "当前任务状态不能开始发布")
return
}
workerToken := randomHex(16)
claimed, err := s.Store.PublishBatches.ClaimBatch(r.Context(), batch.ID, workerToken, time.Now().UTC().Add(publishBatchLease).Unix())
if err != nil {
writeErr(w, http.StatusInternalServerError, "启动任务失败")
return
}
if !claimed {
writeErr(w, http.StatusConflict, "任务已被其他 worker 启动")
return
}
pending, err := s.Store.PublishBatches.PendingRows(r.Context(), batch.ID, false)
if err != nil {
s.failClaimedPublishBatch(batch.ID, workerToken)
writeErr(w, http.StatusInternalServerError, "读取任务失败")
return
}
if len(pending) == 0 {
_, _, _ = s.Store.PublishBatches.FinalizeBatch(r.Context(), batch.ID, workerToken)
writeErr(w, http.StatusBadRequest, "没有可发布的商品行")
return
}
s.startPublishBatchWorker(s.lifecycleContext(), sess.UserID, batch.ID, workerToken)
writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: batch.ID})
writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: startedID})
}
// listItemPublishBatches 返回当前用户的批量发布任务列表。
func (s *Server) listItemPublishBatches(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
limit := atoiDefault(r.URL.Query().Get("limit"), 20)
batches, err := s.Store.PublishBatches.ListForUser(r.Context(), sess.UserID, limit)
result, err := s.itemPublishApplication().ListBatches(r.Context(), sess.UserID, limit)
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取批量任务失败")
return
}
result := make([]itemPublishBatchResponse, 0, len(batches))
for i := range batches {
result = append(result, publishBatchToMap(&batches[i], nil))
}
writeJSON(w, http.StatusOK, itemPublishBatchListResponse{Batches: result})
}
// getItemPublishBatch 返回指定批次及其发布明细。
func (s *Server) getItemPublishBatch(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
batchID := chi.URLParam(r, "batch_id")
batch, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID)
result, err := s.itemPublishApplication().GetBatch(r.Context(), sess.UserID, batchID)
if err != nil {
writeErr(w, http.StatusNotFound, "批量任务不存在")
if errors.Is(err, errItemPublishBatchNotFound) {
writeErr(w, http.StatusNotFound, "批量任务不存在")
} else {
writeErr(w, http.StatusInternalServerError, "读取任务明细失败")
}
return
}
rows, err := s.Store.PublishBatches.Rows(r.Context(), batch.ID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取任务明细失败")
return
}
writeJSON(w, http.StatusOK, publishBatchToMap(batch, rows))
writeJSON(w, http.StatusOK, result)
}
// cancelItemPublishBatch 请求取消指定批次并通知运行中的 worker。
func (s *Server) cancelItemPublishBatch(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
batchID := chi.URLParam(r, "batch_id")
_, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID)
status, err := s.itemPublishApplication().CancelBatch(r.Context(), sess.UserID, batchID)
if err != nil {
writeErr(w, http.StatusNotFound, "批量任务不存在")
return
}
workerToken, running, err := s.Store.PublishBatches.RequestCancel(r.Context(), batchID)
if err != nil {
if errors.Is(err, db.ErrPublishBatchChanged) {
if errors.Is(err, errItemPublishBatchNotFound) {
writeErr(w, http.StatusNotFound, "批量任务不存在")
} else if errors.Is(err, errItemPublishBatchConflict) {
writeErr(w, http.StatusConflict, "任务状态刚刚发生变化,请重试")
return
} else {
writeErr(w, http.StatusInternalServerError, "取消任务失败")
}
writeErr(w, http.StatusInternalServerError, "取消任务失败")
return
}
if running {
s.cancelPublishBatch(batchID, workerToken)
}
writeJSON(w, http.StatusOK, batchCancelResponse{Success: true, Status: map[bool]string{true: "canceling", false: "canceled"}[running]})
writeJSON(w, http.StatusOK, batchCancelResponse{Success: true, Status: status})
}
// deleteItemPublishBatch 删除已结束的批次及其上传目录。
func (s *Server) deleteItemPublishBatch(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
batchID := chi.URLParam(r, "batch_id")
batch, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID)
uploadDir, err := s.itemPublishApplication().DeleteBatch(r.Context(), sess.UserID, batchID)
if err != nil {
writeErr(w, http.StatusNotFound, "批量任务不存在")
if errors.Is(err, errItemPublishBatchNotFound) {
writeErr(w, http.StatusNotFound, "批量任务不存在")
} else if errors.Is(err, errItemPublishBatchConflict) {
writeErr(w, http.StatusConflict, "运行中的任务不能删除,请先取消")
} else {
writeErr(w, http.StatusInternalServerError, "删除批量任务失败")
}
return
}
if batch.Status == "running" || batch.Status == "canceling" {
writeErr(w, http.StatusConflict, "运行中的任务不能删除,请先取消")
return
}
if err := s.Store.PublishBatches.Delete(r.Context(), sess.UserID, batchID); err != nil {
writeErr(w, http.StatusInternalServerError, "删除批量任务失败")
return
}
if strings.TrimSpace(batch.UploadDir) != "" {
_ = os.RemoveAll(batch.UploadDir)
if strings.TrimSpace(uploadDir) != "" {
_ = os.RemoveAll(uploadDir)
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// retryFailedItemPublishBatch 重置失败明细并启动批次重试 worker。
func (s *Server) retryFailedItemPublishBatch(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
batchID := chi.URLParam(r, "batch_id")
batch, err := s.Store.PublishBatches.Get(r.Context(), sess.UserID, batchID)
startedID, err := s.itemPublishApplication().RetryFailedBatch(r.Context(), sess.UserID, batchID)
if err != nil {
writeErr(w, http.StatusNotFound, "批量任务不存在")
if errors.Is(err, errItemPublishBatchNotFound) {
writeErr(w, http.StatusNotFound, "批量任务不存在")
} else if errors.Is(err, errItemPublishBatchConflict) {
writeErr(w, http.StatusConflict, "任务正在运行,不能重复重试")
} else if errors.Is(err, errItemPublishBatchNoRows) {
writeErr(w, http.StatusBadRequest, "没有可重试的失败项")
} else {
writeErr(w, http.StatusInternalServerError, "启动重试失败")
}
return
}
if batch.Status == "running" && batch.LeaseExpiresAt > time.Now().UTC().Unix() {
writeErr(w, http.StatusConflict, "任务正在运行,不能重复重试")
return
}
workerToken := randomHex(16)
claimed, err := s.Store.PublishBatches.ClaimBatch(r.Context(), batchID, workerToken, time.Now().UTC().Add(publishBatchLease).Unix())
if err != nil {
writeErr(w, http.StatusInternalServerError, "启动重试失败")
return
}
if !claimed {
writeErr(w, http.StatusConflict, "任务已被其他 worker 启动")
return
}
if err := s.Store.PublishBatches.ResetFailed(r.Context(), batchID); err != nil {
s.failClaimedPublishBatch(batchID, workerToken)
writeErr(w, http.StatusInternalServerError, "重置失败项失败")
return
}
_ = s.Store.PublishBatches.Recount(r.Context(), batchID)
pending, err := s.Store.PublishBatches.PendingRows(r.Context(), batchID, false)
if err != nil {
s.failClaimedPublishBatch(batchID, workerToken)
writeErr(w, http.StatusInternalServerError, "读取可重试项失败")
return
}
if len(pending) == 0 {
_, _, _ = s.Store.PublishBatches.FinalizeBatch(r.Context(), batchID, workerToken)
writeErr(w, http.StatusBadRequest, "没有可重试的失败项")
return
}
s.startPublishBatchWorker(s.lifecycleContext(), sess.UserID, batchID, workerToken)
writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: batchID})
writeJSON(w, http.StatusOK, batchIDResponse{Success: true, BatchID: startedID})
}
func (s *Server) startPublishBatchWorker(parent context.Context, userID int64, batchID, workerToken string) {
+415
View File
@@ -0,0 +1,415 @@
package server
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
var (
// errItemPublishBatchNotFound 表示当前用户无法访问指定批量任务。
errItemPublishBatchNotFound = errors.New("商品批量任务不存在")
// errItemPublishBatchConflict 表示批量任务的租约或状态发生并发冲突。
errItemPublishBatchConflict = errors.New("商品批量任务状态冲突")
// errItemPublishBatchInvalidState 表示批量任务当前状态不允许执行请求操作。
errItemPublishBatchInvalidState = errors.New("商品批量任务状态不允许执行该操作")
// errItemPublishBatchNoRows 表示批量任务没有可继续处理的明细行。
errItemPublishBatchNoRows = errors.New("商品批量任务没有可处理的明细行")
)
// itemPublishInput 是单个商品发布用例的业务输入,不包含 HTTP 请求对象。
type itemPublishInput struct {
// UserID 是发起发布操作的用户标识。
UserID int64
// CookieID 是执行商品发布的账号标识。
CookieID string
// Title 是商品标题。
Title string
// Description 是商品描述。
Description string
// PriceCents 是商品售价,单位为分。
PriceCents int64
// OriginalPriceCents 是商品原价,单位为分。
OriginalPriceCents int64
// Quantity 是商品库存数量。
Quantity int
// PostageMode 是邮费模式。
PostageMode string
// PostageCents 是邮费金额,单位为分。
PostageCents int64
// Location 是可选的发货地。
Location *mtop.PublishLocation
// Images 是待上传的商品图片。
Images []mtop.PublishImage
}
// itemPublishOutcome 是单个商品发布用例的结果及发布后的持久化风险。
type itemPublishOutcome struct {
// Result 是平台返回的商品信息。
Result *mtop.PublishItemResult
// ResponseCookieErr 是平台响应 Cookie 未能持久化时的错误。
ResponseCookieErr error
// LocalSaveErr 是平台成功后本地商品落库失败时的错误。
LocalSaveErr error
}
// itemPublishPreviewInput 是批量发布预检结果持久化所需的业务输入。
type itemPublishPreviewInput struct {
// UserID 是创建批次的用户标识。
UserID int64
// BatchID 是预检批次标识。
BatchID string
// DefaultCookieID 是未指定账号行使用的默认账号。
DefaultCookieID string
// Filename 是用户上传的表格文件名。
Filename string
// UploadDir 是批次图片和表格的受控目录。
UploadDir string
// Location 是批次统一发货地。
Location mtop.PublishLocation
// Rows 是解析并校验后的商品行。
Rows []publishBatchParsedRow
}
// itemPublishService 是商品发布应用服务,隔离 HTTP 适配与业务状态变更。
type itemPublishService struct {
// server 提供数据库、MTOP 客户端、运行时 Cookie 和 worker 生命周期依赖。
server *Server
}
// itemPublishApplication 返回当前 Server 绑定的商品发布应用服务。
func (s *Server) itemPublishApplication() *itemPublishService {
return &itemPublishService{server: s}
}
// PublishSingle 执行单商品发布、响应 Cookie 持久化和本地商品落库。
func (svc *itemPublishService) PublishSingle(ctx context.Context, input itemPublishInput) (itemPublishOutcome, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// unlock 释放当前账号的凭证串行化锁。
unlock := s.Store.LockAccountCredentials(input.CookieID)
// err 和 latest 保存账号平台详情查询结果。
latest, err := s.loadCookiePlatformDetail(ctx, input.CookieID)
if err != nil || latest == nil || latest.UserID != input.UserID || !hasStoredCookieCredential(latest) {
unlock()
return itemPublishOutcome{}, errors.New("账号凭证已变化,请重试")
}
// cookieValue 是本次 MTOP 调用使用的账号凭证。
cookieValue := latest.Value
// requestCtx 和 cancel 控制单商品发布的最长执行时间。
requestCtx, cancel := context.WithTimeout(ctx, 2*time.Minute)
defer cancel()
// client 是平台发布客户端。
client := s.mtopClient()
// mtopCtx 和 cookieSession 保存带 Cookie 快照的平台调用上下文。
mtopCtx, cookieSession := withMTopCookieSnapshot(requestCtx, latest)
// result 和 callErr 是平台发布结果及调用错误。
result, callErr := client.PublishItem(mtopCtx, cookieValue, mtop.PublishItemRequest{
Title: input.Title, Description: input.Description, PriceCents: input.PriceCents,
OriginalPriceCents: input.OriginalPriceCents, Quantity: input.Quantity,
PostageMode: input.PostageMode, PostageCents: input.PostageCents, Virtual: true,
Location: input.Location, Images: input.Images,
})
// runtimeCookie 是需要同步到运行时账号的刷新凭证。
runtimeCookie := ""
// value、valueChanged、handled 和 persistErr 描述 Cookie Jar 持久化结果。
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
if s.Logger != nil {
s.Logger.Error("保存发布响应 Cookie Jar 失败", "cookie_id", input.CookieID, "err", persistErr)
}
} else if handled && valueChanged {
runtimeCookie = value
} else if !handled && callErr == nil && result != nil && result.UpdatedCookies != "" && result.UpdatedCookies != cookieValue {
// saveErr 表示保存平台返回新 Cookie 的错误。
if saveErr := s.Store.Cookies.UpdateValueOwned(ctx, input.CookieID, result.UpdatedCookies, input.UserID); saveErr != nil {
persistErr = saveErr
} else {
runtimeCookie = result.UpdatedCookies
}
}
unlock()
if runtimeCookie != "" {
s.updateRunningCookie(ctx, input.CookieID, runtimeCookie)
}
if callErr != nil {
if persistErr != nil {
callErr = errors.Join(callErr, fmt.Errorf("保存发布响应 Cookie: %w", persistErr))
}
s.recoverExpiredMTOPSession(ctx, input.CookieID, callErr)
return itemPublishOutcome{ResponseCookieErr: persistErr}, callErr
}
if result == nil || strings.TrimSpace(result.ItemID) == "" {
return itemPublishOutcome{Result: result, ResponseCookieErr: persistErr}, nil
}
// detail 保存平台商品附加信息。
detail := map[string]any{"item_image": result.ImageURL, "web_url": result.ItemURL, "category_name": result.CategoryName, "quantity": result.Quantity, "publish_raw": result.RawData}
// detailJSON 是本地商品详情 JSON。
detailJSON, _ := json.Marshal(detail)
// localErr 表示平台发布成功后本地商品落库的错误。
localErr := s.Store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: input.CookieID, ItemID: result.ItemID, ItemTitle: result.Title,
ItemDescription: input.Description, ItemCategory: result.CategoryID,
ItemPrice: result.PriceText, ItemDetail: string(detailJSON), MultiQuantityDelivery: input.Quantity > 1,
})
return itemPublishOutcome{Result: result, ResponseCookieErr: persistErr, LocalSaveErr: localErr}, nil
}
// RecommendCategory 调用平台类目推荐并持久化刷新后的账号登录状态。
func (svc *itemPublishService) RecommendCategory(ctx context.Context, userID int64, cookieID, keyword string) (mtop.PublishCategory, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// recommender 和 ok 表示 MTOP 客户端是否支持类目推荐。
recommender, ok := s.mtopClient().(publishCategoryRecommender)
if !ok {
return mtop.PublishCategory{}, errors.New("当前 MTOP 客户端不支持类目推荐")
}
// unlock 释放当前账号的凭证串行化锁。
unlock := s.Store.LockAccountCredentials(cookieID)
// runtimeCookie 是需要在释放凭证锁后同步的刷新凭证。
runtimeCookie := ""
defer func() {
unlock()
if runtimeCookie != "" {
s.updateRunningCookie(context.Background(), cookieID, runtimeCookie)
}
}()
// err 和 latest 保存账号平台详情查询结果。
latest, err := s.loadCookiePlatformDetail(ctx, cookieID)
if err != nil || latest == nil || latest.UserID != userID || !hasStoredCookieCredential(latest) {
return mtop.PublishCategory{}, errors.New("账号凭证已变化,请重试")
}
// requestCtx 和 cancel 控制类目推荐的最长执行时间。
requestCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
// mtopCtx 和 cookieSession 保存带 Cookie 快照的平台上下文。
mtopCtx, cookieSession := withMTopCookieSnapshot(requestCtx, latest)
// category、updatedCookies 和 callErr 是平台推荐结果、刷新凭证及调用错误。
category, updatedCookies, callErr := recommender.RecommendPublishCategory(mtopCtx, latest.Value, keyword)
// value、valueChanged、handled 和 persistErr 描述 Cookie Jar 持久化结果。
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
if persistErr != nil {
return mtop.PublishCategory{}, fmt.Errorf("保存账号登录状态失败: %w", persistErr)
}
if !handled && updatedCookies != "" && updatedCookies != latest.Value {
// err 表示保存平台返回新 Cookie 的错误。
if err := s.Store.Cookies.UpdateValueOwned(ctx, cookieID, updatedCookies, userID); err != nil {
return mtop.PublishCategory{}, fmt.Errorf("保存账号登录状态失败: %w", err)
}
runtimeCookie = updatedCookies
} else if handled && valueChanged {
runtimeCookie = value
}
if callErr != nil {
return mtop.PublishCategory{}, callErr
}
return category, nil
}
// PersistPreview 将预检行转换为数据库批次并返回兼容旧接口的预检 DTO。
func (svc *itemPublishService) PersistPreview(ctx context.Context, input itemPublishPreviewInput) (itemPublishBatchPreviewResponse, error) {
// rows 是待写入数据库的批量明细行。
rows := make([]db.ItemPublishBatchRow, 0, len(input.Rows))
// previewRows 是返回给前端的逐行预检视图。
previewRows := make([]publishBatchPreviewRow, 0, len(input.Rows))
// valid 和 invalid 记录预检通过与失败的行数。
valid, invalid := 0, 0
// parsed 是当前正在转换的预检行。
for _, parsed := range input.Rows {
// isValid 表示当前行是否没有校验错误。
isValid := len(parsed.Errors) == 0
if isValid {
valid++
} else {
invalid++
}
// imagesJSON、categoryJSON、automationJSON 和 rawJSON 是行数据的 JSON 表示。
imagesJSON, _ := json.Marshal(parsed.Images)
// categoryJSON 是商品类目的 JSON 表示。
categoryJSON, _ := json.Marshal(parsed.Category)
// automationJSON 是发布后自动化配置的 JSON 表示。
automationJSON, _ := json.Marshal(parsed.Automation)
// rawJSON 是原始导入行的 JSON 表示。
rawJSON, _ := json.Marshal(parsed.Raw)
// status、errorMessage 和 failureKind 保存数据库状态及失败分类。
status, errorMessage, failureKind := "pending", "", ""
if !isValid {
status, errorMessage, failureKind = "failed", strings.Join(parsed.Errors, ";"), "validation"
}
rows = append(rows, db.ItemPublishBatchRow{RowNo: parsed.RowNo, CookieID: parsed.CookieID, Title: parsed.Title, Description: parsed.Description, Price: parsed.Price, OriginalPrice: parsed.OriginalPrice, Quantity: parsed.Quantity, PostageMode: parsed.PostageMode, Postage: parsed.Postage, ImagesJSON: string(imagesJSON), CategoryJSON: string(categoryJSON), AutomationJSON: string(automationJSON), Status: status, ErrorMessage: errorMessage, FailureKind: failureKind, RawJSON: string(rawJSON)})
previewRows = append(previewRows, publishBatchPreviewRow{RowNo: parsed.RowNo, Valid: isValid, Errors: parsed.Errors, CookieID: parsed.CookieID, Title: parsed.Title, Price: parsed.Price, Quantity: parsed.Quantity, Images: parsed.Images, Category: parsed.Category, Automation: parsed.Automation})
}
if len(rows) == 0 {
return itemPublishBatchPreviewResponse{}, errItemPublishBatchNoRows
}
// locationBytes 是批次发货地配置的 JSON 表示。
locationBytes, _ := json.Marshal(input.Location)
// err 表示批次及其明细的事务写入错误。
if err := svc.server.Store.PublishBatches.Create(ctx, &db.ItemPublishBatch{ID: input.BatchID, UserID: input.UserID, DefaultCookieID: input.DefaultCookieID, Filename: input.Filename, UploadDir: input.UploadDir, LocationJSON: string(locationBytes), Status: "preview"}, rows); err != nil {
return itemPublishBatchPreviewResponse{}, fmt.Errorf("保存预检结果失败: %w", err)
}
_ = svc.server.Store.PublishBatches.Recount(ctx, input.BatchID)
return itemPublishBatchPreviewResponse{Success: true, PreviewID: input.BatchID, Total: len(rows), Valid: valid, Invalid: invalid, Rows: previewRows}, nil
}
// StartBatch 校验并声明批量任务租约,然后启动后台发布 worker。
func (svc *itemPublishService) StartBatch(ctx context.Context, userID int64, batchID string) (string, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// batch 和 err 保存批次查询结果。
batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID)
if err != nil {
return "", errItemPublishBatchNotFound
}
if batch.Status == "running" && batch.LeaseExpiresAt > time.Now().UTC().Unix() {
return "", errItemPublishBatchConflict
}
if batch.Status != "preview" && batch.Status != "pending" && batch.Status != "completed" && batch.Status != "running" {
return "", errItemPublishBatchInvalidState
}
// token 是本次 worker 租约的随机凭证。
token := randomHex(16)
// claimed 和 err 保存批次租约声明结果。
claimed, err := s.Store.PublishBatches.ClaimBatch(ctx, batch.ID, token, time.Now().UTC().Add(publishBatchLease).Unix())
if err != nil {
return "", fmt.Errorf("启动任务失败: %w", err)
}
if !claimed {
return "", errItemPublishBatchConflict
}
// pending 和 err 保存待处理明细查询结果。
pending, err := s.Store.PublishBatches.PendingRows(ctx, batch.ID, false)
if err != nil {
s.failClaimedPublishBatch(batch.ID, token)
return "", fmt.Errorf("读取任务失败: %w", err)
}
if len(pending) == 0 {
_, _, _ = s.Store.PublishBatches.FinalizeBatch(ctx, batch.ID, token)
return "", errItemPublishBatchNoRows
}
s.startPublishBatchWorker(s.lifecycleContext(), userID, batch.ID, token)
return batch.ID, nil
}
// ListBatches 查询用户的批量任务并映射为 HTTP 无关的响应 DTO。
func (svc *itemPublishService) ListBatches(ctx context.Context, userID int64, limit int) ([]itemPublishBatchResponse, error) {
// batches 和 err 保存用户批次列表查询结果。
batches, err := svc.server.Store.PublishBatches.ListForUser(ctx, userID, limit)
if err != nil {
return nil, err
}
// result 是批次列表响应视图。
result := make([]itemPublishBatchResponse, 0, len(batches))
// i 是当前批次在查询结果中的索引。
for i := range batches {
result = append(result, publishBatchToMap(&batches[i], nil))
}
return result, nil
}
// GetBatch 查询用户拥有的批量任务及其明细行。
func (svc *itemPublishService) GetBatch(ctx context.Context, userID int64, batchID string) (itemPublishBatchResponse, error) {
// batch 和 err 保存批次查询结果。
batch, err := svc.server.Store.PublishBatches.Get(ctx, userID, batchID)
if err != nil {
return itemPublishBatchResponse{}, errItemPublishBatchNotFound
}
// rows 和 err 保存批次明细查询结果。
rows, err := svc.server.Store.PublishBatches.Rows(ctx, batch.ID)
if err != nil {
return itemPublishBatchResponse{}, err
}
return publishBatchToMap(batch, rows), nil
}
// CancelBatch 请求批量任务取消并通知内存中的 worker。
func (svc *itemPublishService) CancelBatch(ctx context.Context, userID int64, batchID string) (string, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// err 表示批次所有权查询错误。
if _, err := s.Store.PublishBatches.Get(ctx, userID, batchID); err != nil {
return "", errItemPublishBatchNotFound
}
// token、running 和 err 保存取消请求及当前 worker 状态。
token, running, err := s.Store.PublishBatches.RequestCancel(ctx, batchID)
if err != nil {
if errors.Is(err, db.ErrPublishBatchChanged) {
return "", errItemPublishBatchConflict
}
return "", err
}
if running {
s.cancelPublishBatch(batchID, token)
}
if running {
return "canceling", nil
}
return "canceled", nil
}
// DeleteBatch 删除非运行中的批量任务并返回其上传目录供适配层清理。
func (svc *itemPublishService) DeleteBatch(ctx context.Context, userID int64, batchID string) (string, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// batch 和 err 保存批次查询结果。
batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID)
if err != nil {
return "", errItemPublishBatchNotFound
}
if batch.Status == "running" || batch.Status == "canceling" {
return "", errItemPublishBatchConflict
}
// err 表示批次删除错误。
if err := s.Store.PublishBatches.Delete(ctx, userID, batchID); err != nil {
return "", err
}
return batch.UploadDir, nil
}
// RetryFailedBatch 重置失败明细并启动仅处理失败项的后台 worker。
func (svc *itemPublishService) RetryFailedBatch(ctx context.Context, userID int64, batchID string) (string, error) {
// s 是当前商品发布应用服务依赖的 Server。
s := svc.server
// batch 和 err 保存批次查询结果。
batch, err := s.Store.PublishBatches.Get(ctx, userID, batchID)
if err != nil {
return "", errItemPublishBatchNotFound
}
if batch.Status == "running" && batch.LeaseExpiresAt > time.Now().UTC().Unix() {
return "", errItemPublishBatchConflict
}
// token 是本次重试 worker 的租约凭证。
token := randomHex(16)
// claimed 和 err 保存重试租约声明结果。
claimed, err := s.Store.PublishBatches.ClaimBatch(ctx, batchID, token, time.Now().UTC().Add(publishBatchLease).Unix())
if err != nil {
return "", err
}
if !claimed {
return "", errItemPublishBatchConflict
}
// err 表示重置失败明细的错误。
if err := s.Store.PublishBatches.ResetFailed(ctx, batchID); err != nil {
s.failClaimedPublishBatch(batchID, token)
return "", err
}
_ = s.Store.PublishBatches.Recount(ctx, batchID)
// pending 和 err 保存可重试明细查询结果。
pending, err := s.Store.PublishBatches.PendingRows(ctx, batchID, false)
if err != nil {
s.failClaimedPublishBatch(batchID, token)
return "", err
}
if len(pending) == 0 {
_, _, _ = s.Store.PublishBatches.FinalizeBatch(ctx, batchID, token)
return "", errItemPublishBatchNoRows
}
s.startPublishBatchWorker(s.lifecycleContext(), userID, batchID, token)
return batchID, nil
}
@@ -0,0 +1,53 @@
package server
import (
"context"
"testing"
"xianyu-go/internal/xianyu/mtop"
)
// TestItemPublishServicePersistPreview 验证预检结果由应用服务统一持久化并可再次读取。
func TestItemPublishServicePersistPreview(t *testing.T) {
// srv、store 和 cleanup 构造并释放测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// service 是待验证的商品发布应用服务。
service := srv.itemPublishApplication()
// preview 和 err 保存预检持久化结果。
preview, err := service.PersistPreview(context.Background(), itemPublishPreviewInput{
UserID: 1, BatchID: "batch_service_test", DefaultCookieID: "acc1",
Filename: "products.csv", UploadDir: "/tmp/publish-service-test",
Location: mtop.PublishLocation{DivisionID: "3301"},
Rows: []publishBatchParsedRow{{
RowNo: 2, CookieID: "acc1", Title: "服务层商品", Price: "12.50", Quantity: 1,
Images: []string{"img/a.png"}, Category: mtop.PublishCategory{CatID: "5001", CatName: "虚拟商品"},
}},
})
if err != nil {
t.Fatalf("PersistPreview error: %v", err)
}
if !preview.Success || preview.PreviewID != "batch_service_test" || preview.Valid != 1 || preview.Invalid != 0 {
t.Fatalf("unexpected preview: %+v", preview)
}
// got 和 err 保存从数据库读取的批次视图。
got, err := service.GetBatch(context.Background(), 1, preview.PreviewID)
if err != nil {
t.Fatalf("GetBatch error: %v", err)
}
if got.ID != preview.PreviewID || len(got.Rows) != 1 || got.Rows[0].Title != "服务层商品" {
t.Fatalf("unexpected batch: %+v", got)
}
}
// TestItemPublishServiceStartBatchNotFound 验证应用服务对越权或不存在批次返回统一领域错误。
func TestItemPublishServiceStartBatchNotFound(t *testing.T) {
// srv、store 和 cleanup 构造并释放测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// err 保存不存在批次的业务错误。
_, err := srv.itemPublishApplication().StartBatch(context.Background(), 1, "missing-batch")
if err != errItemPublishBatchNotFound {
t.Fatalf("error=%v want %v", err, errItemPublishBatchNotFound)
}
}