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 7.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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. public function getRetainedEarnings(string $startDate): Money
  51. {
  52. $revenueAccounts = Account::where('category', AccountCategory::Revenue)
  53. ->get();
  54. $expenseAccounts = Account::where('category', AccountCategory::Expense)
  55. ->get();
  56. $revenue = 0;
  57. $expense = 0;
  58. foreach ($revenueAccounts as $account) {
  59. $revenue += $this->journalEntryRepository->sumCreditAmounts($account, $startDate);
  60. }
  61. foreach ($expenseAccounts as $account) {
  62. $expense += $this->journalEntryRepository->sumDebitAmounts($account, $startDate);
  63. }
  64. $retainedEarnings = $revenue - $expense;
  65. return new Money($retainedEarnings, CurrencyAccessor::getDefaultCurrency());
  66. }
  67. private function calculateNetMovementByCategory(AccountCategory $category, int $debitBalance, int $creditBalance): int
  68. {
  69. return match ($category) {
  70. AccountCategory::Asset, AccountCategory::Expense => $debitBalance - $creditBalance,
  71. AccountCategory::Liability, AccountCategory::Equity, AccountCategory::Revenue => $creditBalance - $debitBalance,
  72. };
  73. }
  74. private function calculateBalances(Account $account, string $startDate, string $endDate): array
  75. {
  76. $debitBalance = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  77. $creditBalance = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  78. return [
  79. 'debit_balance' => $debitBalance,
  80. 'credit_balance' => $creditBalance,
  81. 'net_movement' => $this->calculateNetMovementByCategory($account->category, $debitBalance, $creditBalance),
  82. ];
  83. }
  84. private function calculateStartingBalances(Account $account, string $startDate): array
  85. {
  86. $debitBalanceBefore = $this->journalEntryRepository->sumDebitAmounts($account, $startDate);
  87. $creditBalanceBefore = $this->journalEntryRepository->sumCreditAmounts($account, $startDate);
  88. return [
  89. 'debit_balance_before' => $debitBalanceBefore,
  90. 'credit_balance_before' => $creditBalanceBefore,
  91. 'starting_balance' => $this->calculateNetMovementByCategory($account->category, $debitBalanceBefore, $creditBalanceBefore),
  92. ];
  93. }
  94. public function getBalances(Account $account, string $startDate, string $endDate, array $fields): array
  95. {
  96. $balances = [];
  97. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  98. // Calculate starting balances only if needed
  99. $startingBalances = null;
  100. $needStartingBalances = ! in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)
  101. && (in_array('starting_balance', $fields) || in_array('ending_balance', $fields));
  102. if ($needStartingBalances) {
  103. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  104. }
  105. foreach ($fields as $field) {
  106. $balances[$field] = match ($field) {
  107. 'debit_balance', 'credit_balance', 'net_movement' => $calculatedBalances[$field],
  108. 'starting_balance' => $needStartingBalances ? $startingBalances['starting_balance'] : null,
  109. 'ending_balance' => $needStartingBalances ? $startingBalances['starting_balance'] + $calculatedBalances['net_movement'] : null,
  110. default => null,
  111. };
  112. }
  113. return array_filter($balances, static fn ($value) => $value !== null);
  114. }
  115. public function getTotalBalanceForAllBankAccounts(string $startDate, string $endDate): Money
  116. {
  117. $bankAccounts = BankAccount::with('account')
  118. ->get();
  119. $totalBalance = 0;
  120. foreach ($bankAccounts as $bankAccount) {
  121. $account = $bankAccount->account;
  122. if ($account) {
  123. $endingBalance = $this->getEndingBalance($account, $startDate, $endDate)?->getAmount() ?? 0;
  124. $totalBalance += $endingBalance;
  125. }
  126. }
  127. return new Money($totalBalance, CurrencyAccessor::getDefaultCurrency());
  128. }
  129. public function getAccountCategoryOrder(): array
  130. {
  131. return [
  132. AccountCategory::Asset->getPluralLabel(),
  133. AccountCategory::Liability->getPluralLabel(),
  134. AccountCategory::Equity->getPluralLabel(),
  135. AccountCategory::Revenue->getPluralLabel(),
  136. AccountCategory::Expense->getPluralLabel(),
  137. ];
  138. }
  139. public function getEarliestTransactionDate(): string
  140. {
  141. $earliestDate = Transaction::oldest('posted_at')
  142. ->value('posted_at');
  143. return $earliestDate ?? now()->format('Y-m-d');
  144. }
  145. }