fix: Service 层移除直接持有的 *gorm.DB,引入 Repository Transaction 方法

- ReactionStore/FollowStore/EnergyStore/FavoriteStore 接口新增 Transaction 方法
- EnergyStore.Transaction 支持跨仓库事务(EnergyStore + FundStore)
- ReactionRepo/FollowRepo/FavoriteRepo/EnergyRepo 实现 Transaction 方法
- ReactionRepo 新增 GetPostLikesCount 方法,消除 Service 直查 DB
- ReactionService/FollowService/FavoriteService/EnergyService 移除 db 字段
- EnergyRepo 通过 SetFundStore 注入 FundStore 用于跨仓库事务
- 更新 deps_extra.go 构造函数调用
This commit is contained in:
2026-06-02 16:46:44 +08:00
parent 1cb7a832f1
commit 3df7b2e672
14 changed files with 94 additions and 92 deletions

View File

@ -5,8 +5,6 @@ import (
"metazone.cc/metalab/internal/common"
"metazone.cc/metalab/internal/model"
"gorm.io/gorm"
)
// AdminAdjust 后台调整用户域能
@ -16,13 +14,10 @@ func (s *EnergyService) AdminAdjust(operatorUID uint, userIDs []uint, amount int
mode = model.FundTypeAdminTransfer
}
return s.db.Transaction(func(tx *gorm.DB) error {
txRepo := s.repo.WithTx(tx)
return s.repo.Transaction(func(txRepo EnergyStore, txFundRepo FundStore) error {
// admin_transfer公户出账需检查余额行锁防 TOCTOU 竞态)
isAdminTransfer := mode == model.FundTypeAdminTransfer
if isAdminTransfer && amount > 0 && s.fundRepo != nil {
txFundRepo := s.fundRepo.WithTx(tx)
if isAdminTransfer && amount > 0 && txFundRepo != nil {
totalCost := amount * len(userIDs)
balance, err := txFundRepo.LockAndGetBalance()
if err != nil {
@ -52,8 +47,7 @@ func (s *EnergyService) AdminAdjust(operatorUID uint, userIDs []uint, amount int
}
// admin_transfer公户扣款 + 公户流水system_operation 不碰公户)
if isAdminTransfer && s.fundRepo != nil {
txFundRepo := s.fundRepo.WithTx(tx)
if isAdminTransfer && txFundRepo != nil {
totalCost := amount * len(userIDs)
if err := txFundRepo.IncrBalance(-totalCost); err != nil {
return fmt.Errorf("公户余额调整失败: %w", err)