fix: close business flow regressions
This commit is contained in:
@@ -179,11 +179,10 @@ func migrateDatabase() error {
|
||||
if config.Spec.Databases == nil {
|
||||
return fmt.Errorf("database configuration is required")
|
||||
}
|
||||
var migrationDatabase interface {
|
||||
Migrator() gorm.Migrator
|
||||
}
|
||||
var migrationDatabase *gorm.DB
|
||||
var err error
|
||||
switch strings.ToLower(config.Spec.Databases.Driver) {
|
||||
driver := strings.ToLower(config.Spec.Databases.Driver)
|
||||
switch driver {
|
||||
case "postgres":
|
||||
migrationDatabase, err = database.NewPostgres(config.Spec.Databases.Source, nil)
|
||||
case "mysql":
|
||||
@@ -194,6 +193,9 @@ func migrateDatabase() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("connect database before migration: %w", err)
|
||||
}
|
||||
if err := prepareAdditiveMigrations(migrationDatabase, driver); err != nil {
|
||||
return err
|
||||
}
|
||||
const legacyPhoneIndex = "idx_platform_account_phone"
|
||||
if migrationDatabase.Migrator().HasIndex(&models.PlatformAccount{}, legacyPhoneIndex) {
|
||||
if err := migrationDatabase.Migrator().DropIndex(&models.PlatformAccount{}, legacyPhoneIndex); err != nil {
|
||||
@@ -210,3 +212,41 @@ func migrateDatabase() error {
|
||||
}
|
||||
return initdb.New(databaseService)
|
||||
}
|
||||
|
||||
// prepareAdditiveMigrations 先处理无法由 GORM AutoMigrate 安全完成的新增非空字段。
|
||||
// 旧轨迹没有服务端接收时间时,以定位发生时间(再退化到创建时间)回填,
|
||||
// 避免直接 ADD NOT NULL 因历史行存在而中断整库迁移。
|
||||
func prepareAdditiveMigrations(databaseService *gorm.DB, driver string) error {
|
||||
if !databaseService.Migrator().HasTable(&models.GasorderTrackPoint{}) {
|
||||
return nil
|
||||
}
|
||||
|
||||
var statements []string
|
||||
hasReceivedAt := databaseService.Migrator().HasColumn(&models.GasorderTrackPoint{}, "received_at")
|
||||
switch driver {
|
||||
case "postgres":
|
||||
if !hasReceivedAt {
|
||||
statements = append(statements, `ALTER TABLE "gasorder_track_point" ADD COLUMN "received_at" timestamptz`)
|
||||
}
|
||||
statements = append(statements,
|
||||
`UPDATE "gasorder_track_point" SET "received_at" = COALESCE("occurred_at", "created_at", CURRENT_TIMESTAMP) WHERE "received_at" IS NULL`,
|
||||
`ALTER TABLE "gasorder_track_point" ALTER COLUMN "received_at" SET NOT NULL`,
|
||||
)
|
||||
case "mysql":
|
||||
if !hasReceivedAt {
|
||||
statements = append(statements, "ALTER TABLE `gasorder_track_point` ADD COLUMN `received_at` datetime(3) NULL")
|
||||
}
|
||||
statements = append(statements,
|
||||
"UPDATE `gasorder_track_point` SET `received_at` = COALESCE(`occurred_at`, `created_at`, CURRENT_TIMESTAMP(3)) WHERE `received_at` IS NULL",
|
||||
"ALTER TABLE `gasorder_track_point` MODIFY COLUMN `received_at` datetime(3) NOT NULL",
|
||||
)
|
||||
default:
|
||||
return fmt.Errorf("unsupported database driver for additive migrations: %s", driver)
|
||||
}
|
||||
for _, statement := range statements {
|
||||
if err := databaseService.Exec(statement).Error; err != nil {
|
||||
return fmt.Errorf("backfill gasorder_track_point.received_at: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
18
backend/api/cmd/cli/main_test.go
Normal file
18
backend/api/cmd/cli/main_test.go
Normal file
@@ -0,0 +1,18 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestPrepareAdditiveMigrationsSkipsMissingLegacyTable(t *testing.T) {
|
||||
databaseService, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatalf("open sqlite database: %v", err)
|
||||
}
|
||||
if err := prepareAdditiveMigrations(databaseService, "postgres"); err != nil {
|
||||
t.Fatalf("missing legacy table should not require a backfill: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
// AccountPasswordMinLength 是账号密码允许的最低字符数。
|
||||
@@ -79,7 +80,10 @@ func IsGenericRecordStatus(status int) bool {
|
||||
|
||||
// ActiveRecords excludes logically archived records from operational queries.
|
||||
func ActiveRecords(query *gorm.DB) *gorm.DB {
|
||||
return query.Where("status <> ?", StatusArchived)
|
||||
return query.Where(clause.Neq{
|
||||
Column: clause.Column{Table: clause.CurrentTable, Name: "status"},
|
||||
Value: StatusArchived,
|
||||
})
|
||||
}
|
||||
|
||||
func ListPage[T any](ctx *gin.Context) {
|
||||
|
||||
@@ -31,11 +31,34 @@ func TestOperationalQueriesExcludeArchivedRecords(t *testing.T) {
|
||||
statement := database.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||
return ActiveRecords(tx.Model(&models.EcProduct{})).Find(&[]models.EcProduct{})
|
||||
})
|
||||
if !strings.Contains(statement, `status <> 3`) {
|
||||
if !strings.Contains(statement, `"ec_product"."status" <> 3`) {
|
||||
t.Fatalf("archive filter missing from operational query: %s", statement)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOperationalQueriesQualifyStatusAcrossJoins(t *testing.T) {
|
||||
sqlDatabase, _, err := sqlmock.New()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sqlDatabase.Close()
|
||||
database, err := gorm.Open(postgres.New(postgres.Config{Conn: sqlDatabase}), &gorm.Config{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
statement := database.ToSQL(func(tx *gorm.DB) *gorm.DB {
|
||||
return ActiveRecords(tx.Model(&models.StaffCredential{})).
|
||||
Joins("JOIN staff_account ON staff_account.id = staff_credential.staff_account_id").
|
||||
Find(&[]models.StaffCredential{})
|
||||
})
|
||||
if !strings.Contains(statement, `"staff_credential"."status" <> 3`) {
|
||||
t.Fatalf("joined archive filter is not table-qualified: %s", statement)
|
||||
}
|
||||
if strings.Contains(statement, `WHERE status <>`) {
|
||||
t.Fatalf("joined archive filter is ambiguous: %s", statement)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResourceResponseStripsInternalIDsRecursively(t *testing.T) {
|
||||
got := ResourceResponse(map[string]any{
|
||||
"id": uint64(1), "identity": "root",
|
||||
|
||||
@@ -59,6 +59,17 @@ func ListBank(ctx *gin.Context) { listWalletChild(ctx, &models.WalletBank{},
|
||||
func ListPayment(ctx *gin.Context) { listWalletChild(ctx, &models.WalletPayment{}, "wallet_payment") }
|
||||
func ListRecord(ctx *gin.Context) { listWalletChild(ctx, &models.WalletRecord{}, "wallet_record") }
|
||||
func ListRefund(ctx *gin.Context) { listWalletChild(ctx, &models.WalletRefund{}, "wallet_refund") }
|
||||
func ListRecharge(ctx *gin.Context) {
|
||||
point, _, ok := currentScope(ctx)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
query := common.ActiveRecords(db().Model(&models.WalletRecord{})).
|
||||
Joins("JOIN wallet_basic ON wallet_basic.id = wallet_record.wallet_basic_id").
|
||||
Where("wallet_basic.owner_type = ? AND wallet_basic.owner_id = ? AND wallet_record.trade_type = ?",
|
||||
"delivery", point.ID, "delivery_admin_recharge")
|
||||
listScoped(ctx, &models.WalletRecord{}, query, "wallet_record.created_at desc")
|
||||
}
|
||||
func ListApplyCash(ctx *gin.Context) {
|
||||
listWalletChild(ctx, &models.WalletApplyCash{}, "wallet_apply_cash")
|
||||
}
|
||||
@@ -79,6 +90,18 @@ func GetBank(ctx *gin.Context) { getWalletChild(ctx, &models.WalletBank{}, "w
|
||||
func GetPayment(ctx *gin.Context) { getWalletChild(ctx, &models.WalletPayment{}, "wallet_payment") }
|
||||
func GetRecord(ctx *gin.Context) { getWalletChild(ctx, &models.WalletRecord{}, "wallet_record") }
|
||||
func GetRefund(ctx *gin.Context) { getWalletChild(ctx, &models.WalletRefund{}, "wallet_refund") }
|
||||
func GetRecharge(ctx *gin.Context) {
|
||||
point, _, ok := currentScope(ctx)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var record models.WalletRecord
|
||||
query := common.ActiveRecords(db().Model(&models.WalletRecord{})).
|
||||
Joins("JOIN wallet_basic ON wallet_basic.id = wallet_record.wallet_basic_id").
|
||||
Where("wallet_record.identity = ? AND wallet_basic.owner_type = ? AND wallet_basic.owner_id = ? AND wallet_record.trade_type = ?",
|
||||
ctx.Param("identity"), "delivery", point.ID, "delivery_admin_recharge")
|
||||
respondRecord(ctx, query, &record)
|
||||
}
|
||||
func GetApplyCash(ctx *gin.Context) {
|
||||
getWalletChild(ctx, &models.WalletApplyCash{}, "wallet_apply_cash")
|
||||
}
|
||||
|
||||
@@ -7,8 +7,15 @@ import (
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/logic/common"
|
||||
"git.apinb.com/heqiapp/platforms/backend/api/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func scopedDeliveryAccounts(databaseService *gorm.DB, gasBasicID uint64) *gorm.DB {
|
||||
return databaseService.Model(&models.DeliveryAccount{}).
|
||||
Joins("JOIN delivery_basic ON delivery_basic.id = delivery_account.delivery_basic_id").
|
||||
Where("delivery_account.status <> ? AND delivery_basic.gas_basic_id = ?", common.StatusArchived, gasBasicID)
|
||||
}
|
||||
|
||||
func ListDeliveryAccount(ctx *gin.Context) {
|
||||
station, ok := currentGas(ctx)
|
||||
if !ok {
|
||||
@@ -18,9 +25,7 @@ func ListDeliveryAccount(ctx *gin.Context) {
|
||||
var list []models.DeliveryAccount
|
||||
var total int64
|
||||
query := common.ApplyKeywordFilter(ctx,
|
||||
common.ActiveRecords(impl.DBService.Model(&models.DeliveryAccount{})).
|
||||
Joins("JOIN delivery_basic ON delivery_basic.id = delivery_account.delivery_basic_id").
|
||||
Where("delivery_basic.gas_basic_id = ?", station.ID), &models.DeliveryAccount{})
|
||||
scopedDeliveryAccounts(impl.DBService, station.ID), &models.DeliveryAccount{})
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
infra.Response.Error(ctx, err)
|
||||
return
|
||||
@@ -37,9 +42,8 @@ func GetDeliveryAccount(ctx *gin.Context) {
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
query := common.ActiveRecords(impl.DBService.Model(&models.DeliveryAccount{})).
|
||||
Joins("JOIN delivery_basic ON delivery_basic.id = delivery_account.delivery_basic_id").
|
||||
Where("delivery_account.identity = ? AND delivery_basic.gas_basic_id = ?", ctx.Param("identity"), station.ID)
|
||||
query := scopedDeliveryAccounts(impl.DBService, station.ID).
|
||||
Where("delivery_account.identity = ?", ctx.Param("identity"))
|
||||
respondScopedRecord(ctx, query, &models.DeliveryAccount{})
|
||||
}
|
||||
|
||||
@@ -84,10 +88,9 @@ func UpdateDeliveryAccount(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
var account models.DeliveryAccount
|
||||
if err := common.ActiveRecords(impl.DBService.Model(&models.DeliveryAccount{})).
|
||||
if err := scopedDeliveryAccounts(impl.DBService, station.ID).
|
||||
Select("delivery_account.*").
|
||||
Joins("JOIN delivery_basic ON delivery_basic.id = delivery_account.delivery_basic_id").
|
||||
Where("delivery_account.identity = ? AND delivery_basic.gas_basic_id = ?", ctx.Param("identity"), station.ID).
|
||||
Where("delivery_account.identity = ?", ctx.Param("identity")).
|
||||
First(&account).Error; err != nil {
|
||||
infra.Response.Error(ctx, errcode.ErrInvalidArgument)
|
||||
return
|
||||
@@ -108,10 +111,9 @@ func UpdateDeliveryAccountStatus(ctx *gin.Context) {
|
||||
return
|
||||
}
|
||||
var account models.DeliveryAccount
|
||||
if err := common.ActiveRecords(impl.DBService.Model(&models.DeliveryAccount{})).
|
||||
if err := scopedDeliveryAccounts(impl.DBService, station.ID).
|
||||
Select("delivery_account.*").
|
||||
Joins("JOIN delivery_basic ON delivery_basic.id = delivery_account.delivery_basic_id").
|
||||
Where("delivery_account.identity = ? AND delivery_basic.gas_basic_id = ?", ctx.Param("identity"), station.ID).
|
||||
Where("delivery_account.identity = ?", ctx.Param("identity")).
|
||||
First(&account).Error; err != nil {
|
||||
infra.Response.Error(ctx, errcode.ErrInvalidArgument)
|
||||
return
|
||||
|
||||
31
backend/api/internal/logic/gas/delivery_account_test.go
Normal file
31
backend/api/internal/logic/gas/delivery_account_test.go
Normal file
@@ -0,0 +1,31 @@
|
||||
package gas
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DATA-DOG/go-sqlmock"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func TestScopedDeliveryAccountsQualifiesJoinedStatusColumn(t *testing.T) {
|
||||
connection, _, err := sqlmock.New()
|
||||
if err != nil {
|
||||
t.Fatalf("create SQL mock: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { _ = connection.Close() })
|
||||
databaseService, err := gorm.Open(postgres.New(postgres.Config{Conn: connection}), &gorm.Config{DryRun: true})
|
||||
if err != nil {
|
||||
t.Fatalf("open GORM database: %v", err)
|
||||
}
|
||||
|
||||
statement := scopedDeliveryAccounts(databaseService, 42).
|
||||
Find(&[]struct{}{}).Statement.SQL.String()
|
||||
if !strings.Contains(statement, "delivery_account.status <>") {
|
||||
t.Fatalf("joined query must qualify delivery account status, got: %s", statement)
|
||||
}
|
||||
if strings.Contains(statement, "WHERE status <>") {
|
||||
t.Fatalf("joined query contains ambiguous status column: %s", statement)
|
||||
}
|
||||
}
|
||||
@@ -88,6 +88,8 @@ func RegisterDelivery(serviceKey string, engine *gin.Engine) {
|
||||
protected.GET("/wallet_basic", deliverylogic.ListWallet)
|
||||
protected.GET("/wallet_basic/:identity", deliverylogic.GetWallet)
|
||||
protected.POST("/wallet_basic/recharge", deliverylogic.Recharge)
|
||||
protected.GET("/wallet_recharge", deliverylogic.ListRecharge)
|
||||
protected.GET("/wallet_recharge/:identity", deliverylogic.GetRecharge)
|
||||
protected.POST("/wallet_recharge", deliverylogic.Recharge)
|
||||
protected.GET("/wallet_bank", deliverylogic.ListBank)
|
||||
protected.GET("/wallet_bank/:identity", deliverylogic.GetBank)
|
||||
|
||||
@@ -43,6 +43,8 @@ func TestDeliveryOrderActionBoundary(t *testing.T) {
|
||||
"POST /heqi/delivery/v1/gasorder_basic/:identity/assign",
|
||||
"POST /heqi/delivery/v1/gasorder_basic/:identity/reclaim",
|
||||
"POST /heqi/delivery/v1/gasorder_basic/:identity/adjust-amount",
|
||||
"GET /heqi/delivery/v1/wallet_recharge",
|
||||
"GET /heqi/delivery/v1/wallet_recharge/:identity",
|
||||
} {
|
||||
if !routes[required] {
|
||||
t.Fatalf("missing confirmed delivery action %s", required)
|
||||
|
||||
Reference in New Issue
Block a user