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

ReportService.php 32KB

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