You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

AccountService.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. $accountIds = array_map('intval', $accountIds);
  63. $query = Account::query()
  64. ->select([
  65. 'accounts.id',
  66. 'accounts.name',
  67. 'accounts.category',
  68. 'accounts.subtype_id',
  69. 'accounts.currency_code',
  70. 'accounts.code',
  71. ])
  72. ->addSelect([
  73. DB::raw("
  74. COALESCE(
  75. IF(accounts.category IN ('asset', 'expense'),
  76. SUM(IF(journal_entries.type = 'debit' 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 = 'credit' AND transactions.posted_at < ?, journal_entries.amount, 0)) -
  79. SUM(IF(journal_entries.type = 'debit' AND transactions.posted_at < ?, journal_entries.amount, 0))
  80. ), 0
  81. ) AS starting_balance
  82. "),
  83. DB::raw("
  84. COALESCE(SUM(
  85. IF(journal_entries.type = 'debit' AND transactions.posted_at BETWEEN ? AND ?, journal_entries.amount, 0)
  86. ), 0) AS total_debit
  87. "),
  88. DB::raw("
  89. COALESCE(SUM(
  90. IF(journal_entries.type = 'credit' AND transactions.posted_at BETWEEN ? AND ?, journal_entries.amount, 0)
  91. ), 0) AS total_credit
  92. "),
  93. ])
  94. ->join('journal_entries', 'journal_entries.account_id', '=', 'accounts.id')
  95. ->join('transactions', function (JoinClause $join) use ($endDate) {
  96. $join->on('transactions.id', '=', 'journal_entries.transaction_id')
  97. ->where('transactions.posted_at', '<=', $endDate);
  98. })
  99. ->groupBy('accounts.id')
  100. ->with(['subtype:id,name']);
  101. if (! empty($accountIds)) {
  102. $query->whereIn('accounts.id', $accountIds);
  103. }
  104. $query->addBinding([$startDate, $startDate, $startDate, $startDate, $startDate, $endDate, $startDate, $endDate], 'select');
  105. return $query;
  106. }
  107. public function getTotalBalanceForAllBankAccounts(string $startDate, string $endDate): Money
  108. {
  109. $accountIds = Account::whereHas('bankAccount')
  110. ->pluck('id')
  111. ->toArray();
  112. if (empty($accountIds)) {
  113. return new Money(0, CurrencyAccessor::getDefaultCurrency());
  114. }
  115. $result = DB::table('journal_entries')
  116. ->join('transactions', function (JoinClause $join) use ($endDate) {
  117. $join->on('transactions.id', '=', 'journal_entries.transaction_id')
  118. ->where('transactions.posted_at', '<=', $endDate);
  119. })
  120. ->whereIn('journal_entries.account_id', $accountIds)
  121. ->selectRaw('
  122. SUM(CASE
  123. WHEN transactions.posted_at < ? AND journal_entries.type = "debit" THEN journal_entries.amount
  124. WHEN transactions.posted_at < ? AND journal_entries.type = "credit" THEN -journal_entries.amount
  125. ELSE 0
  126. END) AS totalStartingBalance,
  127. SUM(CASE
  128. WHEN transactions.posted_at BETWEEN ? AND ? AND journal_entries.type = "debit" THEN journal_entries.amount
  129. WHEN transactions.posted_at BETWEEN ? AND ? AND journal_entries.type = "credit" THEN -journal_entries.amount
  130. ELSE 0
  131. END) AS totalNetMovement
  132. ', [
  133. $startDate,
  134. $startDate,
  135. $startDate,
  136. $endDate,
  137. $startDate,
  138. $endDate,
  139. ])
  140. ->first();
  141. $totalBalance = $result->totalStartingBalance + $result->totalNetMovement;
  142. return new Money($totalBalance, CurrencyAccessor::getDefaultCurrency());
  143. }
  144. public function getEndingBalance(Account $account, string $startDate, string $endDate): ?Money
  145. {
  146. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  147. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  148. $netMovement = $calculatedBalances['net_movement'];
  149. if (in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  150. return new Money($netMovement, $account->currency_code);
  151. }
  152. $endingBalance = $startingBalances['starting_balance'] + $netMovement;
  153. return new Money($endingBalance, $account->currency_code);
  154. }
  155. public function getRetainedEarnings(string $startDate): Money
  156. {
  157. $revenue = JournalEntry::whereHas('account', static function ($query) {
  158. $query->where('category', AccountCategory::Revenue);
  159. })
  160. ->where('type', 'credit')
  161. ->whereHas('transaction', static function ($query) use ($startDate) {
  162. $query->where('posted_at', '<', $startDate);
  163. })
  164. ->sum('amount');
  165. $expense = JournalEntry::whereHas('account', static function ($query) {
  166. $query->where('category', AccountCategory::Expense);
  167. })
  168. ->where('type', 'debit')
  169. ->whereHas('transaction', static function ($query) use ($startDate) {
  170. $query->where('posted_at', '<', $startDate);
  171. })
  172. ->sum('amount');
  173. $retainedEarnings = $revenue - $expense;
  174. return new Money($retainedEarnings, CurrencyAccessor::getDefaultCurrency());
  175. }
  176. private function calculateNetMovementByCategory(AccountCategory $category, int $debitBalance, int $creditBalance): int
  177. {
  178. return match ($category) {
  179. AccountCategory::Asset, AccountCategory::Expense => $debitBalance - $creditBalance,
  180. AccountCategory::Liability, AccountCategory::Equity, AccountCategory::Revenue => $creditBalance - $debitBalance,
  181. };
  182. }
  183. private function calculateBalances(Account $account, string $startDate, string $endDate): array
  184. {
  185. $debitBalance = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  186. $creditBalance = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  187. return [
  188. 'debit_balance' => $debitBalance,
  189. 'credit_balance' => $creditBalance,
  190. 'net_movement' => $this->calculateNetMovementByCategory($account->category, $debitBalance, $creditBalance),
  191. ];
  192. }
  193. private function calculateStartingBalances(Account $account, string $startDate): array
  194. {
  195. $debitBalanceBefore = $this->journalEntryRepository->sumDebitAmounts($account, $startDate);
  196. $creditBalanceBefore = $this->journalEntryRepository->sumCreditAmounts($account, $startDate);
  197. return [
  198. 'debit_balance_before' => $debitBalanceBefore,
  199. 'credit_balance_before' => $creditBalanceBefore,
  200. 'starting_balance' => $this->calculateNetMovementByCategory($account->category, $debitBalanceBefore, $creditBalanceBefore),
  201. ];
  202. }
  203. public function getBalances(Account $account, string $startDate, string $endDate, array $fields): array
  204. {
  205. $balances = [];
  206. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  207. // Calculate starting balances only if needed
  208. $startingBalances = null;
  209. $needStartingBalances = ! in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)
  210. && (in_array('starting_balance', $fields) || in_array('ending_balance', $fields));
  211. if ($needStartingBalances) {
  212. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  213. }
  214. foreach ($fields as $field) {
  215. $balances[$field] = match ($field) {
  216. 'debit_balance', 'credit_balance', 'net_movement' => $calculatedBalances[$field],
  217. 'starting_balance' => $needStartingBalances ? $startingBalances['starting_balance'] : null,
  218. 'ending_balance' => $needStartingBalances ? $startingBalances['starting_balance'] + $calculatedBalances['net_movement'] : null,
  219. default => null,
  220. };
  221. }
  222. return array_filter($balances, static fn ($value) => $value !== null);
  223. }
  224. public function getEarliestTransactionDate(): string
  225. {
  226. $earliestDate = Transaction::oldest('posted_at')
  227. ->value('posted_at');
  228. return $earliestDate ?? now()->format('Y-m-d');
  229. }
  230. }