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

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