Files
Ydisks-Xianyu-Helper/internal/server/automation_handlers.go
T
Christ 16d63dc7c9 完善系统可靠性、登录风控与跨数据库回归
可靠性与数据一致性:为 SQLite、MySQL、PostgreSQL 增加 00017 至 00021 迁移,引入账号暂停时间、默认回复和批量铺货租约、自动化运行恢复、延迟任务、动作检查点与通知 outbox。补强订单、卡密发货、Cookie、批量铺货和自动化任务的原子认领、幂等更新、并发控制、失败分类、重试与进程重启恢复,并扩展跨方言覆盖。

登录与风控恢复:完善扫码、密码登录、Cookie 续期、MTOP token、UA 与 WebSocket 生命周期;加入账号级持久化浏览器目录、Playwright 主引擎和直接 Chromium/CDP 备用引擎、严格的新 x5sec 成功判定、失败控件恢复及真实浏览器集成测试。增加可配置远程滑块服务,在明确失败、链接过期和服务不可用场景中保持既定的本地回退语义。

安全与配置:通过 XIANYU_DATA_KEY 为 Cookie、登录密码、设备与访问令牌、AI/SMTP 密钥及通知配置提供 AES-256-GCM 落库加密和历史明文升级。新增出站网络目标分级、防 DNS rebinding、登录限流、HTTP 客户端超时与 SMTP 目标校验;管理员配置的 AI 服务允许可信内网地址,非可信 Webhook 和远程资源继续限制为公网目标。

自动化与通知:为发货、评价赠送、邀评和回复动作增加断点、租约、延迟执行及人工继续/重试/取消入口;通知改为 outbox 驱动的可恢复投递。同步完善账号运行态、暂停状态、续期冷却、告警审计和异常查询接口。

前端体验:新增风控验证面板、方形二维码、账号运行态合并、暂停状态保护、自动化异常处置、批量铺货状态选择、订单导入结果和最新请求门禁。完善订单搜索与导入、规则编辑、批次恢复、通知与设置页面,并为请求取消、超时、陈旧响应和主要状态转换补充 Vitest 覆盖。

测试与部署:扩展三库功能编排、SQLite 一致性备份、数据卷持久化、浏览器集成镜像、前端类型检查和构建资产分包;功能测试覆盖健康检查、订单、铺货、自动化异常、账号暂停、关键词和系统设置。更新 README 中数据密钥、可信 AI 地址和测试端口说明。

验证结果:go vet ./...、go build ./cmd/server、gofmt 检查、npm run typecheck、npm test(17 个文件、95 个用例)及 npm run build 通过。go test ./... 未完全通过:internal/adapter 仍有 2 个密码续期用例失败,internal/renewal 仍有 4 个浏览器续期调度用例失败;其余 Go 包通过,失败现状随本次既有工作区一并提交。
2026-07-14 21:20:22 +08:00

337 lines
12 KiB
Go

