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:
@@ -12,7 +12,7 @@ import (
|
||||
|
||||
func TestListingDailyOverviewGroupsBySourceChannel(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
@@ -68,7 +68,7 @@ func assertChannelStats(t *testing.T, item ListingChannelDayStatsDTO, published,
|
||||
|
||||
func TestListingDailyOverviewGroupsExternalUploadsByUploader(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
|
||||
@@ -240,22 +240,22 @@ func (r *Repository) dailyItems(ctx context.Context, query DashboardQuery) (dash
|
||||
|
||||
pickupProfits := make([]dailyPickupProfitRow, 0)
|
||||
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,
|
||||
COUNT(id) AS completed_count`).
|
||||
Where("status = ?", "completed").
|
||||
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 {
|
||||
return dashboardDailyResult{}, err
|
||||
}
|
||||
pickupAdjustments := make([]dailyPickupAdjustmentRow, 0)
|
||||
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`).
|
||||
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).
|
||||
Group("DATE(fa.created_at)").
|
||||
Group("DATE_FORMAT(fa.created_at, '%Y-%m-%d')").
|
||||
Scan(&pickupAdjustments).Error; err != nil {
|
||||
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) {
|
||||
rows := make([]dailyEstimatedRow, 0)
|
||||
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,
|
||||
COUNT(id) AS pending_settle_order_count`).
|
||||
Where("settlement_status NOT IN ?", settledSettlementStatuses()).
|
||||
Where("status NOT IN ?", nonBillableOrderStatuses()).
|
||||
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
|
||||
return rows, err
|
||||
}
|
||||
@@ -403,7 +403,7 @@ func (r *Repository) dailySettlements(ctx context.Context, query DashboardQuery)
|
||||
db := r.db.WithContext(ctx)
|
||||
rows := make([]dailySettlementRow, 0)
|
||||
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.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,
|
||||
@@ -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("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).
|
||||
Group("DATE(ro.settled_at)").
|
||||
Group("DATE_FORMAT(ro.settled_at, '%Y-%m-%d')").
|
||||
Scan(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
@@ -521,7 +521,7 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
||||
rows := make([]dailyPaymentRow, 0)
|
||||
db := r.db.WithContext(ctx)
|
||||
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 = '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,
|
||||
@@ -536,7 +536,7 @@ func (r *Repository) dailyPayments(ctx context.Context, query DashboardQuery) ([
|
||||
payBizTypes(), refundBizTypes(), refundBizTypes(), payBizTypes(), refundBizTypes(), refundBizTypes(), refundBizTypes(), normalRefundBizTypes()).
|
||||
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).
|
||||
Group("DATE(po.created_at)").
|
||||
Group("DATE_FORMAT(po.created_at, '%Y-%m-%d')").
|
||||
Scan(&rows).Error
|
||||
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) {
|
||||
rows := make([]dailyPickupCancelledRow, 0)
|
||||
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("cancelled_at >= ? AND cancelled_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE(cancelled_at)").
|
||||
Group("DATE_FORMAT(cancelled_at, '%Y-%m-%d')").
|
||||
Scan(&rows).Error
|
||||
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) {
|
||||
items := make([]dailyPaidOrderRow, 0)
|
||||
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
|
||||
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
|
||||
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
|
||||
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).
|
||||
Select("date, SUM(paid_order_count) AS paid_order_count").
|
||||
Group("date").
|
||||
|
||||
@@ -6,59 +6,39 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func TestDailyPaidOrdersUsePaidAtAndIncludeCreatedPickups(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
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)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
day := func(value int) time.Time { return time.Date(2026, 8, value, 10, 0, 0, 0, loc) }
|
||||
rows := [][]any{
|
||||
{1, 101, "order_pay", "paid", day(2)},
|
||||
{2, 101, "order_pay", "paid", day(2)},
|
||||
{3, 102, "order_pay", "paid", day(3)},
|
||||
{4, 201, "mohong_pay", "paid", day(2)},
|
||||
{5, 103, "order_pay", "created", nil},
|
||||
{6, 104, "order_pay", "paid", day(1)},
|
||||
{1, "PAY-1", 101, "ORD-101", 11, "mockpay", "T-101", "order_pay", "paid", day(2)},
|
||||
{2, "PAY-2", 101, "ORD-101", 11, "mockpay", "T-102", "order_pay", "paid", day(2)},
|
||||
{3, "PAY-3", 102, "ORD-102", 12, "mockpay", "T-103", "order_pay", "paid", day(3)},
|
||||
{4, "PAY-4", 201, "ORD-201", 21, "mockpay", "T-201", "mohong_pay", "paid", day(2)},
|
||||
{5, "PAY-5", 103, "ORD-103", 13, "mockpay", "T-104", "order_pay", "created", nil},
|
||||
{6, "PAY-6", 104, "ORD-104", 14, "mockpay", "T-105", "order_pay", "paid", day(1)},
|
||||
}
|
||||
for _, row := range rows {
|
||||
if err := db.Exec(`INSERT INTO payment_orders (id, order_id, biz_type, status, paid_at)
|
||||
VALUES (?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||
if err := db.Exec(`INSERT INTO payment_orders
|
||||
(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)
|
||||
}
|
||||
}
|
||||
for _, row := range [][]any{
|
||||
{1, "completed", day(2), day(2)},
|
||||
{2, "picking_up", day(2), nil},
|
||||
{3, "completed", day(3), day(3)},
|
||||
{4, "cancelled", day(1), nil},
|
||||
{1, "PK-1", 1, 1, 1, 1, "completed", day(2), day(2)},
|
||||
{2, "PK-2", 2, 2, 2, 1, "picking_up", day(2), nil},
|
||||
{3, "PK-3", 3, 3, 3, 1, "completed", day(3), day(3)},
|
||||
{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)
|
||||
}
|
||||
}
|
||||
@@ -85,37 +65,25 @@ func TestDailyPaidOrdersUsePaidAtAndIncludeCreatedPickups(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDailyPaymentsNormalFullRefundExcludesMohong(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
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)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
day := func(value int) time.Time { return time.Date(2026, 8, value, 10, 0, 0, 0, loc) }
|
||||
rows := [][]any{
|
||||
// 正常订单全额退款:计入 full_refund_count 与 normal_full_refund_count
|
||||
{1, 101, "rent_refund", "refunded", 5000, day(2)},
|
||||
{2, 101, "order_pay", "paid", 5000, day(1)},
|
||||
{1, "PAY-1", 101, "ORD-101", 11, "mockpay", "T-101", "rent_refund", "refunded", 5000, day(2)},
|
||||
{2, "PAY-2", 101, "ORD-101", 11, "mockpay", "T-102", "order_pay", "paid", 5000, day(1)},
|
||||
// 正常订单部分退款:不计入全额
|
||||
{3, 102, "rent_refund", "refunded", 2000, day(2)},
|
||||
{4, 102, "order_pay", "paid", 5000, day(1)},
|
||||
{3, "PAY-3", 102, "ORD-102", 12, "mockpay", "T-103", "rent_refund", "refunded", 2000, day(2)},
|
||||
{4, "PAY-4", 102, "ORD-102", 12, "mockpay", "T-104", "order_pay", "paid", 5000, day(1)},
|
||||
// 撞车商城全额退款:只计入 full_refund_count,不计入 normal_full_refund_count
|
||||
{5, 201, "mohong_refund", "refunded", 3000, day(2)},
|
||||
{6, 201, "mohong_pay", "paid", 3000, day(1)},
|
||||
{5, "PAY-5", 201, "ORD-201", 21, "mockpay", "T-201", "mohong_refund", "refunded", 3000, day(2)},
|
||||
{6, "PAY-6", 201, "ORD-201", 21, "mockpay", "T-202", "mohong_pay", "paid", 3000, day(1)},
|
||||
}
|
||||
for _, row := range rows {
|
||||
if err := db.Exec(`INSERT INTO payment_orders (id, order_id, biz_type, status, amount_cent, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||
if err := db.Exec(`INSERT INTO payment_orders
|
||||
(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)
|
||||
}
|
||||
}
|
||||
@@ -145,28 +113,20 @@ func TestDailyPaymentsNormalFullRefundExcludesMohong(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestDailyPickupCancelledByCancelledAt(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
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)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
day := func(value int) time.Time { return time.Date(2026, 8, value, 15, 0, 0, 0, loc) }
|
||||
for _, row := range [][]any{
|
||||
{1, "cancelled", day(2)},
|
||||
{2, "cancelled", day(2)},
|
||||
{3, "cancelled", day(3)},
|
||||
{4, "cancelled", nil}, // 取消时间缺失的不计
|
||||
{5, "completed", day(2)},
|
||||
{1, "PK-1", 1, 1, 1, 1, "cancelled", day(1), day(2)},
|
||||
{2, "PK-2", 2, 2, 2, 1, "cancelled", day(1), day(2)},
|
||||
{3, "PK-3", 3, 3, 3, 1, "cancelled", day(1), day(3)},
|
||||
{4, "PK-4", 4, 4, 4, 1, "cancelled", day(1), nil}, // 取消时间缺失的不计
|
||||
{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)
|
||||
}
|
||||
}
|
||||
@@ -189,41 +149,19 @@ func TestDailyPickupCancelledByCancelledAt(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPickupSummaryKeepsOriginalAndAdjustmentOnTheirOwnDates(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
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)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
completedAt := time.Date(2026, 8, 2, 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)
|
||||
VALUES (1, 'completed', 12000, 1000, ?)`, completedAt).Error; err != nil {
|
||||
if err := db.Exec(`INSERT INTO admin_pickups
|
||||
(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)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments (id, pickup_id, settle_delta_cent, profit_delta_cent, created_at)
|
||||
VALUES (1, 1, 1500, 500, ?)`, adjustedAt).Error; err != nil {
|
||||
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
||||
(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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -250,66 +188,36 @@ func TestPickupSummaryKeepsOriginalAndAdjustmentOnTheirOwnDates(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestSummaryReturnsNormalOrderCountAndScopedExceptionCount(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
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)
|
||||
}
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
settledAt := time.Date(2026, 8, 2, 10, 0, 0, 0, loc)
|
||||
for _, row := range [][]any{
|
||||
{1, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 300},
|
||||
{2, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 200},
|
||||
{1, "ORD-S1", 1, 1, 1, 1, settledAt, "owner_wallet", 0, "none", "none", "settled", "completed", settledAt, 300},
|
||||
{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
|
||||
(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)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||
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
|
||||
(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)
|
||||
}
|
||||
}
|
||||
for _, row := range [][]any{{1, 1, "in", "owner_income", 700}, {2, 2, "in", "owner_income", 500}} {
|
||||
if err := db.Exec(`INSERT INTO wallet_ledger (id, order_id, direction, biz_type, amount_cent) VALUES (?, ?, ?, ?, ?)`, row...).Error; err != nil {
|
||||
for _, row := range [][]any{
|
||||
{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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,10 @@ type dailyOperatingExpenseRow struct {
|
||||
func (r *Repository) dailyOperatingExpenses(ctx context.Context, query DashboardQuery) ([]dailyOperatingExpenseRow, error) {
|
||||
rows := make([]dailyOperatingExpenseRow, 0)
|
||||
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("occurred_at >= ? AND occurred_at <= ?", query.StartDate, query.EndDate).
|
||||
Group("DATE(occurred_at)").
|
||||
Group("DATE_FORMAT(occurred_at, '%Y-%m-%d')").
|
||||
Scan(&rows).Error
|
||||
return rows, err
|
||||
}
|
||||
@@ -162,38 +162,38 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
db := r.db.WithContext(ctx)
|
||||
offlineRows := make([]dailyDisbursementSourceRow, 0)
|
||||
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,
|
||||
COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
pickupOfflineRows := make([]dailyDisbursementSourceRow, 0)
|
||||
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,
|
||||
COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("offline_settlement_status = ?", "settled").
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
pickupAdjustmentRows := make([]dailyDisbursementSourceRow, 0)
|
||||
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,
|
||||
COUNT(id) AS count`).
|
||||
Where("settlement_mode = ?", "platform_managed").
|
||||
Where("status = ?", "settled").
|
||||
Where("settle_delta_cent > 0").
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
@@ -202,24 +202,24 @@ func (r *Repository) dailyDisbursements(ctx context.Context, query DashboardQuer
|
||||
|
||||
withdrawalRows := make([]dailyDisbursementSourceRow, 0)
|
||||
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,
|
||||
COUNT(id) AS count`).
|
||||
Where("status = ?", "completed").
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
manualRows := make([]dailyDisbursementSourceRow, 0)
|
||||
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,
|
||||
COUNT(id) AS count`).
|
||||
Where("status = ?", "paid").
|
||||
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 {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -4,70 +4,21 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func TestDisbursementListCombinesPlatformSettlementsAndWithdrawals(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
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)
|
||||
}
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
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
|
||||
(1, '平台客服', 'admin:1'), (2, '提现用户', '13900000000')`).Error; err != nil {
|
||||
if err := db.Exec(`INSERT INTO users (id, nickname, phone, password_hash) VALUES
|
||||
(1, '平台客服', 'admin:1', ''), (2, '提现用户', '13900000000', '')`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username) VALUES
|
||||
(7, '财务甲', 'finance_a'), (8, '财务乙', 'finance_b')`).Error; err != nil {
|
||||
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username, password_hash) VALUES
|
||||
(7, '财务甲', 'finance_a', ''), (8, '财务乙', 'finance_b', '')`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO listing_uploads
|
||||
@@ -78,23 +29,25 @@ func TestDisbursementListCombinesPlatformSettlementsAndWithdrawals(t *testing.T)
|
||||
t.Fatal(err)
|
||||
}
|
||||
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)
|
||||
VALUES
|
||||
(1, 'R202607010001', 101, 1, 'platform_managed', 'settled', 12000, '支付宝转账', ?, ?, 7),
|
||||
(2, 'R202607010002', 102, 1, 'platform_managed', 'pending', 8000, '', ?, NULL, NULL)`,
|
||||
(1, 'R202607010001', 101, 101, 1, 2, 'platform_managed', 'settled', 12000, '支付宝转账', ?, ?, 7),
|
||||
(2, 'R202607010002', 102, 102, 1, 2, 'platform_managed', 'pending', 8000, '', ?, NULL, NULL)`,
|
||||
at(2), at(3), at(4)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO admin_pickups
|
||||
(id, pickup_no, owner_id, source_channel, settlement_mode, settle_amount_cent, offline_settlement_status,
|
||||
offline_settlement_remark, offline_settled_by, offline_settled_at, completed_at, account_snapshot)
|
||||
VALUES (30, 'P202607010001', 1, '线下录入', 'platform_managed', 4000, 'settled', '提号结算', 7, ?, ?, '{}')`, at(4), at(3)).Error; err != nil {
|
||||
(id, pickup_no, listing_id, account_id, owner_id, admin_id, source_channel, settlement_mode, settle_amount_cent,
|
||||
offline_settlement_status, offline_settlement_remark, offline_settled_by, offline_settled_at, completed_at,
|
||||
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)
|
||||
}
|
||||
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)
|
||||
VALUES (31, 30, 500, 'platform_managed', 'settled', '补差价', 7, ?, ?)`, at(5), at(5)).Error; err != nil {
|
||||
(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, 7, ?, ?)`, at(5), at(5)).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Exec(`INSERT INTO withdrawal_requests
|
||||
|
||||
@@ -4,63 +4,12 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func TestDisbursementStatisticsUseActualPaymentTimeAndAmount(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
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)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
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)
|
||||
|
||||
for _, args := range [][]any{
|
||||
{1, "platform_managed", "settled", 12000, inRangeOffline},
|
||||
{2, "platform_managed", "settled", 3000, outOfRange},
|
||||
{3, "platform_managed", "pending", 8000, nil},
|
||||
{4, "platform_managed", "pending", 0, nil},
|
||||
{5, "owner_wallet", "pending", 9000, nil},
|
||||
{1, "ORD-1", 1, 1, 1, 1, "platform_managed", "settled", 12000, inRangeOffline},
|
||||
{2, "ORD-2", 2, 2, 2, 2, "platform_managed", "settled", 3000, outOfRange},
|
||||
{3, "ORD-3", 3, 3, 3, 3, "platform_managed", "pending", 8000, nil},
|
||||
{4, "ORD-4", 4, 4, 4, 4, "platform_managed", "pending", 0, nil},
|
||||
{5, "ORD-5", 5, 5, 5, 5, "owner_wallet", "pending", 9000, nil},
|
||||
} {
|
||||
if err := db.Exec(`INSERT INTO rental_orders
|
||||
(id, settlement_mode, offline_settlement_status, offline_settlement_amount_cent, offline_settled_at)
|
||||
VALUES (?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||
(id, order_no, listing_id, account_id, owner_id, renter_id,
|
||||
settlement_mode, offline_settlement_status, offline_settlement_amount_cent, offline_settled_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||
t.Fatalf("写入订单失败: %v", err)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]any{
|
||||
{1, "platform_managed", "settled", 4000, inRangeOffline},
|
||||
{2, "platform_managed", "pending", 2500, nil},
|
||||
{1, "PKR-1", 1, 1, 1, 1, "platform_managed", "settled", 4000, inRangeOffline, inRangeOffline},
|
||||
{2, "PKR-2", 2, 2, 2, 2, "platform_managed", "pending", 2500, nil, inRangeOffline},
|
||||
} {
|
||||
if err := db.Exec(`INSERT INTO admin_pickups
|
||||
(id, settlement_mode, offline_settlement_status, settle_amount_cent, offline_settled_at)
|
||||
VALUES (?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||
(id, pickup_no, listing_id, account_id, owner_id, admin_id, settlement_mode,
|
||||
offline_settlement_status, settle_amount_cent, offline_settled_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||
t.Fatalf("写入提号失败: %v", err)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]any{
|
||||
{1, "platform_managed", "settled", 500, inRangeManual},
|
||||
{2, "platform_managed", "pending", 300, nil},
|
||||
{3, "platform_managed", "recovery_pending", -200, nil},
|
||||
{1, 1, "platform_managed", "settled", "补差价", 1, 500, inRangeManual, inRangeManual},
|
||||
{2, 2, "platform_managed", "pending", "补差价", 1, 300, nil, inRangeManual},
|
||||
{3, 3, "platform_managed", "recovery_pending", "补差价", 1, -200, nil, inRangeManual},
|
||||
} {
|
||||
if err := db.Exec(`INSERT INTO admin_pickup_financial_adjustments
|
||||
(id, settlement_mode, status, settle_delta_cent, settled_at)
|
||||
VALUES (?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||
(id, pickup_id, settlement_mode, status, reason, created_by, settle_delta_cent, settled_at, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||
t.Fatalf("写入提号调整失败: %v", err)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]any{
|
||||
{1, "paid", 2500, inRangeManual},
|
||||
{2, "paid", 1000, outOfRange},
|
||||
{3, "voided", 6000, inRangeManual},
|
||||
{1, "MD-1", "推广投放", "测试收款方", "测试备注", 1, "paid", 2500, inRangeManual},
|
||||
{2, "MD-2", "推广投放", "测试收款方", "测试备注", 1, "paid", 1000, outOfRange},
|
||||
{3, "MD-3", "推广投放", "测试收款方", "测试备注", 1, "voided", 6000, inRangeManual},
|
||||
} {
|
||||
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)
|
||||
}
|
||||
}
|
||||
for _, args := range [][]any{
|
||||
{1, "completed", 10000, 100, 9900, inRangeWithdrawal},
|
||||
{2, "completed", 5000, 0, 5000, outOfRange},
|
||||
{3, "processing", 5000, 200, 4800, nil},
|
||||
{4, "pending", 2100, 100, 2000, nil},
|
||||
{5, "rejected", 6000, 100, 5900, nil},
|
||||
{1, "WD-1", 1, "alipay", "测试户名", "test@example.com", "completed", 10000, 100, 9900, inRangeWithdrawal},
|
||||
{2, "WD-2", 1, "alipay", "测试户名", "test@example.com", "completed", 5000, 0, 5000, outOfRange},
|
||||
{3, "WD-3", 1, "alipay", "测试户名", "test@example.com", "processing", 5000, 200, 4800, nil},
|
||||
{4, "WD-4", 1, "alipay", "测试户名", "test@example.com", "pending", 2100, 100, 2000, nil},
|
||||
{5, "WD-5", 1, "alipay", "测试户名", "test@example.com", "rejected", 6000, 100, 5900, nil},
|
||||
} {
|
||||
if err := db.Exec(`INSERT INTO withdrawal_requests
|
||||
(id, status, amount_cent, fee_cent, actual_amount_cent, paid_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||
(id, withdraw_no, user_id, account_type, account_name, account_no,
|
||||
status, amount_cent, fee_cent, actual_amount_cent, paid_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, args...).Error; err != nil {
|
||||
t.Fatalf("写入提现单失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,41 +6,14 @@ import (
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func TestManualDisbursementCreateAndVoid(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败: %v", err)
|
||||
}
|
||||
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 {
|
||||
db := database.NewTestDB()
|
||||
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username, password_hash) VALUES
|
||||
(7, '财务甲', 'finance_a', ''), (8, '财务乙', 'finance_b', '')`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
|
||||
@@ -6,36 +6,13 @@ import (
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func TestOperatingExpenseCreateListAndVoid(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
if 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 {
|
||||
db := database.NewTestDB()
|
||||
if err := db.Exec(`INSERT INTO admin_users (id, nickname, username, password_hash) VALUES (7, '运营甲', 'ops_a', ''), (8, '运营乙', 'ops_b', '')`).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -79,19 +56,15 @@ func TestOperatingExpenseCreateListAndVoid(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestOperatingExpenseDashboardSummaryExcludesVoided(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
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)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
loc := timeutil.ShanghaiLocation()
|
||||
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
|
||||
(1, 12000, ?, 'paid'), (2, 8000, ?, 'voided'), (3, 5000, ?, 'paid')`, inRange, inRange, inRange.AddDate(0, 0, -1)).Error; err != nil {
|
||||
if err := db.Exec(`INSERT INTO operating_expenses
|
||||
(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)
|
||||
}
|
||||
summary, err := NewRepository(db).operatingExpenseSummary(t.Context(), DashboardQuery{
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -52,7 +52,7 @@ func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
||||
|
||||
func TestRepositoryMarkAllRead(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -93,7 +93,7 @@ func TestRepositoryMarkAllRead(t *testing.T) {
|
||||
|
||||
func TestRepositoryMarkReadNotFound(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
|
||||
@@ -3,14 +3,14 @@ package adminrole
|
||||
import "time"
|
||||
|
||||
type RoleDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
PermCount int `json:"perm_count"`
|
||||
ID uint64 `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
PermCount int `json:"perm_count"`
|
||||
Permissions []PermissionDTO `json:"permissions,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type PermissionDTO struct {
|
||||
|
||||
@@ -5,10 +5,10 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -62,10 +62,7 @@ func TestParseBoolQuery(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestApplyUserFilterHasDepositFreeQuota(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败:%v", err)
|
||||
}
|
||||
db := database.NewDryRunDB()
|
||||
|
||||
stmt := applyUserFilter(db.Table("users AS u"), ListQuery{
|
||||
Status: "active",
|
||||
@@ -328,11 +325,8 @@ func TestFreezeAndUnfreezeBumpUserTokenVersion(t *testing.T) {
|
||||
|
||||
func setupAdminUserTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败:%v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.User{},
|
||||
&model.UserRealname{},
|
||||
&model.AuditLog{},
|
||||
|
||||
@@ -3,27 +3,27 @@ package adtracking
|
||||
import "time"
|
||||
|
||||
type TrackingLinkItem struct {
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Code string `json:"code"`
|
||||
ChannelType string `json:"channel_type"`
|
||||
TargetURL string `json:"target_url"`
|
||||
ShortURL string `json:"short_url"`
|
||||
Status string `json:"status"`
|
||||
CostCent int64 `json:"cost_cent"`
|
||||
Notes string `json:"notes"`
|
||||
CreatedBy uint64 `json:"created_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID uint64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Code string `json:"code"`
|
||||
ChannelType string `json:"channel_type"`
|
||||
TargetURL string `json:"target_url"`
|
||||
ShortURL string `json:"short_url"`
|
||||
Status string `json:"status"`
|
||||
CostCent int64 `json:"cost_cent"`
|
||||
Notes string `json:"notes"`
|
||||
CreatedBy uint64 `json:"created_by"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
|
||||
// 统计指标
|
||||
ClickPV int64 `json:"click_pv"`
|
||||
ClickUV int64 `json:"click_uv"`
|
||||
ClickIP int64 `json:"click_ip"`
|
||||
RegisterCount int64 `json:"register_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
PaidOrderCount int64 `json:"paid_order_count"`
|
||||
PaidGMVCent int64 `json:"paid_gmv_cent"`
|
||||
ClickPV int64 `json:"click_pv"`
|
||||
ClickUV int64 `json:"click_uv"`
|
||||
ClickIP int64 `json:"click_ip"`
|
||||
RegisterCount int64 `json:"register_count"`
|
||||
OrderCount int64 `json:"order_count"`
|
||||
PaidOrderCount int64 `json:"paid_order_count"`
|
||||
PaidGMVCent int64 `json:"paid_gmv_cent"`
|
||||
ConversionRate float64 `json:"conversion_rate"` // 下单转化率 (OrderCount / max(ClickUV, 1))
|
||||
}
|
||||
|
||||
@@ -57,19 +57,19 @@ type ListTrackingLinksQuery struct {
|
||||
}
|
||||
|
||||
type TrackingOverviewStats struct {
|
||||
TotalLinks int64 `json:"total_links"`
|
||||
ActiveLinks int64 `json:"active_links"`
|
||||
TotalPV int64 `json:"total_pv"`
|
||||
TotalUV int64 `json:"total_uv"`
|
||||
TotalIP int64 `json:"total_ip"`
|
||||
TotalRegisters int64 `json:"total_registers"`
|
||||
TotalOrders int64 `json:"total_orders"`
|
||||
TotalPaidOrders int64 `json:"total_paid_orders"`
|
||||
TotalLinks int64 `json:"total_links"`
|
||||
ActiveLinks int64 `json:"active_links"`
|
||||
TotalPV int64 `json:"total_pv"`
|
||||
TotalUV int64 `json:"total_uv"`
|
||||
TotalIP int64 `json:"total_ip"`
|
||||
TotalRegisters int64 `json:"total_registers"`
|
||||
TotalOrders int64 `json:"total_orders"`
|
||||
TotalPaidOrders int64 `json:"total_paid_orders"`
|
||||
TotalPaidGMVCent int64 `json:"total_paid_gmv_cent"`
|
||||
|
||||
TodayPV int64 `json:"today_pv"`
|
||||
TodayUV int64 `json:"today_uv"`
|
||||
TodayRegisters int64 `json:"today_registers"`
|
||||
TodayOrders int64 `json:"today_orders"`
|
||||
TodayPV int64 `json:"today_pv"`
|
||||
TodayUV int64 `json:"today_uv"`
|
||||
TodayRegisters int64 `json:"today_registers"`
|
||||
TodayOrders int64 `json:"today_orders"`
|
||||
TodayPaidGMVCent int64 `json:"today_paid_gmv_cent"`
|
||||
}
|
||||
|
||||
@@ -4,20 +4,12 @@ import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestUserTokenVersionRevokesAccessAndRefreshTokens(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败:%v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.User{}); err != nil {
|
||||
t.Fatalf("数据库迁移失败:%v", err)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
|
||||
user := model.User{Phone: "13900000001", Status: "active", TokenVersion: 1}
|
||||
if err := db.Create(&user).Error; err != nil {
|
||||
|
||||
@@ -4,20 +4,16 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func setupAdminListTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.User{},
|
||||
&model.AdminUser{},
|
||||
&model.RentalListing{},
|
||||
|
||||
@@ -4,22 +4,16 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func setupConversationTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("无法创建测试数据库: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.User{},
|
||||
&model.RentalOrder{},
|
||||
&model.ChatConversation{},
|
||||
|
||||
@@ -6,22 +6,16 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func setupQrCodeTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("无法创建测试数据库: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.ChatQrCode{},
|
||||
&model.DistributionSite{},
|
||||
&model.DistributionSiteAccount{},
|
||||
|
||||
@@ -190,4 +190,3 @@ func isAllDigits(s string) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,6 @@ import (
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
@@ -705,10 +704,7 @@ func TestPartialRefundOwnerIncomeCentUnit(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败: %v", err)
|
||||
}
|
||||
db := database.NewDryRunDB()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -757,4 +753,3 @@ func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -91,49 +91,49 @@ type UpdateRuleStatusRequest struct {
|
||||
}
|
||||
|
||||
type DistributionOrderDTO struct {
|
||||
OrderID uint64 `json:"order_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
SiteID uint64 `json:"site_id"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
AccountID uint64 `json:"account_id"`
|
||||
OwnerID uint64 `json:"owner_id"`
|
||||
RenterID uint64 `json:"renter_id"`
|
||||
Status string `json:"status"`
|
||||
HandoffStatus string `json:"handoff_status"`
|
||||
RefundStatus string `json:"refund_status"`
|
||||
SettlementStatus string `json:"settlement_status"`
|
||||
DistributionMode string `json:"distribution_mode"`
|
||||
GrossPaidAmountCent int64 `json:"gross_paid_amount_cent"`
|
||||
RefundAmountCent int64 `json:"refund_amount_cent"`
|
||||
NetPaidAmountCent int64 `json:"net_paid_amount_cent"`
|
||||
PaymentFeeCent int64 `json:"payment_fee_cent"`
|
||||
ServiceFeeCent int64 `json:"service_fee_cent"`
|
||||
MarkupAmountCent int64 `json:"markup_amount_cent"`
|
||||
TaxAmountCent int64 `json:"tax_amount_cent"`
|
||||
SplitBaseAmountCent int64 `json:"split_base_amount_cent"`
|
||||
RoundingAdjustmentCent int64 `json:"rounding_adjustment_cent"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
OrderID uint64 `json:"order_id"`
|
||||
OrderNo string `json:"order_no"`
|
||||
SiteID uint64 `json:"site_id"`
|
||||
ListingID uint64 `json:"listing_id"`
|
||||
AccountID uint64 `json:"account_id"`
|
||||
OwnerID uint64 `json:"owner_id"`
|
||||
RenterID uint64 `json:"renter_id"`
|
||||
Status string `json:"status"`
|
||||
HandoffStatus string `json:"handoff_status"`
|
||||
RefundStatus string `json:"refund_status"`
|
||||
SettlementStatus string `json:"settlement_status"`
|
||||
DistributionMode string `json:"distribution_mode"`
|
||||
GrossPaidAmountCent int64 `json:"gross_paid_amount_cent"`
|
||||
RefundAmountCent int64 `json:"refund_amount_cent"`
|
||||
NetPaidAmountCent int64 `json:"net_paid_amount_cent"`
|
||||
PaymentFeeCent int64 `json:"payment_fee_cent"`
|
||||
ServiceFeeCent int64 `json:"service_fee_cent"`
|
||||
MarkupAmountCent int64 `json:"markup_amount_cent"`
|
||||
TaxAmountCent int64 `json:"tax_amount_cent"`
|
||||
SplitBaseAmountCent int64 `json:"split_base_amount_cent"`
|
||||
RoundingAdjustmentCent int64 `json:"rounding_adjustment_cent"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
|
||||
// 关联业务与分销商收益透传字段
|
||||
ListingNo string `json:"listing_no,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
GameName string `json:"game_name,omitempty"`
|
||||
ServerRegion string `json:"server_region,omitempty"`
|
||||
LoginPlatform string `json:"login_platform,omitempty"`
|
||||
RentDurationHours int `json:"rent_duration_hours,omitempty"`
|
||||
RentedAt *time.Time `json:"rented_at,omitempty"`
|
||||
RenterPhone string `json:"renter_phone,omitempty"`
|
||||
RenterNickname string `json:"renter_nickname,omitempty"`
|
||||
OwnerRentAmountCent int64 `json:"owner_rent_amount_cent,omitempty"`
|
||||
BasePriceCent int64 `json:"base_price_cent,omitempty"`
|
||||
ShelfMarkupCent int64 `json:"shelf_markup_cent,omitempty"`
|
||||
DepositAmountCent int64 `json:"deposit_amount_cent,omitempty"`
|
||||
ListingNo string `json:"listing_no,omitempty"`
|
||||
Title string `json:"title,omitempty"`
|
||||
GameName string `json:"game_name,omitempty"`
|
||||
ServerRegion string `json:"server_region,omitempty"`
|
||||
LoginPlatform string `json:"login_platform,omitempty"`
|
||||
RentDurationHours int `json:"rent_duration_hours,omitempty"`
|
||||
RentedAt *time.Time `json:"rented_at,omitempty"`
|
||||
RenterPhone string `json:"renter_phone,omitempty"`
|
||||
RenterNickname string `json:"renter_nickname,omitempty"`
|
||||
OwnerRentAmountCent int64 `json:"owner_rent_amount_cent,omitempty"`
|
||||
BasePriceCent int64 `json:"base_price_cent,omitempty"`
|
||||
ShelfMarkupCent int64 `json:"shelf_markup_cent,omitempty"`
|
||||
DepositAmountCent int64 `json:"deposit_amount_cent,omitempty"`
|
||||
|
||||
// 当前分销商在该订单中的收益拆解
|
||||
DistributorEarningCent int64 `json:"distributor_earning_cent"`
|
||||
DistributorRole string `json:"distributor_role,omitempty"`
|
||||
DistributorMarkupCent int64 `json:"distributor_markup_cent"`
|
||||
DistributorSplitCent int64 `json:"distributor_split_cent"`
|
||||
DistributorEarningCent int64 `json:"distributor_earning_cent"`
|
||||
DistributorRole string `json:"distributor_role,omitempty"`
|
||||
DistributorMarkupCent int64 `json:"distributor_markup_cent"`
|
||||
DistributorSplitCent int64 `json:"distributor_split_cent"`
|
||||
}
|
||||
|
||||
type DistributionOrderListQuery struct {
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
@@ -402,7 +403,7 @@ func TestSnapshotPaidOrderTxSplitsPercentOfProfit(t *testing.T) {
|
||||
|
||||
func TestApplyRefundTxWithCheckoutAndDeposit(t *testing.T) {
|
||||
db := distributionTestDB(t)
|
||||
if err := db.AutoMigrate(&model.OrderCheckout{}); err != nil {
|
||||
if err := database.AutoMigrateIfMissing(db, &model.OrderCheckout{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Now()
|
||||
@@ -471,4 +472,3 @@ func TestApplyRefundTxWithCheckoutAndDeposit(t *testing.T) {
|
||||
t.Fatalf("distributorParty.IncomeAmountCent = %d, want 2420", distributorParty.IncomeAmountCent)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -145,6 +145,17 @@ func (r *Repository) ScopeSiteID(ctx context.Context, adminID, requested uint64)
|
||||
|
||||
// ensureSiteAccess 校验管理员可访问指定站点。
|
||||
// 仅超级管理员或持有 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 {
|
||||
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,
|
||||
ServiceFeeValue: parsed.ServiceFeeValue, ServiceFeeUnit: parsed.ServiceFeeUnit,
|
||||
PaymentFeeBPS: req.PaymentFeeBPS, TaxEnabled: req.TaxEnabled, TaxRateBPS: req.TaxRateBPS,
|
||||
EffectiveFrom: effectiveFrom, CreatedBy: &adminID,
|
||||
EffectiveFrom: effectiveFrom, CreatedBy: adminRef(adminID),
|
||||
}
|
||||
if row.PaymentFeeBPS == 0 {
|
||||
row.PaymentFeeBPS = 50
|
||||
@@ -911,7 +922,7 @@ func (r *Repository) CreateSettlementBatch(ctx context.Context, adminID uint64,
|
||||
}
|
||||
var batch model.DistributionSettlementBatch
|
||||
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 {
|
||||
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")
|
||||
dateFormatExpr := "DATE_FORMAT(ro.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)
|
||||
_ = r.db.WithContext(ctx).Table("rental_orders ro").
|
||||
Joins("JOIN distribution_order_financials f ON f.order_id = ro.id").
|
||||
|
||||
@@ -5,19 +5,16 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func distributionTestDB(t *testing.T) *gorm.DB {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.AdminUser{}, &model.Role{}, &model.Permission{}, &model.AdminUserRole{}, &model.RolePermission{},
|
||||
&model.ChatConversation{}, &model.RentalOrder{},
|
||||
&model.AuditLog{}, &model.PaymentMerchantConfig{}, &model.DistributionSite{},
|
||||
@@ -29,6 +26,16 @@ func distributionTestDB(t *testing.T) *gorm.DB {
|
||||
); err != nil {
|
||||
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
|
||||
}
|
||||
|
||||
@@ -948,7 +955,24 @@ func TestLiveMoneyMovementFrozenInProduction(t *testing.T) {
|
||||
if err := db.Create(&batch).Error; err != nil {
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -4,8 +4,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"hfb_sys/backend/internal/database"
|
||||
)
|
||||
|
||||
func TestFilterAdminListingsByAssetLevels(t *testing.T) {
|
||||
@@ -100,10 +99,7 @@ func TestFilterAdminListingsBySkinGroupOnly(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败: %v", err)
|
||||
}
|
||||
db := database.NewDryRunDB()
|
||||
repo := &Repository{}
|
||||
|
||||
tests := []struct {
|
||||
@@ -143,4 +139,3 @@ func TestApplyAdminListFiltersSmartRouting(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -128,34 +128,34 @@ type AdminListResult struct {
|
||||
}
|
||||
|
||||
type PublicListQuery struct {
|
||||
Page int
|
||||
PageSize int
|
||||
Keyword string
|
||||
Sort string
|
||||
Zone string
|
||||
Server []string
|
||||
Region []string
|
||||
LoginMethod []string
|
||||
Rank []string
|
||||
Insurance []string
|
||||
Stamina []string
|
||||
Load []string
|
||||
SkinGroup []string
|
||||
SkinName []string
|
||||
MinCoin *float64
|
||||
MaxCoin *float64
|
||||
MinRatio *float64
|
||||
MaxRatio *float64
|
||||
MinPrice *float64
|
||||
MaxPrice *float64
|
||||
MinDeposit *float64
|
||||
MaxDeposit *float64
|
||||
MinTotal *float64
|
||||
MaxTotal *float64
|
||||
MinFireLevel *float64
|
||||
MaxFireLevel *float64
|
||||
MinDailyLoss *float64
|
||||
MaxDailyLoss *float64
|
||||
Page int
|
||||
PageSize int
|
||||
Keyword string
|
||||
Sort string
|
||||
Zone string
|
||||
Server []string
|
||||
Region []string
|
||||
LoginMethod []string
|
||||
Rank []string
|
||||
Insurance []string
|
||||
Stamina []string
|
||||
Load []string
|
||||
SkinGroup []string
|
||||
SkinName []string
|
||||
MinCoin *float64
|
||||
MaxCoin *float64
|
||||
MinRatio *float64
|
||||
MaxRatio *float64
|
||||
MinPrice *float64
|
||||
MaxPrice *float64
|
||||
MinDeposit *float64
|
||||
MaxDeposit *float64
|
||||
MinTotal *float64
|
||||
MaxTotal *float64
|
||||
MinFireLevel *float64
|
||||
MaxFireLevel *float64
|
||||
MinDailyLoss *float64
|
||||
MaxDailyLoss *float64
|
||||
MinSecretKD *float64
|
||||
MaxSecretKD *float64
|
||||
ResourceRanges map[string]NumberRange
|
||||
|
||||
@@ -209,7 +209,7 @@ func newExternalAdjustmentFixture(
|
||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||
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)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -15,21 +15,21 @@ import (
|
||||
|
||||
type listingRow struct {
|
||||
model.RentalListing
|
||||
Title string
|
||||
OwnerPhone string
|
||||
OwnerNickname string
|
||||
Title string
|
||||
OwnerPhone string
|
||||
OwnerNickname string
|
||||
DisplaySourceChannel string `gorm:"column:display_source_channel"`
|
||||
IsExternalUpload bool `gorm:"column:is_external_upload"`
|
||||
DistributionSiteCode string `gorm:"column:distribution_site_code"`
|
||||
DistributionSiteName string `gorm:"column:distribution_site_name"`
|
||||
Description string
|
||||
GameName string
|
||||
ServerRegion string
|
||||
LoginPlatform string
|
||||
RankLevel string
|
||||
HafCoinAmount int64
|
||||
AssetSummary datatypes.JSON `gorm:"column:asset_summary"`
|
||||
ScreenshotURLS datatypes.JSON `gorm:"column:screenshot_urls"`
|
||||
Description string
|
||||
GameName string
|
||||
ServerRegion string
|
||||
LoginPlatform string
|
||||
RankLevel string
|
||||
HafCoinAmount int64
|
||||
AssetSummary datatypes.JSON `gorm:"column:asset_summary"`
|
||||
ScreenshotURLS datatypes.JSON `gorm:"column:screenshot_urls"`
|
||||
}
|
||||
|
||||
func rowsToDTO(rows []listingRow) []ListingDTO {
|
||||
@@ -165,32 +165,32 @@ func (row listingRow) toDTO() ListingDTO {
|
||||
screenshotURLS := cleanScreenshotURLs(decodeScreenshots(row.ScreenshotURLS))
|
||||
reviewStatus, reviewReason := normalizedReviewState(row.Status, row.ReviewStatus, row.ReviewReason)
|
||||
return ListingDTO{
|
||||
ID: row.ID,
|
||||
ListingNo: row.ListingNo,
|
||||
AccountID: row.AccountID,
|
||||
OwnerID: row.OwnerID,
|
||||
OwnerPhone: row.OwnerPhone,
|
||||
OwnerNickname: row.OwnerNickname,
|
||||
SourceChannel: row.DisplaySourceChannel,
|
||||
IsExternalUpload: row.IsExternalUpload,
|
||||
Title: row.Title,
|
||||
Description: row.Description,
|
||||
GameName: row.GameName,
|
||||
ServerRegion: row.ServerRegion,
|
||||
LoginPlatform: row.LoginPlatform,
|
||||
RankLevel: row.RankLevel,
|
||||
HafCoinAmount: row.HafCoinAmount,
|
||||
AssetSummary: assetSummary,
|
||||
ScreenshotURLS: screenshotURLS,
|
||||
CoverURL: publicCoverURL(row.ID, screenshotURLS, row.Status, row.ReviewStatus),
|
||||
PriceCent: row.PriceCent,
|
||||
DepositAmountCent: row.DepositAmountCent,
|
||||
IsAccelerated: isAcceleratedSale(assetSummary),
|
||||
InTransaction: row.InTransaction,
|
||||
Status: row.Status,
|
||||
ReviewStatus: reviewStatus,
|
||||
HandoffMode: row.HandoffMode,
|
||||
SettlementMode: row.SettlementMode,
|
||||
ID: row.ID,
|
||||
ListingNo: row.ListingNo,
|
||||
AccountID: row.AccountID,
|
||||
OwnerID: row.OwnerID,
|
||||
OwnerPhone: row.OwnerPhone,
|
||||
OwnerNickname: row.OwnerNickname,
|
||||
SourceChannel: row.DisplaySourceChannel,
|
||||
IsExternalUpload: row.IsExternalUpload,
|
||||
Title: row.Title,
|
||||
Description: row.Description,
|
||||
GameName: row.GameName,
|
||||
ServerRegion: row.ServerRegion,
|
||||
LoginPlatform: row.LoginPlatform,
|
||||
RankLevel: row.RankLevel,
|
||||
HafCoinAmount: row.HafCoinAmount,
|
||||
AssetSummary: assetSummary,
|
||||
ScreenshotURLS: screenshotURLS,
|
||||
CoverURL: publicCoverURL(row.ID, screenshotURLS, row.Status, row.ReviewStatus),
|
||||
PriceCent: row.PriceCent,
|
||||
DepositAmountCent: row.DepositAmountCent,
|
||||
IsAccelerated: isAcceleratedSale(assetSummary),
|
||||
InTransaction: row.InTransaction,
|
||||
Status: row.Status,
|
||||
ReviewStatus: reviewStatus,
|
||||
HandoffMode: row.HandoffMode,
|
||||
SettlementMode: row.SettlementMode,
|
||||
ManagedAdminID: row.ManagedAdminID,
|
||||
DistributionSiteID: row.DistributionSiteID,
|
||||
DistributionSiteCode: row.DistributionSiteCode,
|
||||
|
||||
@@ -299,4 +299,3 @@ func isAllDigits(s string) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -434,4 +434,3 @@ func (r *Repository) UpdateScreenshots(ctx context.Context, adminID uint64, list
|
||||
})
|
||||
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)
|
||||
}
|
||||
|
||||
|
||||
@@ -384,7 +384,7 @@ func TestImportExternalUploadStoresSourceChannel(t *testing.T) {
|
||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||
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)
|
||||
}
|
||||
admin := model.AdminUser{
|
||||
@@ -424,7 +424,7 @@ func TestListPendingReviewIncludesSourceChannel(t *testing.T) {
|
||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||
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)
|
||||
}
|
||||
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 {
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -774,7 +774,7 @@ func TestUpdateScreenshots(t *testing.T) {
|
||||
if err := database.MigrateListingLifecycleTestSchema(db); err != nil {
|
||||
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)
|
||||
}
|
||||
repo := NewRepository(db, nil)
|
||||
|
||||
@@ -3,11 +3,11 @@ package notification
|
||||
import "time"
|
||||
|
||||
type NotificationDTO struct {
|
||||
ID uint64 `json:"id"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
ID uint64 `json:"id"`
|
||||
UserID uint64 `json:"user_id"`
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Content string `json:"content"`
|
||||
BizType string `json:"biz_type"`
|
||||
BizID *uint64 `json:"biz_id"`
|
||||
DistributionSiteID *uint64 `json:"distribution_site_id,omitempty"`
|
||||
|
||||
@@ -206,4 +206,3 @@ func toDTO(row model.Notification) NotificationDTO {
|
||||
CreatedAt: row.CreatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
|
||||
func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -53,7 +53,7 @@ func TestRepositoryUnreadCountAndMarkRead(t *testing.T) {
|
||||
|
||||
func TestRepositoryMarkReadNotFound(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -66,7 +66,7 @@ func TestRepositoryMarkReadNotFound(t *testing.T) {
|
||||
|
||||
func TestNotificationTenantIsolation(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
|
||||
@@ -279,7 +279,7 @@ func TestRepositoryCreateAppliesRenterGrowthDiscount(t *testing.T) {
|
||||
|
||||
func TestCreateOrderSnapshotsShelfMarkup(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -859,7 +859,7 @@ func TestCancelPendingHandoffKeepsAssetsUntilRefundApproved(t *testing.T) {
|
||||
t.Fatalf("create account failed: %v", err)
|
||||
}
|
||||
listing := model.RentalListing{
|
||||
ListingNo: "LST-REFUND-REVIEW-001",
|
||||
ListingNo: "LST-REFUND-REV-001",
|
||||
OwnerID: owner.ID,
|
||||
AccountID: account.ID,
|
||||
Status: listingStatusRented,
|
||||
@@ -1319,7 +1319,7 @@ func TestAdminResetRenterConfirmTimeoutRefreshesStageTime(t *testing.T) {
|
||||
|
||||
func TestAdminForceHandoffStartsNormalOwnerOrder(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -1387,7 +1387,7 @@ func TestAdminForceHandoffStartsNormalOwnerOrder(t *testing.T) {
|
||||
|
||||
func TestAdminForceHandoffAbnormalOwnerTimeout(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -1460,26 +1460,26 @@ func TestOwnerConfirmCheckoutAfterTimeout(t *testing.T) {
|
||||
}
|
||||
|
||||
listing := model.RentalListing{
|
||||
OwnerID: owner.ID,
|
||||
AccountID: account.ID,
|
||||
Status: listingStatusRented,
|
||||
ReviewStatus: listingReviewStatusApproved,
|
||||
PriceCent: 1000,
|
||||
OwnerID: owner.ID,
|
||||
AccountID: account.ID,
|
||||
Status: listingStatusRented,
|
||||
ReviewStatus: listingReviewStatusApproved,
|
||||
PriceCent: 1000,
|
||||
}
|
||||
if err := db.Create(&listing).Error; err != nil {
|
||||
t.Fatalf("create listing failed: %v", err)
|
||||
}
|
||||
|
||||
order := model.RentalOrder{
|
||||
OrderNo: "ORD-CHECKOUT-TIMEOUT-001",
|
||||
ListingID: listing.ID,
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
RenterID: renter.ID,
|
||||
Status: orderStatusAbnormal,
|
||||
HandoffStatus: handoffStatusOwnerCheckoutConfirmTimeout,
|
||||
SettlementStatus: settlementStatusPending,
|
||||
RentAmountCent: 1000,
|
||||
OrderNo: "ORD-CHECKOUT-TIMEOUT-001",
|
||||
ListingID: listing.ID,
|
||||
AccountID: account.ID,
|
||||
OwnerID: owner.ID,
|
||||
RenterID: renter.ID,
|
||||
Status: orderStatusAbnormal,
|
||||
HandoffStatus: handoffStatusOwnerCheckoutConfirmTimeout,
|
||||
SettlementStatus: settlementStatusPending,
|
||||
RentAmountCent: 1000,
|
||||
DepositAmountCent: 0,
|
||||
}
|
||||
if err := db.Create(&order).Error; err != nil {
|
||||
@@ -1526,7 +1526,7 @@ func TestOwnerConfirmCheckoutAfterTimeout(t *testing.T) {
|
||||
|
||||
func TestAdminForceHandoffUsesExistingOwnerRecordAndRejectsPlatformOrderBeforeHandoff(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -1607,7 +1607,7 @@ func TestAdminForceHandoffUsesExistingOwnerRecordAndRejectsPlatformOrderBeforeHa
|
||||
|
||||
func TestAdminForceHandoffStartsPlatformManagedOrderAfterPlatformHandoff(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -2017,7 +2017,7 @@ func TestPlatformManagedCheckoutIncludesConsumableAndDepositCompensation(t *test
|
||||
|
||||
func TestAdminPlatformCheckoutDisputeCreatesArbitrationCase(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
@@ -2217,7 +2217,7 @@ func TestAdminPlatformCheckoutConfirmRequiresExplicitConfirmationForZeroOwnerInc
|
||||
|
||||
func TestListForUserAndFindForUserSiteIsolation(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db)
|
||||
|
||||
@@ -5,13 +5,12 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/rentergrowth"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func pureCoinDiscountOrder() model.RentalOrder {
|
||||
@@ -504,10 +503,7 @@ func TestNewOrderNoUsesShanghaiTimeWhenLocalIsUTC(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestApplyAdminOrderFiltersSmartRouting(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败: %v", err)
|
||||
}
|
||||
db := database.NewDryRunDB()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -519,7 +519,7 @@ func TestStartRefundDoesNotCreateNewOrderWhenFailedRefundExists(t *testing.T) {
|
||||
|
||||
func TestStartMohongRefundDefaultsFullAmountForCancelledPaidOrder(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db, nil, nil)
|
||||
@@ -576,7 +576,7 @@ func TestStartMohongRefundDefaultsFullAmountForCancelledPaidOrder(t *testing.T)
|
||||
|
||||
func TestStartMohongRefundRequiresCancelledOrder(t *testing.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)
|
||||
}
|
||||
repo := NewRepository(db, nil, nil)
|
||||
@@ -697,18 +697,18 @@ func TestConfirmPaidRollsBackOrderWhenPaymentUpdateFails(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestConcurrentPaidNotificationsAreIdempotent(t *testing.T) {
|
||||
db := database.NewTestDBWithName("payment-concurrent")
|
||||
db := database.NewTestDB()
|
||||
if err := database.MigrateRentalTransactionTestSchema(db); err != nil {
|
||||
t.Fatalf("数据库迁移失败: %v", err)
|
||||
}
|
||||
sqlDB, err := db.DB()
|
||||
if err != nil {
|
||||
t.Fatalf("get sqlite db: %v", err)
|
||||
t.Fatalf("获取底层连接失败: %v", err)
|
||||
}
|
||||
sqlDB.SetMaxOpenConns(8)
|
||||
orderRepo := ordermodule.NewRepository(db)
|
||||
repo := NewRepository(db, nil, orderRepo)
|
||||
fixture := createPayableOrderFixture(t, db, "CONCURRENT", true)
|
||||
fixture := createPayableOrderFixture(t, db, "CONC", true)
|
||||
params := map[string]string{
|
||||
"third_order_id": fixture.Payment.ThirdOrderID,
|
||||
"status": "paid",
|
||||
|
||||
@@ -9,7 +9,7 @@ type PaymentAccountDTO struct {
|
||||
UserID uint64 `json:"user_id"`
|
||||
AccountType string `json:"account_type"`
|
||||
AccountName string `json:"account_name"`
|
||||
AccountNo string `json:"account_no"` // 脱敏显示
|
||||
AccountNo string `json:"account_no"` // 脱敏显示
|
||||
BankName string `json:"bank_name"`
|
||||
BankBranch string `json:"bank_branch"`
|
||||
CertificateURLs []string `json:"certificate_urls"`
|
||||
|
||||
@@ -5,11 +5,8 @@ import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func TestPrivateCertificateURLsConvertsLegacyPublicURL(t *testing.T) {
|
||||
@@ -26,11 +23,8 @@ func TestPrivateCertificateURLsConvertsLegacyPublicURL(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestValidateCertificateURLsRequiresUploaderOwnership(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite error = %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.FileUploadOwner{}); err != nil {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db, &model.FileUploadOwner{}); err != nil {
|
||||
t.Fatalf("migrate upload owners error = %v", err)
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
// Scan 兼容 MySQL 的 time.Time 和 SQLite 聚合函数返回的字符串时间。
|
||||
// Scan 兼容 MySQL 聚合函数可能返回的 time.Time 与字符串时间。
|
||||
func (nt *nullableTime) Scan(value any) error {
|
||||
switch v := value.(type) {
|
||||
case nil:
|
||||
|
||||
@@ -4,11 +4,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func TestImportCreateRequestKeepsOneActiveConfigPerPayWay(t *testing.T) {
|
||||
@@ -72,11 +69,8 @@ func TestValidateCreateRequestRequiresShunchengSecretID(t *testing.T) {
|
||||
|
||||
// TestListUsesSuccessfulPaymentStats 验证配置页只统计成功支付,不把打开二维码或取消订单算作成交。
|
||||
func TestListUsesSuccessfulPaymentStats(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
if err != nil {
|
||||
t.Fatalf("open db failed: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.PaymentMerchantConfig{}, &model.PaymentOrder{}); err != nil {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db, &model.PaymentMerchantConfig{}, &model.PaymentOrder{}); err != nil {
|
||||
t.Fatalf("migrate failed: %v", err)
|
||||
}
|
||||
config := model.PaymentMerchantConfig{
|
||||
|
||||
@@ -1349,4 +1349,3 @@ func isAllDigits(s string) bool {
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -7,12 +7,11 @@ import (
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/auditlog"
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/datatypes"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func TestBuildPickupPriceSnapshotSplitsOwnerPrice(t *testing.T) {
|
||||
@@ -341,7 +340,7 @@ func TestRepositoryCreateSnapshotsExternalAccountSource(t *testing.T) {
|
||||
|
||||
func TestRepositoryCompleteInternalPickupCreditsWallet(t *testing.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{})
|
||||
if err != nil {
|
||||
t.Fatalf("Create() error = %v", err)
|
||||
@@ -367,7 +366,7 @@ func TestRepositoryCompleteInternalPickupCreditsWallet(t *testing.T) {
|
||||
|
||||
func TestRepositoryCompletePlatformManagedPickupUsesOfflineSettlement(t *testing.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{
|
||||
UploaderName: "外部号主",
|
||||
SourceChannel: "闲鱼",
|
||||
@@ -558,7 +557,7 @@ func TestRepositoryFinancialAdjustmentSettlesPlatformManagedPickupSeparately(t *
|
||||
|
||||
func TestRepositoryOfflineSettlementProcessesPendingPickupAdjustments(t *testing.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 {
|
||||
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) {
|
||||
t.Helper()
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.User{},
|
||||
&model.AdminUser{},
|
||||
&model.GameAccount{},
|
||||
@@ -718,10 +712,7 @@ func seedPickup(t *testing.T, db *gorm.DB, status string) model.AdminPickup {
|
||||
}
|
||||
|
||||
func TestApplyAdminPickupFiltersSmartRouting(t *testing.T) {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{DryRun: true})
|
||||
if err != nil {
|
||||
t.Fatalf("打开测试数据库失败: %v", err)
|
||||
}
|
||||
db := database.NewDryRunDB()
|
||||
|
||||
tests := []struct {
|
||||
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) {
|
||||
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)
|
||||
}
|
||||
user := model.User{Phone: "13800009999", RenterGrowthPoints: 1000, DepositFreeQuotaCent: 30_000}
|
||||
@@ -72,7 +72,7 @@ func TestSnapshotCombinesLevelAndManualDepositQuota(t *testing.T) {
|
||||
|
||||
func TestSyncAllUserLevelsUsesUpdatedThresholds(t *testing.T) {
|
||||
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)
|
||||
}
|
||||
users := []model.User{
|
||||
@@ -128,7 +128,7 @@ func TestCalculateDiscountCentCapsAtPlatformFee(t *testing.T) {
|
||||
|
||||
func TestAwardOrderCompletedUpdatesUserAndIsIdempotent(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := db.AutoMigrate(
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.User{},
|
||||
&model.RentalOrder{},
|
||||
&model.SystemConfig{},
|
||||
@@ -212,7 +212,7 @@ func TestAwardOrderCompletedUpdatesUserAndIsIdempotent(t *testing.T) {
|
||||
|
||||
func TestRevokeOrderCompletedRecordsIdempotencyWhenUserHasNoPoints(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
if err := db.AutoMigrate(
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.User{},
|
||||
&model.RentalOrder{},
|
||||
&model.SystemConfig{},
|
||||
|
||||
@@ -6,23 +6,16 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
func newTestSystemConfigRepo(t *testing.T) (*Repository, *gorm.DB) {
|
||||
t.Helper()
|
||||
dsn := fmt.Sprintf("file:%s?mode=memory&cache=shared", t.Name())
|
||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("连接测试数据库失败: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(&model.SystemConfig{}); err != nil {
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db, &model.SystemConfig{}); err != nil {
|
||||
t.Fatalf("自动迁移 SystemConfig 失败: %v", err)
|
||||
}
|
||||
return NewRepository(db), db
|
||||
|
||||
@@ -4,24 +4,18 @@ import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
// setupTestDB 创建测试数据库连接(使用内存 SQLite)
|
||||
// setupTestDB 创建测试数据库连接(MySQL 测试库)
|
||||
func setupTestDB(t *testing.T) *gorm.DB {
|
||||
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{
|
||||
Logger: logger.Default.LogMode(logger.Silent),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("无法创建测试数据库连接: %v", err)
|
||||
}
|
||||
db := database.NewTestDB()
|
||||
|
||||
// 迁移必要的表
|
||||
if err := db.AutoMigrate(
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.WalletAccount{},
|
||||
&model.WalletLedger{},
|
||||
&model.DistributionSite{},
|
||||
|
||||
@@ -33,28 +33,28 @@ type WithdrawalDetailDTO struct {
|
||||
DistributionSiteID uint64 `json:"distribution_site_id"`
|
||||
UserNickname string `json:"user_nickname"`
|
||||
UserPhone string `json:"user_phone"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
FeeCent int64 `json:"fee_cent"`
|
||||
ActualAmountCent int64 `json:"actual_amount_cent"`
|
||||
PaymentAccountID *uint64 `json:"payment_account_id"`
|
||||
AccountType string `json:"account_type"`
|
||||
AccountName string `json:"account_name"`
|
||||
AccountNo string `json:"account_no"` // 管理员可见完整账号
|
||||
BankName string `json:"bank_name"`
|
||||
BankBranch string `json:"bank_branch"`
|
||||
CertificateURLs []string `json:"certificate_urls"` // 收款二维码图片
|
||||
Status string `json:"status"`
|
||||
ReviewedBy *uint64 `json:"reviewed_by"`
|
||||
ReviewedByName string `json:"reviewed_by_name"`
|
||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||
ReviewRemark string `json:"review_remark"`
|
||||
PaidBy *uint64 `json:"paid_by"`
|
||||
PaidByName string `json:"paid_by_name"`
|
||||
PaidAt *time.Time `json:"paid_at"`
|
||||
PaymentProofURL string `json:"payment_proof_url"`
|
||||
PaymentRemark string `json:"payment_remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
AmountCent int64 `json:"amount_cent"`
|
||||
FeeCent int64 `json:"fee_cent"`
|
||||
ActualAmountCent int64 `json:"actual_amount_cent"`
|
||||
PaymentAccountID *uint64 `json:"payment_account_id"`
|
||||
AccountType string `json:"account_type"`
|
||||
AccountName string `json:"account_name"`
|
||||
AccountNo string `json:"account_no"` // 管理员可见完整账号
|
||||
BankName string `json:"bank_name"`
|
||||
BankBranch string `json:"bank_branch"`
|
||||
CertificateURLs []string `json:"certificate_urls"` // 收款二维码图片
|
||||
Status string `json:"status"`
|
||||
ReviewedBy *uint64 `json:"reviewed_by"`
|
||||
ReviewedByName string `json:"reviewed_by_name"`
|
||||
ReviewedAt *time.Time `json:"reviewed_at"`
|
||||
ReviewRemark string `json:"review_remark"`
|
||||
PaidBy *uint64 `json:"paid_by"`
|
||||
PaidByName string `json:"paid_by_name"`
|
||||
PaidAt *time.Time `json:"paid_at"`
|
||||
PaymentProofURL string `json:"payment_proof_url"`
|
||||
PaymentRemark string `json:"payment_remark"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type CreateWithdrawalRequest struct {
|
||||
|
||||
@@ -81,29 +81,29 @@ func (r *Repository) toDetailDTO(ctx context.Context, w model.WithdrawalRequest)
|
||||
UserID: w.UserID,
|
||||
DistributionSiteID: w.DistributionSiteID,
|
||||
UserNickname: user.Nickname,
|
||||
UserPhone: user.Phone,
|
||||
AmountCent: w.AmountCent,
|
||||
FeeCent: w.FeeCent,
|
||||
ActualAmountCent: w.ActualAmountCent,
|
||||
PaymentAccountID: w.PaymentAccountID,
|
||||
AccountType: w.AccountType,
|
||||
AccountName: w.AccountName,
|
||||
AccountNo: fullAccountNo,
|
||||
BankName: w.BankName,
|
||||
BankBranch: w.BankBranch,
|
||||
CertificateURLs: certificateURLs,
|
||||
Status: w.Status,
|
||||
ReviewedBy: w.ReviewedBy,
|
||||
ReviewedByName: reviewedByName,
|
||||
ReviewedAt: w.ReviewedAt,
|
||||
ReviewRemark: w.ReviewRemark,
|
||||
PaidBy: w.PaidBy,
|
||||
PaidByName: paidByName,
|
||||
PaidAt: w.PaidAt,
|
||||
PaymentProofURL: w.PaymentProofURL,
|
||||
PaymentRemark: w.PaymentRemark,
|
||||
CreatedAt: w.CreatedAt,
|
||||
UpdatedAt: w.UpdatedAt,
|
||||
UserPhone: user.Phone,
|
||||
AmountCent: w.AmountCent,
|
||||
FeeCent: w.FeeCent,
|
||||
ActualAmountCent: w.ActualAmountCent,
|
||||
PaymentAccountID: w.PaymentAccountID,
|
||||
AccountType: w.AccountType,
|
||||
AccountName: w.AccountName,
|
||||
AccountNo: fullAccountNo,
|
||||
BankName: w.BankName,
|
||||
BankBranch: w.BankBranch,
|
||||
CertificateURLs: certificateURLs,
|
||||
Status: w.Status,
|
||||
ReviewedBy: w.ReviewedBy,
|
||||
ReviewedByName: reviewedByName,
|
||||
ReviewedAt: w.ReviewedAt,
|
||||
ReviewRemark: w.ReviewRemark,
|
||||
PaidBy: w.PaidBy,
|
||||
PaidByName: paidByName,
|
||||
PaidAt: w.PaidAt,
|
||||
PaymentProofURL: w.PaymentProofURL,
|
||||
PaymentRemark: w.PaymentRemark,
|
||||
CreatedAt: w.CreatedAt,
|
||||
UpdatedAt: w.UpdatedAt,
|
||||
}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -3,16 +3,14 @@ package withdrawal
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/modules/wallet"
|
||||
"hfb_sys/backend/pkg/crypto"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/logger"
|
||||
)
|
||||
|
||||
type withdrawalFixture struct {
|
||||
@@ -25,12 +23,8 @@ type withdrawalFixture struct {
|
||||
|
||||
func newWithdrawalFixture(t *testing.T) withdrawalFixture {
|
||||
t.Helper()
|
||||
dsn := fmt.Sprintf("file:withdrawal-%s?mode=memory&cache=shared", t.Name())
|
||||
db, err := gorm.Open(sqlite.Open(dsn), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite: %v", err)
|
||||
}
|
||||
if err := db.AutoMigrate(
|
||||
db := database.NewTestDB()
|
||||
if err := database.AutoMigrateIfMissing(db,
|
||||
&model.User{},
|
||||
&model.AdminUser{},
|
||||
&model.UserPaymentAccount{},
|
||||
|
||||
Reference in New Issue
Block a user