Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

TransactionService.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\Accounting\AccountCategory;
  4. use App\Enums\Accounting\AccountType;
  5. use App\Enums\Accounting\JournalEntryType;
  6. use App\Enums\Accounting\TransactionType;
  7. use App\Models\Accounting\Account;
  8. use App\Models\Accounting\JournalEntry;
  9. use App\Models\Accounting\Transaction;
  10. use App\Models\Banking\BankAccount;
  11. use App\Models\Company;
  12. use App\Utilities\Currency\CurrencyAccessor;
  13. use App\Utilities\Currency\CurrencyConverter;
  14. use Illuminate\Support\Carbon;
  15. use Illuminate\Support\Facades\DB;
  16. class TransactionService
  17. {
  18. public function createStartingBalanceIfNeeded(Company $company, Account $account, BankAccount $bankAccount, array $transactions, float $currentBalance, string $startDate): void
  19. {
  20. if ($account->transactions()->doesntExist()) {
  21. $accountSign = $account->category === AccountCategory::Asset ? 1 : -1;
  22. $sumOfTransactions = collect($transactions)->reduce(static function ($carry, $transaction) {
  23. return bcadd($carry, (string) -$transaction->amount, 2);
  24. }, '0.00');
  25. $adjustedBalance = (string) ($currentBalance * $accountSign);
  26. $startingBalance = bcsub($adjustedBalance, $sumOfTransactions, 2);
  27. $this->createStartingBalanceTransaction($company, $account, $bankAccount, (float) $startingBalance, $startDate);
  28. }
  29. }
  30. public function storeTransactions(Company $company, BankAccount $bankAccount, array $transactions): void
  31. {
  32. foreach ($transactions as $transaction) {
  33. $this->storeTransaction($company, $bankAccount, $transaction);
  34. }
  35. }
  36. public function createStartingBalanceTransaction(Company $company, Account $account, BankAccount $bankAccount, float $startingBalance, string $startDate): void
  37. {
  38. $transactionType = $startingBalance >= 0 ? TransactionType::Deposit : TransactionType::Withdrawal;
  39. $chartAccount = $account->where('category', AccountCategory::Equity)->where('name', 'Owner\'s Equity')->first();
  40. $postedAt = Carbon::parse($startDate)->subDay()->toDateTimeString();
  41. Transaction::create([
  42. 'company_id' => $company->id,
  43. 'account_id' => $chartAccount->id,
  44. 'bank_account_id' => $bankAccount->id,
  45. 'type' => $transactionType,
  46. 'amount' => abs($startingBalance),
  47. 'payment_channel' => 'other',
  48. 'posted_at' => $postedAt,
  49. 'description' => 'Starting Balance',
  50. 'pending' => false,
  51. 'reviewed' => false,
  52. ]);
  53. }
  54. public function storeTransaction(Company $company, BankAccount $bankAccount, object $transaction): void
  55. {
  56. $transactionType = $transaction->amount < 0 ? TransactionType::Deposit : TransactionType::Withdrawal;
  57. $paymentChannel = $transaction->payment_channel;
  58. $chartAccount = $this->getAccountFromTransaction($company, $transaction, $transactionType);
  59. $postedAt = $transaction->datetime ?? Carbon::parse($transaction->date)->toDateTimeString();
  60. $description = $transaction->name;
  61. Transaction::create([
  62. 'company_id' => $company->id,
  63. 'account_id' => $chartAccount->id,
  64. 'bank_account_id' => $bankAccount->id,
  65. 'plaid_transaction_id' => $transaction->transaction_id,
  66. 'type' => $transactionType,
  67. 'amount' => abs($transaction->amount),
  68. 'payment_channel' => $paymentChannel,
  69. 'posted_at' => $postedAt,
  70. 'description' => $description,
  71. 'pending' => false,
  72. 'reviewed' => false,
  73. ]);
  74. }
  75. public function getAccountFromTransaction(Company $company, object $transaction, TransactionType $transactionType): Account
  76. {
  77. $accountCategory = match ($transactionType) {
  78. TransactionType::Deposit => AccountCategory::Revenue,
  79. TransactionType::Withdrawal => AccountCategory::Expense,
  80. default => null,
  81. };
  82. $accounts = $company->accounts()
  83. ->where('category', $accountCategory)
  84. ->whereNotIn('type', [AccountType::UncategorizedRevenue, AccountType::UncategorizedExpense])
  85. ->get();
  86. $bestMatchName = $this->findBestAccountMatch($transaction, $accounts->pluck('name')->toArray());
  87. if ($bestMatchName === null) {
  88. return $this->getUncategorizedAccount($company, $transactionType);
  89. }
  90. return $accounts->firstWhere('name', $bestMatchName) ?: $this->getUncategorizedAccount($company, $transactionType);
  91. }
  92. private function findBestAccountMatch(object $transaction, array $accountNames): ?string
  93. {
  94. $acceptableConfidenceLevels = ['VERY_HIGH', 'HIGH'];
  95. $similarityThreshold = 70.0;
  96. $plaidDetail = $transaction->personal_finance_category->detailed ?? null;
  97. $plaidPrimary = $transaction->personal_finance_category->primary ?? null;
  98. $bestMatchName = null;
  99. $bestMatchPercent = 0.0;
  100. foreach ([$plaidDetail, $plaidPrimary] as $plaidCategory) {
  101. if ($plaidCategory !== null && in_array($transaction->personal_finance_category->confidence_level, $acceptableConfidenceLevels, true)) {
  102. foreach ($accountNames as $accountName) {
  103. $normalizedPlaidCategory = strtolower(str_replace('_', ' ', $plaidCategory));
  104. $normalizedAccountName = strtolower(str_replace('_', ' ', $accountName));
  105. $currentMatchPercent = 0.0;
  106. similar_text($normalizedPlaidCategory, $normalizedAccountName, $currentMatchPercent);
  107. if ($currentMatchPercent >= $similarityThreshold && $currentMatchPercent > $bestMatchPercent) {
  108. $bestMatchPercent = $currentMatchPercent;
  109. $bestMatchName = $accountName; // Use and return the original account name for the best match, not the normalized one
  110. }
  111. }
  112. }
  113. }
  114. return $bestMatchName;
  115. }
  116. public function getUncategorizedAccount(Company $company, TransactionType $transactionType): Account
  117. {
  118. [$type, $name] = match ($transactionType) {
  119. TransactionType::Deposit => [AccountType::UncategorizedRevenue, 'Uncategorized Income'],
  120. TransactionType::Withdrawal => [AccountType::UncategorizedExpense, 'Uncategorized Expense'],
  121. default => [null, null],
  122. };
  123. return $company->accounts()
  124. ->where('type', $type)
  125. ->where('name', $name)
  126. ->firstOrFail();
  127. }
  128. public function createJournalEntries(Transaction $transaction): void
  129. {
  130. // Additional check to avoid duplication during replication
  131. if ($transaction->journalEntries()->exists() || $transaction->type->isJournal() || str_starts_with($transaction->description, '(Copy of)')) {
  132. return;
  133. }
  134. [$debitAccount, $creditAccount] = $this->determineAccounts($transaction);
  135. if ($debitAccount === null || $creditAccount === null) {
  136. return;
  137. }
  138. $this->createJournalEntriesForTransaction($transaction, $debitAccount, $creditAccount);
  139. }
  140. public function updateJournalEntries(Transaction $transaction): void
  141. {
  142. if ($transaction->type->isJournal() || $this->hasRelevantChanges($transaction) === false) {
  143. return;
  144. }
  145. $journalEntries = $transaction->journalEntries;
  146. $debitEntry = $journalEntries->where('type', JournalEntryType::Debit)->first();
  147. $creditEntry = $journalEntries->where('type', JournalEntryType::Credit)->first();
  148. if ($debitEntry === null || $creditEntry === null) {
  149. return;
  150. }
  151. [$debitAccount, $creditAccount] = $this->determineAccounts($transaction);
  152. if ($debitAccount === null || $creditAccount === null) {
  153. return;
  154. }
  155. $convertedTransactionAmount = $this->getConvertedTransactionAmount($transaction);
  156. DB::transaction(function () use ($debitEntry, $debitAccount, $convertedTransactionAmount, $creditEntry, $creditAccount) {
  157. $this->updateJournalEntryForTransaction($debitEntry, $debitAccount, $convertedTransactionAmount);
  158. $this->updateJournalEntryForTransaction($creditEntry, $creditAccount, $convertedTransactionAmount);
  159. });
  160. }
  161. public function deleteJournalEntries(Transaction $transaction): void
  162. {
  163. DB::transaction(static function () use ($transaction) {
  164. $transaction->journalEntries()->each(fn (JournalEntry $entry) => $entry->delete());
  165. });
  166. }
  167. private function determineAccounts(Transaction $transaction): array
  168. {
  169. $chartAccount = $transaction->account;
  170. $bankAccount = $transaction->bankAccount?->account;
  171. if ($transaction->type->isTransfer()) {
  172. // Essentially a withdrawal from the bank account and a deposit to the chart account (which is a bank account)
  173. // Credit: bankAccount (source of funds, money is being withdrawn)
  174. // Debit: chartAccount (destination of funds, money is being deposited)
  175. return [$chartAccount, $bankAccount];
  176. }
  177. $debitAccount = $transaction->type->isWithdrawal() ? $chartAccount : $bankAccount;
  178. $creditAccount = $transaction->type->isWithdrawal() ? $bankAccount : $chartAccount;
  179. return [$debitAccount, $creditAccount];
  180. }
  181. private function createJournalEntriesForTransaction(Transaction $transaction, Account $debitAccount, Account $creditAccount): void
  182. {
  183. $convertedTransactionAmount = $this->getConvertedTransactionAmount($transaction);
  184. DB::transaction(function () use ($debitAccount, $transaction, $convertedTransactionAmount, $creditAccount) {
  185. $debitAccount->journalEntries()->create([
  186. 'company_id' => $transaction->company_id,
  187. 'transaction_id' => $transaction->id,
  188. 'type' => JournalEntryType::Debit,
  189. 'amount' => $convertedTransactionAmount,
  190. 'description' => $transaction->description,
  191. ]);
  192. $creditAccount->journalEntries()->create([
  193. 'company_id' => $transaction->company_id,
  194. 'transaction_id' => $transaction->id,
  195. 'type' => JournalEntryType::Credit,
  196. 'amount' => $convertedTransactionAmount,
  197. 'description' => $transaction->description,
  198. ]);
  199. });
  200. }
  201. private function getConvertedTransactionAmount(Transaction $transaction): string
  202. {
  203. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  204. $bankAccountCurrency = $transaction->bankAccount->account->currency_code;
  205. $chartAccountCurrency = $transaction->account->currency_code;
  206. if ($bankAccountCurrency !== $defaultCurrency) {
  207. return $this->convertToDefaultCurrency($transaction->amount, $bankAccountCurrency, $defaultCurrency);
  208. } elseif ($chartAccountCurrency !== $defaultCurrency) {
  209. return $this->convertToDefaultCurrency($transaction->amount, $chartAccountCurrency, $defaultCurrency);
  210. }
  211. return $transaction->amount;
  212. }
  213. private function convertToDefaultCurrency(string $amount, string $fromCurrency, string $toCurrency): string
  214. {
  215. $amountInCents = CurrencyConverter::prepareForAccessor($amount, $fromCurrency);
  216. $convertedAmountInCents = CurrencyConverter::convertBalance($amountInCents, $fromCurrency, $toCurrency);
  217. return CurrencyConverter::prepareForMutator($convertedAmountInCents, $toCurrency);
  218. }
  219. private function hasRelevantChanges(Transaction $transaction): bool
  220. {
  221. return $transaction->wasChanged(['amount', 'account_id', 'bank_account_id', 'type']);
  222. }
  223. private function updateJournalEntryForTransaction(JournalEntry $journalEntry, Account $account, string $convertedTransactionAmount): void
  224. {
  225. DB::transaction(static function () use ($journalEntry, $account, $convertedTransactionAmount) {
  226. $journalEntry->update([
  227. 'account_id' => $account->id,
  228. 'amount' => $convertedTransactionAmount,
  229. ]);
  230. });
  231. }
  232. }