您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

AccountService.php 8.4KB

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