Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

ReportService.php 28KB

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