阶段六:收口Automation发货卡密与通知动作边界
This commit is contained in:
1 parent
9255eb3132
commit
e5df708e4a
6 files changed
+1067
-1226
No files matched your search
+458
-854
File diff suppressed because it is too large.
Load diff
@@ -167,7 +167,8 @@ app shell / routes
|
||||
- 已完成阶段 6 第四个 PR 切片“Engine 凭证状态与 Token 生命周期边界”:将 Cookie 快照、Token 缓存、刷新锁、设备指纹和刷新诊断状态收口到独立 `credentialState`;运行状态锁改为显式 `runtimeMu`,避免匿名组件锁冲突;保留风控恢复、刷新锁、Cookie/Token 绑定和 WebSocket 注册前快照复核语义;Engine 全量测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交;
|
||||
- 已完成阶段 6 第五个 PR 切片“Automation 事件事实与规则匹配边界”:新增事件事实记录器、无动作副作用的规则匹配器和纯动作计划器;`Center` 与 `Scheduler` 统一通过组件查询规则和生成动作计划,规则匹配不执行外部动作,付款发货动作顺序、规格匹配、延迟快照和恢复语义保持不变;Automation/Server race、全量测试、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交;
|
||||
- 已完成阶段 6 第六个 PR 切片“Automation 运行协调与动作执行边界”:新增 `automationRunCoordinator`,统一运行创建/恢复、动作前后检查点、延迟任务续租、账号门禁和不确定结果隔离;`Center` 保留兼容调用入口,外部动作已执行/未执行/结果未知三态语义、人工核对状态机和恢复游标保持不变;Automation 测试、注释和 diff 门禁通过,整批修改合并为一个可回滚提交;
|
||||
- 阶段 6 下一 PR 切片为“Automation 发货、卡密与通知动作边界”:提取确认发货、卡密分配、消息发送和结果通知的动作执行组件,保留凭证锁、卡券锁、发送错误分类和通知幂等语义;
|
||||
- 已完成阶段 6 第七个 PR 切片“Automation 发货、卡密与通知动作边界”:新增 `automationActionExecutor` 与 `deliveryNotifier`,统一确认发货、Cookie/Jar 合并、卡券锁与库存消费、消息错误三态分类和结果通知;`Center` 保留兼容入口,凭证锁、卡券库存、恢复唤醒和通知文案语义保持不变;新增动作执行器回归测试,Automation 测试、注释和 diff 门禁通过,整批修改合并为一个可回滚提交;
|
||||
- 阶段 6 下一 PR 切片为“Automation 账号任务与凭证门禁边界”:提取账号自动评价/发货任务的调度、凭证阻塞和账号状态门禁边界,保留 Session 失效恢复、任务租约和失败重试语义;
|
||||
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
|
||||
|
||||
## 6. 阶段 0:治理文档与强约束
|
||||
@@ -584,3 +585,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-14 | 完成阶段 6 第四个 PR 切片“Engine 凭证状态与 Token 生命周期边界” | 新增 `credentialState`,集中 Cookie 快照、Token 缓存、刷新锁、设备指纹和刷新诊断状态;运行状态组件锁改名为 `runtimeMu`,保持 `Account` facade 字段访问兼容;Cookie 更新、Token 清理、风控恢复和 WS 注册前凭证快照复核语义保持不变;Engine 全量测试、Engine/Server race、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 事件事实与规则匹配边界 |
|
||||
| 2026-08-14 | 完成阶段 6 第五个 PR 切片“Automation 事件事实与规则匹配边界” | 新增 `eventFactRecorder`、`ruleMatcher` 和 `actionPlanner`;事件事实写入、规则查询和动作计划生成职责分离,`Center`/`Scheduler` 不再直接散落调用规则匹配;动作计划保持付款发卡优先、规格过滤和延迟快照语义,新增纯计划与无订单事实回归测试;Automation/Server race、全量测试、vet、lint、注释和前端构建门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 运行协调与动作执行边界 |
|
||||
| 2026-08-14 | 完成阶段 6 第六个 PR 切片“Automation 运行协调与动作执行边界” | 新增 `automationRunCoordinator`,统一运行创建/恢复、动作前后检查点、延迟任务续租、账号门禁和不确定结果隔离;`Center` 保留兼容调用入口,外部动作三态语义、人工核对状态机和恢复游标保持不变;Automation 测试、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 发货、卡密与通知动作边界 |
|
||||
| 2026-08-14 | 完成阶段 6 第七个 PR 切片“Automation 发货、卡密与通知动作边界” | 新增 `automationActionExecutor` 与 `deliveryNotifier`,统一确认发货、Cookie/Jar 合并、卡券锁与库存消费、消息错误三态分类和结果通知;`Center` 保留兼容入口,凭证锁、卡券库存、恢复唤醒和通知文案语义保持不变;新增动作执行器回归测试;Automation 测试、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 6:Automation 账号任务与凭证门禁边界 |
|
||||
@@ -0,0 +1,464 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// automationActionExecutor 负责把动作计划转换为确认发货、卡密发送或消息发送,并集中维护凭证快照、卡券库存和外部发送结果的边界。
|
||||
type automationActionExecutor struct {
|
||||
// store 提供订单、卡券、账号 Cookie 和自动化事实的持久化能力。
|
||||
store *db.Store
|
||||
// senders 提供账号当前在线的消息发送器。
|
||||
senders SenderProvider
|
||||
// mtop 返回当前生效的 MTOP 客户端,支持测试替换和运行时注入。
|
||||
mtop func() mtop.Client
|
||||
// recoverer 返回当前生效的凭证恢复器。
|
||||
recoverer func() CredentialRecoverer
|
||||
// logger 记录确认发货和本地状态持久化异常。
|
||||
logger *slog.Logger
|
||||
// cookieSource 读取测试或运行时覆盖的账号 Cookie。
|
||||
cookieSource func(context.Context, string) (string, error)
|
||||
// wakeCredentialBlocked 在 Cookie 更新后唤醒凭证阻塞的自动化任务。
|
||||
wakeCredentialBlocked func(context.Context, string)
|
||||
// cardLocks 串行化同一卡密组的数据库存取和消费。
|
||||
cardLocks sync.Map
|
||||
}
|
||||
|
||||
// executeAction 执行一个动作,并把消息发送错误分类为可安全重试或结果未知。
|
||||
func (e *automationActionExecutor) executeAction(ctx context.Context, task Task, action db.AutomationAction) (int, error) {
|
||||
switch action.ActionType {
|
||||
case ActionConfirmShipment:
|
||||
return 0, e.confirmShipment(ctx, task)
|
||||
case ActionSendCard:
|
||||
return e.sendCard(ctx, task, action)
|
||||
case ActionSendText:
|
||||
// text 是渲染后的文字动作内容。
|
||||
text := renderTemplate(action.MessageTemplate, task)
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return 0, nil
|
||||
}
|
||||
// sendErr 保存文字消息发送错误。
|
||||
if sendErr := e.sendText(ctx, task, text); sendErr != nil {
|
||||
if errors.Is(sendErr, ErrMessageNotSent) {
|
||||
return 0, sendErr
|
||||
}
|
||||
return 0, uncertainAction(sendErr)
|
||||
}
|
||||
return 1, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("未知自动化动作: %s", action.ActionType)
|
||||
}
|
||||
}
|
||||
|
||||
// confirmShipment 根据账号设置和任务强制标记决定是否确认订单发货。
|
||||
func (e *automationActionExecutor) confirmShipment(ctx context.Context, task Task) error {
|
||||
if task.OrderID == "" {
|
||||
return fmt.Errorf("确认发货缺少订单ID")
|
||||
}
|
||||
// enabled 表示账号是否打开自动确认发货设置。
|
||||
// readErr 保存读取自动确认发货设置的错误。
|
||||
enabled, readErr := e.store.Cookies.GetAutoConfirm(ctx, task.AccountID)
|
||||
if readErr != nil {
|
||||
return fmt.Errorf("读取自动确认发货设置: %w", readErr)
|
||||
}
|
||||
if !enabled && !task.ForceConfirmShipment {
|
||||
return nil
|
||||
}
|
||||
return e.confirmShipmentAttempt(ctx, task, true)
|
||||
}
|
||||
|
||||
// confirmShipmentAttempt 在凭证锁内调用 Consign,并处理 Cookie 合并、凭证恢复和本地状态收口。
|
||||
func (e *automationActionExecutor) confirmShipmentAttempt(ctx context.Context, task Task, allowCredentialRecovery bool) error {
|
||||
// credentialUnlock 是账号凭证锁的释放函数。
|
||||
credentialUnlock := e.store.LockAccountCredentials(task.AccountID)
|
||||
// credentialLocked 标记当前调用是否仍持有凭证锁。
|
||||
credentialLocked := true
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}()
|
||||
// runtimeData 是确认发货所需的最小 Cookie 与 metadata 运行视图,不包含登录密码和账号资料。
|
||||
runtimeData, err := e.store.Cookies.GetCookieRuntimeData(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// completeSnapshot 表示 metadata 中是否包含可恢复的完整 Cookie Jar。
|
||||
_, completeSnapshot := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON)
|
||||
if strings.TrimSpace(runtimeData.Value) == "" && !completeSnapshot {
|
||||
return fmt.Errorf("账号 %s Cookie 为空", task.AccountID)
|
||||
}
|
||||
// cookieStr 是本次确认发货使用的扁平 Cookie。
|
||||
cookieStr := runtimeData.Value
|
||||
// mtopCtx 是携带 Cookie Jar 或扁平 Cookie 的 MTOP 请求上下文。
|
||||
var mtopCtx context.Context
|
||||
// cookieSession 记录 MTOP 响应中的 Cookie 合并结果。
|
||||
var cookieSession *mtop.CookieSession
|
||||
// snapshot 是 metadata 中恢复出的完整 Cookie Jar。
|
||||
// snapshotOK 表示完整 Cookie Jar 是否存在。
|
||||
if snapshot, snapshotOK := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); snapshotOK {
|
||||
mtopCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
mtopCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
// ok 表示远端确认发货是否成功。
|
||||
// ret 保存远端返回的业务错误文本。
|
||||
// updated 保存无权威 Cookie Jar 时的扁平 Cookie 更新结果。
|
||||
// callErr 保存 MTOP 请求层错误。
|
||||
// consignOK 表示远端确认发货是否成功。
|
||||
// ret 保存远端返回的业务错误文本。
|
||||
// updated 保存无权威 Cookie Jar 时的扁平 Cookie 更新结果。
|
||||
// callErr 保存 MTOP 请求层错误。
|
||||
consignOK, ret, updated, callErr := e.mtop().ConsignContext(mtopCtx, cookieStr, task.OrderID)
|
||||
// persistenceErrs 收集远端动作完成后本地状态写入失败。
|
||||
var persistenceErrs []error
|
||||
// runtimeCookie 保存需要同步到在线发送器的最新 Cookie。
|
||||
runtimeCookie := ""
|
||||
// runtimeCookieChanged 表示在线运行时是否需要替换 Cookie。
|
||||
runtimeCookieChanged := false
|
||||
// value 是 Cookie 会话合并后的扁平值。
|
||||
// snapshot 是 Cookie 会话合并后的完整快照。
|
||||
// changed 表示 Cookie 会话是否产生变化。
|
||||
value, snapshot, changed := cookieSession.State()
|
||||
// sessionHandled 表示本次请求是否由完整 Cookie Jar 接管。
|
||||
sessionHandled := snapshot != nil
|
||||
if changed {
|
||||
// metadata 是准备写回数据库的 Cookie metadata。
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON)
|
||||
if snapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(runtimeData.MetadataJSON, snapshot)
|
||||
}
|
||||
// saveErr 保存 Cookie Jar 写回数据库时的错误。
|
||||
if saveErr := e.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr))
|
||||
} else if value != cookieStr {
|
||||
runtimeCookie = value
|
||||
runtimeCookieChanged = true
|
||||
}
|
||||
}
|
||||
if !sessionHandled && callErr == nil && updated != "" && updated != cookieStr {
|
||||
// 没有权威快照的历史账号保留扁平 Cookie 兼容路径,并清除可能过期的旧 Jar。
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON)
|
||||
// saveErr 保存扁平 Cookie 写回数据库时的错误。
|
||||
if saveErr := e.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr))
|
||||
} else {
|
||||
runtimeCookie = updated
|
||||
runtimeCookieChanged = true
|
||||
}
|
||||
}
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
if runtimeCookieChanged && e.senders != nil {
|
||||
// sender 是当前账号的在线消息发送器。
|
||||
// running 表示账号是否仍处于运行状态。
|
||||
if sender, running := e.senders.Sender(task.AccountID); running {
|
||||
sender.UpdateCookie(runtimeCookie)
|
||||
}
|
||||
}
|
||||
if runtimeCookieChanged {
|
||||
e.wakeCredentialBlocked(ctx, task.AccountID)
|
||||
}
|
||||
// sessionErr 将请求层错误和远端业务失败统一为凭证状态判断输入。
|
||||
sessionErr := callErr
|
||||
if sessionErr == nil && !consignOK {
|
||||
sessionErr = errors.New(strings.Join(ret, "; "))
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(sessionErr) {
|
||||
if len(persistenceErrs) > 0 {
|
||||
return errors.Join(fmt.Errorf("确认发货 Session 已失效: %w", sessionErr), errors.Join(persistenceErrs...))
|
||||
}
|
||||
// recoverer 是当前生效的凭证恢复器快照,避免一次判断期间被替换两次。
|
||||
recoverer := e.recoverer()
|
||||
if allowCredentialRecovery && recoverer != nil && recoverer.RecoverExpiredCredential(ctx, task.AccountID) {
|
||||
e.logger.Info("确认发货凭证恢复成功,重新执行确认发货", "account", task.AccountID, "order_id", task.OrderID)
|
||||
return e.confirmShipmentAttempt(ctx, task, false)
|
||||
}
|
||||
if !allowCredentialRecovery {
|
||||
return fmt.Errorf("%w: 确认发货在凭证恢复后仍返回 Session 失效: %v", errActionNotPerformed, sessionErr)
|
||||
}
|
||||
return fmt.Errorf("%w: 确认发货 Session 已失效且凭证恢复失败: %v", errActionNotPerformed, sessionErr)
|
||||
}
|
||||
if callErr != nil {
|
||||
if len(persistenceErrs) > 0 {
|
||||
callErr = errors.Join(callErr, errors.Join(persistenceErrs...))
|
||||
}
|
||||
return uncertainAction(callErr)
|
||||
}
|
||||
if !consignOK {
|
||||
// failure 是远端拒绝确认发货的业务错误。
|
||||
failure := fmt.Errorf("确认发货失败: %s", strings.Join(ret, "; "))
|
||||
if len(persistenceErrs) > 0 {
|
||||
return errors.Join(failure, errors.Join(persistenceErrs...))
|
||||
}
|
||||
return failure
|
||||
}
|
||||
// sysShip 表示本地订单已由系统确认发货。
|
||||
sysShip := true
|
||||
// upsertErr 保存本地订单发货状态写入错误。
|
||||
if upsertErr := e.store.Orders.Upsert(ctx, task.OrderID, db.OrderUpsertOpts{
|
||||
CookieID: task.AccountID,
|
||||
ItemID: task.ItemID,
|
||||
BuyerID: task.BuyerID,
|
||||
ChatID: task.ChatID,
|
||||
OrderStatus: "shipped",
|
||||
SystemShipped: &sysShip,
|
||||
}); upsertErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存本地订单发货状态: %w", upsertErr))
|
||||
}
|
||||
// eventErr 保存订单发货事实写入错误。
|
||||
if eventErr := e.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "shipped_at"); eventErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存订单发货时间: %w", eventErr))
|
||||
}
|
||||
if len(persistenceErrs) > 0 {
|
||||
return uncertainAction(fmt.Errorf("闲鱼已确认发货,但本地状态保存失败: %w", errors.Join(persistenceErrs...)))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// sendCard 按规格和购买数量分配文本、图片或数据卡密。
|
||||
func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, action db.AutomationAction) (int, error) {
|
||||
if !actionMatchesOrderSpec(task, action) {
|
||||
return 0, nil
|
||||
}
|
||||
if action.CardID <= 0 {
|
||||
return 0, fmt.Errorf("发送卡密动作缺少卡密组ID")
|
||||
}
|
||||
// count 是当前订单需要发送的卡密数量。
|
||||
count := deliverySendCount(task, action)
|
||||
// card 是待发送的卡密组完整配置。
|
||||
card, err := e.store.Cards.Get(ctx, action.CardID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !card.Enabled {
|
||||
return 0, fmt.Errorf("卡密组 %d 已停用", card.ID)
|
||||
}
|
||||
if card.Type == "data" {
|
||||
return e.sendDataCard(ctx, task, card, count)
|
||||
}
|
||||
// sent 是已经成功发送的卡密数量。
|
||||
sent := 0
|
||||
// i 表示当前卡密发送序号。
|
||||
for i := 0; i < count; i++ {
|
||||
// content 是当前卡密文本内容。
|
||||
// imageURL 是当前卡密图片地址。
|
||||
content, imageURL, readErr := e.cardContent(ctx, card)
|
||||
if readErr != nil {
|
||||
return sent, readErr
|
||||
}
|
||||
if imageURL != "" {
|
||||
// sendErr 保存图片消息发送错误。
|
||||
if sendErr := e.sendImage(ctx, task, imageURL, card.ID); sendErr != nil {
|
||||
return sent, classifyMessageSendError(sendErr)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(content) != "" {
|
||||
// sendErr 保存文字消息发送错误。
|
||||
if sendErr := e.sendText(ctx, task, renderTemplate(content, task)); sendErr != nil {
|
||||
return sent, classifyMessageSendError(sendErr)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(content) == "" && strings.TrimSpace(imageURL) == "" {
|
||||
return sent, fmt.Errorf("卡密组 %d 没有可发送内容", card.ID)
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
// sendDataCard 在卡券锁内原子消费数据卡密,并在确定未发送时恢复库存。
|
||||
func (e *automationActionExecutor) sendDataCard(ctx context.Context, task Task, card *db.CardFull, count int) (int, error) {
|
||||
// unlock 释放当前卡密组的并发消费锁。
|
||||
unlock := e.lockCard(card.ID)
|
||||
defer unlock()
|
||||
// sent 是已经成功发送的数据卡密数量。
|
||||
sent := 0
|
||||
// i 表示当前数据卡密消费序号。
|
||||
for i := 0; i < count; i++ {
|
||||
// content 是从库存中原子消费出的数据卡密。
|
||||
content, err := e.store.Cards.ConsumeBatchData(ctx, card.ID)
|
||||
if err != nil {
|
||||
return sent, err
|
||||
}
|
||||
if strings.TrimSpace(content) != "" {
|
||||
// sendErr 保存数据卡密消息发送错误。
|
||||
if sendErr := e.sendText(ctx, task, renderTemplate(content, task)); sendErr != nil {
|
||||
if errors.Is(sendErr, ErrMessageNotSent) {
|
||||
// restoreErr 保存确定未发送时恢复库存的错误。
|
||||
if restoreErr := e.store.Cards.RestoreBatchData(ctx, card.ID, content); restoreErr != nil {
|
||||
return sent, uncertainAction(errors.Join(sendErr, fmt.Errorf("恢复未发送卡密库存: %w", restoreErr)))
|
||||
}
|
||||
return sent, sendErr
|
||||
}
|
||||
// 请求已交给传输层后无法判断远端是否收到,保留消费状态并人工核对。
|
||||
return sent, uncertainAction(sendErr)
|
||||
}
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
// sendText 向账号在线发送器发送文字消息,并保留确定未发送的错误标记。
|
||||
func (e *automationActionExecutor) sendText(ctx context.Context, task Task, text string) error {
|
||||
if task.ChatID == "" || task.BuyerID == "" {
|
||||
return fmt.Errorf("%w: 发送消息缺少 chat_id 或 buyer_id", ErrMessageNotSent)
|
||||
}
|
||||
if e.senders == nil {
|
||||
return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent)
|
||||
}
|
||||
// sender 是当前账号的在线消息发送器。
|
||||
// senderOK 表示是否找到在线发送器。
|
||||
sender, senderOK := e.senders.Sender(task.AccountID)
|
||||
if !senderOK {
|
||||
return fmt.Errorf("%w: 账号未在线,无法发送自动化消息", ErrMessageNotSent)
|
||||
}
|
||||
return sender.SendText(ctx, task.ChatID, task.BuyerID, text)
|
||||
}
|
||||
|
||||
// sendImage 向账号在线发送器发送图片消息,并标记关联卡密组。
|
||||
func (e *automationActionExecutor) sendImage(ctx context.Context, task Task, imageURL string, cardID int64) error {
|
||||
if task.ChatID == "" || task.BuyerID == "" {
|
||||
return fmt.Errorf("%w: 发送图片缺少 chat_id 或 buyer_id", ErrMessageNotSent)
|
||||
}
|
||||
if e.senders == nil {
|
||||
return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent)
|
||||
}
|
||||
// sender 是当前账号的在线图片发送器。
|
||||
// senderOK 表示是否找到在线发送器。
|
||||
sender, senderOK := e.senders.Sender(task.AccountID)
|
||||
if !senderOK {
|
||||
return fmt.Errorf("%w: 账号未在线,无法发送自动化图片", ErrMessageNotSent)
|
||||
}
|
||||
return sender.SendImage(ctx, task.ChatID, task.BuyerID, imageURL, cardID)
|
||||
}
|
||||
|
||||
// cardContent 读取卡密组内容并拒绝不支持的卡密类型。
|
||||
func (e *automationActionExecutor) cardContent(_ context.Context, card *db.CardFull) (text, imageURL string, err error) {
|
||||
switch card.Type {
|
||||
case "text":
|
||||
if strings.TrimSpace(card.TextContent) == "" {
|
||||
return "", "", fmt.Errorf("文本卡密组缺少内容")
|
||||
}
|
||||
return card.TextContent, "", nil
|
||||
case "data":
|
||||
return "", "", fmt.Errorf("data 卡密必须通过 sendDataCard 发送")
|
||||
case "image":
|
||||
if strings.TrimSpace(card.ImageURL) == "" {
|
||||
return "", "", fmt.Errorf("图片卡密组缺少图片 URL")
|
||||
}
|
||||
return "", card.ImageURL, nil
|
||||
case "api":
|
||||
return "", "", fmt.Errorf("自动化中心暂不支持 API 卡密动作")
|
||||
default:
|
||||
return "", "", fmt.Errorf("未知卡密类型: %s", card.Type)
|
||||
}
|
||||
}
|
||||
|
||||
// cookieValue 读取账号 Cookie,优先使用测试或运行时覆盖的数据源。
|
||||
func (e *automationActionExecutor) cookieValue(ctx context.Context, cookieID string) (string, error) {
|
||||
return e.cookieSource(ctx, cookieID)
|
||||
}
|
||||
|
||||
// lockCard 获取指定卡密组的进程内互斥锁。
|
||||
func (e *automationActionExecutor) lockCard(cardID int64) func() {
|
||||
// raw 是按卡密组 ID 保存的锁实例。
|
||||
raw, _ := e.cardLocks.LoadOrStore(cardID, &sync.Mutex{})
|
||||
// mu 是当前卡密组的互斥锁。
|
||||
mu := raw.(*sync.Mutex)
|
||||
mu.Lock()
|
||||
return mu.Unlock
|
||||
}
|
||||
|
||||
// actionMatchesOrderSpec 判断动作配置的规格是否匹配订单。
|
||||
func actionMatchesOrderSpec(task Task, action db.AutomationAction) bool {
|
||||
// cfg 保存卡密动作的规格过滤配置。
|
||||
var cfg struct {
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
}
|
||||
if json.Unmarshal([]byte(action.ConfigJSON), &cfg) != nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(cfg.SpecName) == "" && strings.TrimSpace(cfg.SpecValue) == "" {
|
||||
return true
|
||||
}
|
||||
return strings.TrimSpace(task.SpecName) == strings.TrimSpace(cfg.SpecName) &&
|
||||
strings.TrimSpace(task.SpecValue) == strings.TrimSpace(cfg.SpecValue)
|
||||
}
|
||||
|
||||
// deliverySendCount 根据动作单份数量和订单购买数量计算实际发送数量。
|
||||
func deliverySendCount(task Task, action db.AutomationAction) int {
|
||||
// perUnit 是每个购买单位对应的卡密数量。
|
||||
perUnit := action.DeliveryCount
|
||||
if perUnit <= 0 {
|
||||
perUnit = 1
|
||||
}
|
||||
// qty 是订单购买数量。
|
||||
qty := parsePositiveInt(task.Quantity)
|
||||
if qty <= 0 {
|
||||
qty = 1
|
||||
}
|
||||
return perUnit * qty
|
||||
}
|
||||
|
||||
// parsePositiveInt 将数量文本解析为非负整数,非法值返回零。
|
||||
func parsePositiveInt(raw string) int {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return 0
|
||||
}
|
||||
// n 是解析后的数量值。
|
||||
// err 是数量文本解析错误。
|
||||
// n 是解析后的数量值。
|
||||
// parseErr 是数量文本解析错误。
|
||||
n, parseErr := strconv.Atoi(raw)
|
||||
if parseErr != nil || n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// classifyMessageSendError 将消息发送错误统一分类为确定未发送或结果未知。
|
||||
func classifyMessageSendError(err error) error {
|
||||
if err == nil || errors.Is(err, ErrMessageNotSent) {
|
||||
return err
|
||||
}
|
||||
return uncertainAction(err)
|
||||
}
|
||||
|
||||
// renderTemplate 替换自动化消息模板中的订单字段。
|
||||
func renderTemplate(tpl string, task Task) string {
|
||||
// out 是经过字段替换后的模板文本。
|
||||
out := tpl
|
||||
// repl 保存模板占位符与订单字段的映射。
|
||||
repl := map[string]string{
|
||||
"{order_id}": task.OrderID,
|
||||
"{item_id}": task.ItemID,
|
||||
"{buyer_id}": task.BuyerID,
|
||||
"{chat_id}": task.ChatID,
|
||||
"{trigger_type}": task.TriggerType,
|
||||
"{spec_name}": task.SpecName,
|
||||
"{spec_value}": task.SpecValue,
|
||||
"{quantity}": task.Quantity,
|
||||
"{amount}": task.Amount,
|
||||
}
|
||||
// key 和 value 分别表示当前占位符及其替换值。
|
||||
for key, value := range repl {
|
||||
out = strings.ReplaceAll(out, key, value)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestAutomationActionExecutorPreservesMessageNotSent 验证动作执行器保留“确定未发送”错误,供运行协调器安全重试。
|
||||
func TestAutomationActionExecutorPreservesMessageNotSent(t *testing.T) {
|
||||
// sender 是返回确定未发送错误的测试发送器。
|
||||
sender := &testSender{err: fmt.Errorf("%w: websocket 尚未就绪", ErrMessageNotSent)}
|
||||
// executor 是仅注入消息发送器的动作执行器。
|
||||
executor := automationActionExecutor{senders: testSenderProvider{sender: sender}}
|
||||
// sent 是动作执行器报告的已发送数量。
|
||||
sent, err := executor.executeAction(context.Background(), Task{
|
||||
AccountID: "cid",
|
||||
ChatID: "chat",
|
||||
BuyerID: "buyer",
|
||||
}, db.AutomationAction{ActionType: ActionSendText, MessageTemplate: "hello"})
|
||||
if sent != 0 || !errors.Is(err, ErrMessageNotSent) {
|
||||
t.Fatalf("确定未发送错误未保留: sent=%d err=%v", sent, err)
|
||||
}
|
||||
}
|
||||
+55
-371
@@ -12,7 +12,6 @@ import (
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
@@ -93,17 +92,20 @@ type Center struct {
|
||||
// planner 生成不可变动作计划,不执行外部 I/O。
|
||||
planner actionPlanner
|
||||
// runs 协调自动化运行创建、动作检查点、延迟恢复和结果隔离。
|
||||
runs automationRunCoordinator
|
||||
store *db.Store
|
||||
senders SenderProvider
|
||||
fetcher OrderDetailFetcher
|
||||
recoverer CredentialRecoverer
|
||||
notifier Notifier
|
||||
mtop mtop.Client
|
||||
accountTasks AccountTaskClient
|
||||
logger *slog.Logger
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
cardLocks sync.Map
|
||||
runs automationRunCoordinator
|
||||
// actions 执行确认发货、卡密和消息动作,集中维护外部副作用边界。
|
||||
actions automationActionExecutor
|
||||
// notifications 负责把运行结果转换为可选的发货通知。
|
||||
notifications deliveryNotifier
|
||||
store *db.Store
|
||||
senders SenderProvider
|
||||
fetcher OrderDetailFetcher
|
||||
recoverer CredentialRecoverer
|
||||
notifier Notifier
|
||||
mtop mtop.Client
|
||||
accountTasks AccountTaskClient
|
||||
logger *slog.Logger
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
// sessionExpired 保存检测到 Session 失效时的凭证指纹。在凭证续期或
|
||||
// 重新登录真正改变之前,账号任务不得再次调用任何 MTOP 业务接口。
|
||||
sessionExpired sync.Map
|
||||
@@ -125,6 +127,29 @@ func New(store *db.Store, senders SenderProvider, logger *slog.Logger) *Center {
|
||||
accountTasks: client,
|
||||
logger: logger.With("subsys", "automation"),
|
||||
}
|
||||
center.actions = automationActionExecutor{
|
||||
store: store,
|
||||
senders: senders,
|
||||
mtop: func() mtop.Client {
|
||||
return center.mtop
|
||||
},
|
||||
recoverer: func() CredentialRecoverer {
|
||||
return center.recoverer
|
||||
},
|
||||
logger: center.logger,
|
||||
cookieSource: func(ctx context.Context, cookieID string) (string, error) {
|
||||
if center.cookieSrc != nil {
|
||||
return center.cookieSrc(ctx, cookieID)
|
||||
}
|
||||
return center.store.Cookies.GetValue(ctx, cookieID)
|
||||
},
|
||||
wakeCredentialBlocked: center.wakeCredentialBlockedAutomation,
|
||||
}
|
||||
center.notifications = deliveryNotifier{
|
||||
current: func() Notifier {
|
||||
return center.notifier
|
||||
},
|
||||
}
|
||||
center.runs = automationRunCoordinator{
|
||||
store: store,
|
||||
planner: center.planner,
|
||||
@@ -419,32 +444,14 @@ func (c *Center) executeRunActions(ctx context.Context, task Task, ruleID int64,
|
||||
// notifyResult 根据规则执行结果发送通知。成功且实际发出了内容才通知,
|
||||
// 避免无匹配动作的空跑刷屏;失败时发失败通知。
|
||||
func (c *Center) notifyResult(task Task, status string, sent int, errMsg string) {
|
||||
triggerName := map[string]string{
|
||||
TriggerOrderPaid: "付款发货",
|
||||
TriggerBuyerReviewed: "评价赠品",
|
||||
TriggerReviewMissingTimeout: "求评价",
|
||||
}[task.TriggerType]
|
||||
if triggerName == "" {
|
||||
triggerName = task.TriggerType
|
||||
}
|
||||
if status == "success" {
|
||||
if sent <= 0 {
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("✅ %s成功(订单 %s,已发送 %d 条)", triggerName, task.OrderID, sent)
|
||||
c.notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, msg, task.ChatID)
|
||||
return
|
||||
}
|
||||
msg := fmt.Sprintf("🚨 %s失败(订单 %s):%s", triggerName, task.OrderID, errMsg)
|
||||
c.notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, msg, task.ChatID)
|
||||
c.notifications.notifyResult(task, status, sent, errMsg)
|
||||
}
|
||||
|
||||
func (c *Center) notifyRunNeedsReview(run db.AutomationRun, reason string) {
|
||||
if c == nil || c.notifier == nil {
|
||||
if c == nil {
|
||||
return
|
||||
}
|
||||
task := Task{AccountID: run.CookieID, BuyerID: run.BuyerID, ItemID: run.ItemID, ChatID: run.ChatID, OrderID: run.OrderID, TriggerType: run.TriggerType}
|
||||
c.notifyResult(task, "needs_review", run.SentCount, "需要人工核对:"+reason)
|
||||
c.notifications.notifyRunNeedsReview(run, reason)
|
||||
}
|
||||
|
||||
// actionDelaySeconds 统一卡密默认延时和动作覆盖语义。旧动作没有
|
||||
@@ -567,162 +574,17 @@ func mergeOrderIntoTask(task Task, order *db.Order) Task {
|
||||
return task
|
||||
}
|
||||
|
||||
// executeAction 将具体动作委托给发货动作执行器。
|
||||
func (c *Center) executeAction(ctx context.Context, task Task, action db.AutomationAction) (int, error) {
|
||||
switch action.ActionType {
|
||||
case ActionConfirmShipment:
|
||||
return 0, c.confirmShipment(ctx, task)
|
||||
case ActionSendCard:
|
||||
return c.sendCard(ctx, task, action)
|
||||
case ActionSendText:
|
||||
text := renderTemplate(action.MessageTemplate, task)
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return 0, nil
|
||||
}
|
||||
if err := c.sendText(ctx, task, text); err != nil {
|
||||
if errors.Is(err, ErrMessageNotSent) {
|
||||
return 0, err
|
||||
}
|
||||
return 0, uncertainAction(err)
|
||||
}
|
||||
return 1, nil
|
||||
default:
|
||||
return 0, fmt.Errorf("未知自动化动作: %s", action.ActionType)
|
||||
}
|
||||
return c.actions.executeAction(ctx, task, action)
|
||||
}
|
||||
|
||||
// confirmShipment 将确认发货委托给发货动作执行器。
|
||||
func (c *Center) confirmShipment(ctx context.Context, task Task) error {
|
||||
if task.OrderID == "" {
|
||||
return fmt.Errorf("确认发货缺少订单ID")
|
||||
}
|
||||
enabled, err := c.store.Cookies.GetAutoConfirm(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取自动确认发货设置: %w", err)
|
||||
}
|
||||
if !enabled && !task.ForceConfirmShipment {
|
||||
return nil
|
||||
}
|
||||
return c.confirmShipmentAttempt(ctx, task, true)
|
||||
}
|
||||
|
||||
func (c *Center) confirmShipmentAttempt(ctx context.Context, task Task, allowCredentialRecovery bool) error {
|
||||
credentialUnlock := c.store.LockAccountCredentials(task.AccountID)
|
||||
credentialLocked := true
|
||||
defer func() {
|
||||
if credentialLocked {
|
||||
credentialUnlock()
|
||||
}
|
||||
}()
|
||||
// runtimeData 是确认发货所需的最小 Cookie 与 metadata 运行视图,不包含登录密码和账号资料。
|
||||
runtimeData, err := c.store.Cookies.GetCookieRuntimeData(ctx, task.AccountID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// runtimeData 已在凭证锁内读取;这里只根据完整快照判断空 Cookie 的合法性。
|
||||
// completeSnapshot 表示 metadata 中是否包含可恢复的完整 Cookie Jar。
|
||||
_, completeSnapshot := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON)
|
||||
if strings.TrimSpace(runtimeData.Value) == "" && !completeSnapshot {
|
||||
return fmt.Errorf("账号 %s Cookie 为空", task.AccountID)
|
||||
}
|
||||
cookieStr := runtimeData.Value
|
||||
var mtopCtx context.Context
|
||||
var cookieSession *mtop.CookieSession
|
||||
if snapshot, ok := cookierefresh.SnapshotFromMetadataOK(runtimeData.MetadataJSON); ok {
|
||||
mtopCtx, cookieSession = mtop.WithCookieSnapshot(ctx, snapshot)
|
||||
} else {
|
||||
mtopCtx, cookieSession = mtop.WithFlatCookieSession(ctx, cookieStr)
|
||||
}
|
||||
ok, ret, updated, callErr := c.mtop.ConsignContext(mtopCtx, cookieStr, task.OrderID)
|
||||
var persistenceErrs []error
|
||||
runtimeCookie := ""
|
||||
runtimeCookieChanged := false
|
||||
value, snapshot, changed := cookieSession.State()
|
||||
// 完整 Jar 已接管时,即使响应没有 Cookie 变化,也不能因扁平字符串
|
||||
// 格式差异回退覆盖并清除 Jar。
|
||||
sessionHandled := snapshot != nil
|
||||
if changed {
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON)
|
||||
if snapshot != nil {
|
||||
metadata = cookierefresh.MetadataWithSnapshot(runtimeData.MetadataJSON, snapshot)
|
||||
}
|
||||
if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, value, metadata, time.Now().Unix()); saveErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存确认发货响应 Cookie Jar: %w", saveErr))
|
||||
} else if value != cookieStr {
|
||||
runtimeCookie = value
|
||||
runtimeCookieChanged = true
|
||||
}
|
||||
}
|
||||
if !sessionHandled && callErr == nil && updated != "" && updated != cookieStr {
|
||||
// 注入 mock 或没有权威快照的历史账号保留扁平
|
||||
// Cookie 兼容路径;扁平结果无法维护旧 Jar 的作用域,
|
||||
// 因此不得继续保留可能已过期的 snapshot。
|
||||
metadata := cookierefresh.MetadataWithoutSnapshot(runtimeData.MetadataJSON)
|
||||
if saveErr := c.store.Cookies.UpdateRenewalCookie(ctx, task.AccountID, updated, metadata, time.Now().Unix()); saveErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存刷新后的 Cookie: %w", saveErr))
|
||||
} else {
|
||||
runtimeCookie = updated
|
||||
runtimeCookieChanged = true
|
||||
}
|
||||
}
|
||||
credentialUnlock()
|
||||
credentialLocked = false
|
||||
if runtimeCookieChanged && c.senders != nil {
|
||||
if sender, running := c.senders.Sender(task.AccountID); running {
|
||||
sender.UpdateCookie(runtimeCookie)
|
||||
}
|
||||
}
|
||||
if runtimeCookieChanged {
|
||||
c.wakeCredentialBlockedAutomation(ctx, task.AccountID)
|
||||
}
|
||||
sessionErr := callErr
|
||||
if sessionErr == nil && !ok {
|
||||
sessionErr = errors.New(strings.Join(ret, "; "))
|
||||
}
|
||||
if mtop.IsSessionExpiredErr(sessionErr) {
|
||||
if len(persistenceErrs) > 0 {
|
||||
return errors.Join(fmt.Errorf("确认发货 Session 已失效: %w", sessionErr), errors.Join(persistenceErrs...))
|
||||
}
|
||||
if allowCredentialRecovery && c.recoverer != nil && c.recoverer.RecoverExpiredCredential(ctx, task.AccountID) {
|
||||
c.logger.Info("确认发货凭证恢复成功,重新执行确认发货", "account", task.AccountID, "order_id", task.OrderID)
|
||||
return c.confirmShipmentAttempt(ctx, task, false)
|
||||
}
|
||||
if !allowCredentialRecovery {
|
||||
return fmt.Errorf("%w: 确认发货在凭证恢复后仍返回 Session 失效: %v", errActionNotPerformed, sessionErr)
|
||||
}
|
||||
return fmt.Errorf("%w: 确认发货 Session 已失效且凭证恢复失败: %v", errActionNotPerformed, sessionErr)
|
||||
}
|
||||
if callErr != nil {
|
||||
if len(persistenceErrs) > 0 {
|
||||
callErr = errors.Join(callErr, errors.Join(persistenceErrs...))
|
||||
}
|
||||
return uncertainAction(callErr)
|
||||
}
|
||||
if !ok {
|
||||
failure := fmt.Errorf("确认发货失败: %s", strings.Join(ret, "; "))
|
||||
if len(persistenceErrs) > 0 {
|
||||
return errors.Join(failure, errors.Join(persistenceErrs...))
|
||||
}
|
||||
return failure
|
||||
}
|
||||
sysShip := true
|
||||
if upsertErr := c.store.Orders.Upsert(ctx, task.OrderID, db.OrderUpsertOpts{
|
||||
CookieID: task.AccountID,
|
||||
ItemID: task.ItemID,
|
||||
BuyerID: task.BuyerID,
|
||||
ChatID: task.ChatID,
|
||||
OrderStatus: "shipped",
|
||||
SystemShipped: &sysShip,
|
||||
}); upsertErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存本地订单发货状态: %w", upsertErr))
|
||||
}
|
||||
if eventErr := c.store.Automation.MarkOrderEventTime(ctx, task.OrderID, "shipped_at"); eventErr != nil {
|
||||
persistenceErrs = append(persistenceErrs, fmt.Errorf("保存订单发货时间: %w", eventErr))
|
||||
}
|
||||
if len(persistenceErrs) > 0 {
|
||||
return uncertainAction(fmt.Errorf("闲鱼已确认发货,但本地状态保存失败: %w", errors.Join(persistenceErrs...)))
|
||||
}
|
||||
return nil
|
||||
return c.actions.confirmShipment(ctx, task)
|
||||
}
|
||||
|
||||
// wakeCredentialBlockedAutomation 在 Cookie 更新后唤醒凭证阻塞的自动化任务。
|
||||
func (c *Center) wakeCredentialBlockedAutomation(ctx context.Context, accountID string) {
|
||||
if c == nil || c.store == nil || c.store.Automation == nil {
|
||||
return
|
||||
@@ -732,81 +594,12 @@ func (c *Center) wakeCredentialBlockedAutomation(ctx context.Context, accountID
|
||||
}
|
||||
}
|
||||
|
||||
// sendCard 将卡密发送委托给发货动作执行器。
|
||||
func (c *Center) sendCard(ctx context.Context, task Task, action db.AutomationAction) (int, error) {
|
||||
if !actionMatchesOrderSpec(task, action) {
|
||||
return 0, nil
|
||||
}
|
||||
if action.CardID <= 0 {
|
||||
return 0, fmt.Errorf("发送卡密动作缺少卡密组ID")
|
||||
}
|
||||
count := deliverySendCount(task, action)
|
||||
card, err := c.store.Cards.Get(ctx, action.CardID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if !card.Enabled {
|
||||
return 0, fmt.Errorf("卡密组 %d 已停用", card.ID)
|
||||
}
|
||||
if card.Type == "data" {
|
||||
return c.sendDataCard(ctx, task, card, count)
|
||||
}
|
||||
sent := 0
|
||||
for i := 0; i < count; i++ {
|
||||
content, imageURL, err := c.cardContent(ctx, card)
|
||||
if err != nil {
|
||||
return sent, err
|
||||
}
|
||||
if imageURL != "" {
|
||||
if err := c.sendImage(ctx, task, imageURL, card.ID); err != nil {
|
||||
return sent, classifyMessageSendError(err)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(content) != "" {
|
||||
if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil {
|
||||
return sent, classifyMessageSendError(err)
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(content) == "" && strings.TrimSpace(imageURL) == "" {
|
||||
return sent, fmt.Errorf("卡密组 %d 没有可发送内容", card.ID)
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func (c *Center) sendDataCard(ctx context.Context, task Task, card *db.CardFull, count int) (int, error) {
|
||||
unlock := c.lockCard(card.ID)
|
||||
defer unlock()
|
||||
sent := 0
|
||||
for i := 0; i < count; i++ {
|
||||
content, err := c.store.Cards.ConsumeBatchData(ctx, card.ID)
|
||||
if err != nil {
|
||||
return sent, err
|
||||
}
|
||||
if strings.TrimSpace(content) != "" {
|
||||
if err := c.sendText(ctx, task, renderTemplate(content, task)); err != nil {
|
||||
if errors.Is(err, ErrMessageNotSent) {
|
||||
if restoreErr := c.store.Cards.RestoreBatchData(ctx, card.ID, content); restoreErr != nil {
|
||||
return sent, uncertainAction(errors.Join(err, fmt.Errorf("恢复未发送卡密库存: %w", restoreErr)))
|
||||
}
|
||||
return sent, err
|
||||
}
|
||||
// 请求已经交给传输层后无法判断远端是否收到,保留消费状态并人工核对。
|
||||
return sent, uncertainAction(err)
|
||||
}
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func classifyMessageSendError(err error) error {
|
||||
if err == nil || errors.Is(err, ErrMessageNotSent) {
|
||||
return err
|
||||
}
|
||||
return uncertainAction(err)
|
||||
return c.actions.sendCard(ctx, task, action)
|
||||
}
|
||||
|
||||
// accountAutomationAllowed 判断账号是否仍允许执行自动化动作。
|
||||
func (c *Center) accountAutomationAllowed(ctx context.Context, accountID string) (bool, error) {
|
||||
paused, _, err := c.store.Cookies.IsPaused(ctx, accountID)
|
||||
if err != nil {
|
||||
@@ -819,6 +612,7 @@ func (c *Center) accountAutomationAllowed(ctx context.Context, accountID string)
|
||||
return !paused && enabled, nil
|
||||
}
|
||||
|
||||
// accountSenderReady 判断账号是否具备可发送自动化消息的在线连接。
|
||||
func (c *Center) accountSenderReady(accountID string) bool {
|
||||
if c == nil || c.senders == nil {
|
||||
return false
|
||||
@@ -833,110 +627,19 @@ func (c *Center) accountSenderReady(accountID string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
func (c *Center) lockCard(cardID int64) func() {
|
||||
raw, _ := c.cardLocks.LoadOrStore(cardID, &sync.Mutex{})
|
||||
mu := raw.(*sync.Mutex)
|
||||
mu.Lock()
|
||||
return mu.Unlock
|
||||
}
|
||||
|
||||
func actionMatchesOrderSpec(task Task, action db.AutomationAction) bool {
|
||||
var cfg struct {
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
}
|
||||
if json.Unmarshal([]byte(action.ConfigJSON), &cfg) != nil {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(cfg.SpecName) == "" && strings.TrimSpace(cfg.SpecValue) == "" {
|
||||
return true
|
||||
}
|
||||
return strings.TrimSpace(task.SpecName) == strings.TrimSpace(cfg.SpecName) &&
|
||||
strings.TrimSpace(task.SpecValue) == strings.TrimSpace(cfg.SpecValue)
|
||||
}
|
||||
|
||||
func deliverySendCount(task Task, action db.AutomationAction) int {
|
||||
perUnit := action.DeliveryCount
|
||||
if perUnit <= 0 {
|
||||
perUnit = 1
|
||||
}
|
||||
qty := parsePositiveInt(task.Quantity)
|
||||
if qty <= 0 {
|
||||
qty = 1
|
||||
}
|
||||
return perUnit * qty
|
||||
}
|
||||
|
||||
func parsePositiveInt(raw string) int {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return 0
|
||||
}
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 0 {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
// cardContent 获取卡密组内容的兼容入口。
|
||||
func (c *Center) cardContent(ctx context.Context, card *db.CardFull) (text, imageURL string, err error) {
|
||||
switch card.Type {
|
||||
case "text":
|
||||
if strings.TrimSpace(card.TextContent) == "" {
|
||||
return "", "", fmt.Errorf("文本卡密组缺少内容")
|
||||
}
|
||||
return card.TextContent, "", nil
|
||||
case "data":
|
||||
return "", "", fmt.Errorf("data 卡密必须通过 sendDataCard 发送")
|
||||
case "image":
|
||||
if strings.TrimSpace(card.ImageURL) == "" {
|
||||
return "", "", fmt.Errorf("图片卡密组缺少图片 URL")
|
||||
}
|
||||
return "", card.ImageURL, nil
|
||||
case "api":
|
||||
return "", "", fmt.Errorf("自动化中心暂不支持 API 卡密动作")
|
||||
default:
|
||||
return "", "", fmt.Errorf("未知卡密类型: %s", card.Type)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Center) sendText(ctx context.Context, task Task, text string) error {
|
||||
if task.ChatID == "" || task.BuyerID == "" {
|
||||
return fmt.Errorf("%w: 发送消息缺少 chat_id 或 buyer_id", ErrMessageNotSent)
|
||||
}
|
||||
if c.senders == nil {
|
||||
return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent)
|
||||
}
|
||||
sender, ok := c.senders.Sender(task.AccountID)
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: 账号未在线,无法发送自动化消息", ErrMessageNotSent)
|
||||
}
|
||||
return sender.SendText(ctx, task.ChatID, task.BuyerID, text)
|
||||
return c.actions.cardContent(ctx, card)
|
||||
}
|
||||
|
||||
// sendImage 将图片消息发送委托给发货动作执行器。
|
||||
func (c *Center) sendImage(ctx context.Context, task Task, imageURL string, cardID int64) error {
|
||||
if task.ChatID == "" || task.BuyerID == "" {
|
||||
return fmt.Errorf("%w: 发送图片缺少 chat_id 或 buyer_id", ErrMessageNotSent)
|
||||
}
|
||||
if c.senders == nil {
|
||||
return fmt.Errorf("%w: 账号发送器未初始化", ErrMessageNotSent)
|
||||
}
|
||||
sender, ok := c.senders.Sender(task.AccountID)
|
||||
if !ok {
|
||||
return fmt.Errorf("%w: 账号未在线,无法发送自动化图片", ErrMessageNotSent)
|
||||
}
|
||||
return sender.SendImage(ctx, task.ChatID, task.BuyerID, imageURL, cardID)
|
||||
return c.actions.sendImage(ctx, task, imageURL, cardID)
|
||||
}
|
||||
|
||||
// cookieValue 读取账号 Cookie 的兼容入口。
|
||||
func (c *Center) cookieValue(ctx context.Context, cookieID string) (string, error) {
|
||||
if c.cookieSrc != nil {
|
||||
return c.cookieSrc(ctx, cookieID)
|
||||
}
|
||||
value, err := c.store.Cookies.GetValue(ctx, cookieID) // value 是只读取账号 Cookie 明文的单值结果,不会展开完整账号详情。
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return value, nil
|
||||
return c.actions.cookieValue(ctx, cookieID)
|
||||
}
|
||||
|
||||
func buildTriggerKey(task Task) string {
|
||||
@@ -953,22 +656,3 @@ func buildTriggerKey(task Task) string {
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func renderTemplate(tpl string, task Task) string {
|
||||
out := tpl
|
||||
repl := map[string]string{
|
||||
"{order_id}": task.OrderID,
|
||||
"{item_id}": task.ItemID,
|
||||
"{buyer_id}": task.BuyerID,
|
||||
"{chat_id}": task.ChatID,
|
||||
"{trigger_type}": task.TriggerType,
|
||||
"{spec_name}": task.SpecName,
|
||||
"{spec_value}": task.SpecValue,
|
||||
"{quantity}": task.Quantity,
|
||||
"{amount}": task.Amount,
|
||||
}
|
||||
for k, v := range repl {
|
||||
out = strings.ReplaceAll(out, k, v)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// deliveryNotifier 将自动化运行状态转换为可选的多渠道发货结果通知,并通过回调读取运行时替换的通知器。
|
||||
type deliveryNotifier struct {
|
||||
// current 返回当前生效的通知器实例。
|
||||
current func() Notifier
|
||||
}
|
||||
|
||||
// notifyResult 根据规则执行结果发送通知,成功且实际发出内容时才发送成功通知。
|
||||
func (n deliveryNotifier) notifyResult(task Task, status string, sent int, errMsg string) {
|
||||
// notifier 是当前可选的外部通知器。
|
||||
notifier := n.current()
|
||||
if notifier == nil {
|
||||
return
|
||||
}
|
||||
// triggerName 是面向用户展示的自动化触发类型名称。
|
||||
triggerName := map[string]string{
|
||||
TriggerOrderPaid: "付款发货",
|
||||
TriggerBuyerReviewed: "评价赠品",
|
||||
TriggerReviewMissingTimeout: "求评价",
|
||||
}[task.TriggerType]
|
||||
if triggerName == "" {
|
||||
triggerName = task.TriggerType
|
||||
}
|
||||
if status == "success" {
|
||||
if sent <= 0 {
|
||||
return
|
||||
}
|
||||
// message 是成功通知正文。
|
||||
message := fmt.Sprintf("✅ %s成功(订单 %s,已发送 %d 条)", triggerName, task.OrderID, sent)
|
||||
notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, message, task.ChatID)
|
||||
return
|
||||
}
|
||||
// message 是失败或人工核对通知正文。
|
||||
message := fmt.Sprintf("🚨 %s失败(订单 %s):%s", triggerName, task.OrderID, errMsg)
|
||||
notifier.NotifyDelivery(task.AccountID, "", task.BuyerID, task.ItemID, message, task.ChatID)
|
||||
}
|
||||
|
||||
// notifyRunNeedsReview 通知运行需要人工核对,并复用统一结果通知格式。
|
||||
func (n deliveryNotifier) notifyRunNeedsReview(run db.AutomationRun, reason string) {
|
||||
if n.current() == nil {
|
||||
return
|
||||
}
|
||||
// task 是从运行快照构造出的最小通知上下文。
|
||||
task := Task{
|
||||
AccountID: run.CookieID,
|
||||
BuyerID: run.BuyerID,
|
||||
ItemID: run.ItemID,
|
||||
ChatID: run.ChatID,
|
||||
OrderID: run.OrderID,
|
||||
TriggerType: run.TriggerType,
|
||||
}
|
||||
n.notifyResult(task, "needs_review", run.SentCount, "需要人工核对:"+reason)
|
||||
}
|
||||
Reference in new issue
Block a user