Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

UpdateAccountBalances.php 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace App\Listeners;
  3. use App\Enums\Accounting\TransactionType;
  4. use App\Events\CurrencyRateChanged;
  5. use App\Models\Accounting\Account;
  6. use App\Models\Accounting\Transaction;
  7. use App\Models\Banking\BankAccount;
  8. use App\Utilities\Currency\CurrencyConverter;
  9. use Illuminate\Support\Facades\DB;
  10. class UpdateAccountBalances
  11. {
  12. /**
  13. * Create the event listener.
  14. */
  15. public function __construct()
  16. {
  17. //
  18. }
  19. /**
  20. * Handle the event.
  21. */
  22. public function handle(CurrencyRateChanged $event): void
  23. {
  24. DB::transaction(static function () use ($event) {
  25. $bankAccounts = BankAccount::with('account')
  26. ->whereHas('account', static function ($query) use ($event) {
  27. $query->where('currency_code', $event->currency->code);
  28. })
  29. ->get();
  30. foreach ($bankAccounts as $bankAccount) {
  31. /** @var BankAccount $bankAccount */
  32. $account = $bankAccount->account;
  33. $oldConvertedBalanceInCents = $account->ending_balance->convert()->getConvertedAmount();
  34. $ratio = $event->newRate / $event->oldRate;
  35. $newConvertedBalance = bcmul($oldConvertedBalanceInCents, $ratio, 2);
  36. $newConvertedBalanceInCents = (int) round($newConvertedBalance);
  37. $differenceInCents = $newConvertedBalanceInCents - $oldConvertedBalanceInCents;
  38. if ($differenceInCents !== 0) {
  39. $gainOrLossAccountName = $differenceInCents > 0 ? 'Gain on Foreign Exchange' : 'Loss on Foreign Exchange';
  40. $gainOrLossAccount = Account::where('name', $gainOrLossAccountName)->first();
  41. $transactionType = $differenceInCents > 0 ? TransactionType::Deposit : TransactionType::Withdrawal;
  42. $description = "Exchange rate adjustment due to rate change from {$event->oldRate} to {$event->newRate}";
  43. $absoluteDifferenceAmountInCents = abs($differenceInCents);
  44. $formattedSimpleDifference = CurrencyConverter::prepareForMutator($absoluteDifferenceAmountInCents, $bankAccount->account->currency_code);
  45. Transaction::create([
  46. 'company_id' => $account->company_id,
  47. 'account_id' => $gainOrLossAccount->id,
  48. 'bank_account_id' => $bankAccount->id,
  49. 'type' => $transactionType,
  50. 'amount' => $formattedSimpleDifference,
  51. 'payment_channel' => 'other',
  52. 'posted_at' => today(),
  53. 'description' => $description,
  54. 'pending' => false,
  55. 'reviewed' => false,
  56. ]);
  57. }
  58. }
  59. });
  60. }
  61. }