refactor: automation 中心落地 + 清理 delivery_rules/SystemMessage 死代码

把卡密自动发货从 engine.DeliveryService 收敛到统一的 automation.Center:
WS 事件/计划任务/手动触发统一为 Task,trigger_key 持久化防重,付款发货、
评价赠品、超时求评价共用一套规则+动作编排。新增 internal/automation 包、
db.AutomationRules repository、00007 迁移。

同步删除被取代的并行死系统:
- engine.DeliveryService + delivery_test.go(已无引用)
- db.DeliveryRules/DeliveryRule + 3 个 Match 方法(生产零调用)
- card_handlers 的 /delivery-rules CRUD(前端早已只走 automation-rules)
- engine.SystemMessage + extractSystemMessage(dispatch 不再单独路由 message["3"])
- store.DeliveryRules 字段、Cards.IncrementDeliveryTimes
- 00008 迁移 DROP delivery_rules/delivery_rule_variants + email_verifications/
  captcha_codes/ai_item_cache/risk_control_logs + publish 批次 3 个死列
- isAPIPath 清理 ~15 个未挂载的前缀,stub_handlers.go 内联删除
- vite.config 删 /delivery-rules proxy

其它:orders.Upsert 注释改为诚实描述(version 列不参与并发控制);
dispatch.cleanupDedupLocked 用 sort.Slice 取代 O(n²) 选择排序;
删自定义 min 用内置;deliveryRuleItemOwned 改名 itemOwnedByUser。

Co-Authored-By: Claude Opus 4.8 <[email protected]>
This commit is contained in:
ChristandClaude Opus 4.8 committed 2026-06-30 21:40:15 +08:00
1 parent 5546494577
commit 57f9090dd2
29 files changed
+2469 -2382

No files matched your search

