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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065
  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. * @param class-string<BalanceFormattable>|null $dtoClass
  38. */
  39. public function formatBalances(array $balances, ?string $dtoClass = null, bool $formatZeros = true): BalanceFormattable | array
  40. {
  41. $dtoClass ??= AccountBalanceDTO::class;
  42. $formattedBalances = array_map(static function ($balance) use ($formatZeros) {
  43. if (! $formatZeros && $balance === 0) {
  44. return '';
  45. }
  46. return CurrencyConverter::formatCentsToMoney($balance);
  47. }, $balances);
  48. if (! $dtoClass) {
  49. return $formattedBalances;
  50. }
  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->getRawOriginal('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): BalanceFormattable | array
  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): BalanceFormattable | array
  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. ->with(['client:id,name'])
  791. ->get()
  792. ->groupBy('client_id'),
  793. DocumentEntityType::Vendor => Bill::query()
  794. ->whereBetween('date', [$startDate, $endDate])
  795. ->whereNotIn('status', [BillStatus::Void])
  796. ->whereNotNull('paid_at')
  797. ->with(['vendor:id,name'])
  798. ->get()
  799. ->groupBy('vendor_id'),
  800. };
  801. $categories = [];
  802. $totalDocs = 0;
  803. $totalOnTime = 0;
  804. $totalLate = 0;
  805. $allPaymentDays = [];
  806. $allLateDays = [];
  807. /** @var DocumentCollection<int,Invoice|Bill> $entityDocuments */
  808. foreach ($documents as $entityId => $entityDocuments) {
  809. $entity = $entityDocuments->first()->{$entityType->value};
  810. $onTimeDocs = $entityDocuments->filter(fn (Invoice | Bill $doc) => $doc->paid_at->lte($doc->due_date));
  811. $onTimeCount = $onTimeDocs->count();
  812. $lateDocs = $entityDocuments->filter(fn (Invoice | Bill $doc) => $doc->paid_at->gt($doc->due_date));
  813. $lateCount = $lateDocs->count();
  814. $avgDaysToPay = $entityDocuments->avg(
  815. fn (Invoice | Bill $doc) => $doc instanceof Invoice
  816. ? $doc->approved_at->diffInDays($doc->paid_at)
  817. : $doc->date->diffInDays($doc->paid_at)
  818. ) ?? 0;
  819. $avgDaysLate = $lateDocs->avg(fn (Invoice | Bill $doc) => $doc->due_date->diffInDays($doc->paid_at)) ?? 0;
  820. $onTimeRate = $entityDocuments->isNotEmpty()
  821. ? ($onTimeCount / $entityDocuments->count() * 100)
  822. : 0;
  823. $totalDocs += $entityDocuments->count();
  824. $totalOnTime += $onTimeCount;
  825. $totalLate += $lateCount;
  826. $entityDocuments->each(function (Invoice | Bill $doc) use (&$allPaymentDays, &$allLateDays) {
  827. $allPaymentDays[] = $doc instanceof Invoice
  828. ? $doc->approved_at->diffInDays($doc->paid_at)
  829. : $doc->date->diffInDays($doc->paid_at);
  830. if ($doc->paid_at->gt($doc->due_date)) {
  831. $allLateDays[] = $doc->due_date->diffInDays($doc->paid_at);
  832. }
  833. });
  834. $categories[] = new EntityReportDTO(
  835. name: $entity->name,
  836. id: $entityId,
  837. paymentMetrics: new PaymentMetricsDTO(
  838. totalDocuments: $entityDocuments->count(),
  839. onTimeCount: $onTimeCount ?: null,
  840. lateCount: $lateCount ?: null,
  841. avgDaysToPay: $avgDaysToPay ? round($avgDaysToPay) : null,
  842. avgDaysLate: $avgDaysLate ? round($avgDaysLate) : null,
  843. onTimePaymentRate: Number::percentage($onTimeRate, maxPrecision: 2),
  844. ),
  845. );
  846. }
  847. $categories = collect($categories)
  848. ->sortByDesc(static fn (EntityReportDTO $category) => $category->paymentMetrics->onTimePaymentRate, SORT_NATURAL)
  849. ->values()
  850. ->all();
  851. $overallMetrics = new PaymentMetricsDTO(
  852. totalDocuments: $totalDocs,
  853. onTimeCount: $totalOnTime,
  854. lateCount: $totalLate,
  855. avgDaysToPay: round(collect($allPaymentDays)->avg() ?? 0),
  856. avgDaysLate: round(collect($allLateDays)->avg() ?? 0),
  857. onTimePaymentRate: Number::percentage(
  858. $totalDocs > 0 ? ($totalOnTime / $totalDocs * 100) : 0,
  859. maxPrecision: 2
  860. ),
  861. );
  862. return new ReportDTO(
  863. categories: ['Entities' => $categories],
  864. overallPaymentMetrics: $overallMetrics,
  865. fields: $columns,
  866. startDate: Carbon::parse($startDate),
  867. endDate: Carbon::parse($endDate),
  868. );
  869. }
  870. }