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

ReportService.php 38KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. <?php
  2. namespace App\Services;
  3. use App\Collections\Accounting\DocumentCollection;
  4. use App\Contracts\MoneyFormattableDTO;
  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\ClientBalanceDTO;
  13. use App\DTO\ClientReportDTO;
  14. use App\DTO\EntityReportDTO;
  15. use App\DTO\ReportDTO;
  16. use App\Enums\Accounting\AccountCategory;
  17. use App\Enums\Accounting\AccountType;
  18. use App\Enums\Accounting\DocumentEntityType;
  19. use App\Enums\Accounting\InvoiceStatus;
  20. use App\Enums\Accounting\TransactionType;
  21. use App\Models\Accounting\Account;
  22. use App\Models\Accounting\Bill;
  23. use App\Models\Accounting\Invoice;
  24. use App\Models\Accounting\Transaction;
  25. use App\Support\Column;
  26. use App\Utilities\Currency\CurrencyAccessor;
  27. use App\Utilities\Currency\CurrencyConverter;
  28. use App\ValueObjects\Money;
  29. use Illuminate\Database\Eloquent\Builder;
  30. use Illuminate\Support\Carbon;
  31. class ReportService
  32. {
  33. public function __construct(
  34. protected AccountService $accountService,
  35. ) {}
  36. /**
  37. * @param class-string<MoneyFormattableDTO>|null $dtoClass
  38. */
  39. public function formatBalances(array $balances, ?string $dtoClass = null, bool $formatZeros = true): MoneyFormattableDTO | 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. tableAction: null
  163. );
  164. foreach ($account->journalEntries as $journalEntry) {
  165. $transaction = $journalEntry->transaction;
  166. $signedAmount = $journalEntry->signed_amount;
  167. $amount = $journalEntry->getRawOriginal('amount');
  168. if ($journalEntry->type->isDebit()) {
  169. $periodDebitTotal += $amount;
  170. } else {
  171. $periodCreditTotal += $amount;
  172. }
  173. if ($account->category->isNormalDebitBalance()) {
  174. $currentBalance += $signedAmount;
  175. } else {
  176. $currentBalance -= $signedAmount;
  177. }
  178. $formattedAmount = money(abs($signedAmount), $defaultCurrency)->format();
  179. $accountTransactions[] = new AccountTransactionDTO(
  180. id: $transaction->id,
  181. date: $transaction->posted_at->toDefaultDateFormat(),
  182. description: $journalEntry->description ?: $transaction->description ?? 'Add a description',
  183. debit: $journalEntry->type->isDebit() ? $formattedAmount : '',
  184. credit: $journalEntry->type->isCredit() ? $formattedAmount : '',
  185. balance: money($currentBalance, $defaultCurrency)->format(),
  186. type: $transaction->type,
  187. tableAction: $this->determineTableAction($transaction),
  188. );
  189. }
  190. $balanceChange = $currentBalance - $account->starting_balance;
  191. $accountTransactions[] = new AccountTransactionDTO(
  192. id: null,
  193. date: 'Totals and Ending Balance',
  194. description: '',
  195. debit: money($periodDebitTotal, $defaultCurrency)->format(),
  196. credit: money($periodCreditTotal, $defaultCurrency)->format(),
  197. balance: money($currentBalance, $defaultCurrency)->format(),
  198. type: null,
  199. tableAction: null
  200. );
  201. $accountTransactions[] = new AccountTransactionDTO(
  202. id: null,
  203. date: 'Balance Change',
  204. description: '',
  205. debit: '',
  206. credit: '',
  207. balance: money($balanceChange, $defaultCurrency)->format(),
  208. type: null,
  209. tableAction: null
  210. );
  211. $reportCategories[] = [
  212. 'category' => $account->name,
  213. 'under' => $account->category->getLabel() . ' > ' . $account->subtype->name,
  214. 'transactions' => $accountTransactions,
  215. ];
  216. }
  217. return new ReportDTO(categories: $reportCategories, fields: $columns);
  218. }
  219. private function determineTableAction(Transaction $transaction): array
  220. {
  221. if ($transaction->transactionable_type === null || $transaction->is_payment) {
  222. return [
  223. 'type' => 'transaction',
  224. 'action' => match ($transaction->type) {
  225. TransactionType::Journal => 'editJournalTransaction',
  226. TransactionType::Transfer => 'editTransfer',
  227. default => 'editTransaction',
  228. },
  229. 'id' => $transaction->id,
  230. ];
  231. }
  232. return [
  233. 'type' => 'transactionable',
  234. 'model' => $transaction->transactionable_type,
  235. 'id' => $transaction->transactionable_id,
  236. ];
  237. }
  238. public function buildTrialBalanceReport(string $trialBalanceType, string $asOfDate, array $columns = []): ReportDTO
  239. {
  240. $asOfDateCarbon = Carbon::parse($asOfDate);
  241. $startDateCarbon = Carbon::parse($this->accountService->getEarliestTransactionDate());
  242. $orderedCategories = AccountCategory::getOrderedCategories();
  243. $isPostClosingTrialBalance = $trialBalanceType === 'postClosing';
  244. $accounts = $this->accountService->getAccountBalances($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())
  245. ->when($isPostClosingTrialBalance, fn (Builder $query) => $query->whereNotIn('category', [AccountCategory::Revenue, AccountCategory::Expense]))
  246. ->orderByRaw('LENGTH(code), code')
  247. ->get();
  248. $balanceFields = ['debit_balance', 'credit_balance'];
  249. $accountCategories = [];
  250. $reportTotalBalances = array_fill_keys($balanceFields, 0);
  251. foreach ($orderedCategories as $category) {
  252. $accountsInCategory = $accounts->where('category', $category);
  253. $categorySummaryBalances = array_fill_keys($balanceFields, 0);
  254. $categoryAccounts = [];
  255. /** @var Account $account */
  256. foreach ($accountsInCategory as $account) {
  257. $accountBalances = $this->calculateAccountBalances($account);
  258. $endingBalance = $accountBalances['ending_balance'] ?? $accountBalances['net_movement'];
  259. $trialBalance = $this->calculateTrialBalances($account->category, $endingBalance);
  260. foreach ($trialBalance as $balanceType => $balance) {
  261. $categorySummaryBalances[$balanceType] += $balance;
  262. }
  263. $formattedAccountBalances = $this->formatBalances($trialBalance);
  264. $categoryAccounts[] = new AccountDTO(
  265. $account->name,
  266. $account->code,
  267. $account->id,
  268. $formattedAccountBalances,
  269. startDate: $startDateCarbon->toDateString(),
  270. endDate: $asOfDateCarbon->toDateString(),
  271. );
  272. }
  273. if ($category === AccountCategory::Equity && $isPostClosingTrialBalance) {
  274. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())->getAmount();
  275. $isCredit = $retainedEarningsAmount >= 0;
  276. $categorySummaryBalances[$isCredit ? 'credit_balance' : 'debit_balance'] += abs($retainedEarningsAmount);
  277. $categoryAccounts[] = new AccountDTO(
  278. 'Retained Earnings',
  279. 'RE',
  280. null,
  281. $this->formatBalances([
  282. 'debit_balance' => $isCredit ? 0 : abs($retainedEarningsAmount),
  283. 'credit_balance' => $isCredit ? $retainedEarningsAmount : 0,
  284. ]),
  285. startDate: $startDateCarbon->toDateString(),
  286. endDate: $asOfDateCarbon->toDateString(),
  287. );
  288. }
  289. foreach ($categorySummaryBalances as $balanceType => $balance) {
  290. $reportTotalBalances[$balanceType] += $balance;
  291. }
  292. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  293. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  294. accounts: $categoryAccounts,
  295. summary: $formattedCategorySummaryBalances,
  296. );
  297. }
  298. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  299. return new ReportDTO(categories: $accountCategories, overallTotal: $formattedReportTotalBalances, fields: $columns, reportType: $trialBalanceType);
  300. }
  301. public function getRetainedEarningsBalances(string $startDate, string $endDate): MoneyFormattableDTO | array
  302. {
  303. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDate, $endDate)->getAmount();
  304. $isCredit = $retainedEarningsAmount >= 0;
  305. $retainedEarningsDebitAmount = $isCredit ? 0 : abs($retainedEarningsAmount);
  306. $retainedEarningsCreditAmount = $isCredit ? $retainedEarningsAmount : 0;
  307. return $this->formatBalances([
  308. 'debit_balance' => $retainedEarningsDebitAmount,
  309. 'credit_balance' => $retainedEarningsCreditAmount,
  310. ]);
  311. }
  312. public function calculateTrialBalances(AccountCategory $category, int $endingBalance): array
  313. {
  314. if ($category->isNormalDebitBalance()) {
  315. if ($endingBalance >= 0) {
  316. return ['debit_balance' => $endingBalance, 'credit_balance' => 0];
  317. }
  318. return ['debit_balance' => 0, 'credit_balance' => abs($endingBalance)];
  319. }
  320. if ($endingBalance >= 0) {
  321. return ['debit_balance' => 0, 'credit_balance' => $endingBalance];
  322. }
  323. return ['debit_balance' => abs($endingBalance), 'credit_balance' => 0];
  324. }
  325. public function buildIncomeStatementReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  326. {
  327. // Query only relevant accounts and sort them at the query level
  328. $revenueAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  329. ->where('category', AccountCategory::Revenue)
  330. ->orderByRaw('LENGTH(code), code')
  331. ->get();
  332. $cogsAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  333. ->whereRelation('subtype', 'name', 'Cost of Goods Sold')
  334. ->orderByRaw('LENGTH(code), code')
  335. ->get();
  336. $expenseAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  337. ->where('category', AccountCategory::Expense)
  338. ->whereRelation('subtype', 'name', '!=', 'Cost of Goods Sold')
  339. ->orderByRaw('LENGTH(code), code')
  340. ->get();
  341. $accountCategories = [];
  342. $totalRevenue = 0;
  343. $totalCogs = 0;
  344. $totalExpenses = 0;
  345. // Define category groups
  346. $categoryGroups = [
  347. AccountCategory::Revenue->getPluralLabel() => [
  348. 'accounts' => $revenueAccounts,
  349. 'total' => &$totalRevenue,
  350. ],
  351. 'Cost of Goods Sold' => [
  352. 'accounts' => $cogsAccounts,
  353. 'total' => &$totalCogs,
  354. ],
  355. AccountCategory::Expense->getPluralLabel() => [
  356. 'accounts' => $expenseAccounts,
  357. 'total' => &$totalExpenses,
  358. ],
  359. ];
  360. // Process each category group
  361. foreach ($categoryGroups as $label => $group) {
  362. $categoryAccounts = [];
  363. $netMovement = 0;
  364. foreach ($group['accounts'] as $account) {
  365. // Use the category type based on label
  366. $category = match ($label) {
  367. AccountCategory::Revenue->getPluralLabel() => AccountCategory::Revenue,
  368. AccountCategory::Expense->getPluralLabel(), 'Cost of Goods Sold' => AccountCategory::Expense,
  369. default => null
  370. };
  371. if ($category !== null) {
  372. $accountBalances = $this->calculateAccountBalances($account);
  373. $movement = $accountBalances['net_movement'];
  374. $netMovement += $movement;
  375. $group['total'] += $movement;
  376. $categoryAccounts[] = new AccountDTO(
  377. $account->name,
  378. $account->code,
  379. $account->id,
  380. $this->formatBalances(['net_movement' => $movement]),
  381. Carbon::parse($startDate)->toDateString(),
  382. Carbon::parse($endDate)->toDateString(),
  383. );
  384. }
  385. }
  386. $accountCategories[$label] = new AccountCategoryDTO(
  387. accounts: $categoryAccounts,
  388. summary: $this->formatBalances(['net_movement' => $netMovement])
  389. );
  390. }
  391. // Calculate gross and net profit
  392. $grossProfit = $totalRevenue - $totalCogs;
  393. $netProfit = $grossProfit - $totalExpenses;
  394. $formattedReportTotalBalances = $this->formatBalances(['net_movement' => $netProfit]);
  395. return new ReportDTO(
  396. categories: $accountCategories,
  397. overallTotal: $formattedReportTotalBalances,
  398. fields: $columns,
  399. startDate: Carbon::parse($startDate),
  400. endDate: Carbon::parse($endDate),
  401. );
  402. }
  403. public function buildCashFlowStatementReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  404. {
  405. $sections = [
  406. 'Operating Activities' => $this->buildOperatingActivities($startDate, $endDate),
  407. 'Investing Activities' => $this->buildInvestingActivities($startDate, $endDate),
  408. 'Financing Activities' => $this->buildFinancingActivities($startDate, $endDate),
  409. ];
  410. $totalCashFlows = $this->calculateTotalCashFlows($sections, $startDate);
  411. $overview = $this->buildCashFlowOverview($startDate, $endDate);
  412. return new ReportDTO(
  413. categories: $sections,
  414. overallTotal: $totalCashFlows,
  415. fields: $columns,
  416. overview: $overview,
  417. startDate: Carbon::parse($startDate),
  418. endDate: Carbon::parse($endDate),
  419. );
  420. }
  421. private function calculateTotalCashFlows(array $sections, string $startDate): MoneyFormattableDTO | array
  422. {
  423. $totalInflow = 0;
  424. $totalOutflow = 0;
  425. $startingBalance = $this->accountService->getStartingBalanceForAllBankAccounts($startDate)->getAmount();
  426. foreach ($sections as $section) {
  427. $netMovement = $section->summary->netMovement ?? 0;
  428. $numericNetMovement = CurrencyConverter::convertToCents($netMovement);
  429. if ($numericNetMovement > 0) {
  430. $totalInflow += $numericNetMovement;
  431. } else {
  432. $totalOutflow += $numericNetMovement;
  433. }
  434. }
  435. $netCashChange = $totalInflow + $totalOutflow;
  436. $endingBalance = $startingBalance + $netCashChange;
  437. return $this->formatBalances([
  438. 'starting_balance' => $startingBalance,
  439. 'debit_balance' => $totalInflow,
  440. 'credit_balance' => abs($totalOutflow),
  441. 'net_movement' => $netCashChange,
  442. 'ending_balance' => $endingBalance,
  443. ]);
  444. }
  445. private function buildCashFlowOverview(string $startDate, string $endDate): CashFlowOverviewDTO
  446. {
  447. $accounts = $this->accountService->getBankAccountBalances($startDate, $endDate)->get();
  448. $startingBalanceAccounts = [];
  449. $endingBalanceAccounts = [];
  450. $startingBalanceTotal = 0;
  451. $endingBalanceTotal = 0;
  452. foreach ($accounts as $account) {
  453. $accountBalances = $this->calculateAccountBalances($account);
  454. $startingBalanceTotal += $accountBalances['starting_balance'];
  455. $endingBalanceTotal += $accountBalances['ending_balance'];
  456. $startingBalanceAccounts[] = new AccountDTO(
  457. accountName: $account->name,
  458. accountCode: $account->code,
  459. accountId: $account->id,
  460. balance: $this->formatBalances(['starting_balance' => $accountBalances['starting_balance']]),
  461. startDate: $startDate,
  462. endDate: $endDate,
  463. );
  464. $endingBalanceAccounts[] = new AccountDTO(
  465. accountName: $account->name,
  466. accountCode: $account->code,
  467. accountId: $account->id,
  468. balance: $this->formatBalances(['ending_balance' => $accountBalances['ending_balance']]),
  469. startDate: $startDate,
  470. endDate: $endDate,
  471. );
  472. }
  473. $startingBalanceSummary = $this->formatBalances(['starting_balance' => $startingBalanceTotal]);
  474. $endingBalanceSummary = $this->formatBalances(['ending_balance' => $endingBalanceTotal]);
  475. $overviewCategories = [
  476. 'Starting Balance' => new AccountCategoryDTO(
  477. accounts: $startingBalanceAccounts,
  478. summary: $startingBalanceSummary,
  479. ),
  480. 'Ending Balance' => new AccountCategoryDTO(
  481. accounts: $endingBalanceAccounts,
  482. summary: $endingBalanceSummary,
  483. ),
  484. ];
  485. return new CashFlowOverviewDTO($overviewCategories);
  486. }
  487. private function buildOperatingActivities(string $startDate, string $endDate): AccountCategoryDTO
  488. {
  489. $accounts = $this->accountService->getCashFlowAccountBalances($startDate, $endDate)
  490. ->whereIn('accounts.type', [
  491. AccountType::OperatingRevenue,
  492. AccountType::UncategorizedRevenue,
  493. AccountType::ContraRevenue,
  494. AccountType::OperatingExpense,
  495. AccountType::NonOperatingExpense,
  496. AccountType::UncategorizedExpense,
  497. AccountType::ContraExpense,
  498. AccountType::CurrentAsset,
  499. ])
  500. ->whereRelation('subtype', 'name', '!=', 'Cash and Cash Equivalents')
  501. ->orderByRaw('LENGTH(code), code')
  502. ->get();
  503. $adjustments = $this->accountService->getCashFlowAccountBalances($startDate, $endDate)
  504. ->whereIn('accounts.type', [
  505. AccountType::ContraAsset,
  506. AccountType::CurrentLiability,
  507. ])
  508. ->whereRelation('subtype', 'name', '!=', 'Short-Term Borrowings')
  509. ->orderByRaw('LENGTH(code), code')
  510. ->get();
  511. return $this->formatSectionAccounts($accounts, $adjustments, $startDate, $endDate);
  512. }
  513. private function buildInvestingActivities(string $startDate, string $endDate): AccountCategoryDTO
  514. {
  515. $accounts = $this->accountService->getCashFlowAccountBalances($startDate, $endDate)
  516. ->whereIn('accounts.type', [AccountType::NonCurrentAsset])
  517. ->orderByRaw('LENGTH(code), code')
  518. ->get();
  519. $adjustments = $this->accountService->getCashFlowAccountBalances($startDate, $endDate)
  520. ->whereIn('accounts.type', [AccountType::NonOperatingRevenue])
  521. ->orderByRaw('LENGTH(code), code')
  522. ->get();
  523. return $this->formatSectionAccounts($accounts, $adjustments, $startDate, $endDate);
  524. }
  525. private function buildFinancingActivities(string $startDate, string $endDate): AccountCategoryDTO
  526. {
  527. $accounts = $this->accountService->getCashFlowAccountBalances($startDate, $endDate)
  528. ->where(function (Builder $query) {
  529. $query->whereIn('accounts.type', [
  530. AccountType::Equity,
  531. AccountType::NonCurrentLiability,
  532. ])
  533. ->orWhere(function (Builder $subQuery) {
  534. $subQuery->where('accounts.type', AccountType::CurrentLiability)
  535. ->whereRelation('subtype', 'name', 'Short-Term Borrowings');
  536. });
  537. })
  538. ->orderByRaw('LENGTH(code), code')
  539. ->get();
  540. return $this->formatSectionAccounts($accounts, [], $startDate, $endDate);
  541. }
  542. private function formatSectionAccounts($accounts, $adjustments, string $startDate, string $endDate): AccountCategoryDTO
  543. {
  544. $categoryAccountsByType = [];
  545. $sectionTotal = 0;
  546. $subCategoryTotals = [];
  547. // Process accounts and adjustments
  548. /** @var Account[] $entries */
  549. foreach ([$accounts, $adjustments] as $entries) {
  550. foreach ($entries as $entry) {
  551. $accountCategory = $entry->type->getCategory();
  552. $accountBalances = $this->calculateAccountBalances($entry);
  553. $netCashFlow = $accountBalances['net_movement'] ?? 0;
  554. if ($entry->subtype->inverse_cash_flow) {
  555. $netCashFlow *= -1;
  556. }
  557. // Accumulate totals
  558. $sectionTotal += $netCashFlow;
  559. $accountTypeName = $entry->subtype->name;
  560. $subCategoryTotals[$accountTypeName] = ($subCategoryTotals[$accountTypeName] ?? 0) + $netCashFlow;
  561. // Create AccountDTO and group by account type
  562. $accountDTO = new AccountDTO(
  563. $entry->name,
  564. $entry->code,
  565. $entry->id,
  566. $this->formatBalances(['net_movement' => $netCashFlow]),
  567. $startDate,
  568. $endDate
  569. );
  570. $categoryAccountsByType[$accountTypeName][] = $accountDTO;
  571. }
  572. }
  573. // Prepare AccountTypeDTO for each account type with the accumulated totals
  574. $subCategories = [];
  575. foreach ($categoryAccountsByType as $typeName => $accountsInType) {
  576. $typeTotal = $subCategoryTotals[$typeName] ?? 0;
  577. $formattedTypeTotal = $this->formatBalances(['net_movement' => $typeTotal]);
  578. $subCategories[$typeName] = new AccountTypeDTO(
  579. accounts: $accountsInType,
  580. summary: $formattedTypeTotal
  581. );
  582. }
  583. // Format the overall section total as the section summary
  584. $formattedSectionTotal = $this->formatBalances(['net_movement' => $sectionTotal]);
  585. return new AccountCategoryDTO(
  586. accounts: [], // No direct accounts at the section level
  587. types: $subCategories, // Grouped by AccountTypeDTO
  588. summary: $formattedSectionTotal,
  589. );
  590. }
  591. public function buildBalanceSheetReport(string $asOfDate, array $columns = []): ReportDTO
  592. {
  593. $asOfDateCarbon = Carbon::parse($asOfDate);
  594. $startDateCarbon = Carbon::parse($this->accountService->getEarliestTransactionDate());
  595. $orderedCategories = array_filter(AccountCategory::getOrderedCategories(), fn (AccountCategory $category) => $category->isReal());
  596. $accounts = $this->accountService->getAccountBalances($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())
  597. ->whereIn('category', $orderedCategories)
  598. ->orderByRaw('LENGTH(code), code')
  599. ->get();
  600. $accountCategories = [];
  601. $reportTotalBalances = [
  602. 'assets' => 0,
  603. 'liabilities' => 0,
  604. 'equity' => 0,
  605. ];
  606. foreach ($orderedCategories as $category) {
  607. $categorySummaryBalances = ['ending_balance' => 0];
  608. $categoryAccountsByType = [];
  609. $categoryAccounts = [];
  610. $subCategoryTotals = [];
  611. /** @var Account $account */
  612. foreach ($accounts as $account) {
  613. if ($account->type->getCategory() === $category) {
  614. $accountBalances = $this->calculateAccountBalances($account);
  615. $endingBalance = $accountBalances['ending_balance'] ?? $accountBalances['net_movement'];
  616. $categorySummaryBalances['ending_balance'] += $endingBalance;
  617. $formattedAccountBalances = $this->formatBalances($accountBalances);
  618. $accountDTO = new AccountDTO(
  619. $account->name,
  620. $account->code,
  621. $account->id,
  622. $formattedAccountBalances,
  623. startDate: $startDateCarbon->toDateString(),
  624. endDate: $asOfDateCarbon->toDateString(),
  625. );
  626. if ($category === AccountCategory::Equity && $account->type === AccountType::Equity) {
  627. $categoryAccounts[] = $accountDTO;
  628. } else {
  629. $accountType = $account->type->getPluralLabel();
  630. $categoryAccountsByType[$accountType][] = $accountDTO;
  631. $subCategoryTotals[$accountType] = ($subCategoryTotals[$accountType] ?? 0) + $endingBalance;
  632. }
  633. }
  634. }
  635. if ($category === AccountCategory::Equity) {
  636. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())->getAmount();
  637. $categorySummaryBalances['ending_balance'] += $retainedEarningsAmount;
  638. $retainedEarningsDTO = new AccountDTO(
  639. 'Retained Earnings',
  640. 'RE',
  641. null,
  642. $this->formatBalances(['ending_balance' => $retainedEarningsAmount]),
  643. startDate: $startDateCarbon->toDateString(),
  644. endDate: $asOfDateCarbon->toDateString(),
  645. );
  646. $categoryAccounts[] = $retainedEarningsDTO;
  647. }
  648. $subCategories = [];
  649. foreach ($categoryAccountsByType as $accountType => $accountsInType) {
  650. $subCategorySummary = $this->formatBalances([
  651. 'ending_balance' => $subCategoryTotals[$accountType] ?? 0,
  652. ]);
  653. $subCategories[$accountType] = new AccountTypeDTO(
  654. accounts: $accountsInType,
  655. summary: $subCategorySummary
  656. );
  657. }
  658. $reportTotalBalances[match ($category) {
  659. AccountCategory::Asset => 'assets',
  660. AccountCategory::Liability => 'liabilities',
  661. AccountCategory::Equity => 'equity',
  662. }] += $categorySummaryBalances['ending_balance'];
  663. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  664. accounts: $categoryAccounts,
  665. types: $subCategories,
  666. summary: $this->formatBalances($categorySummaryBalances),
  667. );
  668. }
  669. $netAssets = $reportTotalBalances['assets'] - $reportTotalBalances['liabilities'];
  670. $formattedReportTotalBalances = $this->formatBalances(['ending_balance' => $netAssets]);
  671. return new ReportDTO(
  672. categories: $accountCategories,
  673. overallTotal: $formattedReportTotalBalances,
  674. fields: $columns,
  675. startDate: $startDateCarbon,
  676. endDate: $asOfDateCarbon,
  677. );
  678. }
  679. public function buildAgingReport(
  680. string $asOfDate,
  681. DocumentEntityType $entityType,
  682. array $columns = [],
  683. int $daysPerPeriod = 30,
  684. int $numberOfPeriods = 4
  685. ): ReportDTO {
  686. $asOfDateCarbon = Carbon::parse($asOfDate);
  687. /** @var DocumentCollection<int,DocumentCollection<int,Invoice|Bill>> $documents */
  688. $documents = $entityType === DocumentEntityType::Client
  689. ? $this->accountService->getUnpaidClientInvoices($asOfDate)->with(['client:id,name'])->get()->groupBy('client_id')
  690. : $this->accountService->getUnpaidVendorBills($asOfDate)->with(['vendor:id,name'])->get()->groupBy('vendor_id');
  691. $categories = [];
  692. $totalAging = [
  693. 'current' => 0,
  694. ];
  695. for ($i = 1; $i <= $numberOfPeriods; $i++) {
  696. $totalAging["period_{$i}"] = 0;
  697. }
  698. $totalAging['over_periods'] = 0;
  699. $totalAging['total'] = 0;
  700. foreach ($documents as $entityId => $entityDocuments) {
  701. $aging = [
  702. 'current' => $entityDocuments
  703. ->filter(static fn ($doc) => ($doc->days_overdue ?? 0) <= 0)
  704. ->sumMoneyInDefaultCurrency('amount_due'),
  705. ];
  706. for ($i = 1; $i <= $numberOfPeriods; $i++) {
  707. $min = ($i - 1) * $daysPerPeriod;
  708. $max = $i * $daysPerPeriod;
  709. $aging["period_{$i}"] = $entityDocuments
  710. ->filter(static function ($doc) use ($min, $max) {
  711. $days = $doc->days_overdue ?? 0;
  712. return $days > $min && $days <= $max;
  713. })
  714. ->sumMoneyInDefaultCurrency('amount_due');
  715. }
  716. $aging['over_periods'] = $entityDocuments
  717. ->filter(static fn ($doc) => ($doc->days_overdue ?? 0) > ($numberOfPeriods * $daysPerPeriod))
  718. ->sumMoneyInDefaultCurrency('amount_due');
  719. $aging['total'] = array_sum($aging);
  720. foreach ($aging as $bucket => $amount) {
  721. $totalAging[$bucket] += $amount;
  722. }
  723. $entity = $entityDocuments->first()->{$entityType->value};
  724. $categories[] = new EntityReportDTO(
  725. name: $entity->name,
  726. id: $entityId,
  727. aging: $this->formatBalances($aging, AgingBucketDTO::class, false),
  728. );
  729. }
  730. $totalAging['total'] = array_sum($totalAging);
  731. return new ReportDTO(
  732. categories: ['Entities' => $categories],
  733. agingSummary: $this->formatBalances($totalAging, AgingBucketDTO::class),
  734. fields: $columns,
  735. endDate: $asOfDateCarbon,
  736. );
  737. }
  738. public function buildClientBalanceSummaryReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  739. {
  740. /** @var DocumentCollection<int,DocumentCollection<int,Invoice>> $invoices */
  741. $invoices = Invoice::query()
  742. ->whereBetween('date', [$startDate, $endDate])
  743. ->whereNotIn('status', [
  744. InvoiceStatus::Draft,
  745. InvoiceStatus::Void,
  746. ])
  747. ->whereNotNull('approved_at')
  748. ->with(['client:id,name'])
  749. ->get()
  750. ->groupBy('client_id');
  751. $clients = [];
  752. $totalBalance = 0;
  753. $totalPaidBalance = 0;
  754. $totalUnpaidBalance = 0;
  755. foreach ($invoices as $clientInvoices) {
  756. $clientTotalBalance = $clientInvoices->sumMoneyInDefaultCurrency('total');
  757. $clientPaidBalance = $clientInvoices->sumMoneyInDefaultCurrency('amount_paid');
  758. $clientUnpaidBalance = $clientInvoices->whereNot('status', InvoiceStatus::Overpaid)
  759. ->sumMoneyInDefaultCurrency('amount_due');
  760. $totalBalance += $clientTotalBalance;
  761. $totalPaidBalance += $clientPaidBalance;
  762. $totalUnpaidBalance += $clientUnpaidBalance;
  763. $formattedBalances = $this->formatBalances([
  764. 'total_balance' => $clientTotalBalance,
  765. 'paid_balance' => $clientPaidBalance,
  766. 'unpaid_balance' => $clientUnpaidBalance,
  767. ], ClientBalanceDTO::class);
  768. $client = $clientInvoices->first()->client;
  769. $clients[] = new ClientReportDTO(
  770. clientName: $client->name,
  771. clientId: $client->id,
  772. balance: $formattedBalances,
  773. );
  774. }
  775. $clientBalanceTotal = $this->formatBalances([
  776. 'total_balance' => $totalBalance,
  777. 'paid_balance' => $totalPaidBalance,
  778. 'unpaid_balance' => $totalUnpaidBalance,
  779. ], ClientBalanceDTO::class);
  780. return new ReportDTO(
  781. categories: ['Clients' => $clients],
  782. clientBalanceTotal: $clientBalanceTotal,
  783. fields: $columns,
  784. startDate: Carbon::parse($startDate),
  785. endDate: Carbon::parse($endDate),
  786. );
  787. }
  788. }