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

AccountService.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. namespace App\Services;
  3. use App\Contracts\AccountHandler;
  4. use App\Enums\Accounting\AccountCategory;
  5. use App\Models\Accounting\Account;
  6. use App\Models\Accounting\JournalEntry;
  7. use App\Models\Accounting\Transaction;
  8. use App\Repositories\Accounting\JournalEntryRepository;
  9. use App\Utilities\Currency\CurrencyAccessor;
  10. use App\ValueObjects\Money;
  11. use Closure;
  12. use Illuminate\Database\Eloquent\Builder;
  13. use Illuminate\Database\Query\JoinClause;
  14. use Illuminate\Support\Facades\DB;
  15. class AccountService implements AccountHandler
  16. {
  17. public function __construct(
  18. protected JournalEntryRepository $journalEntryRepository
  19. ) {}
  20. public function getDebitBalance(Account $account, string $startDate, string $endDate): Money
  21. {
  22. $amount = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  23. return new Money($amount, $account->currency_code);
  24. }
  25. public function getCreditBalance(Account $account, string $startDate, string $endDate): Money
  26. {
  27. $amount = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  28. return new Money($amount, $account->currency_code);
  29. }
  30. public function getNetMovement(Account $account, string $startDate, string $endDate): Money
  31. {
  32. $balances = $this->calculateBalances($account, $startDate, $endDate);
  33. return new Money($balances['net_movement'], $account->currency_code);
  34. }
  35. public function getStartingBalance(Account $account, string $startDate, bool $override = false): ?Money
  36. {
  37. if ($override === false && in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  38. return null;
  39. }
  40. $balances = $this->calculateStartingBalances($account, $startDate);
  41. return new Money($balances['starting_balance'], $account->currency_code);
  42. }
  43. public function getTransactionDetailsSubquery(string $startDate, string $endDate): Closure
  44. {
  45. return static function ($query) use ($startDate, $endDate) {
  46. $query->select(
  47. 'journal_entries.id',
  48. 'journal_entries.account_id',
  49. 'journal_entries.transaction_id',
  50. 'journal_entries.type',
  51. 'journal_entries.amount',
  52. DB::raw('journal_entries.amount * IF(journal_entries.type = "debit", 1, -1) AS signed_amount')
  53. )
  54. ->whereBetween('transactions.posted_at', [$startDate, $endDate])
  55. ->join('transactions', 'transactions.id', '=', 'journal_entries.transaction_id')
  56. ->orderBy('transactions.posted_at')
  57. ->with('transaction:id,type,description,posted_at');
  58. };
  59. }
  60. public function getAccountBalances(string $startDate, string $endDate, array $accountIds = []): Builder
  61. {
  62. $query = Account::query()
  63. ->select([
  64. 'accounts.id',
  65. 'accounts.name',
  66. 'accounts.category',
  67. 'accounts.subtype_id',
  68. 'accounts.currency_code',
  69. 'accounts.code',
  70. ])
  71. ->addSelect([
  72. DB::raw("
  73. COALESCE(
  74. IF(accounts.category IN ('asset', 'expense'),
  75. SUM(IF(journal_entries.type = 'debit' AND transactions.posted_at < ?, journal_entries.amount, 0)) -
  76. SUM(IF(journal_entries.type = 'credit' AND transactions.posted_at < ?, journal_entries.amount, 0)),
  77. SUM(IF(journal_entries.type = 'credit' AND transactions.posted_at < ?, journal_entries.amount, 0)) -
  78. SUM(IF(journal_entries.type = 'debit' AND transactions.posted_at < ?, journal_entries.amount, 0))
  79. ), 0
  80. ) AS starting_balance
  81. "),
  82. DB::raw("
  83. COALESCE(SUM(
  84. IF(journal_entries.type = 'debit' AND transactions.posted_at BETWEEN ? AND ?, journal_entries.amount, 0)
  85. ), 0) AS total_debit
  86. "),
  87. DB::raw("
  88. COALESCE(SUM(
  89. IF(journal_entries.type = 'credit' AND transactions.posted_at BETWEEN ? AND ?, journal_entries.amount, 0)
  90. ), 0) AS total_credit
  91. "),
  92. ])
  93. ->join('journal_entries', 'journal_entries.account_id', '=', 'accounts.id')
  94. ->join('transactions', function (JoinClause $join) use ($endDate) {
  95. $join->on('transactions.id', '=', 'journal_entries.transaction_id')
  96. ->where('transactions.posted_at', '<=', $endDate);
  97. })
  98. ->groupBy('accounts.id')
  99. ->with(['subtype:id,name']);
  100. if (! empty($accountIds)) {
  101. $query->whereIn('accounts.id', $accountIds);
  102. }
  103. $query->addBinding([$startDate, $startDate, $startDate, $startDate, $startDate, $endDate, $startDate, $endDate], 'select');
  104. return $query;
  105. }
  106. public function getTotalBalanceForAllBankAccounts(string $startDate, string $endDate): Money
  107. {
  108. $accountIds = Account::whereHas('bankAccount')
  109. ->pluck('id')
  110. ->toArray();
  111. if (empty($accountIds)) {
  112. return new Money(0, CurrencyAccessor::getDefaultCurrency());
  113. }
  114. $result = DB::table('journal_entries')
  115. ->join('transactions', function (JoinClause $join) use ($endDate) {
  116. $join->on('transactions.id', '=', 'journal_entries.transaction_id')
  117. ->where('transactions.posted_at', '<=', $endDate);
  118. })
  119. ->whereIn('journal_entries.account_id', $accountIds)
  120. ->selectRaw('
  121. SUM(CASE
  122. WHEN transactions.posted_at < ? AND journal_entries.type = "debit" THEN journal_entries.amount
  123. WHEN transactions.posted_at < ? AND journal_entries.type = "credit" THEN -journal_entries.amount
  124. ELSE 0
  125. END) AS totalStartingBalance,
  126. SUM(CASE
  127. WHEN transactions.posted_at BETWEEN ? AND ? AND journal_entries.type = "debit" THEN journal_entries.amount
  128. WHEN transactions.posted_at BETWEEN ? AND ? AND journal_entries.type = "credit" THEN -journal_entries.amount
  129. ELSE 0
  130. END) AS totalNetMovement
  131. ', [
  132. $startDate,
  133. $startDate,
  134. $startDate,
  135. $endDate,
  136. $startDate,
  137. $endDate,
  138. ])
  139. ->first();
  140. $totalBalance = $result->totalStartingBalance + $result->totalNetMovement;
  141. return new Money($totalBalance, CurrencyAccessor::getDefaultCurrency());
  142. }
  143. public function getEndingBalance(Account $account, string $startDate, string $endDate): ?Money
  144. {
  145. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  146. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  147. $netMovement = $calculatedBalances['net_movement'];
  148. if (in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  149. return new Money($netMovement, $account->currency_code);
  150. }
  151. $endingBalance = $startingBalances['starting_balance'] + $netMovement;
  152. return new Money($endingBalance, $account->currency_code);
  153. }
  154. public function getRetainedEarnings(string $startDate): Money
  155. {
  156. $revenue = JournalEntry::whereHas('account', static function ($query) {
  157. $query->where('category', AccountCategory::Revenue);
  158. })
  159. ->where('type', 'credit')
  160. ->whereHas('transaction', static function ($query) use ($startDate) {
  161. $query->where('posted_at', '<', $startDate);
  162. })
  163. ->sum('amount');
  164. $expense = JournalEntry::whereHas('account', static function ($query) {
  165. $query->where('category', AccountCategory::Expense);
  166. })
  167. ->where('type', 'debit')
  168. ->whereHas('transaction', static function ($query) use ($startDate) {
  169. $query->where('posted_at', '<', $startDate);
  170. })
  171. ->sum('amount');
  172. $retainedEarnings = $revenue - $expense;
  173. return new Money($retainedEarnings, CurrencyAccessor::getDefaultCurrency());
  174. }
  175. private function calculateNetMovementByCategory(AccountCategory $category, int $debitBalance, int $creditBalance): int
  176. {
  177. return match ($category) {
  178. AccountCategory::Asset, AccountCategory::Expense => $debitBalance - $creditBalance,
  179. AccountCategory::Liability, AccountCategory::Equity, AccountCategory::Revenue => $creditBalance - $debitBalance,
  180. };
  181. }
  182. private function calculateBalances(Account $account, string $startDate, string $endDate): array
  183. {
  184. $debitBalance = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  185. $creditBalance = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  186. return [
  187. 'debit_balance' => $debitBalance,
  188. 'credit_balance' => $creditBalance,
  189. 'net_movement' => $this->calculateNetMovementByCategory($account->category, $debitBalance, $creditBalance),
  190. ];
  191. }
  192. private function calculateStartingBalances(Account $account, string $startDate): array
  193. {
  194. $debitBalanceBefore = $this->journalEntryRepository->sumDebitAmounts($account, $startDate);
  195. $creditBalanceBefore = $this->journalEntryRepository->sumCreditAmounts($account, $startDate);
  196. return [
  197. 'debit_balance_before' => $debitBalanceBefore,
  198. 'credit_balance_before' => $creditBalanceBefore,
  199. 'starting_balance' => $this->calculateNetMovementByCategory($account->category, $debitBalanceBefore, $creditBalanceBefore),
  200. ];
  201. }
  202. public function getBalances(Account $account, string $startDate, string $endDate, array $fields): array
  203. {
  204. $balances = [];
  205. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  206. // Calculate starting balances only if needed
  207. $startingBalances = null;
  208. $needStartingBalances = ! in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)
  209. && (in_array('starting_balance', $fields) || in_array('ending_balance', $fields));
  210. if ($needStartingBalances) {
  211. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  212. }
  213. foreach ($fields as $field) {
  214. $balances[$field] = match ($field) {
  215. 'debit_balance', 'credit_balance', 'net_movement' => $calculatedBalances[$field],
  216. 'starting_balance' => $needStartingBalances ? $startingBalances['starting_balance'] : null,
  217. 'ending_balance' => $needStartingBalances ? $startingBalances['starting_balance'] + $calculatedBalances['net_movement'] : null,
  218. default => null,
  219. };
  220. }
  221. return array_filter($balances, static fn ($value) => $value !== null);
  222. }
  223. public function getEarliestTransactionDate(): string
  224. {
  225. $earliestDate = Transaction::oldest('posted_at')
  226. ->value('posted_at');
  227. return $earliestDate ?? now()->format('Y-m-d');
  228. }
  229. }