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

AccountService.php 12KB

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