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:
1 parent
5546494577
commit
57f9090dd2
29 files changed
+2469
-2382
No files matched your search
@@ -0,0 +1,241 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"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)
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
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))
|
||||
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:
|
||||
case automation.ActionSendCard:
|
||||
if act.CardID <= 0 {
|
||||
return db.AutomationRuleInput{}, errStr("发送卡密动作必须选择卡密组")
|
||||
}
|
||||
if !s.cardOwnedByUser(r.Context(), userID, act.CardID) {
|
||||
return db.AutomationRuleInput{}, errStr("卡密组不存在或不属于当前用户")
|
||||
}
|
||||
case automation.ActionSendText:
|
||||
if strings.TrimSpace(act.MessageTemplate) == "" {
|
||||
return db.AutomationRuleInput{}, errStr("发送文本动作必须填写文案")
|
||||
}
|
||||
default:
|
||||
return db.AutomationRuleInput{}, errStr("不支持的动作类型")
|
||||
}
|
||||
if act.DeliveryCount <= 0 {
|
||||
act.DeliveryCount = 1
|
||||
}
|
||||
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),
|
||||
})
|
||||
}
|
||||
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
|
||||
}
|
||||
@@ -1,11 +1,8 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
@@ -13,7 +10,7 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// mountCardsReal 卡券与发货规则 CRUD(真实实现)。
|
||||
// mountCardsReal 卡券 CRUD(真实实现)。发货规则已统一到 automation_rules。
|
||||
func (s *Server) mountCardsReal(r chi.Router) {
|
||||
r.Get("/cards", s.listCards)
|
||||
r.Post("/cards", s.createCard)
|
||||
@@ -21,10 +18,6 @@ func (s *Server) mountCardsReal(r chi.Router) {
|
||||
r.Get("/cards/{card_id}", s.getCard)
|
||||
r.Put("/cards/{card_id}", s.updateCard)
|
||||
r.Delete("/cards/{card_id}", s.deleteCard)
|
||||
r.Get("/delivery-rules", s.listDeliveryRules)
|
||||
r.Post("/delivery-rules", s.createDeliveryRule)
|
||||
r.Put("/delivery-rules/{rule_id}", s.updateDeliveryRule)
|
||||
r.Delete("/delivery-rules/{rule_id}", s.deleteDeliveryRule)
|
||||
}
|
||||
|
||||
func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -128,228 +121,9 @@ func decodeCard(r *http.Request) (*db.CardFull, error) {
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ---- 发货规则 CRUD ----
|
||||
|
||||
type deliveryVariantRequest struct {
|
||||
ID int64 `json:"id,omitempty"`
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
CardID int64 `json:"card_id"`
|
||||
DeliveryCount int `json:"delivery_count"`
|
||||
Enabled *bool `json:"enabled,omitempty"`
|
||||
}
|
||||
|
||||
type deliveryRuleRequest struct {
|
||||
Keyword string `json:"keyword"`
|
||||
CookieID string `json:"cookie_id"`
|
||||
ItemID string `json:"item_id"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Description string `json:"description"`
|
||||
Variants []deliveryVariantRequest `json:"variants"`
|
||||
CardID int64 `json:"card_id"`
|
||||
DeliveryCount int `json:"delivery_count"`
|
||||
}
|
||||
|
||||
func (s *Server) listDeliveryRules(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
rows, err := s.Store.DB.QueryContext(r.Context(),
|
||||
`SELECT dr.id,dr.keyword,COALESCE(dr.cookie_id,''),COALESCE(dr.item_id,''),
|
||||
dr.enabled,COALESCE(dr.description,''),dr.delivery_times,
|
||||
COALESCE((SELECT item_title FROM item_info i
|
||||
WHERE i.cookie_id=dr.cookie_id AND i.item_id=dr.item_id LIMIT 1),'')
|
||||
FROM delivery_rules dr WHERE dr.user_id=? ORDER BY dr.id DESC`, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id int64
|
||||
var deliveryTimes, enabled int
|
||||
var keyword, cookieID, itemID, desc, itemTitle string
|
||||
if err := rows.Scan(&id, &keyword, &cookieID, &itemID, &enabled, &desc, &deliveryTimes, &itemTitle); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取发货规则失败")
|
||||
return
|
||||
}
|
||||
variants, err := s.deliveryRuleVariants(r.Context(), id)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "读取规格映射失败")
|
||||
return
|
||||
}
|
||||
var legacyCardID int64
|
||||
legacyCardName := ""
|
||||
legacyCount := 1
|
||||
if len(variants) > 0 {
|
||||
legacyCardID, _ = variants[0]["card_id"].(int64)
|
||||
legacyCardName, _ = variants[0]["card_name"].(string)
|
||||
legacyCount, _ = variants[0]["delivery_count"].(int)
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": id, "keyword": keyword, "cookie_id": cookieID, "item_id": itemID, "item_title": itemTitle,
|
||||
"card_id": legacyCardID, "card_name": legacyCardName, "delivery_count": legacyCount,
|
||||
"enabled": enabled != 0, "description": desc, "delivery_times": deliveryTimes, "variants": variants,
|
||||
})
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
func (s *Server) createDeliveryRule(w http.ResponseWriter, r *http.Request) {
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
var req deliveryRuleRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if err := normalizeDeliveryRuleRequest(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if !s.deliveryRuleItemOwned(r, sess.UserID, req.CookieID, req.ItemID) {
|
||||
writeErr(w, http.StatusForbidden, "商品不属于当前用户")
|
||||
return
|
||||
}
|
||||
tx, err := s.Store.DB.BeginTx(r.Context(), nil)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "创建失败")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
first := req.Variants[0]
|
||||
res, err := tx.ExecContext(r.Context(),
|
||||
`INSERT INTO delivery_rules
|
||||
(keyword,card_id,delivery_count,enabled,description,user_id,cookie_id,item_id)
|
||||
VALUES (?,?,?,?,?,?,?,?)`,
|
||||
req.Keyword, first.CardID, first.DeliveryCount, req.Enabled, req.Description,
|
||||
sess.UserID, req.CookieID, req.ItemID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "创建失败")
|
||||
return
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
if err := insertDeliveryVariants(r.Context(), tx, sess.UserID, id, req.Variants); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "创建失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id})
|
||||
}
|
||||
|
||||
func (s *Server) updateDeliveryRule(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "无效规则ID")
|
||||
return
|
||||
}
|
||||
var req deliveryRuleRequest
|
||||
if err := decodeJSON(r, &req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "请求格式错误")
|
||||
return
|
||||
}
|
||||
if err := normalizeDeliveryRuleRequest(&req); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
if !s.deliveryRuleItemOwned(r, sess.UserID, req.CookieID, req.ItemID) {
|
||||
writeErr(w, http.StatusForbidden, "商品不属于当前用户")
|
||||
return
|
||||
}
|
||||
tx, err := s.Store.DB.BeginTx(r.Context(), nil)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
defer tx.Rollback()
|
||||
first := req.Variants[0]
|
||||
res, err := tx.ExecContext(r.Context(),
|
||||
`UPDATE delivery_rules SET keyword=?,card_id=?,delivery_count=?,enabled=?,description=?,
|
||||
cookie_id=?,item_id=?,updated_at=CURRENT_TIMESTAMP WHERE id=? AND user_id=?`,
|
||||
req.Keyword, first.CardID, first.DeliveryCount, req.Enabled, req.Description,
|
||||
req.CookieID, req.ItemID, id, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
writeErr(w, http.StatusNotFound, "发货规则不存在")
|
||||
return
|
||||
}
|
||||
if _, err := tx.ExecContext(r.Context(), `DELETE FROM delivery_rule_variants WHERE rule_id=?`, id); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新规格映射失败")
|
||||
return
|
||||
}
|
||||
if err := insertDeliveryVariants(r.Context(), tx, sess.UserID, id, req.Variants); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
func (s *Server) deleteDeliveryRule(w http.ResponseWriter, r *http.Request) {
|
||||
id, err := strconv.ParseInt(chi.URLParam(r, "rule_id"), 10, 64)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, "无效规则ID")
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
res, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM delivery_rules WHERE id=? AND user_id=?`, id, sess.UserID)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "删除失败")
|
||||
return
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
writeErr(w, http.StatusNotFound, "发货规则不存在")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": true})
|
||||
}
|
||||
|
||||
func normalizeDeliveryRuleRequest(req *deliveryRuleRequest) error {
|
||||
req.Keyword = strings.TrimSpace(req.Keyword)
|
||||
req.CookieID = strings.TrimSpace(req.CookieID)
|
||||
req.ItemID = strings.TrimSpace(req.ItemID)
|
||||
req.Description = strings.TrimSpace(req.Description)
|
||||
if len(req.Variants) == 0 && req.CardID > 0 {
|
||||
req.Variants = []deliveryVariantRequest{{CardID: req.CardID, DeliveryCount: req.DeliveryCount}}
|
||||
}
|
||||
if req.ItemID == "" && req.Keyword == "" {
|
||||
return errStr("请选择商品或填写旧规则关键词")
|
||||
}
|
||||
if len(req.Variants) == 0 {
|
||||
return errStr("至少需要一条卡密映射")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for i := range req.Variants {
|
||||
v := &req.Variants[i]
|
||||
v.SpecName = strings.TrimSpace(v.SpecName)
|
||||
v.SpecValue = strings.TrimSpace(v.SpecValue)
|
||||
if v.CardID <= 0 {
|
||||
return errStr("每条规格映射都必须选择卡密")
|
||||
}
|
||||
if (v.SpecName == "") != (v.SpecValue == "") {
|
||||
return errStr("规格名称和规格值必须同时填写")
|
||||
}
|
||||
if v.DeliveryCount <= 0 {
|
||||
v.DeliveryCount = 1
|
||||
}
|
||||
key := v.SpecName + "\x00" + v.SpecValue
|
||||
if seen[key] {
|
||||
return errStr("同一规则中不能存在重复规格")
|
||||
}
|
||||
seen[key] = true
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) deliveryRuleItemOwned(r *http.Request, userID int64, cookieID, itemID string) bool {
|
||||
// itemOwnedByUser 校验 cookieID 归属当前用户且其下存在 itemID 商品。
|
||||
// 由自动化规则校验复用(原 deliveryRuleItemOwned,发货规则删除后改名)。
|
||||
func (s *Server) itemOwnedByUser(r *http.Request, userID int64, cookieID, itemID string) bool {
|
||||
if itemID == "" {
|
||||
return true
|
||||
}
|
||||
@@ -364,54 +138,6 @@ func (s *Server) deliveryRuleItemOwned(r *http.Request, userID int64, cookieID,
|
||||
return err == nil
|
||||
}
|
||||
|
||||
func insertDeliveryVariants(ctx context.Context, tx *sql.Tx, userID, ruleID int64, variants []deliveryVariantRequest) error {
|
||||
for _, v := range variants {
|
||||
var exists int
|
||||
if err := tx.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, v.CardID, userID).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if exists == 0 {
|
||||
return errStr("选择的卡密不存在或不属于当前用户")
|
||||
}
|
||||
enabled := true
|
||||
if v.Enabled != nil {
|
||||
enabled = *v.Enabled
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO delivery_rule_variants
|
||||
(rule_id,spec_name,spec_value,card_id,delivery_count,enabled) VALUES (?,?,?,?,?,?)`,
|
||||
ruleID, v.SpecName, v.SpecValue, v.CardID, v.DeliveryCount, enabled); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) deliveryRuleVariants(ctx context.Context, ruleID int64) ([]map[string]any, error) {
|
||||
rows, err := s.Store.DB.QueryContext(ctx,
|
||||
`SELECT v.id,v.spec_name,v.spec_value,v.card_id,v.delivery_count,v.enabled,c.name,c.type
|
||||
FROM delivery_rule_variants v JOIN cards c ON c.id=v.card_id
|
||||
WHERE v.rule_id=? ORDER BY v.id`, ruleID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, cardID int64
|
||||
var specName, specValue, cardName, cardType string
|
||||
var deliveryCount, enabled int
|
||||
if err := rows.Scan(&id, &specName, &specValue, &cardID, &deliveryCount, &enabled, &cardName, &cardType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, map[string]any{
|
||||
"id": id, "spec_name": specName, "spec_value": specValue, "card_id": cardID,
|
||||
"card_name": cardName, "card_type": cardType, "delivery_count": deliveryCount, "enabled": enabled != 0,
|
||||
})
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
func errStr(s string) error { return &simpleError{s} }
|
||||
|
||||
type simpleError struct{ msg string }
|
||||
|
||||
@@ -155,80 +155,3 @@ func TestCardCRUD(t *testing.T) {
|
||||
}
|
||||
|
||||
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
|
||||
|
||||
// TestDeliveryRuleCRUD 发货规则增删。
|
||||
func TestDeliveryRuleCRUD(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
// 先建一个卡券供规则引用。
|
||||
store.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,user_id) VALUES (1,'卡','text','c',1,1)`)
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
|
||||
body := `{"keyword":"VIP","card_id":1,"delivery_count":1,"enabled":true}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/delivery-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// 列表。
|
||||
req2 := httptest.NewRequest(http.MethodGet, "/delivery-rules", nil)
|
||||
req2.AddCookie(cookie)
|
||||
rec2 := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec2, req2)
|
||||
var arr []map[string]any
|
||||
json.Unmarshal(rec2.Body.Bytes(), &arr)
|
||||
if len(arr) != 1 || arr[0]["keyword"] != "VIP" {
|
||||
t.Fatalf("规则列表异常: %+v", arr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeliveryRuleVariantCRUD(t *testing.T) {
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
ctx := context.Background()
|
||||
admin, _ := store.Users.GetByUsername(ctx, "admin")
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO cards (id,name,type,text_content,enabled,user_id) VALUES
|
||||
(31,'30天库存','text','A',1,?),(32,'90天库存','text','B',1,?)`, admin.ID, admin.ID)
|
||||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title,is_multi_spec) VALUES
|
||||
('acc1','item-vip','视频会员',1)`)
|
||||
|
||||
h := srv.Router()
|
||||
cookie := loginHelper(t, h)
|
||||
body := `{"keyword":"视频会员","cookie_id":"acc1","item_id":"item-vip","enabled":true,"description":"会员发货","variants":[{"spec_name":"套餐","spec_value":"30天","card_id":31,"delivery_count":1,"enabled":true},{"spec_name":"套餐","spec_value":"90天","card_id":32,"delivery_count":2,"enabled":true}]}`
|
||||
req := httptest.NewRequest(http.MethodPost, "/delivery-rules", strings.NewReader(body))
|
||||
req.AddCookie(cookie)
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("create status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
listReq := httptest.NewRequest(http.MethodGet, "/delivery-rules", nil)
|
||||
listReq.AddCookie(cookie)
|
||||
listRec := httptest.NewRecorder()
|
||||
h.ServeHTTP(listRec, listReq)
|
||||
var rules []struct {
|
||||
CookieID string `json:"cookie_id"`
|
||||
ItemID string `json:"item_id"`
|
||||
Variants []struct {
|
||||
SpecValue string `json:"spec_value"`
|
||||
CardID int64 `json:"card_id"`
|
||||
DeliveryCount int `json:"delivery_count"`
|
||||
} `json:"variants"`
|
||||
}
|
||||
if err := json.Unmarshal(listRec.Body.Bytes(), &rules); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rules) != 1 || rules[0].CookieID != "acc1" || rules[0].ItemID != "item-vip" || len(rules[0].Variants) != 2 {
|
||||
t.Fatalf("规则返回异常: %+v body=%s", rules, listRec.Body.String())
|
||||
}
|
||||
if rules[0].Variants[1].SpecValue != "90天" || rules[0].Variants[1].CardID != 32 || rules[0].Variants[1].DeliveryCount != 2 {
|
||||
t.Fatalf("规格返回异常: %+v", rules[0].Variants)
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"testing"
|
||||
|
||||
"xianyu-go/internal/account"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/engine"
|
||||
)
|
||||
@@ -53,7 +54,7 @@ func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
type noopHandler struct{}
|
||||
|
||||
func (noopHandler) HandleChatMessage(context.Context, engine.ChatMessage) error { return nil }
|
||||
func (noopHandler) HandleSystemMessage(context.Context, engine.SystemMessage) error { return nil }
|
||||
func (noopHandler) HandleSystemEvent(context.Context, automation.Task) error { return nil }
|
||||
func (noopHandler) OnPasswordLoginRefresh(context.Context, string) bool { return false }
|
||||
|
||||
// TestLoginVerifyLogout 登录→verify→登出 全链路。
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
package server
|
||||
|
||||
import "github.com/go-chi/chi/v5"
|
||||
|
||||
// stub_handlers.go 原为各分组的 501 占位;现已全部由 Real 实现替换。
|
||||
// 保留本文件作为 mount* 方法名到 Real 实现的别名,保持 server.go 调用简洁。
|
||||
|
||||
func (s *Server) mountItems(r chi.Router) { s.mountItemsReal(r) }
|
||||
func (s *Server) mountKeywords(r chi.Router) { s.mountKeywordsReal(r) }
|
||||
func (s *Server) mountDefaultReplies(r chi.Router) { s.mountDefaultRepliesReal(r) }
|
||||
func (s *Server) mountNotifications(r chi.Router) { s.mountNotificationsReal(r) }
|
||||
func (s *Server) mountSettings(r chi.Router) { s.mountSettingsReal(r) }
|
||||
func (s *Server) mountAIReply(r chi.Router) { s.mountAIReplyReal(r) }
|
||||
func (s *Server) mountUser(r chi.Router) { s.mountUserReal(r) }
|
||||
func (s *Server) mountAdmin(r chi.Router) { s.mountAdminReal(r) }
|
||||
|
||||
Reference in new issue
Block a user