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

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