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

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