273 lines
9.8 KiB
Go
273 lines
9.8 KiB
Go
package v1
|
|
|
|
// settle_handler_test.go S2-D2:消耗日汇总两端点——customer scope 强制收窄
|
|
// (带参越权请求覆盖不报错,stats 同口径)+手动回补落账断言。
|
|
// gin TestMode + sqlite;claims 由中间件注入模拟(stats_handler_test 同款)。
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/glebarez/sqlite"
|
|
"gorm.io/gorm"
|
|
|
|
"go-sms/internal/middleware"
|
|
"go-sms/internal/model/entity"
|
|
"go-sms/internal/service/settle"
|
|
)
|
|
|
|
// newSettleRouter 种子:账号 1/100 今日各 1 条成功明细(通道 1);返回注入器。
|
|
func newSettleRouter(t *testing.T) (*gin.Engine, *gorm.DB, func(*middleware.Claims)) {
|
|
return newSettleRouterWithPerm(t, nil)
|
|
}
|
|
|
|
// newSettleRouterWithPerm 可注入权限 checker(测试 403 路径);nil=仅要求已认证。
|
|
func newSettleRouterWithPerm(t *testing.T, perm middleware.PermissionChecker) (*gin.Engine, *gorm.DB, func(*middleware.Claims)) {
|
|
t.Helper()
|
|
gin.SetMode(gin.TestMode)
|
|
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if s, e := db.DB(); e == nil {
|
|
s.SetMaxOpenConns(1)
|
|
}
|
|
if err := db.AutoMigrate(&entity.MessageDetail{}, &entity.BillingConsumeLog{},
|
|
&entity.StatsChannelDaily{}, &entity.AccountUser{}, &entity.BillingOrder{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// 流水表手动建:idx_account_time 与 BillingOrder 同名,glebarez 索引名
|
|
// 全库唯一不查重(settle 包同款方言坑);无索引版本读写语义零影响。
|
|
if err := db.Exec(`CREATE TABLE IF NOT EXISTS account_balance_log (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
account_id INTEGER NOT NULL, biz_type TEXT, amount INTEGER,
|
|
balance_after INTEGER, ref_id TEXT, operator TEXT, remark TEXT,
|
|
created_at DATETIME DEFAULT CURRENT_TIMESTAMP)`).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
now := time.Now()
|
|
details := []entity.MessageDetail{
|
|
{SnowflakeModel: entity.SnowflakeModel{ID: 9100000001, CreatedAt: now},
|
|
TaskID: 800001, AccountID: 1, ChannelID: 1, Mobile: "13000000001",
|
|
Content: "t", Status: 2, Business: "sms", Fee: 1.5},
|
|
{SnowflakeModel: entity.SnowflakeModel{ID: 9100000002, CreatedAt: now},
|
|
TaskID: 800002, AccountID: 100, ChannelID: 1, Mobile: "13000000002",
|
|
Content: "t", Status: 2, Business: "sms", Fee: 2.5},
|
|
}
|
|
if err := db.Create(&details).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := db.Create(&entity.AccountUser{
|
|
Model: entity.Model{ID: 1}, Username: "admin", Role: "admin", Balance: 1000,
|
|
}).Error; err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
rg := gin.New()
|
|
api := rg.Group("/api/v1")
|
|
var claims *middleware.Claims
|
|
api.Use(func(c *gin.Context) {
|
|
if claims != nil {
|
|
c.Set(middleware.ContextKeyClaims, claims)
|
|
}
|
|
})
|
|
registerSettleRoutes(api, Deps{Settle: settle.NewService(db), Perm: perm})
|
|
return rg, db, func(cl *middleware.Claims) { claims = cl }
|
|
}
|
|
|
|
// TestSettleConsume_AdminSeesAll admin 全量;customer 强制收窄(带参越权覆盖)。
|
|
func TestSettleConsume_Scope(t *testing.T) {
|
|
rg, db, setClaims := newSettleRouter(t)
|
|
// 预落账(查询读事实源,不直查明细)。
|
|
svc := settle.NewService(db)
|
|
if _, _, err := svc.AggregateDay(t.Context(), time.Now()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
|
|
w := httptest.NewRecorder()
|
|
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/billing/consume", nil))
|
|
if w.Code != 200 {
|
|
t.Fatalf("admin status=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
var res struct {
|
|
Data struct {
|
|
Total int64 `json:"total"`
|
|
List []entity.BillingConsumeLog `json:"list"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Data.Total != 2 {
|
|
t.Fatalf("admin 应见全量 2 行,got %d", res.Data.Total)
|
|
}
|
|
|
|
// customer 带参越权(account_id=1):应被覆盖为自身 100。
|
|
setClaims(&middleware.Claims{AccountID: 100, Username: "cust", Roles: []string{"customer"}})
|
|
w = httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodGet, "/api/v1/billing/consume?account_id=1", nil)
|
|
rg.ServeHTTP(w, req)
|
|
if w.Code != 200 {
|
|
t.Fatalf("customer status=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Data.Total != 1 || len(res.Data.List) != 1 || res.Data.List[0].AccountID != 100 {
|
|
t.Fatalf("customer 应强制收窄到自身 100: total=%d list=%v", res.Data.Total, res.Data.List)
|
|
}
|
|
}
|
|
|
|
// TestSettleAggregate_Manual 手动回补:返回行数+落库断言;坏日期 4xx。
|
|
func TestSettleAggregate_Manual(t *testing.T) {
|
|
rg, db, setClaims := newSettleRouter(t)
|
|
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
|
|
|
|
w := httptest.NewRecorder()
|
|
rg.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/ops/settle/aggregate", nil))
|
|
if w.Code != 200 {
|
|
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
var res struct {
|
|
Data struct {
|
|
Day string `json:"day"`
|
|
AccountRows int64 `json:"account_rows"`
|
|
ChannelRows int64 `json:"channel_rows"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
// 缺省=昨日:种子明细是今天 → 0 行也合法;显式补今天断言 2/1。
|
|
w = httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/ops/settle/aggregate",
|
|
strings.NewReader(`{"date":"`+time.Now().Format("2006-01-02")+`"}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
rg.ServeHTTP(w, req)
|
|
if w.Code != 200 {
|
|
t.Fatalf("status=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Data.AccountRows != 2 || res.Data.ChannelRows != 1 {
|
|
t.Fatalf("今日回补应 account_rows=2/channel_rows=1: %+v", res.Data)
|
|
}
|
|
var n int64
|
|
db.Model(&entity.BillingConsumeLog{}).Count(&n)
|
|
if n != 2 {
|
|
t.Fatalf("billing_consume_log 落账=%d 期望 2", n)
|
|
}
|
|
|
|
// 坏日期参数。
|
|
w = httptest.NewRecorder()
|
|
req = httptest.NewRequest(http.MethodPost, "/api/v1/ops/settle/aggregate",
|
|
strings.NewReader(`{"date":"2026/11/14"}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
rg.ServeHTTP(w, req)
|
|
if w.Code == 200 {
|
|
t.Fatalf("坏日期应 4xx,got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
}
|
|
|
|
// TestSettleOrders_FullFlow 订单族全流程:创建(不动余额)→列表→confirm(余额+count)
|
|
// →重复 confirm HTTP 409+ISC:039 →驳回路径;二级权限 403。
|
|
func TestSettleOrders_FullFlow(t *testing.T) {
|
|
rg, db, setClaims := newSettleRouter(t)
|
|
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
|
|
|
|
// 创建(perm=nil:已认证即过,功能路径)。
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/billing/orders",
|
|
strings.NewReader(`{"account_id":1,"count":500,"amount":50.0,"pay_type":"bank"}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
rg.ServeHTTP(w, req)
|
|
if w.Code != 200 {
|
|
t.Fatalf("创建 status=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
var created struct {
|
|
Data entity.BillingOrder `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &created); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if created.Data.PayStatus != 0 || created.Data.ID == 0 {
|
|
t.Fatalf("订单字段错: %+v", created.Data)
|
|
}
|
|
var bal int64
|
|
db.Model(&entity.AccountUser{}).Where("id = ?", int64(1)).Pluck("balance", &bal)
|
|
if bal != 1000 {
|
|
t.Fatalf("创建不应动余额: %d", bal)
|
|
}
|
|
|
|
// 列表(admin 平台角色)。
|
|
w = httptest.NewRecorder()
|
|
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/billing/orders?pay_status=0", nil))
|
|
if w.Code != 200 {
|
|
t.Fatalf("列表 status=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
|
|
// confirm:余额+count。
|
|
w = httptest.NewRecorder()
|
|
req = httptest.NewRequest(http.MethodPost, "/api/v1/billing/orders/1/confirm", nil)
|
|
rg.ServeHTTP(w, req)
|
|
if w.Code != 200 {
|
|
t.Fatalf("confirm status=%d body=%s", w.Code, w.Body.String())
|
|
}
|
|
var res struct {
|
|
Data struct {
|
|
Balance int64 `json:"balance"`
|
|
} `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(w.Body.Bytes(), &res); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if res.Data.Balance != 1500 {
|
|
t.Fatalf("confirm 后余额=%d 期望 1500", res.Data.Balance)
|
|
}
|
|
|
|
// 重复 confirm → HTTP 409 + ISC:039。
|
|
w = httptest.NewRecorder()
|
|
rg.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/billing/orders/1/confirm", nil))
|
|
if w.Code != http.StatusConflict {
|
|
t.Fatalf("重复 confirm 应 409,got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
if !strings.Contains(w.Body.String(), "ISC:039") {
|
|
t.Fatalf("409 响应应带 ISC:039: %s", w.Body.String())
|
|
}
|
|
db.Model(&entity.AccountUser{}).Where("id = ?", int64(1)).Pluck("balance", &bal)
|
|
if bal != 1500 {
|
|
t.Fatalf("重复 confirm 后余额=%d 应保持 1500", bal)
|
|
}
|
|
}
|
|
|
|
// TestSettleOrders_PermissionAndScope 二级权限 403 与 customer 列表 403。
|
|
func TestSettleOrders_PermissionAndScope(t *testing.T) {
|
|
// 恒拒 checker:创建/confirm 应 403。
|
|
denyAll := middleware.PermissionChecker(func(*middleware.Claims, string, string) bool { return false })
|
|
rg, _, setClaims := newSettleRouterWithPerm(t, denyAll)
|
|
setClaims(&middleware.Claims{AccountID: 1, Username: "ops", Roles: []string{"ops"}})
|
|
w := httptest.NewRecorder()
|
|
req := httptest.NewRequest(http.MethodPost, "/api/v1/billing/orders",
|
|
strings.NewReader(`{"account_id":1,"count":100}`))
|
|
req.Header.Set("Content-Type", "application/json")
|
|
rg.ServeHTTP(w, req)
|
|
if w.Code != http.StatusForbidden {
|
|
t.Fatalf("无二级权限创建应 403,got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
|
|
// customer 列表 → 403(perm 不参与,角色判定)。
|
|
rg2, _, setClaims2 := newSettleRouter(t)
|
|
setClaims2(&middleware.Claims{AccountID: 100, Username: "cust", Roles: []string{"customer"}})
|
|
w = httptest.NewRecorder()
|
|
rg2.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/billing/orders", nil))
|
|
if w.Code != http.StatusForbidden {
|
|
t.Fatalf("customer 列表应 403,got %d body=%s", w.Code, w.Body.String())
|
|
}
|
|
}
|