您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

ReportService.php 31KB

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