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 35KB

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