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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. <?php
  2. namespace App\Services;
  3. use App\DTO\AccountBalanceDTO;
  4. use App\DTO\AccountCategoryDTO;
  5. use App\DTO\AccountDTO;
  6. use App\DTO\AccountTransactionDTO;
  7. use App\DTO\AccountTypeDTO;
  8. use App\DTO\ReportDTO;
  9. use App\Enums\Accounting\AccountCategory;
  10. use App\Models\Accounting\Account;
  11. use App\Support\Column;
  12. use App\Utilities\Currency\CurrencyAccessor;
  13. use App\ValueObjects\Money;
  14. use Illuminate\Database\Eloquent\Builder;
  15. use Illuminate\Support\Carbon;
  16. class ReportService
  17. {
  18. public function __construct(
  19. protected AccountService $accountService,
  20. ) {}
  21. public function formatBalances(array $balances): AccountBalanceDTO
  22. {
  23. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  24. foreach ($balances as $key => $balance) {
  25. $balances[$key] = money($balance, $defaultCurrency)->format();
  26. }
  27. return new AccountBalanceDTO(
  28. startingBalance: $balances['starting_balance'] ?? null,
  29. debitBalance: $balances['debit_balance'] ?? null,
  30. creditBalance: $balances['credit_balance'] ?? null,
  31. netMovement: $balances['net_movement'] ?? null,
  32. endingBalance: $balances['ending_balance'] ?? null,
  33. );
  34. }
  35. public function buildAccountBalanceReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  36. {
  37. $orderedCategories = AccountCategory::getOrderedCategories();
  38. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)->get();
  39. $columnNameKeys = array_map(fn (Column $column) => $column->getName(), $columns);
  40. $accountCategories = [];
  41. $reportTotalBalances = [];
  42. foreach ($orderedCategories as $category) {
  43. $accountsInCategory = $accounts->where('category', $category)
  44. ->sortBy('code', SORT_NATURAL);
  45. $relevantFields = array_intersect($category->getRelevantBalanceFields(), $columnNameKeys);
  46. $categorySummaryBalances = array_fill_keys($relevantFields, 0);
  47. $categoryAccounts = [];
  48. /** @var Account $account */
  49. foreach ($accountsInCategory as $account) {
  50. $accountBalances = $this->calculateAccountBalances($account, $category);
  51. foreach ($relevantFields as $field) {
  52. $categorySummaryBalances[$field] += $accountBalances[$field];
  53. }
  54. $formattedAccountBalances = $this->formatBalances($accountBalances);
  55. $categoryAccounts[] = new AccountDTO(
  56. $account->name,
  57. $account->code,
  58. $account->id,
  59. $formattedAccountBalances,
  60. Carbon::parse($startDate)->toDateString(),
  61. Carbon::parse($endDate)->toDateString(),
  62. );
  63. }
  64. foreach ($relevantFields as $field) {
  65. $reportTotalBalances[$field] = ($reportTotalBalances[$field] ?? 0) + $categorySummaryBalances[$field];
  66. }
  67. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  68. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  69. accounts: $categoryAccounts,
  70. summary: $formattedCategorySummaryBalances,
  71. );
  72. }
  73. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  74. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  75. }
  76. public function calculateAccountBalances(Account $account, AccountCategory $category): array
  77. {
  78. $balances = [
  79. 'debit_balance' => $account->total_debit ?? 0,
  80. 'credit_balance' => $account->total_credit ?? 0,
  81. ];
  82. if ($category->isNormalDebitBalance()) {
  83. $balances['net_movement'] = $balances['debit_balance'] - $balances['credit_balance'];
  84. } else {
  85. $balances['net_movement'] = $balances['credit_balance'] - $balances['debit_balance'];
  86. }
  87. if ($category->isReal()) {
  88. $balances['starting_balance'] = $account->starting_balance ?? 0;
  89. $balances['ending_balance'] = $balances['starting_balance'] + $balances['net_movement'];
  90. }
  91. return $balances;
  92. }
  93. public function calculateRetainedEarnings(?string $startDate, string $endDate): Money
  94. {
  95. $startDate ??= Carbon::parse($this->accountService->getEarliestTransactionDate())->toDateTimeString();
  96. $revenueAccounts = $this->accountService->getAccountBalances($startDate, $endDate)->where('category', AccountCategory::Revenue)->get();
  97. $expenseAccounts = $this->accountService->getAccountBalances($startDate, $endDate)->where('category', AccountCategory::Expense)->get();
  98. $revenueTotal = 0;
  99. $expenseTotal = 0;
  100. foreach ($revenueAccounts as $account) {
  101. $revenueBalances = $this->calculateAccountBalances($account, AccountCategory::Revenue);
  102. $revenueTotal += $revenueBalances['net_movement'];
  103. }
  104. foreach ($expenseAccounts as $account) {
  105. $expenseBalances = $this->calculateAccountBalances($account, AccountCategory::Expense);
  106. $expenseTotal += $expenseBalances['net_movement'];
  107. }
  108. $retainedEarnings = $revenueTotal - $expenseTotal;
  109. return new Money($retainedEarnings, CurrencyAccessor::getDefaultCurrency());
  110. }
  111. public function buildAccountTransactionsReport(string $startDate, string $endDate, ?array $columns = null, ?string $accountId = 'all'): ReportDTO
  112. {
  113. $columns ??= [];
  114. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  115. $accountIds = $accountId !== 'all' ? [$accountId] : [];
  116. $query = $this->accountService->getAccountBalances($startDate, $endDate, $accountIds);
  117. $accounts = $query->with(['journalEntries' => $this->accountService->getTransactionDetailsSubquery($startDate, $endDate)])->get();
  118. $reportCategories = [];
  119. foreach ($accounts as $account) {
  120. $accountTransactions = [];
  121. $currentBalance = $account->starting_balance;
  122. $accountTransactions[] = new AccountTransactionDTO(
  123. id: null,
  124. date: 'Starting Balance',
  125. description: '',
  126. debit: '',
  127. credit: '',
  128. balance: money($currentBalance, $defaultCurrency)->format(),
  129. type: null,
  130. tableAction: null
  131. );
  132. /** @var Account $account */
  133. foreach ($account->journalEntries as $journalEntry) {
  134. $transaction = $journalEntry->transaction;
  135. $signedAmount = $journalEntry->signed_amount;
  136. if ($account->category->isNormalDebitBalance()) {
  137. $currentBalance += $signedAmount;
  138. } else {
  139. $currentBalance -= $signedAmount;
  140. }
  141. $formattedAmount = money(abs($signedAmount), $defaultCurrency)->format();
  142. $accountTransactions[] = new AccountTransactionDTO(
  143. id: $transaction->id,
  144. date: $transaction->posted_at->toDefaultDateFormat(),
  145. description: $transaction->description ?? 'Add a description',
  146. debit: $journalEntry->type->isDebit() ? $formattedAmount : '',
  147. credit: $journalEntry->type->isCredit() ? $formattedAmount : '',
  148. balance: money($currentBalance, $defaultCurrency)->format(),
  149. type: $transaction->type,
  150. tableAction: $transaction->type->isJournal() ? 'updateJournalTransaction' : 'updateTransaction'
  151. );
  152. }
  153. $balanceChange = $currentBalance - $account->starting_balance;
  154. $accountTransactions[] = new AccountTransactionDTO(
  155. id: null,
  156. date: 'Totals and Ending Balance',
  157. description: '',
  158. debit: money($account->total_debit, $defaultCurrency)->format(),
  159. credit: money($account->total_credit, $defaultCurrency)->format(),
  160. balance: money($currentBalance, $defaultCurrency)->format(),
  161. type: null,
  162. tableAction: null
  163. );
  164. $accountTransactions[] = new AccountTransactionDTO(
  165. id: null,
  166. date: 'Balance Change',
  167. description: '',
  168. debit: '',
  169. credit: '',
  170. balance: money($balanceChange, $defaultCurrency)->format(),
  171. type: null,
  172. tableAction: null
  173. );
  174. $reportCategories[] = [
  175. 'category' => $account->name,
  176. 'under' => $account->category->getLabel() . ' > ' . $account->subtype->name,
  177. 'transactions' => $accountTransactions,
  178. ];
  179. }
  180. return new ReportDTO(categories: $reportCategories, fields: $columns);
  181. }
  182. public function buildTrialBalanceReport(string $trialBalanceType, string $asOfDate, array $columns = []): ReportDTO
  183. {
  184. $asOfDateCarbon = Carbon::parse($asOfDate);
  185. $startDateCarbon = Carbon::parse($this->accountService->getEarliestTransactionDate());
  186. $orderedCategories = AccountCategory::getOrderedCategories();
  187. $isPostClosingTrialBalance = $trialBalanceType === 'postClosing';
  188. $accounts = $this->accountService->getAccountBalances($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())
  189. ->when($isPostClosingTrialBalance, fn (Builder $query) => $query->whereNotIn('category', [AccountCategory::Revenue, AccountCategory::Expense]))
  190. ->get();
  191. $balanceFields = ['debit_balance', 'credit_balance'];
  192. $accountCategories = [];
  193. $reportTotalBalances = array_fill_keys($balanceFields, 0);
  194. foreach ($orderedCategories as $category) {
  195. $accountsInCategory = $accounts->where('category', $category)
  196. ->sortBy('code', SORT_NATURAL);
  197. $categorySummaryBalances = array_fill_keys($balanceFields, 0);
  198. $categoryAccounts = [];
  199. /** @var Account $account */
  200. foreach ($accountsInCategory as $account) {
  201. $accountBalances = $this->calculateAccountBalances($account, $category);
  202. $endingBalance = $accountBalances['ending_balance'] ?? $accountBalances['net_movement'];
  203. $trialBalance = $this->calculateTrialBalances($account->category, $endingBalance);
  204. foreach ($trialBalance as $balanceType => $balance) {
  205. $categorySummaryBalances[$balanceType] += $balance;
  206. }
  207. $formattedAccountBalances = $this->formatBalances($trialBalance);
  208. $categoryAccounts[] = new AccountDTO(
  209. $account->name,
  210. $account->code,
  211. $account->id,
  212. $formattedAccountBalances,
  213. startDate: $startDateCarbon->toDateString(),
  214. endDate: $asOfDateCarbon->toDateString(),
  215. );
  216. }
  217. if ($category === AccountCategory::Equity && $isPostClosingTrialBalance) {
  218. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())->getAmount();
  219. $isCredit = $retainedEarningsAmount >= 0;
  220. $categorySummaryBalances[$isCredit ? 'credit_balance' : 'debit_balance'] += abs($retainedEarningsAmount);
  221. $categoryAccounts[] = new AccountDTO(
  222. 'Retained Earnings',
  223. 'RE',
  224. null,
  225. $this->formatBalances([
  226. 'debit_balance' => $isCredit ? 0 : abs($retainedEarningsAmount),
  227. 'credit_balance' => $isCredit ? $retainedEarningsAmount : 0,
  228. ]),
  229. startDate: $startDateCarbon->toDateString(),
  230. endDate: $asOfDateCarbon->toDateString(),
  231. );
  232. }
  233. foreach ($categorySummaryBalances as $balanceType => $balance) {
  234. $reportTotalBalances[$balanceType] += $balance;
  235. }
  236. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  237. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  238. accounts: $categoryAccounts,
  239. summary: $formattedCategorySummaryBalances,
  240. );
  241. }
  242. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  243. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns, $trialBalanceType);
  244. }
  245. public function getRetainedEarningsBalances(string $startDate, string $endDate): AccountBalanceDTO
  246. {
  247. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDate, $endDate)->getAmount();
  248. $isCredit = $retainedEarningsAmount >= 0;
  249. $retainedEarningsDebitAmount = $isCredit ? 0 : abs($retainedEarningsAmount);
  250. $retainedEarningsCreditAmount = $isCredit ? $retainedEarningsAmount : 0;
  251. return $this->formatBalances([
  252. 'debit_balance' => $retainedEarningsDebitAmount,
  253. 'credit_balance' => $retainedEarningsCreditAmount,
  254. ]);
  255. }
  256. public function calculateTrialBalances(AccountCategory $category, int $endingBalance): array
  257. {
  258. if ($category->isNormalDebitBalance()) {
  259. if ($endingBalance >= 0) {
  260. return ['debit_balance' => $endingBalance, 'credit_balance' => 0];
  261. }
  262. return ['debit_balance' => 0, 'credit_balance' => abs($endingBalance)];
  263. }
  264. if ($endingBalance >= 0) {
  265. return ['debit_balance' => 0, 'credit_balance' => $endingBalance];
  266. }
  267. return ['debit_balance' => abs($endingBalance), 'credit_balance' => 0];
  268. }
  269. public function buildIncomeStatementReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  270. {
  271. // Query only relevant accounts and sort them at the query level
  272. $revenueAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  273. ->where('category', AccountCategory::Revenue)
  274. ->orderByRaw('LENGTH(code), code')
  275. ->get();
  276. $cogsAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  277. ->whereRelation('subtype', 'name', 'Cost of Goods Sold')
  278. ->orderByRaw('LENGTH(code), code')
  279. ->get();
  280. $expenseAccounts = $this->accountService->getAccountBalances($startDate, $endDate)
  281. ->where('category', AccountCategory::Expense)
  282. ->whereRelation('subtype', 'name', '!=', 'Cost of Goods Sold')
  283. ->orderByRaw('LENGTH(code), code')
  284. ->get();
  285. $accountCategories = [];
  286. $totalRevenue = 0;
  287. $totalCogs = 0;
  288. $totalExpenses = 0;
  289. // Define category groups
  290. $categoryGroups = [
  291. AccountCategory::Revenue->getPluralLabel() => [
  292. 'accounts' => $revenueAccounts,
  293. 'total' => &$totalRevenue,
  294. ],
  295. 'Cost of Goods Sold' => [
  296. 'accounts' => $cogsAccounts,
  297. 'total' => &$totalCogs,
  298. ],
  299. AccountCategory::Expense->getPluralLabel() => [
  300. 'accounts' => $expenseAccounts,
  301. 'total' => &$totalExpenses,
  302. ],
  303. ];
  304. // Process each category group
  305. foreach ($categoryGroups as $label => $group) {
  306. $categoryAccounts = [];
  307. $netMovement = 0;
  308. foreach ($group['accounts'] as $account) {
  309. // Use the category type based on label
  310. $category = match ($label) {
  311. AccountCategory::Revenue->getPluralLabel() => AccountCategory::Revenue,
  312. AccountCategory::Expense->getPluralLabel(), 'Cost of Goods Sold' => AccountCategory::Expense,
  313. default => null
  314. };
  315. if ($category !== null) {
  316. $accountBalances = $this->calculateAccountBalances($account, $category);
  317. $movement = $accountBalances['net_movement'];
  318. $netMovement += $movement;
  319. $group['total'] += $movement;
  320. $categoryAccounts[] = new AccountDTO(
  321. $account->name,
  322. $account->code,
  323. $account->id,
  324. $this->formatBalances(['net_movement' => $movement]),
  325. Carbon::parse($startDate)->toDateString(),
  326. Carbon::parse($endDate)->toDateString(),
  327. );
  328. }
  329. }
  330. $accountCategories[$label] = new AccountCategoryDTO(
  331. accounts: $categoryAccounts,
  332. summary: $this->formatBalances(['net_movement' => $netMovement])
  333. );
  334. }
  335. // Calculate gross and net profit
  336. $grossProfit = $totalRevenue - $totalCogs;
  337. $netProfit = $grossProfit - $totalExpenses;
  338. $formattedReportTotalBalances = $this->formatBalances(['net_movement' => $netProfit]);
  339. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  340. }
  341. public function buildBalanceSheetReport(string $asOfDate, array $columns = []): ReportDTO
  342. {
  343. $asOfDateCarbon = Carbon::parse($asOfDate);
  344. $startDateCarbon = Carbon::parse($this->accountService->getEarliestTransactionDate());
  345. $orderedCategories = AccountCategory::getOrderedCategories();
  346. // Filter out non-real categories like Revenue and Expense
  347. $orderedCategories = array_filter($orderedCategories, fn (AccountCategory $category) => $category->isReal());
  348. // Fetch account balances
  349. $accounts = $this->accountService->getAccountBalances($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())
  350. ->get();
  351. $accountCategories = [];
  352. $reportTotalBalances = [
  353. 'assets' => 0,
  354. 'liabilities' => 0,
  355. 'equity' => 0,
  356. ];
  357. foreach ($orderedCategories as $category) {
  358. $categorySummaryBalances = ['ending_balance' => 0];
  359. // Group the accounts by their type within the current category
  360. $categoryAccountsByType = [];
  361. $subCategoryTotals = [];
  362. /** @var Account $account */
  363. foreach ($accounts as $account) {
  364. // Ensure that the account type's category matches the current loop category
  365. if ($account->type->getCategory() === $category) {
  366. $accountBalances = $this->calculateAccountBalances($account, $category);
  367. $endingBalance = $accountBalances['ending_balance'] ?? $accountBalances['net_movement'];
  368. $categorySummaryBalances['ending_balance'] += $endingBalance;
  369. $formattedAccountBalances = $this->formatBalances($accountBalances);
  370. // Create a DTO for each account
  371. $accountDTO = new AccountDTO(
  372. $account->name,
  373. $account->code,
  374. $account->id,
  375. $formattedAccountBalances,
  376. startDate: $startDateCarbon->toDateString(),
  377. endDate: $asOfDateCarbon->toDateString(),
  378. );
  379. // Group by account type label and accumulate subcategory totals
  380. $accountType = $account->type->getPluralLabel();
  381. $categoryAccountsByType[$accountType][] = $accountDTO;
  382. // Track totals for the subcategory (not formatted)
  383. $subCategoryTotals[$accountType] = ($subCategoryTotals[$accountType] ?? 0) + $endingBalance;
  384. }
  385. }
  386. // If the category is Equity, include Retained Earnings
  387. if ($category === AccountCategory::Equity) {
  388. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDateCarbon->toDateTimeString(), $asOfDateCarbon->toDateTimeString())->getAmount();
  389. $categorySummaryBalances['ending_balance'] += $retainedEarningsAmount;
  390. $accountDTO = new AccountDTO(
  391. 'Retained Earnings',
  392. 'RE',
  393. null,
  394. $this->formatBalances(['ending_balance' => $retainedEarningsAmount]),
  395. startDate: $startDateCarbon->toDateString(),
  396. endDate: $asOfDateCarbon->toDateString(),
  397. );
  398. // Add Retained Earnings to the Equity type
  399. $categoryAccountsByType['Equity'][] = $accountDTO;
  400. // Add to subcategory total as well
  401. $subCategoryTotals['Equity'] = ($subCategoryTotals['Equity'] ?? 0) + $retainedEarningsAmount;
  402. }
  403. // Create SubCategory DTOs for each account type within the category
  404. $subCategories = [];
  405. foreach ($categoryAccountsByType as $accountType => $accountsInType) {
  406. $subCategorySummary = $this->formatBalances([
  407. 'ending_balance' => $subCategoryTotals[$accountType] ?? 0,
  408. ]);
  409. $subCategories[$accountType] = new AccountTypeDTO(
  410. accounts: $accountsInType,
  411. summary: $subCategorySummary
  412. );
  413. }
  414. // Add category totals to the overall totals
  415. if ($category === AccountCategory::Asset) {
  416. $reportTotalBalances['assets'] += $categorySummaryBalances['ending_balance'];
  417. } elseif ($category === AccountCategory::Liability) {
  418. $reportTotalBalances['liabilities'] += $categorySummaryBalances['ending_balance'];
  419. } elseif ($category === AccountCategory::Equity) {
  420. $reportTotalBalances['equity'] += $categorySummaryBalances['ending_balance'];
  421. }
  422. // Store the subcategories and the summary in the accountCategories array
  423. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  424. types: $subCategories,
  425. summary: $this->formatBalances($categorySummaryBalances),
  426. );
  427. }
  428. // Calculate Net Assets (Assets - Liabilities)
  429. $netAssets = $reportTotalBalances['assets'] - $reportTotalBalances['liabilities'];
  430. // Format the overall totals for the report
  431. $formattedReportTotalBalances = $this->formatBalances(['ending_balance' => $netAssets]);
  432. // Return the constructed ReportDTO
  433. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  434. }
  435. }