test: 后端测试从 SQLite 全面切换到 MySQL,与生产环境对齐
测试库不再使用 SQLite 内存库,改为每个测试包独立的 MySQL 库, 表结构由 backend/migrations 的真实迁移建立。 基础设施 - 新增 internal/database/testdb.go:NewTestDB() 保持原签名(28 处调用零改动), 内部连接 MySQL 测试库,首次调用重建库并执行全部真实迁移,之后每次调用清空全表 - 库名 = 测试库基础名 + 包目录名,同包共享、跨包隔离,使 go test ./... 可并发执行 (共用一库时各包会互相 DROP/CREATE 导致 database exists) - 新增 NewDryRunDB():MySQL 方言 + DryRun,供断言 SQL 形态的 5 处测试使用 - 新增 AutoMigrateIfMissing():只对不存在的表 AutoMigrate, 避免改动迁移定义的索引与约束 - 新增 scripts/prepare-test-db.sh:建库与通配授权,可重复执行 - 33 处 sqlite.Open 全部替换,26 个测试文件改用 MySQL - 删除 46 处手写 SQLite 方言 DDL(AUTOINCREMENT / INTEGER PRIMARY KEY / TEXT), 表统一由真实迁移建立 - go.mod 移除 gorm.io/driver/sqlite 与 mattn/go-sqlite3 - 删除生产代码里 distribution/repository.go 的 sqlite 方言分支(strftime) 对齐环境后暴露并修复的真实问题 - DATE(col) 在 MySQL 返回 DATE 类型,使 Date string 字段变成 RFC3339 时间串, 大盘日期会带出时间部分;28 处改为 DATE_FORMAT(col, '%Y-%m-%d') - 系统自动创建分销结算批次时 created_by 写入 0,违反指向 admin_users 的外键, 生产会直接插入失败;改为写 NULL(新增 adminRef helper) - MySQL DATETIME 仅到秒,静默截断 Go 侧写入的时间, 导致租用时长计算与结算时点回读比对偏差; rental_orders 的 9 个业务时间列提到 DATETIME(6) - 测试数据补齐严格模式要求的 NOT NULL 列、修正超出列长的取值、补齐外键父记录 迁移 - 000065 的 ALTER TABLE rental_orders 一并完成业务时间列精度调整, feature 侧不再单开迁移文件 脚本与文档 - check.sh / check-backend-coverage.sh 去掉 -p 1 串行与 SQLite 相关注释 - 更新 docs/Repository层测试补充总结.md 的测试运行说明
This commit is contained in:
+2
-4
@@ -9,6 +9,7 @@ require (
|
|||||||
github.com/gin-gonic/gin v1.12.0
|
github.com/gin-gonic/gin v1.12.0
|
||||||
github.com/go-sql-driver/mysql v1.8.1
|
github.com/go-sql-driver/mysql v1.8.1
|
||||||
github.com/golang-jwt/jwt/v5 v5.3.0
|
github.com/golang-jwt/jwt/v5 v5.3.0
|
||||||
|
github.com/google/uuid v1.6.0
|
||||||
github.com/minio/minio-go/v7 v7.1.0
|
github.com/minio/minio-go/v7 v7.1.0
|
||||||
github.com/redis/go-redis/v9 v9.17.0
|
github.com/redis/go-redis/v9 v9.17.0
|
||||||
github.com/sony/gobreaker/v2 v2.4.0
|
github.com/sony/gobreaker/v2 v2.4.0
|
||||||
@@ -18,9 +19,9 @@ require (
|
|||||||
go.uber.org/zap v1.27.0
|
go.uber.org/zap v1.27.0
|
||||||
golang.org/x/crypto v0.52.0
|
golang.org/x/crypto v0.52.0
|
||||||
golang.org/x/image v0.32.0
|
golang.org/x/image v0.32.0
|
||||||
|
golang.org/x/sync v0.20.0
|
||||||
gorm.io/datatypes v1.2.7
|
gorm.io/datatypes v1.2.7
|
||||||
gorm.io/driver/mysql v1.6.0
|
gorm.io/driver/mysql v1.6.0
|
||||||
gorm.io/driver/sqlite v1.6.0
|
|
||||||
gorm.io/gorm v1.31.1
|
gorm.io/gorm v1.31.1
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -57,7 +58,6 @@ require (
|
|||||||
github.com/go-playground/validator/v10 v10.30.3 // indirect
|
github.com/go-playground/validator/v10 v10.30.3 // indirect
|
||||||
github.com/goccy/go-json v0.10.6 // indirect
|
github.com/goccy/go-json v0.10.6 // indirect
|
||||||
github.com/goccy/go-yaml v1.19.2 // indirect
|
github.com/goccy/go-yaml v1.19.2 // indirect
|
||||||
github.com/google/uuid v1.6.0 // indirect
|
|
||||||
github.com/gorilla/websocket v1.5.3 // indirect
|
github.com/gorilla/websocket v1.5.3 // indirect
|
||||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||||
github.com/jinzhu/now v1.1.5 // indirect
|
github.com/jinzhu/now v1.1.5 // indirect
|
||||||
@@ -67,7 +67,6 @@ require (
|
|||||||
github.com/klauspost/crc32 v1.3.0 // indirect
|
github.com/klauspost/crc32 v1.3.0 // indirect
|
||||||
github.com/leodido/go-urn v1.4.0 // indirect
|
github.com/leodido/go-urn v1.4.0 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.22 // indirect
|
github.com/mattn/go-isatty v0.0.22 // indirect
|
||||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
|
||||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||||
github.com/minio/md5-simd v1.1.2 // indirect
|
github.com/minio/md5-simd v1.1.2 // indirect
|
||||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||||
@@ -88,7 +87,6 @@ require (
|
|||||||
golang.org/x/arch v0.27.0 // indirect
|
golang.org/x/arch v0.27.0 // indirect
|
||||||
golang.org/x/mod v0.36.0 // indirect
|
golang.org/x/mod v0.36.0 // indirect
|
||||||
golang.org/x/net v0.55.0 // indirect
|
golang.org/x/net v0.55.0 // indirect
|
||||||
golang.org/x/sync v0.20.0 // indirect
|
|
||||||
golang.org/x/sys v0.45.0 // indirect
|
golang.org/x/sys v0.45.0 // indirect
|
||||||
golang.org/x/text v0.37.0 // indirect
|
golang.org/x/text v0.37.0 // indirect
|
||||||
golang.org/x/tools v0.45.0 // indirect
|
golang.org/x/tools v0.45.0 // indirect
|
||||||
|
|||||||
@@ -6,24 +6,19 @@ import (
|
|||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"go.uber.org/zap/zaptest/observer"
|
"go.uber.org/zap/zaptest/observer"
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGormLoggerDoesNotLogQueryParameters(t *testing.T) {
|
func TestGormLoggerDoesNotLogQueryParameters(t *testing.T) {
|
||||||
core, observed := observer.New(zap.DebugLevel)
|
core, observed := observer.New(zap.DebugLevel)
|
||||||
logger := zap.New(core)
|
logger := zap.New(core)
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
// 复用 MySQL 测试库,只替换 logger 以观察日志脱敏行为。
|
||||||
Logger: newGormLogger("debug", logger),
|
db := NewTestDB().Session(&gorm.Session{Logger: newGormLogger("debug", logger)})
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
type secretRecord struct {
|
type secretRecord struct {
|
||||||
ID uint64
|
ID uint64
|
||||||
Phone string
|
Phone string
|
||||||
}
|
}
|
||||||
if err := db.AutoMigrate(&secretRecord{}); err != nil {
|
if err := AutoMigrateIfMissing(db, &secretRecord{}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
const secretPhone = "13812345678"
|
const secretPhone = "13812345678"
|
||||||
|
|||||||
@@ -1,42 +1,15 @@
|
|||||||
package database
|
package database
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
|
||||||
"log"
|
|
||||||
|
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// NewTestDB 创建用于测试的内存数据库
|
|
||||||
func NewTestDB() *gorm.DB {
|
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("无法创建测试数据库: %v", err)
|
|
||||||
}
|
|
||||||
return db
|
|
||||||
}
|
|
||||||
|
|
||||||
// NewTestDBWithName 创建用于测试的命名内存数据库(支持多连接共享)
|
|
||||||
func NewTestDBWithName(name string) *gorm.DB {
|
|
||||||
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", name)
|
|
||||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
|
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("无法创建测试数据库 %s: %v", name, err)
|
|
||||||
}
|
|
||||||
return db
|
|
||||||
}
|
|
||||||
|
|
||||||
// MigrateListingLifecycleTestSchema 创建商品生命周期测试所需的共享表结构。
|
// MigrateListingLifecycleTestSchema 创建商品生命周期测试所需的共享表结构。
|
||||||
|
// 真实表结构已由 migrations 建好,这里的 AutoMigrate 只做幂等补齐。
|
||||||
func MigrateListingLifecycleTestSchema(db *gorm.DB) error {
|
func MigrateListingLifecycleTestSchema(db *gorm.DB) error {
|
||||||
return db.AutoMigrate(
|
return AutoMigrateIfMissing(db,
|
||||||
&model.User{},
|
&model.User{},
|
||||||
&model.AdminUser{},
|
&model.AdminUser{},
|
||||||
&model.GameAccount{},
|
&model.GameAccount{},
|
||||||
@@ -53,7 +26,7 @@ func MigrateRentalTransactionTestSchema(db *gorm.DB) error {
|
|||||||
if err := MigrateListingLifecycleTestSchema(db); err != nil {
|
if err := MigrateListingLifecycleTestSchema(db); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return db.AutoMigrate(
|
return AutoMigrateIfMissing(db,
|
||||||
&model.RentalOrder{},
|
&model.RentalOrder{},
|
||||||
&model.SystemConfig{},
|
&model.SystemConfig{},
|
||||||
&model.PaymentOrder{},
|
&model.PaymentOrder{},
|
||||||
@@ -78,5 +51,5 @@ func MigrateRentalDisputeTestSchema(db *gorm.DB) error {
|
|||||||
if err := MigrateRentalTransactionTestSchema(db); err != nil {
|
if err := MigrateRentalTransactionTestSchema(db); err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
return db.AutoMigrate(&model.Dispute{})
|
return AutoMigrateIfMissing(db, &model.Dispute{})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,251 @@
|
|||||||
|
package database
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"database/sql"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"regexp"
|
||||||
|
"runtime"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
|
mysqldriver "github.com/go-sql-driver/mysql"
|
||||||
|
"gorm.io/driver/mysql"
|
||||||
|
"gorm.io/gorm"
|
||||||
|
"gorm.io/gorm/logger"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DefaultTestDSN 指向本地 Docker 开发环境的 MySQL 测试库。
|
||||||
|
// 可通过 HFB_TEST_DSN 覆盖,库名必须包含 test 或 e2e。
|
||||||
|
const DefaultTestDSN = "hfb:secret@tcp(127.0.0.1:13306)/hfb_sys_test?charset=utf8mb4&parseTime=True&loc=Local"
|
||||||
|
|
||||||
|
var (
|
||||||
|
testPrepareOnce sync.Once
|
||||||
|
testConn *gorm.DB
|
||||||
|
testPrepareErr error
|
||||||
|
)
|
||||||
|
|
||||||
|
// NewTestDB 返回指向 MySQL 测试库的干净连接。
|
||||||
|
//
|
||||||
|
// 首次调用会重建测试库并执行 backend/migrations 下的真实迁移,
|
||||||
|
// 因此测试用的表结构与生产完全一致;之后每次调用清空全部表,
|
||||||
|
// 使每个测试都从空库开始。
|
||||||
|
func NewTestDB() *gorm.DB {
|
||||||
|
db, err := sharedTestDB()
|
||||||
|
if err != nil {
|
||||||
|
panic(fmt.Sprintf("初始化 MySQL 测试库失败: %v", err))
|
||||||
|
}
|
||||||
|
if err := truncateAllTables(db); err != nil {
|
||||||
|
panic(fmt.Sprintf("清空 MySQL 测试库失败: %v", err))
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
func sharedTestDB() (*gorm.DB, error) {
|
||||||
|
testPrepareOnce.Do(func() {
|
||||||
|
testConn, testPrepareErr = openTestDatabase()
|
||||||
|
})
|
||||||
|
return testConn, testPrepareErr
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewDryRunDB 返回 MySQL 方言的 DryRun 连接:只生成 SQL 不执行,也无需数据库运行。
|
||||||
|
// 用于断言查询语句形态的测试。
|
||||||
|
func NewDryRunDB() *gorm.DB {
|
||||||
|
db, err := gorm.Open(mysql.New(mysql.Config{
|
||||||
|
DSN: DefaultTestDSN,
|
||||||
|
SkipInitializeWithVersion: true,
|
||||||
|
}), &gorm.Config{
|
||||||
|
DryRun: true,
|
||||||
|
DisableAutomaticPing: true,
|
||||||
|
Logger: logger.Default.LogMode(logger.Silent),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
panic(fmt.Sprintf("初始化 MySQL DryRun 连接失败: %v", err))
|
||||||
|
}
|
||||||
|
return db
|
||||||
|
}
|
||||||
|
|
||||||
|
// AutoMigrateIfMissing 只对尚不存在的表执行 AutoMigrate。
|
||||||
|
//
|
||||||
|
// 测试库的表结构由 migrations 建立,直接 AutoMigrate 会去改迁移定义的
|
||||||
|
// 索引与约束(例如 DROP 掉被外键依赖的唯一索引),因此已存在的表一律跳过,
|
||||||
|
// 仅保留给测试专用的临时表使用。
|
||||||
|
func AutoMigrateIfMissing(db *gorm.DB, models ...any) error {
|
||||||
|
for _, target := range models {
|
||||||
|
if db.Migrator().HasTable(target) {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if err := db.AutoMigrate(target); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func openTestDatabase() (*gorm.DB, error) {
|
||||||
|
dsn := strings.TrimSpace(os.Getenv("HFB_TEST_DSN"))
|
||||||
|
if dsn == "" {
|
||||||
|
dsn = DefaultTestDSN
|
||||||
|
}
|
||||||
|
cfg, err := mysqldriver.ParseDSN(dsn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("解析测试库 DSN 失败: %w", err)
|
||||||
|
}
|
||||||
|
// 每个测试包使用独立库,避免 go test ./... 并发时互相重建同一个库。
|
||||||
|
cfg.DBName = cfg.DBName + "_" + packageSuffix()
|
||||||
|
if err := assertTestDatabaseName(cfg.DBName); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
// 重建空库,保证表结构只来自 migrations。
|
||||||
|
serverCfg := cfg.Clone()
|
||||||
|
serverCfg.DBName = ""
|
||||||
|
serverCfg.MultiStatements = false
|
||||||
|
serverDB, err := sql.Open("mysql", serverCfg.FormatDSN())
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("连接 MySQL 服务失败: %w", err)
|
||||||
|
}
|
||||||
|
defer func() { _ = serverDB.Close() }()
|
||||||
|
if _, err := serverDB.Exec("DROP DATABASE IF EXISTS `" + cfg.DBName + "`"); err != nil {
|
||||||
|
return nil, fmt.Errorf("删除测试库失败: %w", err)
|
||||||
|
}
|
||||||
|
if _, err := serverDB.Exec("CREATE DATABASE `" + cfg.DBName + "` CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci"); err != nil {
|
||||||
|
return nil, fmt.Errorf("创建测试库失败: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.ParseTime = true
|
||||||
|
cfg.MultiStatements = true
|
||||||
|
sqlDB, err := sql.Open("mysql", cfg.FormatDSN())
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("连接测试库失败: %w", err)
|
||||||
|
}
|
||||||
|
if err := applyMigrations(sqlDB); err != nil {
|
||||||
|
_ = sqlDB.Close()
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
gormDB, err := gorm.Open(mysql.New(mysql.Config{Conn: sqlDB}), &gorm.Config{
|
||||||
|
Logger: logger.Default.LogMode(logger.Silent),
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
_ = sqlDB.Close()
|
||||||
|
return nil, fmt.Errorf("打开 gorm 连接失败: %w", err)
|
||||||
|
}
|
||||||
|
return gormDB, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// assertTestDatabaseName 拒绝重置非测试库,避免误删生产数据。
|
||||||
|
func assertTestDatabaseName(name string) error {
|
||||||
|
if name == "" {
|
||||||
|
return errors.New("测试库 DSN 必须包含数据库名")
|
||||||
|
}
|
||||||
|
if !regexp.MustCompile(`^[A-Za-z0-9_]+$`).MatchString(name) {
|
||||||
|
return fmt.Errorf("测试库名只允许字母、数字、下划线: %q", name)
|
||||||
|
}
|
||||||
|
if len(name) > 64 {
|
||||||
|
return fmt.Errorf("测试库名超过 MySQL 上限 64 字符: %q", name)
|
||||||
|
}
|
||||||
|
lower := strings.ToLower(name)
|
||||||
|
if !strings.Contains(lower, "test") && !strings.Contains(lower, "e2e") {
|
||||||
|
return fmt.Errorf("拒绝重置非测试库 %q,库名需包含 test 或 e2e", name)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// packageSuffix 用当前测试进程的工作目录名(即被测包目录)作为库名后缀。
|
||||||
|
// go test 会把工作目录设为包的源目录,因此同包共享一个库、不同包互相隔离。
|
||||||
|
func packageSuffix() string {
|
||||||
|
wd, err := os.Getwd()
|
||||||
|
if err != nil {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
suffix := regexp.MustCompile(`[^A-Za-z0-9_]`).ReplaceAllString(filepath.Base(wd), "_")
|
||||||
|
if suffix == "" {
|
||||||
|
return "unknown"
|
||||||
|
}
|
||||||
|
return suffix
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrationDir() (string, error) {
|
||||||
|
_, currentFile, _, ok := runtime.Caller(0)
|
||||||
|
if !ok {
|
||||||
|
return "", errors.New("无法定位 database 包路径")
|
||||||
|
}
|
||||||
|
return filepath.Join(filepath.Dir(currentFile), "..", "..", "migrations"), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func applyMigrations(db *sql.DB) error {
|
||||||
|
dir, err := migrationDir()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
entries, err := os.ReadDir(dir)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("读取迁移目录失败: %w", err)
|
||||||
|
}
|
||||||
|
for _, entry := range entries {
|
||||||
|
if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".sql") {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
raw, err := os.ReadFile(filepath.Join(dir, entry.Name()))
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("读取迁移 %s 失败: %w", entry.Name(), err)
|
||||||
|
}
|
||||||
|
if _, err := db.Exec(gooseUpSQL(string(raw))); err != nil {
|
||||||
|
return fmt.Errorf("执行迁移 %s 失败: %w", entry.Name(), err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// gooseUpSQL 截取 goose 迁移文件的 Up 段,Down 段与 goose 指令行原样保留,
|
||||||
|
// 后者在 MySQL 中属于注释,不影响执行。
|
||||||
|
func gooseUpSQL(raw string) string {
|
||||||
|
if i := strings.Index(raw, "-- +goose Up"); i >= 0 {
|
||||||
|
raw = raw[i+len("-- +goose Up"):]
|
||||||
|
}
|
||||||
|
if i := strings.Index(raw, "-- +goose Down"); i >= 0 {
|
||||||
|
raw = raw[:i]
|
||||||
|
}
|
||||||
|
return raw
|
||||||
|
}
|
||||||
|
|
||||||
|
// truncateAllTables 清空测试库中的全部基础表,使每个测试从空库开始。
|
||||||
|
func truncateAllTables(db *gorm.DB) error {
|
||||||
|
var tables []string
|
||||||
|
if err := db.Raw(
|
||||||
|
"SELECT table_name FROM information_schema.tables " +
|
||||||
|
"WHERE table_schema = DATABASE() AND table_type = 'BASE TABLE'",
|
||||||
|
).Scan(&tables).Error; err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if len(tables) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
sqlDB, err := db.DB()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
ctx := context.Background()
|
||||||
|
// 固定单连接,保证 FOREIGN_KEY_CHECKS 的会话变量对后续 TRUNCATE 生效。
|
||||||
|
conn, err := sqlDB.Conn(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _ = conn.Close() }()
|
||||||
|
|
||||||
|
if _, err := conn.ExecContext(ctx, "SET FOREIGN_KEY_CHECKS = 0"); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() { _, _ = conn.ExecContext(ctx, "SET FOREIGN_KEY_CHECKS = 1") }()
|
||||||
|
|
||||||
|
for _, table := range tables {
|
||||||
|
if _, err := conn.ExecContext(ctx, "TRUNCATE TABLE `"+table+"`"); err != nil {
|
||||||
|
return fmt.Errorf("清空表 %s 失败: %w", table, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -3,7 +3,6 @@ package e2e
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -19,7 +18,7 @@ import (
|
|||||||
|
|
||||||
func openDistributionE2EDB(t *testing.T) *gorm.DB {
|
func openDistributionE2EDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db := database.NewTestDBWithName(fmt.Sprintf("dist_e2e_%d", time.Now().UnixNano()))
|
db := database.NewTestDB()
|
||||||
sqlDB, err := db.DB()
|
sqlDB, err := db.DB()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
@@ -29,7 +28,7 @@ func openDistributionE2EDB(t *testing.T) *gorm.DB {
|
|||||||
if err := database.MigrateRentalTransactionTestSchema(db); err != nil {
|
if err := database.MigrateRentalTransactionTestSchema(db); err != nil {
|
||||||
t.Fatalf("migrate rental transaction schema failed: %v", err)
|
t.Fatalf("migrate rental transaction schema failed: %v", err)
|
||||||
}
|
}
|
||||||
if err := db.AutoMigrate(
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
&model.Role{}, &model.Permission{}, &model.AdminUserRole{}, &model.RolePermission{},
|
&model.Role{}, &model.Permission{}, &model.AdminUserRole{}, &model.RolePermission{},
|
||||||
&model.PaymentMerchantConfig{},
|
&model.PaymentMerchantConfig{},
|
||||||
&model.DistributionSiteMember{}, &model.DistributionRuleVersion{}, &model.DistributionOrderFinancial{},
|
&model.DistributionSiteMember{}, &model.DistributionRuleVersion{}, &model.DistributionOrderFinancial{},
|
||||||
@@ -48,10 +47,11 @@ func openDistributionE2EDB(t *testing.T) *gorm.DB {
|
|||||||
// 2. 分站 A 同步商品,设置自主提价(调减 20 比例,售价自动升为 125 元,分站加价 25 元);
|
// 2. 分站 A 同步商品,设置自主提价(调减 20 比例,售价自动升为 125 元,分站加价 25 元);
|
||||||
// 3. 租客在分站前台浏览并下单,实付售价 125 元;
|
// 3. 租客在分站前台浏览并下单,实付售价 125 元;
|
||||||
// 4. 支付成功自动触发快照:
|
// 4. 支付成功自动触发快照:
|
||||||
// - 号主成本 80 元保底;
|
// - 号主成本 80 元保底;
|
||||||
// - 分站自主加价 25 元 100% 归卖出分站;
|
// - 分站自主加价 25 元 100% 归卖出分站;
|
||||||
// - 主站提价净利润(20 元 - 通道费 0.63 元 = 19.37 元)按 35% / 40% / 25% 严丝合缝切分;
|
// - 主站提价净利润(20 元 - 通道费 0.63 元 = 19.37 元)按 35% / 40% / 25% 严丝合缝切分;
|
||||||
// - 卖出分站总获得 32.75 元;
|
// - 卖出分站总获得 32.75 元;
|
||||||
|
//
|
||||||
// 5. 完单后创建结算批次并执行结算,分站金库钱包精确入账 32.75 元,财务状态置为 settled。
|
// 5. 完单后创建结算批次并执行结算,分站金库钱包精确入账 32.75 元,财务状态置为 settled。
|
||||||
func TestE2EScenario1_MainSiteReceive_SubSiteMarkupSell_Settlement(t *testing.T) {
|
func TestE2EScenario1_MainSiteReceive_SubSiteMarkupSell_Settlement(t *testing.T) {
|
||||||
db := openDistributionE2EDB(t)
|
db := openDistributionE2EDB(t)
|
||||||
|
|||||||
@@ -5,19 +5,17 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestCleanupOnlyDeletesExpiredUnreferencedUploads(t *testing.T) {
|
func TestCleanupOnlyDeletesExpiredUnreferencedUploads(t *testing.T) {
|
||||||
db := openTestDB(t)
|
db := openTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.FileUploadOwner{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.FileUploadOwner{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
createReferenceTables(t, db)
|
|
||||||
now := time.Date(2026, 8, 16, 0, 0, 0, 0, time.UTC)
|
now := time.Date(2026, 8, 16, 0, 0, 0, 0, time.UTC)
|
||||||
old := now.Add(-31 * 24 * time.Hour)
|
old := now.Add(-31 * 24 * time.Hour)
|
||||||
recent := now.Add(-29 * 24 * time.Hour)
|
recent := now.Add(-29 * 24 * time.Hour)
|
||||||
@@ -29,7 +27,8 @@ func TestCleanupOnlyDeletesExpiredUnreferencedUploads(t *testing.T) {
|
|||||||
if err := db.Create(&records).Error; err != nil {
|
if err := db.Create(&records).Error; err != nil {
|
||||||
t.Fatalf("create upload owners error = %v", err)
|
t.Fatalf("create upload owners error = %v", err)
|
||||||
}
|
}
|
||||||
if err := db.Exec("INSERT INTO game_accounts (id, screenshot_urls) VALUES (1, ?)", `["/api/files/object?key=listing%2Freferenced.jpg"]`).Error; err != nil {
|
if err := db.Exec("INSERT INTO game_accounts (id, owner_id, server_region, login_platform, title, screenshot_urls) "+
|
||||||
|
"VALUES (1, 1, '国服', 'steam', '测试账号', ?)", `["/api/files/object?key=listing%2Freferenced.jpg"]`).Error; err != nil {
|
||||||
t.Fatalf("create referenced account error = %v", err)
|
t.Fatalf("create referenced account error = %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,26 +51,6 @@ func TestCleanupOnlyDeletesExpiredUnreferencedUploads(t *testing.T) {
|
|||||||
|
|
||||||
func openTestDB(t *testing.T) *gorm.DB {
|
func openTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open sqlite error = %v", err)
|
|
||||||
}
|
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
func createReferenceTables(t *testing.T, db *gorm.DB) {
|
|
||||||
t.Helper()
|
|
||||||
statements := []string{
|
|
||||||
"CREATE TABLE game_accounts (id INTEGER PRIMARY KEY, screenshot_urls TEXT)",
|
|
||||||
"CREATE TABLE order_checkouts (id INTEGER PRIMARY KEY, evidence_urls TEXT)",
|
|
||||||
"CREATE TABLE disputes (id INTEGER PRIMARY KEY, evidence_urls TEXT)",
|
|
||||||
"CREATE TABLE handoff_records (id INTEGER PRIMARY KEY, attachment_urls TEXT)",
|
|
||||||
"CREATE TABLE chat_messages (id INTEGER PRIMARY KEY, attachment_urls TEXT)",
|
|
||||||
"CREATE TABLE user_payment_accounts (id INTEGER PRIMARY KEY, certificate_urls TEXT)",
|
|
||||||
}
|
|
||||||
for _, statement := range statements {
|
|
||||||
if err := db.Exec(statement).Error; err != nil {
|
|
||||||
t.Fatalf("create reference table error = %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -4,24 +4,18 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/chat"
|
"hfb_sys/backend/internal/modules/chat"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func setupOrderTimeoutTestDB(t *testing.T) *gorm.DB {
|
func setupOrderTimeoutTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
db := database.NewTestDB()
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("无法创建测试数据库: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(
|
|
||||||
&model.RentalOrder{},
|
&model.RentalOrder{},
|
||||||
&model.HandoffRecord{},
|
&model.HandoffRecord{},
|
||||||
&model.Notification{},
|
&model.Notification{},
|
||||||
|
|||||||
@@ -4,24 +4,18 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/payment"
|
"hfb_sys/backend/internal/modules/payment"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func setupRefundRetryTestDB(t *testing.T) *gorm.DB {
|
func setupRefundRetryTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
db := database.NewTestDB()
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
if err := database.AutoMigrateIfMissing(db, &model.PaymentOrder{}, &model.RentalOrder{}, &model.ChatConversation{}); err != nil {
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("创建测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&model.PaymentOrder{}, &model.RentalOrder{}, &model.ChatConversation{}); err != nil {
|
|
||||||
t.Fatalf("数据库迁移失败: %v", err)
|
t.Fatalf("数据库迁移失败: %v", err)
|
||||||
}
|
}
|
||||||
return db
|
return db
|
||||||
|
|||||||
@@ -4,22 +4,16 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func setupTestDB(t *testing.T) *gorm.DB {
|
func setupTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open("file::memory:?cache=shared"), &gorm.Config{
|
db := database.NewTestDB()
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
if err := database.AutoMigrateIfMissing(db, &model.ListingStatusEvent{}); err != nil {
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open sqlite: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&model.ListingStatusEvent{}); err != nil {
|
|
||||||
t.Fatalf("migrate: %v", err)
|
t.Fatalf("migrate: %v", err)
|
||||||
}
|
}
|
||||||
return db
|
return db
|
||||||
|
|||||||
@@ -8,8 +8,8 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type ChatConversation struct {
|
type ChatConversation struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
OrderID *uint64 `gorm:"uniqueIndex" json:"order_id"`
|
OrderID *uint64 `gorm:"uniqueIndex" json:"order_id"`
|
||||||
ListingID *uint64 `gorm:"index" json:"listing_id"`
|
ListingID *uint64 `gorm:"index" json:"listing_id"`
|
||||||
DistributionSiteID *uint64 `gorm:"index" json:"distribution_site_id,omitempty"`
|
DistributionSiteID *uint64 `gorm:"index" json:"distribution_site_id,omitempty"`
|
||||||
// 发布群没有固定订单时,以下字段保存该商品最新订单的轻量快照,供客服列表筛选使用。
|
// 发布群没有固定订单时,以下字段保存该商品最新订单的轻量快照,供客服列表筛选使用。
|
||||||
|
|||||||
@@ -29,17 +29,17 @@ func (GameAccount) TableName() string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type RentalListing struct {
|
type RentalListing struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
ListingNo string `gorm:"column:listing_no;size:20;not null;uniqueIndex" json:"listing_no"`
|
ListingNo string `gorm:"column:listing_no;size:20;not null;uniqueIndex" json:"listing_no"`
|
||||||
AccountID uint64 `gorm:"not null;index" json:"account_id"`
|
AccountID uint64 `gorm:"not null;index" json:"account_id"`
|
||||||
OwnerID uint64 `gorm:"not null;index" json:"owner_id"`
|
OwnerID uint64 `gorm:"not null;index" json:"owner_id"`
|
||||||
PriceCent int64 `gorm:"not null;default:0" json:"-"`
|
PriceCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
DepositAmountCent int64 `gorm:"not null;default:0" json:"-"`
|
DepositAmountCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
InTransaction bool `gorm:"not null;default:false" json:"in_transaction"`
|
InTransaction bool `gorm:"not null;default:false" json:"in_transaction"`
|
||||||
Status string `gorm:"size:32;not null;default:'draft'" json:"status"`
|
Status string `gorm:"size:32;not null;default:'draft'" json:"status"`
|
||||||
ReviewStatus string `gorm:"size:32;not null;default:'none'" json:"review_status"`
|
ReviewStatus string `gorm:"size:32;not null;default:'none'" json:"review_status"`
|
||||||
HandoffMode string `gorm:"size:16;not null;default:'owner';index" json:"handoff_mode"`
|
HandoffMode string `gorm:"size:16;not null;default:'owner';index" json:"handoff_mode"`
|
||||||
SettlementMode string `gorm:"size:32;not null;default:'owner_wallet'" json:"settlement_mode"`
|
SettlementMode string `gorm:"size:32;not null;default:'owner_wallet'" json:"settlement_mode"`
|
||||||
ManagedAdminID *uint64 `gorm:"index" json:"managed_admin_id"`
|
ManagedAdminID *uint64 `gorm:"index" json:"managed_admin_id"`
|
||||||
DistributionSiteID *uint64 `gorm:"column:distribution_site_id;index" json:"distribution_site_id,omitempty"`
|
DistributionSiteID *uint64 `gorm:"column:distribution_site_id;index" json:"distribution_site_id,omitempty"`
|
||||||
SourceChannel string `gorm:"size:64;not null;default:''" json:"-"`
|
SourceChannel string `gorm:"size:64;not null;default:''" json:"-"`
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ package model
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type Notification struct {
|
type Notification struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
UserID uint64 `gorm:"not null;index" json:"user_id"`
|
UserID uint64 `gorm:"not null;index" json:"user_id"`
|
||||||
Type string `gorm:"size:32;not null" json:"type"`
|
Type string `gorm:"size:32;not null" json:"type"`
|
||||||
Title string `gorm:"size:128;not null" json:"title"`
|
Title string `gorm:"size:128;not null" json:"title"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
BizType string `gorm:"size:32;not null;default:''" json:"biz_type"`
|
BizType string `gorm:"size:32;not null;default:''" json:"biz_type"`
|
||||||
BizID *uint64 `json:"biz_id"`
|
BizID *uint64 `json:"biz_id"`
|
||||||
DistributionSiteID *uint64 `gorm:"index" json:"distribution_site_id"`
|
DistributionSiteID *uint64 `gorm:"index" json:"distribution_site_id"`
|
||||||
|
|||||||
@@ -7,18 +7,18 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type UserPaymentAccount struct {
|
type UserPaymentAccount struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
UserID uint64 `gorm:"not null;index" json:"user_id"`
|
UserID uint64 `gorm:"not null;index" json:"user_id"`
|
||||||
AccountType string `gorm:"size:32;not null" json:"account_type"`
|
AccountType string `gorm:"size:32;not null" json:"account_type"`
|
||||||
AccountName string `gorm:"size:128;not null" json:"account_name"`
|
AccountName string `gorm:"size:128;not null" json:"account_name"`
|
||||||
AccountNo string `gorm:"size:255;not null" json:"account_no"`
|
AccountNo string `gorm:"size:255;not null" json:"account_no"`
|
||||||
BankName string `gorm:"size:128;not null;default:''" json:"bank_name"`
|
BankName string `gorm:"size:128;not null;default:''" json:"bank_name"`
|
||||||
BankBranch string `gorm:"size:255;not null;default:''" json:"bank_branch"`
|
BankBranch string `gorm:"size:255;not null;default:''" json:"bank_branch"`
|
||||||
CertificateURLs datatypes.JSON `json:"certificate_urls"`
|
CertificateURLs datatypes.JSON `json:"certificate_urls"`
|
||||||
IsDefault bool `gorm:"not null;default:0" json:"is_default"`
|
IsDefault bool `gorm:"not null;default:0" json:"is_default"`
|
||||||
Status string `gorm:"size:32;not null;default:'active'" json:"status"`
|
Status string `gorm:"size:32;not null;default:'active'" json:"status"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (UserPaymentAccount) TableName() string {
|
func (UserPaymentAccount) TableName() string {
|
||||||
|
|||||||
@@ -3,12 +3,12 @@ package model
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type Role struct {
|
type Role struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
Code string `gorm:"size:64;not null;uniqueIndex" json:"code"`
|
Code string `gorm:"size:64;not null;uniqueIndex" json:"code"`
|
||||||
Name string `gorm:"size:64;not null" json:"name"`
|
Name string `gorm:"size:64;not null" json:"name"`
|
||||||
Description string `gorm:"size:255;not null;default:''" json:"description"`
|
Description string `gorm:"size:255;not null;default:''" json:"description"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (Role) TableName() string { return "roles" }
|
func (Role) TableName() string { return "roles" }
|
||||||
@@ -26,10 +26,10 @@ type Permission struct {
|
|||||||
func (Permission) TableName() string { return "permissions" }
|
func (Permission) TableName() string { return "permissions" }
|
||||||
|
|
||||||
type AdminUserRole struct {
|
type AdminUserRole struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
AdminID uint64 `gorm:"column:admin_user_id;not null;uniqueIndex:uk_admin_user_roles_user_role" json:"admin_id"`
|
AdminID uint64 `gorm:"column:admin_user_id;not null;uniqueIndex:uk_admin_user_roles_user_role" json:"admin_id"`
|
||||||
RoleID uint64 `gorm:"column:role_id;not null;uniqueIndex:uk_admin_user_roles_user_role" json:"role_id"`
|
RoleID uint64 `gorm:"column:role_id;not null;uniqueIndex:uk_admin_user_roles_user_role" json:"role_id"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (AdminUserRole) TableName() string { return "admin_user_roles" }
|
func (AdminUserRole) TableName() string { return "admin_user_roles" }
|
||||||
|
|||||||
@@ -3,29 +3,29 @@ package model
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type WithdrawalRequest struct {
|
type WithdrawalRequest struct {
|
||||||
ID uint64 `gorm:"primaryKey" json:"id"`
|
ID uint64 `gorm:"primaryKey" json:"id"`
|
||||||
WithdrawNo string `gorm:"size:64;not null;uniqueIndex" json:"withdraw_no"`
|
WithdrawNo string `gorm:"size:64;not null;uniqueIndex" json:"withdraw_no"`
|
||||||
UserID uint64 `gorm:"not null;index:idx_withdrawal_user_site" json:"user_id"`
|
UserID uint64 `gorm:"not null;index:idx_withdrawal_user_site" json:"user_id"`
|
||||||
DistributionSiteID uint64 `gorm:"not null;default:0;index:idx_withdrawal_user_site" json:"distribution_site_id"`
|
DistributionSiteID uint64 `gorm:"not null;default:0;index:idx_withdrawal_user_site" json:"distribution_site_id"`
|
||||||
AmountCent int64 `gorm:"not null;default:0" json:"-"`
|
AmountCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
FeeCent int64 `gorm:"not null;default:0" json:"-"`
|
FeeCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
ActualAmountCent int64 `gorm:"not null;default:0" json:"-"`
|
ActualAmountCent int64 `gorm:"not null;default:0" json:"-"`
|
||||||
PaymentAccountID *uint64 `json:"payment_account_id"`
|
PaymentAccountID *uint64 `json:"payment_account_id"`
|
||||||
AccountType string `gorm:"size:32;not null" json:"account_type"`
|
AccountType string `gorm:"size:32;not null" json:"account_type"`
|
||||||
AccountName string `gorm:"size:128;not null" json:"account_name"`
|
AccountName string `gorm:"size:128;not null" json:"account_name"`
|
||||||
AccountNo string `gorm:"size:128;not null" json:"account_no"`
|
AccountNo string `gorm:"size:128;not null" json:"account_no"`
|
||||||
BankName string `gorm:"size:128;not null;default:''" json:"bank_name"`
|
BankName string `gorm:"size:128;not null;default:''" json:"bank_name"`
|
||||||
BankBranch string `gorm:"size:255;not null;default:''" json:"bank_branch"`
|
BankBranch string `gorm:"size:255;not null;default:''" json:"bank_branch"`
|
||||||
Status string `gorm:"size:32;not null;default:'pending'" json:"status"`
|
Status string `gorm:"size:32;not null;default:'pending'" json:"status"`
|
||||||
ReviewedBy *uint64 `json:"reviewed_by"`
|
ReviewedBy *uint64 `json:"reviewed_by"`
|
||||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||||
ReviewRemark string `gorm:"size:255;not null;default:''" json:"review_remark"`
|
ReviewRemark string `gorm:"size:255;not null;default:''" json:"review_remark"`
|
||||||
PaidBy *uint64 `json:"paid_by"`
|
PaidBy *uint64 `json:"paid_by"`
|
||||||
PaidAt *time.Time `json:"paid_at"`
|
PaidAt *time.Time `json:"paid_at"`
|
||||||
PaymentProofURL string `gorm:"size:512;not null;default:''" json:"payment_proof_url"`
|
PaymentProofURL string `gorm:"size:512;not null;default:''" json:"payment_proof_url"`
|
||||||
PaymentRemark string `gorm:"size:255;not null;default:''" json:"payment_remark"`
|
PaymentRemark string `gorm:"size:255;not null;default:''" json:"payment_remark"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (WithdrawalRequest) TableName() string {
|
func (WithdrawalRequest) TableName() string {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import (
|
|||||||
|
|
||||||
func TestListingDailyOverviewGroupsBySourceChannel(t *testing.T) {
|
func TestListingDailyOverviewGroupsBySourceChannel(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.ListingStatusEvent{}, &model.ListingUpload{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.ListingStatusEvent{}, &model.ListingUpload{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
@@ -68,7 +68,7 @@ func assertChannelStats(t *testing.T, item ListingChannelDayStatsDTO, published,
|
|||||||
|
|
||||||
func TestListingDailyOverviewGroupsExternalUploadsByUploader(t *testing.T) {
|
func TestListingDailyOverviewGroupsExternalUploadsByUploader(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.ListingStatusEvent{}, &model.ListingUpload{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.ListingStatusEvent{}, &model.ListingUpload{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
|
|||||||
@@ -240,22 +240,22 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
|||||||
|
|
||||||
pickupProfits := make([]dailyPickupProfitRow, 0)
|
pickupProfits := make([]dailyPickupProfitRow, 0)
|
||||||
if err := db.Table("admin_pickups").
|
if err := db.Table("admin_pickups").
|
||||||
Select(`DATE(completed_at) AS date,
|
Select(`DATE_FORMAT(completed_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent,
|
COALESCE(SUM(profit_amount_cent), 0) AS profit_amount_cent,
|
||||||
COUNT(id) AS completed_count`).
|
COUNT(id) AS completed_count`).
|
||||||
Where("status = ?", "completed").
|
Where("status = ?", "completed").
|
||||||
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate).
|
Where("completed_at >= ? AND completed_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(completed_at)").
|
Group("DATE_FORMAT(completed_at, '%Y-%m-%d')").
|
||||||
Scan(&pickupProfits).Error; err != nil {
|
Scan(&pickupProfits).Error; err != nil {
|
||||||
return dashboardDailyResult{}, err
|
return dashboardDailyResult{}, err
|
||||||
}
|
}
|
||||||
pickupAdjustments := make([]dailyPickupAdjustmentRow, 0)
|
pickupAdjustments := make([]dailyPickupAdjustmentRow, 0)
|
||||||
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
if err := db.Table("admin_pickup_financial_adjustments AS fa").
|
||||||
Select(`DATE(fa.created_at) AS date,
|
Select(`DATE_FORMAT(fa.created_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`).
|
COALESCE(SUM(fa.profit_delta_cent), 0) AS profit_amount_cent`).
|
||||||
Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed").
|
Joins("JOIN admin_pickups AS p ON p.id = fa.pickup_id AND p.status = ?", "completed").
|
||||||
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate).
|
Where("fa.created_at >= ? AND fa.created_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(fa.created_at)").
|
Group("DATE_FORMAT(fa.created_at, '%Y-%m-%d')").
|
||||||
Scan(&pickupAdjustments).Error; err != nil {
|
Scan(&pickupAdjustments).Error; err != nil {
|
||||||
return dashboardDailyResult{}, err
|
return dashboardDailyResult{}, err
|
||||||
}
|
}
|
||||||
@@ -388,13 +388,13 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
|||||||
func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) ([]dailyEstimatedRow, error) {
|
func (r *Repository) dailyEstimates(ctx context.Context, query DashboardQuery) ([]dailyEstimatedRow, error) {
|
||||||
rows := make([]dailyEstimatedRow, 0)
|
rows := make([]dailyEstimatedRow, 0)
|
||||||
err := r.db.WithContext(ctx).Table("rental_orders").
|
err := r.db.WithContext(ctx).Table("rental_orders").
|
||||||
Select(`DATE(created_at) AS date,
|
Select(`DATE_FORMAT(created_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent,
|
COALESCE(SUM(platform_fee_cent), 0) AS estimated_income_amount_cent,
|
||||||
COUNT(id) AS pending_settle_order_count`).
|
COUNT(id) AS pending_settle_order_count`).
|
||||||
Where("settlement_status NOT IN ?", settledSettlementStatuses()).
|
Where("settlement_status NOT IN ?", settledSettlementStatuses()).
|
||||||
Where("status NOT IN ?", nonBillableOrderStatuses()).
|
Where("status NOT IN ?", nonBillableOrderStatuses()).
|
||||||
Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate).
|
Where("created_at >= ? AND created_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(created_at)").
|
Group("DATE_FORMAT(created_at, '%Y-%m-%d')").
|
||||||
Scan(&rows).Error
|
Scan(&rows).Error
|
||||||
return rows, err
|
return rows, err
|
||||||
}
|
}
|
||||||
@@ -403,7 +403,7 @@ func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery)
|
|||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
rows := make([]dailySettlementRow, 0)
|
rows := make([]dailySettlementRow, 0)
|
||||||
err := db.Table("rental_orders AS ro").
|
err := db.Table("rental_orders AS ro").
|
||||||
Select(`DATE(ro.settled_at) AS date,
|
Select(`DATE_FORMAT(ro.settled_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent,
|
COALESCE(SUM(oc.platform_fee_cent), 0) AS platform_income_amount_cent,
|
||||||
COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent,
|
COALESCE(SUM(oc.owner_income_amount_cent), 0) AS owner_should_income_amount_cent,
|
||||||
COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent,
|
COALESCE(SUM(COALESCE(w.owner_wallet_income_amount_cent, 0)), 0) AS owner_wallet_income_amount_cent,
|
||||||
@@ -445,7 +445,7 @@ func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery)
|
|||||||
Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'").
|
Joins("JOIN order_checkouts AS oc ON oc.order_id = ro.id AND oc.status = 'accepted'").
|
||||||
Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForSettledOrdersSubquery(db, query)).
|
Joins("LEFT JOIN (?) AS w ON w.order_id = ro.id", ownerWalletIncomeForSettledOrdersSubquery(db, query)).
|
||||||
Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate).
|
Where("ro.settled_at >= ? AND ro.settled_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(ro.settled_at)").
|
Group("DATE_FORMAT(ro.settled_at, '%Y-%m-%d')").
|
||||||
Scan(&rows).Error
|
Scan(&rows).Error
|
||||||
return rows, err
|
return rows, err
|
||||||
}
|
}
|
||||||
@@ -521,7 +521,7 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
|||||||
rows := make([]dailyPaymentRow, 0)
|
rows := make([]dailyPaymentRow, 0)
|
||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
err := db.Table("payment_orders AS po").
|
err := db.Table("payment_orders AS po").
|
||||||
Select(`DATE(po.created_at) AS date,
|
Select(`DATE_FORMAT(po.created_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS total_flow_amount_cent,
|
COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'paid' THEN po.amount_cent ELSE 0 END), 0) AS total_flow_amount_cent,
|
||||||
COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS total_refund_amount_cent,
|
COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunded' THEN po.amount_cent ELSE 0 END), 0) AS total_refund_amount_cent,
|
||||||
COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN po.amount_cent ELSE 0 END), 0) AS pending_refund_amount_cent,
|
COALESCE(SUM(CASE WHEN po.biz_type IN ? AND po.status = 'refunding' THEN po.amount_cent ELSE 0 END), 0) AS pending_refund_amount_cent,
|
||||||
@@ -536,7 +536,7 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
|||||||
payBizTypes(), refundBizTypes(), refundBizTypes(), payBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes(), normalRefundBizTypes()).
|
payBizTypes(), refundBizTypes(), refundBizTypes(), payBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes(), normalRefundBizTypes()).
|
||||||
Joins("LEFT JOIN (?) AS orig ON orig.order_id = po.order_id", paymentOriginalAmountForRefundsInRangeSubquery(db, query)).
|
Joins("LEFT JOIN (?) AS orig ON orig.order_id = po.order_id", paymentOriginalAmountForRefundsInRangeSubquery(db, query)).
|
||||||
Where("po.created_at >= ? AND po.created_at <= ?", query.StartDate, query.EndDate).
|
Where("po.created_at >= ? AND po.created_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(po.created_at)").
|
Group("DATE_FORMAT(po.created_at, '%Y-%m-%d')").
|
||||||
Scan(&rows).Error
|
Scan(&rows).Error
|
||||||
return rows, err
|
return rows, err
|
||||||
}
|
}
|
||||||
@@ -545,10 +545,10 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
|||||||
func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQuery) ([]dailyPickupCancelledRow, error) {
|
func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQuery) ([]dailyPickupCancelledRow, error) {
|
||||||
rows := make([]dailyPickupCancelledRow, 0)
|
rows := make([]dailyPickupCancelledRow, 0)
|
||||||
err := r.db.WithContext(ctx).Table("admin_pickups").
|
err := r.db.WithContext(ctx).Table("admin_pickups").
|
||||||
Select(`DATE(cancelled_at) AS date, COUNT(id) AS count`).
|
Select(`DATE_FORMAT(cancelled_at, '%Y-%m-%d') AS date, COUNT(id) AS count`).
|
||||||
Where("status = ?", "cancelled").
|
Where("status = ?", "cancelled").
|
||||||
Where("cancelled_at >= ? AND cancelled_at <= ?", query.StartDate, query.EndDate).
|
Where("cancelled_at >= ? AND cancelled_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(cancelled_at)").
|
Group("DATE_FORMAT(cancelled_at, '%Y-%m-%d')").
|
||||||
Scan(&rows).Error
|
Scan(&rows).Error
|
||||||
return rows, err
|
return rows, err
|
||||||
}
|
}
|
||||||
@@ -557,15 +557,15 @@ func (r *Repository) dailyPickupCancelled(ctx context.Context, query DashboardQu
|
|||||||
func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery) ([]dailyPaidOrderRow, error) {
|
func (r *Repository) dailyPaidOrders(ctx context.Context, query DashboardQuery) ([]dailyPaidOrderRow, error) {
|
||||||
items := make([]dailyPaidOrderRow, 0)
|
items := make([]dailyPaidOrderRow, 0)
|
||||||
err := r.db.WithContext(ctx).Table(`(
|
err := r.db.WithContext(ctx).Table(`(
|
||||||
SELECT DATE(paid_at) AS date, COUNT(DISTINCT order_id) AS paid_order_count
|
SELECT DATE_FORMAT(paid_at, '%Y-%m-%d') AS date, COUNT(DISTINCT order_id) AS paid_order_count
|
||||||
FROM payment_orders
|
FROM payment_orders
|
||||||
WHERE biz_type = 'order_pay' AND status = 'paid' AND paid_at >= ? AND paid_at <= ?
|
WHERE biz_type = 'order_pay' AND status = 'paid' AND paid_at >= ? AND paid_at <= ?
|
||||||
GROUP BY DATE(paid_at)
|
GROUP BY DATE_FORMAT(paid_at, '%Y-%m-%d')
|
||||||
UNION ALL
|
UNION ALL
|
||||||
SELECT DATE(completed_at) AS date, COUNT(id) AS paid_order_count
|
SELECT DATE_FORMAT(completed_at, '%Y-%m-%d') AS date, COUNT(id) AS paid_order_count
|
||||||
FROM admin_pickups
|
FROM admin_pickups
|
||||||
WHERE status = 'completed' AND completed_at >= ? AND completed_at <= ?
|
WHERE status = 'completed' AND completed_at >= ? AND completed_at <= ?
|
||||||
GROUP BY DATE(completed_at)
|
GROUP BY DATE_FORMAT(completed_at, '%Y-%m-%d')
|
||||||
) AS daily_paid_orders`, query.StartDate, query.EndDate, query.StartDate, query.EndDate).
|
) AS daily_paid_orders`, query.StartDate, query.EndDate, query.StartDate, query.EndDate).
|
||||||
Select("date, SUM(paid_order_count) AS paid_order_count").
|
Select("date, SUM(paid_order_count) AS paid_order_count").
|
||||||
Group("date").
|
Group("date").
|
||||||
|
|||||||
@@ -6,59 +6,39 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestDailyPaidOrdersUsePaidAtAndIncludeCreatedPickups(t *testing.T) {
|
func TestDailyPaidOrdersUsePaidAtAndIncludeCreatedPickups(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE payment_orders (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
order_id INTEGER NOT NULL,
|
|
||||||
biz_type TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
paid_at DATETIME NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建支付单表失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE admin_pickups (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
created_at DATETIME NOT NULL,
|
|
||||||
completed_at DATETIME NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建提号表失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
day := func(value int) time.Time { return time.Date(2026, 8, value, 10, 0, 0, 0, loc) }
|
day := func(value int) time.Time { return time.Date(2026, 8, value, 10, 0, 0, 0, loc) }
|
||||||
rows := [][]any{
|
rows := [][]any{
|
||||||
{1, 101, "order_pay", "paid", day(2)},
|
{1, "PAY-1", 101, "ORD-101", 11, "mockpay", "T-101", "order_pay", "paid", day(2)},
|
||||||
{2, 101, "order_pay", "paid", day(2)},
|
{2, "PAY-2", 101, "ORD-101", 11, "mockpay", "T-102", "order_pay", "paid", day(2)},
|
||||||
{3, 102, "order_pay", "paid", day(3)},
|
{3, "PAY-3", 102, "ORD-102", 12, "mockpay", "T-103", "order_pay", "paid", day(3)},
|
||||||
{4, 201, "mohong_pay", "paid", day(2)},
|
{4, "PAY-4", 201, "ORD-201", 21, "mockpay", "T-201", "mohong_pay", "paid", day(2)},
|
||||||
{5, 103, "order_pay", "created", nil},
|
{5, "PAY-5", 103, "ORD-103", 13, "mockpay", "T-104", "order_pay", "created", nil},
|
||||||
{6, 104, "order_pay", "paid", day(1)},
|
{6, "PAY-6", 104, "ORD-104", 14, "mockpay", "T-105", "order_pay", "paid", day(1)},
|
||||||
}
|
}
|
||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
if err := db.Exec(`INSERT INTO payment_orders (id, order_id, biz_type, status, paid_at)
|
if err := db.Exec(`INSERT INTO payment_orders
|
||||||
VALUES (?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
(id, payment_no, order_id, order_no, user_id, provider, third_order_id, biz_type, status, paid_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||||
t.Fatalf("写入支付单失败: %v", err)
|
t.Fatalf("写入支付单失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, row := range [][]any{
|
for _, row := range [][]any{
|
||||||
{1, "completed", day(2), day(2)},
|
{1, "PK-1", 1, 1, 1, 1, "completed", day(2), day(2)},
|
||||||
{2, "picking_up", day(2), nil},
|
{2, "PK-2", 2, 2, 2, 1, "picking_up", day(2), nil},
|
||||||
{3, "completed", day(3), day(3)},
|
{3, "PK-3", 3, 3, 3, 1, "completed", day(3), day(3)},
|
||||||
{4, "cancelled", day(1), nil},
|
{4, "PK-4", 4, 4, 4, 1, "cancelled", day(1), nil},
|
||||||
} {
|
} {
|
||||||
if err := db.Exec(`INSERT INTO admin_pickups (id, status, created_at, completed_at) VALUES (?, ?, ?, ?)`, row...).Error; err != nil {
|
if err := db.Exec(`INSERT INTO admin_pickups
|
||||||
|
(id, pickup_no, listing_id, account_id, owner_id, admin_id, status, created_at, completed_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||||
t.Fatalf("写入提号记录失败: %v", err)
|
t.Fatalf("写入提号记录失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -85,37 +65,25 @@ func TestDailyPaidOrdersUsePaidAtAndIncludeCreatedPickups(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestDailyPaymentsNormalFullRefundExcludesMohong(t *testing.T) {
|
func TestDailyPaymentsNormalFullRefundExcludesMohong(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE payment_orders (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
order_id INTEGER NOT NULL,
|
|
||||||
biz_type TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
amount_cent INTEGER NOT NULL,
|
|
||||||
created_at DATETIME NOT NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建支付单表失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
day := func(value int) time.Time { return time.Date(2026, 8, value, 10, 0, 0, 0, loc) }
|
day := func(value int) time.Time { return time.Date(2026, 8, value, 10, 0, 0, 0, loc) }
|
||||||
rows := [][]any{
|
rows := [][]any{
|
||||||
// 正常订单全额退款:计入 full_refund_count 与 normal_full_refund_count
|
// 正常订单全额退款:计入 full_refund_count 与 normal_full_refund_count
|
||||||
{1, 101, "rent_refund", "refunded", 5000, day(2)},
|
{1, "PAY-1", 101, "ORD-101", 11, "mockpay", "T-101", "rent_refund", "refunded", 5000, day(2)},
|
||||||
{2, 101, "order_pay", "paid", 5000, day(1)},
|
{2, "PAY-2", 101, "ORD-101", 11, "mockpay", "T-102", "order_pay", "paid", 5000, day(1)},
|
||||||
// 正常订单部分退款:不计入全额
|
// 正常订单部分退款:不计入全额
|
||||||
{3, 102, "rent_refund", "refunded", 2000, day(2)},
|
{3, "PAY-3", 102, "ORD-102", 12, "mockpay", "T-103", "rent_refund", "refunded", 2000, day(2)},
|
||||||
{4, 102, "order_pay", "paid", 5000, day(1)},
|
{4, "PAY-4", 102, "ORD-102", 12, "mockpay", "T-104", "order_pay", "paid", 5000, day(1)},
|
||||||
// 撞车商城全额退款:只计入 full_refund_count,不计入 normal_full_refund_count
|
// 撞车商城全额退款:只计入 full_refund_count,不计入 normal_full_refund_count
|
||||||
{5, 201, "mohong_refund", "refunded", 3000, day(2)},
|
{5, "PAY-5", 201, "ORD-201", 21, "mockpay", "T-201", "mohong_refund", "refunded", 3000, day(2)},
|
||||||
{6, 201, "mohong_pay", "paid", 3000, day(1)},
|
{6, "PAY-6", 201, "ORD-201", 21, "mockpay", "T-202", "mohong_pay", "paid", 3000, day(1)},
|
||||||
}
|
}
|
||||||
for _, row := range rows {
|
for _, row := range rows {
|
||||||
if err := db.Exec(`INSERT INTO payment_orders (id, order_id, biz_type, status, amount_cent, created_at)
|
if err := db.Exec(`INSERT INTO payment_orders
|
||||||
VALUES (?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
(id, payment_no, order_id, order_no, user_id, provider, third_order_id, biz_type, status, amount_cent, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||||
t.Fatalf("写入支付单失败: %v", err)
|
t.Fatalf("写入支付单失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -145,28 +113,20 @@ func TestDailyPaymentsNormalFullRefundExcludesMohong(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestDailyPickupCancelledByCancelledAt(t *testing.T) {
|
func TestDailyPickupCancelledByCancelledAt(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE admin_pickups (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
cancelled_at DATETIME NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建提号表失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
day := func(value int) time.Time { return time.Date(2026, 8, value, 15, 0, 0, 0, loc) }
|
day := func(value int) time.Time { return time.Date(2026, 8, value, 15, 0, 0, 0, loc) }
|
||||||
for _, row := range [][]any{
|
for _, row := range [][]any{
|
||||||
{1, "cancelled", day(2)},
|
{1, "PK-1", 1, 1, 1, 1, "cancelled", day(1), day(2)},
|
||||||
{2, "cancelled", day(2)},
|
{2, "PK-2", 2, 2, 2, 1, "cancelled", day(1), day(2)},
|
||||||
{3, "cancelled", day(3)},
|
{3, "PK-3", 3, 3, 3, 1, "cancelled", day(1), day(3)},
|
||||||
{4, "cancelled", nil}, // 取消时间缺失的不计
|
{4, "PK-4", 4, 4, 4, 1, "cancelled", day(1), nil}, // 取消时间缺失的不计
|
||||||
{5, "completed", day(2)},
|
{5, "PK-5", 5, 5, 5, 1, "completed", day(1), day(2)},
|
||||||
} {
|
} {
|
||||||
if err := db.Exec(`INSERT INTO admin_pickups (id, status, cancelled_at) VALUES (?, ?, ?)`, row...).Error; err != nil {
|
if err := db.Exec(`INSERT INTO admin_pickups
|
||||||
|
(id, pickup_no, listing_id, account_id, owner_id, admin_id, status, created_at, cancelled_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||||
t.Fatalf("写入提号记录失败: %v", err)
|
t.Fatalf("写入提号记录失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -189,41 +149,19 @@ func TestDailyPickupCancelledByCancelledAt(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestPickupSummaryKeepsOriginalAndAdjustmentOnTheirOwnDates(t *testing.T) {
|
func TestPickupSummaryKeepsOriginalAndAdjustmentOnTheirOwnDates(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE admin_pickups (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
settle_amount_cent INTEGER NOT NULL,
|
|
||||||
profit_amount_cent INTEGER NOT NULL,
|
|
||||||
completed_at DATETIME NULL,
|
|
||||||
settlement_mode TEXT NOT NULL DEFAULT 'owner_wallet',
|
|
||||||
offline_settlement_status TEXT NOT NULL DEFAULT 'none'
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建提号表失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE admin_pickup_financial_adjustments (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
pickup_id INTEGER NOT NULL,
|
|
||||||
settle_delta_cent INTEGER NOT NULL,
|
|
||||||
profit_delta_cent INTEGER NOT NULL,
|
|
||||||
created_at DATETIME NOT NULL,
|
|
||||||
settlement_mode TEXT NOT NULL DEFAULT 'owner_wallet',
|
|
||||||
status TEXT NOT NULL DEFAULT 'settled'
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建提号调整表失败: %v", err)
|
|
||||||
}
|
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
completedAt := time.Date(2026, 8, 2, 10, 0, 0, 0, loc)
|
completedAt := time.Date(2026, 8, 2, 10, 0, 0, 0, loc)
|
||||||
adjustedAt := time.Date(2026, 8, 4, 10, 0, 0, 0, loc)
|
adjustedAt := time.Date(2026, 8, 4, 10, 0, 0, 0, loc)
|
||||||
if err := db.Exec(`INSERT INTO admin_pickups (id, status, settle_amount_cent, profit_amount_cent, completed_at)
|
if err := db.Exec(`INSERT INTO admin_pickups
|
||||||
VALUES (1, 'completed', 12000, 1000, ?)`, completedAt).Error; err != nil {
|
(id, pickup_no, listing_id, account_id, owner_id, admin_id, status, settle_amount_cent, profit_amount_cent,
|
||||||
|
created_at, completed_at)
|
||||||
|
VALUES (1, 'PK-1', 1, 1, 1, 1, 'completed', 12000, 1000, ?, ?)`, adjustedAt, completedAt).Error; err != nil {
|
||||||
t.Fatalf("写入提号失败: %v", err)
|
t.Fatalf("写入提号失败: %v", err)
|
||||||
}
|
}
|
||||||
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments (id, pickup_id, settle_delta_cent, profit_delta_cent, created_at)
|
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
||||||
VALUES (1, 1, 1500, 500, ?)`, adjustedAt).Error; err != nil {
|
(id, pickup_id, settlement_mode, status, reason, created_by, settle_delta_cent, profit_delta_cent, created_at)
|
||||||
|
VALUES (1, 1, 'owner_wallet', 'settled', '测试调整', 1, 1500, 500, ?)`, adjustedAt).Error; err != nil {
|
||||||
t.Fatalf("写入调整失败: %v", err)
|
t.Fatalf("写入调整失败: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -250,66 +188,36 @@ func TestPickupSummaryKeepsOriginalAndAdjustmentOnTheirOwnDates(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestSummaryReturnsNormalOrderCountAndScopedExceptionCount(t *testing.T) {
|
func TestSummaryReturnsNormalOrderCountAndScopedExceptionCount(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
for _, statement := range []string{
|
|
||||||
`CREATE TABLE payment_orders (
|
|
||||||
id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, biz_type TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL, amount_cent INTEGER NOT NULL, created_at DATETIME NOT NULL
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE rental_orders (
|
|
||||||
id INTEGER PRIMARY KEY, settled_at DATETIME NULL, settlement_mode TEXT NOT NULL,
|
|
||||||
offline_settlement_amount_cent INTEGER NOT NULL, offline_settlement_status TEXT NOT NULL,
|
|
||||||
refund_status TEXT NOT NULL, settlement_status TEXT NOT NULL, status TEXT NOT NULL,
|
|
||||||
created_at DATETIME NOT NULL, platform_fee_cent INTEGER NOT NULL
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE order_checkouts (
|
|
||||||
id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, status TEXT NOT NULL,
|
|
||||||
platform_fee_cent INTEGER NOT NULL, owner_income_amount_cent INTEGER NOT NULL
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE wallet_ledger (
|
|
||||||
id INTEGER PRIMARY KEY, order_id INTEGER NULL, direction TEXT NOT NULL,
|
|
||||||
biz_type TEXT NOT NULL, amount_cent INTEGER NOT NULL
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE admin_pickups (
|
|
||||||
id INTEGER PRIMARY KEY, status TEXT NOT NULL, settle_amount_cent INTEGER NOT NULL,
|
|
||||||
profit_amount_cent INTEGER NOT NULL, completed_at DATETIME NULL,
|
|
||||||
settlement_mode TEXT NOT NULL DEFAULT 'owner_wallet', offline_settlement_status TEXT NOT NULL DEFAULT 'none'
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE admin_pickup_financial_adjustments (
|
|
||||||
id INTEGER PRIMARY KEY, pickup_id INTEGER NOT NULL, settle_delta_cent INTEGER NOT NULL,
|
|
||||||
profit_delta_cent INTEGER NOT NULL, created_at DATETIME NOT NULL,
|
|
||||||
settlement_mode TEXT NOT NULL DEFAULT 'owner_wallet', status TEXT NOT NULL DEFAULT 'settled'
|
|
||||||
)`,
|
|
||||||
} {
|
|
||||||
if err := db.Exec(statement).Error; err != nil {
|
|
||||||
t.Fatalf("创建统计测试表失败: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
settledAt := time.Date(2026, 8, 2, 10, 0, 0, 0, loc)
|
settledAt := time.Date(2026, 8, 2, 10, 0, 0, 0, loc)
|
||||||
for _, row := range [][]any{
|
for _, row := range [][]any{
|
||||||
{1, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 300},
|
{1, "ORD-S1", 1, 1, 1, 1, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 300},
|
||||||
{2, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 200},
|
{2, "ORD-S2", 2, 2, 2, 2, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 200},
|
||||||
} {
|
} {
|
||||||
if err := db.Exec(`INSERT INTO rental_orders
|
if err := db.Exec(`INSERT INTO rental_orders
|
||||||
(id, settled_at, settlement_mode, offline_settlement_amount_cent, offline_settlement_status,
|
(id, order_no, listing_id, account_id, owner_id, renter_id,
|
||||||
|
settled_at, settlement_mode, offline_settlement_amount_cent, offline_settlement_status,
|
||||||
refund_status, settlement_status, status, created_at, platform_fee_cent)
|
refund_status, settlement_status, status, created_at, platform_fee_cent)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||||
t.Fatalf("写入订单失败: %v", err)
|
t.Fatalf("写入订单失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, row := range [][]any{{1, 1, "accepted", 300, 700}, {2, 2, "accepted", 200, 600}} {
|
for _, row := range [][]any{{1, 1, 1, "accepted", 300, 700}, {2, 2, 1, "accepted", 200, 600}} {
|
||||||
if err := db.Exec(`INSERT INTO order_checkouts
|
if err := db.Exec(`INSERT INTO order_checkouts
|
||||||
(id, order_id, status, platform_fee_cent, owner_income_amount_cent) VALUES (?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
(id, order_id, initiated_by, status, platform_fee_cent, owner_income_amount_cent)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||||
t.Fatalf("写入结账单失败: %v", err)
|
t.Fatalf("写入结账单失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, row := range [][]any{{1, 1, "in", "owner_income", 700}, {2, 2, "in", "owner_income", 500}} {
|
for _, row := range [][]any{
|
||||||
if err := db.Exec(`INSERT INTO wallet_ledger (id, order_id, direction, biz_type, amount_cent) VALUES (?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
{1, "WL-1", 1, 1, "in", "available", "owner_income", "WL-1", 700},
|
||||||
|
{2, "WL-2", 2, 2, "in", "available", "owner_income", "WL-2", 500},
|
||||||
|
} {
|
||||||
|
if err := db.Exec(`INSERT INTO wallet_ledger
|
||||||
|
(id, ledger_no, order_id, user_id, direction, balance_type, biz_type, biz_no, amount_cent)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||||
t.Fatalf("写入钱包流水失败: %v", err)
|
t.Fatalf("写入钱包流水失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,10 +11,10 @@ type dailyOperatingExpenseRow struct {
|
|||||||
func (r *Repository) dailyOperatingExpenses(ctx context.Context, query DashboardQuery) ([]dailyOperatingExpenseRow, error) {
|
func (r *Repository) dailyOperatingExpenses(ctx context.Context, query DashboardQuery) ([]dailyOperatingExpenseRow, error) {
|
||||||
rows := make([]dailyOperatingExpenseRow, 0)
|
rows := make([]dailyOperatingExpenseRow, 0)
|
||||||
err := r.db.WithContext(ctx).Table("operating_expenses").
|
err := r.db.WithContext(ctx).Table("operating_expenses").
|
||||||
Select(`DATE(occurred_at) AS date, COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
Select(`DATE_FORMAT(occurred_at, '%Y-%m-%d') AS date, COALESCE(SUM(amount_cent), 0) AS amount_cent, COUNT(id) AS count`).
|
||||||
Where("status = ?", "paid").
|
Where("status = ?", "paid").
|
||||||
Where("occurred_at >= ? AND occurred_at <= ?", query.StartDate, query.EndDate).
|
Where("occurred_at >= ? AND occurred_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(occurred_at)").
|
Group("DATE_FORMAT(occurred_at, '%Y-%m-%d')").
|
||||||
Scan(&rows).Error
|
Scan(&rows).Error
|
||||||
return rows, err
|
return rows, err
|
||||||
}
|
}
|
||||||
@@ -162,38 +162,38 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
|||||||
db := r.db.WithContext(ctx)
|
db := r.db.WithContext(ctx)
|
||||||
offlineRows := make([]dailyDisbursementSourceRow, 0)
|
offlineRows := make([]dailyDisbursementSourceRow, 0)
|
||||||
if err := db.Table("rental_orders").
|
if err := db.Table("rental_orders").
|
||||||
Select(`DATE(offline_settled_at) AS date,
|
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent,
|
COALESCE(SUM(offline_settlement_amount_cent), 0) AS amount_cent,
|
||||||
COUNT(id) AS count`).
|
COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
Where("offline_settlement_status = ?", "settled").
|
Where("offline_settlement_status = ?", "settled").
|
||||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(offline_settled_at)").
|
Group("DATE_FORMAT(offline_settled_at, '%Y-%m-%d')").
|
||||||
Scan(&offlineRows).Error; err != nil {
|
Scan(&offlineRows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pickupOfflineRows := make([]dailyDisbursementSourceRow, 0)
|
pickupOfflineRows := make([]dailyDisbursementSourceRow, 0)
|
||||||
if err := db.Table("admin_pickups").
|
if err := db.Table("admin_pickups").
|
||||||
Select(`DATE(offline_settled_at) AS date,
|
Select(`DATE_FORMAT(offline_settled_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(settle_amount_cent), 0) AS amount_cent,
|
COALESCE(SUM(settle_amount_cent), 0) AS amount_cent,
|
||||||
COUNT(id) AS count`).
|
COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
Where("offline_settlement_status = ?", "settled").
|
Where("offline_settlement_status = ?", "settled").
|
||||||
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
Where("offline_settled_at >= ? AND offline_settled_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(offline_settled_at)").
|
Group("DATE_FORMAT(offline_settled_at, '%Y-%m-%d')").
|
||||||
Scan(&pickupOfflineRows).Error; err != nil {
|
Scan(&pickupOfflineRows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
pickupAdjustmentRows := make([]dailyDisbursementSourceRow, 0)
|
pickupAdjustmentRows := make([]dailyDisbursementSourceRow, 0)
|
||||||
if err := db.Table("admin_pickup_financial_adjustments").
|
if err := db.Table("admin_pickup_financial_adjustments").
|
||||||
Select(`DATE(settled_at) AS date,
|
Select(`DATE_FORMAT(settled_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(settle_delta_cent), 0) AS amount_cent,
|
COALESCE(SUM(settle_delta_cent), 0) AS amount_cent,
|
||||||
COUNT(id) AS count`).
|
COUNT(id) AS count`).
|
||||||
Where("settlement_mode = ?", "platform_managed").
|
Where("settlement_mode = ?", "platform_managed").
|
||||||
Where("status = ?", "settled").
|
Where("status = ?", "settled").
|
||||||
Where("settle_delta_cent > 0").
|
Where("settle_delta_cent > 0").
|
||||||
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
Where("settled_at >= ? AND settled_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(settled_at)").
|
Group("DATE_FORMAT(settled_at, '%Y-%m-%d')").
|
||||||
Scan(&pickupAdjustmentRows).Error; err != nil {
|
Scan(&pickupAdjustmentRows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
@@ -202,24 +202,24 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
|||||||
|
|
||||||
withdrawalRows := make([]dailyDisbursementSourceRow, 0)
|
withdrawalRows := make([]dailyDisbursementSourceRow, 0)
|
||||||
if err := db.Table("withdrawal_requests").
|
if err := db.Table("withdrawal_requests").
|
||||||
Select(`DATE(paid_at) AS date,
|
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(actual_amount_cent), 0) AS amount_cent,
|
COALESCE(SUM(actual_amount_cent), 0) AS amount_cent,
|
||||||
COUNT(id) AS count`).
|
COUNT(id) AS count`).
|
||||||
Where("status = ?", "completed").
|
Where("status = ?", "completed").
|
||||||
Where("paid_at >= ? AND paid_at <= ?", query.StartDate, query.EndDate).
|
Where("paid_at >= ? AND paid_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(paid_at)").
|
Group("DATE_FORMAT(paid_at, '%Y-%m-%d')").
|
||||||
Scan(&withdrawalRows).Error; err != nil {
|
Scan(&withdrawalRows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
manualRows := make([]dailyDisbursementSourceRow, 0)
|
manualRows := make([]dailyDisbursementSourceRow, 0)
|
||||||
if err := db.Table("manual_disbursements").
|
if err := db.Table("manual_disbursements").
|
||||||
Select(`DATE(paid_at) AS date,
|
Select(`DATE_FORMAT(paid_at, '%Y-%m-%d') AS date,
|
||||||
COALESCE(SUM(amount_cent), 0) AS amount_cent,
|
COALESCE(SUM(amount_cent), 0) AS amount_cent,
|
||||||
COUNT(id) AS count`).
|
COUNT(id) AS count`).
|
||||||
Where("status = ?", "paid").
|
Where("status = ?", "paid").
|
||||||
Where("paid_at >= ? AND paid_at <= ?", query.StartDate, query.EndDate).
|
Where("paid_at >= ? AND paid_at <= ?", query.StartDate, query.EndDate).
|
||||||
Group("DATE(paid_at)").
|
Group("DATE_FORMAT(paid_at, '%Y-%m-%d')").
|
||||||
Scan(&manualRows).Error; err != nil {
|
Scan(&manualRows).Error; err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,70 +4,21 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestDisbursementListCombinesPlatformSettlementsAndWithdrawals(t *testing.T) {
|
func TestDisbursementListCombinesPlatformSettlementsAndWithdrawals(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
statements := []string{
|
|
||||||
`CREATE TABLE rental_orders (
|
|
||||||
id INTEGER PRIMARY KEY, order_no TEXT, listing_id INTEGER, owner_id INTEGER,
|
|
||||||
settlement_mode TEXT, offline_settlement_status TEXT,
|
|
||||||
offline_settlement_amount_cent INTEGER, offline_settlement_remark TEXT,
|
|
||||||
settled_at DATETIME, offline_settled_at DATETIME, offline_settled_by INTEGER
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE listing_uploads (
|
|
||||||
id INTEGER PRIMARY KEY, listing_id INTEGER, uploader_name TEXT,
|
|
||||||
source_channel TEXT, parsed_payload BLOB
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE withdrawal_requests (
|
|
||||||
id INTEGER PRIMARY KEY, withdraw_no TEXT, user_id INTEGER,
|
|
||||||
account_type TEXT, account_name TEXT, account_no TEXT, bank_name TEXT,
|
|
||||||
amount_cent INTEGER, fee_cent INTEGER, actual_amount_cent INTEGER,
|
|
||||||
status TEXT, created_at DATETIME, paid_at DATETIME, paid_by INTEGER,
|
|
||||||
reviewed_by INTEGER, payment_remark TEXT, review_remark TEXT
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE users (id INTEGER PRIMARY KEY, nickname TEXT, phone TEXT)`,
|
|
||||||
`CREATE TABLE admin_users (id INTEGER PRIMARY KEY, nickname TEXT, username TEXT)`,
|
|
||||||
`CREATE TABLE manual_disbursements (
|
|
||||||
id INTEGER PRIMARY KEY, disbursement_no TEXT, category TEXT, custom_category_name TEXT NOT NULL DEFAULT '', payee_name TEXT,
|
|
||||||
amount_cent INTEGER, paid_at DATETIME, remark TEXT, voucher_url TEXT,
|
|
||||||
status TEXT, created_by INTEGER, voided_by INTEGER, voided_at DATETIME,
|
|
||||||
void_reason TEXT, created_at DATETIME
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE admin_pickups (
|
|
||||||
id INTEGER PRIMARY KEY, pickup_no TEXT, owner_id INTEGER, source_channel TEXT,
|
|
||||||
settlement_mode TEXT, settle_amount_cent INTEGER, offline_settlement_status TEXT,
|
|
||||||
offline_settlement_remark TEXT, offline_settled_by INTEGER, offline_settled_at DATETIME,
|
|
||||||
completed_at DATETIME, account_snapshot BLOB
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE admin_pickup_financial_adjustments (
|
|
||||||
id INTEGER PRIMARY KEY, pickup_id INTEGER, settle_delta_cent INTEGER,
|
|
||||||
settlement_mode TEXT, status TEXT, reason TEXT, settled_by INTEGER,
|
|
||||||
settled_at DATETIME, created_at DATETIME
|
|
||||||
)`,
|
|
||||||
}
|
|
||||||
for _, statement := range statements {
|
|
||||||
if err := db.Exec(statement).Error; err != nil {
|
|
||||||
t.Fatalf("创建测试表失败: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
at := func(day int) time.Time { return time.Date(2026, 7, day, 10, 0, 0, 0, loc) }
|
at := func(day int) time.Time { return time.Date(2026, 7, day, 10, 0, 0, 0, loc) }
|
||||||
if err := db.Exec(`INSERT INTO users (id, nickname, phone) VALUES
|
if err := db.Exec(`INSERT INTO users (id, nickname, phone, password_hash) VALUES
|
||||||
(1, '平台客服', 'admin:1'), (2, '提现用户', '13900000000')`).Error; err != nil {
|
(1, '平台客服', 'admin:1', ''), (2, '提现用户', '13900000000', '')`).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username) VALUES
|
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username, password_hash) VALUES
|
||||||
(7, '财务甲', 'finance_a'), (8, '财务乙', 'finance_b')`).Error; err != nil {
|
(7, '财务甲', 'finance_a', ''), (8, '财务乙', 'finance_b', '')`).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := db.Exec(`INSERT INTO listing_uploads
|
if err := db.Exec(`INSERT INTO listing_uploads
|
||||||
@@ -78,23 +29,25 @@ func TestDisbursementListCombinesPlatformSettlementsAndWithdrawals(t *testing.T)
|
|||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := db.Exec(`INSERT INTO rental_orders
|
if err := db.Exec(`INSERT INTO rental_orders
|
||||||
(id, order_no, listing_id, owner_id, settlement_mode, offline_settlement_status,
|
(id, order_no, listing_id, account_id, owner_id, renter_id, settlement_mode, offline_settlement_status,
|
||||||
offline_settlement_amount_cent, offline_settlement_remark, settled_at, offline_settled_at, offline_settled_by)
|
offline_settlement_amount_cent, offline_settlement_remark, settled_at, offline_settled_at, offline_settled_by)
|
||||||
VALUES
|
VALUES
|
||||||
(1, 'R202607010001', 101, 1, 'platform_managed', 'settled', 12000, '支付宝转账', ?, ?, 7),
|
(1, 'R202607010001', 101, 101, 1, 2, 'platform_managed', 'settled', 12000, '支付宝转账', ?, ?, 7),
|
||||||
(2, 'R202607010002', 102, 1, 'platform_managed', 'pending', 8000, '', ?, NULL, NULL)`,
|
(2, 'R202607010002', 102, 102, 1, 2, 'platform_managed', 'pending', 8000, '', ?, NULL, NULL)`,
|
||||||
at(2), at(3), at(4)).Error; err != nil {
|
at(2), at(3), at(4)).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := db.Exec(`INSERT INTO admin_pickups
|
if err := db.Exec(`INSERT INTO admin_pickups
|
||||||
(id, pickup_no, owner_id, source_channel, settlement_mode, settle_amount_cent, offline_settlement_status,
|
(id, pickup_no, listing_id, account_id, owner_id, admin_id, source_channel, settlement_mode, settle_amount_cent,
|
||||||
offline_settlement_remark, offline_settled_by, offline_settled_at, completed_at, account_snapshot)
|
offline_settlement_status, offline_settlement_remark, offline_settled_by, offline_settled_at, completed_at,
|
||||||
VALUES (30, 'P202607010001', 1, '线下录入', 'platform_managed', 4000, 'settled', '提号结算', 7, ?, ?, '{}')`, at(4), at(3)).Error; err != nil {
|
created_at, account_snapshot)
|
||||||
|
VALUES (30, 'P202607010001', 101, 101, 1, 7, '线下录入', 'platform_managed', 4000, 'settled', '提号结算', 7, ?, ?, ?, '{}')`,
|
||||||
|
at(4), at(3), at(2)).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
||||||
(id, pickup_id, settle_delta_cent, settlement_mode, status, reason, settled_by, settled_at, created_at)
|
(id, pickup_id, settle_delta_cent, settlement_mode, status, reason, created_by, settled_by, settled_at, created_at)
|
||||||
VALUES (31, 30, 500, 'platform_managed', 'settled', '补差价', 7, ?, ?)`, at(5), at(5)).Error; err != nil {
|
VALUES (31, 30, 500, 'platform_managed', 'settled', '补差价', 7, 7, ?, ?)`, at(5), at(5)).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := db.Exec(`INSERT INTO withdrawal_requests
|
if err := db.Exec(`INSERT INTO withdrawal_requests
|
||||||
|
|||||||
@@ -4,63 +4,12 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestDisbursementStatisticsUseActualPaymentTimeAndAmount(t *testing.T) {
|
func TestDisbursementStatisticsUseActualPaymentTimeAndAmount(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE rental_orders (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
settlement_mode TEXT NOT NULL,
|
|
||||||
offline_settlement_status TEXT NOT NULL,
|
|
||||||
offline_settlement_amount_cent INTEGER NOT NULL,
|
|
||||||
offline_settled_at DATETIME NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建订单表失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE withdrawal_requests (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
amount_cent INTEGER NOT NULL,
|
|
||||||
fee_cent INTEGER NOT NULL,
|
|
||||||
actual_amount_cent INTEGER NOT NULL,
|
|
||||||
paid_at DATETIME NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建提现表失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE manual_disbursements (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
amount_cent INTEGER NOT NULL,
|
|
||||||
paid_at DATETIME NOT NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建其他线下出款表失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE admin_pickups (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
settlement_mode TEXT NOT NULL,
|
|
||||||
offline_settlement_status TEXT NOT NULL,
|
|
||||||
settle_amount_cent INTEGER NOT NULL,
|
|
||||||
offline_settled_at DATETIME NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建提号表失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE admin_pickup_financial_adjustments (
|
|
||||||
id INTEGER PRIMARY KEY,
|
|
||||||
settlement_mode TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL,
|
|
||||||
settle_delta_cent INTEGER NOT NULL,
|
|
||||||
settled_at DATETIME NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建提号调整表失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
inRangeOffline := time.Date(2026, 7, 1, 10, 0, 0, 0, loc)
|
inRangeOffline := time.Date(2026, 7, 1, 10, 0, 0, 0, loc)
|
||||||
@@ -69,59 +18,63 @@ func TestDisbursementStatisticsUseActualPaymentTimeAndAmount(t *testing.T) {
|
|||||||
outOfRange := time.Date(2026, 6, 30, 23, 59, 0, 0, loc)
|
outOfRange := time.Date(2026, 6, 30, 23, 59, 0, 0, loc)
|
||||||
|
|
||||||
for _, args := range [][]any{
|
for _, args := range [][]any{
|
||||||
{1, "platform_managed", "settled", 12000, inRangeOffline},
|
{1, "ORD-1", 1, 1, 1, 1, "platform_managed", "settled", 12000, inRangeOffline},
|
||||||
{2, "platform_managed", "settled", 3000, outOfRange},
|
{2, "ORD-2", 2, 2, 2, 2, "platform_managed", "settled", 3000, outOfRange},
|
||||||
{3, "platform_managed", "pending", 8000, nil},
|
{3, "ORD-3", 3, 3, 3, 3, "platform_managed", "pending", 8000, nil},
|
||||||
{4, "platform_managed", "pending", 0, nil},
|
{4, "ORD-4", 4, 4, 4, 4, "platform_managed", "pending", 0, nil},
|
||||||
{5, "owner_wallet", "pending", 9000, nil},
|
{5, "ORD-5", 5, 5, 5, 5, "owner_wallet", "pending", 9000, nil},
|
||||||
} {
|
} {
|
||||||
if err := db.Exec(`INSERT INTO rental_orders
|
if err := db.Exec(`INSERT INTO rental_orders
|
||||||
(id, settlement_mode, offline_settlement_status, offline_settlement_amount_cent, offline_settled_at)
|
(id, order_no, listing_id, account_id, owner_id, renter_id,
|
||||||
VALUES (?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
settlement_mode, offline_settlement_status, offline_settlement_amount_cent, offline_settled_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||||
t.Fatalf("写入订单失败: %v", err)
|
t.Fatalf("写入订单失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, args := range [][]any{
|
for _, args := range [][]any{
|
||||||
{1, "platform_managed", "settled", 4000, inRangeOffline},
|
{1, "PKR-1", 1, 1, 1, 1, "platform_managed", "settled", 4000, inRangeOffline, inRangeOffline},
|
||||||
{2, "platform_managed", "pending", 2500, nil},
|
{2, "PKR-2", 2, 2, 2, 2, "platform_managed", "pending", 2500, nil, inRangeOffline},
|
||||||
} {
|
} {
|
||||||
if err := db.Exec(`INSERT INTO admin_pickups
|
if err := db.Exec(`INSERT INTO admin_pickups
|
||||||
(id, settlement_mode, offline_settlement_status, settle_amount_cent, offline_settled_at)
|
(id, pickup_no, listing_id, account_id, owner_id, admin_id, settlement_mode,
|
||||||
VALUES (?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
offline_settlement_status, settle_amount_cent, offline_settled_at, created_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||||
t.Fatalf("写入提号失败: %v", err)
|
t.Fatalf("写入提号失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, args := range [][]any{
|
for _, args := range [][]any{
|
||||||
{1, "platform_managed", "settled", 500, inRangeManual},
|
{1, 1, "platform_managed", "settled", "补差价", 1, 500, inRangeManual, inRangeManual},
|
||||||
{2, "platform_managed", "pending", 300, nil},
|
{2, 2, "platform_managed", "pending", "补差价", 1, 300, nil, inRangeManual},
|
||||||
{3, "platform_managed", "recovery_pending", -200, nil},
|
{3, 3, "platform_managed", "recovery_pending", "补差价", 1, -200, nil, inRangeManual},
|
||||||
} {
|
} {
|
||||||
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
||||||
(id, settlement_mode, status, settle_delta_cent, settled_at)
|
(id, pickup_id, settlement_mode, status, reason, created_by, settle_delta_cent, settled_at, created_at)
|
||||||
VALUES (?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||||
t.Fatalf("写入提号调整失败: %v", err)
|
t.Fatalf("写入提号调整失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, args := range [][]any{
|
for _, args := range [][]any{
|
||||||
{1, "paid", 2500, inRangeManual},
|
{1, "MD-1", "推广投放", "测试收款方", "测试备注", 1, "paid", 2500, inRangeManual},
|
||||||
{2, "paid", 1000, outOfRange},
|
{2, "MD-2", "推广投放", "测试收款方", "测试备注", 1, "paid", 1000, outOfRange},
|
||||||
{3, "voided", 6000, inRangeManual},
|
{3, "MD-3", "推广投放", "测试收款方", "测试备注", 1, "voided", 6000, inRangeManual},
|
||||||
} {
|
} {
|
||||||
if err := db.Exec(`INSERT INTO manual_disbursements
|
if err := db.Exec(`INSERT INTO manual_disbursements
|
||||||
(id, status, amount_cent, paid_at) VALUES (?, ?, ?, ?)`, args...).Error; err != nil {
|
(id, disbursement_no, category, payee_name, remark, created_by, status, amount_cent, paid_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||||
t.Fatalf("写入其他线下出款失败: %v", err)
|
t.Fatalf("写入其他线下出款失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for _, args := range [][]any{
|
for _, args := range [][]any{
|
||||||
{1, "completed", 10000, 100, 9900, inRangeWithdrawal},
|
{1, "WD-1", 1, "alipay", "测试户名", "test@example.com", "completed", 10000, 100, 9900, inRangeWithdrawal},
|
||||||
{2, "completed", 5000, 0, 5000, outOfRange},
|
{2, "WD-2", 1, "alipay", "测试户名", "test@example.com", "completed", 5000, 0, 5000, outOfRange},
|
||||||
{3, "processing", 5000, 200, 4800, nil},
|
{3, "WD-3", 1, "alipay", "测试户名", "test@example.com", "processing", 5000, 200, 4800, nil},
|
||||||
{4, "pending", 2100, 100, 2000, nil},
|
{4, "WD-4", 1, "alipay", "测试户名", "test@example.com", "pending", 2100, 100, 2000, nil},
|
||||||
{5, "rejected", 6000, 100, 5900, nil},
|
{5, "WD-5", 1, "alipay", "测试户名", "test@example.com", "rejected", 6000, 100, 5900, nil},
|
||||||
} {
|
} {
|
||||||
if err := db.Exec(`INSERT INTO withdrawal_requests
|
if err := db.Exec(`INSERT INTO withdrawal_requests
|
||||||
(id, status, amount_cent, fee_cent, actual_amount_cent, paid_at)
|
(id, withdraw_no, user_id, account_type, account_name, account_no,
|
||||||
VALUES (?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
status, amount_cent, fee_cent, actual_amount_cent, paid_at)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||||
t.Fatalf("写入提现单失败: %v", err)
|
t.Fatalf("写入提现单失败: %v", err)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,41 +6,14 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/auditlog"
|
"hfb_sys/backend/internal/auditlog"
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestManualDisbursementCreateAndVoid(t *testing.T) {
|
func TestManualDisbursementCreateAndVoid(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username, password_hash) VALUES
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
(7, '财务甲', 'finance_a', ''), (8, '财务乙', 'finance_b', '')`).Error; err != nil {
|
||||||
}
|
|
||||||
statements := []string{
|
|
||||||
`CREATE TABLE manual_disbursements (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT, disbursement_no TEXT NOT NULL UNIQUE,
|
|
||||||
category TEXT NOT NULL, custom_category_name TEXT NOT NULL DEFAULT '', payee_name TEXT NOT NULL, amount_cent INTEGER NOT NULL,
|
|
||||||
paid_at DATETIME NOT NULL, remark TEXT NOT NULL, voucher_url TEXT NOT NULL,
|
|
||||||
status TEXT NOT NULL, created_by INTEGER NOT NULL, voided_by INTEGER,
|
|
||||||
voided_at DATETIME, void_reason TEXT NOT NULL DEFAULT '', created_at DATETIME,
|
|
||||||
updated_at DATETIME
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE admin_users (id INTEGER PRIMARY KEY, nickname TEXT, username TEXT)`,
|
|
||||||
`CREATE TABLE audit_logs (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT, actor_type TEXT, actor_id INTEGER,
|
|
||||||
action TEXT, biz_type TEXT, biz_id INTEGER, ip TEXT, user_agent TEXT,
|
|
||||||
detail BLOB, created_at DATETIME
|
|
||||||
)`,
|
|
||||||
}
|
|
||||||
for _, statement := range statements {
|
|
||||||
if err := db.Exec(statement).Error; err != nil {
|
|
||||||
t.Fatalf("创建测试表失败: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username) VALUES
|
|
||||||
(7, '财务甲', 'finance_a'), (8, '财务乙', 'finance_b')`).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -6,36 +6,13 @@ import (
|
|||||||
"time"
|
"time"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/auditlog"
|
"hfb_sys/backend/internal/auditlog"
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestOperatingExpenseCreateListAndVoid(t *testing.T) {
|
func TestOperatingExpenseCreateListAndVoid(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username, password_hash) VALUES (7, '运营甲', 'ops_a', ''), (8, '运营乙', 'ops_b', '')`).Error; err != nil {
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
for _, statement := range []string{
|
|
||||||
`CREATE TABLE operating_expenses (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT, expense_no TEXT NOT NULL UNIQUE, category TEXT NOT NULL,
|
|
||||||
payee_name TEXT NOT NULL, amount_cent INTEGER NOT NULL, occurred_at DATETIME NOT NULL,
|
|
||||||
remark TEXT NOT NULL, voucher_url TEXT NOT NULL, status TEXT NOT NULL, created_by INTEGER NOT NULL,
|
|
||||||
voided_by INTEGER, voided_at DATETIME, void_reason TEXT NOT NULL DEFAULT '', created_at DATETIME, updated_at DATETIME
|
|
||||||
)`,
|
|
||||||
`CREATE TABLE admin_users (id INTEGER PRIMARY KEY, nickname TEXT, username TEXT)`,
|
|
||||||
`CREATE TABLE audit_logs (
|
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT, actor_type TEXT, actor_id INTEGER, action TEXT, biz_type TEXT,
|
|
||||||
biz_id INTEGER, ip TEXT, user_agent TEXT, detail BLOB, created_at DATETIME
|
|
||||||
)`,
|
|
||||||
} {
|
|
||||||
if err := db.Exec(statement).Error; err != nil {
|
|
||||||
t.Fatalf("创建测试表失败: %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username) VALUES (7, '运营甲', 'ops_a'), (8, '运营乙', 'ops_b')`).Error; err != nil {
|
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,19 +56,15 @@ func TestOperatingExpenseCreateListAndVoid(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestOperatingExpenseDashboardSummaryExcludesVoided(t *testing.T) {
|
func TestOperatingExpenseDashboardSummaryExcludesVoided(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.Exec(`CREATE TABLE operating_expenses (
|
|
||||||
id INTEGER PRIMARY KEY, amount_cent INTEGER NOT NULL, occurred_at DATETIME NOT NULL, status TEXT NOT NULL
|
|
||||||
)`).Error; err != nil {
|
|
||||||
t.Fatalf("创建运营开支表失败: %v", err)
|
|
||||||
}
|
|
||||||
loc := timeutil.ShanghaiLocation()
|
loc := timeutil.ShanghaiLocation()
|
||||||
inRange := time.Date(2026, 8, 20, 10, 0, 0, 0, loc)
|
inRange := time.Date(2026, 8, 20, 10, 0, 0, 0, loc)
|
||||||
if err := db.Exec(`INSERT INTO operating_expenses (id, amount_cent, occurred_at, status) VALUES
|
if err := db.Exec(`INSERT INTO operating_expenses
|
||||||
(1, 12000, ?, 'paid'), (2, 8000, ?, 'voided'), (3, 5000, ?, 'paid')`, inRange, inRange, inRange.AddDate(0, 0, -1)).Error; err != nil {
|
(id, expense_no, category, payee_name, remark, created_by, amount_cent, occurred_at, status) VALUES
|
||||||
|
(1, 'OE-1', '推广投放', '测试收款方', '测试备注', 1, 12000, ?, 'paid'),
|
||||||
|
(2, 'OE-2', '推广投放', '测试收款方', '测试备注', 1, 8000, ?, 'voided'),
|
||||||
|
(3, 'OE-3', '推广投放', '测试收款方', '测试备注', 1, 5000, ?, 'paid')`,
|
||||||
|
inRange, inRange, inRange.AddDate(0, 0, -1)).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
summary, err := NewRepository(db).operatingExpenseSummary(t.Context(), DashboardQuery{
|
summary, err := NewRepository(db).operatingExpenseSummary(t.Context(), DashboardQuery{
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
|
|
||||||
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.AdminNotification{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.AdminNotification{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -52,7 +52,7 @@ func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
|||||||
|
|
||||||
func TestRepositoryMarkAllRead(t *testing.T) {
|
func TestRepositoryMarkAllRead(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.AdminNotification{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.AdminNotification{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -93,7 +93,7 @@ func TestRepositoryMarkAllRead(t *testing.T) {
|
|||||||
|
|
||||||
func TestRepositoryMarkReadNotFound(t *testing.T) {
|
func TestRepositoryMarkReadNotFound(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.AdminNotification{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.AdminNotification{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
|
|||||||
@@ -3,14 +3,14 @@ package adminrole
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type RoleDTO struct {
|
type RoleDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Description string `json:"description"`
|
Description string `json:"description"`
|
||||||
PermCount int `json:"perm_count"`
|
PermCount int `json:"perm_count"`
|
||||||
Permissions []PermissionDTO `json:"permissions,omitempty"`
|
Permissions []PermissionDTO `json:"permissions,omitempty"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type PermissionDTO struct {
|
type PermissionDTO struct {
|
||||||
|
|||||||
@@ -5,10 +5,10 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -62,10 +62,7 @@ func TestParseBoolQuery(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyUserFilterHasDepositFreeQuota(t *testing.T) {
|
func TestApplyUserFilterHasDepositFreeQuota(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
db := database.NewDryRunDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败:%v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
stmt := applyUserFilter(db.Table("users AS u"), ListQuery{
|
stmt := applyUserFilter(db.Table("users AS u"), ListQuery{
|
||||||
Status: "active",
|
Status: "active",
|
||||||
@@ -328,11 +325,8 @@ func TestFreezeAndUnfreezeBumpUserTokenVersion(t *testing.T) {
|
|||||||
|
|
||||||
func setupAdminUserTestDB(t *testing.T) *gorm.DB {
|
func setupAdminUserTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
t.Fatalf("打开测试数据库失败:%v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(
|
|
||||||
&model.User{},
|
&model.User{},
|
||||||
&model.UserRealname{},
|
&model.UserRealname{},
|
||||||
&model.AuditLog{},
|
&model.AuditLog{},
|
||||||
|
|||||||
@@ -3,27 +3,27 @@ package adtracking
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type TrackingLinkItem struct {
|
type TrackingLinkItem struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Code string `json:"code"`
|
Code string `json:"code"`
|
||||||
ChannelType string `json:"channel_type"`
|
ChannelType string `json:"channel_type"`
|
||||||
TargetURL string `json:"target_url"`
|
TargetURL string `json:"target_url"`
|
||||||
ShortURL string `json:"short_url"`
|
ShortURL string `json:"short_url"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
CostCent int64 `json:"cost_cent"`
|
CostCent int64 `json:"cost_cent"`
|
||||||
Notes string `json:"notes"`
|
Notes string `json:"notes"`
|
||||||
CreatedBy uint64 `json:"created_by"`
|
CreatedBy uint64 `json:"created_by"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
|
|
||||||
// 统计指标
|
// 统计指标
|
||||||
ClickPV int64 `json:"click_pv"`
|
ClickPV int64 `json:"click_pv"`
|
||||||
ClickUV int64 `json:"click_uv"`
|
ClickUV int64 `json:"click_uv"`
|
||||||
ClickIP int64 `json:"click_ip"`
|
ClickIP int64 `json:"click_ip"`
|
||||||
RegisterCount int64 `json:"register_count"`
|
RegisterCount int64 `json:"register_count"`
|
||||||
OrderCount int64 `json:"order_count"`
|
OrderCount int64 `json:"order_count"`
|
||||||
PaidOrderCount int64 `json:"paid_order_count"`
|
PaidOrderCount int64 `json:"paid_order_count"`
|
||||||
PaidGMVCent int64 `json:"paid_gmv_cent"`
|
PaidGMVCent int64 `json:"paid_gmv_cent"`
|
||||||
ConversionRate float64 `json:"conversion_rate"` // 下单转化率 (OrderCount / max(ClickUV, 1))
|
ConversionRate float64 `json:"conversion_rate"` // 下单转化率 (OrderCount / max(ClickUV, 1))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,19 +57,19 @@ type ListTrackingLinksQuery struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type TrackingOverviewStats struct {
|
type TrackingOverviewStats struct {
|
||||||
TotalLinks int64 `json:"total_links"`
|
TotalLinks int64 `json:"total_links"`
|
||||||
ActiveLinks int64 `json:"active_links"`
|
ActiveLinks int64 `json:"active_links"`
|
||||||
TotalPV int64 `json:"total_pv"`
|
TotalPV int64 `json:"total_pv"`
|
||||||
TotalUV int64 `json:"total_uv"`
|
TotalUV int64 `json:"total_uv"`
|
||||||
TotalIP int64 `json:"total_ip"`
|
TotalIP int64 `json:"total_ip"`
|
||||||
TotalRegisters int64 `json:"total_registers"`
|
TotalRegisters int64 `json:"total_registers"`
|
||||||
TotalOrders int64 `json:"total_orders"`
|
TotalOrders int64 `json:"total_orders"`
|
||||||
TotalPaidOrders int64 `json:"total_paid_orders"`
|
TotalPaidOrders int64 `json:"total_paid_orders"`
|
||||||
TotalPaidGMVCent int64 `json:"total_paid_gmv_cent"`
|
TotalPaidGMVCent int64 `json:"total_paid_gmv_cent"`
|
||||||
|
|
||||||
TodayPV int64 `json:"today_pv"`
|
TodayPV int64 `json:"today_pv"`
|
||||||
TodayUV int64 `json:"today_uv"`
|
TodayUV int64 `json:"today_uv"`
|
||||||
TodayRegisters int64 `json:"today_registers"`
|
TodayRegisters int64 `json:"today_registers"`
|
||||||
TodayOrders int64 `json:"today_orders"`
|
TodayOrders int64 `json:"today_orders"`
|
||||||
TodayPaidGMVCent int64 `json:"today_paid_gmv_cent"`
|
TodayPaidGMVCent int64 `json:"today_paid_gmv_cent"`
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,20 +4,12 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestUserTokenVersionRevokesAccessAndRefreshTokens(t *testing.T) {
|
func TestUserTokenVersionRevokesAccessAndRefreshTokens(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败:%v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&model.User{}); err != nil {
|
|
||||||
t.Fatalf("数据库迁移失败:%v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
user := model.User{Phone: "13900000001", Status: "active", TokenVersion: 1}
|
user := model.User{Phone: "13900000001", Status: "active", TokenVersion: 1}
|
||||||
if err := db.Create(&user).Error; err != nil {
|
if err := db.Create(&user).Error; err != nil {
|
||||||
|
|||||||
@@ -4,20 +4,16 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func setupAdminListTestDB(t *testing.T) *gorm.DB {
|
func setupAdminListTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(
|
|
||||||
&model.User{},
|
&model.User{},
|
||||||
&model.AdminUser{},
|
&model.AdminUser{},
|
||||||
&model.RentalListing{},
|
&model.RentalListing{},
|
||||||
|
|||||||
@@ -4,22 +4,16 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func setupConversationTestDB(t *testing.T) *gorm.DB {
|
func setupConversationTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
db := database.NewTestDB()
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("无法创建测试数据库: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(
|
|
||||||
&model.User{},
|
&model.User{},
|
||||||
&model.RentalOrder{},
|
&model.RentalOrder{},
|
||||||
&model.ChatConversation{},
|
&model.ChatConversation{},
|
||||||
|
|||||||
@@ -6,22 +6,16 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func setupQrCodeTestDB(t *testing.T) *gorm.DB {
|
func setupQrCodeTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
db := database.NewTestDB()
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("无法创建测试数据库: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(
|
|
||||||
&model.ChatQrCode{},
|
&model.ChatQrCode{},
|
||||||
&model.DistributionSite{},
|
&model.DistributionSite{},
|
||||||
&model.DistributionSiteAccount{},
|
&model.DistributionSiteAccount{},
|
||||||
|
|||||||
@@ -190,4 +190,3 @@ func isAllDigits(s string) bool {
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,6 @@ import (
|
|||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/datatypes"
|
"gorm.io/datatypes"
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -705,10 +704,7 @@ func TestPartialRefundOwnerIncomeCentUnit(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
db := database.NewDryRunDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -757,4 +753,3 @@ func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -91,49 +91,49 @@ type UpdateRuleStatusRequest struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type DistributionOrderDTO struct {
|
type DistributionOrderDTO struct {
|
||||||
OrderID uint64 `json:"order_id"`
|
OrderID uint64 `json:"order_id"`
|
||||||
OrderNo string `json:"order_no"`
|
OrderNo string `json:"order_no"`
|
||||||
SiteID uint64 `json:"site_id"`
|
SiteID uint64 `json:"site_id"`
|
||||||
ListingID uint64 `json:"listing_id"`
|
ListingID uint64 `json:"listing_id"`
|
||||||
AccountID uint64 `json:"account_id"`
|
AccountID uint64 `json:"account_id"`
|
||||||
OwnerID uint64 `json:"owner_id"`
|
OwnerID uint64 `json:"owner_id"`
|
||||||
RenterID uint64 `json:"renter_id"`
|
RenterID uint64 `json:"renter_id"`
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
HandoffStatus string `json:"handoff_status"`
|
HandoffStatus string `json:"handoff_status"`
|
||||||
RefundStatus string `json:"refund_status"`
|
RefundStatus string `json:"refund_status"`
|
||||||
SettlementStatus string `json:"settlement_status"`
|
SettlementStatus string `json:"settlement_status"`
|
||||||
DistributionMode string `json:"distribution_mode"`
|
DistributionMode string `json:"distribution_mode"`
|
||||||
GrossPaidAmountCent int64 `json:"gross_paid_amount_cent"`
|
GrossPaidAmountCent int64 `json:"gross_paid_amount_cent"`
|
||||||
RefundAmountCent int64 `json:"refund_amount_cent"`
|
RefundAmountCent int64 `json:"refund_amount_cent"`
|
||||||
NetPaidAmountCent int64 `json:"net_paid_amount_cent"`
|
NetPaidAmountCent int64 `json:"net_paid_amount_cent"`
|
||||||
PaymentFeeCent int64 `json:"payment_fee_cent"`
|
PaymentFeeCent int64 `json:"payment_fee_cent"`
|
||||||
ServiceFeeCent int64 `json:"service_fee_cent"`
|
ServiceFeeCent int64 `json:"service_fee_cent"`
|
||||||
MarkupAmountCent int64 `json:"markup_amount_cent"`
|
MarkupAmountCent int64 `json:"markup_amount_cent"`
|
||||||
TaxAmountCent int64 `json:"tax_amount_cent"`
|
TaxAmountCent int64 `json:"tax_amount_cent"`
|
||||||
SplitBaseAmountCent int64 `json:"split_base_amount_cent"`
|
SplitBaseAmountCent int64 `json:"split_base_amount_cent"`
|
||||||
RoundingAdjustmentCent int64 `json:"rounding_adjustment_cent"`
|
RoundingAdjustmentCent int64 `json:"rounding_adjustment_cent"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
|
|
||||||
// 关联业务与分销商收益透传字段
|
// 关联业务与分销商收益透传字段
|
||||||
ListingNo string `json:"listing_no,omitempty"`
|
ListingNo string `json:"listing_no,omitempty"`
|
||||||
Title string `json:"title,omitempty"`
|
Title string `json:"title,omitempty"`
|
||||||
GameName string `json:"game_name,omitempty"`
|
GameName string `json:"game_name,omitempty"`
|
||||||
ServerRegion string `json:"server_region,omitempty"`
|
ServerRegion string `json:"server_region,omitempty"`
|
||||||
LoginPlatform string `json:"login_platform,omitempty"`
|
LoginPlatform string `json:"login_platform,omitempty"`
|
||||||
RentDurationHours int `json:"rent_duration_hours,omitempty"`
|
RentDurationHours int `json:"rent_duration_hours,omitempty"`
|
||||||
RentedAt *time.Time `json:"rented_at,omitempty"`
|
RentedAt *time.Time `json:"rented_at,omitempty"`
|
||||||
RenterPhone string `json:"renter_phone,omitempty"`
|
RenterPhone string `json:"renter_phone,omitempty"`
|
||||||
RenterNickname string `json:"renter_nickname,omitempty"`
|
RenterNickname string `json:"renter_nickname,omitempty"`
|
||||||
OwnerRentAmountCent int64 `json:"owner_rent_amount_cent,omitempty"`
|
OwnerRentAmountCent int64 `json:"owner_rent_amount_cent,omitempty"`
|
||||||
BasePriceCent int64 `json:"base_price_cent,omitempty"`
|
BasePriceCent int64 `json:"base_price_cent,omitempty"`
|
||||||
ShelfMarkupCent int64 `json:"shelf_markup_cent,omitempty"`
|
ShelfMarkupCent int64 `json:"shelf_markup_cent,omitempty"`
|
||||||
DepositAmountCent int64 `json:"deposit_amount_cent,omitempty"`
|
DepositAmountCent int64 `json:"deposit_amount_cent,omitempty"`
|
||||||
|
|
||||||
// 当前分销商在该订单中的收益拆解
|
// 当前分销商在该订单中的收益拆解
|
||||||
DistributorEarningCent int64 `json:"distributor_earning_cent"`
|
DistributorEarningCent int64 `json:"distributor_earning_cent"`
|
||||||
DistributorRole string `json:"distributor_role,omitempty"`
|
DistributorRole string `json:"distributor_role,omitempty"`
|
||||||
DistributorMarkupCent int64 `json:"distributor_markup_cent"`
|
DistributorMarkupCent int64 `json:"distributor_markup_cent"`
|
||||||
DistributorSplitCent int64 `json:"distributor_split_cent"`
|
DistributorSplitCent int64 `json:"distributor_split_cent"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type DistributionOrderListQuery struct {
|
type DistributionOrderListQuery struct {
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
@@ -402,7 +403,7 @@ func TestSnapshotPaidOrderTxSplitsPercentOfProfit(t *testing.T) {
|
|||||||
|
|
||||||
func TestApplyRefundTxWithCheckoutAndDeposit(t *testing.T) {
|
func TestApplyRefundTxWithCheckoutAndDeposit(t *testing.T) {
|
||||||
db := distributionTestDB(t)
|
db := distributionTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.OrderCheckout{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.OrderCheckout{}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
now := time.Now()
|
now := time.Now()
|
||||||
@@ -471,4 +472,3 @@ func TestApplyRefundTxWithCheckoutAndDeposit(t *testing.T) {
|
|||||||
t.Fatalf("distributorParty.IncomeAmountCent = %d, want 2420", distributorParty.IncomeAmountCent)
|
t.Fatalf("distributorParty.IncomeAmountCent = %d, want 2420", distributorParty.IncomeAmountCent)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -145,6 +145,17 @@ func (r *Repository) ScopeSiteID(ctx context.Context, adminID, requested uint64)
|
|||||||
|
|
||||||
// ensureSiteAccess 校验管理员可访问指定站点。
|
// ensureSiteAccess 校验管理员可访问指定站点。
|
||||||
// 仅超级管理员或持有 distribution:all_view 的账号可跨站;无成员记录不再视为超管。
|
// 仅超级管理员或持有 distribution:all_view 的账号可跨站;无成员记录不再视为超管。
|
||||||
|
// adminRef 把 adminID=0(代表系统自动操作)映射为 NULL。
|
||||||
|
//
|
||||||
|
// 分销规则与结算批次的 created_by 都带指向 admin_users 的外键,
|
||||||
|
// 直接写 0 会因找不到对应管理员而违反外键约束;NULL 才是"无具体操作人"的正确表示。
|
||||||
|
func adminRef(adminID uint64) *uint64 {
|
||||||
|
if adminID == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return &adminID
|
||||||
|
}
|
||||||
|
|
||||||
func (r *Repository) ensureSiteAccess(ctx context.Context, adminID, siteID uint64) error {
|
func (r *Repository) ensureSiteAccess(ctx context.Context, adminID, siteID uint64) error {
|
||||||
return r.ensureSiteAccessWithDB(ctx, r.db, adminID, siteID)
|
return r.ensureSiteAccessWithDB(ctx, r.db, adminID, siteID)
|
||||||
}
|
}
|
||||||
@@ -345,7 +356,7 @@ func (r *Repository) CreateRule(ctx context.Context, adminID uint64, req CreateR
|
|||||||
DistributorARatio: parsed.DistributorARatio, DistributorBRatio: parsed.DistributorBRatio,
|
DistributorARatio: parsed.DistributorARatio, DistributorBRatio: parsed.DistributorBRatio,
|
||||||
ServiceFeeValue: parsed.ServiceFeeValue, ServiceFeeUnit: parsed.ServiceFeeUnit,
|
ServiceFeeValue: parsed.ServiceFeeValue, ServiceFeeUnit: parsed.ServiceFeeUnit,
|
||||||
PaymentFeeBPS: req.PaymentFeeBPS, TaxEnabled: req.TaxEnabled, TaxRateBPS: req.TaxRateBPS,
|
PaymentFeeBPS: req.PaymentFeeBPS, TaxEnabled: req.TaxEnabled, TaxRateBPS: req.TaxRateBPS,
|
||||||
EffectiveFrom: effectiveFrom, CreatedBy: &adminID,
|
EffectiveFrom: effectiveFrom, CreatedBy: adminRef(adminID),
|
||||||
}
|
}
|
||||||
if row.PaymentFeeBPS == 0 {
|
if row.PaymentFeeBPS == 0 {
|
||||||
row.PaymentFeeBPS = 50
|
row.PaymentFeeBPS = 50
|
||||||
@@ -911,7 +922,7 @@ func (r *Repository) CreateSettlementBatch(ctx context.Context, adminID uint64,
|
|||||||
}
|
}
|
||||||
var batch model.DistributionSettlementBatch
|
var batch model.DistributionSettlementBatch
|
||||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||||
batch = model.DistributionSettlementBatch{SiteID: req.SiteID, BatchNo: "DS" + time.Now().Format("20060102150405.000000000"), PeriodStart: req.PeriodStart, PeriodEnd: req.PeriodEnd, Status: "draft", CreatedBy: &adminID}
|
batch = model.DistributionSettlementBatch{SiteID: req.SiteID, BatchNo: "DS" + time.Now().Format("20060102150405.000000000"), PeriodStart: req.PeriodStart, PeriodEnd: req.PeriodEnd, Status: "draft", CreatedBy: adminRef(adminID)}
|
||||||
if err := tx.Create(&batch).Error; err != nil {
|
if err := tx.Create(&batch).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
@@ -2114,10 +2125,6 @@ func (r *Repository) GetDashboardAnalytics(ctx context.Context, adminID, siteID
|
|||||||
startDate := time.Now().AddDate(0, 0, -6).Format("2006-01-02")
|
startDate := time.Now().AddDate(0, 0, -6).Format("2006-01-02")
|
||||||
dateFormatExpr := "DATE_FORMAT(ro.created_at, '%Y-%m-%d')"
|
dateFormatExpr := "DATE_FORMAT(ro.created_at, '%Y-%m-%d')"
|
||||||
dateFormatPartyExpr := "DATE_FORMAT(created_at, '%Y-%m-%d')"
|
dateFormatPartyExpr := "DATE_FORMAT(created_at, '%Y-%m-%d')"
|
||||||
if r.db != nil && r.db.Dialector != nil && r.db.Dialector.Name() == "sqlite" {
|
|
||||||
dateFormatExpr = "strftime('%Y-%m-%d', ro.created_at)"
|
|
||||||
dateFormatPartyExpr = "strftime('%Y-%m-%d', created_at)"
|
|
||||||
}
|
|
||||||
selectTrendSQL := fmt.Sprintf("%s AS date_str, COUNT(ro.id) AS orders, COALESCE(SUM(f.gross_paid_amount_cent), 0) AS gmv", dateFormatExpr)
|
selectTrendSQL := fmt.Sprintf("%s AS date_str, COUNT(ro.id) AS orders, COALESCE(SUM(f.gross_paid_amount_cent), 0) AS gmv", dateFormatExpr)
|
||||||
_ = r.db.WithContext(ctx).Table("rental_orders ro").
|
_ = r.db.WithContext(ctx).Table("rental_orders ro").
|
||||||
Joins("JOIN distribution_order_financials f ON f.order_id = ro.id").
|
Joins("JOIN distribution_order_financials f ON f.order_id = ro.id").
|
||||||
|
|||||||
@@ -5,19 +5,16 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
func distributionTestDB(t *testing.T) *gorm.DB {
|
func distributionTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
t.Fatal(err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(
|
|
||||||
&model.AdminUser{}, &model.Role{}, &model.Permission{}, &model.AdminUserRole{}, &model.RolePermission{},
|
&model.AdminUser{}, &model.Role{}, &model.Permission{}, &model.AdminUserRole{}, &model.RolePermission{},
|
||||||
&model.ChatConversation{}, &model.RentalOrder{},
|
&model.ChatConversation{}, &model.RentalOrder{},
|
||||||
&model.AuditLog{}, &model.PaymentMerchantConfig{}, &model.DistributionSite{},
|
&model.AuditLog{}, &model.PaymentMerchantConfig{}, &model.DistributionSite{},
|
||||||
@@ -29,6 +26,16 @@ func distributionTestDB(t *testing.T) *gorm.DB {
|
|||||||
); err != nil {
|
); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
// 000065 迁移为分销表加了指向 admin_users 的外键,
|
||||||
|
// 测试数据引用的管理员必须先落库才能通过约束校验。
|
||||||
|
if err := db.Create(&model.AdminUser{
|
||||||
|
ID: 7,
|
||||||
|
Username: "distribution_test_admin",
|
||||||
|
Nickname: "分销测试管理员",
|
||||||
|
Status: "active",
|
||||||
|
}).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -948,7 +955,24 @@ func TestLiveMoneyMovementFrozenInProduction(t *testing.T) {
|
|||||||
if err := db.Create(&batch).Error; err != nil {
|
if err := db.Create(&batch).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if err := db.Create(&model.DistributionSettlementItem{BatchID: batch.ID, OrderID: 1, PartyID: 1, AmountCent: 100, Status: "pending"}).Error; err != nil {
|
// 结算明细的 order_id / party_id 都带外键,必须先落库对应的订单与参与方。
|
||||||
|
order := model.RentalOrder{
|
||||||
|
OrderNo: "ORD-FROZEN", ListingID: 1, AccountID: 1, OwnerID: 1, RenterID: 1,
|
||||||
|
Status: "completed", SettlementMode: "platform_managed",
|
||||||
|
}
|
||||||
|
if err := db.Create(&order).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
party := model.DistributionOrderParty{
|
||||||
|
OrderID: order.ID, SiteID: site.ID, PartyRole: "distributor_receive",
|
||||||
|
PartyType: "site", PartyID: site.ID, IncomeAmountCent: 100,
|
||||||
|
}
|
||||||
|
if err := db.Create(&party).Error; err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := db.Create(&model.DistributionSettlementItem{
|
||||||
|
BatchID: batch.ID, OrderID: order.ID, PartyID: party.ID, AmountCent: 100, Status: "pending",
|
||||||
|
}).Error; err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
if _, err := repo.MarkSettlementBatch(t.Context(), 0, batch.ID); err != ErrLiveMoneyMovementFrozen {
|
if _, err := repo.MarkSettlementBatch(t.Context(), 0, batch.ID); err != ErrLiveMoneyMovementFrozen {
|
||||||
|
|||||||
@@ -304,6 +304,3 @@ func (s *Service) GetDashboardAnalytics(ctx context.Context, adminID, siteID uin
|
|||||||
}
|
}
|
||||||
return s.repo.GetDashboardAnalytics(ctx, adminID, siteID)
|
return s.repo.GetDashboardAnalytics(ctx, adminID, siteID)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -4,8 +4,7 @@ import (
|
|||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
"hfb_sys/backend/internal/database"
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestFilterAdminListingsByAssetLevels(t *testing.T) {
|
func TestFilterAdminListingsByAssetLevels(t *testing.T) {
|
||||||
@@ -100,10 +99,7 @@ func TestFilterAdminListingsBySkinGroupOnly(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
db := database.NewDryRunDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
repo := &Repository{}
|
repo := &Repository{}
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
@@ -143,4 +139,3 @@ func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -128,34 +128,34 @@ type AdminListResult struct {
|
|||||||
}
|
}
|
||||||
|
|
||||||
type PublicListQuery struct {
|
type PublicListQuery struct {
|
||||||
Page int
|
Page int
|
||||||
PageSize int
|
PageSize int
|
||||||
Keyword string
|
Keyword string
|
||||||
Sort string
|
Sort string
|
||||||
Zone string
|
Zone string
|
||||||
Server []string
|
Server []string
|
||||||
Region []string
|
Region []string
|
||||||
LoginMethod []string
|
LoginMethod []string
|
||||||
Rank []string
|
Rank []string
|
||||||
Insurance []string
|
Insurance []string
|
||||||
Stamina []string
|
Stamina []string
|
||||||
Load []string
|
Load []string
|
||||||
SkinGroup []string
|
SkinGroup []string
|
||||||
SkinName []string
|
SkinName []string
|
||||||
MinCoin *float64
|
MinCoin *float64
|
||||||
MaxCoin *float64
|
MaxCoin *float64
|
||||||
MinRatio *float64
|
MinRatio *float64
|
||||||
MaxRatio *float64
|
MaxRatio *float64
|
||||||
MinPrice *float64
|
MinPrice *float64
|
||||||
MaxPrice *float64
|
MaxPrice *float64
|
||||||
MinDeposit *float64
|
MinDeposit *float64
|
||||||
MaxDeposit *float64
|
MaxDeposit *float64
|
||||||
MinTotal *float64
|
MinTotal *float64
|
||||||
MaxTotal *float64
|
MaxTotal *float64
|
||||||
MinFireLevel *float64
|
MinFireLevel *float64
|
||||||
MaxFireLevel *float64
|
MaxFireLevel *float64
|
||||||
MinDailyLoss *float64
|
MinDailyLoss *float64
|
||||||
MaxDailyLoss *float64
|
MaxDailyLoss *float64
|
||||||
MinSecretKD *float64
|
MinSecretKD *float64
|
||||||
MaxSecretKD *float64
|
MaxSecretKD *float64
|
||||||
ResourceRanges map[string]NumberRange
|
ResourceRanges map[string]NumberRange
|
||||||
|
|||||||
@@ -209,7 +209,7 @@ func newExternalAdjustmentFixture(
|
|||||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||||
t.Fatalf("初始化商品测试表失败: %v", err)
|
t.Fatalf("初始化商品测试表失败: %v", err)
|
||||||
}
|
}
|
||||||
if err := db.AutoMigrate(&model.ListingUpload{}, &model.AuditLog{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.ListingUpload{}, &model.AuditLog{}); err != nil {
|
||||||
t.Fatalf("初始化外部商品测试表失败: %v", err)
|
t.Fatalf("初始化外部商品测试表失败: %v", err)
|
||||||
}
|
}
|
||||||
user := model.User{Phone: "18800000009", Nickname: "测试号主", RealnameStatus: "verified", Status: "active"}
|
user := model.User{Phone: "18800000009", Nickname: "测试号主", RealnameStatus: "verified", Status: "active"}
|
||||||
|
|||||||
@@ -205,4 +205,3 @@ func (h *Handler) UpdateScreenshots(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
response.OK(c, item)
|
response.OK(c, item)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -15,21 +15,21 @@ import (
|
|||||||
|
|
||||||
type listingRow struct {
|
type listingRow struct {
|
||||||
model.RentalListing
|
model.RentalListing
|
||||||
Title string
|
Title string
|
||||||
OwnerPhone string
|
OwnerPhone string
|
||||||
OwnerNickname string
|
OwnerNickname string
|
||||||
DisplaySourceChannel string `gorm:"column:display_source_channel"`
|
DisplaySourceChannel string `gorm:"column:display_source_channel"`
|
||||||
IsExternalUpload bool `gorm:"column:is_external_upload"`
|
IsExternalUpload bool `gorm:"column:is_external_upload"`
|
||||||
DistributionSiteCode string `gorm:"column:distribution_site_code"`
|
DistributionSiteCode string `gorm:"column:distribution_site_code"`
|
||||||
DistributionSiteName string `gorm:"column:distribution_site_name"`
|
DistributionSiteName string `gorm:"column:distribution_site_name"`
|
||||||
Description string
|
Description string
|
||||||
GameName string
|
GameName string
|
||||||
ServerRegion string
|
ServerRegion string
|
||||||
LoginPlatform string
|
LoginPlatform string
|
||||||
RankLevel string
|
RankLevel string
|
||||||
HafCoinAmount int64
|
HafCoinAmount int64
|
||||||
AssetSummary datatypes.JSON `gorm:"column:asset_summary"`
|
AssetSummary datatypes.JSON `gorm:"column:asset_summary"`
|
||||||
ScreenshotURLS datatypes.JSON `gorm:"column:screenshot_urls"`
|
ScreenshotURLS datatypes.JSON `gorm:"column:screenshot_urls"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func rowsToDTO(rows []listingRow) []ListingDTO {
|
func rowsToDTO(rows []listingRow) []ListingDTO {
|
||||||
@@ -165,32 +165,32 @@ func (row listingRow) toDTO() ListingDTO {
|
|||||||
screenshotURLS := cleanScreenshotURLs(decodeScreenshots(row.ScreenshotURLS))
|
screenshotURLS := cleanScreenshotURLs(decodeScreenshots(row.ScreenshotURLS))
|
||||||
reviewStatus, reviewReason := normalizedReviewState(row.Status, row.ReviewStatus, row.ReviewReason)
|
reviewStatus, reviewReason := normalizedReviewState(row.Status, row.ReviewStatus, row.ReviewReason)
|
||||||
return ListingDTO{
|
return ListingDTO{
|
||||||
ID: row.ID,
|
ID: row.ID,
|
||||||
ListingNo: row.ListingNo,
|
ListingNo: row.ListingNo,
|
||||||
AccountID: row.AccountID,
|
AccountID: row.AccountID,
|
||||||
OwnerID: row.OwnerID,
|
OwnerID: row.OwnerID,
|
||||||
OwnerPhone: row.OwnerPhone,
|
OwnerPhone: row.OwnerPhone,
|
||||||
OwnerNickname: row.OwnerNickname,
|
OwnerNickname: row.OwnerNickname,
|
||||||
SourceChannel: row.DisplaySourceChannel,
|
SourceChannel: row.DisplaySourceChannel,
|
||||||
IsExternalUpload: row.IsExternalUpload,
|
IsExternalUpload: row.IsExternalUpload,
|
||||||
Title: row.Title,
|
Title: row.Title,
|
||||||
Description: row.Description,
|
Description: row.Description,
|
||||||
GameName: row.GameName,
|
GameName: row.GameName,
|
||||||
ServerRegion: row.ServerRegion,
|
ServerRegion: row.ServerRegion,
|
||||||
LoginPlatform: row.LoginPlatform,
|
LoginPlatform: row.LoginPlatform,
|
||||||
RankLevel: row.RankLevel,
|
RankLevel: row.RankLevel,
|
||||||
HafCoinAmount: row.HafCoinAmount,
|
HafCoinAmount: row.HafCoinAmount,
|
||||||
AssetSummary: assetSummary,
|
AssetSummary: assetSummary,
|
||||||
ScreenshotURLS: screenshotURLS,
|
ScreenshotURLS: screenshotURLS,
|
||||||
CoverURL: publicCoverURL(row.ID, screenshotURLS, row.Status, row.ReviewStatus),
|
CoverURL: publicCoverURL(row.ID, screenshotURLS, row.Status, row.ReviewStatus),
|
||||||
PriceCent: row.PriceCent,
|
PriceCent: row.PriceCent,
|
||||||
DepositAmountCent: row.DepositAmountCent,
|
DepositAmountCent: row.DepositAmountCent,
|
||||||
IsAccelerated: isAcceleratedSale(assetSummary),
|
IsAccelerated: isAcceleratedSale(assetSummary),
|
||||||
InTransaction: row.InTransaction,
|
InTransaction: row.InTransaction,
|
||||||
Status: row.Status,
|
Status: row.Status,
|
||||||
ReviewStatus: reviewStatus,
|
ReviewStatus: reviewStatus,
|
||||||
HandoffMode: row.HandoffMode,
|
HandoffMode: row.HandoffMode,
|
||||||
SettlementMode: row.SettlementMode,
|
SettlementMode: row.SettlementMode,
|
||||||
ManagedAdminID: row.ManagedAdminID,
|
ManagedAdminID: row.ManagedAdminID,
|
||||||
DistributionSiteID: row.DistributionSiteID,
|
DistributionSiteID: row.DistributionSiteID,
|
||||||
DistributionSiteCode: row.DistributionSiteCode,
|
DistributionSiteCode: row.DistributionSiteCode,
|
||||||
|
|||||||
@@ -299,4 +299,3 @@ func isAllDigits(s string) bool {
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -434,4 +434,3 @@ func (r *Repository) UpdateScreenshots(ctx context.Context, adminID uint64, list
|
|||||||
})
|
})
|
||||||
return dto, err
|
return dto, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -91,4 +91,3 @@ func (s *Service) UpdateScreenshots(ctx context.Context, adminID uint64, id uint
|
|||||||
}
|
}
|
||||||
return s.repo.UpdateScreenshots(ctx, adminID, id, req, meta)
|
return s.repo.UpdateScreenshots(ctx, adminID, id, req, meta)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -384,7 +384,7 @@ func TestImportExternalUploadStoresSourceChannel(t *testing.T) {
|
|||||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||||
t.Fatalf("failed to migrate test db: %v", err)
|
t.Fatalf("failed to migrate test db: %v", err)
|
||||||
}
|
}
|
||||||
if err := db.AutoMigrate(&model.AdminUser{}, &model.ListingUpload{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.AdminUser{}, &model.ListingUpload{}); err != nil {
|
||||||
t.Fatalf("failed to migrate upload tables: %v", err)
|
t.Fatalf("failed to migrate upload tables: %v", err)
|
||||||
}
|
}
|
||||||
admin := model.AdminUser{
|
admin := model.AdminUser{
|
||||||
@@ -424,7 +424,7 @@ func TestListPendingReviewIncludesSourceChannel(t *testing.T) {
|
|||||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||||
t.Fatalf("failed to migrate test db: %v", err)
|
t.Fatalf("failed to migrate test db: %v", err)
|
||||||
}
|
}
|
||||||
if err := db.AutoMigrate(&model.ListingUpload{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.ListingUpload{}); err != nil {
|
||||||
t.Fatalf("failed to migrate listing uploads: %v", err)
|
t.Fatalf("failed to migrate listing uploads: %v", err)
|
||||||
}
|
}
|
||||||
user := model.User{Phone: "18800000001", RealnameStatus: "verified", Status: "active"}
|
user := model.User{Phone: "18800000001", RealnameStatus: "verified", Status: "active"}
|
||||||
@@ -682,7 +682,7 @@ func TestListPublicWithDistributionSiteCode(t *testing.T) {
|
|||||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||||
t.Fatalf("migrate err: %v", err)
|
t.Fatalf("migrate err: %v", err)
|
||||||
}
|
}
|
||||||
if err := db.AutoMigrate(&model.DistributionSite{}, &model.DistributionSiteAccount{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.DistributionSite{}, &model.DistributionSiteAccount{}); err != nil {
|
||||||
t.Fatalf("migrate distribution err: %v", err)
|
t.Fatalf("migrate distribution err: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -774,7 +774,7 @@ func TestUpdateScreenshots(t *testing.T) {
|
|||||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||||
t.Fatalf("failed to migrate test db: %v", err)
|
t.Fatalf("failed to migrate test db: %v", err)
|
||||||
}
|
}
|
||||||
if err := db.AutoMigrate(&model.AuditLog{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.AuditLog{}); err != nil {
|
||||||
t.Fatalf("failed to migrate audit log: %v", err)
|
t.Fatalf("failed to migrate audit log: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db, nil)
|
repo := NewRepository(db, nil)
|
||||||
|
|||||||
@@ -3,11 +3,11 @@ package notification
|
|||||||
import "time"
|
import "time"
|
||||||
|
|
||||||
type NotificationDTO struct {
|
type NotificationDTO struct {
|
||||||
ID uint64 `json:"id"`
|
ID uint64 `json:"id"`
|
||||||
UserID uint64 `json:"user_id"`
|
UserID uint64 `json:"user_id"`
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Title string `json:"title"`
|
Title string `json:"title"`
|
||||||
Content string `json:"content"`
|
Content string `json:"content"`
|
||||||
BizType string `json:"biz_type"`
|
BizType string `json:"biz_type"`
|
||||||
BizID *uint64 `json:"biz_id"`
|
BizID *uint64 `json:"biz_id"`
|
||||||
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
|
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
|
||||||
|
|||||||
@@ -206,4 +206,3 @@ func toDTO(row model.Notification) NotificationDTO {
|
|||||||
CreatedAt: row.CreatedAt,
|
CreatedAt: row.CreatedAt,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ import (
|
|||||||
|
|
||||||
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.Notification{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.Notification{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -53,7 +53,7 @@ func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
|||||||
|
|
||||||
func TestRepositoryMarkReadNotFound(t *testing.T) {
|
func TestRepositoryMarkReadNotFound(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.Notification{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.Notification{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -66,7 +66,7 @@ func TestRepositoryMarkReadNotFound(t *testing.T) {
|
|||||||
|
|
||||||
func TestNotificationTenantIsolation(t *testing.T) {
|
func TestNotificationTenantIsolation(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.Notification{}, &model.DistributionSite{}, &model.RentalOrder{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.Notification{}, &model.DistributionSite{}, &model.RentalOrder{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
|
|||||||
@@ -279,7 +279,7 @@ func TestRepositoryCreateAppliesRenterGrowthDiscount(t *testing.T) {
|
|||||||
|
|
||||||
func TestCreateOrderSnapshotsShelfMarkup(t *testing.T) {
|
func TestCreateOrderSnapshotsShelfMarkup(t *testing.T) {
|
||||||
db := setupOrderTestDB(t)
|
db := setupOrderTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.DistributionSite{}, &model.DistributionSiteAccount{}, &model.DistributionRuleVersion{}, &model.DistributionOrderFinancial{}, &model.DistributionOrderParty{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.DistributionSite{}, &model.DistributionSiteAccount{}, &model.DistributionRuleVersion{}, &model.DistributionOrderFinancial{}, &model.DistributionOrderParty{}); err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -859,7 +859,7 @@ func TestCancelPendingHandoffKeepsAssetsUntilRefundApproved(t *testing.T) {
|
|||||||
t.Fatalf("create account failed: %v", err)
|
t.Fatalf("create account failed: %v", err)
|
||||||
}
|
}
|
||||||
listing := model.RentalListing{
|
listing := model.RentalListing{
|
||||||
ListingNo: "LST-REFUND-REVIEW-001",
|
ListingNo: "LST-REFUND-REV-001",
|
||||||
OwnerID: owner.ID,
|
OwnerID: owner.ID,
|
||||||
AccountID: account.ID,
|
AccountID: account.ID,
|
||||||
Status: listingStatusRented,
|
Status: listingStatusRented,
|
||||||
@@ -1319,7 +1319,7 @@ func TestAdminResetRenterConfirmTimeoutRefreshesStageTime(t *testing.T) {
|
|||||||
|
|
||||||
func TestAdminForceHandoffStartsNormalOwnerOrder(t *testing.T) {
|
func TestAdminForceHandoffStartsNormalOwnerOrder(t *testing.T) {
|
||||||
db := setupOrderTestDB(t)
|
db := setupOrderTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.Dispute{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.Dispute{}); err != nil {
|
||||||
t.Fatalf("migrate disputes failed: %v", err)
|
t.Fatalf("migrate disputes failed: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -1387,7 +1387,7 @@ func TestAdminForceHandoffStartsNormalOwnerOrder(t *testing.T) {
|
|||||||
|
|
||||||
func TestAdminForceHandoffAbnormalOwnerTimeout(t *testing.T) {
|
func TestAdminForceHandoffAbnormalOwnerTimeout(t *testing.T) {
|
||||||
db := setupOrderTestDB(t)
|
db := setupOrderTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.Dispute{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.Dispute{}); err != nil {
|
||||||
t.Fatalf("migrate disputes failed: %v", err)
|
t.Fatalf("migrate disputes failed: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -1460,26 +1460,26 @@ func TestOwnerConfirmCheckoutAfterTimeout(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
listing := model.RentalListing{
|
listing := model.RentalListing{
|
||||||
OwnerID: owner.ID,
|
OwnerID: owner.ID,
|
||||||
AccountID: account.ID,
|
AccountID: account.ID,
|
||||||
Status: listingStatusRented,
|
Status: listingStatusRented,
|
||||||
ReviewStatus: listingReviewStatusApproved,
|
ReviewStatus: listingReviewStatusApproved,
|
||||||
PriceCent: 1000,
|
PriceCent: 1000,
|
||||||
}
|
}
|
||||||
if err := db.Create(&listing).Error; err != nil {
|
if err := db.Create(&listing).Error; err != nil {
|
||||||
t.Fatalf("create listing failed: %v", err)
|
t.Fatalf("create listing failed: %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
order := model.RentalOrder{
|
order := model.RentalOrder{
|
||||||
OrderNo: "ORD-CHECKOUT-TIMEOUT-001",
|
OrderNo: "ORD-CHECKOUT-TIMEOUT-001",
|
||||||
ListingID: listing.ID,
|
ListingID: listing.ID,
|
||||||
AccountID: account.ID,
|
AccountID: account.ID,
|
||||||
OwnerID: owner.ID,
|
OwnerID: owner.ID,
|
||||||
RenterID: renter.ID,
|
RenterID: renter.ID,
|
||||||
Status: orderStatusAbnormal,
|
Status: orderStatusAbnormal,
|
||||||
HandoffStatus: handoffStatusOwnerCheckoutConfirmTimeout,
|
HandoffStatus: handoffStatusOwnerCheckoutConfirmTimeout,
|
||||||
SettlementStatus: settlementStatusPending,
|
SettlementStatus: settlementStatusPending,
|
||||||
RentAmountCent: 1000,
|
RentAmountCent: 1000,
|
||||||
DepositAmountCent: 0,
|
DepositAmountCent: 0,
|
||||||
}
|
}
|
||||||
if err := db.Create(&order).Error; err != nil {
|
if err := db.Create(&order).Error; err != nil {
|
||||||
@@ -1526,7 +1526,7 @@ func TestOwnerConfirmCheckoutAfterTimeout(t *testing.T) {
|
|||||||
|
|
||||||
func TestAdminForceHandoffUsesExistingOwnerRecordAndRejectsPlatformOrderBeforeHandoff(t *testing.T) {
|
func TestAdminForceHandoffUsesExistingOwnerRecordAndRejectsPlatformOrderBeforeHandoff(t *testing.T) {
|
||||||
db := setupOrderTestDB(t)
|
db := setupOrderTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.Dispute{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.Dispute{}); err != nil {
|
||||||
t.Fatalf("migrate disputes failed: %v", err)
|
t.Fatalf("migrate disputes failed: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -1607,7 +1607,7 @@ func TestAdminForceHandoffUsesExistingOwnerRecordAndRejectsPlatformOrderBeforeHa
|
|||||||
|
|
||||||
func TestAdminForceHandoffStartsPlatformManagedOrderAfterPlatformHandoff(t *testing.T) {
|
func TestAdminForceHandoffStartsPlatformManagedOrderAfterPlatformHandoff(t *testing.T) {
|
||||||
db := setupOrderTestDB(t)
|
db := setupOrderTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.Dispute{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.Dispute{}); err != nil {
|
||||||
t.Fatalf("migrate disputes failed: %v", err)
|
t.Fatalf("migrate disputes failed: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -2017,7 +2017,7 @@ func TestPlatformManagedCheckoutIncludesConsumableAndDepositCompensation(t *test
|
|||||||
|
|
||||||
func TestAdminPlatformCheckoutDisputeCreatesArbitrationCase(t *testing.T) {
|
func TestAdminPlatformCheckoutDisputeCreatesArbitrationCase(t *testing.T) {
|
||||||
db := setupOrderTestDB(t)
|
db := setupOrderTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.Dispute{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.Dispute{}); err != nil {
|
||||||
t.Fatalf("migrate dispute failed: %v", err)
|
t.Fatalf("migrate dispute failed: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
@@ -2217,7 +2217,7 @@ func TestAdminPlatformCheckoutConfirmRequiresExplicitConfirmationForZeroOwnerInc
|
|||||||
|
|
||||||
func TestListForUserAndFindForUserSiteIsolation(t *testing.T) {
|
func TestListForUserAndFindForUserSiteIsolation(t *testing.T) {
|
||||||
db := setupOrderTestDB(t)
|
db := setupOrderTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.DistributionSite{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.DistributionSite{}); err != nil {
|
||||||
t.Fatalf("migrate distribution_sites err: %v", err)
|
t.Fatalf("migrate distribution_sites err: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db)
|
repo := NewRepository(db)
|
||||||
|
|||||||
@@ -5,13 +5,12 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||||
"hfb_sys/backend/internal/timeutil"
|
"hfb_sys/backend/internal/timeutil"
|
||||||
|
|
||||||
"gorm.io/datatypes"
|
"gorm.io/datatypes"
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func pureCoinDiscountOrder() model.RentalOrder {
|
func pureCoinDiscountOrder() model.RentalOrder {
|
||||||
@@ -504,10 +503,7 @@ func TestNewOrderNoUsesShanghaiTimeWhenLocalIsUTC(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyAdminOrderFiltersSmartRouting(t *testing.T) {
|
func TestApplyAdminOrderFiltersSmartRouting(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
db := database.NewDryRunDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
|
|||||||
@@ -519,7 +519,7 @@ func TestStartRefundDoesNotCreateNewOrderWhenFailedRefundExists(t *testing.T) {
|
|||||||
|
|
||||||
func TestStartMohongRefundDefaultsFullAmountForCancelledPaidOrder(t *testing.T) {
|
func TestStartMohongRefundDefaultsFullAmountForCancelledPaidOrder(t *testing.T) {
|
||||||
db := setupPaymentTestDB(t)
|
db := setupPaymentTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.MohongOrder{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.MohongOrder{}); err != nil {
|
||||||
t.Fatalf("migrate mohong order failed: %v", err)
|
t.Fatalf("migrate mohong order failed: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db, nil, nil)
|
repo := NewRepository(db, nil, nil)
|
||||||
@@ -576,7 +576,7 @@ func TestStartMohongRefundDefaultsFullAmountForCancelledPaidOrder(t *testing.T)
|
|||||||
|
|
||||||
func TestStartMohongRefundRequiresCancelledOrder(t *testing.T) {
|
func TestStartMohongRefundRequiresCancelledOrder(t *testing.T) {
|
||||||
db := setupPaymentTestDB(t)
|
db := setupPaymentTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.MohongOrder{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.MohongOrder{}); err != nil {
|
||||||
t.Fatalf("migrate mohong order failed: %v", err)
|
t.Fatalf("migrate mohong order failed: %v", err)
|
||||||
}
|
}
|
||||||
repo := NewRepository(db, nil, nil)
|
repo := NewRepository(db, nil, nil)
|
||||||
@@ -697,18 +697,18 @@ func TestConfirmPaidRollsBackOrderWhenPaymentUpdateFails(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestConcurrentPaidNotificationsAreIdempotent(t *testing.T) {
|
func TestConcurrentPaidNotificationsAreIdempotent(t *testing.T) {
|
||||||
db := database.NewTestDBWithName("payment-concurrent")
|
db := database.NewTestDB()
|
||||||
if err := database.MigrateRentalTransactionTestSchema(db); err != nil {
|
if err := database.MigrateRentalTransactionTestSchema(db); err != nil {
|
||||||
t.Fatalf("数据库迁移失败: %v", err)
|
t.Fatalf("数据库迁移失败: %v", err)
|
||||||
}
|
}
|
||||||
sqlDB, err := db.DB()
|
sqlDB, err := db.DB()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("get sqlite db: %v", err)
|
t.Fatalf("获取底层连接失败: %v", err)
|
||||||
}
|
}
|
||||||
sqlDB.SetMaxOpenConns(8)
|
sqlDB.SetMaxOpenConns(8)
|
||||||
orderRepo := ordermodule.NewRepository(db)
|
orderRepo := ordermodule.NewRepository(db)
|
||||||
repo := NewRepository(db, nil, orderRepo)
|
repo := NewRepository(db, nil, orderRepo)
|
||||||
fixture := createPayableOrderFixture(t, db, "CONCURRENT", true)
|
fixture := createPayableOrderFixture(t, db, "CONC", true)
|
||||||
params := map[string]string{
|
params := map[string]string{
|
||||||
"third_order_id": fixture.Payment.ThirdOrderID,
|
"third_order_id": fixture.Payment.ThirdOrderID,
|
||||||
"status": "paid",
|
"status": "paid",
|
||||||
|
|||||||
@@ -9,7 +9,7 @@ type PaymentAccountDTO struct {
|
|||||||
UserID uint64 `json:"user_id"`
|
UserID uint64 `json:"user_id"`
|
||||||
AccountType string `json:"account_type"`
|
AccountType string `json:"account_type"`
|
||||||
AccountName string `json:"account_name"`
|
AccountName string `json:"account_name"`
|
||||||
AccountNo string `json:"account_no"` // 脱敏显示
|
AccountNo string `json:"account_no"` // 脱敏显示
|
||||||
BankName string `json:"bank_name"`
|
BankName string `json:"bank_name"`
|
||||||
BankBranch string `json:"bank_branch"`
|
BankBranch string `json:"bank_branch"`
|
||||||
CertificateURLs []string `json:"certificate_urls"`
|
CertificateURLs []string `json:"certificate_urls"`
|
||||||
|
|||||||
@@ -5,11 +5,8 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestPrivateCertificateURLsConvertsLegacyPublicURL(t *testing.T) {
|
func TestPrivateCertificateURLsConvertsLegacyPublicURL(t *testing.T) {
|
||||||
@@ -26,11 +23,8 @@ func TestPrivateCertificateURLsConvertsLegacyPublicURL(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestValidateCertificateURLsRequiresUploaderOwnership(t *testing.T) {
|
func TestValidateCertificateURLsRequiresUploaderOwnership(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.FileUploadOwner{}); err != nil {
|
||||||
t.Fatalf("open sqlite error = %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&model.FileUploadOwner{}); err != nil {
|
|
||||||
t.Fatalf("migrate upload owners error = %v", err)
|
t.Fatalf("migrate upload owners error = %v", err)
|
||||||
}
|
}
|
||||||
if err := db.Create(&model.FileUploadOwner{UserID: 1, ObjectKey: "payment-cert/owned.jpg"}).Error; err != nil {
|
if err := db.Create(&model.FileUploadOwner{UserID: 1, ObjectKey: "payment-cert/owned.jpg"}).Error; err != nil {
|
||||||
|
|||||||
@@ -186,7 +186,7 @@ func (nt nullableTime) Value() (driver.Value, error) {
|
|||||||
return *nt.Time, nil
|
return *nt.Time, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Scan 兼容 MySQL 的 time.Time 和 SQLite 聚合函数返回的字符串时间。
|
// Scan 兼容 MySQL 聚合函数可能返回的 time.Time 与字符串时间。
|
||||||
func (nt *nullableTime) Scan(value any) error {
|
func (nt *nullableTime) Scan(value any) error {
|
||||||
switch v := value.(type) {
|
switch v := value.(type) {
|
||||||
case nil:
|
case nil:
|
||||||
|
|||||||
@@ -4,11 +4,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestImportCreateRequestKeepsOneActiveConfigPerPayWay(t *testing.T) {
|
func TestImportCreateRequestKeepsOneActiveConfigPerPayWay(t *testing.T) {
|
||||||
@@ -72,11 +69,8 @@ func TestValidateCreateRequestRequiresShunchengSecretID(t *testing.T) {
|
|||||||
|
|
||||||
// TestListUsesSuccessfulPaymentStats 验证配置页只统计成功支付,不把打开二维码或取消订单算作成交。
|
// TestListUsesSuccessfulPaymentStats 验证配置页只统计成功支付,不把打开二维码或取消订单算作成交。
|
||||||
func TestListUsesSuccessfulPaymentStats(t *testing.T) {
|
func TestListUsesSuccessfulPaymentStats(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.PaymentMerchantConfig{}, &model.PaymentOrder{}); err != nil {
|
||||||
t.Fatalf("open db failed: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&model.PaymentMerchantConfig{}, &model.PaymentOrder{}); err != nil {
|
|
||||||
t.Fatalf("migrate failed: %v", err)
|
t.Fatalf("migrate failed: %v", err)
|
||||||
}
|
}
|
||||||
config := model.PaymentMerchantConfig{
|
config := model.PaymentMerchantConfig{
|
||||||
|
|||||||
@@ -1349,4 +1349,3 @@ func isAllDigits(s string) bool {
|
|||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -7,12 +7,11 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/auditlog"
|
"hfb_sys/backend/internal/auditlog"
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/datatypes"
|
"gorm.io/datatypes"
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestBuildPickupPriceSnapshotSplitsOwnerPrice(t *testing.T) {
|
func TestBuildPickupPriceSnapshotSplitsOwnerPrice(t *testing.T) {
|
||||||
@@ -341,7 +340,7 @@ func TestRepositoryCreateSnapshotsExternalAccountSource(t *testing.T) {
|
|||||||
|
|
||||||
func TestRepositoryCompleteInternalPickupCreditsWallet(t *testing.T) {
|
func TestRepositoryCompleteInternalPickupCreditsWallet(t *testing.T) {
|
||||||
repo, db := newPickupTestRepo(t)
|
repo, db := newPickupTestRepo(t)
|
||||||
listing := seedAvailableListing(t, db, "LST-COMPLETE-INTERNAL", "站内结算账号", false)
|
listing := seedAvailableListing(t, db, "LST-CMPL-INTERNAL", "站内结算账号", false)
|
||||||
pickup, err := repo.Create(t.Context(), CreateRequest{ListingID: listing.ID}, 99, auditlog.Meta{})
|
pickup, err := repo.Create(t.Context(), CreateRequest{ListingID: listing.ID}, 99, auditlog.Meta{})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatalf("Create() error = %v", err)
|
t.Fatalf("Create() error = %v", err)
|
||||||
@@ -367,7 +366,7 @@ func TestRepositoryCompleteInternalPickupCreditsWallet(t *testing.T) {
|
|||||||
|
|
||||||
func TestRepositoryCompletePlatformManagedPickupUsesOfflineSettlement(t *testing.T) {
|
func TestRepositoryCompletePlatformManagedPickupUsesOfflineSettlement(t *testing.T) {
|
||||||
repo, db := newPickupTestRepo(t)
|
repo, db := newPickupTestRepo(t)
|
||||||
listing := seedAvailableListing(t, db, "LST-COMPLETE-EXTERNAL", "代管结算账号", true)
|
listing := seedAvailableListing(t, db, "LST-CMPL-EXTERNAL", "代管结算账号", true)
|
||||||
if err := db.Create(&model.ListingUpload{
|
if err := db.Create(&model.ListingUpload{
|
||||||
UploaderName: "外部号主",
|
UploaderName: "外部号主",
|
||||||
SourceChannel: "闲鱼",
|
SourceChannel: "闲鱼",
|
||||||
@@ -558,7 +557,7 @@ func TestRepositoryFinancialAdjustmentSettlesPlatformManagedPickupSeparately(t *
|
|||||||
|
|
||||||
func TestRepositoryOfflineSettlementProcessesPendingPickupAdjustments(t *testing.T) {
|
func TestRepositoryOfflineSettlementProcessesPendingPickupAdjustments(t *testing.T) {
|
||||||
repo, db := newPickupTestRepo(t)
|
repo, db := newPickupTestRepo(t)
|
||||||
listing := seedAvailableListing(t, db, "LST-ADJUST-WITH-SETTLEMENT", "代管合并结算账号", true)
|
listing := seedAvailableListing(t, db, "LST-ADJ-SETTLEMENT", "代管合并结算账号", true)
|
||||||
if err := db.Create(&model.ListingUpload{UploaderName: "外部号主", ListingID: &listing.ID, Status: "listing_created"}).Error; err != nil {
|
if err := db.Create(&model.ListingUpload{UploaderName: "外部号主", ListingID: &listing.ID, Status: "listing_created"}).Error; err != nil {
|
||||||
t.Fatalf("创建外部上传记录失败: %v", err)
|
t.Fatalf("创建外部上传记录失败: %v", err)
|
||||||
}
|
}
|
||||||
@@ -613,13 +612,8 @@ func assertJSONNumber(t *testing.T, name string, got any, want float64) {
|
|||||||
|
|
||||||
func newPickupTestRepo(t *testing.T) (*Repository, *gorm.DB) {
|
func newPickupTestRepo(t *testing.T) (*Repository, *gorm.DB) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
db := database.NewTestDB()
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(
|
|
||||||
&model.User{},
|
&model.User{},
|
||||||
&model.AdminUser{},
|
&model.AdminUser{},
|
||||||
&model.GameAccount{},
|
&model.GameAccount{},
|
||||||
@@ -718,10 +712,7 @@ func seedPickup(t *testing.T, db *gorm.DB, status string) model.AdminPickup {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestApplyAdminPickupFiltersSmartRouting(t *testing.T) {
|
func TestApplyAdminPickupFiltersSmartRouting(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
db := database.NewDryRunDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("打开测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tests := []struct {
|
tests := []struct {
|
||||||
name string
|
name string
|
||||||
@@ -770,4 +761,3 @@ func TestApplyAdminPickupFiltersSmartRouting(t *testing.T) {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -54,7 +54,7 @@ func TestLegacyConfigBackfillsQuotaButKeepsExplicitZero(t *testing.T) {
|
|||||||
|
|
||||||
func TestSnapshotCombinesLevelAndManualDepositQuota(t *testing.T) {
|
func TestSnapshotCombinesLevelAndManualDepositQuota(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.User{}, &model.SystemConfig{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.User{}, &model.SystemConfig{}); err != nil {
|
||||||
t.Fatalf("migrate failed: %v", err)
|
t.Fatalf("migrate failed: %v", err)
|
||||||
}
|
}
|
||||||
user := model.User{Phone: "13800009999", RenterGrowthPoints: 1000, DepositFreeQuotaCent: 30_000}
|
user := model.User{Phone: "13800009999", RenterGrowthPoints: 1000, DepositFreeQuotaCent: 30_000}
|
||||||
@@ -72,7 +72,7 @@ func TestSnapshotCombinesLevelAndManualDepositQuota(t *testing.T) {
|
|||||||
|
|
||||||
func TestSyncAllUserLevelsUsesUpdatedThresholds(t *testing.T) {
|
func TestSyncAllUserLevelsUsesUpdatedThresholds(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(&model.User{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.User{}); err != nil {
|
||||||
t.Fatalf("migrate failed: %v", err)
|
t.Fatalf("migrate failed: %v", err)
|
||||||
}
|
}
|
||||||
users := []model.User{
|
users := []model.User{
|
||||||
@@ -128,7 +128,7 @@ func TestCalculateDiscountCentCapsAtPlatformFee(t *testing.T) {
|
|||||||
|
|
||||||
func TestAwardOrderCompletedUpdatesUserAndIsIdempotent(t *testing.T) {
|
func TestAwardOrderCompletedUpdatesUserAndIsIdempotent(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
&model.User{},
|
&model.User{},
|
||||||
&model.RentalOrder{},
|
&model.RentalOrder{},
|
||||||
&model.SystemConfig{},
|
&model.SystemConfig{},
|
||||||
@@ -212,7 +212,7 @@ func TestAwardOrderCompletedUpdatesUserAndIsIdempotent(t *testing.T) {
|
|||||||
|
|
||||||
func TestRevokeOrderCompletedRecordsIdempotencyWhenUserHasNoPoints(t *testing.T) {
|
func TestRevokeOrderCompletedRecordsIdempotencyWhenUserHasNoPoints(t *testing.T) {
|
||||||
db := database.NewTestDB()
|
db := database.NewTestDB()
|
||||||
if err := db.AutoMigrate(
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
&model.User{},
|
&model.User{},
|
||||||
&model.RentalOrder{},
|
&model.RentalOrder{},
|
||||||
&model.SystemConfig{},
|
&model.SystemConfig{},
|
||||||
|
|||||||
@@ -6,23 +6,16 @@ import (
|
|||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func newTestSystemConfigRepo(t *testing.T) (*Repository, *gorm.DB) {
|
func newTestSystemConfigRepo(t *testing.T) (*Repository, *gorm.DB) {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())
|
db := database.NewTestDB()
|
||||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
|
if err := database.AutoMigrateIfMissing(db, &model.SystemConfig{}); err != nil {
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("连接测试数据库失败: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(&model.SystemConfig{}); err != nil {
|
|
||||||
t.Fatalf("自动迁移 SystemConfig 失败: %v", err)
|
t.Fatalf("自动迁移 SystemConfig 失败: %v", err)
|
||||||
}
|
}
|
||||||
return NewRepository(db), db
|
return NewRepository(db), db
|
||||||
|
|||||||
@@ -4,24 +4,18 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
// setupTestDB 创建测试数据库连接(使用内存 SQLite)
|
// setupTestDB 创建测试数据库连接(MySQL 测试库)
|
||||||
func setupTestDB(t *testing.T) *gorm.DB {
|
func setupTestDB(t *testing.T) *gorm.DB {
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
db := database.NewTestDB()
|
||||||
Logger: logger.Default.LogMode(logger.Silent),
|
|
||||||
})
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("无法创建测试数据库连接: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 迁移必要的表
|
// 迁移必要的表
|
||||||
if err := db.AutoMigrate(
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
&model.WalletAccount{},
|
&model.WalletAccount{},
|
||||||
&model.WalletLedger{},
|
&model.WalletLedger{},
|
||||||
&model.DistributionSite{},
|
&model.DistributionSite{},
|
||||||
|
|||||||
@@ -33,28 +33,28 @@ type WithdrawalDetailDTO struct {
|
|||||||
DistributionSiteID uint64 `json:"distribution_site_id"`
|
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||||
UserNickname string `json:"user_nickname"`
|
UserNickname string `json:"user_nickname"`
|
||||||
UserPhone string `json:"user_phone"`
|
UserPhone string `json:"user_phone"`
|
||||||
AmountCent int64 `json:"amount_cent"`
|
AmountCent int64 `json:"amount_cent"`
|
||||||
FeeCent int64 `json:"fee_cent"`
|
FeeCent int64 `json:"fee_cent"`
|
||||||
ActualAmountCent int64 `json:"actual_amount_cent"`
|
ActualAmountCent int64 `json:"actual_amount_cent"`
|
||||||
PaymentAccountID *uint64 `json:"payment_account_id"`
|
PaymentAccountID *uint64 `json:"payment_account_id"`
|
||||||
AccountType string `json:"account_type"`
|
AccountType string `json:"account_type"`
|
||||||
AccountName string `json:"account_name"`
|
AccountName string `json:"account_name"`
|
||||||
AccountNo string `json:"account_no"` // 管理员可见完整账号
|
AccountNo string `json:"account_no"` // 管理员可见完整账号
|
||||||
BankName string `json:"bank_name"`
|
BankName string `json:"bank_name"`
|
||||||
BankBranch string `json:"bank_branch"`
|
BankBranch string `json:"bank_branch"`
|
||||||
CertificateURLs []string `json:"certificate_urls"` // 收款二维码图片
|
CertificateURLs []string `json:"certificate_urls"` // 收款二维码图片
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
ReviewedBy *uint64 `json:"reviewed_by"`
|
ReviewedBy *uint64 `json:"reviewed_by"`
|
||||||
ReviewedByName string `json:"reviewed_by_name"`
|
ReviewedByName string `json:"reviewed_by_name"`
|
||||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||||
ReviewRemark string `json:"review_remark"`
|
ReviewRemark string `json:"review_remark"`
|
||||||
PaidBy *uint64 `json:"paid_by"`
|
PaidBy *uint64 `json:"paid_by"`
|
||||||
PaidByName string `json:"paid_by_name"`
|
PaidByName string `json:"paid_by_name"`
|
||||||
PaidAt *time.Time `json:"paid_at"`
|
PaidAt *time.Time `json:"paid_at"`
|
||||||
PaymentProofURL string `json:"payment_proof_url"`
|
PaymentProofURL string `json:"payment_proof_url"`
|
||||||
PaymentRemark string `json:"payment_remark"`
|
PaymentRemark string `json:"payment_remark"`
|
||||||
CreatedAt time.Time `json:"created_at"`
|
CreatedAt time.Time `json:"created_at"`
|
||||||
UpdatedAt time.Time `json:"updated_at"`
|
UpdatedAt time.Time `json:"updated_at"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type CreateWithdrawalRequest struct {
|
type CreateWithdrawalRequest struct {
|
||||||
|
|||||||
@@ -81,29 +81,29 @@ func (r *Repository) toDetailDTO(ctx context.Context, w model.WithdrawalRequest)
|
|||||||
UserID: w.UserID,
|
UserID: w.UserID,
|
||||||
DistributionSiteID: w.DistributionSiteID,
|
DistributionSiteID: w.DistributionSiteID,
|
||||||
UserNickname: user.Nickname,
|
UserNickname: user.Nickname,
|
||||||
UserPhone: user.Phone,
|
UserPhone: user.Phone,
|
||||||
AmountCent: w.AmountCent,
|
AmountCent: w.AmountCent,
|
||||||
FeeCent: w.FeeCent,
|
FeeCent: w.FeeCent,
|
||||||
ActualAmountCent: w.ActualAmountCent,
|
ActualAmountCent: w.ActualAmountCent,
|
||||||
PaymentAccountID: w.PaymentAccountID,
|
PaymentAccountID: w.PaymentAccountID,
|
||||||
AccountType: w.AccountType,
|
AccountType: w.AccountType,
|
||||||
AccountName: w.AccountName,
|
AccountName: w.AccountName,
|
||||||
AccountNo: fullAccountNo,
|
AccountNo: fullAccountNo,
|
||||||
BankName: w.BankName,
|
BankName: w.BankName,
|
||||||
BankBranch: w.BankBranch,
|
BankBranch: w.BankBranch,
|
||||||
CertificateURLs: certificateURLs,
|
CertificateURLs: certificateURLs,
|
||||||
Status: w.Status,
|
Status: w.Status,
|
||||||
ReviewedBy: w.ReviewedBy,
|
ReviewedBy: w.ReviewedBy,
|
||||||
ReviewedByName: reviewedByName,
|
ReviewedByName: reviewedByName,
|
||||||
ReviewedAt: w.ReviewedAt,
|
ReviewedAt: w.ReviewedAt,
|
||||||
ReviewRemark: w.ReviewRemark,
|
ReviewRemark: w.ReviewRemark,
|
||||||
PaidBy: w.PaidBy,
|
PaidBy: w.PaidBy,
|
||||||
PaidByName: paidByName,
|
PaidByName: paidByName,
|
||||||
PaidAt: w.PaidAt,
|
PaidAt: w.PaidAt,
|
||||||
PaymentProofURL: w.PaymentProofURL,
|
PaymentProofURL: w.PaymentProofURL,
|
||||||
PaymentRemark: w.PaymentRemark,
|
PaymentRemark: w.PaymentRemark,
|
||||||
CreatedAt: w.CreatedAt,
|
CreatedAt: w.CreatedAt,
|
||||||
UpdatedAt: w.UpdatedAt,
|
UpdatedAt: w.UpdatedAt,
|
||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -3,16 +3,14 @@ package withdrawal
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
"hfb_sys/backend/internal/modules/wallet"
|
"hfb_sys/backend/internal/modules/wallet"
|
||||||
"hfb_sys/backend/pkg/crypto"
|
"hfb_sys/backend/pkg/crypto"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
type withdrawalFixture struct {
|
type withdrawalFixture struct {
|
||||||
@@ -25,12 +23,8 @@ type withdrawalFixture struct {
|
|||||||
|
|
||||||
func newWithdrawalFixture(t *testing.T) withdrawalFixture {
|
func newWithdrawalFixture(t *testing.T) withdrawalFixture {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
dsn := fmt.Sprintf("file:withdrawal-%s?mode=memory&cache=shared", t.Name())
|
db := database.NewTestDB()
|
||||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
if err := database.AutoMigrateIfMissing(db,
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open sqlite: %v", err)
|
|
||||||
}
|
|
||||||
if err := db.AutoMigrate(
|
|
||||||
&model.User{},
|
&model.User{},
|
||||||
&model.AdminUser{},
|
&model.AdminUser{},
|
||||||
&model.UserPaymentAccount{},
|
&model.UserPaymentAccount{},
|
||||||
|
|||||||
@@ -4,36 +4,39 @@ import (
|
|||||||
"context"
|
"context"
|
||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
"hfb_sys/backend/internal/model"
|
"hfb_sys/backend/internal/model"
|
||||||
|
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
"gorm.io/gorm/logger"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestPrivateFileAuthorizer(t *testing.T) {
|
func TestPrivateFileAuthorizer(t *testing.T) {
|
||||||
db := openAuthorizerTestDB(t)
|
db := openAuthorizerTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.FileUploadOwner{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.FileUploadOwner{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
createAuthorizerBusinessTables(t, db)
|
|
||||||
|
|
||||||
if err := db.Create(&model.FileUploadOwner{UserID: 11, ObjectKey: "listing/draft.jpg"}).Error; err != nil {
|
if err := db.Create(&model.FileUploadOwner{UserID: 11, ObjectKey: "listing/draft.jpg"}).Error; err != nil {
|
||||||
t.Fatalf("create upload owner error = %v", err)
|
t.Fatalf("create upload owner error = %v", err)
|
||||||
}
|
}
|
||||||
if err := db.Exec("INSERT INTO game_accounts (id, owner_id, screenshot_urls) VALUES (1, 21, ?), (2, 23, ?)", `["/api/files/object?key=listing%2Faccount.jpg"]`, `["/api/files/object?key=listing%2Fno-order.jpg"]`).Error; err != nil {
|
if err := db.Exec("INSERT INTO game_accounts (id, owner_id, server_region, login_platform, title, screenshot_urls) "+
|
||||||
|
"VALUES (1, 21, '国服', 'steam', '测试账号', ?), (2, 23, '国服', 'steam', '测试账号', ?)", `["/api/files/object?key=listing%2Faccount.jpg"]`, `["/api/files/object?key=listing%2Fno-order.jpg"]`).Error; err != nil {
|
||||||
t.Fatalf("create account error = %v", err)
|
t.Fatalf("create account error = %v", err)
|
||||||
}
|
}
|
||||||
if err := db.Exec("INSERT INTO rental_orders (id, account_id, owner_id, renter_id) VALUES (1, 1, 21, 22)").Error; err != nil {
|
if err := db.Exec("INSERT INTO rental_orders (id, order_no, listing_id, account_id, owner_id, renter_id) " +
|
||||||
|
"VALUES (1, 'ORD-1', 1, 1, 21, 22)").Error; err != nil {
|
||||||
t.Fatalf("create order error = %v", err)
|
t.Fatalf("create order error = %v", err)
|
||||||
}
|
}
|
||||||
if err := db.Exec("INSERT INTO chat_messages (id, conversation_id, attachment_urls) VALUES (1, 8, ?)", `["/api/files/object?key=chat%2Fmessage.jpg"]`).Error; err != nil {
|
if err := db.Exec("INSERT INTO chat_messages (id, conversation_id, sender_type, attachment_urls) "+
|
||||||
|
"VALUES (1, 8, 'user', ?)", `["/api/files/object?key=chat%2Fmessage.jpg"]`).Error; err != nil {
|
||||||
t.Fatalf("create chat message error = %v", err)
|
t.Fatalf("create chat message error = %v", err)
|
||||||
}
|
}
|
||||||
if err := db.Exec("INSERT INTO chat_participants (id, conversation_id, participant_type, participant_id) VALUES (1, 8, 'user', 31)").Error; err != nil {
|
if err := db.Exec("INSERT INTO chat_participants (id, conversation_id, participant_type, participant_id, role) " +
|
||||||
|
"VALUES (1, 8, 'user', 31, 'renter')").Error; err != nil {
|
||||||
t.Fatalf("create chat participant error = %v", err)
|
t.Fatalf("create chat participant error = %v", err)
|
||||||
}
|
}
|
||||||
if err := db.Exec("INSERT INTO user_payment_accounts (id, user_id, certificate_urls) VALUES (1, 41, ?)", `["/api/files/object?key=payment-cert%2Fqr.jpg"]`).Error; err != nil {
|
if err := db.Exec("INSERT INTO user_payment_accounts (id, user_id, account_type, account_name, account_no, certificate_urls) "+
|
||||||
|
"VALUES (1, 41, 'alipay', '测试户名', 'test@example.com', ?)", `["/api/files/object?key=payment-cert%2Fqr.jpg"]`).Error; err != nil {
|
||||||
t.Fatalf("create payment account error = %v", err)
|
t.Fatalf("create payment account error = %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,7 +69,7 @@ func TestPrivateFileAuthorizer(t *testing.T) {
|
|||||||
|
|
||||||
func TestRecordPrivateFileUpload(t *testing.T) {
|
func TestRecordPrivateFileUpload(t *testing.T) {
|
||||||
db := openAuthorizerTestDB(t)
|
db := openAuthorizerTestDB(t)
|
||||||
if err := db.AutoMigrate(&model.FileUploadOwner{}); err != nil {
|
if err := database.AutoMigrateIfMissing(db, &model.FileUploadOwner{}); err != nil {
|
||||||
t.Fatalf("AutoMigrate() error = %v", err)
|
t.Fatalf("AutoMigrate() error = %v", err)
|
||||||
}
|
}
|
||||||
record := recordPrivateFileUpload(db)
|
record := recordPrivateFileUpload(db)
|
||||||
@@ -88,28 +91,6 @@ func TestRecordPrivateFileUpload(t *testing.T) {
|
|||||||
|
|
||||||
func openAuthorizerTestDB(t *testing.T) *gorm.DB {
|
func openAuthorizerTestDB(t *testing.T) *gorm.DB {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open sqlite error = %v", err)
|
|
||||||
}
|
|
||||||
return db
|
return db
|
||||||
}
|
}
|
||||||
|
|
||||||
func createAuthorizerBusinessTables(t *testing.T, db *gorm.DB) {
|
|
||||||
t.Helper()
|
|
||||||
statements := []string{
|
|
||||||
"CREATE TABLE game_accounts (id INTEGER PRIMARY KEY, owner_id INTEGER NOT NULL, screenshot_urls TEXT)",
|
|
||||||
"CREATE TABLE rental_orders (id INTEGER PRIMARY KEY, account_id INTEGER NOT NULL, owner_id INTEGER NOT NULL, renter_id INTEGER NOT NULL)",
|
|
||||||
"CREATE TABLE order_checkouts (id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, evidence_urls TEXT)",
|
|
||||||
"CREATE TABLE disputes (id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, evidence_urls TEXT)",
|
|
||||||
"CREATE TABLE handoff_records (id INTEGER PRIMARY KEY, order_id INTEGER NOT NULL, attachment_urls TEXT)",
|
|
||||||
"CREATE TABLE chat_messages (id INTEGER PRIMARY KEY, conversation_id INTEGER NOT NULL, attachment_urls TEXT)",
|
|
||||||
"CREATE TABLE chat_participants (id INTEGER PRIMARY KEY, conversation_id INTEGER NOT NULL, participant_type TEXT NOT NULL, participant_id INTEGER NOT NULL)",
|
|
||||||
"CREATE TABLE user_payment_accounts (id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, certificate_urls TEXT)",
|
|
||||||
}
|
|
||||||
for _, statement := range statements {
|
|
||||||
if err := db.Exec(statement).Error; err != nil {
|
|
||||||
t.Fatalf("create test table error = %v", err)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -6,10 +6,9 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
|
|
||||||
"hfb_sys/backend/internal/config"
|
"hfb_sys/backend/internal/config"
|
||||||
|
"hfb_sys/backend/internal/database"
|
||||||
|
|
||||||
"go.uber.org/zap"
|
"go.uber.org/zap"
|
||||||
"gorm.io/driver/sqlite"
|
|
||||||
"gorm.io/gorm"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func testConfig() config.Config {
|
func testConfig() config.Config {
|
||||||
@@ -37,10 +36,7 @@ func TestHealthRoutesSeparateLivenessAndReadiness(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func TestExtractedAdminRoutesRemainRegisteredWithoutDuplicates(t *testing.T) {
|
func TestExtractedAdminRoutesRemainRegisteredWithoutDuplicates(t *testing.T) {
|
||||||
db, err := gorm.Open(sqlite.Open("file:router-routes?mode=memory&cache=shared"), &gorm.Config{})
|
db := database.NewTestDB()
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("open sqlite: %v", err)
|
|
||||||
}
|
|
||||||
engine := New(testConfig(), Dependencies{DB: db}, zap.NewNop())
|
engine := New(testConfig(), Dependencies{DB: db}, zap.NewNop())
|
||||||
routes := engine.Routes()
|
routes := engine.Routes()
|
||||||
registered := make(map[string]struct{}, len(routes))
|
registered := make(map[string]struct{}, len(routes))
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
-- 分销站点、规则、分账、结算,以及主站表上的租户隔离列。
|
-- 分销站点、规则、分账、结算,以及主站表上的租户隔离列。
|
||||||
-- 分成字段存百分数:收号 35、卖出 40、服务费 25。
|
-- 分成字段存百分数:收号 35、卖出 40、服务费 25。
|
||||||
-- 货架调价存 shelf_ratio_delta(分站 1 元兑换哈夫币比例相对主站的增量)。
|
-- 货架调价存 shelf_ratio_delta(分站 1 元兑换哈夫币比例相对主站的增量)。
|
||||||
|
-- 同时把 rental_orders 的业务时间列提到微秒精度(见下方第二条 ALTER)。
|
||||||
|
|
||||||
CREATE TABLE distribution_sites (
|
CREATE TABLE distribution_sites (
|
||||||
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
|
||||||
@@ -206,6 +207,19 @@ ALTER TABLE rental_orders
|
|||||||
ADD CONSTRAINT fk_rental_orders_distribution_site FOREIGN KEY (distribution_site_id) REFERENCES distribution_sites (id),
|
ADD CONSTRAINT fk_rental_orders_distribution_site FOREIGN KEY (distribution_site_id) REFERENCES distribution_sites (id),
|
||||||
ADD CONSTRAINT fk_rental_orders_distribution_rule FOREIGN KEY (distribution_rule_version_id) REFERENCES distribution_rule_versions (id);
|
ADD CONSTRAINT fk_rental_orders_distribution_rule FOREIGN KEY (distribution_rule_version_id) REFERENCES distribution_rule_versions (id);
|
||||||
|
|
||||||
|
-- 顺带把订单业务时间列提到微秒精度:秒级 DATETIME 会静默截断 Go 侧写入的时间,
|
||||||
|
-- 影响租用时长计算与结算时点回读比对。与分销字段同表,合并成一次 ALTER。
|
||||||
|
ALTER TABLE rental_orders
|
||||||
|
MODIFY COLUMN rented_at DATETIME(6) NULL COMMENT '租用开始时间',
|
||||||
|
MODIFY COLUMN handoff_started_at DATETIME(6) NULL COMMENT '进入待号主交接的时间,用于计算交接超时',
|
||||||
|
MODIFY COLUMN growth_points_awarded_at DATETIME(6) NULL COMMENT '成长积分发放时间',
|
||||||
|
MODIFY COLUMN offline_settled_at DATETIME(6) NULL COMMENT '线下结算确认时间',
|
||||||
|
MODIFY COLUMN refunded_at DATETIME(6) NULL COMMENT '退款完成时间',
|
||||||
|
MODIFY COLUMN deposit_held_at DATETIME(6) NULL COMMENT '暂扣时间',
|
||||||
|
MODIFY COLUMN deposit_hold_released_at DATETIME(6) NULL COMMENT '押金归还时间',
|
||||||
|
MODIFY COLUMN owner_settled_at DATETIME(6) NULL COMMENT '号主结算时间',
|
||||||
|
MODIFY COLUMN settled_at DATETIME(6) NULL COMMENT '订单结算时间';
|
||||||
|
|
||||||
ALTER TABLE rental_listings
|
ALTER TABLE rental_listings
|
||||||
ADD COLUMN distribution_site_id BIGINT UNSIGNED NULL AFTER managed_admin_id,
|
ADD COLUMN distribution_site_id BIGINT UNSIGNED NULL AFTER managed_admin_id,
|
||||||
ADD COLUMN source_channel VARCHAR(64) NOT NULL DEFAULT '' AFTER distribution_site_id,
|
ADD COLUMN source_channel VARCHAR(64) NOT NULL DEFAULT '' AFTER distribution_site_id,
|
||||||
@@ -309,6 +323,17 @@ ALTER TABLE rental_listings
|
|||||||
DROP COLUMN source_channel,
|
DROP COLUMN source_channel,
|
||||||
DROP COLUMN distribution_site_id;
|
DROP COLUMN distribution_site_id;
|
||||||
|
|
||||||
|
ALTER TABLE rental_orders
|
||||||
|
MODIFY COLUMN rented_at DATETIME NULL COMMENT '租用开始时间',
|
||||||
|
MODIFY COLUMN handoff_started_at DATETIME NULL COMMENT '进入待号主交接的时间,用于计算交接超时',
|
||||||
|
MODIFY COLUMN growth_points_awarded_at DATETIME NULL COMMENT '成长积分发放时间',
|
||||||
|
MODIFY COLUMN offline_settled_at DATETIME NULL COMMENT '线下结算确认时间',
|
||||||
|
MODIFY COLUMN refunded_at DATETIME NULL COMMENT '退款完成时间',
|
||||||
|
MODIFY COLUMN deposit_held_at DATETIME NULL COMMENT '暂扣时间',
|
||||||
|
MODIFY COLUMN deposit_hold_released_at DATETIME NULL COMMENT '押金归还时间',
|
||||||
|
MODIFY COLUMN owner_settled_at DATETIME NULL COMMENT '号主结算时间',
|
||||||
|
MODIFY COLUMN settled_at DATETIME NULL COMMENT '订单结算时间';
|
||||||
|
|
||||||
ALTER TABLE rental_orders
|
ALTER TABLE rental_orders
|
||||||
DROP FOREIGN KEY fk_rental_orders_distribution_rule,
|
DROP FOREIGN KEY fk_rental_orders_distribution_rule,
|
||||||
DROP FOREIGN KEY fk_rental_orders_distribution_site,
|
DROP FOREIGN KEY fk_rental_orders_distribution_site,
|
||||||
|
|||||||
+20
-14
@@ -31,7 +31,7 @@
|
|||||||
- ✅ `TestNewLedgerNoUsesReadableFormat` - 流水号格式验证
|
- ✅ `TestNewLedgerNoUsesReadableFormat` - 流水号格式验证
|
||||||
|
|
||||||
#### 1.2 集成测试 (`repository_integration_test.go`)
|
#### 1.2 集成测试 (`repository_integration_test.go`)
|
||||||
创建了 **9 个集成测试用例**,使用内存 SQLite 数据库:
|
创建了 **9 个集成测试用例**,使用 MySQL 测试库:
|
||||||
|
|
||||||
**Account 相关**:
|
**Account 相关**:
|
||||||
- ✅ `TestRepositoryAccountCreatesAccountIfNotExists` - 账户自动创建
|
- ✅ `TestRepositoryAccountCreatesAccountIfNotExists` - 账户自动创建
|
||||||
@@ -54,15 +54,15 @@
|
|||||||
#### 2.1 测试辅助工具 (`database/test_helper.go`)
|
#### 2.1 测试辅助工具 (`database/test_helper.go`)
|
||||||
创建了数据库测试辅助函数:
|
创建了数据库测试辅助函数:
|
||||||
```go
|
```go
|
||||||
func NewTestDB() *gorm.DB // 创建内存数据库
|
func NewTestDB() *gorm.DB // 返回指向 MySQL 测试库的干净连接
|
||||||
func NewTestDBWithName(name string) *gorm.DB // 创建命名内存数据库(支持多连接)
|
func NewDryRunDB() *gorm.DB // MySQL 方言的 DryRun 连接,仅生成 SQL 不执行
|
||||||
```
|
```
|
||||||
|
|
||||||
**优势**:
|
**特点**:
|
||||||
- 使用 SQLite 内存数据库,无需 MySQL 环境
|
- 测试跑在真实 MySQL 上,表结构由 `backend/migrations` 的真实迁移建立,与生产一致
|
||||||
- 测试速度快(纯内存操作)
|
- 每个测试包使用独立库 `hfb_sys_test_<包名>`,因此 `go test ./...` 可并发执行
|
||||||
- 测试隔离性好(每个测试独立数据库)
|
- 每次 `NewTestDB()` 调用会清空全部表,测试之间互相隔离
|
||||||
- 支持并发测试
|
- 需要 MySQL 可用:首次执行 `bash scripts/prepare-test-db.sh` 完成建库授权
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -209,11 +209,17 @@ func TestXxx(t *testing.T) {
|
|||||||
|
|
||||||
## 🚀 如何运行测试
|
## 🚀 如何运行测试
|
||||||
|
|
||||||
### 1. **首次运行(需要安装 SQLite 驱动)**
|
### 1. **首次运行(需要准备 MySQL 测试库)**
|
||||||
```bash
|
```bash
|
||||||
cd backend
|
# 启动本地 MySQL(如未启动)
|
||||||
go mod tidy # 下载依赖(包括 gorm.io/driver/sqlite)
|
bash scripts/dev.sh
|
||||||
|
# 建库并授权(可重复执行,只需一次)
|
||||||
|
bash scripts/prepare-test-db.sh
|
||||||
```
|
```
|
||||||
|
测试库由测试代码自行创建:首次连接时会重建 `hfb_sys_test_<包名>` 并执行
|
||||||
|
`backend/migrations` 下的真实迁移,无需手工建表。
|
||||||
|
|
||||||
|
可通过 `HFB_TEST_DSN` 覆盖测试库连接(库名必须包含 `test` 或 `e2e`)。
|
||||||
|
|
||||||
### 2. **运行所有 wallet 模块测试**
|
### 2. **运行所有 wallet 模块测试**
|
||||||
```bash
|
```bash
|
||||||
@@ -290,11 +296,11 @@ go tool cover -html=coverage.out
|
|||||||
---
|
---
|
||||||
|
|
||||||
**备注**:
|
**备注**:
|
||||||
- 集成测试需要先运行 `go mod tidy` 下载 SQLite 驱动
|
- 集成测试跑在真实 MySQL 上,需先执行 `bash scripts/prepare-test-db.sh` 完成建库授权
|
||||||
- 所有测试代码已编写完成,等待依赖安装后即可运行
|
- 表结构来自 `backend/migrations` 的真实迁移,测试环境与生产一致
|
||||||
- 测试覆盖了核心业务逻辑、边界条件、并发安全和数据一致性
|
- 测试覆盖了核心业务逻辑、边界条件、并发安全和数据一致性
|
||||||
|
|
||||||
**下一步建议**:
|
**下一步建议**:
|
||||||
1. 运行 `go mod tidy` 安装依赖
|
1. 执行 `bash scripts/prepare-test-db.sh` 准备测试库
|
||||||
2. 运行 wallet 模块所有测试验证通过
|
2. 运行 wallet 模块所有测试验证通过
|
||||||
3. 继续为 order 和 payment 模块补充 Repository 层测试
|
3. 继续为 order 和 payment 模块补充 Repository 层测试
|
||||||
|
|||||||
@@ -8,7 +8,8 @@ OUTPUT="$(mktemp -t hfb-backend-cover-output.XXXXXX)"
|
|||||||
trap 'rm -f "${PROFILE}" "${OUTPUT}"' EXIT
|
trap 'rm -f "${PROFILE}" "${OUTPUT}"' EXIT
|
||||||
|
|
||||||
cd "${BACKEND_DIR}"
|
cd "${BACKEND_DIR}"
|
||||||
go test -p 1 -count=1 -coverprofile="${PROFILE}" ./... | tee "${OUTPUT}"
|
# 每个测试包使用独立 MySQL 测试库,可并发执行。
|
||||||
|
go test -count=1 -coverprofile="${PROFILE}" ./... | tee "${OUTPUT}"
|
||||||
|
|
||||||
coverage_for_package() {
|
coverage_for_package() {
|
||||||
local package="$1"
|
local package="$1"
|
||||||
|
|||||||
+3
-1
@@ -96,7 +96,9 @@ if [[ "${SKIP_BACKEND}" == "0" ]]; then
|
|||||||
run_step "go vet ./..." go vet ./... || FAILED=1
|
run_step "go vet ./..." go vet ./... || FAILED=1
|
||||||
run_step "go build ./..." go build ./... || FAILED=1
|
run_step "go build ./..." go build ./... || FAILED=1
|
||||||
if [[ "${SKIP_TESTS}" == "0" ]]; then
|
if [[ "${SKIP_TESTS}" == "0" ]]; then
|
||||||
# -p 1 串行避免 SQLite 内存库并发; 真实 MySQL e2e 默认 skip
|
# 后端测试跑在真实 MySQL 上:每个包使用独立测试库 hfb_sys_test_<包名>,可并发执行。
|
||||||
|
# 真实链路 e2e(internal/e2e 中依赖 HFB_E2E_DSN 的用例)需要显式配置该变量。
|
||||||
|
run_step "准备 MySQL 测试库" bash "${ROOT_DIR}/scripts/prepare-test-db.sh" || FAILED=1
|
||||||
run_step "go test + coverage" bash "${ROOT_DIR}/scripts/check-backend-coverage.sh" || FAILED=1
|
run_step "go test + coverage" bash "${ROOT_DIR}/scripts/check-backend-coverage.sh" || FAILED=1
|
||||||
else
|
else
|
||||||
log_warn "跳过后端测试 (--skip-tests)"
|
log_warn "跳过后端测试 (--skip-tests)"
|
||||||
|
|||||||
Executable
+46
@@ -0,0 +1,46 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# 准备后端测试所需的 MySQL 库与授权。
|
||||||
|
#
|
||||||
|
# 测试按包使用独立库(默认 hfb_sys_test_<包名>),这里用一条通配授权覆盖全部包,
|
||||||
|
# 因此只需在搭建环境时执行一次。可重复执行。
|
||||||
|
#
|
||||||
|
# 可用环境变量覆盖:
|
||||||
|
# TEST_MYSQL_HOST/PORT 应用账号连接地址(默认 127.0.0.1:13306)
|
||||||
|
# MYSQL_ADMIN_USER/PASSWORD 管理员账号(默认 root/rootsecret)
|
||||||
|
# TEST_MYSQL_USER/PASSWORD 应用账号(默认 hfb/secret)
|
||||||
|
# HFB_TEST_DATABASE 测试库基础名(默认 hfb_sys_test)
|
||||||
|
# TEST_MYSQL_CONTAINER 优先使用的容器名(默认 hfb-mysql)
|
||||||
|
|
||||||
|
host="${TEST_MYSQL_HOST:-127.0.0.1}"
|
||||||
|
port="${TEST_MYSQL_PORT:-13306}"
|
||||||
|
admin_user="${MYSQL_ADMIN_USER:-root}"
|
||||||
|
admin_password="${MYSQL_ADMIN_PASSWORD:-rootsecret}"
|
||||||
|
app_user="${TEST_MYSQL_USER:-hfb}"
|
||||||
|
app_password="${TEST_MYSQL_PASSWORD:-secret}"
|
||||||
|
base_database="${HFB_TEST_DATABASE:-hfb_sys_test}"
|
||||||
|
container="${TEST_MYSQL_CONTAINER:-hfb-mysql}"
|
||||||
|
|
||||||
|
[[ "${base_database}" =~ ^[A-Za-z0-9_]+$ ]] || { printf '测试库基础名不合法: %s\n' "${base_database}" >&2; exit 2; }
|
||||||
|
|
||||||
|
# MySQL 模式串里下划线是通配符,需要转义成字面量。
|
||||||
|
pattern="$(printf '%s' "${base_database}" | sed 's/_/\\\\_/g')"
|
||||||
|
|
||||||
|
run_admin_sql() {
|
||||||
|
if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' 2>/dev/null | grep -qx "${container}"; then
|
||||||
|
docker exec -i "${container}" mysql -u"${admin_user}" -p"${admin_password}"
|
||||||
|
else
|
||||||
|
MYSQL_PWD="${admin_password}" mysql --host="${host}" --port="${port}" --user="${admin_user}"
|
||||||
|
fi
|
||||||
|
}
|
||||||
|
|
||||||
|
printf '准备 MySQL 测试库授权:%s_%% -> %s@%%\n' "${base_database}" "${app_user}"
|
||||||
|
|
||||||
|
run_admin_sql <<SQL
|
||||||
|
CREATE USER IF NOT EXISTS '${app_user}'@'%' IDENTIFIED BY '${app_password}';
|
||||||
|
GRANT ALL PRIVILEGES ON \`${pattern}\_%\`.* TO '${app_user}'@'%';
|
||||||
|
FLUSH PRIVILEGES;
|
||||||
|
SQL
|
||||||
|
|
||||||
|
printf '测试库授权已就绪。测试运行时会自动重建各自的库:%s_<包名>\n' "${base_database}"
|
||||||
Reference in New Issue
Block a user