feat(fulfillment): 接入Rock发货平台(0666.pro)代理履约、通用库存池与UID强一致风控
1. 数据库新增 012_rock_fulfillment 迁移,创建 rock_configs 配置表与 rock_tokens 通用库存表,补齐黑色ROCK长袖T恤与蓝色运动服上衣商品目录; 2. 封装 RockClient 与 RockService,实现 0666.pro 平台 Bearer Token 极简连通校验、批量采购50个入库、水位监控巡检与自动补货; 3. 新增 RockProvider 实现标准履约路由,引入 Anti-Ghost 旧绑定基线比对与 UID 强一致门禁,扫错号硬阻断并记录为 mismatch 状态; 4. 针对黑色ROCK与蓝色运动服实现动态发货(绑定后发货前动态选择 skin),并提取腾讯官方发货流水号 fulfillId 对账; 5. 新增全局自动发货总开关(Kill Switch),支持一键软熔断降级转人工接单处理; 6. 前端新增 PlatformRock 管理大屏,提供总开关切换、Token配置与连通测试、库存监控、一键补货及错单解冻重置。
This commit is contained in:
@@ -96,6 +96,13 @@ func main() {
|
||||
}, nil)
|
||||
lewanProvider := service.NewLewanProvider(lewanClient)
|
||||
deliverySvc.RegisterProvider(lewanProvider)
|
||||
|
||||
// Rock 平台 (0666.pro) 客户端、服务与履约提供商注册
|
||||
rockClient := service.NewRockClient("https://0666.pro")
|
||||
rockSvc := service.NewRockService(db, rockClient)
|
||||
rockProvider := service.NewRockProvider(rockSvc)
|
||||
deliverySvc.RegisterProvider(rockProvider)
|
||||
|
||||
fulfillmentSvc.SetUpstreamCancel(deliverySvc.CancelUpstream)
|
||||
fulfillmentSvc.SetUpstreamSync(deliverySvc.SyncDeliveringOrder)
|
||||
|
||||
@@ -122,6 +129,7 @@ func main() {
|
||||
CORSAllowedOrigins: cfg.CORSAllowedOrigins,
|
||||
LewanWebhook: handler.NewLewanWebhookHandler(fulfillmentSvc, db, cfg.LewanWebhookSecret, cfg.LewanApplicationID),
|
||||
PlatformLewan: handler.NewPlatformLewanHandler(merchantSvc, lewanClient),
|
||||
Rock: handler.NewRockHandler(rockSvc),
|
||||
}
|
||||
|
||||
go callbackSvc.Run(context.Background())
|
||||
@@ -131,6 +139,15 @@ func main() {
|
||||
time.Duration(cfg.FulfillmentTimeoutScanIntervalSeconds)*time.Second,
|
||||
)
|
||||
|
||||
// 定时巡检 Rock 库存低水位与自动补货(每5分钟)
|
||||
go func() {
|
||||
ticker := time.NewTicker(5 * time.Minute)
|
||||
defer ticker.Stop()
|
||||
for range ticker.C {
|
||||
rockSvc.CheckStockAndAutoPurchase(context.Background())
|
||||
}
|
||||
}()
|
||||
|
||||
r := router.Setup(h)
|
||||
addr := ":" + cfg.Port
|
||||
applog.Infof("游戏皮肤供货平台 API 启动: http://localhost%s (日志级别: %s)", addr, applog.GetLevel())
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
-- ============================================================================
|
||||
-- 012_rock_fulfillment.sql: Rock 发货平台 (0666.pro) 代理接入与库存风控数据表与商品目录
|
||||
-- ============================================================================
|
||||
|
||||
-- 1) Rock 平台系统配置表
|
||||
CREATE TABLE IF NOT EXISTS rock_configs (
|
||||
id BIGINT PRIMARY KEY DEFAULT 1,
|
||||
auto_delivery_enabled BOOLEAN NOT NULL DEFAULT true,
|
||||
base_url VARCHAR(255) NOT NULL DEFAULT 'https://0666.pro',
|
||||
bearer_token TEXT NOT NULL DEFAULT '',
|
||||
username VARCHAR(128) NOT NULL DEFAULT '',
|
||||
points NUMERIC(12, 2) NOT NULL DEFAULT 0.00,
|
||||
min_points_warning NUMERIC(12, 2) NOT NULL DEFAULT 1050.00,
|
||||
token_warning_stock INT NOT NULL DEFAULT 10,
|
||||
auto_purchase_enabled BOOLEAN NOT NULL DEFAULT false,
|
||||
auto_purchase_count INT NOT NULL DEFAULT 50,
|
||||
purchase_cooldown_minutes INT NOT NULL DEFAULT 10,
|
||||
last_purchased_at TIMESTAMPTZ,
|
||||
last_heartbeat_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
-- 初始化默认配置行(固定 ID=1)
|
||||
INSERT INTO rock_configs (id, auto_delivery_enabled, base_url, bearer_token, min_points_warning, token_warning_stock, auto_purchase_enabled, auto_purchase_count)
|
||||
VALUES (1, true, 'https://0666.pro', '', 1050.00, 10, false, 50)
|
||||
ON CONFLICT (id) DO NOTHING;
|
||||
|
||||
-- 2) Rock 通用 Token 本地库存池表
|
||||
CREATE TABLE IF NOT EXISTS rock_tokens (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
upstream_token_id VARCHAR(64) NOT NULL DEFAULT '',
|
||||
token TEXT NOT NULL,
|
||||
redeem_code VARCHAR(64) NOT NULL,
|
||||
color VARCHAR(32) NOT NULL DEFAULT 'black',
|
||||
region VARCHAR(64) NOT NULL DEFAULT 'Q/V可用',
|
||||
status VARCHAR(32) NOT NULL DEFAULT 'available',
|
||||
assigned_order_no VARCHAR(128),
|
||||
expected_uid VARCHAR(64),
|
||||
actual_role_name VARCHAR(128),
|
||||
actual_role_id VARCHAR(64),
|
||||
actual_channel VARCHAR(64),
|
||||
initial_bound_snapshot TEXT,
|
||||
upstream_fulfill_id BIGINT,
|
||||
target_skin VARCHAR(128),
|
||||
target_currency VARCHAR(64) NOT NULL DEFAULT '幸运币',
|
||||
target_currency_quantity INT NOT NULL DEFAULT 0,
|
||||
mismatch_at TIMESTAMPTZ,
|
||||
mismatch_reason VARCHAR(255),
|
||||
claimed_at TIMESTAMPTZ,
|
||||
bound_at TIMESTAMPTZ,
|
||||
redeemed_at TIMESTAMPTZ,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_rock_tokens_status_color ON rock_tokens (status, color);
|
||||
CREATE INDEX IF NOT EXISTS idx_rock_tokens_assigned_order ON rock_tokens (assigned_order_no);
|
||||
CREATE INDEX IF NOT EXISTS idx_rock_tokens_redeem_code ON rock_tokens (redeem_code);
|
||||
CREATE INDEX IF NOT EXISTS idx_rock_tokens_mismatch ON rock_tokens (status, mismatch_at);
|
||||
|
||||
-- 3) 插入 Rock 皮肤到商品目录 (products 表与自营 merchant_products 表)
|
||||
WITH rock_products(sku, name, category, default_price, fulfillment_config) AS (
|
||||
VALUES
|
||||
('rock_black_tshirt', '黑色ROCK长袖T恤', '服饰', 2500, '{"routing_mode":"rock","priority":["rock"],"delivery_type":"LINK_BINDING"}'),
|
||||
('rock_blue_sportswear', '蓝色运动服上衣', '服饰', 2500, '{"routing_mode":"rock","priority":["rock"],"delivery_type":"LINK_BINDING"}')
|
||||
)
|
||||
INSERT INTO products (code, name, category, status)
|
||||
SELECT p.sku, p.name, p.category, 'active'
|
||||
FROM rock_products p
|
||||
ON CONFLICT (code) DO UPDATE
|
||||
SET
|
||||
name = EXCLUDED.name,
|
||||
category = EXCLUDED.category,
|
||||
status = 'active';
|
||||
|
||||
WITH rock_products(sku, name, category, default_price, fulfillment_config) AS (
|
||||
VALUES
|
||||
('rock_black_tshirt', '黑色ROCK长袖T恤', '服饰', 2500, '{"routing_mode":"rock","priority":["rock"],"delivery_type":"LINK_BINDING"}'),
|
||||
('rock_blue_sportswear', '蓝色运动服上衣', '服饰', 2500, '{"routing_mode":"rock","priority":["rock"],"delivery_type":"LINK_BINDING"}')
|
||||
),
|
||||
self_merchant AS (
|
||||
SELECT id FROM merchants WHERE code = 'self-operated' LIMIT 1
|
||||
)
|
||||
INSERT INTO merchant_products (
|
||||
merchant_id, product_id, sku, display_name,
|
||||
price_amount, cost_amount, currency, stock, status, fulfillment_config
|
||||
)
|
||||
SELECT
|
||||
sm.id,
|
||||
p.id,
|
||||
rp.sku,
|
||||
rp.name,
|
||||
rp.default_price,
|
||||
rp.default_price,
|
||||
'POINT',
|
||||
-1,
|
||||
'active',
|
||||
rp.fulfillment_config
|
||||
FROM rock_products rp
|
||||
JOIN products p ON p.code = rp.sku
|
||||
CROSS JOIN self_merchant sm
|
||||
ON CONFLICT (merchant_id, sku) DO UPDATE
|
||||
SET
|
||||
display_name = EXCLUDED.display_name,
|
||||
price_amount = EXCLUDED.price_amount,
|
||||
cost_amount = EXCLUDED.cost_amount,
|
||||
fulfillment_config = EXCLUDED.fulfillment_config,
|
||||
status = 'active',
|
||||
deleted_at = NULL;
|
||||
@@ -0,0 +1,125 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"affiliate_dash/internal/pkg/response"
|
||||
"affiliate_dash/internal/service"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
type RockHandler struct {
|
||||
rockSvc *service.RockService
|
||||
}
|
||||
|
||||
func NewRockHandler(rockSvc *service.RockService) *RockHandler {
|
||||
return &RockHandler{rockSvc: rockSvc}
|
||||
}
|
||||
|
||||
// GetConfig 获取 Rock 平台配置
|
||||
func (h *RockHandler) GetConfig(c *gin.Context) {
|
||||
cfg, err := h.rockSvc.GetConfig(c.Request.Context())
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, cfg)
|
||||
}
|
||||
|
||||
// UpdateConfig 更新 Rock 平台配置
|
||||
func (h *RockHandler) UpdateConfig(c *gin.Context) {
|
||||
var req service.UpdateRockConfigReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
response.BadRequest(c, "参数解析失败")
|
||||
return
|
||||
}
|
||||
cfg, err := h.rockSvc.UpdateConfig(c.Request.Context(), req)
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, cfg)
|
||||
}
|
||||
|
||||
type testConnReq struct {
|
||||
BearerToken string `json:"bearer_token"`
|
||||
}
|
||||
|
||||
// TestConnection 测试上游 Token 连通性
|
||||
func (h *RockHandler) TestConnection(c *gin.Context) {
|
||||
var req testConnReq
|
||||
_ = c.ShouldBindJSON(&req)
|
||||
me, err := h.rockSvc.TestConnection(c.Request.Context(), req.BearerToken)
|
||||
if err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, me)
|
||||
}
|
||||
|
||||
// GetStats 获取概览数据与库存统计
|
||||
func (h *RockHandler) GetStats(c *gin.Context) {
|
||||
stats, err := h.rockSvc.GetStats(c.Request.Context())
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, stats)
|
||||
}
|
||||
|
||||
type purchaseReq struct {
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
// PurchaseTokens 手动采购并入库 Token
|
||||
func (h *RockHandler) PurchaseTokens(c *gin.Context) {
|
||||
var req purchaseReq
|
||||
if err := c.ShouldBindJSON(&req); err != nil || req.Count <= 0 {
|
||||
req.Count = 50
|
||||
}
|
||||
tokens, err := h.rockSvc.PurchaseTokens(c.Request.Context(), req.Count, false)
|
||||
if err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{
|
||||
"purchased_count": len(tokens),
|
||||
"message": "采购成功,已批量入库",
|
||||
})
|
||||
}
|
||||
|
||||
// ListTokens 分页获取 Token 库存列表
|
||||
func (h *RockHandler) ListTokens(c *gin.Context) {
|
||||
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
|
||||
pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20"))
|
||||
status := strings.TrimSpace(c.Query("status"))
|
||||
search := strings.TrimSpace(c.Query("search"))
|
||||
|
||||
tokens, total, err := h.rockSvc.ListTokens(c.Request.Context(), page, pageSize, status, search)
|
||||
if err != nil {
|
||||
response.ServerError(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{
|
||||
"list": tokens,
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": pageSize,
|
||||
})
|
||||
}
|
||||
|
||||
// ResetToken 客服人工重置 mismatch 状态的 Token
|
||||
func (h *RockHandler) ResetToken(c *gin.Context) {
|
||||
idUint, err := strconv.ParseUint(c.Param("id"), 10, 64)
|
||||
if err != nil {
|
||||
response.BadRequest(c, "无效的 Token ID")
|
||||
return
|
||||
}
|
||||
if err := h.rockSvc.ResetMismatchToken(c.Request.Context(), uint(idUint)); err != nil {
|
||||
response.BadRequest(c, err.Error())
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"message": "重置成功,Token 已重新释放至可用库存"})
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"time"
|
||||
)
|
||||
|
||||
// Rock 相关常量
|
||||
const (
|
||||
RockColorBlack = "black"
|
||||
RockColorBlue = "blue"
|
||||
|
||||
RockStatusAvailable = "available" // 可用库存
|
||||
RockStatusUsing = "using" // 已分配给订单,正在提货扫码
|
||||
RockStatusBound = "bound" // 扫码绑定成功
|
||||
RockStatusRedeemed = "redeemed" // 发货完成
|
||||
RockStatusMismatch = "mismatch" // UID 校验不符阻断(绑错)
|
||||
RockStatusAbnormal = "abnormal" // 异常/作废
|
||||
|
||||
RockSKUBlackTshirt = "rock_black_tshirt"
|
||||
RockSKUBlueSportswear = "rock_blue_sportswear"
|
||||
|
||||
RockSkinBlackTshirt = "黑色ROCK长袖T恤"
|
||||
RockSkinBlueSportswear = "蓝色运动服上衣"
|
||||
)
|
||||
|
||||
// RockConfig 平台配置项
|
||||
type RockConfig struct {
|
||||
ID uint `gorm:"primaryKey;default:1" json:"id"`
|
||||
AutoDeliveryEnabled bool `gorm:"not null;default:true" json:"auto_delivery_enabled"` // 全局自动发货总开关
|
||||
BaseURL string `gorm:"size:255;not null;default:'https://0666.pro'" json:"base_url"`
|
||||
BearerToken string `gorm:"type:text;not null;default:''" json:"bearer_token"`
|
||||
Username string `gorm:"size:128;not null;default:''" json:"username"`
|
||||
Points float64 `gorm:"type:numeric(12,2);not null;default:0.00" json:"points"`
|
||||
MinPointsWarning float64 `gorm:"type:numeric(12,2);not null;default:1050.00" json:"min_points_warning"`
|
||||
TokenWarningStock int `gorm:"not null;default:10" json:"token_warning_stock"`
|
||||
AutoPurchaseEnabled bool `gorm:"not null;default:false" json:"auto_purchase_enabled"`
|
||||
AutoPurchaseCount int `gorm:"not null;default:50" json:"auto_purchase_count"`
|
||||
PurchaseCooldownMinutes int `gorm:"not null;default:10" json:"purchase_cooldown_minutes"`
|
||||
LastPurchasedAt *time.Time `json:"last_purchased_at"`
|
||||
LastHeartbeatAt *time.Time `json:"last_heartbeat_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (RockConfig) TableName() string {
|
||||
return "rock_configs"
|
||||
}
|
||||
|
||||
// RockToken 通用 Token 本地库存池记录
|
||||
type RockToken struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
UpstreamTokenID string `gorm:"size:64;not null;default:''" json:"upstream_token_id"`
|
||||
Token string `gorm:"type:text;not null" json:"-"`
|
||||
RedeemCode string `gorm:"size:64;not null;index" json:"redeem_code"`
|
||||
Color string `gorm:"size:32;not null;default:'black';index" json:"color"`
|
||||
Region string `gorm:"size:64;not null;default:'Q/V可用'" json:"region"`
|
||||
Status string `gorm:"size:32;not null;default:'available';index" json:"status"`
|
||||
AssignedOrderNo string `gorm:"size:128;index" json:"assigned_order_no"`
|
||||
ExpectedUID string `gorm:"size:64" json:"expected_uid"`
|
||||
ActualRoleName string `gorm:"size:128" json:"actual_role_name"`
|
||||
ActualRoleID string `gorm:"size:64" json:"actual_role_id"`
|
||||
ActualChannel string `gorm:"size:64" json:"actual_channel"`
|
||||
InitialBoundSnapshot string `gorm:"type:text" json:"-"` // 分配时初始旧数据快照 JSON
|
||||
UpstreamFulfillID int64 `json:"upstream_fulfill_id"`
|
||||
TargetSkin string `gorm:"size:128" json:"target_skin"`
|
||||
TargetCurrency string `gorm:"size:64;not null;default:'幸运币'" json:"target_currency"`
|
||||
TargetCurrencyQuantity int `gorm:"not null;default:0" json:"target_currency_quantity"`
|
||||
MismatchAt *time.Time `gorm:"index" json:"mismatch_at"`
|
||||
MismatchReason string `gorm:"size:255" json:"mismatch_reason"`
|
||||
ClaimedAt *time.Time `json:"claimed_at"`
|
||||
BoundAt *time.Time `json:"bound_at"`
|
||||
RedeemedAt *time.Time `json:"redeemed_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (RockToken) TableName() string {
|
||||
return "rock_tokens"
|
||||
}
|
||||
@@ -41,6 +41,7 @@ type Handlers struct {
|
||||
|
||||
LewanWebhook *handler.LewanWebhookHandler
|
||||
PlatformLewan *handler.PlatformLewanHandler
|
||||
Rock *handler.RockHandler
|
||||
}
|
||||
|
||||
// defaultCORSOrigins 未配置 CORS_ALLOWED_ORIGINS 时的本地开发默认来源。
|
||||
@@ -304,6 +305,17 @@ func Setup(h *Handlers) *gin.Engine {
|
||||
admin.POST("/platform/lewan/batch-sync-catalog", h.PlatformLewan.BatchSyncLewanProducts)
|
||||
admin.PUT("/platform/products/:id/routing", h.PlatformLewan.UpdateProductRouting)
|
||||
}
|
||||
|
||||
// Rock平台 (0666.pro) 自动发货与库存风控管理
|
||||
if h.Rock != nil {
|
||||
admin.GET("/platform/rock/config", h.Rock.GetConfig)
|
||||
admin.PUT("/platform/rock/config", h.Rock.UpdateConfig)
|
||||
admin.POST("/platform/rock/test-conn", h.Rock.TestConnection)
|
||||
admin.GET("/platform/rock/stats", h.Rock.GetStats)
|
||||
admin.POST("/platform/rock/purchase", h.Rock.PurchaseTokens)
|
||||
admin.GET("/platform/rock/tokens", h.Rock.ListTokens)
|
||||
admin.POST("/platform/rock/tokens/:id/reset", h.Rock.ResetToken)
|
||||
}
|
||||
}
|
||||
|
||||
auth.POST("/upload", h.Recharge.Upload)
|
||||
|
||||
@@ -12,10 +12,12 @@ import (
|
||||
const (
|
||||
ProviderDLC = "dlc"
|
||||
ProviderLewan = "lewan"
|
||||
ProviderRock = "rock"
|
||||
|
||||
RoutingModePriority = "priority"
|
||||
RoutingModeLewan = "lewan"
|
||||
RoutingModeDLC = "dlc"
|
||||
RoutingModeRock = "rock"
|
||||
)
|
||||
|
||||
// ProductRoutingConfig 商品履约配置
|
||||
@@ -62,9 +64,12 @@ func ParseProductRoutingConfig(fulfillmentConfig string, sku string) ProductRout
|
||||
cfg.DLCGoodID = builtinDLC
|
||||
}
|
||||
|
||||
// 若未配置 RoutingMode:双渠道优先 priority,单渠道按已有 ID / legacy provider 决定
|
||||
// 若未配置 RoutingMode:优先判断是否为 Rock 渠道专属商品
|
||||
if cfg.RoutingMode == "" {
|
||||
if cfg.LewanProductID != "" && cfg.DLCGoodID != "" {
|
||||
if strings.HasPrefix(sku, "rock_") {
|
||||
cfg.RoutingMode = RoutingModeRock
|
||||
cfg.Priority = []string{ProviderRock}
|
||||
} else if cfg.LewanProductID != "" && cfg.DLCGoodID != "" {
|
||||
cfg.RoutingMode = RoutingModePriority
|
||||
cfg.Priority = []string{ProviderLewan, ProviderDLC}
|
||||
} else if cfg.LewanProductID != "" || legacyProvider == ProviderLewan {
|
||||
@@ -199,6 +204,10 @@ func (r *FulfillmentRouter) ResolveProviders(order *model.FulfillmentOrder) ([]F
|
||||
if p, ok := r.providers[ProviderDLC]; ok {
|
||||
list = append(list, p)
|
||||
}
|
||||
case RoutingModeRock:
|
||||
if p, ok := r.providers[ProviderRock]; ok {
|
||||
list = append(list, p)
|
||||
}
|
||||
case RoutingModePriority:
|
||||
for _, name := range cfg.Priority {
|
||||
if p, ok := r.providers[name]; ok {
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
)
|
||||
|
||||
// RockProvider 实现 Rock 发货平台履约逻辑
|
||||
type RockProvider struct {
|
||||
rockService *RockService
|
||||
}
|
||||
|
||||
func NewRockProvider(rockService *RockService) *RockProvider {
|
||||
return &RockProvider{
|
||||
rockService: rockService,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RockProvider) Name() string {
|
||||
return ProviderRock
|
||||
}
|
||||
|
||||
func (p *RockProvider) PrepareDelivery(ctx context.Context, order *model.FulfillmentOrder, openOrder *OpenOrderQuery) (*DeliveryOrderState, error) {
|
||||
if p.rockService == nil {
|
||||
return nil, errors.New("Rock 发货服务未初始化")
|
||||
}
|
||||
|
||||
cfg, err := p.rockService.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 Rock 配置失败: %w", err)
|
||||
}
|
||||
|
||||
// 1. 全局软熔断总开关检查 (Kill Switch)
|
||||
if !cfg.AutoDeliveryEnabled {
|
||||
return &DeliveryOrderState{
|
||||
CanShip: false,
|
||||
CannotShipReason: "当前该商品自动发货通道维护中,已转交人工客服/打手为您处理",
|
||||
Provider: ProviderRock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 2. 检查可用库存
|
||||
stats, err := p.rockService.GetStats(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("获取库存失败: %w", err)
|
||||
}
|
||||
if stats.AvailableStock <= 0 {
|
||||
return &DeliveryOrderState{
|
||||
CanShip: false,
|
||||
CannotShipReason: "当前商品库存补充中,已通知管理员自动补货,请稍后刷新或联系客服",
|
||||
Provider: ProviderRock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
sku := ""
|
||||
productName := "和平精英道具"
|
||||
if order != nil {
|
||||
sku = order.ProductSKU
|
||||
if order.MerchantProduct != nil && order.MerchantProduct.DisplayName != "" {
|
||||
productName = order.MerchantProduct.DisplayName
|
||||
}
|
||||
}
|
||||
if openOrder != nil && openOrder.Product != nil && openOrder.Product.Name != "" {
|
||||
productName = openOrder.Product.Name
|
||||
}
|
||||
|
||||
deliveryProd := &DeliveryProduct{
|
||||
Name: productName,
|
||||
SKU: sku,
|
||||
Game: "和平精英",
|
||||
}
|
||||
|
||||
return &DeliveryOrderState{
|
||||
CanShip: true,
|
||||
Product: deliveryProd,
|
||||
Provider: ProviderRock,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *RockProvider) Bind(ctx context.Context, order *model.FulfillmentOrder, gameAccount string) (*ProviderBindResult, error) {
|
||||
if p.rockService == nil {
|
||||
return nil, errors.New("Rock 发货服务未初始化")
|
||||
}
|
||||
|
||||
trimmedUID := strings.TrimSpace(gameAccount)
|
||||
if trimmedUID == "" {
|
||||
return nil, errors.New("请先填写正确的游戏数字账号(UID)")
|
||||
}
|
||||
|
||||
// 分配或锁定一个 Token 并获取上游活动链接
|
||||
token, detail, err := p.rockService.AssignTokenForOrder(ctx, order.OrderNo, trimmedUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
patch := map[string]interface{}{
|
||||
"provider": ProviderRock,
|
||||
"rock_token_id": token.ID,
|
||||
"rock_redeem_code": token.RedeemCode,
|
||||
"expected_uid": trimmedUID,
|
||||
}
|
||||
|
||||
bindURL := strings.TrimSpace(detail.BindURL)
|
||||
qrURL := detail.QRURL
|
||||
if qrURL == "" && bindURL != "" {
|
||||
qrURL = qrCodeURL(bindURL)
|
||||
}
|
||||
|
||||
return &ProviderBindResult{
|
||||
BindUUID: fmt.Sprintf("%d", token.ID),
|
||||
BindURL: bindURL,
|
||||
QRURL: qrURL,
|
||||
Bound: false,
|
||||
ExpectedGameAccount: trimmedUID,
|
||||
Message: "请使用手机微信/QQ扫描上方二维码绑定游戏角色",
|
||||
Provider: ProviderRock,
|
||||
PatchResultData: patch,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *RockProvider) CheckBind(ctx context.Context, order *model.FulfillmentOrder, bindUUID string) (*ProviderBindResult, error) {
|
||||
if p.rockService == nil {
|
||||
return nil, errors.New("Rock 发货服务未初始化")
|
||||
}
|
||||
|
||||
tokenIDUint, err := strconv.ParseUint(strings.TrimSpace(bindUUID), 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("无效的 bind_uuid: %s", bindUUID)
|
||||
}
|
||||
|
||||
expectedUID := resultDataString(order.ResultData, "expected_uid")
|
||||
if expectedUID == "" {
|
||||
expectedUID = resultDataString(order.RequestData, "game_account")
|
||||
}
|
||||
if expectedUID == "" {
|
||||
expectedUID = resultDataString(order.ResultData, "game_account")
|
||||
}
|
||||
|
||||
res, err := p.rockService.CheckBindingAndVerifyUID(ctx, uint(tokenIDUint), expectedUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
patch := map[string]interface{}{
|
||||
"provider": ProviderRock,
|
||||
}
|
||||
if res.RoleName != "" {
|
||||
patch["role_name"] = res.RoleName
|
||||
}
|
||||
if res.Channel != "" {
|
||||
patch["game_channel"] = res.Channel
|
||||
}
|
||||
if res.RoleID != "" {
|
||||
patch["actual_role_id"] = res.RoleID
|
||||
}
|
||||
|
||||
return &ProviderBindResult{
|
||||
BindUUID: bindUUID,
|
||||
Bound: res.Bound,
|
||||
RoleName: res.RoleName,
|
||||
GameAccount: res.RoleID,
|
||||
GameChannel: res.Channel,
|
||||
ExpectedGameAccount: res.ExpectedUID,
|
||||
Mismatch: res.Mismatch,
|
||||
Message: res.Message,
|
||||
Provider: ProviderRock,
|
||||
PatchResultData: patch,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *RockProvider) Submit(ctx context.Context, order *model.FulfillmentOrder, gameAccount, bindUUID string) (*ProviderSubmitResult, error) {
|
||||
if p.rockService == nil {
|
||||
return nil, errors.New("Rock 发货服务未初始化")
|
||||
}
|
||||
|
||||
sku := order.ProductSKU
|
||||
expectedUID := strings.TrimSpace(gameAccount)
|
||||
if expectedUID == "" {
|
||||
expectedUID = resultDataString(order.ResultData, "expected_uid")
|
||||
}
|
||||
|
||||
redeemResp, err := p.rockService.RedeemTokenForOrder(ctx, order.OrderNo, sku, expectedUID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
fulfillIDStr := ""
|
||||
if redeemResp.Delivery.FulfillID > 0 {
|
||||
fulfillIDStr = fmt.Sprintf("%d", redeemResp.Delivery.FulfillID)
|
||||
}
|
||||
|
||||
patch := map[string]interface{}{
|
||||
"provider": ProviderRock,
|
||||
"provider_order_no": fulfillIDStr,
|
||||
"fulfill_id": redeemResp.Delivery.FulfillID,
|
||||
"skin": redeemResp.Delivery.Skin,
|
||||
"currency": redeemResp.Delivery.Currency,
|
||||
"currency_quantity": redeemResp.Delivery.Quantity,
|
||||
}
|
||||
|
||||
return &ProviderSubmitResult{
|
||||
ProviderOrderNo: fulfillIDStr,
|
||||
NextStatus: model.OrderStatusDelivered,
|
||||
Message: "发货成功!道具及附赠货币已发放至游戏,请登录游戏邮件查收",
|
||||
GameAccount: map[string]interface{}{
|
||||
"role_name": resultDataString(order.ResultData, "role_name"),
|
||||
"game_channel": resultDataString(order.ResultData, "game_channel"),
|
||||
"role_id": expectedUID,
|
||||
},
|
||||
PatchResultData: patch,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (p *RockProvider) SyncStatus(ctx context.Context, order *model.FulfillmentOrder) (*ProviderSyncResult, error) {
|
||||
if p.rockService == nil {
|
||||
return nil, errors.New("Rock 发货服务未初始化")
|
||||
}
|
||||
|
||||
var token model.RockToken
|
||||
err := p.rockService.db.WithContext(ctx).
|
||||
Where("assigned_order_no = ?", order.OrderNo).
|
||||
Order("id DESC").
|
||||
First(&token).Error
|
||||
if err != nil {
|
||||
return &ProviderSyncResult{
|
||||
Status: "",
|
||||
}, nil
|
||||
}
|
||||
|
||||
switch token.Status {
|
||||
case model.RockStatusRedeemed:
|
||||
return &ProviderSyncResult{
|
||||
Status: "success",
|
||||
ProviderOrderNo: fmt.Sprintf("%d", token.UpstreamFulfillID),
|
||||
GameUID: token.ActualRoleID,
|
||||
RoleName: token.ActualRoleName,
|
||||
RoleArea: token.ActualChannel,
|
||||
}, nil
|
||||
case model.RockStatusMismatch:
|
||||
return &ProviderSyncResult{
|
||||
Status: "failed",
|
||||
FailReason: token.MismatchReason,
|
||||
}, nil
|
||||
default:
|
||||
return &ProviderSyncResult{
|
||||
Status: "delivering",
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (p *RockProvider) Cancel(ctx context.Context, order *model.FulfillmentOrder) error {
|
||||
if p.rockService == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
// 若订单尚未扫码绑定成功,将处于 using 状态的 Token 安全重置回 available
|
||||
var token model.RockToken
|
||||
err := p.rockService.db.WithContext(ctx).
|
||||
Where("assigned_order_no = ? AND status = ?", order.OrderNo, model.RockStatusUsing).
|
||||
First(&token).Error
|
||||
if err == nil {
|
||||
_ = p.rockService.db.WithContext(ctx).Model(&token).Updates(map[string]interface{}{
|
||||
"status": model.RockStatusAvailable,
|
||||
"assigned_order_no": "",
|
||||
"expected_uid": "",
|
||||
}).Error
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
"affiliate_dash/internal/testdb"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func newRockTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
return testdb.New(t,
|
||||
&model.Merchant{},
|
||||
&model.Product{},
|
||||
&model.MerchantProduct{},
|
||||
&model.FulfillmentOrder{},
|
||||
&model.RockConfig{},
|
||||
&model.RockToken{},
|
||||
)
|
||||
}
|
||||
|
||||
func TestRockProvider_KillSwitch(t *testing.T) {
|
||||
db := newRockTestDB(t)
|
||||
client := NewRockClient("https://example.com")
|
||||
rockSvc := NewRockService(db, client)
|
||||
provider := NewRockProvider(rockSvc)
|
||||
|
||||
// 1. 初始化配置并关闭总开关
|
||||
cfg, err := rockSvc.GetConfig(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("get config: %v", err)
|
||||
}
|
||||
f := false
|
||||
_, err = rockSvc.UpdateConfig(context.Background(), UpdateRockConfigReq{
|
||||
AutoDeliveryEnabled: &f,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("update config: %v", err)
|
||||
}
|
||||
|
||||
order := &model.FulfillmentOrder{
|
||||
OrderNo: "ROCK-ORDER-001",
|
||||
ProductSKU: model.RockSKUBlackTshirt,
|
||||
}
|
||||
|
||||
// 2. PrepareDelivery 检查是否触发熔断
|
||||
state, err := provider.PrepareDelivery(context.Background(), order, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("prepare delivery: %v", err)
|
||||
}
|
||||
if state.CanShip {
|
||||
t.Fatalf("总开关关闭时应该不可发货")
|
||||
}
|
||||
if !strings.Contains(state.CannotShipReason, "维护中") {
|
||||
t.Fatalf("熔断提示信息不符: %s", state.CannotShipReason)
|
||||
}
|
||||
|
||||
// 3. 恢复开启总开关
|
||||
tr := true
|
||||
_, _ = rockSvc.UpdateConfig(context.Background(), UpdateRockConfigReq{
|
||||
AutoDeliveryEnabled: &tr,
|
||||
})
|
||||
_ = cfg
|
||||
}
|
||||
|
||||
func TestRockProvider_AntiGhostAndUIDMismatch(t *testing.T) {
|
||||
db := newRockTestDB(t)
|
||||
|
||||
// Mock 上游 0666.pro 响应
|
||||
var currentBoundAccount string
|
||||
var currentBoundRoleID string
|
||||
var currentBindChangedAt string
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if strings.HasPrefix(r.URL.Path, "/api/redeem/") {
|
||||
_ = json.NewEncoder(w).Encode(RockRedeemDetailResponse{
|
||||
ID: 151153,
|
||||
RedeemCode: "mock_redeem_code",
|
||||
Color: "black",
|
||||
Status: "available",
|
||||
BindURL: "https://gp.qq.com/cp/mock_bind",
|
||||
})
|
||||
return
|
||||
}
|
||||
if strings.HasSuffix(r.URL.Path, "/refresh") {
|
||||
var resp RockRefreshResponse
|
||||
if currentBoundRoleID != "" {
|
||||
resp.Binding.Bound = true
|
||||
resp.Binding.RoleName = currentBoundAccount
|
||||
resp.Binding.RoleID = currentBoundRoleID
|
||||
resp.Binding.Channel = "安卓-微信"
|
||||
resp.Token.BindChangedAt = currentBindChangedAt
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := NewRockClient(server.URL)
|
||||
rockSvc := NewRockService(db, client)
|
||||
provider := NewRockProvider(rockSvc)
|
||||
|
||||
// 预先插入 1 个可用 Token,模拟历史残留数据
|
||||
now := time.Now()
|
||||
token := model.RockToken{
|
||||
UpstreamTokenID: "151153",
|
||||
Token: "mock_jwt_token",
|
||||
RedeemCode: "mock_redeem_code",
|
||||
Color: model.RockColorBlack,
|
||||
Status: model.RockStatusAvailable,
|
||||
ClaimedAt: &now,
|
||||
}
|
||||
db.Create(&token)
|
||||
|
||||
// 模拟场景 A:上游初始已有历史残留账号“总荒凉”(3751279035)
|
||||
currentBoundAccount = "总荒凉"
|
||||
currentBoundRoleID = "3751279035"
|
||||
currentBindChangedAt = "2026-10-01 10:00:00"
|
||||
|
||||
// 买家期望 UID 为 3688825401
|
||||
expectedUID := "3688825401"
|
||||
order := &model.FulfillmentOrder{
|
||||
OrderNo: "ROCK-ORDER-002",
|
||||
ProductSKU: model.RockSKUBlackTshirt,
|
||||
ResultData: fmt.Sprintf(`{"expected_uid":"%s"}`, expectedUID),
|
||||
}
|
||||
|
||||
// 1. 买家点击生成绑定二维码
|
||||
bindRes, err := provider.Bind(context.Background(), order, expectedUID)
|
||||
if err != nil {
|
||||
t.Fatalf("bind error: %v", err)
|
||||
}
|
||||
if bindRes.BindURL == "" {
|
||||
t.Fatalf("bind URL 不应为空")
|
||||
}
|
||||
|
||||
// 2. 买家尚未扫码,轮询 CheckBind:应当识别出历史残留并忽略,不报错也不发货
|
||||
check1, err := provider.CheckBind(context.Background(), order, bindRes.BindUUID)
|
||||
if err != nil {
|
||||
t.Fatalf("check bind: %v", err)
|
||||
}
|
||||
if check1.Bound {
|
||||
t.Fatalf("买家尚未扫码,不应判定为绑定成功(被历史残留误导)")
|
||||
}
|
||||
|
||||
// 3. 买家扫错了号!拿了微信小号扫码,实际角色变成了“错误小号”(9999999999)
|
||||
currentBoundAccount = "错误小号"
|
||||
currentBoundRoleID = "9999999999"
|
||||
currentBindChangedAt = "2026-10-05 14:00:00"
|
||||
|
||||
check2, err := provider.CheckBind(context.Background(), order, bindRes.BindUUID)
|
||||
if err != nil {
|
||||
t.Fatalf("check bind mismatch: %v", err)
|
||||
}
|
||||
if !check2.Mismatch {
|
||||
t.Fatalf("UID 不匹配时必须标记 mismatch = true!")
|
||||
}
|
||||
if check2.Bound {
|
||||
t.Fatalf("UID 不匹配时严禁 bound = true!")
|
||||
}
|
||||
|
||||
// 检查数据库中 Token 状态是否已跃迁为 mismatch
|
||||
var dbToken model.RockToken
|
||||
db.First(&dbToken, token.ID)
|
||||
if dbToken.Status != model.RockStatusMismatch {
|
||||
t.Fatalf("Token 状态应为 mismatch,当前为 %s", dbToken.Status)
|
||||
}
|
||||
if !strings.Contains(dbToken.MismatchReason, "不一致") {
|
||||
t.Fatalf("mismatch reason 异常: %s", dbToken.MismatchReason)
|
||||
}
|
||||
|
||||
// 4. 客服确认买家输错,执行人工解冻重置
|
||||
err = rockSvc.ResetMismatchToken(context.Background(), token.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("reset mismatch token: %v", err)
|
||||
}
|
||||
db.First(&dbToken, token.ID)
|
||||
if dbToken.Status != model.RockStatusAvailable {
|
||||
t.Fatalf("重置后状态应为 available,当前为 %s", dbToken.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRockProvider_SubmitBlueAndBlack(t *testing.T) {
|
||||
db := newRockTestDB(t)
|
||||
|
||||
var receivedSkin string
|
||||
var receivedCurrency string
|
||||
var receivedAccount string
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if strings.HasPrefix(r.URL.Path, "/api/redeem/") {
|
||||
var req map[string]string
|
||||
_ = json.NewDecoder(r.Body).Decode(&req)
|
||||
receivedSkin = req["skin"]
|
||||
receivedCurrency = req["currency"]
|
||||
receivedAccount = req["account"]
|
||||
|
||||
resp := RockRedeemResponse{
|
||||
Success: true,
|
||||
Message: "发放成功",
|
||||
}
|
||||
resp.Delivery.Skin = receivedSkin
|
||||
resp.Delivery.Currency = receivedCurrency
|
||||
resp.Delivery.Quantity = 10
|
||||
resp.Delivery.FulfillID = 888999
|
||||
_ = json.NewEncoder(w).Encode(resp)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := NewRockClient(server.URL)
|
||||
rockSvc := NewRockService(db, client)
|
||||
provider := NewRockProvider(rockSvc)
|
||||
|
||||
// 场景 A:兑换蓝色运动服上衣
|
||||
now := time.Now()
|
||||
tokenBlue := model.RockToken{
|
||||
UpstreamTokenID: "151154",
|
||||
Token: "token_blue",
|
||||
RedeemCode: "code_blue",
|
||||
Color: model.RockColorBlack, // 通用黑色 Token
|
||||
Status: model.RockStatusBound,
|
||||
AssignedOrderNo: "ORDER-BLUE-001",
|
||||
ExpectedUID: "4331027062",
|
||||
ActualRoleName: "破浪小王子",
|
||||
ActualRoleID: "4331027062",
|
||||
BoundAt: &now,
|
||||
}
|
||||
db.Create(&tokenBlue)
|
||||
|
||||
orderBlue := &model.FulfillmentOrder{
|
||||
OrderNo: "ORDER-BLUE-001",
|
||||
ProductSKU: model.RockSKUBlueSportswear, // 蓝色运动服
|
||||
ResultData: `{"expected_uid":"4331027062"}`,
|
||||
}
|
||||
|
||||
submitRes, err := provider.Submit(context.Background(), orderBlue, "4331027062", fmt.Sprintf("%d", tokenBlue.ID))
|
||||
if err != nil {
|
||||
t.Fatalf("submit blue error: %v", err)
|
||||
}
|
||||
|
||||
if receivedSkin != model.RockSkinBlueSportswear {
|
||||
t.Fatalf("蓝色运动服发货应传入 %s,实际为 %s", model.RockSkinBlueSportswear, receivedSkin)
|
||||
}
|
||||
if receivedAccount != "破浪小王子" {
|
||||
t.Fatalf("发货账号应为 破浪小王子,实际为 %s", receivedAccount)
|
||||
}
|
||||
if submitRes.ProviderOrderNo != "888999" {
|
||||
t.Fatalf("期望官方 fulfillId 888999,实际为 %s", submitRes.ProviderOrderNo)
|
||||
}
|
||||
|
||||
// 检查数据库记录
|
||||
var dbToken model.RockToken
|
||||
db.First(&dbToken, tokenBlue.ID)
|
||||
if dbToken.Status != model.RockStatusRedeemed {
|
||||
t.Fatalf("发货后 Token 状态应为 redeemed,当前为 %s", dbToken.Status)
|
||||
}
|
||||
if dbToken.UpstreamFulfillID != 888999 {
|
||||
t.Fatalf("fulfillID 记录错误: %d", dbToken.UpstreamFulfillID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRockService_StatsAndPurchase(t *testing.T) {
|
||||
db := newRockTestDB(t)
|
||||
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if r.URL.Path == "/api/me" {
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"user": map[string]interface{}{
|
||||
"id": 10028,
|
||||
"username": "王大锤",
|
||||
"role": "merchant",
|
||||
"points": 8271.2,
|
||||
"status": "active",
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/user/tokens/claim" {
|
||||
_ = json.NewEncoder(w).Encode(map[string]interface{}{
|
||||
"tokens": []map[string]interface{}{
|
||||
{
|
||||
"id": 20001,
|
||||
"token": "token_mock_1",
|
||||
"color": "black",
|
||||
"region": "Q/V可用",
|
||||
"status": "available",
|
||||
"redeem_code": "code_mock_1",
|
||||
"claimed_at": "2026-10-05 14:00:00",
|
||||
},
|
||||
{
|
||||
"id": 20002,
|
||||
"token": "token_mock_2",
|
||||
"color": "black",
|
||||
"region": "Q/V可用",
|
||||
"status": "available",
|
||||
"redeem_code": "code_mock_2",
|
||||
"claimed_at": "2026-10-05 14:00:00",
|
||||
},
|
||||
},
|
||||
})
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
client := NewRockClient(server.URL)
|
||||
rockSvc := NewRockService(db, client)
|
||||
|
||||
// 1. 测试 Token 连通性
|
||||
me, err := rockSvc.TestConnection(context.Background(), "mock_bearer_token")
|
||||
if err != nil {
|
||||
t.Fatalf("test connection: %v", err)
|
||||
}
|
||||
if me.User.Username != "王大锤" || me.User.Points != 8271.2 {
|
||||
t.Fatalf("用户信息解析不符: %+v", me.User)
|
||||
}
|
||||
|
||||
// 2. 更新系统配置设置 BearerToken
|
||||
tokenStr := "mock_bearer_token"
|
||||
_, err = rockSvc.UpdateConfig(context.Background(), UpdateRockConfigReq{
|
||||
BearerToken: &tokenStr,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("update config: %v", err)
|
||||
}
|
||||
|
||||
// 3. 采购 2 个黑色通用 Token
|
||||
tokens, err := rockSvc.PurchaseTokens(context.Background(), 2, false)
|
||||
if err != nil {
|
||||
t.Fatalf("purchase tokens: %v", err)
|
||||
}
|
||||
if len(tokens) != 2 {
|
||||
t.Fatalf("期望采购 2 个,实际返回 %d", len(tokens))
|
||||
}
|
||||
|
||||
// 4. 检查库存统计
|
||||
stats, err := rockSvc.GetStats(context.Background())
|
||||
if err != nil {
|
||||
t.Fatalf("get stats: %v", err)
|
||||
}
|
||||
if stats.AvailableStock != 2 {
|
||||
t.Fatalf("期望可用库存为 2,实际为 %d", stats.AvailableStock)
|
||||
}
|
||||
if stats.Username != "王大锤" {
|
||||
t.Fatalf("期望采购商户名为王大锤,实际为 %s", stats.Username)
|
||||
}
|
||||
|
||||
// 5. 分页查询列表
|
||||
list, total, err := rockSvc.ListTokens(context.Background(), 1, 10, "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("list tokens: %v", err)
|
||||
}
|
||||
if total != 2 || len(list) != 2 {
|
||||
t.Fatalf("期望查询到 2 条,实际为 total=%d len=%d", total, len(list))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RockClient 负责与 0666.pro 平台进行 HTTP 通信
|
||||
type RockClient struct {
|
||||
baseURL string
|
||||
httpClient *http.Client
|
||||
}
|
||||
|
||||
func NewRockClient(baseURL string) *RockClient {
|
||||
base := strings.TrimRight(baseURL, "/")
|
||||
if base == "" {
|
||||
base = "https://0666.pro"
|
||||
}
|
||||
return &RockClient{
|
||||
baseURL: base,
|
||||
httpClient: &http.Client{
|
||||
Timeout: 15 * time.Second,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type RockMeResponse struct {
|
||||
User struct {
|
||||
ID uint64 `json:"id"`
|
||||
Username string `json:"username"`
|
||||
Role string `json:"role"`
|
||||
Points float64 `json:"points"`
|
||||
Status string `json:"status"`
|
||||
} `json:"user"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type RockClaimedToken struct {
|
||||
ID int64 `json:"id"`
|
||||
Token string `json:"token"`
|
||||
Color string `json:"color"`
|
||||
Region string `json:"region"`
|
||||
Status string `json:"status"`
|
||||
RedeemCode string `json:"redeem_code"`
|
||||
ClaimedAt string `json:"claimed_at"`
|
||||
}
|
||||
|
||||
type RockClaimResponse struct {
|
||||
Tokens []RockClaimedToken `json:"tokens"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type RockRedeemDetailResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
RedeemCode string `json:"redeem_code"`
|
||||
Color string `json:"color"`
|
||||
Status string `json:"status"`
|
||||
BindURL string `json:"bindUrl"`
|
||||
QRURL string `json:"qrUrl"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type RockDeliveryItem struct {
|
||||
SkinID int `json:"skinId"`
|
||||
Skin string `json:"skin"`
|
||||
CurrencyID int `json:"currencyId"`
|
||||
Currency string `json:"currency"`
|
||||
CurrencyQuantity int `json:"currencyQuantity"`
|
||||
Time string `json:"time"`
|
||||
Role string `json:"role"`
|
||||
Message string `json:"message"`
|
||||
FulfillID int64 `json:"fulfillId"`
|
||||
Membership int `json:"membership"`
|
||||
}
|
||||
|
||||
type RockRefreshResponse struct {
|
||||
Binding struct {
|
||||
Bound bool `json:"bound"`
|
||||
RoleName string `json:"roleName"`
|
||||
RoleID string `json:"roleId"`
|
||||
Channel string `json:"channel"`
|
||||
} `json:"binding"`
|
||||
Token struct {
|
||||
ID int64 `json:"id"`
|
||||
Status string `json:"status"`
|
||||
BoundAccount string `json:"bound_account"`
|
||||
BoundAccountID string `json:"bound_account_id"`
|
||||
PreviousBoundAccount string `json:"previous_bound_account"`
|
||||
BindChangedAt string `json:"bind_changed_at"`
|
||||
BindChangeType string `json:"bind_change_type"`
|
||||
} `json:"token"`
|
||||
DeliveryList []RockDeliveryItem `json:"deliveryList"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type RockRedeemResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message"`
|
||||
Delivery struct {
|
||||
Skin string `json:"skin"`
|
||||
Currency string `json:"currency"`
|
||||
Quantity int `json:"quantity"`
|
||||
FulfillID int64 `json:"fulfillId"`
|
||||
} `json:"delivery"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
type RockExchangeRecordsResponse struct {
|
||||
Records []struct {
|
||||
ID int64 `json:"id"`
|
||||
TokenID int64 `json:"token_id"`
|
||||
Skin string `json:"skin"`
|
||||
Currency string `json:"currency"`
|
||||
Quantity int `json:"quantity"`
|
||||
Role string `json:"role"`
|
||||
RoleID string `json:"role_id"`
|
||||
FulfillID int64 `json:"fulfill_id"`
|
||||
RedeemedAt string `json:"redeemed_at"`
|
||||
ClaimedAt string `json:"claimed_at"`
|
||||
RedeemCode string `json:"redeem_code"`
|
||||
DeliveryUser string `json:"delivery_user"`
|
||||
} `json:"records"`
|
||||
Pagination struct {
|
||||
Page int `json:"page"`
|
||||
PageSize int `json:"pageSize"`
|
||||
Total int `json:"total"`
|
||||
TotalPages int `json:"totalPages"`
|
||||
} `json:"pagination"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// GetMe 获取商户个人信息及积分
|
||||
func (c *RockClient) GetMe(ctx context.Context, bearerToken string) (*RockMeResponse, error) {
|
||||
reqURL := fmt.Sprintf("%s/api/me", c.baseURL)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", strings.TrimSpace(bearerToken)))
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求 0666 /api/me 失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取响应失败: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode == http.StatusUnauthorized {
|
||||
return nil, fmt.Errorf("上游 Bearer Token 已失效或未授权 (401)")
|
||||
}
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("上游返回错误状态码 %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var res RockMeResponse
|
||||
if err := json.Unmarshal(body, &res); err != nil {
|
||||
return nil, fmt.Errorf("解析 /api/me 响应失败: %w", err)
|
||||
}
|
||||
if res.User.Username == "" && res.Error != "" {
|
||||
return nil, fmt.Errorf("上游业务错误: %s", res.Error)
|
||||
}
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
// ClaimTokens 批量提取采购 Token
|
||||
func (c *RockClient) ClaimTokens(ctx context.Context, bearerToken string, color string, count int) ([]RockClaimedToken, error) {
|
||||
if count <= 0 {
|
||||
return nil, fmt.Errorf("提取数量必须大于 0")
|
||||
}
|
||||
reqURL := fmt.Sprintf("%s/api/user/tokens/claim", c.baseURL)
|
||||
payload := map[string]interface{}{
|
||||
"color": color,
|
||||
"count": fmt.Sprintf("%d", count),
|
||||
}
|
||||
jsonBytes, _ := json.Marshal(payload)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(jsonBytes))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", strings.TrimSpace(bearerToken)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求 0666 claim 失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 claim 响应失败: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("上游 claim 接口返回错误码 %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var res RockClaimResponse
|
||||
if err := json.Unmarshal(body, &res); err != nil {
|
||||
return nil, fmt.Errorf("解析 claim 响应失败: %w", err)
|
||||
}
|
||||
if len(res.Tokens) == 0 && res.Error != "" {
|
||||
return nil, fmt.Errorf("上游 claim 失败: %s", res.Error)
|
||||
}
|
||||
return res.Tokens, nil
|
||||
}
|
||||
|
||||
// GetRedeemDetail 根据 redeem_code 免登录获取腾讯官方绑定链接与状态
|
||||
func (c *RockClient) GetRedeemDetail(ctx context.Context, redeemCode string) (*RockRedeemDetailResponse, error) {
|
||||
reqURL := fmt.Sprintf("%s/api/redeem/%s", c.baseURL, url.PathEscape(redeemCode))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求 0666 /api/redeem/{code} 失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 redeem 详情响应失败: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("上游 redeem 详情接口返回错误码 %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var res RockRedeemDetailResponse
|
||||
if err := json.Unmarshal(body, &res); err != nil {
|
||||
return nil, fmt.Errorf("解析 redeem 详情失败: %w", err)
|
||||
}
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
// RefreshToken 刷新 Token 绑定状态并获取官方履约结果
|
||||
func (c *RockClient) RefreshToken(ctx context.Context, bearerToken string, upstreamTokenID string) (*RockRefreshResponse, error) {
|
||||
reqURL := fmt.Sprintf("%s/api/user/tokens/%s/refresh", c.baseURL, url.PathEscape(upstreamTokenID))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bearerToken != "" {
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", strings.TrimSpace(bearerToken)))
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求 0666 refresh 失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 refresh 响应失败: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("上游 refresh 接口返回错误码 %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var res RockRefreshResponse
|
||||
if err := json.Unmarshal(body, &res); err != nil {
|
||||
return nil, fmt.Errorf("解析 refresh 响应失败: %w", err)
|
||||
}
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
// RedeemSkin 执行最终皮肤兑换发货
|
||||
func (c *RockClient) RedeemSkin(ctx context.Context, upstreamTokenID, skin, currency, account string) (*RockRedeemResponse, error) {
|
||||
reqURL := fmt.Sprintf("%s/api/redeem/%s", c.baseURL, url.PathEscape(upstreamTokenID))
|
||||
payload := map[string]interface{}{
|
||||
"skin": skin,
|
||||
"currency": currency,
|
||||
"account": account,
|
||||
}
|
||||
jsonBytes, _ := json.Marshal(payload)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(jsonBytes))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求 0666 兑换发货接口失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取兑换响应失败: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("上游兑换发货接口返回错误码 %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var res RockRedeemResponse
|
||||
if err := json.Unmarshal(body, &res); err != nil {
|
||||
return nil, fmt.Errorf("解析兑换响应失败: %w", err)
|
||||
}
|
||||
if !res.Success && res.Error != "" {
|
||||
return nil, fmt.Errorf("上游兑换失败: %s", res.Error)
|
||||
}
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
// QueryExchangeRecords 异步查询兑换对账记录
|
||||
func (c *RockClient) QueryExchangeRecords(ctx context.Context, bearerToken string, page, pageSize int, search string) (*RockExchangeRecordsResponse, error) {
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
reqURL := fmt.Sprintf("%s/api/user/exchange-records?page=%d&pageSize=%d&search=%s", c.baseURL, page, pageSize, url.QueryEscape(search))
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, reqURL, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", strings.TrimSpace(bearerToken)))
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("请求 0666 exchange-records 失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取对账响应失败: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("上游对账接口返回错误码 %d: %s", resp.StatusCode, string(body))
|
||||
}
|
||||
|
||||
var res RockExchangeRecordsResponse
|
||||
if err := json.Unmarshal(body, &res); err != nil {
|
||||
return nil, fmt.Errorf("解析对账响应失败: %w", err)
|
||||
}
|
||||
return &res, nil
|
||||
}
|
||||
|
||||
// ReportAbnormal 上报异常 Token
|
||||
func (c *RockClient) ReportAbnormal(ctx context.Context, bearerToken, upstreamTokenID, reason string) error {
|
||||
reqURL := fmt.Sprintf("%s/api/user/tokens/%s/report", c.baseURL, url.PathEscape(upstreamTokenID))
|
||||
payload := map[string]string{"reason": reason}
|
||||
jsonBytes, _ := json.Marshal(payload)
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqURL, bytes.NewReader(jsonBytes))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", strings.TrimSpace(bearerToken)))
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Accept", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return fmt.Errorf("请求 0666 report 失败: %w", err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return fmt.Errorf("上报异常失败(%d): %s", resp.StatusCode, string(body))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,632 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"affiliate_dash/internal/model"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// RockService 负责管理 Rock 平台的配置、库存池、采购、UID强一致风控与状态机
|
||||
type RockService struct {
|
||||
db *gorm.DB
|
||||
client *RockClient
|
||||
mu sync.Mutex
|
||||
}
|
||||
|
||||
func NewRockService(db *gorm.DB, client *RockClient) *RockService {
|
||||
return &RockService{
|
||||
db: db,
|
||||
client: client,
|
||||
}
|
||||
}
|
||||
|
||||
// RockStatsResponse 看板与库存统计返回
|
||||
type RockStatsResponse struct {
|
||||
AvailableStock int64 `json:"available_stock"`
|
||||
UsingStock int64 `json:"using_stock"`
|
||||
BoundStock int64 `json:"bound_stock"`
|
||||
RedeemedStock int64 `json:"redeemed_stock"`
|
||||
MismatchStock int64 `json:"mismatch_stock"` // 绑定错误(待排查)
|
||||
AbnormalStock int64 `json:"abnormal_stock"`
|
||||
UpstreamPoints float64 `json:"upstream_points"`
|
||||
AutoDeliveryEnabled bool `json:"auto_delivery_enabled"`
|
||||
TokenWarningStock int `json:"token_warning_stock"`
|
||||
AutoPurchaseEnabled bool `json:"auto_purchase_enabled"`
|
||||
Username string `json:"username"`
|
||||
LastHeartbeatAt string `json:"last_heartbeat_at,omitempty"`
|
||||
}
|
||||
|
||||
type UpdateRockConfigReq struct {
|
||||
AutoDeliveryEnabled *bool `json:"auto_delivery_enabled"`
|
||||
BaseURL *string `json:"base_url"`
|
||||
BearerToken *string `json:"bearer_token"`
|
||||
MinPointsWarning *float64 `json:"min_points_warning"`
|
||||
TokenWarningStock *int `json:"token_warning_stock"`
|
||||
AutoPurchaseEnabled *bool `json:"auto_purchase_enabled"`
|
||||
AutoPurchaseCount *int `json:"auto_purchase_count"`
|
||||
PurchaseCooldownMinutes *int `json:"purchase_cooldown_minutes"`
|
||||
}
|
||||
|
||||
// GetConfig 获取当前配置,若无则初始化
|
||||
func (s *RockService) GetConfig(ctx context.Context) (*model.RockConfig, error) {
|
||||
var cfg model.RockConfig
|
||||
err := s.db.WithContext(ctx).First(&cfg, 1).Error
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
cfg = model.RockConfig{
|
||||
ID: 1,
|
||||
AutoDeliveryEnabled: true,
|
||||
BaseURL: "https://0666.pro",
|
||||
BearerToken: "",
|
||||
MinPointsWarning: 1050.00,
|
||||
TokenWarningStock: 10,
|
||||
AutoPurchaseEnabled: false,
|
||||
AutoPurchaseCount: 50,
|
||||
PurchaseCooldownMinutes: 10,
|
||||
}
|
||||
if createErr := s.db.WithContext(ctx).Create(&cfg).Error; createErr != nil {
|
||||
return nil, createErr
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &cfg, nil
|
||||
}
|
||||
|
||||
// UpdateConfig 更新系统配置
|
||||
func (s *RockService) UpdateConfig(ctx context.Context, req UpdateRockConfigReq) (*model.RockConfig, error) {
|
||||
cfg, err := s.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
updates := make(map[string]interface{})
|
||||
if req.AutoDeliveryEnabled != nil {
|
||||
updates["auto_delivery_enabled"] = *req.AutoDeliveryEnabled
|
||||
}
|
||||
if req.BaseURL != nil && strings.TrimSpace(*req.BaseURL) != "" {
|
||||
updates["base_url"] = strings.TrimRight(strings.TrimSpace(*req.BaseURL), "/")
|
||||
s.client.baseURL = updates["base_url"].(string)
|
||||
}
|
||||
if req.BearerToken != nil {
|
||||
updates["bearer_token"] = strings.TrimSpace(*req.BearerToken)
|
||||
}
|
||||
if req.MinPointsWarning != nil {
|
||||
updates["min_points_warning"] = *req.MinPointsWarning
|
||||
}
|
||||
if req.TokenWarningStock != nil {
|
||||
updates["token_warning_stock"] = *req.TokenWarningStock
|
||||
}
|
||||
if req.AutoPurchaseEnabled != nil {
|
||||
updates["auto_purchase_enabled"] = *req.AutoPurchaseEnabled
|
||||
}
|
||||
if req.AutoPurchaseCount != nil {
|
||||
updates["auto_purchase_count"] = *req.AutoPurchaseCount
|
||||
}
|
||||
if req.PurchaseCooldownMinutes != nil {
|
||||
updates["purchase_cooldown_minutes"] = *req.PurchaseCooldownMinutes
|
||||
}
|
||||
|
||||
if len(updates) > 0 {
|
||||
updates["updated_at"] = time.Now()
|
||||
if err := s.db.WithContext(ctx).Model(&model.RockConfig{}).Where("id = ?", cfg.ID).Updates(updates).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
return s.GetConfig(ctx)
|
||||
}
|
||||
|
||||
// TestConnection 测试上游 Token 连通性并同步最新用户信息与积分
|
||||
func (s *RockService) TestConnection(ctx context.Context, bearerToken string) (*RockMeResponse, error) {
|
||||
token := strings.TrimSpace(bearerToken)
|
||||
if token == "" {
|
||||
cfg, err := s.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
token = cfg.BearerToken
|
||||
}
|
||||
if token == "" {
|
||||
return nil, fmt.Errorf("请先输入或配置上游 Bearer Token")
|
||||
}
|
||||
|
||||
me, err := s.client.GetMe(ctx, token)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 连通成功,顺便异步更新数据库快照
|
||||
now := time.Now()
|
||||
_ = s.db.WithContext(ctx).Model(&model.RockConfig{}).Where("id = 1").Updates(map[string]interface{}{
|
||||
"username": me.User.Username,
|
||||
"points": me.User.Points,
|
||||
"last_heartbeat_at": now,
|
||||
}).Error
|
||||
|
||||
return me, nil
|
||||
}
|
||||
|
||||
// GetStats 获取概览统计
|
||||
func (s *RockService) GetStats(ctx context.Context) (*RockStatsResponse, error) {
|
||||
cfg, err := s.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var stats RockStatsResponse
|
||||
stats.AutoDeliveryEnabled = cfg.AutoDeliveryEnabled
|
||||
stats.TokenWarningStock = cfg.TokenWarningStock
|
||||
stats.AutoPurchaseEnabled = cfg.AutoPurchaseEnabled
|
||||
stats.UpstreamPoints = cfg.Points
|
||||
stats.Username = cfg.Username
|
||||
if cfg.LastHeartbeatAt != nil {
|
||||
stats.LastHeartbeatAt = cfg.LastHeartbeatAt.Format("2006-01-02 15:04:05")
|
||||
}
|
||||
|
||||
type CountResult struct {
|
||||
Status string
|
||||
Total int64
|
||||
}
|
||||
var results []CountResult
|
||||
err = s.db.WithContext(ctx).Model(&model.RockToken{}).
|
||||
Select("status, count(*) as total").
|
||||
Group("status").
|
||||
Scan(&results).Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, r := range results {
|
||||
switch r.Status {
|
||||
case model.RockStatusAvailable:
|
||||
stats.AvailableStock = r.Total
|
||||
case model.RockStatusUsing:
|
||||
stats.UsingStock = r.Total
|
||||
case model.RockStatusBound:
|
||||
stats.BoundStock = r.Total
|
||||
case model.RockStatusRedeemed:
|
||||
stats.RedeemedStock = r.Total
|
||||
case model.RockStatusMismatch:
|
||||
stats.MismatchStock = r.Total
|
||||
case model.RockStatusAbnormal:
|
||||
stats.AbnormalStock = r.Total
|
||||
}
|
||||
}
|
||||
|
||||
return &stats, nil
|
||||
}
|
||||
|
||||
// PurchaseTokens 执行采购并批量入库(通用黑色 Token)
|
||||
func (s *RockService) PurchaseTokens(ctx context.Context, count int, isAuto bool) ([]model.RockToken, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
cfg, err := s.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if cfg.BearerToken == "" {
|
||||
return nil, fmt.Errorf("尚未配置上游 Bearer Token,无法执行采购")
|
||||
}
|
||||
|
||||
// 自动补货防抖冷却检查
|
||||
now := time.Now()
|
||||
if isAuto && cfg.LastPurchasedAt != nil {
|
||||
cooldown := time.Duration(cfg.PurchaseCooldownMinutes) * time.Minute
|
||||
if now.Sub(*cfg.LastPurchasedAt) < cooldown {
|
||||
return nil, fmt.Errorf("自动采购处于冷却中(冷却时间 %d 分钟)", cfg.PurchaseCooldownMinutes)
|
||||
}
|
||||
}
|
||||
|
||||
// 调上游 Claim 接口(统一下单黑色通用 Token)
|
||||
tokens, err := s.client.ClaimTokens(ctx, cfg.BearerToken, model.RockColorBlack, count)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("调用上游采购接口失败: %w", err)
|
||||
}
|
||||
|
||||
if len(tokens) == 0 {
|
||||
return nil, fmt.Errorf("上游未返回任何有效 Token")
|
||||
}
|
||||
|
||||
var dbTokens []model.RockToken
|
||||
for _, t := range tokens {
|
||||
dbTokens = append(dbTokens, model.RockToken{
|
||||
UpstreamTokenID: fmt.Sprintf("%d", t.ID),
|
||||
Token: t.Token,
|
||||
RedeemCode: t.RedeemCode,
|
||||
Color: model.RockColorBlack,
|
||||
Region: t.Region,
|
||||
Status: model.RockStatusAvailable,
|
||||
ClaimedAt: &now,
|
||||
})
|
||||
}
|
||||
|
||||
// 事务写入库存表
|
||||
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(&dbTokens).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
// 更新最后采购时间
|
||||
return tx.Model(&model.RockConfig{}).Where("id = ?", cfg.ID).Update("last_purchased_at", now).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("入库采购 Token 失败: %w", err)
|
||||
}
|
||||
|
||||
// 异步更新上游剩余积分快照
|
||||
go func() {
|
||||
bgCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
me, meErr := s.client.GetMe(bgCtx, cfg.BearerToken)
|
||||
if meErr == nil && me != nil {
|
||||
_ = s.db.Model(&model.RockConfig{}).Where("id = 1").Update("points", me.User.Points).Error
|
||||
}
|
||||
}()
|
||||
|
||||
return dbTokens, nil
|
||||
}
|
||||
|
||||
// CheckStockAndAutoPurchase 水位检查与自动采购触发
|
||||
func (s *RockService) CheckStockAndAutoPurchase(ctx context.Context) {
|
||||
cfg, err := s.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
var count int64
|
||||
s.db.WithContext(ctx).Model(&model.RockToken{}).
|
||||
Where("status = ? AND color = ?", model.RockStatusAvailable, model.RockColorBlack).
|
||||
Count(&count)
|
||||
|
||||
if count <= int64(cfg.TokenWarningStock) {
|
||||
log.Printf("[RockService] 可用库存预警: 当前仅存 %d 个 (预警阈值 %d)", count, cfg.TokenWarningStock)
|
||||
if cfg.AutoPurchaseEnabled {
|
||||
buyCount := cfg.AutoPurchaseCount
|
||||
if buyCount <= 0 {
|
||||
buyCount = 50
|
||||
}
|
||||
log.Printf("[RockService] 触发自动补货,采购数量: %d", buyCount)
|
||||
_, err := s.PurchaseTokens(ctx, buyCount, true)
|
||||
if err != nil {
|
||||
log.Printf("[RockService] 自动补货失败: %v", err)
|
||||
} else {
|
||||
log.Printf("[RockService] 自动补货成功,新增 %d 个 Token", buyCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// BindingSnapshot 保存分配 Token 时上游的绑定快照
|
||||
type BindingSnapshot struct {
|
||||
Bound bool `json:"bound"`
|
||||
RoleName string `json:"role_name"`
|
||||
RoleID string `json:"role_id"`
|
||||
Channel string `json:"channel"`
|
||||
BindChangedAt string `json:"bind_changed_at"`
|
||||
}
|
||||
|
||||
// AssignTokenForOrder 为指定订单锁定分配一个可用 Token
|
||||
func (s *RockService) AssignTokenForOrder(ctx context.Context, orderNo, expectedUID string) (*model.RockToken, *RockRedeemDetailResponse, error) {
|
||||
cfg, err := s.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !cfg.AutoDeliveryEnabled {
|
||||
return nil, nil, fmt.Errorf("Rock 自动发货通道已维护关闭")
|
||||
}
|
||||
|
||||
var token model.RockToken
|
||||
|
||||
// 1. 检查订单是否已分配过 Token
|
||||
err = s.db.WithContext(ctx).
|
||||
Where("assigned_order_no = ? AND status IN (?, ?)", orderNo, model.RockStatusUsing, model.RockStatusBound).
|
||||
First(&token).Error
|
||||
|
||||
if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// 2. 若尚未分配,锁定一个可用 Token (行锁防并发超卖)
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
err = s.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE", Options: "SKIP LOCKED"}).
|
||||
Where("status = ? AND color = ?", model.RockStatusAvailable, model.RockColorBlack).
|
||||
Order("id ASC").
|
||||
First(&token).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return fmt.Errorf("Rock平台库存不足,请联系管理员补货")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
token.Status = model.RockStatusUsing
|
||||
token.AssignedOrderNo = orderNo
|
||||
token.ExpectedUID = strings.TrimSpace(expectedUID)
|
||||
return tx.Save(&token).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
// 检查水位触发异步自动补货
|
||||
go s.CheckStockAndAutoPurchase(context.Background())
|
||||
}
|
||||
|
||||
// 3. 调上游获取绑定活动链接
|
||||
detail, err := s.client.GetRedeemDetail(ctx, token.RedeemCode)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("获取上游活动绑定链接失败: %w", err)
|
||||
}
|
||||
|
||||
// 4. 首次分配记录上游初始绑定快照(防范 Ghost-Binding 历史残留数据)
|
||||
if token.InitialBoundSnapshot == "" && cfg.BearerToken != "" {
|
||||
ref, refErr := s.client.RefreshToken(ctx, cfg.BearerToken, token.UpstreamTokenID)
|
||||
if refErr == nil && ref != nil {
|
||||
snap := BindingSnapshot{
|
||||
Bound: ref.Binding.Bound,
|
||||
RoleName: ref.Binding.RoleName,
|
||||
RoleID: ref.Binding.RoleID,
|
||||
Channel: ref.Binding.Channel,
|
||||
BindChangedAt: ref.Token.BindChangedAt,
|
||||
}
|
||||
snapBytes, _ := json.Marshal(snap)
|
||||
token.InitialBoundSnapshot = string(snapBytes)
|
||||
_ = s.db.WithContext(ctx).Model(&token).Update("initial_bound_snapshot", token.InitialBoundSnapshot).Error
|
||||
}
|
||||
}
|
||||
|
||||
return &token, detail, nil
|
||||
}
|
||||
|
||||
type CheckBindingResult struct {
|
||||
Bound bool `json:"bound"`
|
||||
RoleName string `json:"role_name"`
|
||||
RoleID string `json:"role_id"`
|
||||
Channel string `json:"channel"`
|
||||
ExpectedUID string `json:"expected_uid"`
|
||||
Mismatch bool `json:"mismatch"`
|
||||
Message string `json:"message"`
|
||||
UpstreamFulfillID int64 `json:"upstream_fulfill_id,omitempty"`
|
||||
}
|
||||
|
||||
// CheckBindingAndVerifyUID Anti-Ghost 基线比对与 UID 强一致门禁
|
||||
func (s *RockService) CheckBindingAndVerifyUID(ctx context.Context, tokenID uint, expectedUID string) (*CheckBindingResult, error) {
|
||||
cfg, err := s.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var token model.RockToken
|
||||
if err := s.db.WithContext(ctx).First(&token, tokenID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 若已经是 mismatch 状态,直接返回阻断提示
|
||||
if token.Status == model.RockStatusMismatch {
|
||||
return &CheckBindingResult{
|
||||
Bound: false,
|
||||
Mismatch: true,
|
||||
RoleName: token.ActualRoleName,
|
||||
RoleID: token.ActualRoleID,
|
||||
Channel: token.ActualChannel,
|
||||
ExpectedUID: token.ExpectedUID,
|
||||
Message: fmt.Sprintf("UID 不匹配阻断: %s", token.MismatchReason),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 调上游 refresh 接口
|
||||
ref, err := s.client.RefreshToken(ctx, cfg.BearerToken, token.UpstreamTokenID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("刷新绑定状态失败: %w", err)
|
||||
}
|
||||
|
||||
// 1. 检查上游是否已绑定
|
||||
if !ref.Binding.Bound || strings.TrimSpace(ref.Binding.RoleID) == "" {
|
||||
return &CheckBindingResult{
|
||||
Bound: false,
|
||||
Message: "等待买家微信/QQ扫码授权",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 2. Anti-Ghost 历史残留比对
|
||||
if token.InitialBoundSnapshot != "" {
|
||||
var snap BindingSnapshot
|
||||
if jsonErr := json.Unmarshal([]byte(token.InitialBoundSnapshot), &snap); jsonErr == nil {
|
||||
// 若当前绑定的角色、UID 与初始分配时完全一样且变更时间没有更新,说明买家还未扫码,仍是历史旧数据
|
||||
if snap.Bound && snap.RoleID == ref.Binding.RoleID && snap.BindChangedAt == ref.Token.BindChangedAt {
|
||||
return &CheckBindingResult{
|
||||
Bound: false,
|
||||
Message: "等待买家扫码(检测到历史绑定残留,已自动忽略)",
|
||||
}, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 核心门禁:UID 强一致校验
|
||||
trimmedExpected := strings.TrimSpace(expectedUID)
|
||||
if trimmedExpected == "" {
|
||||
trimmedExpected = strings.TrimSpace(token.ExpectedUID)
|
||||
}
|
||||
trimmedActual := strings.TrimSpace(ref.Binding.RoleID)
|
||||
|
||||
now := time.Now()
|
||||
if trimmedExpected != "" && trimmedActual != trimmedExpected {
|
||||
// 严禁发货!跃迁为 mismatch
|
||||
mismatchReason := fmt.Sprintf("预期UID(%s) 与 扫码UID(%s/%s) 不一致", trimmedExpected, ref.Binding.RoleName, trimmedActual)
|
||||
_ = s.db.WithContext(ctx).Model(&token).Updates(map[string]interface{}{
|
||||
"status": model.RockStatusMismatch,
|
||||
"actual_role_name": ref.Binding.RoleName,
|
||||
"actual_role_id": trimmedActual,
|
||||
"actual_channel": ref.Binding.Channel,
|
||||
"mismatch_at": now,
|
||||
"mismatch_reason": mismatchReason,
|
||||
}).Error
|
||||
|
||||
return &CheckBindingResult{
|
||||
Bound: false,
|
||||
Mismatch: true,
|
||||
RoleName: ref.Binding.RoleName,
|
||||
RoleID: trimmedActual,
|
||||
Channel: ref.Binding.Channel,
|
||||
ExpectedUID: trimmedExpected,
|
||||
Message: fmt.Sprintf("扫码角色UID(%s)与订单填写UID(%s)不一致,严禁发货!", trimmedActual, trimmedExpected),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 4. UID 一致,更新为 bound 成功状态
|
||||
_ = s.db.WithContext(ctx).Model(&token).Updates(map[string]interface{}{
|
||||
"status": model.RockStatusBound,
|
||||
"actual_role_name": ref.Binding.RoleName,
|
||||
"actual_role_id": trimmedActual,
|
||||
"actual_channel": ref.Binding.Channel,
|
||||
"bound_at": now,
|
||||
}).Error
|
||||
|
||||
return &CheckBindingResult{
|
||||
Bound: true,
|
||||
RoleName: ref.Binding.RoleName,
|
||||
RoleID: trimmedActual,
|
||||
Channel: ref.Binding.Channel,
|
||||
ExpectedUID: trimmedExpected,
|
||||
Message: "扫码授权成功,UID核验一致",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// RedeemTokenForOrder 执行最终发货兑换(动态判定皮肤)
|
||||
func (s *RockService) RedeemTokenForOrder(ctx context.Context, orderNo, sku, expectedUID string) (*RockRedeemResponse, error) {
|
||||
cfg, err := s.GetConfig(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !cfg.AutoDeliveryEnabled {
|
||||
return nil, fmt.Errorf("Rock 自动发货通道维护中,已关闭自动兑换")
|
||||
}
|
||||
|
||||
var token model.RockToken
|
||||
err = s.db.WithContext(ctx).
|
||||
Where("assigned_order_no = ? AND status = ?", orderNo, model.RockStatusBound).
|
||||
First(&token).Error
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, fmt.Errorf("未找到该订单已绑定的有效 Token,或当前状态不可发货")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 最终双重防御:核验 UID
|
||||
trimmedExpected := strings.TrimSpace(expectedUID)
|
||||
if trimmedExpected == "" {
|
||||
trimmedExpected = strings.TrimSpace(token.ExpectedUID)
|
||||
}
|
||||
if trimmedExpected != "" && token.ActualRoleID != trimmedExpected {
|
||||
return nil, fmt.Errorf("终审拦截:扫码UID(%s)与预期UID(%s)不符,禁止发货!", token.ActualRoleID, trimmedExpected)
|
||||
}
|
||||
|
||||
// 根据商品 SKU 动态决定兑换的皮肤名称
|
||||
targetSkin := model.RockSkinBlackTshirt
|
||||
if sku == model.RockSKUBlueSportswear {
|
||||
targetSkin = model.RockSkinBlueSportswear
|
||||
}
|
||||
|
||||
// 调上游兑换发货接口
|
||||
redeemResp, err := s.client.RedeemSkin(ctx, token.UpstreamTokenID, targetSkin, "幸运币", token.ActualRoleName)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("调用上游兑换失败: %w", err)
|
||||
}
|
||||
|
||||
// 提取官方 fulfillId,若兑换响应中没有则通过 refresh 提取
|
||||
fulfillID := redeemResp.Delivery.FulfillID
|
||||
now := time.Now()
|
||||
if fulfillID == 0 {
|
||||
ref, refErr := s.client.RefreshToken(ctx, cfg.BearerToken, token.UpstreamTokenID)
|
||||
if refErr == nil && len(ref.DeliveryList) > 0 {
|
||||
fulfillID = ref.DeliveryList[len(ref.DeliveryList)-1].FulfillID
|
||||
}
|
||||
}
|
||||
|
||||
// 状态跃迁至 redeemed
|
||||
_ = s.db.WithContext(ctx).Model(&token).Updates(map[string]interface{}{
|
||||
"status": model.RockStatusRedeemed,
|
||||
"upstream_fulfill_id": fulfillID,
|
||||
"target_skin": targetSkin,
|
||||
"target_currency": "幸运币",
|
||||
"target_currency_quantity": redeemResp.Delivery.Quantity,
|
||||
"redeemed_at": now,
|
||||
}).Error
|
||||
|
||||
return redeemResp, nil
|
||||
}
|
||||
|
||||
// ListTokens 分页查询 Token 列表
|
||||
func (s *RockService) ListTokens(ctx context.Context, page, pageSize int, status, search string) ([]model.RockToken, int64, error) {
|
||||
if page <= 0 {
|
||||
page = 1
|
||||
}
|
||||
if pageSize <= 0 {
|
||||
pageSize = 20
|
||||
}
|
||||
|
||||
db := s.db.WithContext(ctx).Model(&model.RockToken{})
|
||||
if strings.TrimSpace(status) != "" {
|
||||
db = db.Where("status = ?", strings.TrimSpace(status))
|
||||
}
|
||||
if strings.TrimSpace(search) != "" {
|
||||
term := "%" + strings.TrimSpace(search) + "%"
|
||||
db = db.Where("assigned_order_no LIKE ? OR expected_uid LIKE ? OR actual_role_name LIKE ? OR actual_role_id LIKE ? OR redeem_code LIKE ?",
|
||||
term, term, term, term, term)
|
||||
}
|
||||
|
||||
var total int64
|
||||
if err := db.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
var tokens []model.RockToken
|
||||
err := db.Order("id DESC").
|
||||
Offset((page - 1) * pageSize).
|
||||
Limit(pageSize).
|
||||
Find(&tokens).Error
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
return tokens, total, nil
|
||||
}
|
||||
|
||||
// ResetMismatchToken 客服人工重置解冻绑定错误的 Token
|
||||
func (s *RockService) ResetMismatchToken(ctx context.Context, tokenID uint) error {
|
||||
var token model.RockToken
|
||||
if err := s.db.WithContext(ctx).First(&token, tokenID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if token.Status != model.RockStatusMismatch {
|
||||
return fmt.Errorf("仅 mismatch 状态的 Token 允许人工解冻重置")
|
||||
}
|
||||
|
||||
// 重置回 available,清空订单关联
|
||||
return s.db.WithContext(ctx).Model(&token).Updates(map[string]interface{}{
|
||||
"status": model.RockStatusAvailable,
|
||||
"assigned_order_no": "",
|
||||
"expected_uid": "",
|
||||
"actual_role_name": "",
|
||||
"actual_role_id": "",
|
||||
"actual_channel": "",
|
||||
"initial_bound_snapshot": "",
|
||||
"mismatch_at": nil,
|
||||
"mismatch_reason": "",
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
Reference in New Issue
Block a user