Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

TransactionService.php 12KB

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