Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ReportService.php 31KB

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