Files
sure/app/models/plaid_account/investments/transactions_processor.rb
soky srm 4fb0a3856e Providers factory (#250)
* Implement providers factory

* Multiple providers sync support

- Proper Multi-Provider Syncing: When you click sync on an account with multiple providers (e.g., both Plaid and SimpleFin), all provider items are synced
- Better API: The existing account.providers method already returns all providers, and account.provider returns the first one for backward compatibility
- Correct Holdings Deletion Logic: Holdings can only be deleted if ALL providers allow it, preventing accidental deletions that would be recreated on next sync
TODO: validate this is the way we want to go? We would need to check holdings belong to which account, and then check provider allows deletion. More complex
- Database Constraints: The existing validations ensure an account can have at most one provider of each type (one PlaidAccount, one SimplefinAccount, etc.)

* Add generic provider_import_adapter

* Finish unified import strategy

* Update app/models/plaid_account.rb

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: soky srm <sokysrm@gmail.com>

* Update app/models/provider/factory.rb

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Signed-off-by: soky srm <sokysrm@gmail.com>

* Fix account linked by plaid_id instead of external_id

* Parse numerics to BigDecimal

Parse numerics to BigDecimal before computing amount; guard nils.

Avoid String * String and float drift; also normalize date.

* Fix incorrect usage of assert_raises.

* Fix linter

* Fix processor test.

* Update current_balance_manager.rb

* Test fixes

* Fix plaid linked account test

* Add support for holding per account_provider

* Fix proper account access

Also fix account deletion for simpefin too

* FIX match tests for consistency

* Some more factory updates

* Fix account schema for multipe providers

  Can do:
  - Account #1 → PlaidAccount + SimplefinAccount (multiple different providers)
  - Account #2 → PlaidAccount only
  - Account #3 → SimplefinAccount only

  Cannot do:
  - Account #1 → PlaidAccount + PlaidAccount (duplicate provider type)
  - PlaidAccount #123 → Account #1 + Account #2 (provider linked to multiple accounts)

* Fix account setup

- An account CAN have multiple providers (the schema shows account_providers with unique index on [account_id, provider_type])
  - Each provider should maintain its own separate entries
  - We should NOT update one provider's entry when another provider syncs

* Fix linter and guard migration

* FIX linter issues.

* Fixes

- Remove duplicated index
- Pass account_provider_id
- Guard holdings call to avoid NoMethodError

* Update schema and provider import fix

* Plaid doesn't allow holdings deletion

* Use ClimateControl for proper env setup

* No need for this in .git

---------

Signed-off-by: soky srm <sokysrm@gmail.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Co-authored-by: Juan José Mata <juanjo.mata@gmail.com>
2025-10-28 19:32:27 +01:00

96 lines
3.0 KiB
Ruby

class PlaidAccount::Investments::TransactionsProcessor
SecurityNotFoundError = Class.new(StandardError)
def initialize(plaid_account, security_resolver:)
@plaid_account = plaid_account
@security_resolver = security_resolver
end
def process
transactions.each do |transaction|
if cash_transaction?(transaction)
find_or_create_cash_entry(transaction)
else
find_or_create_trade_entry(transaction)
end
end
end
private
attr_reader :plaid_account, :security_resolver
def import_adapter
@import_adapter ||= Account::ProviderImportAdapter.new(account)
end
def account
plaid_account.current_account
end
def cash_transaction?(transaction)
transaction["type"] == "cash" || transaction["type"] == "fee" || transaction["type"] == "transfer"
end
def find_or_create_trade_entry(transaction)
resolved_security_result = security_resolver.resolve(plaid_security_id: transaction["security_id"])
unless resolved_security_result.security.present?
Sentry.capture_exception(SecurityNotFoundError.new("Could not find security for plaid trade")) do |scope|
scope.set_tags(plaid_account_id: plaid_account.id)
end
return # We can't process a non-cash transaction without a security
end
external_id = transaction["investment_transaction_id"]
return if external_id.blank?
import_adapter.import_trade(
external_id: external_id,
security: resolved_security_result.security,
quantity: derived_qty(transaction),
price: transaction["price"],
amount: derived_qty(transaction) * transaction["price"],
currency: transaction["iso_currency_code"],
date: transaction["date"],
name: transaction["name"],
source: "plaid"
)
end
def find_or_create_cash_entry(transaction)
external_id = transaction["investment_transaction_id"]
return if external_id.blank?
import_adapter.import_transaction(
external_id: external_id,
amount: transaction["amount"],
currency: transaction["iso_currency_code"],
date: transaction["date"],
name: transaction["name"],
source: "plaid"
)
end
def transactions
plaid_account.raw_investments_payload["transactions"] || []
end
# Plaid unfortunately returns incorrect signage on some `quantity` values. They claim all "sell" transactions
# are negative signage, but we have found multiple instances of production data where this is not the case.
#
# This method attempts to use several Plaid data points to derive the true quantity with the correct signage.
def derived_qty(transaction)
reported_qty = transaction["quantity"]
abs_qty = reported_qty.abs
if transaction["type"] == "sell" || transaction["amount"] < 0
-abs_qty
elsif transaction["type"] == "buy" || transaction["amount"] > 0
abs_qty
else
reported_qty
end
end
end