Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

AccountService.php 10KB

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