package server
import (
"encoding/json"
"errors"
"net/http"
"strconv"
"strings"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/automation"
"xianyu-go/internal/db"
)
func (s *Server) mountAutomation(r chi.Router) {
r.Get("/automation-rules", s.listAutomationRules)
r.Post("/automation-rules", s.createAutomationRule)
r.Put("/automation-rules/{rule_id}", s.updateAutomationRule)
r.Delete("/automation-rules/{rule_id}", s.deleteAutomationRule)
r.Get("/automation-issues", s.listAutomationIssues)
r.Post("/automation-runs/{run_id}/resolve", s.resolveAutomationRun)
r.Post("/automation-pending-tasks/{task_id}/resolve", s.resolveDeferredAutomationTask)
}
func (s *Server) listAutomationIssues(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
runs, tasks, err := s.Store.Automation.ListIssues(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化异常任务失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"runs": runs, "pending_tasks": tasks})
}
func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
runID, err := strconv.ParseInt(chi.URLParam(r, "run_id"), 10, 64)
if err != nil || runID <= 0 {
writeErr(w, http.StatusBadRequest, "无效运行ID")
return
}
var req struct {
Resolution string `json:"resolution"`
}
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
sess := auth.SessionFromContext(r.Context())
if err := s.Store.Automation.ResolveRunIssue(r.Context(), sess.UserID, runID, strings.TrimSpace(req.Resolution)); err != nil {
if errors.Is(err, db.ErrNotFound) {
writeErr(w, http.StatusNotFound, "异常运行不存在或已处理")
return
}
writeErr(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Request) {
taskID, err := strconv.ParseInt(chi.URLParam(r, "task_id"), 10, 64)
if err != nil || taskID <= 0 {
writeErr(w, http.StatusBadRequest, "无效任务ID")
return
}
var req struct {
Resolution string `json:"resolution"`
}
if err := decodeJSON(r, &req); err != nil || (req.Resolution != "retry" && req.Resolution != "dismiss") {
writeErr(w, http.StatusBadRequest, "处理方式必须是 retry 或 dismiss")
return
}
sess := auth.SessionFromContext(r.Context())
if err := s.Store.Automation.ResolveDeferredIssue(r.Context(), sess.UserID, taskID, req.Resolution == "retry"); err != nil {
writeErr(w, http.StatusNotFound, "异常任务不存在或已处理")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
type automationActionRequest struct {
ActionType string `json:"action_type"`
CardID int64 `json:"card_id"`
DeliveryCount int `json:"delivery_count"`
MessageTemplate string `json:"message_template"`
DelaySeconds int `json:"delay_seconds"`
ConfigJSON string `json:"config_json"`
Enabled *bool `json:"enabled"`
SortOrder int `json:"sort_order"`
}
type automationRuleRequest struct {
CookieID string `json:"cookie_id"`
ItemID string `json:"item_id"`
Name string `json:"name"`
TriggerType string `json:"trigger_type"`
Enabled bool `json:"enabled"`
Priority int `json:"priority"`
ConfigJSON string `json:"config_json"`
Actions []automationActionRequest `json:"actions"`
}
func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
rules, err := s.Store.Automation.ListForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询自动化规则失败")
return
}
out := make([]map[string]any, 0, len(rules))
for _, rule := range rules {
actions := make([]map[string]any, 0, len(rule.Actions))
for _, action := range rule.Actions {
actions = append(actions, map[string]any{
"id": action.ID, "action_type": action.ActionType, "card_id": action.CardID,
"card_name": action.CardName, "delivery_count": action.DeliveryCount,
"message_template": action.MessageTemplate, "delay_seconds": action.DelaySeconds,
"config_json": action.ConfigJSON, "enabled": action.Enabled, "sort_order": action.SortOrder,
})
}
out = append(out, map[string]any{
"id": rule.ID, "cookie_id": rule.CookieID, "item_id": rule.ItemID, "item_title": rule.ItemTitle,
"name": rule.Name, "trigger_type": rule.TriggerType, "enabled": rule.Enabled,
"priority": rule.Priority, "config_json": rule.ConfigJSON, "actions": actions,
"created_at": rule.CreatedAt, "updated_at": rule.UpdatedAt,
})
}
writeJSON(w, http.StatusOK, out)
}
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
var req automationRuleRequest
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
in, err := s.normalizeAutomationRuleRequest(r, sess.UserID, req)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
id, err := s.Store.Automation.Create(r.Context(), in)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建自动化规则失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id})
}
func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
sess := auth.SessionFromContext(r.Context())
var req automationRuleRequest
if err := decodeJSON(r, &req); err != nil {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
in, err := s.normalizeAutomationRuleRequest(r, sess.UserID, req)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
if err := s.Store.Automation.Update(r.Context(), sess.UserID, ruleID, in); err != nil {
if err == db.ErrNotFound {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
return
}
writeErr(w, http.StatusInternalServerError, "更新自动化规则失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
ruleID, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效规则ID")
return
}
sess := auth.SessionFromContext(r.Context())
if err := s.Store.Automation.Delete(r.Context(), sess.UserID, ruleID); err != nil {
if err == db.ErrNotFound {
writeErr(w, http.StatusNotFound, "自动化规则不存在")
return
}
if errors.Is(err, db.ErrAutomationRunActive) {
writeErr(w, http.StatusConflict, "规则仍有运行中或待人工处理的任务,处理完成后才能删除")
return
}
writeErr(w, http.StatusInternalServerError, "删除自动化规则失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, req automationRuleRequest) (db.AutomationRuleInput, error) {
req.CookieID = strings.TrimSpace(req.CookieID)
req.ItemID = strings.TrimSpace(req.ItemID)
req.Name = strings.TrimSpace(req.Name)
req.TriggerType = strings.TrimSpace(req.TriggerType)
switch req.TriggerType {
case automation.TriggerOrderPaid, automation.TriggerBuyerReviewed, automation.TriggerReviewMissingTimeout:
default:
return db.AutomationRuleInput{}, errStr("不支持的触发类型")
}
if req.CookieID == "" || !s.cookieOwnedByUser(r.Context(), userID, req.CookieID) {
return db.AutomationRuleInput{}, errStr("账号不存在或不属于当前用户")
}
if req.ItemID != "" && !s.itemOwnedByUser(r, userID, req.CookieID, req.ItemID) {
return db.AutomationRuleInput{}, errStr("商品不属于当前用户")
}
if req.Priority <= 0 {
req.Priority = 100
}
config := req.ConfigJSON
if config == "" {
config = "{}"
}
if !isJSONObject(config) {
return db.AutomationRuleInput{}, errStr("规则配置必须是 JSON 对象")
}
if len(req.Actions) == 0 {
return db.AutomationRuleInput{}, errStr("至少需要一个自动化动作")
}
if req.Name == "" {
req.Name = defaultAutomationRuleName(req.TriggerType, req.ItemID)
}
actions := make([]db.AutomationActionInput, 0, len(req.Actions))
hasSendCard, hasSendText, hasConfirmShipment := false, false, false
for i, act := range req.Actions {
enabled := true
if act.Enabled != nil {
enabled = *act.Enabled
}
act.ActionType = strings.TrimSpace(act.ActionType)
switch act.ActionType {
case automation.ActionConfirmShipment:
hasConfirmShipment = hasConfirmShipment || enabled
case automation.ActionSendCard:
if act.CardID <= 0 {
return db.AutomationRuleInput{}, errStr("发送卡密动作必须选择卡密组")
}
card, cardErr := s.Store.Cards.Get(r.Context(), act.CardID)
if cardErr != nil || card.UserID != userID {
return db.AutomationRuleInput{}, errStr("卡密组不存在或不属于当前用户")
}
if card.Type == "api" {
return db.AutomationRuleInput{}, errStr("API 卡密暂不支持自动发货,请选择文本、批量数据或图片卡密")
}
hasSendCard = hasSendCard || enabled
case automation.ActionSendText:
if strings.TrimSpace(act.MessageTemplate) == "" {
return db.AutomationRuleInput{}, errStr("发送文本动作必须填写文案")
}
hasSendText = hasSendText || enabled
default:
return db.AutomationRuleInput{}, errStr("不支持的动作类型")
}
if act.DeliveryCount <= 0 {
act.DeliveryCount = 1
}
if act.DelaySeconds < 0 || act.DelaySeconds > 86400 {
return db.AutomationRuleInput{}, errStr("动作延时必须在 0 到 86400 秒之间")
}
if act.ConfigJSON == "" {
act.ConfigJSON = "{}"
}
if !isJSONObject(act.ConfigJSON) {
return db.AutomationRuleInput{}, errStr("动作配置必须是 JSON 对象")
}
actions = append(actions, db.AutomationActionInput{
ActionType: act.ActionType, CardID: act.CardID, DeliveryCount: act.DeliveryCount,
MessageTemplate: act.MessageTemplate, DelaySeconds: act.DelaySeconds, ConfigJSON: act.ConfigJSON,
Enabled: enabled, SortOrder: firstNonZero(act.SortOrder, i+1),
})
}
switch req.TriggerType {
case automation.TriggerOrderPaid:
if !hasSendCard {
return db.AutomationRuleInput{}, errStr("付款后自动发货至少需要一个已启用的发送卡密动作")
}
case automation.TriggerBuyerReviewed:
if hasConfirmShipment {
return db.AutomationRuleInput{}, errStr("评价后规则不能包含确认发货动作")
}
if !hasSendCard && !hasSendText {
return db.AutomationRuleInput{}, errStr("评价后规则至少需要一个已启用的发送动作")
}
case automation.TriggerReviewMissingTimeout:
if hasConfirmShipment || hasSendCard {
return db.AutomationRuleInput{}, errStr("求评价规则只能发送文本")
}
if !hasSendText {
return db.AutomationRuleInput{}, errStr("求评价规则至少需要一个已启用的文本动作")
}
}
return db.AutomationRuleInput{
UserID: userID, CookieID: req.CookieID, ItemID: req.ItemID, Name: req.Name,
TriggerType: req.TriggerType, Enabled: req.Enabled, Priority: req.Priority,
ConfigJSON: config, Actions: actions,
}, nil
}
func defaultAutomationRuleName(triggerType, itemID string) string {
name := map[string]string{
automation.TriggerOrderPaid: "付款后自动发货",
automation.TriggerBuyerReviewed: "评价后发送赠品",
automation.TriggerReviewMissingTimeout: "超时未评价求评价",
}[triggerType]
if name == "" {
name = "自动化规则"
}
if strings.TrimSpace(itemID) != "" {
return name + " - " + strings.TrimSpace(itemID)
}
return name
}
func isJSONObject(s string) bool {
var m map[string]any
return json.Unmarshal([]byte(s), &m) == nil
}
func firstNonZero(v, fallback int) int {
if v != 0 {
return v
}
return fallback
}