Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

AccountService.php 8.7KB

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