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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  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\JournalEntry;
  7. use App\Models\Accounting\Transaction;
  8. use App\Repositories\Accounting\JournalEntryRepository;
  9. use App\Utilities\Currency\CurrencyAccessor;
  10. use App\ValueObjects\Money;
  11. use Illuminate\Support\Facades\DB;
  12. class AccountService implements AccountHandler
  13. {
  14. public function __construct(
  15. protected JournalEntryRepository $journalEntryRepository
  16. ) {}
  17. public function getDebitBalance(Account $account, string $startDate, string $endDate): Money
  18. {
  19. $amount = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  20. return new Money($amount, $account->currency_code);
  21. }
  22. public function getCreditBalance(Account $account, string $startDate, string $endDate): Money
  23. {
  24. $amount = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  25. return new Money($amount, $account->currency_code);
  26. }
  27. public function getNetMovement(Account $account, string $startDate, string $endDate): Money
  28. {
  29. $balances = $this->calculateBalances($account, $startDate, $endDate);
  30. return new Money($balances['net_movement'], $account->currency_code);
  31. }
  32. public function getStartingBalance(Account $account, string $startDate, bool $override = false): ?Money
  33. {
  34. if ($override === false && in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  35. return null;
  36. }
  37. $balances = $this->calculateStartingBalances($account, $startDate);
  38. return new Money($balances['starting_balance'], $account->currency_code);
  39. }
  40. public function getEndingBalance(Account $account, string $startDate, string $endDate): ?Money
  41. {
  42. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  43. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  44. $netMovement = $calculatedBalances['net_movement'];
  45. if (in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  46. return new Money($netMovement, $account->currency_code);
  47. }
  48. $endingBalance = $startingBalances['starting_balance'] + $netMovement;
  49. return new Money($endingBalance, $account->currency_code);
  50. }
  51. public function getRetainedEarnings(string $startDate): Money
  52. {
  53. $revenue = JournalEntry::whereHas('account', static function ($query) {
  54. $query->where('category', AccountCategory::Revenue);
  55. })
  56. ->where('type', 'credit')
  57. ->whereHas('transaction', static function ($query) use ($startDate) {
  58. $query->where('posted_at', '<=', $startDate);
  59. })
  60. ->sum('amount');
  61. $expense = JournalEntry::whereHas('account', static function ($query) {
  62. $query->where('category', AccountCategory::Expense);
  63. })
  64. ->where('type', 'debit')
  65. ->whereHas('transaction', static function ($query) use ($startDate) {
  66. $query->where('posted_at', '<=', $startDate);
  67. })
  68. ->sum('amount');
  69. $retainedEarnings = $revenue - $expense;
  70. return new Money($retainedEarnings, CurrencyAccessor::getDefaultCurrency());
  71. }
  72. private function calculateNetMovementByCategory(AccountCategory $category, int $debitBalance, int $creditBalance): int
  73. {
  74. return match ($category) {
  75. AccountCategory::Asset, AccountCategory::Expense => $debitBalance - $creditBalance,
  76. AccountCategory::Liability, AccountCategory::Equity, AccountCategory::Revenue => $creditBalance - $debitBalance,
  77. };
  78. }
  79. private function calculateBalances(Account $account, string $startDate, string $endDate): array
  80. {
  81. $debitBalance = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  82. $creditBalance = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  83. return [
  84. 'debit_balance' => $debitBalance,
  85. 'credit_balance' => $creditBalance,
  86. 'net_movement' => $this->calculateNetMovementByCategory($account->category, $debitBalance, $creditBalance),
  87. ];
  88. }
  89. private function calculateStartingBalances(Account $account, string $startDate): array
  90. {
  91. $debitBalanceBefore = $this->journalEntryRepository->sumDebitAmounts($account, $startDate);
  92. $creditBalanceBefore = $this->journalEntryRepository->sumCreditAmounts($account, $startDate);
  93. return [
  94. 'debit_balance_before' => $debitBalanceBefore,
  95. 'credit_balance_before' => $creditBalanceBefore,
  96. 'starting_balance' => $this->calculateNetMovementByCategory($account->category, $debitBalanceBefore, $creditBalanceBefore),
  97. ];
  98. }
  99. public function getBalances(Account $account, string $startDate, string $endDate, array $fields): array
  100. {
  101. $balances = [];
  102. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  103. // Calculate starting balances only if needed
  104. $startingBalances = null;
  105. $needStartingBalances = ! in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)
  106. && (in_array('starting_balance', $fields) || in_array('ending_balance', $fields));
  107. if ($needStartingBalances) {
  108. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  109. }
  110. foreach ($fields as $field) {
  111. $balances[$field] = match ($field) {
  112. 'debit_balance', 'credit_balance', 'net_movement' => $calculatedBalances[$field],
  113. 'starting_balance' => $needStartingBalances ? $startingBalances['starting_balance'] : null,
  114. 'ending_balance' => $needStartingBalances ? $startingBalances['starting_balance'] + $calculatedBalances['net_movement'] : null,
  115. default => null,
  116. };
  117. }
  118. return array_filter($balances, static fn ($value) => $value !== null);
  119. }
  120. public function getTotalBalanceForAllBankAccounts(string $startDate, string $endDate): Money
  121. {
  122. $accountIds = Account::whereHas('bankAccount')
  123. ->pluck('id')
  124. ->toArray();
  125. if (empty($accountIds)) {
  126. return new Money(0, CurrencyAccessor::getDefaultCurrency());
  127. }
  128. $result = DB::table('journal_entries')
  129. ->join('transactions', 'journal_entries.transaction_id', '=', 'transactions.id')
  130. ->whereIn('journal_entries.account_id', $accountIds)
  131. ->where('transactions.posted_at', '<=', $endDate)
  132. ->selectRaw('
  133. SUM(CASE
  134. WHEN transactions.posted_at <= ? AND journal_entries.type = "debit" THEN journal_entries.amount
  135. WHEN transactions.posted_at <= ? AND journal_entries.type = "credit" THEN -journal_entries.amount
  136. ELSE 0
  137. END) AS totalStartingBalance,
  138. SUM(CASE
  139. WHEN transactions.posted_at BETWEEN ? AND ? AND journal_entries.type = "debit" THEN journal_entries.amount
  140. WHEN transactions.posted_at BETWEEN ? AND ? AND journal_entries.type = "credit" THEN -journal_entries.amount
  141. ELSE 0
  142. END) AS totalNetMovement
  143. ', [
  144. $startDate,
  145. $startDate,
  146. $startDate,
  147. $endDate,
  148. $startDate,
  149. $endDate,
  150. ])
  151. ->first();
  152. $totalBalance = $result->totalStartingBalance + $result->totalNetMovement;
  153. return new Money($totalBalance, CurrencyAccessor::getDefaultCurrency());
  154. }
  155. public function getAccountCategoryOrder(): array
  156. {
  157. return [
  158. AccountCategory::Asset->getPluralLabel(),
  159. AccountCategory::Liability->getPluralLabel(),
  160. AccountCategory::Equity->getPluralLabel(),
  161. AccountCategory::Revenue->getPluralLabel(),
  162. AccountCategory::Expense->getPluralLabel(),
  163. ];
  164. }
  165. public function getEarliestTransactionDate(): string
  166. {
  167. $earliestDate = Transaction::oldest('posted_at')
  168. ->value('posted_at');
  169. return $earliestDate ?? now()->format('Y-m-d');
  170. }
  171. }