feat(批量铺货): 支持关键词类目推荐与最终兜底
This commit is contained in:
1 parent
b98c4edf68
commit
8fdc25483f
20 files changed
+531
-194
No files matched your search
@@ -23,6 +23,7 @@ func (s *Server) mountItemsReal(r chi.Router) {
|
||||
r.Post("/items/get-all-from-account", s.syncItemsFromAccount)
|
||||
r.Post("/items/get-by-page", s.syncItemsPageFromAccount)
|
||||
r.Post("/items/publish", s.publishItem)
|
||||
r.Post("/items/publish-categories/recommend", s.recommendItemPublishCategory)
|
||||
r.Post("/items/publish-batches/preview", s.previewItemPublishBatch)
|
||||
r.Post("/items/publish-batches", s.startItemPublishBatch)
|
||||
r.Get("/items/publish-batches", s.listItemPublishBatches)
|
||||
|
||||
@@ -20,6 +20,45 @@ type stubPublishMTop struct {
|
||||
publish func(context.Context, string, mtop.PublishItemRequest) (*mtop.PublishItemResult, error)
|
||||
}
|
||||
|
||||
func TestRecommendItemPublishCategory(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
client := mtop.NewClient()
|
||||
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||||
if req.URL.Query().Get("api") != "mtop.taobao.idle.kgraph.property.recommend" {
|
||||
t.Fatalf("api=%q", req.URL.Query().Get("api"))
|
||||
}
|
||||
return &http.Response{
|
||||
StatusCode: http.StatusOK,
|
||||
Header: make(http.Header),
|
||||
Body: io.NopCloser(strings.NewReader(
|
||||
`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"propertyId":"-10000","propertyName":"分类","valuesList":[{"catId":"50023914","catName":"电子资料","channelCatId":"202036301","isClicked":"1"}]}}]}}`,
|
||||
)),
|
||||
Request: req,
|
||||
}, nil
|
||||
})}
|
||||
srv.MTop = client
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-categories/recommend", strings.NewReader(`{"cookie_id":"acc1","keyword":"课程资料"}`))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var response struct {
|
||||
Category mtop.PublishCategory `json:"category"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("decode: %v", err)
|
||||
}
|
||||
if response.Category.CatID != "50023914" || response.Category.CatName != "电子资料" || response.Category.ChannelCatID != "202036301" {
|
||||
t.Fatalf("category=%+v", response.Category)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *stubPublishMTop) PublishItem(ctx context.Context, cookies string, req mtop.PublishItemRequest) (*mtop.PublishItemResult, error) {
|
||||
return s.publish(ctx, cookies, req)
|
||||
}
|
||||
|
||||
@@ -94,6 +94,72 @@ type publishReviewRequestCfg struct {
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
}
|
||||
|
||||
type publishCategoryRecommender interface {
|
||||
RecommendPublishCategory(ctx context.Context, cookiesStr, keyword string) (mtop.PublishCategory, string, error)
|
||||
}
|
||||
|
||||
func (s *Server) recommendItemPublishCategory(w http.ResponseWriter, r *http.Request) {
|
||||
var req struct {
|
||||
CookieID string `json:"cookie_id"`
|
||||
Keyword string `json:"keyword"`
|
||||
}
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
req.CookieID = strings.TrimSpace(req.CookieID)
|
||||
req.Keyword = strings.TrimSpace(req.Keyword)
|
||||
if req.CookieID == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请先选择发布账号")
|
||||
return
|
||||
}
|
||||
if req.Keyword == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请输入类目关键词")
|
||||
return
|
||||
}
|
||||
_, userID, ok := s.cookieForCurrentUser(w, r, req.CookieID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
recommender, ok := s.mtopClient().(publishCategoryRecommender)
|
||||
if !ok {
|
||||
writeErr(w, http.StatusNotImplemented, "当前 MTOP 客户端不支持类目推荐")
|
||||
return
|
||||
}
|
||||
|
||||
credentialUnlock := s.Store.LockAccountCredentials(req.CookieID)
|
||||
defer credentialUnlock()
|
||||
latest, err := s.Store.Cookies.GetDetails(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)
|
||||
_, _, 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, "保存账号登录状态失败")
|
||||
return
|
||||
}
|
||||
}
|
||||
if callErr != nil {
|
||||
if errors.Is(callErr, mtop.ErrPublishCategoryUnrecognized) {
|
||||
writeErr(w, http.StatusNotFound, "没有匹配到可发布类目,请换一个关键词")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusBadGateway, callErr.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "category": category})
|
||||
}
|
||||
|
||||
func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
s.cleanupExpiredPublishUploads(r.Context())
|
||||
@@ -119,8 +185,9 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
ChannelCatID: strings.TrimSpace(r.FormValue("fallback_channel_category_id")),
|
||||
TBCatID: strings.TrimSpace(r.FormValue("fallback_tb_category_id")),
|
||||
}
|
||||
if fallbackCategory.CatID == "" || fallbackCategory.CatName == "" {
|
||||
writeErr(w, http.StatusBadRequest, "请同时填写批次兜底类目 ID 和类目名称")
|
||||
hasDefaultCategory := fallbackCategory.CatID != "" || fallbackCategory.CatName != "" || fallbackCategory.ChannelCatID != "" || fallbackCategory.TBCatID != ""
|
||||
if hasDefaultCategory && (fallbackCategory.CatID == "" || fallbackCategory.CatName == "" || fallbackCategory.ChannelCatID == "") {
|
||||
writeErr(w, http.StatusBadRequest, "默认类目信息不完整,请重新通过关键词获取")
|
||||
return
|
||||
}
|
||||
source, sourceHeader, err := r.FormFile("file")
|
||||
@@ -536,7 +603,7 @@ func (s *Server) downloadItemPublishBatchResult(w http.ResponseWriter, r *http.R
|
||||
var buf bytes.Buffer
|
||||
buf.WriteString("\xEF\xBB\xBF")
|
||||
cw := csv.NewWriter(&buf)
|
||||
_ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "兜底类目ID", "兜底类目名称", "商品ID", "商品URL", "错误原因"})
|
||||
_ = cw.Write([]string{"行号", "状态", "账号ID", "标题", "价格", "库存", "默认类目ID", "默认类目名称", "商品ID", "商品URL", "错误原因"})
|
||||
for _, row := range rows {
|
||||
var category mtop.PublishCategory
|
||||
_ = json.Unmarshal([]byte(row.CategoryJSON), &category)
|
||||
@@ -781,16 +848,19 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
res := &mtop.PublishItemResult{ItemID: row.ItemID, ItemURL: row.ItemURL, Title: row.Title, PriceText: row.Price, Quantity: row.Quantity}
|
||||
var responseCookieErr error
|
||||
if row.ItemID == "" {
|
||||
var preferredCategory *mtop.PublishCategory
|
||||
rawCategory := strings.TrimSpace(row.CategoryJSON)
|
||||
if rawCategory == "" || rawCategory == "{}" {
|
||||
return errors.New("批量任务缺少兜底类目,请重新上传并创建任务")
|
||||
}
|
||||
var fallbackCategory mtop.PublishCategory
|
||||
if err := json.Unmarshal([]byte(rawCategory), &fallbackCategory); err != nil {
|
||||
return errors.New("兜底类目配置损坏,请重新创建批量任务")
|
||||
}
|
||||
if strings.TrimSpace(fallbackCategory.CatID) == "" || strings.TrimSpace(fallbackCategory.CatName) == "" {
|
||||
return errors.New("兜底类目缺少类目 ID 或类目名称,请重新创建批量任务")
|
||||
if rawCategory != "" && rawCategory != "{}" {
|
||||
var configured mtop.PublishCategory
|
||||
if err := json.Unmarshal([]byte(rawCategory), &configured); err != nil {
|
||||
return errors.New("默认类目配置损坏,请重新创建批量任务")
|
||||
}
|
||||
if strings.TrimSpace(configured.CatID) != "" || strings.TrimSpace(configured.CatName) != "" || strings.TrimSpace(configured.ChannelCatID) != "" || strings.TrimSpace(configured.TBCatID) != "" {
|
||||
if strings.TrimSpace(configured.CatID) == "" || strings.TrimSpace(configured.CatName) == "" || strings.TrimSpace(configured.ChannelCatID) == "" {
|
||||
return errors.New("默认类目信息不完整,请重新创建批量任务")
|
||||
}
|
||||
preferredCategory = &configured
|
||||
}
|
||||
}
|
||||
images, err := loadBatchPublishImages(ctx, batch.UploadDir, row)
|
||||
if err != nil {
|
||||
@@ -830,7 +900,7 @@ func (s *Server) publishBatchRow(ctx context.Context, userID int64, client mtop.
|
||||
PostageMode: row.PostageMode,
|
||||
PostageCents: postageCents,
|
||||
Virtual: true,
|
||||
FallbackCategory: &fallbackCategory,
|
||||
PreferredCategory: preferredCategory,
|
||||
Images: images,
|
||||
})
|
||||
value, valueChanged, handled, persistErr := s.persistMTopCookieSessionLocked(ctx, latest, cookieSession)
|
||||
@@ -1064,8 +1134,8 @@ func (s *Server) parsePublishRows(ctx context.Context, userID int64, defaultCook
|
||||
hasRowCategory := rowCategory.CatID != "" || rowCategory.CatName != "" || rowCategory.ChannelCatID != "" || rowCategory.TBCatID != ""
|
||||
if hasRowCategory {
|
||||
row.Category = rowCategory
|
||||
if rowCategory.CatID == "" || rowCategory.CatName == "" {
|
||||
row.Errors = append(row.Errors, "指定行类目时必须同时填写类目ID和类目名称")
|
||||
if rowCategory.CatID == "" || rowCategory.CatName == "" || rowCategory.ChannelCatID == "" {
|
||||
row.Errors = append(row.Errors, "指定行类目时必须同时填写类目ID、类目名称和频道类目ID")
|
||||
}
|
||||
} else {
|
||||
row.Category = fallbackCategory
|
||||
|
||||
@@ -97,6 +97,7 @@ func previewPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie) stri
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -126,6 +127,7 @@ func previewTwoRowPublishBatch(t *testing.T, h http.Handler, cookie *http.Cookie
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\nacc1,商品B,13.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
|
||||
@@ -81,6 +81,7 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
@@ -107,7 +108,7 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewItemPublishBatchRequiresFallbackCategory(t *testing.T) {
|
||||
func TestPreviewItemPublishBatchAllowsEmptyDefaultCategory(t *testing.T) {
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
h := srv.Router()
|
||||
@@ -124,9 +125,16 @@ func TestPreviewItemPublishBatchRequiresFallbackCategory(t *testing.T) {
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "兜底类目") {
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var res map[string]any
|
||||
_ = json.Unmarshal(rec.Body.Bytes(), &res)
|
||||
row := res["rows"].([]any)[0].(map[string]any)
|
||||
category := row["category"].(map[string]any)
|
||||
if category["cat_id"] != "" || category["cat_name"] != "" {
|
||||
t.Fatalf("category should be empty: %+v", category)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreviewItemPublishBatchRowCategoryOverridesFallback(t *testing.T) {
|
||||
@@ -140,8 +148,9 @@ func TestPreviewItemPublishBatchRowCategoryOverridesFallback(t *testing.T) {
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "批次类目")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
file, _ := mw.CreateFormFile("file", "products.csv")
|
||||
file.Write([]byte("标题,价格,图片,类目ID,类目名称\n商品A,12.50,https://example.com/a.png,7001,行指定类目\n"))
|
||||
file.Write([]byte("标题,价格,图片,类目ID,类目名称,频道类目ID\n商品A,12.50,https://example.com/a.png,7001,行指定类目,8001\n"))
|
||||
_ = mw.Close()
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
req.Header.Set("Content-Type", mw.FormDataContentType())
|
||||
@@ -172,6 +181,7 @@ func TestPreviewItemPublishBatchNoFile(t *testing.T) {
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
_ = mw.Close()
|
||||
|
||||
req := httptest.NewRequest(http.MethodPost, "/items/publish-batches/preview", &buf)
|
||||
@@ -246,6 +256,7 @@ func TestPreviewItemPublishBatchTooManyRows(t *testing.T) {
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write(csvBuf.Bytes())
|
||||
_ = mw.Close()
|
||||
@@ -278,6 +289,7 @@ func TestPreviewItemPublishBatchZipTraversal(t *testing.T) {
|
||||
_ = mw.WriteField("default_cookie_id", "acc1")
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,../escape.png\n"))
|
||||
zipField, _ := mw.CreateFormFile("images_zip", "images.zip")
|
||||
|
||||
Reference in new issue
Block a user