Files
Ydisks-Xianyu-Helper/internal/server/card_handlers.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 <noreply@anthropic.com>
2026-06-30 21:40:15 +08:00

146 lines
4.3 KiB
Go

package server
import (
"net/http"
"strconv"
"github.com/go-chi/chi/v5"
"xianyu-go/internal/auth"
"xianyu-go/internal/db"
)
// mountCardsReal 卡券 CRUD(真实实现)。发货规则已统一到 automation_rules。
func (s *Server) mountCardsReal(r chi.Router) {
r.Get("/cards", s.listCards)
r.Post("/cards", s.createCard)
r.Get("/cards/{card_id}/details", s.getCard)
r.Get("/cards/{card_id}", s.getCard)
r.Put("/cards/{card_id}", s.updateCard)
r.Delete("/cards/{card_id}", s.deleteCard)
}
func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
cards, err := s.Store.Cards.AllForUser(r.Context(), sess.UserID)
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
writeJSON(w, http.StatusOK, cards)
}
func (s *Server) getCard(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
cf, err := s.Store.Cards.Get(r.Context(), id)
if err != nil {
writeErr(w, http.StatusNotFound, "卡券不存在")
return
}
writeJSON(w, http.StatusOK, cf)
}
func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
cf, err := decodeCard(r)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
cf.UserID = sess.UserID
id, err := s.Store.Cards.Create(r.Context(), cf)
if err != nil {
writeErr(w, http.StatusInternalServerError, "创建失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id})
}
func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
cf, err := decodeCard(r)
if err != nil {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
cf.ID = id
if err := s.Store.Cards.Update(r.Context(), cf); err != nil {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) deleteCard(w http.ResponseWriter, r *http.Request) {
id, err := strconv.ParseInt(chi.URLParam(r, "card_id"), 10, 64)
if err != nil {
writeErr(w, http.StatusBadRequest, "无效卡券ID")
return
}
if err := s.Store.Cards.Delete(r.Context(), id); err != nil {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func decodeCard(r *http.Request) (*db.CardFull, error) {
var req struct {
Name string `json:"name"`
Type string `json:"type"`
APIConfig string `json:"api_config"`
TextContent string `json:"text_content"`
DataContent string `json:"data_content"`
ImageURL string `json:"image_url"`
Description string `json:"description"`
Enabled bool `json:"enabled"`
DelaySeconds int `json:"delay_seconds"`
IsMultiSpec bool `json:"is_multi_spec"`
SpecName string `json:"spec_name"`
SpecValue string `json:"spec_value"`
}
if err := decodeJSON(r, &req); err != nil {
return nil, err
}
if req.Name == "" || req.Type == "" {
return nil, errStr("名称和类型不能为空")
}
return &db.CardFull{
Name: req.Name, Type: req.Type, APIConfig: req.APIConfig, TextContent: req.TextContent,
DataContent: req.DataContent, ImageURL: req.ImageURL, Description: req.Description,
Enabled: req.Enabled, DelaySeconds: req.DelaySeconds, IsMultiSpec: req.IsMultiSpec,
SpecName: req.SpecName, SpecValue: req.SpecValue,
}, nil
}
// itemOwnedByUser 校验 cookieID 归属当前用户且其下存在 itemID 商品。
// 由自动化规则校验复用(原 deliveryRuleItemOwned,发货规则删除后改名)。
func (s *Server) itemOwnedByUser(r *http.Request, userID int64, cookieID, itemID string) bool {
if itemID == "" {
return true
}
all, err := s.Store.Cookies.AllForUser(r.Context(), userID)
if err != nil || cookieID == "" {
return false
}
if _, ok := all[cookieID]; !ok {
return false
}
_, err = s.Store.Items.Get(r.Context(), cookieID, itemID)
return err == nil
}
func errStr(s string) error { return &simpleError{s} }
type simpleError struct{ msg string }
func (e *simpleError) Error() string { return e.msg }