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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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\AccountTypeDTO;
  8. use App\DTO\ReportDTO;
  9. use App\Enums\Accounting\AccountCategory;
  10. use App\Enums\Accounting\AccountType;
  11. use App\Models\Accounting\Account;
  12. use App\Support\Column;
  13. use App\Utilities\Currency\CurrencyAccessor;
  14. use App\ValueObjects\Money;
  15. use Illuminate\Database\Eloquent\Builder;
  16. use Illuminate\Support\Carbon;
  17. class ReportService
  18. {
  19. public function __construct(
  20. protected AccountService $accountService,
  21. ) {}
  22. public function formatBalances(array $balances): AccountBalanceDTO
  23. {
  24. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  25. foreach ($balances as $key => $balance) {
  26. $balances[$key] = money($balance, $defaultCurrency)->format();
  27. }
  28. return new AccountBalanceDTO(
  29. startingBalance: $balances['starting_balance'] ?? null,
  30. debitBalance: $balances['debit_balance'] ?? null,
  31. creditBalance: $balances['credit_balance'] ?? null,
  32. netMovement: $balances['net_movement'] ?? null,
  33. endingBalance: $balances['ending_balance'] ?? null,
  34. );
  35. }
  36. public function buildAccountBalanceReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  37. {
  38. $orderedCategories = AccountCategory::getOrderedCategories();
  39. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)->get();
  40. $columnNameKeys = array_map(fn (Column $column) => $column->getName(), $columns);
  41. $accountCategories = [];
  42. $reportTotalBalances = [];
  43. foreach ($orderedCategories as $category) {
  44. $accountsInCategory = $accounts->where('category', $category)
  45. ->sortBy('code', SORT_NATURAL);
  46. $relevantFields = array_intersect($category->getRelevantBalanceFields(), $columnNameKeys);
  47. $categorySummaryBalances = array_fill_keys($relevantFields, 0);
  48. $categoryAccounts = [];
  49. /** @var Account $account */
  50. foreach ($accountsInCategory as $account) {
  51. $accountBalances = $this->calculateAccountBalances($account);
  52. foreach ($relevantFields as $field) {
  53. $categorySummaryBalances[$field] += $accountBalances[$field];
  54. }
  55. $formattedAccountBalances = $this->formatBalances($accountBalances);
  56. $categoryAccounts[] = new AccountDTO(
  57. $account->name,
  58. $account->code,
  59. $account->id,
  60. $formattedAccountBalances,
  61. Carbon::parse($startDate)->toDateString(),
  62. Carbon::parse($endDate)->toDateString(),
  63. );
  64. }
  65. foreach ($relevantFields as $field) {
  66. $reportTotalBalances[$field] = ($reportTotalBalances[$field] ?? 0) + $categorySummaryBalances[$field];
  67. }
  68. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  69. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  70. accounts: $categoryAccounts,
  71. summary: $formattedCategorySummaryBalances,
  72. );
  73. }
  74. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  75. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  76. }
  77. public function calculateAccountBalances(Account $account): array
  78. {
  79. $category = $account->category;
  80. $balances = [
  81. 'debit_balance' => $account->total_debit ?? 0,
  82. 'credit_balance' => $account->total_credit ?? 0,
  83. ];
  84. if ($category->isNormalDebitBalance()) {
  85. $balances['net_movement'] = $balances['debit_balance'] - $balances['credit_balance'];
  86. } else {
  87. $balances['net_movement'] = $balances['credit_balance'] - $balances['debit_balance'];
  88. }
  89. if ($category->isReal()) {
  90. $balances['starting_balance'] = $account->starting_balance ?? 0;
  91. $balances['ending_balance'] = $balances['starting_balance'] + $balances['net_movement'];
  92. }
  93. return $balances;
  94. }
  95. public function calculateRetainedEarnings(?string $startDate, string $endDate): Money
  96. {
  97. $startDate ??= Carbon::parse($this->accountService->getEarliestTransactionDate())->toDateTimeString();
  98. $revenueAccounts = $this->accountService->getAccountBalances($startDate, $endDate)->where('category', AccountCategory::Revenue)->get();
  99. $expenseAccounts = $this->accountService->getAccountBalances($startDate, $endDate)->where('category', AccountCategory::Expense)->get();
  100. $revenueTotal = 0;
  101. $expenseTotal = 0;
  102. foreach ($revenueAccounts as $account) {
  103. $revenueBalances = $this->calculateAccountBalances($account);
  104. $revenueTotal += $revenueBalances['net_movement'];
  105. }
  106. foreach ($expenseAccounts as $account) {
  107. $expenseBalances = $this->calculateAccountBalances($account);
  108. $expenseTotal += $expenseBalances['net_movement'];
  109. }
  110. $retainedEarnings = $revenueTotal - $expenseTotal;
  111. return new Money($retainedEarnings, CurrencyAccessor::getDefaultCurrency());
  112. }
  113. public function buildAccountTransactionsReport(string $startDate, string $endDate, ?array $columns = null, ?string $accountId = 'all'): ReportDTO
  114. {
  115. $columns ??= [];
  116. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  117. $accountIds = $accountId !== 'all' ? [$accountId] : [];
  118. $query = $this->accountService->getAccountBalances($startDate, $endDate, $accountIds);
  119. $accounts = $query->with(['journalEntries' => $this->accountService->getTransactionDetailsSubquery($startDate, $endDate)])->get();
  120. $reportCategories = [];
  121. foreach ($accounts as $account) {
  122. $accountTransactions = [];
  123. $currentBalance = $account->starting_balance;
  124. $accountTransactions[] = new AccountTransactionDTO(
  125. id: null,
  126. date: 'Starting Balance',
  127. description: '',
  128. debit: '',
  129. credit: '',
  130. balance: money($currentBalance, $defaultCurrency)->format(),
  131. type: null,
  132. tableAction: null
  133. );
  134. /** @var Account $account */
  135. foreach ($account->journalEntries as $journalEntry) {
  136. $transaction = $journalEntry->transaction;
  137. $signedAmount = $journalEntry->signed_amount;
  138. if ($account->category->isNormalDebitBalance()) {
  139. $currentBalance += $signedAmount;
  140. } else {
  141. $currentBalance -= $signedAmount;
  142. }
  143. $formattedAmount = money(abs($signedAmount), $defaultCurrency)->format();
  144. $accountTransactions[] = new AccountTransactionDTO(
  145. id: $transaction->id,
  146. date: $transaction->posted_at->toDefaultDateFormat(),
  147. description: $transaction->description ?? 'Add a description',
  148. debit: $journalEntry->type->isDebit() ? $formattedAmount : '',
  149. credit: $journalEntry->type->isCredit() ? $formattedAmount : '',
  150. balance: money($currentBalance, $defaultCurrency)->format(),
  151. type: $transaction->type,
  152. tableAction: $transaction->type->isJournal() ? 'updateJournalTransaction' : 'updateTransaction'
  153. );
  154. }
  155. $balanceChange = $currentBalance - $account->starting_balance;
  156. $accountTransactions[] = new AccountTransactionDTO(
  157. id: null,
  158. date: 'Totals and Ending Balance',
  159. description: '',
  160. debit: money($account->total_debit, $defaultCurrency)->format(),
  161. credit: money($account->total_credit, $defaultCurrency)->format(),
  162. balance: money($currentBalance, $defaultCurrency)->format(),
  163. type: null,
  164. tableAction: null
  165. );
  166. $accountTransactions[] = new AccountTransactionDTO(
  167. id: null,
  168. date: 'Balance Change',
  169. description: '',
  170. debit: '',
  171. credit: '',
  172. balance: money($balanceChange, $defaultCurrency)->format(),
  173. type: null,
  174. tableAction: null
  175. );
  176. $reportCategories[] = [
  177. 'category' => $account->name,
  178. 'under' => $account->category->getLabel() . ' > ' . $account->subtype->name,
  179. 'transactions' => $accountTransactions,
  180. ];
  181. }
  182. return new ReportDTO(categories: $reportCategories, fields: $columns);
  183. }
  184. public function buildTrialBalanceReport(string $trialBalanceType, string $asOfDate, array $columns = []): ReportDTO
  185. {
  186. $asOfDateCarbon = Carbon::parse($asOfDate);
  187. $startDateCarbon = Carbon::parse($this->accountService->getEarliestTransactionDate());
  188. $orderedCategories = AccountCategory::getOrderedCategories();
  189. $isPostClosingTrialBalance = $trialBalanceType === 'postClosing';
  190. $accounts = $this->accountService->getAccountBalances($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())
  191. ->when($isPostClosingTrialBalance, fn (Builder $query) => $query->whereNotIn('category', [AccountCategory::Revenue, AccountCategory::Expense]))
  192. ->get();
  193. $balanceFields = ['debit_balance', 'credit_balance'];
  194. $accountCategories = [];
  195. $reportTotalBalances = array_fill_keys($balanceFields, 0);
  196. foreach ($orderedCategories as $category) {
  197. $accountsInCategory = $accounts->where('category', $category)
  198. ->sortBy('code', SORT_NATURAL);
  199. $categorySummaryBalances = array_fill_keys($balanceFields, 0);
  200. $categoryAccounts = [];
  201. /** @var Account $account */
  202. foreach ($accountsInCategory as $account) {
  203. $accountBalances = $this->calculateAccountBalances($account);
  204. $endingBalance = $accountBalances['ending_balance'] ?? $accountBalances['net_movement'];
  205. $trialBalance = $this->calculateTrialBalances($account->category, $endingBalance);
  206. foreach ($trialBalance as $balanceType => $balance) {
  207. $categorySummaryBalances[$balanceType] += $balance;
  208. }
  209. $formattedAccountBalances = $this->formatBalances($trialBalance);
  210. $categoryAccounts[] = new AccountDTO(
  211. $account->name,
  212. $account->code,
  213. $account->id,
  214. $formattedAccountBalances,
  215. startDate: $startDateCarbon->toDateString(),
  216. endDate: $asOfDateCarbon->toDateString(),
  217. );
  218. }
  219. if ($category === AccountCategory::Equity && $isPostClosingTrialBalance) {
  220. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())->getAmount();
  221. $isCredit = $retainedEarningsAmount >= 0;
  222. $categorySummaryBalances[$isCredit ? 'credit_balance' : 'debit_balance'] += abs($retainedEarningsAmount);
  223. $categoryAccounts[] = new AccountDTO(
  224. 'Retained Earnings',
  225. 'RE',
  226. null,
  227. $this->formatBalances([
  228. 'debit_balance' => $isCredit ? 0 : abs($retainedEarningsAmount),
  229. 'credit_balance' => $isCredit ? $retainedEarningsAmount : 0,
  230. ]),
  231. startDate: $startDateCarbon->toDateString(),
  232. endDate: $asOfDateCarbon->toDateString(),
  233. );
  234. }
  235. foreach ($categorySummaryBalances as $balanceType => $balance) {
  236. $reportTotalBalances[$balanceType] += $balance;
  237. }
  238. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  239. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  240. accounts: $categoryAccounts,
  241. summary: $formattedCategorySummaryBalances,
  242. );
  243. }
  244. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  245. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns, $trialBalanceType);
  246. }
  247. public function getRetainedEarningsBalances(string $startDate, string $endDate): AccountBalanceDTO
  248. {
  249. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDate, $endDate)->getAmount();
  250. $isCredit = $retainedEarningsAmount >= 0;
  251. $retainedEarningsDebitAmount = $isCredit ? 0 : abs($retainedEarningsAmount);
  252. $retainedEarningsCreditAmount = $isCredit ? $retainedEarningsAmount : 0;
  253. return $this->formatBalances([
  254. 'debit_balance' => $retainedEarningsDebitAmount,
  255. 'credit_balance' => $retainedEarningsCreditAmount,
  256. ]);
  257. }
  258. public function calculateTrialBalances(AccountCategory $category, int $endingBalance): array
  259. {
  260. if ($category->isNormalDebitBalance()) {
  261. if ($endingBalance >= 0) {
  262. return ['debit_balance' => $endingBalance, 'credit_balance' => 0];
  263. }
  264. return ['debit_balance' => 0, 'credit_balance' => abs($endingBalance)];
  265. }
  266. if ($endingBalance >= 0) {
  267. return ['debit_balance' => 0, 'credit_balance' => $endingBalance];
  268. }
  269. return ['debit_balance' => abs($endingBalance), 'credit_balance' => 0];
  270. }
  271. public function buildIncomeStatementReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  272. {
  273. // Query only relevant accounts and sort them at the query level
  274. $revenueAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  275. ->where('category', AccountCategory::Revenue)
  276. ->orderByRaw('LENGTH(code), code')
  277. ->get();
  278. $cogsAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  279. ->whereRelation('subtype', 'name', 'Cost of Goods Sold')
  280. ->orderByRaw('LENGTH(code), code')
  281. ->get();
  282. $expenseAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  283. ->where('category', AccountCategory::Expense)
  284. ->whereRelation('subtype', 'name', '!=', 'Cost of Goods Sold')
  285. ->orderByRaw('LENGTH(code), code')
  286. ->get();
  287. $accountCategories = [];
  288. $totalRevenue = 0;
  289. $totalCogs = 0;
  290. $totalExpenses = 0;
  291. // Define category groups
  292. $categoryGroups = [
  293. AccountCategory::Revenue->getPluralLabel() => [
  294. 'accounts' => $revenueAccounts,
  295. 'total' => &$totalRevenue,
  296. ],
  297. 'Cost of Goods Sold' => [
  298. 'accounts' => $cogsAccounts,
  299. 'total' => &$totalCogs,
  300. ],
  301. AccountCategory::Expense->getPluralLabel() => [
  302. 'accounts' => $expenseAccounts,
  303. 'total' => &$totalExpenses,
  304. ],
  305. ];
  306. // Process each category group
  307. foreach ($categoryGroups as $label => $group) {
  308. $categoryAccounts = [];
  309. $netMovement = 0;
  310. foreach ($group['accounts'] as $account) {
  311. // Use the category type based on label
  312. $category = match ($label) {
  313. AccountCategory::Revenue->getPluralLabel() => AccountCategory::Revenue,
  314. AccountCategory::Expense->getPluralLabel(), 'Cost of Goods Sold' => AccountCategory::Expense,
  315. default => null
  316. };
  317. if ($category !== null) {
  318. $accountBalances = $this->calculateAccountBalances($account);
  319. $movement = $accountBalances['net_movement'];
  320. $netMovement += $movement;
  321. $group['total'] += $movement;
  322. $categoryAccounts[] = new AccountDTO(
  323. $account->name,
  324. $account->code,
  325. $account->id,
  326. $this->formatBalances(['net_movement' => $movement]),
  327. Carbon::parse($startDate)->toDateString(),
  328. Carbon::parse($endDate)->toDateString(),
  329. );
  330. }
  331. }
  332. $accountCategories[$label] = new AccountCategoryDTO(
  333. accounts: $categoryAccounts,
  334. summary: $this->formatBalances(['net_movement' => $netMovement])
  335. );
  336. }
  337. // Calculate gross and net profit
  338. $grossProfit = $totalRevenue - $totalCogs;
  339. $netProfit = $grossProfit - $totalExpenses;
  340. $formattedReportTotalBalances = $this->formatBalances(['net_movement' => $netProfit]);
  341. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  342. }
  343. public function buildCashFlowStatementReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  344. {
  345. $sections = [
  346. 'Operating Activities' => $this->buildOperatingActivities($startDate, $endDate),
  347. 'Investing Activities' => $this->buildInvestingActivities($startDate, $endDate),
  348. 'Financing Activities' => $this->buildFinancingActivities($startDate, $endDate),
  349. ];
  350. $totalCashFlows = $this->calculateTotalCashFlows($sections);
  351. return new ReportDTO($sections, $totalCashFlows, $columns);
  352. }
  353. private function buildOperatingActivities(string $startDate, string $endDate): AccountCategoryDTO
  354. {
  355. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)
  356. ->whereIn('accounts.type', [
  357. AccountType::OperatingRevenue,
  358. AccountType::UncategorizedRevenue,
  359. AccountType::OperatingExpense,
  360. AccountType::NonOperatingExpense,
  361. AccountType::UncategorizedExpense,
  362. AccountType::CurrentAsset,
  363. ])
  364. ->whereRelation('subtype', 'name', '!=', 'Cash and Cash Equivalents')
  365. ->orderByRaw('LENGTH(code), code')
  366. ->get();
  367. $adjustments = $this->accountService->getAccountBalances($startDate, $endDate)
  368. ->whereIn('accounts.type', [
  369. AccountType::ContraAsset,
  370. AccountType::CurrentLiability,
  371. ])
  372. ->whereRelation('subtype', 'name', '!=', 'Short-Term Borrowings')
  373. ->orderByRaw('LENGTH(code), code')
  374. ->get();
  375. return $this->formatSectionAccounts($accounts, $adjustments, $startDate, $endDate);
  376. }
  377. private function buildInvestingActivities(string $startDate, string $endDate): AccountCategoryDTO
  378. {
  379. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)
  380. ->whereIn('accounts.type', [AccountType::NonCurrentAsset])
  381. ->orderByRaw('LENGTH(code), code')
  382. ->get();
  383. $adjustments = $this->accountService->getAccountBalances($startDate, $endDate)
  384. ->whereIn('accounts.type', [AccountType::NonOperatingRevenue])
  385. ->orderByRaw('LENGTH(code), code')
  386. ->get();
  387. return $this->formatSectionAccounts($accounts, $adjustments, $startDate, $endDate);
  388. }
  389. private function buildFinancingActivities(string $startDate, string $endDate): AccountCategoryDTO
  390. {
  391. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)
  392. ->where(function (Builder $query) {
  393. $query->whereIn('accounts.type', [
  394. AccountType::Equity,
  395. AccountType::NonCurrentLiability,
  396. ])
  397. ->orWhere(function (Builder $subQuery) {
  398. $subQuery->where('accounts.type', AccountType::CurrentLiability)
  399. ->whereRelation('subtype', 'name', 'Short-Term Borrowings');
  400. });
  401. })
  402. ->orderByRaw('LENGTH(code), code')
  403. ->get();
  404. return $this->formatSectionAccounts($accounts, [], $startDate, $endDate);
  405. }
  406. private function formatSectionAccounts($accounts, $adjustments, string $startDate, string $endDate): AccountCategoryDTO
  407. {
  408. $categoryAccountsByType = [];
  409. $sectionTotal = 0;
  410. $subCategoryTotals = [];
  411. // Process accounts and adjustments
  412. /** @var Account[] $entries */
  413. foreach ([$accounts, $adjustments] as $entries) {
  414. foreach ($entries as $entry) {
  415. $accountCategory = $entry->type->getCategory();
  416. $accountBalances = $this->calculateAccountBalances($entry);
  417. $netCashFlow = $accountBalances['net_movement'] ?? 0;
  418. if ($entry->subtype->inverse_cash_flow) {
  419. $netCashFlow *= -1;
  420. }
  421. // Accumulate totals
  422. $sectionTotal += $netCashFlow;
  423. $accountTypeName = $entry->subtype->name;
  424. $subCategoryTotals[$accountTypeName] = ($subCategoryTotals[$accountTypeName] ?? 0) + $netCashFlow;
  425. // Create AccountDTO and group by account type
  426. $accountDTO = new AccountDTO(
  427. $entry->name,
  428. $entry->code,
  429. $entry->id,
  430. $this->formatBalances(['net_movement' => $netCashFlow]),
  431. $startDate,
  432. $endDate
  433. );
  434. $categoryAccountsByType[$accountTypeName][] = $accountDTO;
  435. }
  436. }
  437. // Prepare AccountTypeDTO for each account type with the accumulated totals
  438. $subCategories = [];
  439. foreach ($categoryAccountsByType as $typeName => $accountsInType) {
  440. $typeTotal = $subCategoryTotals[$typeName] ?? 0;
  441. $formattedTypeTotal = $this->formatBalances(['net_movement' => $typeTotal]);
  442. $subCategories[$typeName] = new AccountTypeDTO(
  443. accounts: $accountsInType,
  444. summary: $formattedTypeTotal
  445. );
  446. }
  447. // Format the overall section total as the section summary
  448. $formattedSectionTotal = $this->formatBalances(['net_movement' => $sectionTotal]);
  449. return new AccountCategoryDTO(
  450. accounts: [], // No direct accounts at the section level
  451. types: $subCategories, // Grouped by AccountTypeDTO
  452. summary: $formattedSectionTotal,
  453. );
  454. }
  455. private function calculateTotalCashFlows(array $sections): AccountBalanceDTO
  456. {
  457. $totalCashFlow = 0;
  458. foreach ($sections as $section) {
  459. $netMovement = $section->summary->netMovement ?? 0;
  460. $numericNetMovement = money($netMovement, CurrencyAccessor::getDefaultCurrency(), true)->getAmount();
  461. $totalCashFlow += $numericNetMovement;
  462. }
  463. return $this->formatBalances(['net_movement' => $totalCashFlow]);
  464. }
  465. public function buildBalanceSheetReport(string $asOfDate, array $columns = []): ReportDTO
  466. {
  467. $asOfDateCarbon = Carbon::parse($asOfDate);
  468. $startDateCarbon = Carbon::parse($this->accountService->getEarliestTransactionDate());
  469. $orderedCategories = array_filter(AccountCategory::getOrderedCategories(), fn (AccountCategory $category) => $category->isReal());
  470. $accounts = $this->accountService->getAccountBalances($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())
  471. ->whereIn('category', $orderedCategories)
  472. ->orderByRaw('LENGTH(code), code')
  473. ->get();
  474. $accountCategories = [];
  475. $reportTotalBalances = [
  476. 'assets' => 0,
  477. 'liabilities' => 0,
  478. 'equity' => 0,
  479. ];
  480. foreach ($orderedCategories as $category) {
  481. $categorySummaryBalances = ['ending_balance' => 0];
  482. $categoryAccountsByType = [];
  483. $categoryAccounts = [];
  484. $subCategoryTotals = [];
  485. /** @var Account $account */
  486. foreach ($accounts as $account) {
  487. if ($account->type->getCategory() === $category) {
  488. $accountBalances = $this->calculateAccountBalances($account);
  489. $endingBalance = $accountBalances['ending_balance'] ?? $accountBalances['net_movement'];
  490. $categorySummaryBalances['ending_balance'] += $endingBalance;
  491. $formattedAccountBalances = $this->formatBalances($accountBalances);
  492. $accountDTO = new AccountDTO(
  493. $account->name,
  494. $account->code,
  495. $account->id,
  496. $formattedAccountBalances,
  497. startDate: $startDateCarbon->toDateString(),
  498. endDate: $asOfDateCarbon->toDateString(),
  499. );
  500. if ($category === AccountCategory::Equity && $account->type === AccountType::Equity) {
  501. $categoryAccounts[] = $accountDTO;
  502. } else {
  503. $accountType = $account->type->getPluralLabel();
  504. $categoryAccountsByType[$accountType][] = $accountDTO;
  505. $subCategoryTotals[$accountType] = ($subCategoryTotals[$accountType] ?? 0) + $endingBalance;
  506. }
  507. }
  508. }
  509. if ($category === AccountCategory::Equity) {
  510. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())->getAmount();
  511. $categorySummaryBalances['ending_balance'] += $retainedEarningsAmount;
  512. $retainedEarningsDTO = new AccountDTO(
  513. 'Retained Earnings',
  514. 'RE',
  515. null,
  516. $this->formatBalances(['ending_balance' => $retainedEarningsAmount]),
  517. startDate: $startDateCarbon->toDateString(),
  518. endDate: $asOfDateCarbon->toDateString(),
  519. );
  520. $categoryAccounts[] = $retainedEarningsDTO;
  521. }
  522. $subCategories = [];
  523. foreach ($categoryAccountsByType as $accountType => $accountsInType) {
  524. $subCategorySummary = $this->formatBalances([
  525. 'ending_balance' => $subCategoryTotals[$accountType] ?? 0,
  526. ]);
  527. $subCategories[$accountType] = new AccountTypeDTO(
  528. accounts: $accountsInType,
  529. summary: $subCategorySummary
  530. );
  531. }
  532. $reportTotalBalances[match ($category) {
  533. AccountCategory::Asset => 'assets',
  534. AccountCategory::Liability => 'liabilities',
  535. AccountCategory::Equity => 'equity',
  536. }] += $categorySummaryBalances['ending_balance'];
  537. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  538. accounts: $categoryAccounts,
  539. types: $subCategories,
  540. summary: $this->formatBalances($categorySummaryBalances),
  541. );
  542. }
  543. $netAssets = $reportTotalBalances['assets'] - $reportTotalBalances['liabilities'];
  544. $formattedReportTotalBalances = $this->formatBalances(['ending_balance' => $netAssets]);
  545. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  546. }
  547. }