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.

ReportService.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. <?php
  2. namespace App\Services;
  3. use App\DTO\AccountBalanceDTO;
  4. use App\DTO\AccountCategoryDTO;
  5. use App\DTO\AccountDTO;
  6. use App\DTO\AccountTransactionDTO;
  7. use App\DTO\ReportDTO;
  8. use App\Enums\Accounting\AccountCategory;
  9. use App\Models\Accounting\Account;
  10. use App\Support\Column;
  11. use App\Utilities\Currency\CurrencyAccessor;
  12. use Illuminate\Database\Eloquent\Builder;
  13. use Illuminate\Database\Eloquent\Collection;
  14. use Illuminate\Database\Eloquent\Relations\Relation;
  15. class ReportService
  16. {
  17. public function __construct(
  18. protected AccountService $accountService,
  19. ) {}
  20. public function formatBalances(array $balances): AccountBalanceDTO
  21. {
  22. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  23. foreach ($balances as $key => $balance) {
  24. $balances[$key] = money($balance, $defaultCurrency)->format();
  25. }
  26. return new AccountBalanceDTO(
  27. startingBalance: $balances['starting_balance'] ?? null,
  28. debitBalance: $balances['debit_balance'] ?? null,
  29. creditBalance: $balances['credit_balance'] ?? null,
  30. netMovement: $balances['net_movement'] ?? null,
  31. endingBalance: $balances['ending_balance'] ?? null,
  32. );
  33. }
  34. private function filterBalances(array $balances, array $fields): array
  35. {
  36. return array_filter($balances, static fn ($key) => in_array($key, $fields, true), ARRAY_FILTER_USE_KEY);
  37. }
  38. private function getCategoryGroupedAccounts(array $allCategories): Collection
  39. {
  40. return Account::whereHas('journalEntries')
  41. ->select('id', 'name', 'currency_code', 'category', 'code')
  42. ->get()
  43. ->groupBy(fn (Account $account) => $account->category->getPluralLabel())
  44. ->sortBy(static fn (Collection $groupedAccounts, string $key) => array_search($key, $allCategories, true));
  45. }
  46. public function buildAccountBalanceReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  47. {
  48. $allCategories = $this->accountService->getAccountCategoryOrder();
  49. $categoryGroupedAccounts = $this->getCategoryGroupedAccounts($allCategories);
  50. $balanceFields = ['starting_balance', 'debit_balance', 'credit_balance', 'net_movement', 'ending_balance'];
  51. $columnNameKeys = array_map(fn (Column $column) => $column->getName(), $columns);
  52. $updatedBalanceFields = array_filter($balanceFields, fn (string $balanceField) => in_array($balanceField, $columnNameKeys, true));
  53. return $this->buildReport(
  54. $allCategories,
  55. $categoryGroupedAccounts,
  56. fn (Account $account) => $this->accountService->getBalances($account, $startDate, $endDate, $updatedBalanceFields),
  57. $updatedBalanceFields,
  58. $columns,
  59. fn (string $categoryName, array &$categorySummaryBalances) => $this->adjustAccountBalanceCategoryFields($categoryName, $categorySummaryBalances),
  60. );
  61. }
  62. public function buildAccountTransactionsReport(string $startDate, string $endDate, ?array $columns = null, ?string $accountId = 'all'): ReportDTO
  63. {
  64. $columns ??= [];
  65. $query = Account::whereHas('journalEntries.transaction', function (Builder $query) use ($startDate, $endDate) {
  66. $query->whereBetween('posted_at', [$startDate, $endDate]);
  67. })
  68. ->with(['journalEntries' => function (Relation $query) use ($startDate, $endDate) {
  69. $query->whereHas('transaction', function (Builder $query) use ($startDate, $endDate) {
  70. $query->whereBetween('posted_at', [$startDate, $endDate]);
  71. })
  72. ->with(['transaction' => function (Relation $query) {
  73. $query->select(['id', 'description', 'posted_at']);
  74. }])
  75. ->select(['account_id', 'transaction_id'])
  76. ->selectRaw('SUM(CASE WHEN type = "debit" THEN amount ELSE 0 END) AS total_debit')
  77. ->selectRaw('SUM(CASE WHEN type = "credit" THEN amount ELSE 0 END) AS total_credit')
  78. ->selectRaw('(SELECT MIN(posted_at) FROM transactions WHERE transactions.id = journal_entries.transaction_id) AS earliest_posted_at')
  79. ->groupBy('account_id', 'transaction_id')
  80. ->orderBy('earliest_posted_at');
  81. }])
  82. ->select(['id', 'name', 'category', 'subtype_id', 'currency_code']);
  83. if ($accountId !== 'all') {
  84. $query->where('id', $accountId);
  85. }
  86. $accounts = $query->get();
  87. $reportCategories = [];
  88. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  89. foreach ($accounts as $account) {
  90. $accountTransactions = [];
  91. $startingBalance = $this->accountService->getStartingBalance($account, $startDate, true);
  92. $currentBalance = $startingBalance?->getAmount() ?? 0;
  93. $totalDebit = 0;
  94. $totalCredit = 0;
  95. $accountTransactions[] = new AccountTransactionDTO(
  96. date: 'Starting Balance',
  97. description: '',
  98. debit: '',
  99. credit: '',
  100. balance: $startingBalance?->formatInDefaultCurrency() ?? 0,
  101. );
  102. foreach ($account->journalEntries as $journalEntry) {
  103. $transaction = $journalEntry->transaction;
  104. $totalDebit += $journalEntry->total_debit;
  105. $totalCredit += $journalEntry->total_credit;
  106. $currentBalance += $journalEntry->total_debit;
  107. $currentBalance -= $journalEntry->total_credit;
  108. $accountTransactions[] = new AccountTransactionDTO(
  109. date: $transaction->posted_at->format('Y-m-d'),
  110. description: $transaction->description ?? '',
  111. debit: $journalEntry->total_debit ? money($journalEntry->total_debit, $defaultCurrency)->format() : '',
  112. credit: $journalEntry->total_credit ? money($journalEntry->total_credit, $defaultCurrency)->format() : '',
  113. balance: money($currentBalance, $defaultCurrency)->format(),
  114. );
  115. }
  116. $balanceChange = $currentBalance - ($startingBalance?->getAmount() ?? 0);
  117. $accountTransactions[] = new AccountTransactionDTO(
  118. date: 'Totals and Ending Balance',
  119. description: '',
  120. debit: money($totalDebit, $defaultCurrency)->format(),
  121. credit: money($totalCredit, $defaultCurrency)->format(),
  122. balance: money($currentBalance, $defaultCurrency)->format(),
  123. );
  124. $accountTransactions[] = new AccountTransactionDTO(
  125. date: 'Balance Change',
  126. description: '',
  127. debit: '',
  128. credit: '',
  129. balance: money($balanceChange, $defaultCurrency)->format(),
  130. );
  131. $reportCategories[] = [
  132. 'category' => $account->name,
  133. 'under' => $account->category->getLabel() . ' > ' . $account->subtype->name,
  134. 'transactions' => $accountTransactions,
  135. ];
  136. }
  137. return new ReportDTO(categories: $reportCategories, fields: $columns);
  138. }
  139. private function buildReport(array $allCategories, Collection $categoryGroupedAccounts, callable $balanceCalculator, array $balanceFields, array $allFields, ?callable $initializeCategoryBalances = null, bool $includeRetainedEarnings = false, ?string $startDate = null): ReportDTO
  140. {
  141. $accountCategories = [];
  142. $reportTotalBalances = array_fill_keys($balanceFields, 0);
  143. foreach ($allCategories as $categoryName) {
  144. $accountsInCategory = $categoryGroupedAccounts[$categoryName] ?? collect();
  145. $categorySummaryBalances = array_fill_keys($balanceFields, 0);
  146. if ($initializeCategoryBalances) {
  147. $initializeCategoryBalances($categoryName, $categorySummaryBalances);
  148. }
  149. $categoryAccounts = [];
  150. foreach ($accountsInCategory as $account) {
  151. /** @var Account $account */
  152. $accountBalances = $balanceCalculator($account);
  153. if (array_sum($accountBalances) === 0) {
  154. continue;
  155. }
  156. foreach ($accountBalances as $accountBalanceType => $accountBalance) {
  157. if (array_key_exists($accountBalanceType, $categorySummaryBalances)) {
  158. $categorySummaryBalances[$accountBalanceType] += $accountBalance;
  159. }
  160. }
  161. $filteredAccountBalances = $this->filterBalances($accountBalances, $balanceFields);
  162. $formattedAccountBalances = $this->formatBalances($filteredAccountBalances);
  163. $categoryAccounts[] = new AccountDTO(
  164. $account->name,
  165. $account->code,
  166. $formattedAccountBalances,
  167. );
  168. }
  169. if ($includeRetainedEarnings && $categoryName === AccountCategory::Equity->getPluralLabel()) {
  170. $retainedEarnings = $this->accountService->getRetainedEarnings($startDate);
  171. $retainedEarningsAmount = $retainedEarnings->getAmount();
  172. if ($retainedEarningsAmount >= 0) {
  173. $categorySummaryBalances['credit_balance'] += $retainedEarningsAmount;
  174. $categoryAccounts[] = new AccountDTO(
  175. 'Retained Earnings',
  176. 'RE',
  177. $this->formatBalances(['debit_balance' => 0, 'credit_balance' => $retainedEarningsAmount])
  178. );
  179. } else {
  180. $categorySummaryBalances['debit_balance'] += abs($retainedEarningsAmount);
  181. $categoryAccounts[] = new AccountDTO(
  182. 'Retained Earnings',
  183. 'RE',
  184. $this->formatBalances(['debit_balance' => abs($retainedEarningsAmount), 'credit_balance' => 0])
  185. );
  186. }
  187. }
  188. foreach ($balanceFields as $field) {
  189. if (array_key_exists($field, $categorySummaryBalances)) {
  190. $reportTotalBalances[$field] += $categorySummaryBalances[$field];
  191. }
  192. }
  193. $filteredCategorySummaryBalances = $this->filterBalances($categorySummaryBalances, $balanceFields);
  194. $formattedCategorySummaryBalances = $this->formatBalances($filteredCategorySummaryBalances);
  195. $accountCategories[$categoryName] = new AccountCategoryDTO(
  196. $categoryAccounts,
  197. $formattedCategorySummaryBalances,
  198. );
  199. }
  200. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  201. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $allFields);
  202. }
  203. private function adjustAccountBalanceCategoryFields(string $categoryName, array &$categorySummaryBalances): void
  204. {
  205. if (in_array($categoryName, [AccountCategory::Expense->getPluralLabel(), AccountCategory::Revenue->getPluralLabel()], true)) {
  206. unset($categorySummaryBalances['starting_balance'], $categorySummaryBalances['ending_balance']);
  207. }
  208. }
  209. public function buildTrialBalanceReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  210. {
  211. $allCategories = $this->accountService->getAccountCategoryOrder();
  212. $categoryGroupedAccounts = $this->getCategoryGroupedAccounts($allCategories);
  213. $balanceFields = ['debit_balance', 'credit_balance'];
  214. return $this->buildReport($allCategories, $categoryGroupedAccounts, function (Account $account) use ($startDate, $endDate) {
  215. $endingBalance = $this->accountService->getEndingBalance($account, $startDate, $endDate)?->getAmount() ?? 0;
  216. if ($endingBalance === 0) {
  217. return [];
  218. }
  219. return $this->calculateTrialBalance($account->category, $endingBalance);
  220. }, $balanceFields, $columns, null, true, $startDate);
  221. }
  222. private function calculateTrialBalance(AccountCategory $category, int $endingBalance): array
  223. {
  224. if (in_array($category, [AccountCategory::Asset, AccountCategory::Expense], true)) {
  225. if ($endingBalance >= 0) {
  226. return ['debit_balance' => $endingBalance, 'credit_balance' => 0];
  227. }
  228. return ['debit_balance' => 0, 'credit_balance' => abs($endingBalance)];
  229. }
  230. if ($endingBalance >= 0) {
  231. return ['debit_balance' => 0, 'credit_balance' => $endingBalance];
  232. }
  233. return ['debit_balance' => abs($endingBalance), 'credit_balance' => 0];
  234. }
  235. }