Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

ReportService.php 43KB

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