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

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