feat(tenant): 按租户隔离用户身份与后台权限
This commit is contained in:
@@ -9,6 +9,7 @@ import (
|
||||
"time"
|
||||
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
"hfb_sys/backend/internal/timeutil"
|
||||
"hfb_sys/backend/pkg/money"
|
||||
|
||||
@@ -21,6 +22,7 @@ type Repository struct {
|
||||
}
|
||||
|
||||
type Entry struct {
|
||||
TenantID uint64
|
||||
UserID uint64
|
||||
DistributionSiteID uint64
|
||||
OrderID *uint64
|
||||
@@ -66,10 +68,15 @@ func (r *Repository) Account(ctx context.Context, userID uint64, siteCode ...str
|
||||
|
||||
var account model.WalletAccount
|
||||
err = r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
if err := ensureAccount(tx, userID, siteID); err != nil {
|
||||
tenantID := resolveTenantID(tx, tenancy.IDFromContext(ctx), userID)
|
||||
if err := ensureAccount(tx, userID, tenantID, siteID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Where("user_id = ? AND distribution_site_id = ?", userID, siteID).First(&account).Error
|
||||
query := tx.Where("user_id = ? AND distribution_site_id = ?", userID, siteID)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
return query.First(&account).Error
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -87,7 +94,11 @@ func (r *Repository) Ledger(ctx context.Context, userID uint64, page, pageSize i
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
query := r.db.WithContext(ctx).Model(&model.WalletLedger{}).Where("user_id = ?", userID)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if siteID > 0 {
|
||||
query = query.Where("distribution_site_id = ?", siteID)
|
||||
} else {
|
||||
@@ -101,6 +112,9 @@ func (r *Repository) Ledger(ctx context.Context, userID uint64, page, pageSize i
|
||||
offset := (page - 1) * pageSize
|
||||
var rows []model.WalletLedger
|
||||
dataQuery := r.db.WithContext(ctx).Where("user_id = ?", userID)
|
||||
if tenantID > 0 {
|
||||
dataQuery = dataQuery.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if siteID > 0 {
|
||||
dataQuery = dataQuery.Where("distribution_site_id = ?", siteID)
|
||||
} else {
|
||||
@@ -122,7 +136,9 @@ func (r *Repository) Withdraw(ctx context.Context, userID uint64, amountCent int
|
||||
return nil, ErrInvalidAmount
|
||||
}
|
||||
err := r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
|
||||
tenantID := resolveTenantID(tx, tenancy.IDFromContext(ctx), userID)
|
||||
return AppendEntries(tx, Entry{
|
||||
TenantID: tenantID,
|
||||
UserID: userID,
|
||||
Direction: "out",
|
||||
AmountCent: amountCent,
|
||||
@@ -139,6 +155,7 @@ func (r *Repository) Withdraw(ctx context.Context, userID uint64, amountCent int
|
||||
}
|
||||
|
||||
func (r *Repository) AdminLedger(ctx context.Context, query AdminLedgerQuery) (*PaginatedResult, error) {
|
||||
tenantID := tenancy.IDFromContext(ctx)
|
||||
db := r.db.WithContext(ctx).Table("wallet_ledger AS wl").
|
||||
Select(`wl.id, wl.ledger_no, wl.user_id, COALESCE(u.phone, '') AS user_phone,
|
||||
COALESCE(u.nickname, '') AS user_nickname, wl.order_id, COALESCE(ro.order_no, '') AS order_no,
|
||||
@@ -148,6 +165,10 @@ func (r *Repository) AdminLedger(ctx context.Context, query AdminLedgerQuery) (*
|
||||
Joins("LEFT JOIN rental_orders AS ro ON ro.id = wl.order_id")
|
||||
|
||||
countDB := r.db.WithContext(ctx).Model(&model.WalletLedger{})
|
||||
if tenantID > 0 {
|
||||
db = db.Where("wl.tenant_id = ?", tenantID)
|
||||
countDB = countDB.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if query.UserID > 0 {
|
||||
db = db.Where("wl.user_id = ?", query.UserID)
|
||||
countDB = countDB.Where("user_id = ?", query.UserID)
|
||||
@@ -179,11 +200,17 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
||||
if entry.AmountCent <= 0 {
|
||||
continue
|
||||
}
|
||||
if err := ensureAccount(tx, entry.UserID, entry.DistributionSiteID); err != nil {
|
||||
tenantID := resolveTenantID(tx, entry.TenantID, entry.UserID)
|
||||
if err := ensureAccount(tx, entry.UserID, tenantID, entry.DistributionSiteID); err != nil {
|
||||
return err
|
||||
}
|
||||
var account model.WalletAccount
|
||||
if err := tx.Clauses(clause.Locking{Strength: "UPDATE"}).Where("user_id = ? AND distribution_site_id = ?", entry.UserID, entry.DistributionSiteID).First(&account).Error; err != nil {
|
||||
query := tx.Clauses(clause.Locking{Strength: "UPDATE"}).
|
||||
Where("user_id = ? AND distribution_site_id = ?", entry.UserID, entry.DistributionSiteID)
|
||||
if tenantID > 0 {
|
||||
query = query.Where("tenant_id = ?", tenantID)
|
||||
}
|
||||
if err := query.First(&account).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
balanceAfterCent, err := applyEntry(&account, entry)
|
||||
@@ -199,6 +226,7 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
||||
}
|
||||
ledger := model.WalletLedger{
|
||||
LedgerNo: ledgerNo,
|
||||
TenantID: tenantID,
|
||||
UserID: entry.UserID,
|
||||
DistributionSiteID: entry.DistributionSiteID,
|
||||
OrderID: entry.OrderID,
|
||||
@@ -217,8 +245,20 @@ func AppendEntries(tx *gorm.DB, entries ...Entry) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func ensureAccount(tx *gorm.DB, userID uint64, siteID ...uint64) error {
|
||||
return EnsureAccountTx(tx, userID, siteID...)
|
||||
func ensureAccount(tx *gorm.DB, userID uint64, tenantID uint64, siteID ...uint64) error {
|
||||
var sID uint64
|
||||
if len(siteID) > 0 {
|
||||
sID = siteID[0]
|
||||
}
|
||||
account := model.WalletAccount{
|
||||
TenantID: resolveTenantID(tx, tenantID, userID),
|
||||
UserID: userID,
|
||||
DistributionSiteID: sID,
|
||||
AvailableBalanceCent: 0,
|
||||
FrozenBalanceCent: 0,
|
||||
Status: "active",
|
||||
}
|
||||
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error
|
||||
}
|
||||
|
||||
// EnsureAccountTx 在事务内确保用户钱包账户存在(幂等)。
|
||||
@@ -227,14 +267,31 @@ func EnsureAccountTx(tx *gorm.DB, userID uint64, siteID ...uint64) error {
|
||||
if len(siteID) > 0 {
|
||||
sID = siteID[0]
|
||||
}
|
||||
account := model.WalletAccount{
|
||||
UserID: userID,
|
||||
DistributionSiteID: sID,
|
||||
AvailableBalanceCent: 0,
|
||||
FrozenBalanceCent: 0,
|
||||
Status: "active",
|
||||
return ensureAccount(tx, userID, tenantIDFromDB(tx), sID)
|
||||
}
|
||||
|
||||
func resolveTenantID(db *gorm.DB, explicitTenantID uint64, userID uint64) uint64 {
|
||||
if explicitTenantID > 0 {
|
||||
return explicitTenantID
|
||||
}
|
||||
return tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error
|
||||
if tenantID := tenantIDFromDB(db); tenantID > 0 {
|
||||
return tenantID
|
||||
}
|
||||
if userID == 0 {
|
||||
return 0
|
||||
}
|
||||
var tenantID uint64
|
||||
if err := db.Model(&model.User{}).Select("tenant_id").Where("id = ?", userID).Scan(&tenantID).Error; err != nil {
|
||||
return 0
|
||||
}
|
||||
return tenantID
|
||||
}
|
||||
|
||||
func tenantIDFromDB(db *gorm.DB) uint64 {
|
||||
if db == nil || db.Statement == nil || db.Statement.Context == nil {
|
||||
return 0
|
||||
}
|
||||
return tenancy.IDFromContext(db.Statement.Context)
|
||||
}
|
||||
|
||||
func applyEntry(account *model.WalletAccount, entry Entry) (int64, error) {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package wallet
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"hfb_sys/backend/internal/database"
|
||||
"hfb_sys/backend/internal/model"
|
||||
"hfb_sys/backend/internal/tenancy"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func walletTenantContext(tenantID uint64) context.Context {
|
||||
return tenancy.WithScope(context.Background(), tenancy.Scope{TenantID: tenantID})
|
||||
}
|
||||
|
||||
func TestWalletAccountsAndLedgerAreScopedByTenant(t *testing.T) {
|
||||
db := database.NewTestDB()
|
||||
dachuiUser := model.User{TenantID: 101, Phone: "13400000001", Status: "active"}
|
||||
jieyouUser := model.User{TenantID: 202, Phone: "13400000001", Status: "active"}
|
||||
if err := db.Create(&dachuiUser).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := db.Create(&jieyouUser).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db)
|
||||
dachuiCtx := walletTenantContext(101)
|
||||
jieyouCtx := walletTenantContext(202)
|
||||
if _, err := repo.Account(dachuiCtx, dachuiUser.ID); err != nil {
|
||||
t.Fatalf("create dachui wallet: %v", err)
|
||||
}
|
||||
if _, err := repo.Account(jieyouCtx, jieyouUser.ID); err != nil {
|
||||
t.Fatalf("create jieyou wallet: %v", err)
|
||||
}
|
||||
if err := db.WithContext(dachuiCtx).Transaction(func(tx *gorm.DB) error {
|
||||
return AppendEntries(tx, Entry{
|
||||
UserID: dachuiUser.ID, Direction: "in", AmountCent: 1000,
|
||||
BalanceType: "available", BizType: "test", BizNo: "DACHUI-1",
|
||||
})
|
||||
}); err != nil {
|
||||
t.Fatalf("append dachui ledger: %v", err)
|
||||
}
|
||||
|
||||
dachuiLedger, err := repo.Ledger(dachuiCtx, dachuiUser.ID, 1, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if dachuiLedger.Total != 1 {
|
||||
t.Fatalf("dachui ledger total = %d, want 1", dachuiLedger.Total)
|
||||
}
|
||||
jieyouLedger, err := repo.Ledger(jieyouCtx, dachuiUser.ID, 1, 10)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if jieyouLedger.Total != 0 {
|
||||
t.Fatalf("cross-tenant ledger total = %d, want 0", jieyouLedger.Total)
|
||||
}
|
||||
|
||||
var accounts []model.WalletAccount
|
||||
if err := db.Order("id ASC").Find(&accounts).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(accounts) != 2 || accounts[0].TenantID != 101 || accounts[1].TenantID != 202 {
|
||||
t.Fatalf("tenant wallet accounts = %+v", accounts)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user