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

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