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

ReportService.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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\Relations\Relation;
  14. use Illuminate\Support\Collection;
  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:id,type,description,posted_at')
  73. ->select(['account_id', 'transaction_id'])
  74. ->selectRaw('SUM(CASE WHEN type = "debit" THEN amount ELSE 0 END) AS total_debit')
  75. ->selectRaw('SUM(CASE WHEN type = "credit" THEN amount ELSE 0 END) AS total_credit')
  76. ->selectRaw('(SELECT MIN(posted_at) FROM transactions WHERE transactions.id = journal_entries.transaction_id) AS earliest_posted_at')
  77. ->groupBy('account_id', 'transaction_id')
  78. ->orderBy('earliest_posted_at');
  79. }])
  80. ->select(['id', 'name', 'category', 'subtype_id', 'currency_code']);
  81. if ($accountId !== 'all') {
  82. $query->where('id', $accountId);
  83. }
  84. $accounts = $query->get();
  85. $reportCategories = [];
  86. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  87. foreach ($accounts as $account) {
  88. $accountTransactions = [];
  89. $startingBalance = $this->accountService->getStartingBalance($account, $startDate, true);
  90. $currentBalance = $startingBalance?->getAmount() ?? 0;
  91. $totalDebit = 0;
  92. $totalCredit = 0;
  93. $accountTransactions[] = new AccountTransactionDTO(
  94. id: null,
  95. date: 'Starting Balance',
  96. description: '',
  97. debit: '',
  98. credit: '',
  99. balance: $startingBalance?->formatInDefaultCurrency() ?? 0,
  100. type: null,
  101. tableAction: null,
  102. );
  103. foreach ($account->journalEntries as $journalEntry) {
  104. $transaction = $journalEntry->transaction;
  105. $totalDebit += $journalEntry->total_debit;
  106. $totalCredit += $journalEntry->total_credit;
  107. $currentBalance += $journalEntry->total_debit;
  108. $currentBalance -= $journalEntry->total_credit;
  109. $accountTransactions[] = new AccountTransactionDTO(
  110. id: $transaction->id,
  111. date: $transaction->posted_at->format('Y-m-d'),
  112. description: $transaction->description ?? '',
  113. debit: $journalEntry->total_debit ? money($journalEntry->total_debit, $defaultCurrency)->format() : '',
  114. credit: $journalEntry->total_credit ? money($journalEntry->total_credit, $defaultCurrency)->format() : '',
  115. balance: money($currentBalance, $defaultCurrency)->format(),
  116. type: $transaction->type,
  117. tableAction: $transaction->type->isJournal() ? 'updateJournalTransaction' : 'updateTransaction',
  118. );
  119. }
  120. $balanceChange = $currentBalance - ($startingBalance?->getAmount() ?? 0);
  121. $accountTransactions[] = new AccountTransactionDTO(
  122. id: null,
  123. date: 'Totals and Ending Balance',
  124. description: '',
  125. debit: money($totalDebit, $defaultCurrency)->format(),
  126. credit: money($totalCredit, $defaultCurrency)->format(),
  127. balance: money($currentBalance, $defaultCurrency)->format(),
  128. type: null,
  129. tableAction: null,
  130. );
  131. $accountTransactions[] = new AccountTransactionDTO(
  132. id: null,
  133. date: 'Balance Change',
  134. description: '',
  135. debit: '',
  136. credit: '',
  137. balance: money($balanceChange, $defaultCurrency)->format(),
  138. type: null,
  139. tableAction: null,
  140. );
  141. $reportCategories[] = [
  142. 'category' => $account->name,
  143. 'under' => $account->category->getLabel() . ' > ' . $account->subtype->name,
  144. 'transactions' => $accountTransactions,
  145. ];
  146. }
  147. return new ReportDTO(categories: $reportCategories, fields: $columns);
  148. }
  149. private function buildReport(array $allCategories, Collection $categoryGroupedAccounts, callable $balanceCalculator, array $balanceFields, array $allFields, ?callable $initializeCategoryBalances = null, bool $includeRetainedEarnings = false, ?string $startDate = null): ReportDTO
  150. {
  151. $accountCategories = [];
  152. $reportTotalBalances = array_fill_keys($balanceFields, 0);
  153. foreach ($allCategories as $categoryName) {
  154. $accountsInCategory = $categoryGroupedAccounts[$categoryName] ?? collect();
  155. $categorySummaryBalances = array_fill_keys($balanceFields, 0);
  156. if ($initializeCategoryBalances) {
  157. $initializeCategoryBalances($categoryName, $categorySummaryBalances);
  158. }
  159. $categoryAccounts = [];
  160. foreach ($accountsInCategory as $account) {
  161. /** @var Account $account */
  162. $accountBalances = $balanceCalculator($account);
  163. if (array_sum($accountBalances) === 0) {
  164. continue;
  165. }
  166. foreach ($accountBalances as $accountBalanceType => $accountBalance) {
  167. if (array_key_exists($accountBalanceType, $categorySummaryBalances)) {
  168. $categorySummaryBalances[$accountBalanceType] += $accountBalance;
  169. }
  170. }
  171. $filteredAccountBalances = $this->filterBalances($accountBalances, $balanceFields);
  172. $formattedAccountBalances = $this->formatBalances($filteredAccountBalances);
  173. $categoryAccounts[] = new AccountDTO(
  174. $account->name,
  175. $account->code,
  176. $account->id,
  177. $formattedAccountBalances,
  178. );
  179. }
  180. if ($includeRetainedEarnings && $categoryName === AccountCategory::Equity->getPluralLabel()) {
  181. $retainedEarnings = $this->accountService->getRetainedEarnings($startDate);
  182. $retainedEarningsAmount = $retainedEarnings->getAmount();
  183. if ($retainedEarningsAmount >= 0) {
  184. $categorySummaryBalances['credit_balance'] += $retainedEarningsAmount;
  185. $categoryAccounts[] = new AccountDTO(
  186. 'Retained Earnings',
  187. 'RE',
  188. null,
  189. $this->formatBalances(['debit_balance' => 0, 'credit_balance' => $retainedEarningsAmount])
  190. );
  191. } else {
  192. $categorySummaryBalances['debit_balance'] += abs($retainedEarningsAmount);
  193. $categoryAccounts[] = new AccountDTO(
  194. 'Retained Earnings',
  195. 'RE',
  196. null,
  197. $this->formatBalances(['debit_balance' => abs($retainedEarningsAmount), 'credit_balance' => 0])
  198. );
  199. }
  200. }
  201. foreach ($balanceFields as $field) {
  202. if (array_key_exists($field, $categorySummaryBalances)) {
  203. $reportTotalBalances[$field] += $categorySummaryBalances[$field];
  204. }
  205. }
  206. $filteredCategorySummaryBalances = $this->filterBalances($categorySummaryBalances, $balanceFields);
  207. $formattedCategorySummaryBalances = $this->formatBalances($filteredCategorySummaryBalances);
  208. $accountCategories[$categoryName] = new AccountCategoryDTO(
  209. $categoryAccounts,
  210. $formattedCategorySummaryBalances,
  211. );
  212. }
  213. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  214. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $allFields);
  215. }
  216. private function adjustAccountBalanceCategoryFields(string $categoryName, array &$categorySummaryBalances): void
  217. {
  218. if (in_array($categoryName, [AccountCategory::Expense->getPluralLabel(), AccountCategory::Revenue->getPluralLabel()], true)) {
  219. unset($categorySummaryBalances['starting_balance'], $categorySummaryBalances['ending_balance']);
  220. }
  221. }
  222. public function buildTrialBalanceReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  223. {
  224. $allCategories = $this->accountService->getAccountCategoryOrder();
  225. $categoryGroupedAccounts = $this->getCategoryGroupedAccounts($allCategories);
  226. $balanceFields = ['debit_balance', 'credit_balance'];
  227. return $this->buildReport($allCategories, $categoryGroupedAccounts, function (Account $account) use ($startDate, $endDate) {
  228. $endingBalance = $this->accountService->getEndingBalance($account, $startDate, $endDate)?->getAmount() ?? 0;
  229. if ($endingBalance === 0) {
  230. return [];
  231. }
  232. return $this->calculateTrialBalance($account->category, $endingBalance);
  233. }, $balanceFields, $columns, null, true, $startDate);
  234. }
  235. private function calculateTrialBalance(AccountCategory $category, int $endingBalance): array
  236. {
  237. if (in_array($category, [AccountCategory::Asset, AccountCategory::Expense], true)) {
  238. if ($endingBalance >= 0) {
  239. return ['debit_balance' => $endingBalance, 'credit_balance' => 0];
  240. }
  241. return ['debit_balance' => 0, 'credit_balance' => abs($endingBalance)];
  242. }
  243. if ($endingBalance >= 0) {
  244. return ['debit_balance' => 0, 'credit_balance' => $endingBalance];
  245. }
  246. return ['debit_balance' => abs($endingBalance), 'credit_balance' => 0];
  247. }
  248. }