diff --git a/app/Services/Dealer/WalletService.php b/app/Services/Dealer/WalletService.php new file mode 100644 index 00000000..9084d525 --- /dev/null +++ b/app/Services/Dealer/WalletService.php @@ -0,0 +1,80 @@ +wallet($user); + + // 变更前余额 + $beforeBalance = $wallet->balance; + + if (bccomp($changeBalance, '0', 2) < 0) { + // 支出 + + $absChangeBalance = abs($changeBalance); + + if (bccomp($wallet->balance, $absChangeBalance, 2) === -1) { + throw new BizException('余额不足'); + } + + $wallet->update([ + 'balance' => bcsub($wallet->balance, $absChangeBalance, 2), + 'total_expenses' => bcadd($wallet->total_expenses, $absChangeBalance, 2), + ]); + } else { + // 收入 + + $wallet->update([ + 'balance' => bcadd($wallet->balance, $changeBalance, 2), + 'total_revenue' => bcadd($wallet->total_revenue, $changeBalance, 2), + ]); + } + + $user->dealerWalletLogs()->create([ + 'loggable_id' => $loggable?->id, + 'loggable_type' => $loggable?->getMorphClass(), + 'before_balance' => $beforeBalance, + 'change_balance' => $changeBalance, + 'action' => $action, + 'remarks' => $remarks, + ]); + } + + /** + * @param \App\Models\User $user + * @return \App\Models\DealerWallet + */ + protected function wallet(User $user): DealerWallet + { + if ($wallet = $user->dealerWallet()->lockForUpdate()->first()) { + return $wallet; + } + + $user->dealerWallet()->create(); + + return $this->wallet($user); + } +}