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

ReportService.php 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. Carbon::parse($startDate)->toDateString(),
  59. Carbon::parse($endDate)->toDateString(),
  60. );
  61. }
  62. foreach ($relevantFields as $field) {
  63. $reportTotalBalances[$field] = ($reportTotalBalances[$field] ?? 0) + $categorySummaryBalances[$field];
  64. }
  65. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  66. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  67. $categoryAccounts,
  68. $formattedCategorySummaryBalances,
  69. );
  70. }
  71. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  72. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  73. }
  74. private function calculateAccountBalances(Account $account, AccountCategory $category): array
  75. {
  76. $balances = [
  77. 'debit_balance' => $account->total_debit ?? 0,
  78. 'credit_balance' => $account->total_credit ?? 0,
  79. ];
  80. if ($category->isNormalDebitBalance()) {
  81. $balances['net_movement'] = $balances['debit_balance'] - $balances['credit_balance'];
  82. } else {
  83. $balances['net_movement'] = $balances['credit_balance'] - $balances['debit_balance'];
  84. }
  85. if ($category->isReal()) {
  86. $balances['starting_balance'] = $account->starting_balance ?? 0;
  87. $balances['ending_balance'] = $balances['starting_balance'] + $balances['net_movement'];
  88. }
  89. return $balances;
  90. }
  91. public function calculateRetainedEarnings(string $startDate): Money
  92. {
  93. $modifiedStartDate = Carbon::parse($this->accountService->getEarliestTransactionDate())->startOfYear()->toDateTimeString();
  94. $endDate = Carbon::parse($startDate)->subYear()->endOfYear()->toDateTimeString();
  95. $revenueAccounts = $this->accountService->getAccountBalances($modifiedStartDate, $endDate)->where('category', AccountCategory::Revenue)->get();
  96. $expenseAccounts = $this->accountService->getAccountBalances($modifiedStartDate, $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 $startDate, string $endDate, array $columns = []): ReportDTO
  182. {
  183. $orderedCategories = AccountCategory::getOrderedCategories();
  184. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)->get();
  185. $balanceFields = ['debit_balance', 'credit_balance'];
  186. $accountCategories = [];
  187. $reportTotalBalances = array_fill_keys($balanceFields, 0);
  188. foreach ($orderedCategories as $category) {
  189. $accountsInCategory = $accounts->where('category', $category)
  190. ->sortBy('code', SORT_NATURAL);
  191. $categorySummaryBalances = array_fill_keys($balanceFields, 0);
  192. $categoryAccounts = [];
  193. /** @var Account $account */
  194. foreach ($accountsInCategory as $account) {
  195. $accountBalances = $this->calculateAccountBalances($account, $category);
  196. $endingBalance = $accountBalances['ending_balance'] ?? $accountBalances['net_movement'];
  197. $trialBalance = $this->calculateTrialBalance($account->category, $endingBalance);
  198. foreach ($trialBalance as $balanceType => $balance) {
  199. $categorySummaryBalances[$balanceType] += $balance;
  200. }
  201. $formattedAccountBalances = $this->formatBalances($trialBalance);
  202. $categoryAccounts[] = new AccountDTO(
  203. $account->name,
  204. $account->code,
  205. $account->id,
  206. $formattedAccountBalances,
  207. Carbon::parse($startDate)->toDateString(),
  208. Carbon::parse($endDate)->toDateString(),
  209. );
  210. }
  211. if ($category === AccountCategory::Equity) {
  212. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDate)->getAmount();
  213. $isCredit = $retainedEarningsAmount >= 0;
  214. $categorySummaryBalances[$isCredit ? 'credit_balance' : 'debit_balance'] += abs($retainedEarningsAmount);
  215. $categoryAccounts[] = new AccountDTO(
  216. 'Retained Earnings',
  217. 'RE',
  218. null,
  219. $this->formatBalances([
  220. 'debit_balance' => $isCredit ? 0 : abs($retainedEarningsAmount),
  221. 'credit_balance' => $isCredit ? $retainedEarningsAmount : 0,
  222. ]),
  223. null,
  224. null,
  225. );
  226. }
  227. foreach ($categorySummaryBalances as $balanceType => $balance) {
  228. $reportTotalBalances[$balanceType] += $balance;
  229. }
  230. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  231. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  232. $categoryAccounts,
  233. $formattedCategorySummaryBalances,
  234. );
  235. }
  236. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  237. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  238. }
  239. private function calculateTrialBalance(AccountCategory $category, int $endingBalance): array
  240. {
  241. if ($category->isNormalDebitBalance()) {
  242. if ($endingBalance >= 0) {
  243. return ['debit_balance' => $endingBalance, 'credit_balance' => 0];
  244. }
  245. return ['debit_balance' => 0, 'credit_balance' => abs($endingBalance)];
  246. }
  247. if ($endingBalance >= 0) {
  248. return ['debit_balance' => 0, 'credit_balance' => $endingBalance];
  249. }
  250. return ['debit_balance' => abs($endingBalance), 'credit_balance' => 0];
  251. }
  252. public function buildIncomeStatementReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  253. {
  254. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)->get();
  255. $accountCategories = [];
  256. $totalRevenue = 0;
  257. $cogs = 0;
  258. $totalExpenses = 0;
  259. $categoryGroups = [
  260. 'Revenue' => [
  261. 'accounts' => $accounts->where('category', AccountCategory::Revenue),
  262. 'total' => &$totalRevenue,
  263. ],
  264. 'Cost of Goods Sold' => [
  265. 'accounts' => $accounts->where('subtype.name', 'Cost of Goods Sold'),
  266. 'total' => &$cogs,
  267. ],
  268. 'Expenses' => [
  269. 'accounts' => $accounts->where('category', AccountCategory::Expense)->where('subtype.name', '!=', 'Cost of Goods Sold'),
  270. 'total' => &$totalExpenses,
  271. ],
  272. ];
  273. foreach ($categoryGroups as $label => $group) {
  274. $categoryAccounts = [];
  275. $netMovement = 0;
  276. foreach ($group['accounts']->sortBy('code', SORT_NATURAL) as $account) {
  277. $category = null;
  278. if ($label === 'Revenue') {
  279. $category = AccountCategory::Revenue;
  280. } elseif ($label === 'Expenses') {
  281. $category = AccountCategory::Expense;
  282. } elseif ($label === 'Cost of Goods Sold') {
  283. // COGS is treated as part of Expenses, so we use AccountCategory::Expense
  284. $category = AccountCategory::Expense;
  285. }
  286. if ($category !== null) {
  287. $accountBalances = $this->calculateAccountBalances($account, $category);
  288. $movement = $accountBalances['net_movement'];
  289. $netMovement += $movement;
  290. $group['total'] += $movement;
  291. $categoryAccounts[] = new AccountDTO(
  292. $account->name,
  293. $account->code,
  294. $account->id,
  295. $this->formatBalances(['net_movement' => $movement]),
  296. Carbon::parse($startDate)->toDateString(),
  297. Carbon::parse($endDate)->toDateString(),
  298. );
  299. }
  300. }
  301. $accountCategories[$label] = new AccountCategoryDTO(
  302. $categoryAccounts,
  303. $this->formatBalances(['net_movement' => $netMovement]),
  304. );
  305. }
  306. $grossProfit = $totalRevenue - $cogs;
  307. $netProfit = $grossProfit - $totalExpenses;
  308. $formattedReportTotalBalances = $this->formatBalances(['net_movement' => $netProfit]);
  309. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  310. }
  311. }