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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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\ReportDTO;
  8. use App\Enums\Accounting\AccountCategory;
  9. use App\Models\Accounting\Account;
  10. use App\Support\Column;
  11. use App\Utilities\Currency\CurrencyAccessor;
  12. class ReportService
  13. {
  14. public function __construct(
  15. protected AccountService $accountService,
  16. ) {}
  17. public function formatBalances(array $balances): AccountBalanceDTO
  18. {
  19. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  20. foreach ($balances as $key => $balance) {
  21. $balances[$key] = money($balance, $defaultCurrency)->format();
  22. }
  23. return new AccountBalanceDTO(
  24. startingBalance: $balances['starting_balance'] ?? null,
  25. debitBalance: $balances['debit_balance'] ?? null,
  26. creditBalance: $balances['credit_balance'] ?? null,
  27. netMovement: $balances['net_movement'] ?? null,
  28. endingBalance: $balances['ending_balance'] ?? null,
  29. );
  30. }
  31. public function buildAccountBalanceReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  32. {
  33. $orderedCategories = AccountCategory::getOrderedCategories();
  34. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)->get();
  35. $columnNameKeys = array_map(fn (Column $column) => $column->getName(), $columns);
  36. $accountCategories = [];
  37. $reportTotalBalances = [];
  38. foreach ($orderedCategories as $category) {
  39. $accountsInCategory = $accounts->where('category', $category)
  40. ->sortBy('code', SORT_NATURAL);
  41. $relevantFields = array_intersect($category->getRelevantBalanceFields(), $columnNameKeys);
  42. $categorySummaryBalances = array_fill_keys($relevantFields, 0);
  43. $categoryAccounts = [];
  44. /** @var Account $account */
  45. foreach ($accountsInCategory as $account) {
  46. $accountBalances = $this->calculateAccountBalances($account, $category);
  47. foreach ($relevantFields as $field) {
  48. $categorySummaryBalances[$field] += $accountBalances[$field];
  49. }
  50. $formattedAccountBalances = $this->formatBalances($accountBalances);
  51. $categoryAccounts[] = new AccountDTO(
  52. $account->name,
  53. $account->code,
  54. $account->id,
  55. $formattedAccountBalances,
  56. );
  57. }
  58. foreach ($relevantFields as $field) {
  59. $reportTotalBalances[$field] = ($reportTotalBalances[$field] ?? 0) + $categorySummaryBalances[$field];
  60. }
  61. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  62. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  63. $categoryAccounts,
  64. $formattedCategorySummaryBalances,
  65. );
  66. }
  67. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  68. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  69. }
  70. private function calculateAccountBalances(Account $account, AccountCategory $category): array
  71. {
  72. $balances = [
  73. 'debit_balance' => $account->total_debit ?? 0,
  74. 'credit_balance' => $account->total_credit ?? 0,
  75. ];
  76. if ($category->isNormalDebitBalance()) {
  77. $balances['net_movement'] = $balances['debit_balance'] - $balances['credit_balance'];
  78. } else {
  79. $balances['net_movement'] = $balances['credit_balance'] - $balances['debit_balance'];
  80. }
  81. if ($category->isReal()) {
  82. $balances['starting_balance'] = $account->starting_balance ?? 0;
  83. $balances['ending_balance'] = $balances['starting_balance'] + $balances['net_movement'];
  84. }
  85. return $balances;
  86. }
  87. public function buildAccountTransactionsReport(string $startDate, string $endDate, ?array $columns = null, ?string $accountId = 'all'): ReportDTO
  88. {
  89. $columns ??= [];
  90. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  91. $accountIds = $accountId !== 'all' ? [$accountId] : [];
  92. $query = $this->accountService->getAccountBalances($startDate, $endDate, $accountIds);
  93. $accounts = $query->with(['journalEntries' => $this->accountService->getTransactionDetailsSubquery($startDate, $endDate)])->get();
  94. $reportCategories = [];
  95. foreach ($accounts as $account) {
  96. $accountTransactions = [];
  97. $currentBalance = $account->starting_balance;
  98. $accountTransactions[] = new AccountTransactionDTO(
  99. id: null,
  100. date: 'Starting Balance',
  101. description: '',
  102. debit: '',
  103. credit: '',
  104. balance: money($currentBalance, $defaultCurrency)->format(),
  105. type: null,
  106. tableAction: null
  107. );
  108. /** @var Account $account */
  109. foreach ($account->journalEntries as $journalEntry) {
  110. $transaction = $journalEntry->transaction;
  111. $signedAmount = $journalEntry->signed_amount;
  112. if ($account->category->isNormalDebitBalance()) {
  113. $currentBalance += $signedAmount;
  114. } else {
  115. $currentBalance -= $signedAmount;
  116. }
  117. $formattedAmount = money(abs($signedAmount), $defaultCurrency)->format();
  118. $accountTransactions[] = new AccountTransactionDTO(
  119. id: $transaction->id,
  120. date: $transaction->posted_at->toDefaultDateFormat(),
  121. description: $transaction->description ?? 'Add a description',
  122. debit: $journalEntry->type->isDebit() ? $formattedAmount : '',
  123. credit: $journalEntry->type->isCredit() ? $formattedAmount : '',
  124. balance: money($currentBalance, $defaultCurrency)->format(),
  125. type: $transaction->type,
  126. tableAction: $transaction->type->isJournal() ? 'updateJournalTransaction' : 'updateTransaction'
  127. );
  128. }
  129. $balanceChange = $currentBalance - $account->starting_balance;
  130. $accountTransactions[] = new AccountTransactionDTO(
  131. id: null,
  132. date: 'Totals and Ending Balance',
  133. description: '',
  134. debit: money($account->total_debit, $defaultCurrency)->format(),
  135. credit: money($account->total_credit, $defaultCurrency)->format(),
  136. balance: money($currentBalance, $defaultCurrency)->format(),
  137. type: null,
  138. tableAction: null
  139. );
  140. $accountTransactions[] = new AccountTransactionDTO(
  141. id: null,
  142. date: 'Balance Change',
  143. description: '',
  144. debit: '',
  145. credit: '',
  146. balance: money($balanceChange, $defaultCurrency)->format(),
  147. type: null,
  148. tableAction: null
  149. );
  150. $reportCategories[] = [
  151. 'category' => $account->name,
  152. 'under' => $account->category->getLabel() . ' > ' . $account->subtype->name,
  153. 'transactions' => $accountTransactions,
  154. ];
  155. }
  156. return new ReportDTO(categories: $reportCategories, fields: $columns);
  157. }
  158. public function buildTrialBalanceReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  159. {
  160. $orderedCategories = AccountCategory::getOrderedCategories();
  161. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)->get();
  162. $balanceFields = ['debit_balance', 'credit_balance'];
  163. $accountCategories = [];
  164. $reportTotalBalances = array_fill_keys($balanceFields, 0);
  165. foreach ($orderedCategories as $category) {
  166. $accountsInCategory = $accounts->where('category', $category)
  167. ->sortBy('code', SORT_NATURAL);
  168. $categorySummaryBalances = array_fill_keys($balanceFields, 0);
  169. $categoryAccounts = [];
  170. /** @var Account $account */
  171. foreach ($accountsInCategory as $account) {
  172. $accountBalances = $this->calculateAccountBalances($account, $category);
  173. $endingBalance = $accountBalances['ending_balance'] ?? $accountBalances['net_movement'];
  174. $trialBalance = $this->calculateTrialBalance($account->category, $endingBalance);
  175. foreach ($trialBalance as $balanceType => $balance) {
  176. $categorySummaryBalances[$balanceType] += $balance;
  177. }
  178. $formattedAccountBalances = $this->formatBalances($trialBalance);
  179. $categoryAccounts[] = new AccountDTO(
  180. $account->name,
  181. $account->code,
  182. $account->id,
  183. $formattedAccountBalances,
  184. );
  185. }
  186. if ($category === AccountCategory::Equity) {
  187. $retainedEarningsAmount = $this->accountService->getRetainedEarnings($startDate)->getAmount();
  188. $isCredit = $retainedEarningsAmount >= 0;
  189. $categorySummaryBalances[$isCredit ? 'credit_balance' : 'debit_balance'] += abs($retainedEarningsAmount);
  190. $categoryAccounts[] = new AccountDTO(
  191. 'Retained Earnings',
  192. 'RE',
  193. null,
  194. $this->formatBalances([
  195. 'debit_balance' => $isCredit ? 0 : abs($retainedEarningsAmount),
  196. 'credit_balance' => $isCredit ? $retainedEarningsAmount : 0,
  197. ])
  198. );
  199. }
  200. foreach ($categorySummaryBalances as $balanceType => $balance) {
  201. $reportTotalBalances[$balanceType] += $balance;
  202. }
  203. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  204. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  205. $categoryAccounts,
  206. $formattedCategorySummaryBalances,
  207. );
  208. }
  209. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  210. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  211. }
  212. private function calculateTrialBalance(AccountCategory $category, int $endingBalance): array
  213. {
  214. if ($category->isNormalDebitBalance()) {
  215. if ($endingBalance >= 0) {
  216. return ['debit_balance' => $endingBalance, 'credit_balance' => 0];
  217. }
  218. return ['debit_balance' => 0, 'credit_balance' => abs($endingBalance)];
  219. }
  220. if ($endingBalance >= 0) {
  221. return ['debit_balance' => 0, 'credit_balance' => $endingBalance];
  222. }
  223. return ['debit_balance' => abs($endingBalance), 'credit_balance' => 0];
  224. }
  225. public function buildIncomeStatementReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  226. {
  227. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)->get();
  228. $accountCategories = [];
  229. $totalRevenue = 0;
  230. $cogs = 0;
  231. $totalExpenses = 0;
  232. $categoryGroups = [
  233. 'Revenue' => [
  234. 'accounts' => $accounts->where('category', AccountCategory::Revenue),
  235. 'total' => &$totalRevenue,
  236. ],
  237. 'Cost of Goods Sold' => [
  238. 'accounts' => $accounts->where('subtype.name', 'Cost of Goods Sold'),
  239. 'total' => &$cogs,
  240. ],
  241. 'Expenses' => [
  242. 'accounts' => $accounts->where('category', AccountCategory::Expense)->where('subtype.name', '!=', 'Cost of Goods Sold'),
  243. 'total' => &$totalExpenses,
  244. ],
  245. ];
  246. foreach ($categoryGroups as $label => $group) {
  247. $categoryAccounts = [];
  248. $netMovement = 0;
  249. foreach ($group['accounts']->sortBy('code', SORT_NATURAL) as $account) {
  250. $category = null;
  251. if ($label === 'Revenue') {
  252. $category = AccountCategory::Revenue;
  253. } elseif ($label === 'Expenses') {
  254. $category = AccountCategory::Expense;
  255. } elseif ($label === 'Cost of Goods Sold') {
  256. // COGS is treated as part of Expenses, so we use AccountCategory::Expense
  257. $category = AccountCategory::Expense;
  258. }
  259. if ($category !== null) {
  260. $accountBalances = $this->calculateAccountBalances($account, $category);
  261. $movement = $accountBalances['net_movement'];
  262. $netMovement += $movement;
  263. $group['total'] += $movement;
  264. $categoryAccounts[] = new AccountDTO(
  265. $account->name,
  266. $account->code,
  267. $account->id,
  268. $this->formatBalances(['net_movement' => $movement]),
  269. );
  270. }
  271. }
  272. $accountCategories[$label] = new AccountCategoryDTO(
  273. $categoryAccounts,
  274. $this->formatBalances(['net_movement' => $netMovement]),
  275. );
  276. }
  277. $grossProfit = $totalRevenue - $cogs;
  278. $netProfit = $grossProfit - $totalExpenses;
  279. $formattedReportTotalBalances = $this->formatBalances(['net_movement' => $netProfit]);
  280. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  281. }
  282. }