您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

TransactionService.php 6.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. <?php
  2. namespace App\Services;
  3. use App\Enums\Accounting\AccountCategory;
  4. use App\Enums\Accounting\AccountType;
  5. use App\Enums\Accounting\TransactionType;
  6. use App\Models\Accounting\Account;
  7. use App\Models\Accounting\Transaction;
  8. use App\Models\Banking\BankAccount;
  9. use App\Models\Company;
  10. use App\Scopes\CurrentCompanyScope;
  11. use Illuminate\Support\Carbon;
  12. class TransactionService
  13. {
  14. public function createStartingBalanceIfNeeded(Company $company, Account $account, BankAccount $bankAccount, array $transactions, float $currentBalance, string $startDate): void
  15. {
  16. if ($account->transactions()->withoutGlobalScope(CurrentCompanyScope::class)->doesntExist()) {
  17. $accountSign = $account->category === AccountCategory::Asset ? 1 : -1;
  18. $sumOfTransactions = collect($transactions)->reduce(static function ($carry, $transaction) {
  19. return bcadd($carry, (string) -$transaction->amount, 2);
  20. }, '0.00');
  21. $adjustedBalance = (string) ($currentBalance * $accountSign);
  22. $startingBalance = bcsub($adjustedBalance, $sumOfTransactions, 2);
  23. $this->createStartingBalanceTransaction($company, $account, $bankAccount, (float) $startingBalance, $startDate);
  24. }
  25. }
  26. public function storeTransactions(Company $company, BankAccount $bankAccount, array $transactions): void
  27. {
  28. foreach ($transactions as $transaction) {
  29. $this->storeTransaction($company, $bankAccount, $transaction);
  30. }
  31. }
  32. public function createStartingBalanceTransaction(Company $company, Account $account, BankAccount $bankAccount, float $startingBalance, string $startDate): void
  33. {
  34. $transactionType = $startingBalance >= 0 ? TransactionType::Deposit : TransactionType::Withdrawal;
  35. $chartAccount = $account->where('category', AccountCategory::Equity)->where('name', 'Owner\'s Equity')->first();
  36. $postedAt = Carbon::parse($startDate)->subDay()->toDateTimeString();
  37. Transaction::create([
  38. 'company_id' => $company->id,
  39. 'account_id' => $chartAccount->id,
  40. 'bank_account_id' => $bankAccount->id,
  41. 'type' => $transactionType,
  42. 'amount' => abs($startingBalance),
  43. 'payment_channel' => 'other',
  44. 'posted_at' => $postedAt,
  45. 'description' => 'Starting Balance',
  46. 'pending' => false,
  47. 'reviewed' => false,
  48. ]);
  49. }
  50. public function storeTransaction(Company $company, BankAccount $bankAccount, object $transaction): void
  51. {
  52. $transactionType = $transaction->amount < 0 ? TransactionType::Deposit : TransactionType::Withdrawal;
  53. $paymentChannel = $transaction->payment_channel;
  54. $chartAccount = $this->getAccountFromTransaction($company, $transaction, $transactionType);
  55. $postedAt = $transaction->datetime ?? Carbon::parse($transaction->date)->toDateTimeString();
  56. $description = $transaction->name;
  57. Transaction::create([
  58. 'company_id' => $company->id,
  59. 'account_id' => $chartAccount->id,
  60. 'bank_account_id' => $bankAccount->id,
  61. 'type' => $transactionType,
  62. 'amount' => abs($transaction->amount),
  63. 'payment_channel' => $paymentChannel,
  64. 'posted_at' => $postedAt,
  65. 'description' => $description,
  66. 'pending' => false,
  67. 'reviewed' => false,
  68. ]);
  69. }
  70. public function getAccountFromTransaction(Company $company, object $transaction, TransactionType $transactionType): Account
  71. {
  72. $accountCategory = match ($transactionType) {
  73. TransactionType::Deposit => AccountCategory::Revenue,
  74. TransactionType::Withdrawal => AccountCategory::Expense,
  75. default => null,
  76. };
  77. $accounts = $company->accounts()
  78. ->where('category', $accountCategory)
  79. ->whereNotIn('type', [AccountType::UncategorizedRevenue, AccountType::UncategorizedExpense])
  80. ->get();
  81. $bestMatchName = $this->findBestAccountMatch($transaction, $accounts->pluck('name')->toArray());
  82. if ($bestMatchName === null) {
  83. return $this->getUncategorizedAccount($company, $transactionType);
  84. }
  85. return $accounts->firstWhere('name', $bestMatchName) ?: $this->getUncategorizedAccount($company, $transactionType);
  86. }
  87. private function findBestAccountMatch(object $transaction, array $accountNames): ?string
  88. {
  89. $acceptableConfidenceLevels = ['VERY_HIGH', 'HIGH'];
  90. $similarityThreshold = 70.0;
  91. $plaidDetail = $transaction->personal_finance_category->detailed ?? null;
  92. $plaidPrimary = $transaction->personal_finance_category->primary ?? null;
  93. $bestMatchName = null;
  94. $bestMatchPercent = 0.0;
  95. foreach ([$plaidDetail, $plaidPrimary] as $plaidCategory) {
  96. if ($plaidCategory !== null && in_array($transaction->personal_finance_category->confidence_level, $acceptableConfidenceLevels, true)) {
  97. foreach ($accountNames as $accountName) {
  98. $normalizedPlaidCategory = strtolower(str_replace('_', ' ', $plaidCategory));
  99. $normalizedAccountName = strtolower(str_replace('_', ' ', $accountName));
  100. $currentMatchPercent = 0.0;
  101. similar_text($normalizedPlaidCategory, $normalizedAccountName, $currentMatchPercent);
  102. if ($currentMatchPercent >= $similarityThreshold && $currentMatchPercent > $bestMatchPercent) {
  103. $bestMatchPercent = $currentMatchPercent;
  104. $bestMatchName = $accountName; // Use and return the original account name for the best match, not the normalized one
  105. }
  106. }
  107. }
  108. }
  109. return $bestMatchName;
  110. }
  111. public function getUncategorizedAccount(Company $company, TransactionType $transactionType): Account
  112. {
  113. [$type, $name] = match ($transactionType) {
  114. TransactionType::Deposit => [AccountType::UncategorizedRevenue, 'Uncategorized Income'],
  115. TransactionType::Withdrawal => [AccountType::UncategorizedExpense, 'Uncategorized Expense'],
  116. default => [null, null],
  117. };
  118. return $company->accounts()
  119. ->where('type', $type)
  120. ->where('name', $name)
  121. ->firstOrFail();
  122. }
  123. }