Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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