+386
View File
@@ -0,0 +1,386 @@
package db
import (
"context"
"database/sql"
"encoding/json"
"fmt"
)
// AutomationRules 管理自动化规则、动作和执行记录。
//
// 自动化中心不区分触发来源:WS 系统事件、计划任务、后台手动触发都通过
// trigger_type + action 编排表达;真正的防重由 automation_runs.trigger_key 保证。
type AutomationRules struct{ DB *sql.DB }
// AutomationRule 是一条自动化规则。规则只描述“什么时候、对哪个商品生效”,
// 具体做什么放在 AutomationAction 中,便于组合付款发货、评价赠品、求评价等流程。
type AutomationRule struct {
ID int64
UserID int64
CookieID string
ItemID string
ItemTitle string
Name string
TriggerType string
Enabled bool
Priority int
ConfigJSON string
CreatedAt string
UpdatedAt string
Actions []AutomationAction
}
// AutomationAction 是规则下的一步动作。
type AutomationAction struct {
ID int64
RuleID int64
ActionType string
CardID int64
CardName string
DeliveryCount int
MessageTemplate string
DelaySeconds int
ConfigJSON string
Enabled bool
SortOrder int
}
// AutomationRun 是一次自动化执行记录。trigger_key 是持久化防重键。
type AutomationRun struct {
ID int64
RuleID int64
CookieID string
ItemID string
OrderID string
BuyerID string
ChatID string
TriggerType string
TriggerKey string
Status string
SentCount int
ErrorMessage string
RawEventJSON string
CreatedAt string
UpdatedAt string
}
// AutomationRuleInput 是创建/更新规则的输入。
type AutomationRuleInput struct {
UserID int64
CookieID string
ItemID string
Name string
TriggerType string
Enabled bool
Priority int
ConfigJSON string
Actions []AutomationActionInput
}
// AutomationActionInput 是创建动作的输入。
type AutomationActionInput struct {
ActionType string
CardID int64
DeliveryCount int
MessageTemplate string
DelaySeconds int
ConfigJSON string
Enabled bool
SortOrder int
}
// ListForUser 返回用户下全部自动化规则和动作。
func (a *AutomationRules) ListForUser(ctx context.Context, userID int64) ([]AutomationRule, error) {
rows, err := a.DB.QueryContext(ctx, `
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,COALESCE(r.created_at,''),COALESCE(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.user_id=?
ORDER BY r.created_at DESC,r.id DESC`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []AutomationRule{}
for rows.Next() {
var r AutomationRule
var enabled int
if err := rows.Scan(&r.ID, &r.UserID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.Name, &r.TriggerType,
&enabled, &r.Priority, &r.ConfigJSON, &r.CreatedAt, &r.UpdatedAt); err != nil {
return nil, err
}
r.Enabled = enabled != 0
acts, err := a.Actions(ctx, r.ID)
if err != nil {
return nil, err
}
r.Actions = acts
out = append(out, r)
}
return out, rows.Err()
}
// Match 查询某事件可触发的规则。商品精确规则优先,其次允许 item_id 为空的账号级规则。
func (a *AutomationRules) Match(ctx context.Context, cookieID, itemID, triggerType string) ([]AutomationRule, error) {
rows, err := a.DB.QueryContext(ctx, `
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,COALESCE(r.created_at,''),COALESCE(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=?
AND (r.item_id=? OR r.item_id='')
ORDER BY CASE WHEN r.item_id=? THEN 0 ELSE 1 END, r.priority ASC, r.id ASC`,
cookieID, triggerType, itemID, itemID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []AutomationRule{}
for rows.Next() {
var r AutomationRule
var enabled int
if err := rows.Scan(&r.ID, &r.UserID, &r.CookieID, &r.ItemID, &r.ItemTitle, &r.Name, &r.TriggerType,
&enabled, &r.Priority, &r.ConfigJSON, &r.CreatedAt, &r.UpdatedAt); err != nil {
return nil, err
}
r.Enabled = enabled != 0
acts, err := a.Actions(ctx, r.ID)
if err != nil {
return nil, err
}
r.Actions = acts
out = append(out, r)
}
return out, rows.Err()
}
// Create 创建规则和动作。
func (a *AutomationRules) Create(ctx context.Context, in AutomationRuleInput) (int64, error) {
tx, err := a.DB.BeginTx(ctx, nil)
if err != nil {
return 0, err
}
defer tx.Rollback()
id, err := createAutomationRuleTx(ctx, tx, in)
if err != nil {
return 0, err
}
if err := tx.Commit(); err != nil {
return 0, err
}
return id, nil
}
// Update 替换规则和动作。动作采用删除重建,避免前端携带展示字段造成局部更新不一致。
func (a *AutomationRules) Update(ctx context.Context, userID, ruleID int64, in AutomationRuleInput) error {
tx, err := a.DB.BeginTx(ctx, nil)
if err != nil {
return err
}
defer tx.Rollback()
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=?`,
in.CookieID, in.ItemID, in.Name, in.TriggerType, boolToInt(in.Enabled), in.Priority, validJSON(in.ConfigJSON), ruleID, userID)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
if _, err := tx.ExecContext(ctx, `DELETE FROM automation_rule_actions WHERE rule_id=?`, ruleID); err != nil {
return err
}
for _, act := range in.Actions {
if err := insertAutomationActionTx(ctx, tx, ruleID, act); err != nil {
return err
}
}
return tx.Commit()
}
// 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=?`, ruleID, userID)
if err != nil {
return err
}
if n, _ := res.RowsAffected(); n == 0 {
return ErrNotFound
}
return nil
}
// Actions 返回规则动作。
func (a *AutomationRules) Actions(ctx context.Context, ruleID int64) ([]AutomationAction, error) {
rows, err := a.DB.QueryContext(ctx, `
SELECT a.id,a.rule_id,a.action_type,COALESCE(a.card_id,0),COALESCE(c.name,''),a.delivery_count,
a.message_template,a.delay_seconds,a.config_json,a.enabled,a.sort_order
FROM automation_rule_actions a
LEFT JOIN cards c ON c.id=a.card_id
WHERE a.rule_id=?
ORDER BY a.sort_order ASC,a.id ASC`, ruleID)
if err != nil {
return nil, err
}
defer rows.Close()
out := []AutomationAction{}
for rows.Next() {
var act AutomationAction
var enabled int
if err := rows.Scan(&act.ID, &act.RuleID, &act.ActionType, &act.CardID, &act.CardName,
&act.DeliveryCount, &act.MessageTemplate, &act.DelaySeconds, &act.ConfigJSON, &enabled,
&act.SortOrder); err != nil {
return nil, err
}
act.Enabled = enabled != 0
out = append(out, act)
}
return out, rows.Err()
}
// TryStartRun 以 UNIQUE(rule_id, trigger_key) 作为持久化防重。
// 返回 started=false 表示该规则对该触发已执行或正在执行,调用方应直接跳过。
func (a *AutomationRules) TryStartRun(ctx context.Context, run AutomationRun) (int64, bool, error) {
res, err := a.DB.ExecContext(ctx, `
INSERT OR IGNORE INTO automation_runs
(rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigger_key,status,raw_event_json)
VALUES (?,?,?,?,?,?,?,?,?,?)`,
run.RuleID, run.CookieID, run.ItemID, run.OrderID, run.BuyerID, run.ChatID, run.TriggerType,
run.TriggerKey, "running", validJSON(run.RawEventJSON))
if err != nil {
return 0, false, err
}
if n, _ := res.RowsAffected(); n == 0 {
return 0, false, nil
}
id, _ := res.LastInsertId()
return id, true, nil
}
// FinishRun 标记执行完成或失败。
func (a *AutomationRules) FinishRun(ctx context.Context, id int64, status string, sentCount int, errMsg string) error {
_, err := a.DB.ExecContext(ctx, `
UPDATE automation_runs
SET status=?,sent_count=?,error_message=?,updated_at=CURRENT_TIMESTAMP
WHERE id=?`, status, sentCount, errMsg, id)
return err
}
// MarkOrderEventTime 更新订单事件时间字段。字段名由调用方控制白名单。
func (a *AutomationRules) MarkOrderEventTime(ctx context.Context, orderID, field string) error {
switch field {
case "paid_at", "shipped_at", "completed_at", "buyer_reviewed_at", "last_review_request_at":
default:
return fmt.Errorf("不允许更新的订单时间字段: %s", field)
}
_, err := a.DB.ExecContext(ctx, "UPDATE orders SET "+field+"=CURRENT_TIMESTAMP, updated_at=CURRENT_TIMESTAMP WHERE order_id=?", orderID)
return err
}
// IncrementReviewRequest 记录一次求评价请求。
func (a *AutomationRules) IncrementReviewRequest(ctx context.Context, orderID string) error {
_, err := a.DB.ExecContext(ctx, `
UPDATE orders
SET review_request_count=review_request_count+1,
last_review_request_at=CURRENT_TIMESTAMP,
updated_at=CURRENT_TIMESTAMP
WHERE order_id=?`, orderID)
return err
}
// DueReviewRequestOrders 返回到期但尚未评价的订单。调度器会再按规则配置做精确判断。
func (a *AutomationRules) DueReviewRequestOrders(ctx context.Context, limit int) ([]Order, error) {
if limit <= 0 {
limit = 200
}
rows, err := a.DB.QueryContext(ctx, `
SELECT order_id,item_id,buyer_id,spec_name,spec_value,quantity,amount,order_status,cookie_id,is_bargain,
receiver_name,receiver_phone,receiver_address,receiver_city,version,chat_id,system_shipped,
COALESCE(paid_at,''),COALESCE(shipped_at,''),COALESCE(completed_at,''),
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
COALESCE(created_at,''),COALESCE(updated_at,'')
FROM orders
WHERE system_shipped=1
AND COALESCE(buyer_reviewed_at,'')=''
AND COALESCE(chat_id,'')<>''
ORDER BY updated_at ASC
LIMIT ?`, limit)
if err != nil {
return nil, err
}
defer rows.Close()
out := []Order{}
for rows.Next() {
var ord Order
var isBargain, version, sysShipped int
if err := rows.Scan(&ord.OrderID, &ord.ItemID, &ord.BuyerID, &ord.SpecName, &ord.SpecValue, &ord.Quantity,
&ord.Amount, &ord.OrderStatus, &ord.CookieID, &isBargain, &ord.ReceiverName, &ord.ReceiverPhone,
&ord.ReceiverAddr, &ord.ReceiverCity, &version, &ord.ChatID, &sysShipped, &ord.PaidAt,
&ord.ShippedAt, &ord.CompletedAt, &ord.BuyerReviewedAt, &ord.LastReviewRequestAt,
&ord.ReviewRequestCount, &ord.CreatedAt, &ord.UpdatedAt); err != nil {
return nil, err
}
ord.IsBargain = isBargain
ord.Version = version
ord.SystemShipped = sysShipped != 0
out = append(out, ord)
}
return out, rows.Err()
}
func createAutomationRuleTx(ctx context.Context, tx *sql.Tx, in AutomationRuleInput) (int64, error) {
if in.Priority <= 0 {
in.Priority = 100
}
res, err := tx.ExecContext(ctx, `
INSERT INTO automation_rules (user_id,cookie_id,item_id,name,trigger_type,enabled,priority,config_json)
VALUES (?,?,?,?,?,?,?,?)`,
in.UserID, in.CookieID, in.ItemID, in.Name, in.TriggerType, boolToInt(in.Enabled), in.Priority, validJSON(in.ConfigJSON))
if err != nil {
return 0, err
}
id, _ := res.LastInsertId()
for _, act := range in.Actions {
if err := insertAutomationActionTx(ctx, tx, id, act); err != nil {
return 0, err
}
}
return id, nil
}
func insertAutomationActionTx(ctx context.Context, tx *sql.Tx, ruleID int64, act AutomationActionInput) error {
if act.DeliveryCount <= 0 {
act.DeliveryCount = 1
}
_, err := tx.ExecContext(ctx, `
INSERT INTO automation_rule_actions
(rule_id,action_type,card_id,delivery_count,message_template,delay_seconds,config_json,enabled,sort_order)
VALUES (?,?,?,?,?,?,?,?,?)`,
ruleID, act.ActionType, nullInt64(act.CardID), act.DeliveryCount, act.MessageTemplate,
act.DelaySeconds, validJSON(act.ConfigJSON), boolToInt(act.Enabled), act.SortOrder)
return err
}
func nullInt64(v int64) any {
if v <= 0 {
return nil
}
return v
}
func validJSON(s string) string {
if s == "" {
return "{}"
}
var v any
if err := json.Unmarshal([]byte(s), &v); err != nil {
return "{}"
}
return s
}
+5 -5
View File
@@ -1,8 +1,8 @@
// Package db 提供 SQLite 连接管理与迁移。
// 使用 modernc.org/sqlite(纯 Go,免 CGO,跨平台编译友好),WAL 模式 + busy_timeout。
// 迁移用 goose 嵌入式执行,schema 从 Python db_manager.py 收敛而来——把历史上 12+ 处
// 运行时 ALTER TABLE 补齐到 CREATE TABLE,并修复 schema 不一致
// (orders.system_shipped、delivery_rules.user_id 等列在原 CREATE 中缺失却被引用)。
// 迁移用 goose 嵌入式执行,把历史 schema 变更收敛为有序 migration。
// 00001 初始 schema 已把历史上运行时 ALTER TABLE 的列补齐到 CREATE TABLE,
// 并修复 schema 不一致(如 orders.system_shipped 原 CREATE 缺失却被引用)。
package db
import (
@@ -34,12 +34,12 @@ func Open(ctx context.Context, dbPath string) (*sql.DB, error) {
db.SetConnMaxLifetime(time.Hour)
if err := db.PingContext(ctx); err != nil {
db.Close()
_ = db.Close()
return nil, fmt.Errorf("ping 数据库: %w", err)
}
if err := Migrate(ctx, db); err != nil {
db.Close()
_ = db.Close()
return nil, err
}
return db, nil
+3 -148
View File
@@ -3,9 +3,7 @@ package db
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
)
// ItemInfo 对应 item_info 表。
@@ -40,28 +38,6 @@ type Card struct {
UserID int64
}
// DeliveryRule 对应 delivery_rules JOIN cards 的发货匹配结果。
type DeliveryRule struct {
ID int64
Keyword string
CardID int64
DeliveryCount int
Enabled bool
Description string
DeliveryTimes int
CardName string
CardType string
APIConfig string
TextContent string
DataContent string
ImageURL string
CardDescription string
CardDelaySeconds int
IsMultiSpec bool
SpecName string
SpecValue string
}
// Items 商品信息操作。
type Items struct{ DB *sql.DB }
@@ -116,7 +92,7 @@ func (i *Items) MultiQuantityDelivery(ctx context.Context, cookieID, itemID stri
type Cards struct{ DB *sql.DB }
// ConsumeBatchData 消费一条批量数据卡券(data 类型),返回内容。
// 对应 Python consume_batch_data:取 data_content 第一行,删除已消费行,发完置空。
// ConsumeBatchData 取 data_content 第一行,删除已消费行,发完置空。
func (c *Cards) ConsumeBatchData(ctx context.Context, cardID int64) (string, error) {
tx, err := c.DB.BeginTx(ctx, nil)
if err != nil {
@@ -155,125 +131,7 @@ func (c *Cards) ConsumeBatchData(ctx context.Context, cardID int64) (string, err
return content, nil
}
// IncrementDeliveryTimes 发货次数 +1。
func (c *Cards) IncrementDeliveryTimes(ctx context.Context, ruleID int64) error {
_, err := c.DB.ExecContext(ctx,
`UPDATE delivery_rules SET delivery_times=delivery_times+1, updated_at=CURRENT_TIMESTAMP WHERE id=?`, ruleID)
return err
}
// DeliveryRules 发货规则匹配。
type DeliveryRules struct{ DB *sql.DB }
// MatchByKeyword 非多规格双向模糊匹配(? LIKE %keyword% OR keyword LIKE %?%)。
// 按关键字长度降序(商品包含关键字时按全长,否则半长)+ id 升序。
// 移植自 get_delivery_rules_by_keyword。
func (d *DeliveryRules) MatchByKeyword(ctx context.Context, searchText string) ([]DeliveryRule, error) {
q := `
SELECT dr.id, dr.keyword, dr.card_id, dr.delivery_count, dr.enabled, dr.description, dr.delivery_times,
c.name, c.type, c.api_config, c.text_content, c.data_content, c.image_url, c.description,
c.delay_seconds, c.is_multi_spec, c.spec_name, c.spec_value
FROM delivery_rules dr
LEFT JOIN cards c ON dr.card_id = c.id
WHERE dr.enabled=1 AND c.enabled=1
AND (? LIKE '%' || dr.keyword || '%' OR dr.keyword LIKE '%' || ? || '%')
ORDER BY
CASE WHEN ? LIKE '%' || dr.keyword || '%' THEN LENGTH(dr.keyword) ELSE LENGTH(dr.keyword)/2 END DESC,
dr.id ASC`
return d.scanRules(ctx, q, searchText, searchText, searchText)
}
// MatchByKeywordAndSpec 多规格匹配:双向模糊 + spec_name/spec_value 精确匹配。
// 移植自 get_delivery_rules_by_keyword_and_spec。
func (d *DeliveryRules) MatchByKeywordAndSpec(ctx context.Context, searchText, specName, specValue string) ([]DeliveryRule, error) {
q := `
SELECT dr.id, dr.keyword, dr.card_id, dr.delivery_count, dr.enabled, dr.description, dr.delivery_times,
c.name, c.type, c.api_config, c.text_content, c.data_content, c.image_url, c.description,
c.delay_seconds, c.is_multi_spec, c.spec_name, c.spec_value
FROM delivery_rules dr
LEFT JOIN cards c ON dr.card_id = c.id
WHERE dr.enabled=1 AND c.enabled=1
AND (? LIKE '%' || dr.keyword || '%' OR dr.keyword LIKE '%' || ? || '%')
AND c.is_multi_spec=1 AND c.spec_name=? AND c.spec_value=?
ORDER BY
CASE WHEN ? LIKE '%' || dr.keyword || '%' THEN LENGTH(dr.keyword) ELSE LENGTH(dr.keyword)/2 END DESC,
dr.delivery_times ASC`
return d.scanRules(ctx, q, searchText, searchText, specName, specValue, searchText)
}
// MatchForOrder 按账号、真实商品 ID 和订单规格匹配卡券。
// 新规则优先精确 item_id;旧规则(item_id 为空)保留关键词回退。
func (d *DeliveryRules) MatchForOrder(ctx context.Context, cookieID, itemID, searchText, specName, specValue string) ([]DeliveryRule, error) {
q := `
SELECT dr.id, dr.keyword, v.card_id, v.delivery_count, dr.enabled, dr.description, dr.delivery_times,
c.name, c.type, c.api_config, c.text_content, c.data_content, c.image_url, c.description,
c.delay_seconds,
CASE WHEN v.spec_name <> '' OR v.spec_value <> '' THEN 1 ELSE 0 END,
v.spec_name, v.spec_value
FROM delivery_rules dr
JOIN delivery_rule_variants v ON v.rule_id = dr.id
JOIN cards c ON c.id = v.card_id
WHERE dr.enabled=1 AND v.enabled=1 AND c.enabled=1
AND (dr.cookie_id='' OR dr.cookie_id=?)
AND ((dr.item_id<>'' AND dr.item_id=?) OR
(dr.item_id='' AND (? LIKE '%' || dr.keyword || '%' OR dr.keyword LIKE '%' || ? || '%')))
AND v.spec_name=? AND v.spec_value=?
ORDER BY
CASE WHEN dr.item_id=? THEN 1 ELSE 0 END DESC,
CASE WHEN ? LIKE '%' || dr.keyword || '%' THEN LENGTH(dr.keyword) ELSE LENGTH(dr.keyword)/2 END DESC,
dr.delivery_times ASC`
return d.scanRules(ctx, q, cookieID, itemID, searchText, searchText, specName, specValue, itemID, searchText)
}
func (d *DeliveryRules) scanRules(ctx context.Context, query string, args ...any) ([]DeliveryRule, error) {
rows, err := d.DB.QueryContext(ctx, query, args...)
if err != nil {
return nil, err
}
defer rows.Close()
var rules []DeliveryRule
for rows.Next() {
var r DeliveryRule
var enabled, isMultiSpec int
var apiConfig, textContent, dataContent, imageURL, specName, specValue, desc, cardDesc sql.NullString
var delaySeconds sql.NullInt64
if err := rows.Scan(
&r.ID, &r.Keyword, &r.CardID, &r.DeliveryCount, &enabled, &desc, &r.DeliveryTimes,
&r.CardName, &r.CardType, &apiConfig, &textContent, &dataContent, &imageURL, &cardDesc,
&delaySeconds, &isMultiSpec, &specName, &specValue); err != nil {
return nil, err
}
r.Enabled = enabled != 0
r.Description = desc.String
r.APIConfig = apiConfig.String
r.TextContent = textContent.String
r.DataContent = dataContent.String
r.ImageURL = imageURL.String
r.CardDescription = cardDesc.String
if delaySeconds.Valid {
r.CardDelaySeconds = int(delaySeconds.Int64)
}
r.IsMultiSpec = isMultiSpec != 0
r.SpecName = specName.String
r.SpecValue = specValue.String
rules = append(rules, r)
}
return rules, rows.Err()
}
// APIConfig 解析卡券的 api_config JSON。
func (r *DeliveryRule) APIConfigMap() map[string]any {
if r.APIConfig == "" {
return nil
}
var m map[string]any
if err := json.Unmarshal([]byte(r.APIConfig), &m); err != nil {
return nil
}
return m
}
// splitLines / joinLines 复刻 Python str.splitlines / "\n".join。
// splitLines / joinLines 统一处理多行库存内容。
func splitLines(s string) []string {
var out []string
cur := []rune{}
@@ -293,7 +151,7 @@ func splitLines(s string) []string {
if len(cur) > 0 {
out = append(out, string(cur))
}
// 过滤空行(Python consume_batch_data 行为)。
// 过滤空行。
res := out[:0]
for _, l := range out {
if l != "" {
@@ -313,6 +171,3 @@ func joinLines(lines []string) string {
}
return out
}
// 防止 fmt 未用(保留供未来错误格式化)。
var _ = fmt.Sprintf
+1 -2
View File
@@ -8,7 +8,7 @@ import (
)
// TestMigrate_AppliesCleanSchema 在临时库上跑迁移,验证全量 schema 干净落地、
// 关键不一致列(orders.system_shipped / delivery_rules.user_id)存在、默认设置就位。
// 关键不一致列(orders.system_shipped 等)存在、默认设置就位。
func TestMigrate_AppliesCleanSchema(t *testing.T) {
tmp := t.TempDir()
dbPath := filepath.Join(tmp, "test.db")
@@ -27,7 +27,6 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
{"orders", "system_shipped"},
{"orders", "receiver_city"},
{"orders", "version"},
{"delivery_rules", "user_id"},
{"cards", "image_url"},
{"cards", "delay_seconds"},
{"keywords", "item_id"},
@@ -0,0 +1,90 @@
-- +goose Up
-- +goose StatementBegin
-- 自动化中心 schema。
--
-- 设计目标:
-- 1. 不再把“自动发货”写死成唯一业务,付款发货、评价赠品、超时求评价都统一为自动化规则。
-- 2. 触发来源可以是 WS 系统事件、计划任务或后台手动触发;规则和动作统一落在 automation_rules/actions。
-- 3. automation_runs 使用 trigger_key 做持久化防重,避免 WS 重放、服务重启或计划任务重复扫描导致重复发送。
CREATE TABLE IF NOT EXISTS automation_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
cookie_id TEXT NOT NULL DEFAULT '',
item_id TEXT NOT NULL DEFAULT '',
name TEXT NOT NULL,
trigger_type TEXT NOT NULL,
enabled INTEGER NOT NULL DEFAULT 1,
priority INTEGER NOT NULL DEFAULT 100,
config_json TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE
);
CREATE INDEX IF NOT EXISTS idx_automation_rules_user ON automation_rules(user_id, created_at DESC);
CREATE INDEX IF NOT EXISTS idx_automation_rules_match ON automation_rules(cookie_id, item_id, trigger_type, enabled, priority);
CREATE TABLE IF NOT EXISTS automation_rule_actions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
action_type TEXT NOT NULL,
card_id INTEGER,
delivery_count INTEGER NOT NULL DEFAULT 1,
message_template TEXT NOT NULL DEFAULT '',
delay_seconds INTEGER NOT NULL DEFAULT 0,
config_json TEXT NOT NULL DEFAULT '{}',
enabled INTEGER NOT NULL DEFAULT 1,
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES automation_rules(id) ON DELETE CASCADE,
FOREIGN KEY (card_id) REFERENCES cards(id) ON DELETE RESTRICT
);
CREATE INDEX IF NOT EXISTS idx_automation_rule_actions_rule ON automation_rule_actions(rule_id, sort_order, id);
CREATE TABLE IF NOT EXISTS automation_runs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
cookie_id TEXT NOT NULL,
item_id TEXT NOT NULL DEFAULT '',
order_id TEXT NOT NULL DEFAULT '',
buyer_id TEXT NOT NULL DEFAULT '',
chat_id TEXT NOT NULL DEFAULT '',
trigger_type TEXT NOT NULL,
trigger_key TEXT NOT NULL,
status TEXT NOT NULL,
sent_count INTEGER NOT NULL DEFAULT 0,
error_message TEXT NOT NULL DEFAULT '',
raw_event_json TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (rule_id) REFERENCES automation_rules(id) ON DELETE CASCADE,
UNIQUE(rule_id, trigger_key)
);
CREATE INDEX IF NOT EXISTS idx_automation_runs_cookie_order ON automation_runs(cookie_id, order_id, trigger_type);
CREATE INDEX IF NOT EXISTS idx_automation_runs_status ON automation_runs(status, updated_at);
ALTER TABLE orders ADD COLUMN paid_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN shipped_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN completed_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN buyer_reviewed_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN last_review_request_at TEXT DEFAULT '';
ALTER TABLE orders ADD COLUMN review_request_count INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN automation_json TEXT NOT NULL DEFAULT '{}';
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
DROP TABLE IF EXISTS automation_runs;
DROP TABLE IF EXISTS automation_rule_actions;
DROP TABLE IF EXISTS automation_rules;
ALTER TABLE item_publish_batch_rows DROP COLUMN automation_json;
ALTER TABLE orders DROP COLUMN review_request_count;
ALTER TABLE orders DROP COLUMN last_review_request_at;
ALTER TABLE orders DROP COLUMN buyer_reviewed_at;
ALTER TABLE orders DROP COLUMN completed_at;
ALTER TABLE orders DROP COLUMN shipped_at;
ALTER TABLE orders DROP COLUMN paid_at;
-- +goose StatementEnd
@@ -0,0 +1,51 @@
-- +goose Up
-- +goose StatementBegin
-- 清理被 automation_rules 取代或从未使用的 schema:
-- - delivery_rules + delivery_rule_variants:发货规则旧系统,已被 automation_rules 完全取代(前端只走 automation-rules)。
-- - email_verifications / captcha_codes / ai_item_cache / risk_control_logs:从未有 Go 代码读写。
-- - item_publish_batch_rows.auto_create_delivery_rule / card_group_id / delivery_count:批量铺货改走 automation_json,三列从未读写。
DROP TABLE IF EXISTS delivery_rule_variants;
DROP TABLE IF EXISTS delivery_rules;
DROP TABLE IF EXISTS email_verifications;
DROP TABLE IF EXISTS captcha_codes;
DROP TABLE IF EXISTS ai_item_cache;
DROP TABLE IF EXISTS risk_control_logs;
ALTER TABLE item_publish_batch_rows DROP COLUMN auto_create_delivery_rule;
ALTER TABLE item_publish_batch_rows DROP COLUMN card_group_id;
ALTER TABLE item_publish_batch_rows DROP COLUMN delivery_count;
-- +goose StatementEnd
-- +goose Down
-- +goose StatementBegin
-- 仅重建结构,历史数据不可恢复。
CREATE TABLE IF NOT EXISTS delivery_rules (
id INTEGER PRIMARY KEY AUTOINCREMENT,
keyword TEXT NOT NULL,
card_id INTEGER NOT NULL,
delivery_count INTEGER DEFAULT 1,
enabled BOOLEAN DEFAULT TRUE,
description TEXT,
delivery_times INTEGER DEFAULT 0,
user_id INTEGER NOT NULL DEFAULT 1,
cookie_id TEXT NOT NULL DEFAULT '',
item_id TEXT NOT NULL DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS delivery_rule_variants (
id INTEGER PRIMARY KEY AUTOINCREMENT,
rule_id INTEGER NOT NULL,
spec_name TEXT NOT NULL DEFAULT '',
spec_value TEXT NOT NULL DEFAULT '',
card_id INTEGER NOT NULL,
delivery_count INTEGER NOT NULL DEFAULT 1,
enabled BOOLEAN NOT NULL DEFAULT TRUE,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
ALTER TABLE item_publish_batch_rows ADD COLUMN auto_create_delivery_rule INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN card_group_id INTEGER NOT NULL DEFAULT 0;
ALTER TABLE item_publish_batch_rows ADD COLUMN delivery_count INTEGER NOT NULL DEFAULT 1;
-- +goose StatementEnd
+21 -5
View File
@@ -25,6 +25,12 @@ type Order struct {
Version int
ChatID string
SystemShipped bool
PaidAt string
ShippedAt string
CompletedAt string
BuyerReviewedAt string
LastReviewRequestAt string
ReviewRequestCount int
CreatedAt string
UpdatedAt string
}
@@ -32,8 +38,9 @@ type Order struct {
// Orders 订单操作。
type Orders struct{ DB *sql.DB }
// Upsert 插入或更新订单。仅更新提供的非零字段,使用 version 乐观锁。
// 对应 Python insert_or_update_order 的核心行为。
// Upsert 插入或更新订单。仅更新提供的非零字段(INSERT OR IGNORE 占位 + 动态 UPDATE)。
// 注:orders.version 列当前仅作占位读取,不参与并发控制——SQLite 单写者序列化写入,
// 且本场景无多进程/多协程并发更新同一订单的需求,故未实现乐观锁以避免引入失败重试复杂度。
func (o *Orders) Upsert(ctx context.Context, orderID string, opts OrderUpsertOpts) error {
if orderID == "" {
return errors.New("order_id 不能为空")
@@ -138,15 +145,19 @@ type OrderUpsertOpts struct {
func (o *Orders) Get(ctx context.Context, orderID string) (*Order, error) {
var ord Order
var isBargain, version, sysShipped int
var itemID, buyerID, specName, specValue, qty, amount, status, cookieID, receiverName, receiverPhone, receiverAddr, receiverCity, chatID, createdAt, updatedAt sql.NullString
var itemID, buyerID, specName, specValue, qty, amount, status, cookieID, receiverName, receiverPhone, receiverAddr, receiverCity, chatID, paidAt, shippedAt, completedAt, buyerReviewedAt, lastReviewRequestAt, createdAt, updatedAt sql.NullString
err := o.DB.QueryRowContext(ctx,
`SELECT order_id, item_id, buyer_id, spec_name, spec_value, quantity, amount,
order_status, cookie_id, is_bargain, receiver_name, receiver_phone, receiver_address,
receiver_city, version, chat_id, system_shipped, created_at, updated_at
receiver_city, version, chat_id, system_shipped,
COALESCE(paid_at,''),COALESCE(shipped_at,''),COALESCE(completed_at,''),
COALESCE(buyer_reviewed_at,''),COALESCE(last_review_request_at,''),review_request_count,
created_at, updated_at
FROM orders WHERE order_id=?`, orderID).Scan(
&ord.OrderID, &itemID, &buyerID, &specName, &specValue, &qty, &amount,
&status, &cookieID, &isBargain, &receiverName, &receiverPhone, &receiverAddr,
&receiverCity, &version, &chatID, &sysShipped, &createdAt, &updatedAt)
&receiverCity, &version, &chatID, &sysShipped, &paidAt, &shippedAt, &completedAt,
&buyerReviewedAt, &lastReviewRequestAt, &ord.ReviewRequestCount, &createdAt, &updatedAt)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
@@ -169,6 +180,11 @@ func (o *Orders) Get(ctx context.Context, orderID string) (*Order, error) {
ord.Version = version
ord.ChatID = chatID.String
ord.SystemShipped = sysShipped != 0
ord.PaidAt = paidAt.String
ord.ShippedAt = shippedAt.String
ord.CompletedAt = completedAt.String
ord.BuyerReviewedAt = buyerReviewedAt.String
ord.LastReviewRequestAt = lastReviewRequestAt.String
ord.CreatedAt = createdAt.String
ord.UpdatedAt = updatedAt.String
return &ord, nil
+2 -2
View File
@@ -10,7 +10,7 @@ type Store struct {
Cookies *Cookies
Items *Items
Cards *Cards
DeliveryRules *DeliveryRules
Automation *AutomationRules
Orders *Orders
Keywords *Keywords
DefaultReps *DefaultReplies
@@ -31,7 +31,7 @@ func NewStore(db *sql.DB) *Store {
Cookies: &Cookies{DB: db},
Items: &Items{DB: db},
Cards: &Cards{DB: db},
DeliveryRules: &DeliveryRules{DB: db},
Automation: &AutomationRules{DB: db},
Orders: &Orders{DB: db},
Keywords: &Keywords{DB: db},
DefaultReps: &DefaultReplies{DB: db},