選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

ReportService.php 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  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. $modifiedStartDate = Carbon::parse($this->accountService->getEarliestTransactionDate())->startOfYear()->toDateString();
  213. $modifiedEndDate = Carbon::parse($startDate)->subYear()->endOfYear()->toDateString();
  214. $retainedEarningsAmount = $this->calculateRetainedEarnings($startDate)->getAmount();
  215. $isCredit = $retainedEarningsAmount >= 0;
  216. $categorySummaryBalances[$isCredit ? 'credit_balance' : 'debit_balance'] += abs($retainedEarningsAmount);
  217. $categoryAccounts[] = new AccountDTO(
  218. 'Retained Earnings',
  219. 'RE',
  220. null,
  221. $this->formatBalances([
  222. 'debit_balance' => $isCredit ? 0 : abs($retainedEarningsAmount),
  223. 'credit_balance' => $isCredit ? $retainedEarningsAmount : 0,
  224. ]),
  225. $modifiedStartDate,
  226. $modifiedEndDate,
  227. );
  228. }
  229. foreach ($categorySummaryBalances as $balanceType => $balance) {
  230. $reportTotalBalances[$balanceType] += $balance;
  231. }
  232. $formattedCategorySummaryBalances = $this->formatBalances($categorySummaryBalances);
  233. $accountCategories[$category->getPluralLabel()] = new AccountCategoryDTO(
  234. $categoryAccounts,
  235. $formattedCategorySummaryBalances,
  236. );
  237. }
  238. $formattedReportTotalBalances = $this->formatBalances($reportTotalBalances);
  239. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  240. }
  241. private function calculateTrialBalance(AccountCategory $category, int $endingBalance): array
  242. {
  243. if ($category->isNormalDebitBalance()) {
  244. if ($endingBalance >= 0) {
  245. return ['debit_balance' => $endingBalance, 'credit_balance' => 0];
  246. }
  247. return ['debit_balance' => 0, 'credit_balance' => abs($endingBalance)];
  248. }
  249. if ($endingBalance >= 0) {
  250. return ['debit_balance' => 0, 'credit_balance' => $endingBalance];
  251. }
  252. return ['debit_balance' => abs($endingBalance), 'credit_balance' => 0];
  253. }
  254. public function buildIncomeStatementReport(string $startDate, string $endDate, array $columns = []): ReportDTO
  255. {
  256. $accounts = $this->accountService->getAccountBalances($startDate, $endDate)->get();
  257. $accountCategories = [];
  258. $totalRevenue = 0;
  259. $cogs = 0;
  260. $totalExpenses = 0;
  261. $categoryGroups = [
  262. 'Revenue' => [
  263. 'accounts' => $accounts->where('category', AccountCategory::Revenue),
  264. 'total' => &$totalRevenue,
  265. ],
  266. 'Cost of Goods Sold' => [
  267. 'accounts' => $accounts->where('subtype.name', 'Cost of Goods Sold'),
  268. 'total' => &$cogs,
  269. ],
  270. 'Expenses' => [
  271. 'accounts' => $accounts->where('category', AccountCategory::Expense)->where('subtype.name', '!=', 'Cost of Goods Sold'),
  272. 'total' => &$totalExpenses,
  273. ],
  274. ];
  275. foreach ($categoryGroups as $label => $group) {
  276. $categoryAccounts = [];
  277. $netMovement = 0;
  278. foreach ($group['accounts']->sortBy('code', SORT_NATURAL) as $account) {
  279. $category = null;
  280. if ($label === 'Revenue') {
  281. $category = AccountCategory::Revenue;
  282. } elseif ($label === 'Expenses') {
  283. $category = AccountCategory::Expense;
  284. } elseif ($label === 'Cost of Goods Sold') {
  285. // COGS is treated as part of Expenses, so we use AccountCategory::Expense
  286. $category = AccountCategory::Expense;
  287. }
  288. if ($category !== null) {
  289. $accountBalances = $this->calculateAccountBalances($account, $category);
  290. $movement = $accountBalances['net_movement'];
  291. $netMovement += $movement;
  292. $group['total'] += $movement;
  293. $categoryAccounts[] = new AccountDTO(
  294. $account->name,
  295. $account->code,
  296. $account->id,
  297. $this->formatBalances(['net_movement' => $movement]),
  298. Carbon::parse($startDate)->toDateString(),
  299. Carbon::parse($endDate)->toDateString(),
  300. );
  301. }
  302. }
  303. $accountCategories[$label] = new AccountCategoryDTO(
  304. $categoryAccounts,
  305. $this->formatBalances(['net_movement' => $netMovement]),
  306. );
  307. }
  308. $grossProfit = $totalRevenue - $cogs;
  309. $netProfit = $grossProfit - $totalExpenses;
  310. $formattedReportTotalBalances = $this->formatBalances(['net_movement' => $netProfit]);
  311. return new ReportDTO($accountCategories, $formattedReportTotalBalances, $columns);
  312. }
  313. }