package main import ( "encoding/json" "fmt" "net/http" "net/http/httptest" "path/filepath" "strconv" "testing" "github.com/gin-gonic/gin" "github.com/glebarez/sqlite" "gorm.io/gorm" businessbiz "kra/internal/biz/business" "kra/internal/biz/system" businessdata "kra/internal/data/business" systemdata "kra/internal/data/system" "kra/internal/server/handler" businessservice "kra/internal/service/business" ) type activationHTTPDatabases struct{ oa *gorm.DB } func (p *activationHTTPDatabases) Database(name string) (*gorm.DB, error) { if name == "oa" && p.oa != nil { return p.oa, nil } return nil, fmt.Errorf("数据源未配置") } func TestActivationHTTPNamedDatabaseAndSpend(t *testing.T) { open := func(name string) *gorm.DB { db, err := gorm.Open(sqlite.Open(filepath.Join(t.TempDir(), name)), &gorm.Config{}) if err != nil { t.Fatal(err) } pool, _ := db.DB() t.Cleanup(func() { _ = pool.Close() }) return db } db, oa := open("main.db"), open("oa.db") for _, step := range append(systemdata.Migrations(), businessdata.Migrations()...) { if err := step.Migrate(db); err != nil { t.Fatal(err) } } for _, sql := range []string{ "INSERT INTO sys_users(id,uuid,username,level,parent_id,id_path,enable) VALUES(1,'root','admin',0,0,'0',1),(7,'parent','parent',2,0,'0',1),(8,'leaf','leaf',3,7,'0,7',1)", "INSERT INTO sys_user_bind_platform(user_id,source_db,platform_busier_id,platform_busier_account,status) VALUES(8,'lx',14,'Own','0')", "CREATE TABLE tab_promote(id INTEGER,source_db TEXT,parent_id INTEGER,top_promote_id INTEGER)", "INSERT INTO tab_promote VALUES(100,'lx',0,0),(101,'lx',100,0),(100,'hw',0,0)", "CREATE TABLE tab_spend(source_db TEXT,promote_id INTEGER,pay_status INTEGER,pay_time INTEGER,game_id INTEGER,game_name TEXT,pay_amount DECIMAL(20,2))", "INSERT INTO tab_spend VALUES('lx',100,1,1000,1,'游戏甲',10.10),('lx',101,1,2000,2,'游戏乙',20.20),('lx',100,1,2001,1,'游戏甲',999),('hw',100,1,1000,1,'其他平台',999)", } { if err := db.Exec(sql).Error; err != nil { t.Fatal(err) } } for _, sql := range []string{ "CREATE TABLE sys_promote_active_pool_bind(id INTEGER PRIMARY KEY,promote_id INTEGER,platform_name TEXT,promote_account TEXT,busier_account TEXT,applicant_oa TEXT,bind_at DATETIME,reach_at DATETIME,unbind_at DATETIME,accum_amount TEXT,status TEXT,deleted_at DATETIME)", "INSERT INTO sys_promote_active_pool_bind VALUES(9007199254740993,100,'lx','主渠道','OWN','test-oa','1970-01-01 00:16:40','1970-01-01 00:33:20','1970-01-01 01:00:00','30.30','reached',NULL),(2,100,'lx','待审渠道','Own','test-oa',NULL,NULL,NULL,'0','pending',NULL),(3,100,'hw','其他商务渠道','other','test-oa',NULL,NULL,NULL,'0','pending',NULL)", } { if err := oa.Exec(sql).Error; err != nil { t.Fatal(err) } } provider := businessHTTPData{db} databases := &activationHTTPDatabases{oa: oa} uc := businessbiz.NewActivationUsecase(businessdata.NewActivationRepo(provider, databases), businessbiz.NewAccountUsecase(businessdata.NewAccountRepo(provider))) h := handler.NewActivation(businessservice.NewActivationService(uc)) engine := gin.New() engine.Use(func(c *gin.Context) { id, _ := strconv.ParseUint(c.GetHeader("X-Test-User"), 10, 64) aid := uint(903) if id == 1 { aid = 888 } c.Request = c.Request.WithContext(system.NewActorContext(c.Request.Context(), system.Actor{UserID: uint(id), AuthorityID: aid})) c.Next() }) engine.GET("/sw/promoteActivePool/bindList", h.List) engine.GET("/sw/promoteActivePool/bindSpendDetail", h.SpendDetail) server := httptest.NewServer(engine) defer server.Close() call := func(user int, path string, expected int) map[string]any { t.Helper() req, _ := http.NewRequest("GET", server.URL+path, nil) req.Header.Set("X-Test-User", strconv.Itoa(user)) res, err := server.Client().Do(req) if err != nil { t.Fatal(err) } defer res.Body.Close() var body map[string]any if err = json.NewDecoder(res.Body).Decode(&body); err != nil { t.Fatal(err) } if body["code"] != float64(expected) { t.Fatalf("接口错误 %s: %+v", path, body) } return body["data"].(map[string]any) } const list = "/sw/promoteActivePool/bindList" for _, tc := range []struct { user, total int query string }{{1, 3, ""}, {8, 2, ""}, {7, 0, ""}, {8, 1, "?platformNames=lx,hw&statuses=%E5%B7%B2%E8%BE%BE%E6%A0%87"}, {8, 0, "?busierAccount=other"}, {1, 1, "?busierAccount=other"}} { data := call(tc.user, list+tc.query, 0) if data["total"] != float64(tc.total) { t.Fatalf("范围或筛选错误: %+v", data) } } const detail = "/sw/promoteActivePool/bindSpendDetail?id=9007199254740993" data := call(8, detail, 0) if data["totalAmount"] != "30.30" || len(data["list"].([]any)) != 2 || data["endAt"] != "1970-01-01 00:33:20" { t.Fatalf("流水金额、树范围或达标优先截止错误: %+v", data) } call(7, detail, 7) call(8, "/sw/promoteActivePool/bindSpendDetail?id=2", 7) call(8, "/sw/promoteActivePool/bindSpendDetail?id=3", 7) call(1, "/sw/promoteActivePool/bindSpendDetail?id=0", 7) if err := db.Exec("DROP TABLE tab_spend").Error; err != nil { t.Fatal(err) } call(8, detail, 7) databases.oa = nil data = call(1, list, 0) if data["available"] != false { t.Fatal("缺 OA 数据源应明确不可用") } data = call(7, list, 0) if data["available"] != true || data["total"] != float64(0) { t.Fatal("无本人绑定仍为确定空集") } call(1, detail, 7) }