You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TransactionObserver.php 6.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. <?php
  2. namespace App\Observers;
  3. use App\Enums\Accounting\JournalEntryType;
  4. use App\Models\Accounting\Account;
  5. use App\Models\Accounting\JournalEntry;
  6. use App\Models\Accounting\Transaction;
  7. use App\Utilities\Currency\CurrencyAccessor;
  8. use App\Utilities\Currency\CurrencyConverter;
  9. use Illuminate\Support\Facades\DB;
  10. class TransactionObserver
  11. {
  12. /**
  13. * Handle the Transaction "saving" event.
  14. */
  15. public function saving(Transaction $transaction): void
  16. {
  17. if ($transaction->type->isTransfer() && $transaction->description === null) {
  18. $transaction->description = 'Account Transfer';
  19. }
  20. }
  21. /**
  22. * Handle the Transaction "created" event.
  23. */
  24. public function created(Transaction $transaction): void
  25. {
  26. // Additional check to avoid duplication during replication
  27. if ($transaction->journalEntries()->exists() || $transaction->type->isJournal() || str_starts_with($transaction->description, '(Copy of)')) {
  28. return;
  29. }
  30. [$debitAccount, $creditAccount] = $this->determineAccounts($transaction);
  31. if ($debitAccount === null || $creditAccount === null) {
  32. return;
  33. }
  34. $this->createJournalEntries($transaction, $debitAccount, $creditAccount);
  35. }
  36. /**
  37. * Handle the Transaction "updated" event.
  38. */
  39. public function updated(Transaction $transaction): void
  40. {
  41. $transaction->refresh(); // DO NOT REMOVE
  42. if ($transaction->type->isJournal() || $this->hasRelevantChanges($transaction) === false) {
  43. return;
  44. }
  45. $journalEntries = $transaction->journalEntries;
  46. $debitEntry = $journalEntries->where('type', JournalEntryType::Debit)->first();
  47. $creditEntry = $journalEntries->where('type', JournalEntryType::Credit)->first();
  48. if ($debitEntry === null || $creditEntry === null) {
  49. return;
  50. }
  51. [$debitAccount, $creditAccount] = $this->determineAccounts($transaction);
  52. if ($debitAccount === null || $creditAccount === null) {
  53. return;
  54. }
  55. $convertedTransactionAmount = $this->getConvertedTransactionAmount($transaction);
  56. $this->updateJournalEntriesForTransaction($debitEntry, $debitAccount, $convertedTransactionAmount);
  57. $this->updateJournalEntriesForTransaction($creditEntry, $creditAccount, $convertedTransactionAmount);
  58. }
  59. /**
  60. * Handle the Transaction "deleting" event.
  61. */
  62. public function deleting(Transaction $transaction): void
  63. {
  64. DB::transaction(static function () use ($transaction) {
  65. $transaction->journalEntries()->each(fn (JournalEntry $entry) => $entry->delete());
  66. });
  67. }
  68. private function determineAccounts(Transaction $transaction): array
  69. {
  70. $chartAccount = $transaction->account;
  71. $bankAccount = $transaction->bankAccount?->account;
  72. if ($transaction->type->isTransfer()) {
  73. // Essentially a withdrawal from the bank account and a deposit to the chart account (which is a bank account)
  74. // Credit: bankAccount (source of funds, money is being withdrawn)
  75. // Debit: chartAccount (destination of funds, money is being deposited)
  76. return [$chartAccount, $bankAccount];
  77. }
  78. $debitAccount = $transaction->type->isWithdrawal() ? $chartAccount : $bankAccount;
  79. $creditAccount = $transaction->type->isWithdrawal() ? $bankAccount : $chartAccount;
  80. return [$debitAccount, $creditAccount];
  81. }
  82. private function createJournalEntries(Transaction $transaction, Account $debitAccount, Account $creditAccount): void
  83. {
  84. $convertedTransactionAmount = $this->getConvertedTransactionAmount($transaction);
  85. $debitAccount->journalEntries()->create([
  86. 'company_id' => $transaction->company_id,
  87. 'transaction_id' => $transaction->id,
  88. 'type' => JournalEntryType::Debit,
  89. 'amount' => $convertedTransactionAmount,
  90. 'description' => $transaction->description,
  91. ]);
  92. $creditAccount->journalEntries()->create([
  93. 'company_id' => $transaction->company_id,
  94. 'transaction_id' => $transaction->id,
  95. 'type' => JournalEntryType::Credit,
  96. 'amount' => $convertedTransactionAmount,
  97. 'description' => $transaction->description,
  98. ]);
  99. }
  100. private function getConvertedTransactionAmount(Transaction $transaction): string
  101. {
  102. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  103. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  104. $chartAccountCurrency = $transaction->account->currency_code;
  105. if ($bankAccountCurrency !== $defaultCurrency) {
  106. return $this->convertToDefaultCurrency($transaction->amount, $bankAccountCurrency, $defaultCurrency);
  107. } elseif ($chartAccountCurrency !== $defaultCurrency) {
  108. return $this->convertToDefaultCurrency($transaction->amount, $chartAccountCurrency, $defaultCurrency);
  109. }
  110. return $transaction->amount;
  111. }
  112. private function convertToDefaultCurrency(string $amount, string $fromCurrency, string $toCurrency): string
  113. {
  114. $amountInCents = CurrencyConverter::prepareForAccessor($amount, $fromCurrency);
  115. $convertedAmountInCents = CurrencyConverter::convertBalance($amountInCents, $fromCurrency, $toCurrency);
  116. return CurrencyConverter::prepareForMutator($convertedAmountInCents, $toCurrency);
  117. }
  118. private function hasRelevantChanges(Transaction $transaction): bool
  119. {
  120. return $transaction->wasChanged(['amount', 'account_id', 'bank_account_id', 'type']);
  121. }
  122. private function updateJournalEntriesForTransaction(JournalEntry $journalEntry, Account $account, string $convertedTransactionAmount): void
  123. {
  124. DB::transaction(static function () use ($journalEntry, $account, $convertedTransactionAmount) {
  125. $journalEntry->update([
  126. 'account_id' => $account->id,
  127. 'amount' => $convertedTransactionAmount,
  128. ]);
  129. });
  130. }
  131. }