Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

TransactionObserver.php 6.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. <?php
  2. namespace App\Observers;
  3. use App\Enums\Accounting\BillStatus;
  4. use App\Enums\Accounting\InvoiceStatus;
  5. use App\Models\Accounting\Bill;
  6. use App\Models\Accounting\Invoice;
  7. use App\Models\Accounting\Transaction;
  8. use App\Services\TransactionService;
  9. use App\Utilities\Currency\CurrencyConverter;
  10. use Illuminate\Database\Eloquent\Builder;
  11. use Illuminate\Support\Facades\DB;
  12. class TransactionObserver
  13. {
  14. public function __construct(
  15. protected TransactionService $transactionService,
  16. ) {}
  17. /**
  18. * Handle the Transaction "saving" event.
  19. */
  20. public function saving(Transaction $transaction): void
  21. {
  22. if ($transaction->type->isTransfer() && $transaction->description === null) {
  23. $transaction->description = 'Account Transfer';
  24. }
  25. }
  26. /**
  27. * Handle the Transaction "created" event.
  28. */
  29. public function created(Transaction $transaction): void
  30. {
  31. $this->transactionService->createJournalEntries($transaction);
  32. if (! $transaction->transactionable) {
  33. return;
  34. }
  35. $document = $transaction->transactionable;
  36. if ($document instanceof Invoice) {
  37. $this->updateInvoiceTotals($document);
  38. } elseif ($document instanceof Bill) {
  39. $this->updateBillTotals($document);
  40. }
  41. }
  42. /**
  43. * Handle the Transaction "updated" event.
  44. */
  45. public function updated(Transaction $transaction): void
  46. {
  47. $transaction->refresh(); // DO NOT REMOVE
  48. $this->transactionService->updateJournalEntries($transaction);
  49. if (! $transaction->transactionable) {
  50. return;
  51. }
  52. $document = $transaction->transactionable;
  53. if ($document instanceof Invoice) {
  54. $this->updateInvoiceTotals($document);
  55. } elseif ($document instanceof Bill) {
  56. $this->updateBillTotals($document);
  57. }
  58. }
  59. /**
  60. * Handle the Transaction "deleting" event.
  61. */
  62. public function deleting(Transaction $transaction): void
  63. {
  64. DB::transaction(function () use ($transaction) {
  65. $this->transactionService->deleteJournalEntries($transaction);
  66. if (! $transaction->transactionable) {
  67. return;
  68. }
  69. $document = $transaction->transactionable;
  70. if (($document instanceof Invoice || $document instanceof Bill) && ! $document->exists) {
  71. return;
  72. }
  73. if ($document instanceof Invoice) {
  74. $this->updateInvoiceTotals($document, $transaction);
  75. } elseif ($document instanceof Bill) {
  76. $this->updateBillTotals($document, $transaction);
  77. }
  78. });
  79. }
  80. public function deleted(Transaction $transaction): void
  81. {
  82. //
  83. }
  84. protected function updateInvoiceTotals(Invoice $invoice, ?Transaction $excludedTransaction = null): void
  85. {
  86. if (! $invoice->hasPayments()) {
  87. return;
  88. }
  89. $invoiceCurrency = $invoice->currency_code;
  90. $depositTotalInInvoiceCurrencyCents = (int) $invoice->deposits()
  91. ->when($excludedTransaction, fn (Builder $query) => $query->whereKeyNot($excludedTransaction->getKey()))
  92. ->get()
  93. ->sum(function (Transaction $transaction) use ($invoiceCurrency) {
  94. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  95. $amountCents = (int) $transaction->getRawOriginal('amount');
  96. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $invoiceCurrency);
  97. });
  98. $withdrawalTotalInInvoiceCurrencyCents = (int) $invoice->withdrawals()
  99. ->when($excludedTransaction, fn (Builder $query) => $query->whereKeyNot($excludedTransaction->getKey()))
  100. ->get()
  101. ->sum(function (Transaction $transaction) use ($invoiceCurrency) {
  102. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  103. $amountCents = (int) $transaction->getRawOriginal('amount');
  104. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $invoiceCurrency);
  105. });
  106. $totalPaidInInvoiceCurrencyCents = $depositTotalInInvoiceCurrencyCents - $withdrawalTotalInInvoiceCurrencyCents;
  107. $invoiceTotalInInvoiceCurrencyCents = (int) $invoice->getRawOriginal('total');
  108. $newStatus = match (true) {
  109. $totalPaidInInvoiceCurrencyCents > $invoiceTotalInInvoiceCurrencyCents => InvoiceStatus::Overpaid,
  110. $totalPaidInInvoiceCurrencyCents === $invoiceTotalInInvoiceCurrencyCents => InvoiceStatus::Paid,
  111. default => InvoiceStatus::Partial,
  112. };
  113. $paidAt = $invoice->paid_at;
  114. if (in_array($newStatus, [InvoiceStatus::Paid, InvoiceStatus::Overpaid]) && ! $paidAt) {
  115. $paidAt = $invoice->deposits()
  116. ->latest('posted_at')
  117. ->value('posted_at');
  118. }
  119. $invoice->update([
  120. 'amount_paid' => CurrencyConverter::convertCentsToFormatSimple($totalPaidInInvoiceCurrencyCents, $invoiceCurrency),
  121. 'status' => $newStatus,
  122. 'paid_at' => $paidAt,
  123. ]);
  124. }
  125. protected function updateBillTotals(Bill $bill, ?Transaction $excludedTransaction = null): void
  126. {
  127. if (! $bill->hasPayments()) {
  128. return;
  129. }
  130. $billCurrency = $bill->currency_code;
  131. $withdrawalTotalInBillCurrencyCents = (int) $bill->withdrawals()
  132. ->when($excludedTransaction, fn (Builder $query) => $query->whereKeyNot($excludedTransaction->getKey()))
  133. ->get()
  134. ->sum(function (Transaction $transaction) use ($billCurrency) {
  135. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  136. $amountCents = (int) $transaction->getRawOriginal('amount');
  137. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $billCurrency);
  138. });
  139. $totalPaidInBillCurrencyCents = $withdrawalTotalInBillCurrencyCents;
  140. $billTotalInBillCurrencyCents = (int) $bill->getRawOriginal('total');
  141. $newStatus = match (true) {
  142. $totalPaidInBillCurrencyCents >= $billTotalInBillCurrencyCents => BillStatus::Paid,
  143. default => BillStatus::Partial,
  144. };
  145. $paidAt = $bill->paid_at;
  146. if ($newStatus === BillStatus::Paid && ! $paidAt) {
  147. $paidAt = $bill->withdrawals()
  148. ->latest('posted_at')
  149. ->value('posted_at');
  150. }
  151. $bill->update([
  152. 'amount_paid' => CurrencyConverter::convertCentsToFormatSimple($totalPaidInBillCurrencyCents, $billCurrency),
  153. 'status' => $newStatus,
  154. 'paid_at' => $paidAt,
  155. ]);
  156. }
  157. }