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

TransactionObserver.php 9.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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\Models\Common\Client;
  9. use App\Models\Common\Vendor;
  10. use App\Services\TransactionService;
  11. use App\Utilities\Currency\CurrencyConverter;
  12. use Illuminate\Database\Eloquent\Builder;
  13. use Illuminate\Support\Facades\DB;
  14. class TransactionObserver
  15. {
  16. public function __construct(
  17. protected TransactionService $transactionService,
  18. ) {}
  19. /**
  20. * Handle the Transaction "saving" event.
  21. */
  22. public function saving(Transaction $transaction): void
  23. {
  24. if ($transaction->type->isTransfer() && $transaction->description === null) {
  25. $transaction->description = 'Account Transfer';
  26. }
  27. if ($transaction->transactionable && ! $transaction->payeeable_id) {
  28. $document = $transaction->transactionable;
  29. if ($document instanceof Invoice) {
  30. $transaction->payeeable_id = $document->client_id;
  31. $transaction->payeeable_type = Client::class;
  32. } elseif ($document instanceof Bill) {
  33. $transaction->payeeable_id = $document->vendor_id;
  34. $transaction->payeeable_type = Vendor::class;
  35. }
  36. }
  37. }
  38. /**
  39. * Handle the Transaction "created" event.
  40. */
  41. public function created(Transaction $transaction): void
  42. {
  43. $this->transactionService->createJournalEntries($transaction);
  44. if (! $transaction->transactionable) {
  45. return;
  46. }
  47. $document = $transaction->transactionable;
  48. if ($document instanceof Invoice) {
  49. $this->updateInvoiceTotals($document);
  50. } elseif ($document instanceof Bill) {
  51. $this->updateBillTotals($document);
  52. }
  53. }
  54. /**
  55. * Handle the Transaction "updated" event.
  56. */
  57. public function updated(Transaction $transaction): void
  58. {
  59. $transaction->refresh(); // DO NOT REMOVE
  60. $this->transactionService->updateJournalEntries($transaction);
  61. if (! $transaction->transactionable) {
  62. return;
  63. }
  64. $document = $transaction->transactionable;
  65. if ($document instanceof Invoice) {
  66. $this->updateInvoiceTotals($document);
  67. } elseif ($document instanceof Bill) {
  68. $this->updateBillTotals($document);
  69. }
  70. }
  71. /**
  72. * Handle the Transaction "deleting" event.
  73. */
  74. public function deleting(Transaction $transaction): void
  75. {
  76. DB::transaction(function () use ($transaction) {
  77. $this->transactionService->deleteJournalEntries($transaction);
  78. if (! $transaction->transactionable) {
  79. return;
  80. }
  81. $document = $transaction->transactionable;
  82. if (($document instanceof Invoice || $document instanceof Bill) && ! $document->exists) {
  83. return;
  84. }
  85. if ($document instanceof Invoice) {
  86. $this->updateInvoiceTotals($document, $transaction);
  87. } elseif ($document instanceof Bill) {
  88. $this->updateBillTotals($document, $transaction);
  89. }
  90. });
  91. }
  92. public function deleted(Transaction $transaction): void
  93. {
  94. //
  95. }
  96. protected function updateInvoiceTotals(Invoice $invoice, ?Transaction $excludedTransaction = null): void
  97. {
  98. if (! $invoice->hasPayments()) {
  99. return;
  100. }
  101. $invoiceCurrency = $invoice->currency_code;
  102. $depositTotalInInvoiceCurrencyCents = (int) $invoice->deposits()
  103. ->when($excludedTransaction, fn (Builder $query) => $query->whereKeyNot($excludedTransaction->getKey()))
  104. ->get()
  105. ->sum(function (Transaction $transaction) use ($invoiceCurrency) {
  106. // If the transaction has stored the original invoice amount in metadata, use that
  107. if (! empty($transaction->meta) &&
  108. isset($transaction->meta['original_document_currency']) &&
  109. $transaction->meta['original_document_currency'] === $invoiceCurrency &&
  110. isset($transaction->meta['amount_in_document_currency_cents'])) {
  111. return (int) $transaction->meta['amount_in_document_currency_cents'];
  112. }
  113. // Fall back to conversion if metadata is not available
  114. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  115. $amountCents = (int) $transaction->amount;
  116. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $invoiceCurrency);
  117. });
  118. $withdrawalTotalInInvoiceCurrencyCents = (int) $invoice->withdrawals()
  119. ->when($excludedTransaction, fn (Builder $query) => $query->whereKeyNot($excludedTransaction->getKey()))
  120. ->get()
  121. ->sum(function (Transaction $transaction) use ($invoiceCurrency) {
  122. // If the transaction has stored the original invoice amount in metadata, use that
  123. if (! empty($transaction->meta) &&
  124. isset($transaction->meta['original_document_currency']) &&
  125. $transaction->meta['original_document_currency'] === $invoiceCurrency &&
  126. isset($transaction->meta['amount_in_document_currency_cents'])) {
  127. return (int) $transaction->meta['amount_in_document_currency_cents'];
  128. }
  129. // Fall back to conversion if metadata is not available
  130. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  131. $amountCents = (int) $transaction->amount;
  132. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $invoiceCurrency);
  133. });
  134. $totalPaidInInvoiceCurrencyCents = $depositTotalInInvoiceCurrencyCents - $withdrawalTotalInInvoiceCurrencyCents;
  135. $invoiceTotalInInvoiceCurrencyCents = (int) $invoice->total;
  136. $newStatus = match (true) {
  137. $totalPaidInInvoiceCurrencyCents > $invoiceTotalInInvoiceCurrencyCents => InvoiceStatus::Overpaid,
  138. $totalPaidInInvoiceCurrencyCents === $invoiceTotalInInvoiceCurrencyCents => InvoiceStatus::Paid,
  139. $totalPaidInInvoiceCurrencyCents === 0 => $invoice->last_sent_at ? InvoiceStatus::Sent : InvoiceStatus::Unsent,
  140. default => InvoiceStatus::Partial,
  141. };
  142. $paidAt = $invoice->paid_at;
  143. if (in_array($newStatus, [InvoiceStatus::Paid, InvoiceStatus::Overpaid]) && ! $paidAt) {
  144. $paidAt = $invoice->deposits()
  145. ->latest('posted_at')
  146. ->value('posted_at');
  147. }
  148. $invoice->update([
  149. 'amount_paid' => $totalPaidInInvoiceCurrencyCents,
  150. 'status' => $newStatus,
  151. 'paid_at' => $paidAt,
  152. ]);
  153. }
  154. protected function updateBillTotals(Bill $bill, ?Transaction $excludedTransaction = null): void
  155. {
  156. if (! $bill->hasPayments()) {
  157. return;
  158. }
  159. $billCurrency = $bill->currency_code;
  160. $withdrawalTotalInBillCurrencyCents = (int) $bill->withdrawals()
  161. ->when($excludedTransaction, fn (Builder $query) => $query->whereKeyNot($excludedTransaction->getKey()))
  162. ->get()
  163. ->sum(function (Transaction $transaction) use ($billCurrency) {
  164. // If the transaction has stored the original bill amount in metadata, use that
  165. if (! empty($transaction->meta) &&
  166. isset($transaction->meta['original_document_currency']) &&
  167. $transaction->meta['original_document_currency'] === $billCurrency &&
  168. isset($transaction->meta['amount_in_document_currency_cents'])) {
  169. return (int) $transaction->meta['amount_in_document_currency_cents'];
  170. }
  171. // Fall back to conversion if metadata is not available
  172. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  173. $amountCents = (int) $transaction->amount;
  174. return CurrencyConverter::convertBalance($amountCents, $bankAccountCurrency, $billCurrency);
  175. });
  176. $totalPaidInBillCurrencyCents = $withdrawalTotalInBillCurrencyCents;
  177. $billTotalInBillCurrencyCents = (int) $bill->total;
  178. $newStatus = match (true) {
  179. $totalPaidInBillCurrencyCents >= $billTotalInBillCurrencyCents => BillStatus::Paid,
  180. $totalPaidInBillCurrencyCents === 0 => BillStatus::Open,
  181. default => BillStatus::Partial,
  182. };
  183. $paidAt = $bill->paid_at;
  184. if ($newStatus === BillStatus::Paid && ! $paidAt) {
  185. $paidAt = $bill->withdrawals()
  186. ->latest('posted_at')
  187. ->value('posted_at');
  188. }
  189. $bill->update([
  190. 'amount_paid' => $totalPaidInBillCurrencyCents,
  191. 'status' => $newStatus,
  192. 'paid_at' => $paidAt,
  193. ]);
  194. }
  195. }