473 lines
18 KiB
Go
473 lines
18 KiB
Go
package v1
|
||
|
||
// settle_handler_test.go S2-D2:消耗日汇总两端点——customer scope 强制收窄
|
||
// (带参越权请求覆盖不报错,stats 同口径)+手动回补落账断言。
|
||
// gin TestMode + sqlite;claims 由中间件注入模拟(stats_handler_test 同款)。
|
||
|
||
import (
|
||
"bytes"
|
||
"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{},
|
||
&entity.AccountPrice{}, &entity.ChannelPrice{}, &entity.ChannelChannel{}); 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())
|
||
}
|
||
}
|
||
|
||
// TestSettleBill_FullFlow D4 出账全流程:消耗落账→生成(时间线价)→阶梯配档重算
|
||
// →确认→结账(SettleRecord)→导出;已结拒重算;settle:write 权限门。
|
||
func TestSettleBill_FullFlow(t *testing.T) {
|
||
rg, db, setClaims := newSettleRouter(t)
|
||
// 种价格+消耗(账号1:0.10 价,11-10 succ=100)。
|
||
d, _ := time.ParseInLocation("2006-01-02", "2026-11-10", time.Local)
|
||
if err := db.AutoMigrate(&entity.AccountPrice{}, &entity.SettleLadder{},
|
||
&entity.SettleCustomer{}, &entity.SettleRecord{}); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := db.Create(&[]entity.AccountPrice{
|
||
{AccountID: 1, Business: "sms", Price: 0.10, EffectiveAt: d},
|
||
}).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := db.Create(&entity.BillingConsumeLog{
|
||
AccountID: 1, Business: "sms", StatDate: d, SuccessCount: 100,
|
||
}).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
|
||
|
||
// 生成:金额=100×0.10=10。
|
||
w := httptest.NewRecorder()
|
||
req := httptest.NewRequest(http.MethodPost, "/api/v1/settle/customer/generate",
|
||
strings.NewReader(`{"period":"2026-11"}`))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
rg.ServeHTTP(w, req)
|
||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"generated":1`) {
|
||
t.Fatalf("生成失败: %d %s", w.Code, w.Body.String())
|
||
}
|
||
// 配阶梯(0→0.05)重算:100×0.05=5。
|
||
w = httptest.NewRecorder()
|
||
req = httptest.NewRequest(http.MethodPost, "/api/v1/settle/ladder",
|
||
strings.NewReader(`{"owner_type":"account","owner_id":1,"tier_from":0,"price":0.05}`))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
rg.ServeHTTP(w, req)
|
||
if w.Code != 200 {
|
||
t.Fatalf("配档失败: %d %s", w.Code, w.Body.String())
|
||
}
|
||
w = httptest.NewRecorder()
|
||
req = httptest.NewRequest(http.MethodPost, "/api/v1/settle/customer/generate",
|
||
strings.NewReader(`{"period":"2026-11"}`))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
rg.ServeHTTP(w, req)
|
||
if !strings.Contains(w.Body.String(), `"recalculated":1`) {
|
||
t.Fatalf("重算失败: %s", w.Body.String())
|
||
}
|
||
// 列表校验金额 5。
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/settle/customer?account_id=1", nil))
|
||
if !strings.Contains(w.Body.String(), `"amount":5`) {
|
||
t.Fatalf("阶梯金额错: %s", w.Body.String())
|
||
}
|
||
// 确认→结账(SettleRecord direction=1)。
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodPost, "/api/v1/settle/customer/1/confirm", nil))
|
||
if w.Code != 200 {
|
||
t.Fatalf("确认失败: %d %s", w.Code, w.Body.String())
|
||
}
|
||
w = httptest.NewRecorder()
|
||
req = httptest.NewRequest(http.MethodPost, "/api/v1/settle/customer/1/settle",
|
||
strings.NewReader(`{"pay_type":"bank"}`))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
rg.ServeHTTP(w, req)
|
||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"settle_no":"SC202611-1"`) {
|
||
t.Fatalf("结账失败: %d %s", w.Code, w.Body.String())
|
||
}
|
||
// 已结拒重算。
|
||
w = httptest.NewRecorder()
|
||
req = httptest.NewRequest(http.MethodPost, "/api/v1/settle/customer/generate",
|
||
strings.NewReader(`{"period":"2026-11"}`))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
rg.ServeHTTP(w, req)
|
||
if !strings.Contains(w.Body.String(), `"skipped":1`) {
|
||
t.Fatalf("已结应 skipped: %s", w.Body.String())
|
||
}
|
||
// 导出 XLSX(PK 魔数)。
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1/settle/customer/1/export", nil))
|
||
if w.Code != 200 || !bytes.HasPrefix(w.Body.Bytes(), []byte("PK")) {
|
||
t.Fatalf("导出失败: %d", w.Code)
|
||
}
|
||
// 权限门:settle:write 恒拒 → 生成 403。
|
||
denyAll := middleware.PermissionChecker(func(*middleware.Claims, string, string) bool { return false })
|
||
rg2, _, setClaims2 := newSettleRouterWithPerm(t, denyAll)
|
||
setClaims2(&middleware.Claims{AccountID: 1, Username: "x", Roles: []string{"ops"}})
|
||
w = httptest.NewRecorder()
|
||
req = httptest.NewRequest(http.MethodPost, "/api/v1/settle/customer/generate",
|
||
strings.NewReader(`{"period":"2026-11"}`))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
rg2.ServeHTTP(w, req)
|
||
if w.Code != http.StatusForbidden {
|
||
t.Fatalf("无 settle:write 应 403: %d %s", w.Code, w.Body.String())
|
||
}
|
||
}
|
||
|
||
// TestSettleProfit_Endpoints S2-D5:利润双端点——平台角色可查(数值口径),
|
||
// customer 403;坏日期 400。种子=helper 明细(账号1/100 今日各 1 成功,通道1)
|
||
// + 价(账号1=1.0,通道1=0.5):acc1 rev1.0/cost0.5(分摊 1.0×1/2)/profit0.5;
|
||
// ch1 succ2/cost1.0/rev1.0/profit0(账号100 无账号行,消耗行不入结果)。
|
||
func TestSettleProfit_Endpoints(t *testing.T) {
|
||
rg, db, setClaims := newSettleRouter(t)
|
||
today := time.Now().Format("2006-01-02")
|
||
yday := time.Now().AddDate(0, 0, -1)
|
||
if err := db.Create(&[]entity.AccountPrice{
|
||
{AccountID: 1, Business: "sms", Price: 1.0, EffectiveAt: yday},
|
||
}).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if err := db.Create(&[]entity.ChannelPrice{
|
||
{ChannelID: 1, Price: 0.5, EffectiveAt: yday},
|
||
}).Error; err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if _, _, err := settle.NewService(db).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/stats/profit/users?date_from="+today+"&date_to="+today, nil))
|
||
if w.Code != 200 {
|
||
t.Fatalf("users status=%d body=%s", w.Code, w.Body.String())
|
||
}
|
||
var users struct {
|
||
Data struct {
|
||
Total int64 `json:"total"`
|
||
List []struct {
|
||
AccountID int64 `json:"account_id"`
|
||
Revenue float64 `json:"revenue"`
|
||
Cost float64 `json:"cost"`
|
||
Profit float64 `json:"profit"`
|
||
} `json:"list"`
|
||
Summary struct {
|
||
TotalRevenue float64 `json:"total_revenue"`
|
||
} `json:"summary"`
|
||
} `json:"data"`
|
||
}
|
||
if err := json.Unmarshal(w.Body.Bytes(), &users); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if users.Data.Total != 1 || len(users.Data.List) != 1 {
|
||
t.Fatalf("users 应 1 行(账号100 无账号实体): %+v", users.Data)
|
||
}
|
||
r := users.Data.List[0]
|
||
if r.AccountID != 1 || r.Revenue != 1.0 || r.Cost != 0.5 || r.Profit != 0.5 {
|
||
t.Fatalf("acc1 利润行错: %+v", r)
|
||
}
|
||
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
|
||
"/api/v1/stats/profit/channels?date_from="+today+"&date_to="+today, nil))
|
||
if w.Code != 200 {
|
||
t.Fatalf("channels status=%d body=%s", w.Code, w.Body.String())
|
||
}
|
||
var channels struct {
|
||
Data struct {
|
||
Total int64 `json:"total"`
|
||
List []struct {
|
||
ChannelID int64 `json:"channel_id"`
|
||
SuccessCount int64 `json:"success_count"`
|
||
Revenue float64 `json:"revenue"`
|
||
Cost float64 `json:"cost"`
|
||
Profit float64 `json:"profit"`
|
||
} `json:"list"`
|
||
} `json:"data"`
|
||
}
|
||
if err := json.Unmarshal(w.Body.Bytes(), &channels); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if channels.Data.Total != 1 || len(channels.Data.List) != 1 {
|
||
t.Fatalf("channels 应 1 行: %+v", channels.Data)
|
||
}
|
||
c := channels.Data.List[0]
|
||
if c.ChannelID != 1 || c.SuccessCount != 2 || c.Revenue != 1.0 || c.Cost != 1.0 || c.Profit != 0 {
|
||
t.Fatalf("ch1 利润行错: %+v", c)
|
||
}
|
||
|
||
// customer → 403;坏日期 → 400。
|
||
setClaims(&middleware.Claims{AccountID: 100, Username: "cust", Roles: []string{"customer"}})
|
||
for _, path := range []string{"/stats/profit/users", "/stats/profit/channels"} {
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet, "/api/v1"+path, nil))
|
||
if w.Code != http.StatusForbidden {
|
||
t.Fatalf("customer %s 应 403: %d %s", path, w.Code, w.Body.String())
|
||
}
|
||
}
|
||
setClaims(&middleware.Claims{AccountID: 1, Username: "admin", Roles: []string{"admin"}})
|
||
w = httptest.NewRecorder()
|
||
rg.ServeHTTP(w, httptest.NewRequest(http.MethodGet,
|
||
"/api/v1/stats/profit/users?date_from=2026/11/14", nil))
|
||
if w.Code == 200 {
|
||
t.Fatalf("坏日期应 4xx: %d %s", w.Code, w.Body.String())
|
||
}
|
||
}
|