Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ReportService.php 22KB

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