merge: 合并商品同步修复到 main

This commit is contained in:
Christ committed 2026-08-10 01:11:56 +08:00
commit 4fb857da1e
4 files changed
+202 -15

No files matched your search

+79
View File
@@ -5,6 +5,7 @@ import (
"database/sql"
"errors"
"strconv"
"strings"
)
// ---- 关键字 CRUD ----
@@ -520,6 +521,12 @@ type ItemInfoRow struct {
MultiQuantityDelivery bool
}
// ItemSyncResult 是一次远端商品全集同步的结果。
type ItemSyncResult struct {
Saved int
Deleted int
}
// AllForCookie 取某账号全部商品。
func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRow, error) {
rows, err := i.DB.QueryContext(ctx,
@@ -577,6 +584,78 @@ func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) e
return i.upsertBasic(ctx, tx, r)
}
// SyncFromRemote 将远端商品全集同步到本地。
//
// 远端列表只提供商品基础信息,因此保留本地的描述和发货配置;基础字段
// (标题、分类、价格、详情)由远端非空值覆盖。整个 reconcile 在一个事务内
// 完成,只有在全部远端商品写入成功后,才会删除本次全集中不存在的本地商品。
func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []ItemInfoRow) (ItemSyncResult, error) {
cookieID = strings.TrimSpace(cookieID)
if cookieID == "" {
return ItemSyncResult{}, errors.New("cookie_id 不能为空")
}
remoteIDs := make(map[string]struct{}, len(rows))
validRows := make([]ItemInfoRow, 0, len(rows))
for _, row := range rows {
row.CookieID = cookieID
row.ItemID = strings.TrimSpace(row.ItemID)
if row.ItemID == "" {
continue
}
if _, exists := remoteIDs[row.ItemID]; exists {
continue
}
remoteIDs[row.ItemID] = struct{}{}
validRows = append(validRows, row)
}
tx, err := i.DB.BeginTx(ctx, nil)
if err != nil {
return ItemSyncResult{}, err
}
rollback := func(err error) (ItemSyncResult, error) {
_ = tx.Rollback()
return ItemSyncResult{}, err
}
for index := range validRows {
if err := i.UpsertBasicTx(ctx, tx, &validRows[index]); err != nil {
return rollback(err)
}
if validRows[index].IsMultiSpec {
if _, err := tx.ExecContext(ctx,
`UPDATE item_info SET is_multi_spec=? WHERE cookie_id=? AND item_id=?`,
boolToInt(true), cookieID, validRows[index].ItemID); err != nil {
return rollback(err)
}
}
}
args := make([]any, 0, len(remoteIDs)+1)
args = append(args, cookieID)
deleteQuery := `DELETE FROM item_info WHERE cookie_id=?`
if len(remoteIDs) > 0 {
placeholders := make([]string, 0, len(remoteIDs))
for itemID := range remoteIDs {
placeholders = append(placeholders, "?")
args = append(args, itemID)
}
deleteQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")"
}
deletedResult, err := tx.ExecContext(ctx, deleteQuery, args...)
if err != nil {
return rollback(err)
}
deleted, err := deletedResult.RowsAffected()
if err != nil {
return rollback(err)
}
if err := tx.Commit(); err != nil {
return ItemSyncResult{}, err
}
return ItemSyncResult{Saved: len(validRows), Deleted: int(deleted)}, nil
}
func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRow) error {
// 三种数据库的条件 upsert:非空才覆盖,空值保留旧值。
// SQLite/Postgres 用 EXCLUDED.col 引用插入值;MySQL 用 VALUES(col)。
+62
View File
@@ -104,3 +104,65 @@ func TestExtraRepositoriesCRUD(t *testing.T) {
t.Fatal(err)
}
}
func TestItemsSyncFromRemoteReconcilesAndPreservesLocalSettings(t *testing.T) {
store, cleanup := newTestDB(t)
defer cleanup()
ctx := context.Background()
ok, err := store.Users.Create(ctx, "sync-user", "sync@example.com", "password")
if err != nil || !ok {
t.Fatalf("create test user: ok=%v err=%v", ok, err)
}
user, err := store.Users.GetByUsername(ctx, "sync-user")
if err != nil {
t.Fatal(err)
}
if err := store.Cookies.Save(ctx, "acc1", "unb=1", user.ID); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &ItemInfoRow{
CookieID: "acc1", ItemID: "existing", ItemTitle: "旧标题", ItemDescription: "本地描述", ItemPrice: "¥9.90",
}); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiSpec(ctx, "acc1", "existing", true); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiQuantity(ctx, "acc1", "existing", true); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &ItemInfoRow{CookieID: "acc1", ItemID: "deleted"}); err != nil {
t.Fatal(err)
}
result, err := store.Items.SyncFromRemote(ctx, "acc1", []ItemInfoRow{
{CookieID: "wrong-cookie", ItemID: "existing", ItemTitle: "新标题", ItemPrice: "¥19.90", IsMultiSpec: true},
{ItemID: "new", ItemTitle: "新商品", ItemPrice: "¥3.00"},
})
if err != nil {
t.Fatal(err)
}
if result.Saved != 2 || result.Deleted != 1 {
t.Fatalf("sync result=%+v, want saved=2 deleted=1", result)
}
items, err := store.Items.AllForCookie(ctx, "acc1")
if err != nil {
t.Fatal(err)
}
if len(items) != 2 {
t.Fatalf("items=%+v, want 2 rows", items)
}
item, err := store.Items.Get(ctx, "acc1", "existing")
if err != nil {
t.Fatal(err)
}
if item.ItemTitle != "新标题" || item.ItemPrice != "¥19.90" || item.ItemDescription != "本地描述" ||
!item.IsMultiSpec || !item.MultiQuantityDelivery {
t.Fatalf("existing item was not updated/preserved: %+v", item)
}
if _, err := store.Items.Get(ctx, "acc1", "deleted"); err != ErrNotFound {
t.Fatalf("deleted item still exists: err=%v", err)
}
}
+34 -6
View File
@@ -408,13 +408,21 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
if runtimeCookieChanged {
s.updateRunningCookie(r.Context(), req.CookieID, runtimeCookie)
}
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
syncResult, syncErr := s.syncSyncedItems(r.Context(), req.CookieID, res.Items)
if syncErr != nil {
if s.Logger != nil {
s.Logger.Error("同步商品到本地失败", "cookie_id", req.CookieID, "err", syncErr)
}
writeErr(w, http.StatusInternalServerError, "保存商品同步结果失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(saved) + " 件",
"total_count": len(res.Items),
"total_pages": res.TotalPages,
"saved_count": saved,
"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,
})
}
@@ -554,6 +562,26 @@ func (s *Server) saveSyncedItems(ctx context.Context, cookieID string, items []m
return saved
}
func (s *Server) syncSyncedItems(ctx context.Context, cookieID string, items []mtop.ItemListItem) (db.ItemSyncResult, error) {
rows := make([]db.ItemInfoRow, 0, len(items))
for _, item := range items {
priceText := item.PriceText
if priceText == "" {
priceText = item.Price
}
rows = append(rows, db.ItemInfoRow{
CookieID: cookieID,
ItemID: item.ID,
ItemTitle: item.Title,
ItemCategory: item.CategoryID,
ItemPrice: priceText,
ItemDetail: item.ItemDetail,
IsMultiSpec: item.IsMultiSpec,
})
}
return s.Store.Items.SyncFromRemote(ctx, cookieID, rows)
}
func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Client, cookies, cookieID string, items []mtop.ItemListItem) {
fetcher, ok := client.(mtop.ItemDetailFetcher)
if !ok {
+27 -9
View File
@@ -13,6 +13,7 @@ import (
"testing"
"time"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
)
@@ -373,6 +374,21 @@ func TestPublishItemStockPermissionMissing(t *testing.T) {
func TestSyncItemsFromAccountSuccess(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
ctx := context.Background()
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{
CookieID: "acc1", ItemID: "it-sync-1", ItemTitle: "旧标题", ItemDescription: "本地描述", ItemPrice: "¥9.90",
}); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiSpec(ctx, "acc1", "it-sync-1", true); err != nil {
t.Fatal(err)
}
if err := store.Items.SetMultiQuantity(ctx, "acc1", "it-sync-1", true); err != nil {
t.Fatal(err)
}
if err := store.Items.Upsert(ctx, &db.ItemInfoRow{CookieID: "acc1", ItemID: "it-removed", ItemTitle: "已删除商品"}); err != nil {
t.Fatal(err)
}
prev := srv.MTop
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
body := `{"ret":["SUCCESS::调用成功"],"data":{"cardList":[` +
@@ -402,16 +418,18 @@ func TestSyncItemsFromAccountSuccess(t *testing.T) {
if res["saved_count"] != float64(1) {
t.Fatalf("应保存1件商品: %+v", res)
}
// 验证 DB 已写入。
items, _ := store.Items.AllForCookie(context.Background(), "acc1")
found := false
for _, it := range items {
if it.ItemID == "it-sync-1" && it.ItemTitle == "同步商品A" {
found = true
}
if res["deleted_count"] != float64(1) {
t.Fatalf("应删除1件已下架商品: %+v", res)
}
if !found {
t.Fatalf("商品未保存: %+v", items)
// 验证 DB 已写入。
items, _ := store.Items.AllForCookie(ctx, "acc1")
if len(items) != 1 {
t.Fatalf("同步后本地应只保留1件商品: %+v", items)
}
item := items[0]
if item.ItemID != "it-sync-1" || item.ItemTitle != "同步商品A" || item.ItemPrice != "¥12.50" || item.ItemDescription != "本地描述" ||
!item.IsMultiSpec || !item.MultiQuantityDelivery {
t.Fatalf("线上商品更新或本地配置保留异常: %+v", item)
}
}