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

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