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.

AccountService.php 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. <?php
  2. namespace App\Services;
  3. use App\Contracts\AccountHandler;
  4. use App\Enums\Accounting\AccountCategory;
  5. use App\Models\Accounting\Account;
  6. use App\Models\Accounting\Transaction;
  7. use App\Models\Banking\BankAccount;
  8. use App\Repositories\Accounting\JournalEntryRepository;
  9. use App\Utilities\Currency\CurrencyAccessor;
  10. use App\ValueObjects\Money;
  11. class AccountService implements AccountHandler
  12. {
  13. public function __construct(
  14. protected JournalEntryRepository $journalEntryRepository
  15. ) {}
  16. public function getDebitBalance(Account $account, string $startDate, string $endDate): Money
  17. {
  18. $amount = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  19. return new Money($amount, $account->currency_code);
  20. }
  21. public function getCreditBalance(Account $account, string $startDate, string $endDate): Money
  22. {
  23. $amount = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  24. return new Money($amount, $account->currency_code);
  25. }
  26. public function getNetMovement(Account $account, string $startDate, string $endDate): Money
  27. {
  28. $balances = $this->calculateBalances($account, $startDate, $endDate);
  29. return new Money($balances['net_movement'], $account->currency_code);
  30. }
  31. public function getStartingBalance(Account $account, string $startDate, bool $override = false): ?Money
  32. {
  33. if ($override === false && in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  34. return null;
  35. }
  36. $balances = $this->calculateStartingBalances($account, $startDate);
  37. return new Money($balances['starting_balance'], $account->currency_code);
  38. }
  39. public function getEndingBalance(Account $account, string $startDate, string $endDate): ?Money
  40. {
  41. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  42. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  43. $netMovement = $calculatedBalances['net_movement'];
  44. if (in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  45. return new Money($netMovement, $account->currency_code);
  46. }
  47. $endingBalance = $startingBalances['starting_balance'] + $netMovement;
  48. return new Money($endingBalance, $account->currency_code);
  49. }
  50. private function calculateNetMovementByCategory(AccountCategory $category, int $debitBalance, int $creditBalance): int
  51. {
  52. return match ($category) {
  53. AccountCategory::Asset, AccountCategory::Expense => $debitBalance - $creditBalance,
  54. AccountCategory::Liability, AccountCategory::Equity, AccountCategory::Revenue => $creditBalance - $debitBalance,
  55. };
  56. }
  57. private function calculateBalances(Account $account, string $startDate, string $endDate): array
  58. {
  59. $debitBalance = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  60. $creditBalance = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  61. return [
  62. 'debit_balance' => $debitBalance,
  63. 'credit_balance' => $creditBalance,
  64. 'net_movement' => $this->calculateNetMovementByCategory($account->category, $debitBalance, $creditBalance),
  65. ];
  66. }
  67. private function calculateStartingBalances(Account $account, string $startDate): array
  68. {
  69. $debitBalanceBefore = $this->journalEntryRepository->sumDebitAmounts($account, $startDate);
  70. $creditBalanceBefore = $this->journalEntryRepository->sumCreditAmounts($account, $startDate);
  71. return [
  72. 'debit_balance_before' => $debitBalanceBefore,
  73. 'credit_balance_before' => $creditBalanceBefore,
  74. 'starting_balance' => $this->calculateNetMovementByCategory($account->category, $debitBalanceBefore, $creditBalanceBefore),
  75. ];
  76. }
  77. public function getBalances(Account $account, string $startDate, string $endDate, array $fields): array
  78. {
  79. $balances = [];
  80. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  81. // Calculate starting balances only if needed
  82. $startingBalances = null;
  83. $needStartingBalances = ! in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)
  84. && (in_array('starting_balance', $fields) || in_array('ending_balance', $fields));
  85. if ($needStartingBalances) {
  86. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  87. }
  88. foreach ($fields as $field) {
  89. $balances[$field] = match ($field) {
  90. 'debit_balance', 'credit_balance', 'net_movement' => $calculatedBalances[$field],
  91. 'starting_balance' => $needStartingBalances ? $startingBalances['starting_balance'] : null,
  92. 'ending_balance' => $needStartingBalances ? $startingBalances['starting_balance'] + $calculatedBalances['net_movement'] : null,
  93. default => null,
  94. };
  95. }
  96. return array_filter($balances, static fn ($value) => $value !== null);
  97. }
  98. public function getTotalBalanceForAllBankAccounts(string $startDate, string $endDate): Money
  99. {
  100. $bankAccounts = BankAccount::with('account')
  101. ->get();
  102. $totalBalance = 0;
  103. foreach ($bankAccounts as $bankAccount) {
  104. $account = $bankAccount->account;
  105. if ($account) {
  106. $endingBalance = $this->getEndingBalance($account, $startDate, $endDate)?->getAmount() ?? 0;
  107. $totalBalance += $endingBalance;
  108. }
  109. }
  110. return new Money($totalBalance, CurrencyAccessor::getDefaultCurrency());
  111. }
  112. public function getAccountCategoryOrder(): array
  113. {
  114. return [
  115. AccountCategory::Asset->getPluralLabel(),
  116. AccountCategory::Liability->getPluralLabel(),
  117. AccountCategory::Equity->getPluralLabel(),
  118. AccountCategory::Revenue->getPluralLabel(),
  119. AccountCategory::Expense->getPluralLabel(),
  120. ];
  121. }
  122. public function getEarliestTransactionDate(): string
  123. {
  124. $earliestDate = Transaction::oldest('posted_at')
  125. ->value('posted_at');
  126. return $earliestDate ?? now()->format('Y-m-d');
  127. }
  128. }