feat: 新增交易服务和AI记账服务,实现交易的创建、验证及账户余额更新逻辑。

This commit is contained in:
2026-01-29 22:32:21 +08:00
parent ba16aebdba
commit 162742a4cd
2 changed files with 16 additions and 3 deletions

View File

@@ -351,6 +351,9 @@ func (s *TransactionService) UpdateTransaction(userID, id uint, input Transactio
// Step 1: Reverse the old transaction's effect on balances
oldReversedBalance := calculateNewBalance(oldAccount.Balance, existingTxn.Amount, existingTxn.Type, false)
if !oldAccount.IsCredit && oldReversedBalance < 0 {
return fmt.Errorf("%w: update would cause negative balance in account '%s'", ErrInsufficientBalance, oldAccount.Name)
}
if err := txAccountRepo.UpdateBalance(userID, existingTxn.AccountID, oldReversedBalance); err != nil {
return fmt.Errorf("failed to reverse old account balance: %w", err)
}
@@ -358,6 +361,9 @@ func (s *TransactionService) UpdateTransaction(userID, id uint, input Transactio
// Reverse old transfer destination if applicable
if oldToAccount != nil {
oldToReversedBalance := oldToAccount.Balance - existingTxn.Amount
if !oldToAccount.IsCredit && oldToReversedBalance < 0 {
return fmt.Errorf("%w: update would cause negative balance in old destination account '%s'", ErrInsufficientBalance, oldToAccount.Name)
}
if err := txAccountRepo.UpdateBalance(userID, *existingTxn.ToAccountID, oldToReversedBalance); err != nil {
return fmt.Errorf("failed to reverse old destination account balance: %w", err)
}
@@ -449,6 +455,9 @@ func (s *TransactionService) DeleteTransaction(userID, id uint) error {
// Reverse the transaction's effect on balance
reversedBalance := calculateNewBalance(account.Balance, existingTxn.Amount, existingTxn.Type, false)
if !account.IsCredit && reversedBalance < 0 {
return fmt.Errorf("%w: deletion would cause negative balance in account '%s'", ErrInsufficientBalance, account.Name)
}
if err := txAccountRepo.UpdateBalance(userID, existingTxn.AccountID, reversedBalance); err != nil {
return fmt.Errorf("failed to reverse account balance: %w", err)
}
@@ -461,6 +470,9 @@ func (s *TransactionService) DeleteTransaction(userID, id uint) error {
}
if toAccount != nil {
reversedToBalance := toAccount.Balance - existingTxn.Amount
if !toAccount.IsCredit && reversedToBalance < 0 {
return fmt.Errorf("%w: deletion would cause negative balance in destination account '%s'", ErrInsufficientBalance, toAccount.Name)
}
if err := txAccountRepo.UpdateBalance(userID, *existingTxn.ToAccountID, reversedToBalance); err != nil {
return fmt.Errorf("failed to reverse destination account balance: %w", err)
}