Files
Ydisks-Xianyu-Helper/internal/automation/events.go
T
ChristandClaude Opus 4.8 57f9090dd2 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]>
2026-06-30 21:40:15 +08:00

300 lines
7.4 KiB
Go

// Package automation 实现自动化处理中心。
//
// 重要边界:
// - engine 只负责 WS 消息连接和分流,不在分流层判断业务规则。
// - 用户消息进入关键词/AI 回复链;系统卡片和平台通知只进入自动化中心。
// - 自动化中心把 WS 事件、计划任务、后台手动任务统一转换为 Task,再匹配规则和执行动作。
package automation
import (
"encoding/json"
"net/url"
"regexp"
"strings"
)
const (
TriggerOrderPaid = "order_paid"
TriggerBuyerReviewed = "buyer_reviewed"
TriggerReviewMissingTimeout = "review_missing_timeout"
ActionConfirmShipment = "confirm_shipment"
ActionSendCard = "send_card"
ActionSendText = "send_text"
)
// Task 是自动化中心的统一输入。它可以来自 WS 系统事件、计划任务或手动触发。
type Task struct {
Source string // ws/scheduler/manual
AccountID string
CookieStr string
TriggerType string
ChatID string
OrderID string
ItemID string
BuyerID string
SpecName string
SpecValue string
Quantity string
Amount string
OrderStatus string
Text string
UpdateKey string
Raw map[string]any
}
// OrderDetail 是自动化中心执行交易类任务前需要补齐的订单事实。
// 规格和数量来自闲鱼订单,不由自动化规则修改商品属性。
type OrderDetail struct {
Quantity string
SpecName string
SpecValue string
Amount string
OrderStatus string
}
// ExtractTaskFromWS 从一条解密后的 WS 消息中提取系统事件。
// 这里只做事实解析:识别平台告诉了我们什么;是否执行自动化由 Center 根据规则决定。
func ExtractTaskFromWS(accountID, cookieStr string, raw map[string]any) *Task {
if raw == nil {
return nil
}
f := fieldsFromRaw(raw)
if f.text == "" && f.redReminder == "" && f.updateKey == "" {
return nil
}
task := &Task{
Source: "ws",
AccountID: accountID,
CookieStr: cookieStr,
ChatID: f.chatID,
OrderID: f.orderID,
ItemID: f.itemID,
BuyerID: f.buyerID,
Text: firstNonEmpty(f.text, f.redReminder),
UpdateKey: f.updateKey,
Raw: raw,
}
switch {
case isOrderPaidEvent(f):
task.TriggerType = TriggerOrderPaid
case isBuyerReviewedEvent(f):
task.TriggerType = TriggerBuyerReviewed
default:
return nil
}
return task
}
type rawFields struct {
text string
redReminder string
title string
detail string
updateKey string
contentType string
chatID string
orderID string
itemID string
buyerID string
reminderURL string
}
func fieldsFromRaw(raw map[string]any) rawFields {
var f rawFields
if m1 := mapAt(raw, "1"); m1 != nil {
if s := strAny(m1["2"]); s != "" {
f.chatID = trimGoofishSID(s)
}
if m10 := mapAt(m1, "10"); m10 != nil {
f.text = strAny(m10["reminderContent"])
f.redReminder = strAny(m10["redReminder"])
f.title = strAny(m10["reminderTitle"])
f.detail = strAny(m10["detailNotice"])
f.reminderURL = strAny(m10["reminderUrl"])
f.buyerID = strAny(m10["senderUserId"])
f.updateKey, f.contentType = extFields(strAny(m10["extJson"]))
}
if contentJSON := nestedString(raw, "1", "6", "3", "5"); contentJSON != "" {
if id := extractOrderIDFromContent(contentJSON); id != "" {
f.orderID = id
}
}
}
if m3 := mapAt(raw, "3"); m3 != nil {
if f.redReminder == "" {
f.redReminder = strAny(m3["redReminder"])
}
}
if m4 := mapAt(raw, "4"); m4 != nil {
if f.text == "" {
f.text = strAny(m4["reminderContent"])
}
if f.redReminder == "" {
f.redReminder = strAny(m4["redReminder"])
}
if f.title == "" {
f.title = strAny(m4["reminderTitle"])
}
if f.detail == "" {
f.detail = strAny(m4["detailNotice"])
}
if f.reminderURL == "" {
f.reminderURL = strAny(m4["reminderUrl"])
}
if f.updateKey == "" {
f.updateKey, f.contentType = extFields(strAny(m4["extJson"]))
}
}
if f.updateKey != "" {
chatID, orderID := parseUpdateKey(f.updateKey)
if f.chatID == "" {
f.chatID = chatID
}
if f.orderID == "" {
f.orderID = orderID
}
}
if f.reminderURL != "" {
if f.itemID == "" {
f.itemID = queryValue(f.reminderURL, "itemId")
}
if f.buyerID == "" {
f.buyerID = queryValue(f.reminderURL, "peerUserId")
}
if f.chatID == "" {
f.chatID = queryValue(f.reminderURL, "sid")
}
if f.orderID == "" {
f.orderID = matchOrderID(f.reminderURL)
}
}
return f
}
func isOrderPaidEvent(f rawFields) bool {
return strings.Contains(f.text, "我已付款,等待你发货") ||
strings.Contains(f.text, "已付款,待发货") ||
strings.Contains(f.text, "记得及时发货") ||
strings.Contains(f.redReminder, "等待卖家发货")
}
func isBuyerReviewedEvent(f rawFields) bool {
// 闲鱼评价样本:
// redReminder=有新交易评价
// reminderContent=[我完成了评价]
// updateKey=chat_id:order_id:10:BUYER_RATE_SELLER:26
// 仅“服务评价邀请”不含 BUYER_RATE_SELLER,不能误触发赠品。
return strings.Contains(f.redReminder, "有新交易评价") &&
strings.Contains(f.text, "我完成了评价") &&
strings.Contains(f.updateKey, "BUYER_RATE_SELLER")
}
func extFields(ext string) (updateKey, contentType string) {
if strings.TrimSpace(ext) == "" {
return "", ""
}
var m map[string]any
if json.Unmarshal([]byte(ext), &m) != nil {
return "", ""
}
return strAny(m["updateKey"]), strAny(m["contentType"])
}
func parseUpdateKey(updateKey string) (chatID, orderID string) {
parts := strings.Split(updateKey, ":")
if len(parts) >= 2 {
return parts[0], parts[1]
}
return "", ""
}
func queryValue(rawURL, key string) string {
if strings.HasPrefix(rawURL, "fleamarket://") {
rawURL = "https://local.invalid/" + strings.TrimPrefix(rawURL, "fleamarket://")
}
u, err := url.Parse(rawURL)
if err != nil {
return ""
}
return u.Query().Get(key)
}
func mapAt(m map[string]any, key string) map[string]any {
v, _ := m[key].(map[string]any)
return v
}
func nestedString(m map[string]any, path ...string) string {
var cur any = m
for _, p := range path {
cm, ok := cur.(map[string]any)
if !ok {
return ""
}
cur = cm[p]
}
return strAny(cur)
}
func strAny(v any) string {
switch x := v.(type) {
case string:
return x
case nil:
return ""
default:
b, _ := json.Marshal(x)
return string(b)
}
}
func firstNonEmpty(values ...string) string {
for _, v := range values {
if strings.TrimSpace(v) != "" {
return v
}
}
return ""
}
func trimGoofishSID(s string) string {
if i := strings.Index(s, "@"); i >= 0 {
return s[:i]
}
return s
}
var orderIDPatterns = []*regexp.Regexp{
regexp.MustCompile(`orderId[=:](\d{10,})`),
regexp.MustCompile(`order_detail\?id=(\d{10,})`),
regexp.MustCompile(`bizOrderId[=:](\d{10,})`),
regexp.MustCompile(`id=(\d{10,})`),
}
func matchOrderID(s string) string {
for _, re := range orderIDPatterns {
if m := re.FindStringSubmatch(s); len(m) == 2 {
return m[1]
}
}
return ""
}
func extractOrderIDFromContent(contentJSON string) string {
var c map[string]any
if json.Unmarshal([]byte(contentJSON), &c) != nil {
return ""
}
for _, path := range [][]string{
{"dxCard", "item", "main", "exContent", "button", "targetUrl"},
{"dxCard", "item", "main", "targetUrl"},
{"dynamicOperation", "changeContent", "dxCard", "item", "main", "exContent", "button", "targetUrl"},
} {
if id := matchOrderID(nestedString(c, path...)); id != "" {
return id
}
}
return ""
}