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

ReportService.php 17KB

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