Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

TransactionObserver.php 8.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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. // If the transaction has stored the original invoice amount in metadata, use that
  95. if (! empty($transaction->meta) &&
  96. isset($transaction->meta['original_document_currency']) &&
  97. $transaction->meta['original_document_currency'] === $invoiceCurrency &&
  98. isset($transaction->meta['amount_in_document_currency_cents'])) {
  99. return (int) $transaction->meta['amount_in_document_currency_cents'];
  100. }
  101. // Fall back to conversion if metadata is not available
  102. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  103. $amountCents = (int) $transaction->getRawOriginal('amount');
  104. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $invoiceCurrency);
  105. });
  106. $withdrawalTotalInInvoiceCurrencyCents = (int) $invoice->withdrawals()
  107. ->when($excludedTransaction, fn (Builder $query) => $query->whereKeyNot($excludedTransaction->getKey()))
  108. ->get()
  109. ->sum(function (Transaction $transaction) use ($invoiceCurrency) {
  110. // If the transaction has stored the original invoice amount in metadata, use that
  111. if (! empty($transaction->meta) &&
  112. isset($transaction->meta['original_document_currency']) &&
  113. $transaction->meta['original_document_currency'] === $invoiceCurrency &&
  114. isset($transaction->meta['amount_in_document_currency_cents'])) {
  115. return (int) $transaction->meta['amount_in_document_currency_cents'];
  116. }
  117. // Fall back to conversion if metadata is not available
  118. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  119. $amountCents = (int) $transaction->getRawOriginal('amount');
  120. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $invoiceCurrency);
  121. });
  122. $totalPaidInInvoiceCurrencyCents = $depositTotalInInvoiceCurrencyCents - $withdrawalTotalInInvoiceCurrencyCents;
  123. $invoiceTotalInInvoiceCurrencyCents = (int) $invoice->getRawOriginal('total');
  124. $newStatus = match (true) {
  125. $totalPaidInInvoiceCurrencyCents > $invoiceTotalInInvoiceCurrencyCents => InvoiceStatus::Overpaid,
  126. $totalPaidInInvoiceCurrencyCents === $invoiceTotalInInvoiceCurrencyCents => InvoiceStatus::Paid,
  127. $totalPaidInInvoiceCurrencyCents === 0 => $invoice->last_sent_at ? InvoiceStatus::Sent : InvoiceStatus::Unsent,
  128. default => InvoiceStatus::Partial,
  129. };
  130. $paidAt = $invoice->paid_at;
  131. if (in_array($newStatus, [InvoiceStatus::Paid, InvoiceStatus::Overpaid]) && ! $paidAt) {
  132. $paidAt = $invoice->deposits()
  133. ->latest('posted_at')
  134. ->value('posted_at');
  135. }
  136. $invoice->update([
  137. 'amount_paid' => CurrencyConverter::convertCentsToFormatSimple($totalPaidInInvoiceCurrencyCents, $invoiceCurrency),
  138. 'status' => $newStatus,
  139. 'paid_at' => $paidAt,
  140. ]);
  141. }
  142. protected function updateBillTotals(Bill $bill, ?Transaction $excludedTransaction = null): void
  143. {
  144. if (! $bill->hasPayments()) {
  145. return;
  146. }
  147. $billCurrency = $bill->currency_code;
  148. $withdrawalTotalInBillCurrencyCents = (int) $bill->withdrawals()
  149. ->when($excludedTransaction, fn (Builder $query) => $query->whereKeyNot($excludedTransaction->getKey()))
  150. ->get()
  151. ->sum(function (Transaction $transaction) use ($billCurrency) {
  152. // If the transaction has stored the original bill amount in metadata, use that
  153. if (! empty($transaction->meta) &&
  154. isset($transaction->meta['original_document_currency']) &&
  155. $transaction->meta['original_document_currency'] === $billCurrency &&
  156. isset($transaction->meta['amount_in_document_currency_cents'])) {
  157. return (int) $transaction->meta['amount_in_document_currency_cents'];
  158. }
  159. // Fall back to conversion if metadata is not available
  160. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  161. $amountCents = (int) $transaction->getRawOriginal('amount');
  162. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $billCurrency);
  163. });
  164. $totalPaidInBillCurrencyCents = $withdrawalTotalInBillCurrencyCents;
  165. $billTotalInBillCurrencyCents = (int) $bill->getRawOriginal('total');
  166. $newStatus = match (true) {
  167. $totalPaidInBillCurrencyCents >= $billTotalInBillCurrencyCents => BillStatus::Paid,
  168. $totalPaidInBillCurrencyCents === 0 => BillStatus::Open,
  169. default => BillStatus::Partial,
  170. };
  171. $paidAt = $bill->paid_at;
  172. if ($newStatus === BillStatus::Paid && ! $paidAt) {
  173. $paidAt = $bill->withdrawals()
  174. ->latest('posted_at')
  175. ->value('posted_at');
  176. }
  177. $bill->update([
  178. 'amount_paid' => CurrencyConverter::convertCentsToFormatSimple($totalPaidInBillCurrencyCents, $billCurrency),
  179. 'status' => $newStatus,
  180. 'paid_at' => $paidAt,
  181. ]);
  182. }
  183. }