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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. <?php
  2. namespace App\Services;
  3. use Akaunting\Money\Money;
  4. use App\DTO\AccountBalanceDTO;
  5. use App\DTO\AccountBalanceReportDTO;
  6. use App\DTO\AccountCategoryDTO;
  7. use App\DTO\AccountDTO;
  8. use App\Enums\Accounting\AccountCategory;
  9. use App\Models\Accounting\Account;
  10. use App\Models\Accounting\Transaction;
  11. use App\Models\Banking\BankAccount;
  12. use App\Repositories\Accounting\JournalEntryRepository;
  13. use App\ValueObjects\BalanceValue;
  14. use Illuminate\Database\Eloquent\Collection;
  15. class AccountService
  16. {
  17. protected JournalEntryRepository $journalEntryRepository;
  18. public function __construct(JournalEntryRepository $journalEntryRepository)
  19. {
  20. $this->journalEntryRepository = $journalEntryRepository;
  21. }
  22. public function getDebitBalance(Account $account, string $startDate, string $endDate): BalanceValue
  23. {
  24. $amount = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  25. return new BalanceValue($amount, $account->currency_code ?? 'USD');
  26. }
  27. public function getCreditBalance(Account $account, string $startDate, string $endDate): BalanceValue
  28. {
  29. $amount = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  30. return new BalanceValue($amount, $account->currency_code ?? 'USD');
  31. }
  32. public function getNetMovement(Account $account, string $startDate, string $endDate): BalanceValue
  33. {
  34. $debitBalance = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  35. $creditBalance = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  36. $netMovement = $this->calculateNetMovementByCategory($account->category, $debitBalance, $creditBalance);
  37. return new BalanceValue($netMovement, $account->currency_code ?? 'USD');
  38. }
  39. public function getStartingBalance(Account $account, string $startDate): ?BalanceValue
  40. {
  41. if (in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  42. return null;
  43. }
  44. $debitBalanceBefore = $this->journalEntryRepository->sumDebitAmounts($account, $startDate);
  45. $creditBalanceBefore = $this->journalEntryRepository->sumCreditAmounts($account, $startDate);
  46. $startingBalance = $this->calculateNetMovementByCategory($account->category, $debitBalanceBefore, $creditBalanceBefore);
  47. return new BalanceValue($startingBalance, $account->currency_code ?? 'USD');
  48. }
  49. public function getEndingBalance(Account $account, string $startDate, string $endDate): ?BalanceValue
  50. {
  51. if (in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  52. return null;
  53. }
  54. $startingBalance = $this->getStartingBalance($account, $startDate)?->getValue();
  55. $netMovement = $this->getNetMovement($account, $startDate, $endDate)->getValue();
  56. $endingBalance = $startingBalance + $netMovement;
  57. return new BalanceValue($endingBalance, $account->currency_code ?? 'USD');
  58. }
  59. public function calculateNetMovementByCategory(AccountCategory $category, int $debitBalance, int $creditBalance): int
  60. {
  61. return match ($category) {
  62. AccountCategory::Asset, AccountCategory::Expense => $debitBalance - $creditBalance,
  63. AccountCategory::Liability, AccountCategory::Equity, AccountCategory::Revenue => $creditBalance - $debitBalance,
  64. };
  65. }
  66. public function getBalances(Account $account, string $startDate, string $endDate): array
  67. {
  68. $debitBalance = $this->getDebitBalance($account, $startDate, $endDate)->getValue();
  69. $creditBalance = $this->getCreditBalance($account, $startDate, $endDate)->getValue();
  70. $netMovement = $this->getNetMovement($account, $startDate, $endDate)->getValue();
  71. $balances = [
  72. 'debit_balance' => $debitBalance,
  73. 'credit_balance' => $creditBalance,
  74. 'net_movement' => $netMovement,
  75. ];
  76. if (! in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  77. $balances['starting_balance'] = $this->getStartingBalance($account, $startDate)?->getValue();
  78. $balances['ending_balance'] = $this->getEndingBalance($account, $startDate, $endDate)?->getValue();
  79. }
  80. return $balances;
  81. }
  82. public function getBalancesFormatted(Account $account, string $startDate, string $endDate): AccountBalanceDTO
  83. {
  84. $balances = $this->getBalances($account, $startDate, $endDate);
  85. $currency = $account->currency_code ?? 'USD';
  86. return $this->formatBalances($balances, $currency);
  87. }
  88. public function formatBalances(array $balances, string $currency): AccountBalanceDTO
  89. {
  90. foreach ($balances as $key => $balance) {
  91. $balances[$key] = Money::{$currency}($balance)->format();
  92. }
  93. return new AccountBalanceDTO(
  94. startingBalance: $balances['starting_balance'] ?? null,
  95. debitBalance: $balances['debit_balance'],
  96. creditBalance: $balances['credit_balance'],
  97. netMovement: $balances['net_movement'] ?? null,
  98. endingBalance: $balances['ending_balance'] ?? null,
  99. );
  100. }
  101. public function buildAccountBalanceReport(string $startDate, string $endDate): AccountBalanceReportDTO
  102. {
  103. $allCategories = $this->getAccountCategoryOrder();
  104. $categoryGroupedAccounts = Account::whereHas('journalEntries')
  105. ->select('id', 'name', 'currency_code', 'category', 'code')
  106. ->get()
  107. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  108. ->sortBy(static fn (Collection $groupedAccounts, string $key) => array_search($key, $allCategories, true));
  109. $accountCategories = [];
  110. $reportTotalBalances = [
  111. 'debit_balance' => 0,
  112. 'credit_balance' => 0,
  113. ];
  114. foreach ($allCategories as $categoryName) {
  115. $accountsInCategory = $categoryGroupedAccounts[$categoryName] ?? collect();
  116. $categorySummaryBalances = [
  117. 'debit_balance' => 0,
  118. 'credit_balance' => 0,
  119. 'net_movement' => 0,
  120. ];
  121. if (! in_array($categoryName, [AccountCategory::Expense->getPluralLabel(), AccountCategory::Revenue->getPluralLabel()], true)) {
  122. $categorySummaryBalances['starting_balance'] = 0;
  123. $categorySummaryBalances['ending_balance'] = 0;
  124. }
  125. $categoryAccounts = [];
  126. foreach ($accountsInCategory as $account) {
  127. $accountBalances = $this->getBalances($account, $startDate, $endDate);
  128. if (array_sum($accountBalances) === 0) {
  129. continue;
  130. }
  131. foreach ($accountBalances as $accountBalanceType => $accountBalance) {
  132. $categorySummaryBalances[$accountBalanceType] += $accountBalance;
  133. }
  134. $formattedAccountBalances = $this->formatBalances($accountBalances, $account->currency_code ?? 'USD');
  135. $categoryAccounts[] = new AccountDTO(
  136. $account->name,
  137. $account->code,
  138. $formattedAccountBalances,
  139. );
  140. }
  141. $reportTotalBalances['debit_balance'] += $categorySummaryBalances['debit_balance'];
  142. $reportTotalBalances['credit_balance'] += $categorySummaryBalances['credit_balance'];
  143. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances, $accountsInCategory->first()->currency_code ?? 'USD');
  144. $accountCategories[$categoryName] = new AccountCategoryDTO(
  145. $categoryAccounts,
  146. $formattedCategorySummaryBalances,
  147. );
  148. }
  149. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances, 'USD');
  150. return new AccountBalanceReportDTO($accountCategories, $formattedReportTotalBalances);
  151. }
  152. public function getTotalBalanceForAllBankAccount(string $startDate, string $endDate): BalanceValue
  153. {
  154. $bankAccountsAccounts = Account::where('accountable_type', BankAccount::class)
  155. ->get();
  156. $totalBalance = 0;
  157. // Get ending balance for each bank account
  158. foreach ($bankAccountsAccounts as $account) {
  159. $endingBalance = $this->getEndingBalance($account, $startDate, $endDate)?->getValue() ?? 0;
  160. $totalBalance += $endingBalance;
  161. }
  162. return new BalanceValue($totalBalance, 'USD');
  163. }
  164. public function getAccountCategoryOrder(): array
  165. {
  166. return [
  167. AccountCategory::Asset->getPluralLabel(),
  168. AccountCategory::Liability->getPluralLabel(),
  169. AccountCategory::Equity->getPluralLabel(),
  170. AccountCategory::Revenue->getPluralLabel(),
  171. AccountCategory::Expense->getPluralLabel(),
  172. ];
  173. }
  174. public function getEarliestTransactionDate(): string
  175. {
  176. $earliestDate = Transaction::oldest('posted_at')
  177. ->value('posted_at');
  178. return $earliestDate ?? now()->format('Y-m-d');
  179. }
  180. }