您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

UpdateAccountBalances.php 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. namespace App\Listeners;
  3. use App\Events\CurrencyRateChanged;
  4. use Illuminate\Support\Facades\DB;
  5. class UpdateAccountBalances
  6. {
  7. /**
  8. * Create the event listener.
  9. */
  10. public function __construct()
  11. {
  12. //
  13. }
  14. /**
  15. * Handle the event.
  16. */
  17. public function handle(CurrencyRateChanged $event): void
  18. {
  19. DB::transaction(static function () use ($event) {
  20. $accounts = $event->currency->accounts;
  21. foreach ($accounts as $account) {
  22. $initialHistory = $account->histories()->where('account_id', $account->id)
  23. ->orderBy('created_at')
  24. ->first();
  25. if ($initialHistory) {
  26. $originalBalance = $initialHistory->balance;
  27. $originalBalance = money($originalBalance, $account->currency->code)->getAmount();
  28. $originalRate = $initialHistory->exchange_rate;
  29. $precision = $account->currency->precision;
  30. $newRate = $event->currency->rate;
  31. $newBalance = ($newRate / $originalRate) * $originalBalance;
  32. $newBalanceScaled = round($newBalance, $precision);
  33. $account->balance = $newBalanceScaled;
  34. $account->save();
  35. }
  36. }
  37. });
  38. }
  39. }