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.

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