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.

SyncTransactionsFromPlaid.php 5.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. <?php
  2. namespace App\Listeners;
  3. use App\Enums\Accounting\AccountType;
  4. use App\Events\PlaidSuccess;
  5. use App\Models\Accounting\Account;
  6. use App\Models\Company;
  7. use App\Models\Setting\Category;
  8. use App\Services\PlaidService;
  9. use Illuminate\Support\Carbon;
  10. use Illuminate\Support\Str;
  11. class SyncTransactionsFromPlaid
  12. {
  13. protected PlaidService $plaid;
  14. /**
  15. * Create the event listener.
  16. */
  17. public function __construct(PlaidService $plaid)
  18. {
  19. $this->plaid = $plaid;
  20. }
  21. /**
  22. * Handle the event.
  23. */
  24. public function handle(PlaidSuccess $event): void
  25. {
  26. $accessToken = $event->accessToken;
  27. $company = $event->company;
  28. $syncResponse = $this->plaid->syncTransactions($accessToken);
  29. foreach ($syncResponse->added as $transaction) {
  30. $this->storeTransaction($company, $transaction);
  31. }
  32. }
  33. public function storeTransaction(Company $company, $transaction): void
  34. {
  35. $account = $company->accounts()->where('external_account_id', $transaction->account_id)->first();
  36. if ($account === null) {
  37. return;
  38. }
  39. $transactionType = $transaction->amount < 0 ? 'income' : 'expense';
  40. $method = $transactionType === 'income' ? 'deposit' : 'withdrawal';
  41. $paymentChannel = $transaction->payment_channel ?? 'other';
  42. $category = $this->getCategoryFromTransaction($company, $transaction, $transactionType);
  43. $chart = $category->account ?? $this->getChartFromTransaction($company, $transaction, $transactionType);
  44. // Use datetime and if null, then use date and convert to datetime
  45. $postedAt = $transaction->datetime ?? Carbon::parse($transaction->date)->toDateTimeString();
  46. $description = $transaction->original_description ?? $transaction->name;
  47. $cleanDescription = preg_replace('/\\*\\/\\/$/', '', $description);
  48. $cleanDescription = trim(preg_replace('/\\s+/', ' ', $cleanDescription));
  49. $account->transactions()->create([
  50. 'company_id' => $company->id,
  51. 'account_id' => $account->id,
  52. 'category_id' => $category->id,
  53. 'chart_id' => $chart->id,
  54. 'amount' => abs($transaction->amount),
  55. 'type' => $transactionType,
  56. 'method' => $method,
  57. 'payment_channel' => $paymentChannel,
  58. 'posted_at' => $postedAt,
  59. 'description' => $cleanDescription,
  60. 'pending' => $transaction->pending,
  61. 'reviewed' => false,
  62. ]);
  63. }
  64. public function getCategoryFromTransaction(Company $company, $transaction, string $transactionType): Category
  65. {
  66. $acceptableConfidenceLevels = ['VERY_HIGH', 'HIGH'];
  67. $userCategories = $company->categories()->get();
  68. $plaidDetail = $transaction->personal_finance_category->detailed ?? null;
  69. $plaidPrimary = $transaction->personal_finance_category->primary ?? null;
  70. $category = null;
  71. if ($plaidDetail !== null && in_array($transaction->personal_finance_category->confidence_level, $acceptableConfidenceLevels, true)) {
  72. $category = $this->matchCategory($userCategories, $plaidDetail, $transactionType);
  73. }
  74. if ($plaidPrimary !== null && ($category === null || $this->isUncategorized($category))) {
  75. $category = $this->matchCategory($userCategories, $plaidPrimary, $transactionType);
  76. }
  77. return $category ?? $this->getUncategorizedCategory($company, $transaction, $transactionType);
  78. }
  79. public function isUncategorized(Category $category): bool
  80. {
  81. return Str::contains(strtolower($category->name), 'other');
  82. }
  83. public function matchCategory($userCategories, $plaidCategory, string $transactionType): ?Category
  84. {
  85. $plaidWords = explode(' ', strtolower($plaidCategory));
  86. $bestMatchCategory = null;
  87. $bestMatchScore = 0; // Higher is better
  88. foreach ($userCategories as $category) {
  89. if (strtolower($category->type->value) !== strtolower($transactionType)) {
  90. continue;
  91. }
  92. $categoryWords = explode(' ', strtolower($category->name));
  93. $matchScore = count(array_intersect($plaidWords, $categoryWords));
  94. if ($matchScore > $bestMatchScore) {
  95. $bestMatchScore = $matchScore;
  96. $bestMatchCategory = $category;
  97. }
  98. }
  99. return $bestMatchCategory;
  100. }
  101. public function getUncategorizedCategory(Company $company, $transaction, string $transactionType): Category
  102. {
  103. $uncategorizedCategoryName = 'Other ' . ucfirst($transactionType);
  104. $uncategorizedCategory = $company->categories()->where('type', $transactionType)->where('name', $uncategorizedCategoryName)->first();
  105. if ($uncategorizedCategory === null) {
  106. $uncategorizedCategory = $company->categories()->where('type', $transactionType)->where('name', 'Other')->first();
  107. if ($uncategorizedCategory === null) {
  108. $uncategorizedCategory = $company->categories()->where('name', 'Other')->first();
  109. }
  110. }
  111. return $uncategorizedCategory;
  112. }
  113. public function getChartFromTransaction(Company $company, $transaction, string $transactionType): Account
  114. {
  115. if ($transactionType === 'income') {
  116. $chart = $company->accounts()->where('type', AccountType::OperatingRevenue)->where('name', 'Uncategorized Income')->first();
  117. } else {
  118. $chart = $company->accounts()->where('type', AccountType::OperatingExpense)->where('name', 'Uncategorized Expense')->first();
  119. }
  120. return $chart;
  121. }
  122. }