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 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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\Query\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 getStartingBalanceSubquery($startDate, $accountIds = null): Builder
  44. {
  45. return DB::table('journal_entries')
  46. ->select('journal_entries.account_id')
  47. ->selectRaw('
  48. COALESCE(SUM(
  49. CASE
  50. WHEN accounts.category IN ("asset", "expense") THEN
  51. CASE WHEN journal_entries.type = "debit" THEN journal_entries.amount ELSE -journal_entries.amount END
  52. ELSE
  53. CASE WHEN journal_entries.type = "credit" THEN journal_entries.amount ELSE -journal_entries.amount END
  54. END
  55. ), 0) AS starting_balance
  56. ')
  57. ->join('transactions', 'transactions.id', '=', 'journal_entries.transaction_id')
  58. ->join('accounts', 'accounts.id', '=', 'journal_entries.account_id')
  59. ->where('transactions.posted_at', '<', $startDate)
  60. ->groupBy('journal_entries.account_id');
  61. }
  62. public function getTotalDebitSubquery($startDate, $endDate, $accountIds = null): Builder
  63. {
  64. return DB::table('journal_entries')
  65. ->select('journal_entries.account_id')
  66. ->selectRaw('
  67. COALESCE(SUM(CASE WHEN journal_entries.type = "debit" THEN journal_entries.amount ELSE 0 END), 0) as total_debit
  68. ')
  69. ->join('transactions', 'transactions.id', '=', 'journal_entries.transaction_id')
  70. ->whereBetween('transactions.posted_at', [$startDate, $endDate])
  71. ->groupBy('journal_entries.account_id');
  72. }
  73. public function getTotalCreditSubquery($startDate, $endDate, $accountIds = null): Builder
  74. {
  75. return DB::table('journal_entries')
  76. ->select('journal_entries.account_id')
  77. ->selectRaw('
  78. COALESCE(SUM(CASE WHEN journal_entries.type = "credit" THEN journal_entries.amount ELSE 0 END), 0) as total_credit
  79. ')
  80. ->join('transactions', 'transactions.id', '=', 'journal_entries.transaction_id')
  81. ->whereBetween('transactions.posted_at', [$startDate, $endDate])
  82. ->groupBy('journal_entries.account_id');
  83. }
  84. public function getTransactionDetailsSubquery($startDate, $endDate): Closure
  85. {
  86. return function ($query) use ($startDate, $endDate) {
  87. $query->select(
  88. 'journal_entries.id',
  89. 'journal_entries.account_id',
  90. 'journal_entries.transaction_id',
  91. 'journal_entries.type',
  92. 'journal_entries.amount',
  93. DB::raw('journal_entries.amount * IF(journal_entries.type = "debit", 1, -1) AS signed_amount')
  94. )
  95. ->whereBetween('transactions.posted_at', [$startDate, $endDate])
  96. ->join('transactions', 'transactions.id', '=', 'journal_entries.transaction_id')
  97. ->orderBy('transactions.posted_at')
  98. ->with('transaction:id,type,description,posted_at');
  99. };
  100. }
  101. public function getAccountBalances(string $startDate, string $endDate, array $accountIds = []): \Illuminate\Database\Eloquent\Builder
  102. {
  103. $query = Account::query()
  104. ->select([
  105. 'accounts.id',
  106. 'accounts.name',
  107. 'accounts.category',
  108. 'accounts.subtype_id',
  109. 'accounts.currency_code',
  110. 'accounts.code',
  111. ])
  112. ->leftJoinSub($this->getStartingBalanceSubquery($startDate), 'starting_balance', function (JoinClause $join) {
  113. $join->on('accounts.id', '=', 'starting_balance.account_id');
  114. })
  115. ->leftJoinSub($this->getTotalDebitSubquery($startDate, $endDate), 'total_debit', function (JoinClause $join) {
  116. $join->on('accounts.id', '=', 'total_debit.account_id');
  117. })
  118. ->leftJoinSub($this->getTotalCreditSubquery($startDate, $endDate), 'total_credit', function (JoinClause $join) {
  119. $join->on('accounts.id', '=', 'total_credit.account_id');
  120. })
  121. ->addSelect([
  122. DB::raw('COALESCE(starting_balance.starting_balance, 0) as starting_balance'),
  123. DB::raw('COALESCE(total_debit.total_debit, 0) as total_debit'),
  124. DB::raw('COALESCE(total_credit.total_credit, 0) as total_credit'),
  125. ])
  126. ->with(['subtype:id,name'])
  127. ->whereHas('journalEntries.transaction', function ($query) use ($startDate, $endDate) {
  128. $query->whereBetween('posted_at', [$startDate, $endDate]);
  129. });
  130. if (! empty($accountIds)) {
  131. $query->whereIn('accounts.id', $accountIds);
  132. }
  133. return $query;
  134. }
  135. public function getEndingBalance(Account $account, string $startDate, string $endDate): ?Money
  136. {
  137. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  138. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  139. $netMovement = $calculatedBalances['net_movement'];
  140. if (in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)) {
  141. return new Money($netMovement, $account->currency_code);
  142. }
  143. $endingBalance = $startingBalances['starting_balance'] + $netMovement;
  144. return new Money($endingBalance, $account->currency_code);
  145. }
  146. public function getRetainedEarnings(string $startDate): Money
  147. {
  148. $revenue = JournalEntry::whereHas('account', static function ($query) {
  149. $query->where('category', AccountCategory::Revenue);
  150. })
  151. ->where('type', 'credit')
  152. ->whereHas('transaction', static function ($query) use ($startDate) {
  153. $query->where('posted_at', '<=', $startDate);
  154. })
  155. ->sum('amount');
  156. $expense = JournalEntry::whereHas('account', static function ($query) {
  157. $query->where('category', AccountCategory::Expense);
  158. })
  159. ->where('type', 'debit')
  160. ->whereHas('transaction', static function ($query) use ($startDate) {
  161. $query->where('posted_at', '<=', $startDate);
  162. })
  163. ->sum('amount');
  164. $retainedEarnings = $revenue - $expense;
  165. return new Money($retainedEarnings, CurrencyAccessor::getDefaultCurrency());
  166. }
  167. private function calculateNetMovementByCategory(AccountCategory $category, int $debitBalance, int $creditBalance): int
  168. {
  169. return match ($category) {
  170. AccountCategory::Asset, AccountCategory::Expense => $debitBalance - $creditBalance,
  171. AccountCategory::Liability, AccountCategory::Equity, AccountCategory::Revenue => $creditBalance - $debitBalance,
  172. };
  173. }
  174. private function calculateBalances(Account $account, string $startDate, string $endDate): array
  175. {
  176. $debitBalance = $this->journalEntryRepository->sumDebitAmounts($account, $startDate, $endDate);
  177. $creditBalance = $this->journalEntryRepository->sumCreditAmounts($account, $startDate, $endDate);
  178. return [
  179. 'debit_balance' => $debitBalance,
  180. 'credit_balance' => $creditBalance,
  181. 'net_movement' => $this->calculateNetMovementByCategory($account->category, $debitBalance, $creditBalance),
  182. ];
  183. }
  184. private function calculateStartingBalances(Account $account, string $startDate): array
  185. {
  186. $debitBalanceBefore = $this->journalEntryRepository->sumDebitAmounts($account, $startDate);
  187. $creditBalanceBefore = $this->journalEntryRepository->sumCreditAmounts($account, $startDate);
  188. return [
  189. 'debit_balance_before' => $debitBalanceBefore,
  190. 'credit_balance_before' => $creditBalanceBefore,
  191. 'starting_balance' => $this->calculateNetMovementByCategory($account->category, $debitBalanceBefore, $creditBalanceBefore),
  192. ];
  193. }
  194. public function getBalances(Account $account, string $startDate, string $endDate, array $fields): array
  195. {
  196. $balances = [];
  197. $calculatedBalances = $this->calculateBalances($account, $startDate, $endDate);
  198. // Calculate starting balances only if needed
  199. $startingBalances = null;
  200. $needStartingBalances = ! in_array($account->category, [AccountCategory::Expense, AccountCategory::Revenue], true)
  201. && (in_array('starting_balance', $fields) || in_array('ending_balance', $fields));
  202. if ($needStartingBalances) {
  203. $startingBalances = $this->calculateStartingBalances($account, $startDate);
  204. }
  205. foreach ($fields as $field) {
  206. $balances[$field] = match ($field) {
  207. 'debit_balance', 'credit_balance', 'net_movement' => $calculatedBalances[$field],
  208. 'starting_balance' => $needStartingBalances ? $startingBalances['starting_balance'] : null,
  209. 'ending_balance' => $needStartingBalances ? $startingBalances['starting_balance'] + $calculatedBalances['net_movement'] : null,
  210. default => null,
  211. };
  212. }
  213. return array_filter($balances, static fn ($value) => $value !== null);
  214. }
  215. public function getTotalBalanceForAllBankAccounts(string $startDate, string $endDate): Money
  216. {
  217. $accountIds = Account::whereHas('bankAccount')
  218. ->pluck('id')
  219. ->toArray();
  220. if (empty($accountIds)) {
  221. return new Money(0, CurrencyAccessor::getDefaultCurrency());
  222. }
  223. $result = DB::table('journal_entries')
  224. ->join('transactions', 'journal_entries.transaction_id', '=', 'transactions.id')
  225. ->whereIn('journal_entries.account_id', $accountIds)
  226. ->where('transactions.posted_at', '<=', $endDate)
  227. ->selectRaw('
  228. SUM(CASE
  229. WHEN transactions.posted_at <= ? AND journal_entries.type = "debit" THEN journal_entries.amount
  230. WHEN transactions.posted_at <= ? AND journal_entries.type = "credit" THEN -journal_entries.amount
  231. ELSE 0
  232. END) AS totalStartingBalance,
  233. SUM(CASE
  234. WHEN transactions.posted_at BETWEEN ? AND ? AND journal_entries.type = "debit" THEN journal_entries.amount
  235. WHEN transactions.posted_at BETWEEN ? AND ? AND journal_entries.type = "credit" THEN -journal_entries.amount
  236. ELSE 0
  237. END) AS totalNetMovement
  238. ', [
  239. $startDate,
  240. $startDate,
  241. $startDate,
  242. $endDate,
  243. $startDate,
  244. $endDate,
  245. ])
  246. ->first();
  247. $totalBalance = $result->totalStartingBalance + $result->totalNetMovement;
  248. return new Money($totalBalance, CurrencyAccessor::getDefaultCurrency());
  249. }
  250. public function getAccountCategoryOrder(): array
  251. {
  252. return [
  253. AccountCategory::Asset->getPluralLabel(),
  254. AccountCategory::Liability->getPluralLabel(),
  255. AccountCategory::Equity->getPluralLabel(),
  256. AccountCategory::Revenue->getPluralLabel(),
  257. AccountCategory::Expense->getPluralLabel(),
  258. ];
  259. }
  260. public function getEarliestTransactionDate(): string
  261. {
  262. $earliestDate = Transaction::oldest('posted_at')
  263. ->value('posted_at');
  264. return $earliestDate ?? now()->format('Y-m-d');
  265. }
  266. }