From 9adc77df73add7641774cb718fa3eaa288594efd Mon Sep 17 00:00:00 2001 From: Christ Date: Mon, 10 Aug 2026 11:21:35 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E5=95=86=E5=93=81=E5=90=8C=E6=AD=A5):=20?= =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=85=A8=E9=87=8F=E5=90=8C=E6=AD=A5=E5=88=A0?= =?UTF-8?q?=E9=99=A4=E4=B8=8E=E8=A7=84=E5=88=99=E7=94=9F=E5=91=BD=E5=91=A8?= =?UTF-8?q?=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cmd/init-admin/main.go | 89 ++++++++++++----- internal/db/automation.go | 39 ++++---- internal/db/automation_test.go | 8 ++ internal/db/delivery.go | 6 +- internal/db/extras.go | 50 ++++++++-- internal/db/extras_repository_test.go | 98 ++++++++++++++++++- internal/db/migrate_test.go | 9 +- .../00026_item_automation_soft_delete.sql | 11 +++ .../00026_item_automation_soft_delete.sql | 11 +++ .../00026_item_automation_soft_delete.sql | 11 +++ internal/db/multidb_test.go | 4 +- .../server/item_publish_batch_handlers.go | 2 +- internal/xianyu/mtop/items.go | 37 ++++++- internal/xianyu/mtop/items_test.go | 27 +++++ 14 files changed, 342 insertions(+), 60 deletions(-) create mode 100644 internal/db/migrations/mysql/00026_item_automation_soft_delete.sql create mode 100644 internal/db/migrations/postgres/00026_item_automation_soft_delete.sql create mode 100644 internal/db/migrations/sqlite/00026_item_automation_soft_delete.sql diff --git a/cmd/init-admin/main.go b/cmd/init-admin/main.go index fa2f597..257dbd1 100644 --- a/cmd/init-admin/main.go +++ b/cmd/init-admin/main.go @@ -55,78 +55,119 @@ func run(ctx context.Context, resolved string, reader *bufio.Reader, out io.Writ } if existing != nil { - fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username) - fmt.Fprint(out, "是否重置管理员密码?(y/N): ") + if _, err := fmt.Fprintf(out, "管理员用户 %s 已存在\n", existing.Username); err != nil { + return err + } + if _, err := fmt.Fprint(out, "是否重置管理员密码?(y/N): "); err != nil { + return err + } ans, _ := reader.ReadString('\n') if !strings.HasPrefix(strings.ToLower(strings.TrimSpace(ans)), "y") { - fmt.Fprintln(out, "跳过初始化") + if _, err := fmt.Fprintln(out, "跳过初始化"); err != nil { + return err + } return nil } - pw := promptPasswordTwice(reader, out) + pw, err := promptPasswordTwice(reader, out) + if err != nil { + return fmt.Errorf("读取密码失败: %w", err) + } if _, err := auth.InitAdmin(ctx, store, "", pw); err != nil { return fmt.Errorf("重置 admin 密码失败: %w", err) } - fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username) + if _, err := fmt.Fprintf(out, "重置完成:已更新 %s 的密码\n", existing.Username); err != nil { + return err + } return nil } - fmt.Fprintln(out, "=== 初始化管理员账号(CLI)===") - fmt.Fprint(out, "请输入管理员邮箱: ") + if _, err := fmt.Fprintln(out, "=== 初始化管理员账号(CLI)==="); err != nil { + return err + } + if _, err := fmt.Fprint(out, "请输入管理员邮箱: "); err != nil { + return err + } email, _ := reader.ReadString('\n') email = strings.TrimSpace(email) if email == "" { return errors.New("邮箱不能为空") } - pw := promptPasswordTwice(reader, out) + pw, err := promptPasswordTwice(reader, out) + if err != nil { + return fmt.Errorf("读取密码失败: %w", err) + } created, err := auth.InitAdmin(ctx, store, email, pw) if err != nil { return fmt.Errorf("创建 admin 用户失败:%w", err) } if created { - fmt.Fprintln(out, "初始化完成:已创建 admin 用户") + if _, err := fmt.Fprintln(out, "初始化完成:已创建 admin 用户"); err != nil { + return err + } } return nil } // promptPasswordTwice 两次输入密码(不回显)并校验一致性。 -func promptPasswordTwice(reader *bufio.Reader, out io.Writer) string { +func promptPasswordTwice(reader *bufio.Reader, out io.Writer) (string, error) { for { - p1 := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out) + p1, err := readPasswordNoEcho(reader, "请输入管理员密码(不回显): ", out) + if err != nil { + return "", err + } if p1 == "" { - fmt.Fprintln(out, "密码不能为空") + if _, err := fmt.Fprintln(out, "密码不能为空"); err != nil { + return "", err + } continue } - p2 := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out) + p2, err := readPasswordNoEcho(reader, "请再次输入管理员密码(不回显): ", out) + if err != nil { + return "", err + } if p1 != p2 { - fmt.Fprintln(out, "两次输入不一致,请重试") + if _, err := fmt.Fprintln(out, "两次输入不一致,请重试"); err != nil { + return "", err + } continue } - return p1 + return p1, nil } } // readPasswordNoEcho 不回显读取密码。非 TTY 时回退到普通读取(如管道), // 共用同一 bufio.Reader 避免缓冲吞掉后续输入。 -func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) string { - fmt.Fprint(out, prompt) +func readPasswordNoEcho(reader *bufio.Reader, prompt string, out io.Writer) (string, error) { + if _, err := fmt.Fprint(out, prompt); err != nil { + return "", err + } if term.IsTerminal(int(os.Stdin.Fd())) { b, err := term.ReadPassword(int(os.Stdin.Fd())) - fmt.Fprintln(out) if err != nil { - fatalf("读取密码失败: %v", err) + return "", err } - return strings.TrimSpace(string(b)) + if _, err := fmt.Fprintln(out); err != nil { + return "", err + } + return strings.TrimSpace(string(b)), nil } // 非 TTY 回退:共用传入的 reader。 - s, _ := reader.ReadString('\n') - fmt.Println() - return strings.TrimSpace(s) + s, err := reader.ReadString('\n') + if err != nil && !errors.Is(err, io.EOF) { + return "", err + } + if _, err := fmt.Fprintln(out); err != nil { + return "", err + } + return strings.TrimSpace(s), nil } func isNotFound(err error) bool { return errors.Is(err, db.ErrNotFound) } func fatalf(format string, a ...any) { - fmt.Fprintf(os.Stderr, format+"\n", a...) + if _, err := fmt.Fprintf(os.Stderr, format+"\n", a...); err != nil { + os.Exit(1) + } os.Exit(1) } diff --git a/internal/db/automation.go b/internal/db/automation.go index 355dce2..6282b9c 100644 --- a/internal/db/automation.go +++ b/internal/db/automation.go @@ -163,7 +163,7 @@ func (a *AutomationRules) ListForUser(ctx context.Context, userID int64) ([]Auto // ListPageForUser 按用户隔离筛选并分页查询自动化规则和动作。 func (a *AutomationRules) ListPageForUser(ctx context.Context, f AutomationRuleListFilter) ([]AutomationRule, int, error) { - where := []string{"r.user_id=?"} + where := []string{"r.user_id=?", "r.deleted_at IS NULL"} args := []any{f.UserID} if f.CookieID != "" { where = append(where, "r.cookie_id=?") @@ -190,7 +190,7 @@ func (a *AutomationRules) ListPageForUser(ctx context.Context, f AutomationRuleL if err := a.DB.QueryRowContext(ctx, ` SELECT COUNT(*) FROM automation_rules r - LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id + LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL WHERE `+whereSQL, args...).Scan(&total); err != nil { return nil, 0, err } @@ -205,7 +205,7 @@ SELECT COUNT(*) SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled, r.priority,r.config_json,r.created_at,r.updated_at FROM automation_rules r - LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id + LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL WHERE `+whereSQL+` ORDER BY r.created_at DESC,r.id DESC`+limitSQL, queryArgs...) if err != nil { @@ -257,8 +257,8 @@ func (a *AutomationRules) Get(ctx context.Context, ruleID int64) (*AutomationRul SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled, r.priority,r.config_json,r.created_at,r.updated_at FROM automation_rules r - LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id - WHERE r.id=?`, ruleID).Scan(&rule.ID, &rule.UserID, &rule.CookieID, &rule.ItemID, &rule.ItemTitle, + LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL + WHERE r.id=? AND r.deleted_at IS NULL`, ruleID).Scan(&rule.ID, &rule.UserID, &rule.CookieID, &rule.ItemID, &rule.ItemTitle, &rule.Name, &rule.TriggerType, &enabled, &rule.Priority, &rule.ConfigJSON, &rule.CreatedAt, &rule.UpdatedAt) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound @@ -276,12 +276,13 @@ func (a *AutomationRules) matchScope(ctx context.Context, cookieID, itemID, trig SELECT r.id,r.user_id,r.cookie_id,r.item_id,COALESCE(i.item_title,''),r.name,r.trigger_type,r.enabled, r.priority,r.config_json,r.created_at,r.updated_at FROM automation_rules r - LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id - WHERE r.enabled=1 - AND r.cookie_id=? - AND r.trigger_type=? + LEFT JOIN item_info i ON i.cookie_id=r.cookie_id AND i.item_id=r.item_id AND i.deleted_at IS NULL + WHERE r.deleted_at IS NULL + AND r.enabled=1 + AND r.cookie_id=? + AND r.trigger_type=? AND r.item_id=? - ORDER BY r.priority ASC, r.id ASC`, cookieID, triggerType, itemID) + ORDER BY r.priority ASC, r.id ASC`, cookieID, triggerType, itemID) if err != nil { return nil, err } @@ -332,7 +333,7 @@ func (a *AutomationRules) Update(ctx context.Context, userID, ruleID int64, in A res, err := tx.ExecContext(ctx, ` UPDATE automation_rules SET cookie_id=?,item_id=?,name=?,trigger_type=?,enabled=?,priority=?,config_json=?,updated_at=CURRENT_TIMESTAMP - WHERE id=? AND user_id=?`, + WHERE id=? AND user_id=? AND deleted_at IS NULL`, in.CookieID, in.ItemID, in.Name, in.TriggerType, boolToInt(in.Enabled), in.Priority, validJSON(in.ConfigJSON), ruleID, userID) if err != nil { return err @@ -351,10 +352,11 @@ UPDATE automation_rules return tx.Commit() } -// Delete 删除规则。 +// Delete 逻辑删除规则,保留动作和执行记录以便审计;逻辑删除后不再出现在规则列表和匹配结果中。 func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) error { - res, err := a.DB.ExecContext(ctx, `DELETE FROM automation_rules - WHERE id=? AND user_id=? AND NOT EXISTS ( + res, err := a.DB.ExecContext(ctx, `UPDATE automation_rules + SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP + WHERE id=? AND user_id=? AND deleted_at IS NULL AND NOT EXISTS ( SELECT 1 FROM automation_runs ar WHERE ar.rule_id=automation_rules.id AND (ar.status IN ('running','needs_review') OR (ar.status='failed' AND ar.sent_count=0 AND ar.attempt_count<3)))`, ruleID, userID) if err != nil { @@ -362,7 +364,7 @@ func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) erro } if n, _ := res.RowsAffected(); n == 0 { var exists int - if err := a.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_rules WHERE id=? AND user_id=?`, ruleID, userID).Scan(&exists); err != nil { + if err := a.DB.QueryRowContext(ctx, `SELECT COUNT(*) FROM automation_rules WHERE id=? AND user_id=? AND deleted_at IS NULL`, ruleID, userID).Scan(&exists); err != nil { return err } if exists > 0 { @@ -667,7 +669,7 @@ func (a *AutomationRules) ListIssues(ctx context.Context, userID int64) ([]Autom ar.action_cursor,ar.sent_count,ar.updated_at,ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0) FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id LEFT JOIN automation_rules r ON r.id=ar.rule_id - WHERE c.user_id=? AND ar.status='needs_review' ORDER BY ar.updated_at DESC,ar.id DESC`, userID) + WHERE c.user_id=? AND ar.status='needs_review' AND r.deleted_at IS NULL ORDER BY ar.updated_at DESC,ar.id DESC`, userID) if err != nil { return nil, nil, err } @@ -715,7 +717,7 @@ func (a *AutomationRules) ResolveRunIssue(ctx context.Context, userID, runID int err := a.DB.QueryRowContext(ctx, `SELECT ar.raw_event_json,ar.action_started,COALESCE(r.enabled,0),ar.sent_count,ar.error_message FROM automation_runs ar JOIN cookies c ON c.id=ar.cookie_id LEFT JOIN automation_rules r ON r.id=ar.rule_id - WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=?`, runID, userID). + WHERE ar.id=? AND ar.status='needs_review' AND c.user_id=? AND r.deleted_at IS NULL`, runID, userID). Scan(&rawEventJSON, &actionStarted, &ruleEnabled, &sentCount, &errorMessage) if errors.Is(err, sql.ErrNoRows) { return ErrNotFound @@ -979,7 +981,8 @@ SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_stat AND COALESCE(o.chat_id,'')<>'' AND EXISTS (SELECT 1 FROM automation_rules r WHERE r.cookie_id=o.cookie_id AND r.trigger_type='review_missing_timeout' - AND r.enabled=1 AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+` + AND r.deleted_at IS NULL AND r.enabled=1 + AND (r.item_id=o.item_id OR r.item_id=''))`+cursorSQL+` ORDER BY o.order_id ASC LIMIT ?`, args...) if err != nil { diff --git a/internal/db/automation_test.go b/internal/db/automation_test.go index c45db1d..57e3252 100644 --- a/internal/db/automation_test.go +++ b/internal/db/automation_test.go @@ -204,6 +204,14 @@ func TestAutomation_UpdateDelete(t *testing.T) { if len(rules) != 0 { t.Fatalf("Delete 后 len=%d want 0", len(rules)) } + var deletedAt string + var enabled int + if err := s.DB.QueryRowContext(ctx, `SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&deletedAt, &enabled); err != nil { + t.Fatalf("逻辑删除后规则原始行不存在: %v", err) + } + if deletedAt == "" || enabled != 0 { + t.Fatalf("规则未逻辑删除并禁用: deleted_at=%q enabled=%d", deletedAt, enabled) + } // 重复 Delete → ErrNotFound。 if err := s.Automation.Delete(ctx, uid, ruleID); !errors.Is(err, ErrNotFound) { t.Fatalf("重复 Delete 应 ErrNotFound, got %v", err) diff --git a/internal/db/delivery.go b/internal/db/delivery.go index 62e34ea..1fb5c7f 100644 --- a/internal/db/delivery.go +++ b/internal/db/delivery.go @@ -53,7 +53,7 @@ func (i *Items) Get(ctx context.Context, cookieID, itemID string) (*ItemInfo, er err := i.DB.QueryRowContext(ctx, `SELECT id, cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, is_multi_spec, multi_quantity_delivery - FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan( + FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan( &it.ID, &it.CookieID, &it.ItemID, &title, &desc, &cat, &price, &detail, &isMulti, &multiQty) if err != nil { @@ -75,7 +75,7 @@ func (i *Items) Get(ctx context.Context, cookieID, itemID string) (*ItemInfo, er // IsMultiSpec 是否多规格商品。 func (i *Items) IsMultiSpec(ctx context.Context, cookieID, itemID string) bool { var v int - err := i.DB.QueryRowContext(ctx, `SELECT is_multi_spec FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(&v) + err := i.DB.QueryRowContext(ctx, `SELECT is_multi_spec FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(&v) if err != nil { return false } @@ -85,7 +85,7 @@ func (i *Items) IsMultiSpec(ctx context.Context, cookieID, itemID string) bool { // MultiQuantityDelivery 是否开启多数量发货。 func (i *Items) MultiQuantityDelivery(ctx context.Context, cookieID, itemID string) bool { var v int - err := i.DB.QueryRowContext(ctx, `SELECT multi_quantity_delivery FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID).Scan(&v) + err := i.DB.QueryRowContext(ctx, `SELECT multi_quantity_delivery FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(&v) if err != nil { return false } diff --git a/internal/db/extras.go b/internal/db/extras.go index 75c23d0..7cf7461 100644 --- a/internal/db/extras.go +++ b/internal/db/extras.go @@ -533,7 +533,7 @@ func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRo `SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''), COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''), is_multi_spec, COALESCE(multi_quantity_delivery,0) - FROM item_info WHERE cookie_id=? ORDER BY id DESC`, cookieID) + FROM item_info WHERE cookie_id=? AND deleted_at IS NULL ORDER BY id DESC`, cookieID) if err != nil { return nil, err } @@ -567,6 +567,7 @@ func (i *Items) Upsert(ctx context.Context, r *ItemInfoRow) error { "item_detail": "EXCLUDED.item_detail", "is_multi_spec": "EXCLUDED.is_multi_spec", "multi_quantity_delivery": "EXCLUDED.multi_quantity_delivery", + "deleted_at": "NULL", "updated_at": "CURRENT_TIMESTAMP", }), r.CookieID, r.ItemID, nullable(r.ItemTitle), nullable(r.ItemDescription), @@ -588,7 +589,7 @@ func (i *Items) UpsertBasicTx(ctx context.Context, tx *sql.Tx, r *ItemInfoRow) e // // 远端列表只提供商品基础信息,因此保留本地的描述和发货配置;基础字段 // (标题、分类、价格、详情)由远端非空值覆盖。整个 reconcile 在一个事务内 -// 完成,只有在全部远端商品写入成功后,才会删除本次全集中不存在的本地商品。 +// 完成,只有在全部远端商品写入成功后,才会逻辑删除本次全集中不存在的本地商品及其商品级自动化规则。 func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []ItemInfoRow) (ItemSyncResult, error) { cookieID = strings.TrimSpace(cookieID) if cookieID == "" { @@ -633,7 +634,7 @@ func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []Item args := make([]any, 0, len(remoteIDs)+1) args = append(args, cookieID) - deleteQuery := `DELETE FROM item_info WHERE cookie_id=?` + deleteQuery := `UPDATE item_info SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND deleted_at IS NULL` if len(remoteIDs) > 0 { placeholders := make([]string, 0, len(remoteIDs)) for itemID := range remoteIDs { @@ -650,6 +651,23 @@ func (i *Items) SyncFromRemote(ctx context.Context, cookieID string, rows []Item if err != nil { return rollback(err) } + + ruleArgs := make([]any, 0, len(remoteIDs)+1) + ruleArgs = append(ruleArgs, cookieID) + ruleQuery := `UPDATE automation_rules + SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP + WHERE cookie_id=? AND item_id<>'' AND deleted_at IS NULL` + if len(remoteIDs) > 0 { + placeholders := make([]string, 0, len(remoteIDs)) + for itemID := range remoteIDs { + placeholders = append(placeholders, "?") + ruleArgs = append(ruleArgs, itemID) + } + ruleQuery += ` AND item_id NOT IN (` + strings.Join(placeholders, ",") + ")" + } + if _, err := tx.ExecContext(ctx, ruleQuery, ruleArgs...); err != nil { + return rollback(err) + } if err := tx.Commit(); err != nil { return ItemSyncResult{}, err } @@ -668,6 +686,7 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo item_category=CASE WHEN VALUES(item_category) IS NOT NULL AND VALUES(item_category) != '' THEN VALUES(item_category) ELSE item_info.item_category END, item_price=CASE WHEN VALUES(item_price) IS NOT NULL AND VALUES(item_price) != '' THEN VALUES(item_price) ELSE item_info.item_price END, item_detail=CASE WHEN VALUES(item_detail) IS NOT NULL AND VALUES(item_detail) != '' THEN VALUES(item_detail) ELSE item_info.item_detail END, + deleted_at=NULL, updated_at=CURRENT_TIMESTAMP` default: conflictClause = ` ON CONFLICT(cookie_id, item_id) DO UPDATE SET @@ -676,6 +695,7 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo item_category=CASE WHEN EXCLUDED.item_category IS NOT NULL AND EXCLUDED.item_category != '' THEN EXCLUDED.item_category ELSE item_info.item_category END, item_price=CASE WHEN EXCLUDED.item_price IS NOT NULL AND EXCLUDED.item_price != '' THEN EXCLUDED.item_price ELSE item_info.item_price END, item_detail=CASE WHEN EXCLUDED.item_detail IS NOT NULL AND EXCLUDED.item_detail != '' THEN EXCLUDED.item_detail ELSE item_info.item_detail END, + deleted_at=NULL, updated_at=CURRENT_TIMESTAMP` } _, err := execer.ExecContext(ctx, @@ -687,16 +707,30 @@ func (i *Items) upsertBasic(ctx context.Context, execer sqlExecer, r *ItemInfoRo return err } -// Delete 删除商品。 +// Delete 逻辑删除商品及其商品级自动化规则,保留历史数据以便审计和恢复。 func (i *Items) Delete(ctx context.Context, cookieID, itemID string) error { - _, err := i.DB.ExecContext(ctx, `DELETE FROM item_info WHERE cookie_id=? AND item_id=?`, cookieID, itemID) - return err + tx, err := i.DB.BeginTx(ctx, nil) + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.ExecContext(ctx, `UPDATE item_info + SET deleted_at=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP + WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil { + return err + } + if _, err := tx.ExecContext(ctx, `UPDATE automation_rules + SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP + WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID); err != nil { + return err + } + return tx.Commit() } // SetMultiSpec 设置多规格开关。 func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bool) error { _, err := i.DB.ExecContext(ctx, - `UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=?`, + `UPDATE item_info SET is_multi_spec=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, boolToInt(on), cookieID, itemID) return err } @@ -704,7 +738,7 @@ func (i *Items) SetMultiSpec(ctx context.Context, cookieID, itemID string, on bo // SetMultiQuantity 设置多数量发货开关。 func (i *Items) SetMultiQuantity(ctx context.Context, cookieID, itemID string, on bool) error { _, err := i.DB.ExecContext(ctx, - `UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=?`, + `UPDATE item_info SET multi_quantity_delivery=?, updated_at=CURRENT_TIMESTAMP WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, boolToInt(on), cookieID, itemID) return err } diff --git a/internal/db/extras_repository_test.go b/internal/db/extras_repository_test.go index 86e0274..e50b81f 100644 --- a/internal/db/extras_repository_test.go +++ b/internal/db/extras_repository_test.go @@ -2,6 +2,7 @@ package db import ( "context" + "database/sql" "testing" ) @@ -135,6 +136,14 @@ func TestItemsSyncFromRemoteReconcilesAndPreservesLocalSettings(t *testing.T) { if err := store.Items.Upsert(ctx, &ItemInfoRow{CookieID: "acc1", ItemID: "deleted"}); err != nil { t.Fatal(err) } + ruleID, err := store.Automation.Create(ctx, AutomationRuleInput{ + UserID: user.ID, CookieID: "acc1", ItemID: "deleted", Name: "删除商品规则", + TriggerType: "paid", Enabled: true, Priority: 100, + Actions: []AutomationActionInput{{ActionType: "send_msg", MessageTemplate: "hello", Enabled: true, SortOrder: 1}}, + }) + if err != nil { + t.Fatal(err) + } result, err := store.Items.SyncFromRemote(ctx, "acc1", []ItemInfoRow{ {CookieID: "wrong-cookie", ItemID: "existing", ItemTitle: "新标题", ItemPrice: "¥19.90", IsMultiSpec: true}, @@ -163,6 +172,93 @@ func TestItemsSyncFromRemoteReconcilesAndPreservesLocalSettings(t *testing.T) { 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) + t.Fatalf("deleted item should be hidden from active lookup: err=%v", err) + } + var itemDeletedAt sql.NullString + if err := store.DB.QueryRowContext(ctx, + `SELECT deleted_at FROM item_info WHERE cookie_id=? AND item_id=?`, "acc1", "deleted").Scan(&itemDeletedAt); err != nil { + t.Fatalf("商品逻辑删除后原始行不存在: %v", err) + } + if !itemDeletedAt.Valid || itemDeletedAt.String == "" { + t.Fatalf("商品 deleted_at 未写入: %#v", itemDeletedAt) + } + var ruleDeletedAt sql.NullString + var ruleEnabled int + if err := store.DB.QueryRowContext(ctx, + `SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&ruleDeletedAt, &ruleEnabled); err != nil { + t.Fatalf("关联规则逻辑删除后原始行不存在: %v", err) + } + if !ruleDeletedAt.Valid || ruleDeletedAt.String == "" || ruleEnabled != 0 { + t.Fatalf("关联规则未逻辑删除并禁用: deleted_at=%#v enabled=%d", ruleDeletedAt, ruleEnabled) + } + rules, err := store.Automation.ListForUser(ctx, user.ID) + if err != nil { + t.Fatal(err) + } + if len(rules) != 0 { + t.Fatalf("已删除商品的规则不应出现在管理列表: %#v", rules) + } + matched, err := store.Automation.Match(ctx, "acc1", "deleted", "paid") + if err != nil { + t.Fatal(err) + } + if len(matched) != 0 { + t.Fatalf("已删除商品的规则不应再匹配: %#v", matched) + } + + // 商品再次出现在远端时只恢复商品,不自动恢复已删除规则,避免旧规则误复活。 + if _, err := store.Items.SyncFromRemote(ctx, "acc1", []ItemInfoRow{{ItemID: "existing"}, {ItemID: "deleted"}}); err != nil { + t.Fatal(err) + } + if _, err := store.Items.Get(ctx, "acc1", "deleted"); err != nil { + t.Fatalf("商品重新同步后应恢复商品记录: %v", err) + } + rules, err = store.Automation.ListForUser(ctx, user.ID) + if err != nil { + t.Fatal(err) + } + if len(rules) != 0 { + t.Fatalf("商品恢复后不应自动恢复旧规则: %#v", rules) + } +} + +func TestItemsDeleteSoftDeletesRelatedAutomationRule(t *testing.T) { + store, cleanup := newTestDB(t) + defer cleanup() + ctx := context.Background() + if ok, err := store.Users.Create(ctx, "item-delete-user", "item-delete@example.com", "password"); err != nil || !ok { + t.Fatalf("create test user: ok=%v err=%v", ok, err) + } + user, err := store.Users.GetByUsername(ctx, "item-delete-user") + if err != nil { + t.Fatal(err) + } + if err := store.Cookies.Save(ctx, "item-delete-cookie", "unb=1", user.ID); err != nil { + t.Fatal(err) + } + if err := store.Items.Upsert(ctx, &ItemInfoRow{CookieID: "item-delete-cookie", ItemID: "item-1", ItemTitle: "待删除商品"}); err != nil { + t.Fatal(err) + } + ruleID, err := store.Automation.Create(ctx, AutomationRuleInput{ + UserID: user.ID, CookieID: "item-delete-cookie", ItemID: "item-1", Name: "商品规则", + TriggerType: "paid", Enabled: true, Priority: 100, + Actions: []AutomationActionInput{{ActionType: "send_msg", MessageTemplate: "hello", Enabled: true, SortOrder: 1}}, + }) + if err != nil { + t.Fatal(err) + } + if err := store.Items.Delete(ctx, "item-delete-cookie", "item-1"); err != nil { + t.Fatal(err) + } + var itemDeletedAt, ruleDeletedAt string + var ruleEnabled int + if err := store.DB.QueryRowContext(ctx, `SELECT deleted_at FROM item_info WHERE cookie_id=? AND item_id=?`, "item-delete-cookie", "item-1").Scan(&itemDeletedAt); err != nil { + t.Fatalf("商品行未保留: %v", err) + } + if err := store.DB.QueryRowContext(ctx, `SELECT deleted_at, enabled FROM automation_rules WHERE id=?`, ruleID).Scan(&ruleDeletedAt, &ruleEnabled); err != nil { + t.Fatalf("规则行未保留: %v", err) + } + if itemDeletedAt == "" || ruleDeletedAt == "" || ruleEnabled != 0 { + t.Fatalf("商品和规则未完成逻辑删除: item_deleted_at=%q rule_deleted_at=%q enabled=%d", itemDeletedAt, ruleDeletedAt, ruleEnabled) } } diff --git a/internal/db/migrate_test.go b/internal/db/migrate_test.go index c0d1752..94a3049 100644 --- a/internal/db/migrate_test.go +++ b/internal/db/migrate_test.go @@ -33,6 +33,8 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) { {"cards", "delay_seconds"}, {"keywords", "item_id"}, {"item_info", "multi_quantity_delivery"}, + {"item_info", "deleted_at"}, + {"automation_rules", "deleted_at"}, {"default_replies", "reply_once"}, {"default_reply_records", "status"}, {"default_reply_records", "text_sent"}, @@ -125,8 +127,8 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) { t.Fatalf("goose dialect: %v", err) } goose.SetBaseFS(migrationsFS) - // 依次回滚最新版本到 14,再整体升级。 - for i := 0; i < 12; i++ { + // 依次回滚最新版本到 13,再整体升级。 + for i := 0; i < 13; i++ { if err := goose.Down(d, "migrations/sqlite"); err != nil { t.Fatalf("down migration #%d: %v", i+1, err) } @@ -146,6 +148,9 @@ func TestLatestMigrationsDownUpSQLite(t *testing.T) { if columnExists(t, d, "item_publish_batch_rows", "category_json") { t.Fatal("item_publish_batch_rows.category_json should be removed after migration 23 down") } + if columnExists(t, d, "item_info", "deleted_at") || columnExists(t, d, "automation_rules", "deleted_at") { + t.Fatal("soft-delete columns should be removed after migration 26 down") + } for _, table := range []string{"account_task_settings", "account_task_runs", "chat_sessions", "chat_messages"} { if tableExists(t, d, table) { t.Fatalf("table should be removed after migration 24 down: %s", table) diff --git a/internal/db/migrations/mysql/00026_item_automation_soft_delete.sql b/internal/db/migrations/mysql/00026_item_automation_soft_delete.sql new file mode 100644 index 0000000..0a3f980 --- /dev/null +++ b/internal/db/migrations/mysql/00026_item_automation_soft_delete.sql @@ -0,0 +1,11 @@ +-- +goose Up +ALTER TABLE item_info ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL; +ALTER TABLE automation_rules ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL; +CREATE INDEX idx_item_info_active ON item_info(cookie_id, deleted_at); +CREATE INDEX idx_automation_rules_active_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, deleted_at); + +-- +goose Down +DROP INDEX idx_automation_rules_active_match ON automation_rules; +DROP INDEX idx_item_info_active ON item_info; +ALTER TABLE automation_rules DROP COLUMN deleted_at; +ALTER TABLE item_info DROP COLUMN deleted_at; diff --git a/internal/db/migrations/postgres/00026_item_automation_soft_delete.sql b/internal/db/migrations/postgres/00026_item_automation_soft_delete.sql new file mode 100644 index 0000000..34256f2 --- /dev/null +++ b/internal/db/migrations/postgres/00026_item_automation_soft_delete.sql @@ -0,0 +1,11 @@ +-- +goose Up +ALTER TABLE item_info ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL; +ALTER TABLE automation_rules ADD COLUMN deleted_at TIMESTAMP NULL DEFAULT NULL; +CREATE INDEX idx_item_info_active ON item_info(cookie_id, deleted_at); +CREATE INDEX idx_automation_rules_active_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, deleted_at); + +-- +goose Down +DROP INDEX IF EXISTS idx_automation_rules_active_match; +DROP INDEX IF EXISTS idx_item_info_active; +ALTER TABLE automation_rules DROP COLUMN deleted_at; +ALTER TABLE item_info DROP COLUMN deleted_at; diff --git a/internal/db/migrations/sqlite/00026_item_automation_soft_delete.sql b/internal/db/migrations/sqlite/00026_item_automation_soft_delete.sql new file mode 100644 index 0000000..4e0513a --- /dev/null +++ b/internal/db/migrations/sqlite/00026_item_automation_soft_delete.sql @@ -0,0 +1,11 @@ +-- +goose Up +ALTER TABLE item_info ADD COLUMN deleted_at TIMESTAMP NULL; +ALTER TABLE automation_rules ADD COLUMN deleted_at TIMESTAMP NULL; +CREATE INDEX idx_item_info_active ON item_info(cookie_id, deleted_at); +CREATE INDEX idx_automation_rules_active_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, deleted_at); + +-- +goose Down +DROP INDEX IF EXISTS idx_automation_rules_active_match; +DROP INDEX IF EXISTS idx_item_info_active; +ALTER TABLE automation_rules DROP COLUMN deleted_at; +ALTER TABLE item_info DROP COLUMN deleted_at; diff --git a/internal/db/multidb_test.go b/internal/db/multidb_test.go index 7fe7e94..b6b57ae 100644 --- a/internal/db/multidb_test.go +++ b/internal/db/multidb_test.go @@ -771,7 +771,7 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) { t.Fatalf("set goose dialect: %v", err) } goose.SetBaseFS(migrationsFS) - for i := 0; i < 12; i++ { + for i := 0; i < 13; i++ { if err := goose.Down(tg.store.DB, "migrations/"+subdir); err != nil { t.Fatalf("migration down #%d: %v", i+1, err) } @@ -816,6 +816,8 @@ func TestMultiDB_LatestMigrationsDownUp(t *testing.T) { {"automation_runs", "action_started"}, {"account_tokens", "cookie_fingerprint"}, {"item_publish_batch_rows", "category_json"}, + {"item_info", "deleted_at"}, + {"automation_rules", "deleted_at"}, {"account_task_settings", "auto_rate_enabled"}, {"account_task_runs", "run_key"}, {"chat_sessions", "unread_count"}, diff --git a/internal/server/item_publish_batch_handlers.go b/internal/server/item_publish_batch_handlers.go index 7e0f1b5..18c8d85 100644 --- a/internal/server/item_publish_batch_handlers.go +++ b/internal/server/item_publish_batch_handlers.go @@ -1099,7 +1099,7 @@ func (s *Server) ensurePublishAutomationRule(ctx context.Context, input db.Autom var exists bool err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS( SELECT 1 FROM automation_rules - WHERE user_id=? AND cookie_id=? AND item_id=? AND trigger_type=? AND name=? + WHERE user_id=? AND cookie_id=? AND item_id=? AND trigger_type=? AND name=? AND deleted_at IS NULL )`, input.UserID, input.CookieID, input.ItemID, input.TriggerType, input.Name).Scan(&exists) if err != nil { return err diff --git a/internal/xianyu/mtop/items.go b/internal/xianyu/mtop/items.go index de08bc1..566c1bb 100644 --- a/internal/xianyu/mtop/items.go +++ b/internal/xianyu/mtop/items.go @@ -111,11 +111,14 @@ func (c *ClientImpl) fetchItemsPageOnce(ctx context.Context, cookiesStr string, } items := parseItemList(decoded.Data) + totalCount, totalPages := itemListPagination(decoded.Data, pageNumber, pageSize) return &ItemListResult{ Items: items, PageNumber: pageNumber, PageSize: pageSize, CurrentCount: len(items), + TotalCount: totalCount, + TotalPages: totalPages, SavedCountHint: len(items), UpdatedCookies: updated, }, decoded.Ret, updated, nil @@ -131,6 +134,7 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS currentCookies, _, _ = session.State() } page := 1 + fetchedPages := 0 var all []ItemListItem for maxPages <= 0 || page <= maxPages { res, err := c.FetchItemsPage(ctx, currentCookies, page, pageSize) @@ -139,7 +143,11 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS } currentCookies = res.UpdatedCookies all = append(all, res.Items...) - if len(res.Items) < pageSize { + fetchedPages = page + if res.TotalPages > 0 && page >= res.TotalPages { + break + } + if res.TotalPages <= 0 && len(res.Items) < pageSize { break } page++ @@ -153,12 +161,37 @@ func (c *ClientImpl) FetchAllItems(ctx context.Context, cookiesStr string, pageS PageSize: pageSize, CurrentCount: len(all), TotalCount: len(all), - TotalPages: page, + TotalPages: fetchedPages, SavedCountHint: len(all), UpdatedCookies: currentCookies, }, nil } +func itemListPagination(data map[string]any, pageNumber, pageSize int) (totalCount, totalPages int) { + for _, key := range []string{"totalCount", "total_count", "total"} { + if value := mtopInt(data[key]); value > 0 { + totalCount = value + break + } + } + for _, key := range []string{"pageCount", "page_count", "totalPages", "total_pages"} { + if value := mtopInt(data[key]); value > 0 { + totalPages = value + break + } + } + if totalPages == 0 && totalCount > 0 && pageSize > 0 { + totalPages = (totalCount + pageSize - 1) / pageSize + } + if totalCount == 0 && totalPages > 0 && pageSize > 0 { + totalCount = totalPages * pageSize + } + if totalPages > 0 && pageNumber > totalPages { + totalPages = pageNumber + } + return totalCount, totalPages +} + func buildItemListQuery(t, sign string) string { parts := [][2]string{ {"jsv", "2.7.2"}, diff --git a/internal/xianyu/mtop/items_test.go b/internal/xianyu/mtop/items_test.go index d1225fd..d6d7a83 100644 --- a/internal/xianyu/mtop/items_test.go +++ b/internal/xianyu/mtop/items_test.go @@ -227,6 +227,33 @@ func TestFetchAllItemsMultiPage(t *testing.T) { } } +func TestFetchAllItemsUsesRemotePageCountWhenPageIsShort(t *testing.T) { + var pageReqs atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + page := pageReqs.Add(1) + if page == 1 { + fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"pageCount":2,"cardList":[ + {"cardData":{"title":"A","detailParams":{"itemId":"i1"}}} + ]}}`) + return + } + fmt.Fprint(w, `{"ret":["SUCCESS::调用成功"],"data":{"pageCount":2,"cardList":[ + {"cardData":{"title":"B","detailParams":{"itemId":"i2"}}} + ]}}`) + })) + defer server.Close() + + rt := &rewriteTransport{base: server.Client().Transport, target: server.URL} + client := &ClientImpl{HTTPClient: &http.Client{Transport: rt, Timeout: 5 * time.Second}} + res, err := client.FetchAllItems(context.Background(), consignCookies, 20, 10) + if err != nil { + t.Fatalf("err=%v", err) + } + if len(res.Items) != 2 || pageReqs.Load() != 2 { + t.Fatalf("items=%d pageReqs=%d want 2/2", len(res.Items), pageReqs.Load()) + } +} + // TestFetchAllItemsMaxPagesCap: maxPages 限制最大页数。 func TestFetchAllItemsMaxPagesCap(t *testing.T) { var pageReqs atomic.Int32