Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Write every Plaid holding of a sync on its snapshot date (#4317)

jaysbeekay5e6cfd62d9c5
diff --git a/app/models/account/provider_import_adapter.rb b/app/models/account/provider_import_adapter.rb
index 7b742c8b3a..9d4a02c938 100644
--- a/app/models/account/provider_import_adapter.rb
+++ b/app/models/account/provider_import_adapter.rb
@@ -585,12 +585,11 @@ class Account::ProviderImportAdapter
external_id: external_id
}
+ corrections = corrections_from(carried, provider_security_id: security.id)
+ attributes.merge!(corrections)
+
# Only update security if not locked by user
- if carried&.security_locked?
- attributes[:security] = carried.security
- attributes[:provider_security_id] = carried.provider_security_id || security.id
- attributes[:security_locked] = true
- elsif holding.new_record? || holding.security_replaceable_by_provider?
+ if !corrections.key?(:security) && (holding.new_record? || holding.security_replaceable_by_provider?)
attributes[:security] = security
# Track the provider's original security so reset_security_to_provider! works
# Only set if not already set (preserves original if user remapped then unlocked)
@@ -598,11 +597,7 @@ class Account::ProviderImportAdapter
end
# Only update cost_basis if reconciliation says to
- if carried&.cost_basis_locked?
- attributes[:cost_basis] = carried.cost_basis
- attributes[:cost_basis_source] = carried.cost_basis_source
- attributes[:cost_basis_locked] = true
- elsif reconciled[:should_update]
+ if !corrections.key?(:cost_basis) && reconciled[:should_update]
attributes[:cost_basis] = reconciled[:cost_basis]
attributes[:cost_basis_source] = reconciled[:cost_basis_source]
end
@@ -1145,7 +1140,88 @@ class Account::ProviderImportAdapter
}
end
+ # Moves the user's corrections on a provider row that is about to be removed
+ # onto the row import_holding carries corrections from: the latest one of
+ # the same provider security on or before `date`. Returns that row, or nil
+ # when there is none or nothing to move.
+ def carry_corrections_back(from:, date:)
+ corrections = corrections_from(from, provider_security_id: from.provider_security_id || from.security_id)
+ return if corrections.empty?
+
+ target = previous_holding_for(security: from.provider_security || from.security, currency: from.currency,
+ date: date + 1, account_provider_id: from.account_provider_id)
+ return if target.nil?
+
+ # A remap onto a security the target's date already holds would break the
+ # unique (account, security, date, currency) index. The target folds into
+ # that row instead, as Holding#remap_security! merges a collision. Another
+ # provider's row is that provider's position and is never folded into: the
+ # target keeps its own security and the remap is dropped, which is logged.
+ collision = corrections.key?(:security) &&
+ account.holdings.where.not(id: target.id)
+ .find_by(security: corrections[:security], date: target.date, currency: target.currency)
+ return target.tap { |row| row.update!(corrections) } unless collision
+
+ if collision.account_provider_id.present? && collision.account_provider_id != target.account_provider_id
+ Rails.logger.warn(
+ "ProviderImportAdapter: cross-provider remap collision for account=#{account.id} security=#{corrections[:security].id} date=#{target.date} currency=#{target.currency}; keeping existing id=#{collision.id}"
+ )
+ return target.tap { |row| row.update!(corrections.except(:security, :provider_security_id, :security_locked)) }
+ end
+
+ target.assign_attributes(corrections.except(:security, :provider_security_id, :security_locked))
+ merge_holding_into!(target, collision)
+ end
+
private
+ # Folds `holding` into `existing`, a row of another security on the same
+ # date and currency, with the arithmetic of Holding#remap_security!'s
+ # collision merge: quantities and amounts add, cost basis is the weighted
+ # average when both have one, and the provider tracking moves across.
+ # Returns `existing`.
+ def merge_holding_into!(holding, existing)
+ merged_qty = existing.qty + holding.qty
+ merged_amount = existing.amount + holding.amount
+ merged_cost_basis = if existing.cost_basis.present? && holding.cost_basis.present? && merged_qty.positive?
+ ((existing.cost_basis * existing.qty) + (holding.cost_basis * holding.qty)) / merged_qty
+ else
+ existing.cost_basis
+ end
+
+ merge_attrs = {
+ qty: merged_qty,
+ amount: merged_amount,
+ price: merged_qty.positive? ? merged_amount / merged_qty : 0,
+ cost_basis: merged_cost_basis,
+ security_locked: true
+ }
+ merge_attrs[:external_id] = holding.external_id if existing.external_id.blank? && holding.external_id.present?
+ merge_attrs[:provider_security_id] = holding.provider_security_id || holding.security_id if existing.provider_security_id.blank?
+ merge_attrs[:account_provider_id] = holding.account_provider_id if existing.account_provider_id.blank? && holding.account_provider_id.present?
+
+ Holding.transaction(requires_new: true) do
+ holding.destroy!
+ existing.update!(merge_attrs)
+ end
+ existing
+ end
+
+ # The user's corrections a row holds: a remapped security and a locked
+ # cost basis, as attributes for the row that takes them over.
+ def corrections_from(holding, provider_security_id:)
+ corrections = {}
+ if holding&.security_locked?
+ corrections[:security] = holding.security
+ corrections[:provider_security_id] = holding.provider_security_id || provider_security_id
+ corrections[:security_locked] = true
+ end
+ if holding&.cost_basis_locked?
+ corrections[:cost_basis] = holding.cost_basis
+ corrections[:cost_basis_source] = holding.cost_basis_source
+ corrections[:cost_basis_locked] = true
+ end
+ corrections
+ end
# The latest earlier holding of the security the provider reports. A
# remapped row records that security in provider_security_id; an
diff --git a/app/models/plaid_account.rb b/app/models/plaid_account.rb
index 9ed9a48315..e13f6985e9 100644
--- a/app/models/plaid_account.rb
+++ b/app/models/plaid_account.rb
@@ -68,7 +68,42 @@ class PlaidAccount < ApplicationRecord
save!
end
+ # The one date every holding of a holdings sync is written on, and the date
+ # the balance anchor for that sync goes on.
+ #
+ # Plaid dates each holding by its own institution price date, so a fund
+ # priced at the previous close sits a day or more behind the rest. The
+ # quantities all describe the same moment, though, and "current holdings"
+ # are read as the provider rows on one date, so a lagging row would drop out.
+ # The snapshot is dated by the newest price date it carries. A date ahead of
+ # today is discounted on its own, so one bad feed does not pull the snapshot
+ # off the date the rest agree on; a snapshot with no usable date is today's.
+ def holdings_snapshot_date
+ holdings = raw_holdings_payload&.dig("holdings") || []
+ dates = holdings.filter_map { |holding| parse_holding_date(holding["institution_price_as_of"]) }
+ dates.reject { |date| date > Date.current }.max || Date.current
+ end
+
+ # Price dates in the holdings payload that are present but cannot be read,
+ # which holdings_snapshot_date leaves out.
+ def unparseable_holding_price_dates
+ holdings = raw_holdings_payload&.dig("holdings") || []
+ holdings.filter_map do |holding|
+ value = holding["institution_price_as_of"]
+ value if value.present? && parse_holding_date(value).nil?
+ end
+ end
+
private
+ def parse_holding_date(value)
+ return nil if value.blank?
+ return value.to_date if value.respond_to?(:to_date) && !value.is_a?(String)
+
+ Date.parse(value.to_s)
+ rescue ArgumentError, TypeError
+ nil
+ end
+
# Plaid guarantees at least one of these. This validation is a sanity check for that guarantee.
def has_balance
return if current_balance.present? || available_balance.present?
diff --git a/app/models/plaid_account/investments/holdings_processor.rb b/app/models/plaid_account/investments/holdings_processor.rb
index 29ad89510b..49a3176330 100644
--- a/app/models/plaid_account/investments/holdings_processor.rb
+++ b/app/models/plaid_account/investments/holdings_processor.rb
@@ -6,6 +6,12 @@ class PlaidAccount::Investments::HoldingsProcessor
end
def process
+ # Every holding of one sync goes on one date, the snapshot's, whatever its
+ # own price date: the quantities are all as of this sync, and the readers
+ # of current holdings take the provider rows on a single date.
+ snapshot_date = plaid_account.holdings_snapshot_date
+ capture_unparseable_price_dates(snapshot_date)
+
holdings.each do |plaid_holding|
resolved_security_result = security_resolver.resolve(plaid_security_id: plaid_holding["security_id"])
@@ -23,26 +29,65 @@ class PlaidAccount::Investments::HoldingsProcessor
# Compute amount using BigDecimal arithmetic to avoid floating point drift
amount_bd = quantity_bd * price_bd
- # Normalize date - handle string, Date, or nil
- holding_date = parse_date(plaid_holding["institution_price_as_of"]) || Date.current
-
import_adapter.import_holding(
security: security,
quantity: quantity_bd,
amount: amount_bd,
currency: plaid_holding["iso_currency_code"] || @currency || account.currency,
- date: holding_date,
+ date: snapshot_date,
price: price_bd,
account_provider_id: plaid_account.account_provider&.id,
source: "plaid",
delete_future_holdings: false # Plaid doesn't allow holdings deletion
)
end
+
+ retire_rows_after(snapshot_date)
end
private
attr_reader :plaid_account, :security_resolver
+ # A snapshot can be dated before the last one (that sync had no usable
+ # price date and landed on today). Plaid's own rows after it would stay the
+ # newest provider date and hide this snapshot, so they go once it is
+ # written. A correction the user made on one moves to the snapshot row
+ # first, oldest row first so the latest wins. Other providers' rows, and
+ # rows with no provider, are kept.
+ def retire_rows_after(snapshot_date)
+ account_provider_id = plaid_account.account_provider&.id
+ return if account_provider_id.nil?
+
+ # Read through the provider link, so a sync with no holdings to write
+ # leaves plaid_account.current_account unloaded, as it was, for the
+ # balance anchor the processor sets after this runs.
+ later = Holding.where(account_provider_id: account_provider_id).where("date > ?", snapshot_date)
+ later.where("security_locked OR cost_basis_locked").order(:date, :id).each do |holding|
+ import_adapter.carry_corrections_back(from: holding, date: snapshot_date)
+ end
+ later.delete_all
+ end
+
+ # A price date that cannot be read is left out of the snapshot date, and
+ # with nothing else usable the sync lands on today. Recorded once per sync,
+ # where support can see why.
+ def capture_unparseable_price_dates(snapshot_date)
+ unparseable = plaid_account.unparseable_holding_price_dates
+ return if unparseable.empty?
+
+ DebugLogEntry.capture(
+ category: "provider_sync",
+ level: "warn",
+ message: "Plaid holdings carried unparseable price dates; they were left out of the snapshot date",
+ source: self.class.name,
+ provider_key: "plaid",
+ family: account&.family,
+ account: account,
+ account_provider: plaid_account.account_provider,
+ metadata: { unparseable_dates: unparseable.first(5).map(&:to_s), count: unparseable.size, snapshot_date: snapshot_date.iso8601 }
+ )
+ end
+
def import_adapter
@import_adapter ||= Account::ProviderImportAdapter.new(account)
end
@@ -72,22 +117,4 @@ class PlaidAccount::Investments::HoldingsProcessor
Rails.logger.error("Failed to parse Plaid holding decimal value: #{value.inspect} - #{e.message}")
nil
end
-
- def parse_date(date_value)
- return nil if date_value.nil?
-
- case date_value
- when Date
- date_value
- when String
- Date.parse(date_value)
- when Time, DateTime
- date_value.to_date
- else
- nil
- end
- rescue ArgumentError, TypeError => e
- Rails.logger.error("Failed to parse Plaid holding date: #{date_value.inspect} - #{e.message}")
- nil
- end
end
diff --git a/app/models/plaid_account/processor.rb b/app/models/plaid_account/processor.rb
index 37bd4cf3ce..0d34ecd211 100644
--- a/app/models/plaid_account/processor.rb
+++ b/app/models/plaid_account/processor.rb
@@ -190,28 +190,12 @@ class PlaidAccount::Processor
# alongside is as of that same date. Anchoring that total on today would
# set it against holdings later repriced for today, and the difference
# would read as cash on every day in between -- the shift #3815 removed
- # from IBKR. The anchor goes on the newest date the holdings carry; a
- # snapshot with no dated holdings is today's.
+ # from IBKR. The anchor goes on the holdings snapshot's date, the date the
+ # holdings processor writes every holding of this sync on.
def balance_date
return Date.current unless plaid_account.plaid_type == "investment"
- # A holding dated ahead of today is discounted on its own, so one bad
- # feed does not pull the anchor off the date the rest agree on.
- dated = holdings.filter_map { |holding| parse_date(holding["institution_price_as_of"]) }
- dated.reject { |date| date > Date.current }.max || Date.current
- end
-
- def holdings
- plaid_account.raw_holdings_payload&.dig("holdings") || []
- end
-
- def parse_date(value)
- return nil if value.blank?
- return value.to_date if value.respond_to?(:to_date) && !value.is_a?(String)
-
- Date.parse(value.to_s)
- rescue ArgumentError, TypeError
- nil
+ plaid_account.holdings_snapshot_date
end
def balance_calculator
diff --git a/db/migrate/20261118090002_remove_plaid_holdings_ahead_of_their_snapshot.rb b/db/migrate/20261118090002_remove_plaid_holdings_ahead_of_their_snapshot.rb
new file mode 100644
index 0000000000..6b0cbe1203
--- /dev/null
+++ b/db/migrate/20261118090002_remove_plaid_holdings_ahead_of_their_snapshot.rb
@@ -0,0 +1,114 @@
+# The Plaid holdings processor used to date each row by its own
+# `institution_price_as_of`, or today when that was missing or unreadable. It
+# now writes every holding of a sync on one snapshot date: the newest price
+# date in the payload that is not after today, else today
+# (`PlaidAccount#holdings_snapshot_date`).
+#
+# A row the old processor left later than that date (a holding priced ahead of
+# today, or an undated one written on the day of a sync that came after the
+# newest price date) stays the account's newest provider date. Every reader of
+# current holdings takes the provider rows on that one date, so it would show
+# only the stale row, at its old quantity, and hide the whole new snapshot
+# until the price dates caught up -- for good, for a row priced far ahead.
+# The processor now retires its own rows after the snapshot as it syncs, but
+# only on an account's next sync; this clears every account at once.
+#
+# Removed: rows owned by a Plaid account provider and dated after the snapshot
+# date of that Plaid account's stored payload. That is the set the processor
+# retires at each sync and the readers would otherwise pick. Rows of
+# other providers, and rows with no provider (calculated or manual), are left
+# alone. Running it again removes nothing more.
+#
+# Balances and holdings history were computed with the removed rows, so each
+# Plaid item that lost rows is synced again to rebuild them.
+class RemovePlaidHoldingsAheadOfTheirSnapshot < ActiveRecord::Migration[8.1]
+ # Each account's DELETE commits on its own, so row locks are not held for
+ # the whole scan, and the syncs scheduled at the end read committed rows.
+ # Safe to interrupt: a rerun picks up where it stopped.
+ disable_ddl_transaction!
+
+ # The processor's rule, copied rather than called, so the migration keeps
+ # meaning what it meant when it was written.
+ def self.snapshot_date(payload, today: Date.current)
+ holdings = payload.is_a?(Hash) ? Array(payload["holdings"]) : []
+ dates = holdings.filter_map do |holding|
+ value = holding.is_a?(Hash) ? holding["institution_price_as_of"] : nil
+ next if value.blank?
+
+ Date.parse(value.to_s)
+ rescue ArgumentError, TypeError
+ nil
+ end
+
+ dates.reject { |date| date > today }.max || today
+ end
+
+ BATCH_SIZE = 100
+
+ # The payload is read through a model, not raw SQL: where Active Record
+ # encryption is configured, PlaidAccount encrypts raw_holdings_payload, and a
+ # raw read would see ciphertext and no price dates. This declares it under
+ # the same condition PlaidAccount does (Encryptable#encryption_ready?), and
+ # is built when the migration runs so it takes the configuration of then.
+ def self.plaid_account_payloads
+ Class.new(ActiveRecord::Base) do
+ self.table_name = "plaid_accounts"
+ def self.name = "RemovePlaidHoldingsAheadOfTheirSnapshot::PlaidAccountPayload"
+ encrypts :raw_holdings_payload if ActiveRecordEncryptionConfig.ready?
+ end
+ end
+
+ def up
+ schedule_syncs(remove_stale_rows(batch_size: BATCH_SIZE))
+ end
+
+ # In batches, so neither every Plaid payload nor every provider id is held at
+ # once; one DELETE per account provider. Returns the ids of the Plaid items
+ # that lost rows.
+ def remove_stale_rows(batch_size:)
+ item_ids = []
+
+ self.class.plaid_account_payloads
+ .joins("JOIN account_providers ON account_providers.provider_id = plaid_accounts.id")
+ .where(account_providers: { provider_type: "PlaidAccount" })
+ .select("plaid_accounts.id", "plaid_accounts.plaid_item_id", "plaid_accounts.raw_holdings_payload",
+ "account_providers.id AS account_provider_id")
+ .find_each(batch_size: batch_size) do |plaid_account|
+ cutoff = self.class.snapshot_date(plaid_account.raw_holdings_payload)
+ carry_corrections_back(plaid_account.account_provider_id, cutoff)
+
+ removed = connection.delete(ActiveRecord::Base.sanitize_sql_array([
+ "DELETE FROM holdings WHERE account_provider_id = ? AND date > ?", plaid_account.account_provider_id, cutoff
+ ]))
+ item_ids << plaid_account.plaid_item_id if removed.positive?
+ end
+
+ item_ids.uniq
+ end
+
+ # The removed rows were stale copies of positions the next Plaid sync writes
+ # again on its snapshot date. Putting them back would hide that snapshot
+ # again, and their old quantities are not kept anywhere to restore.
+ def down
+ raise ActiveRecord::IrreversibleMigration
+ end
+
+ private
+ # A correction the user made on a row about to go moves to the row the
+ # next sync carries corrections from, through the same adapter method the
+ # processor uses, so it is not lost with the row.
+ def carry_corrections_back(account_provider_id, cutoff)
+ Holding.where(account_provider_id: account_provider_id).where("date > ?", cutoff)
+ .where("security_locked OR cost_basis_locked").order(:date, :id).each do |holding|
+ Account::ProviderImportAdapter.new(holding.account).carry_corrections_back(from: holding, date: cutoff)
+ end
+ end
+
+ def schedule_syncs(item_ids)
+ PlaidItem.syncable.where(id: item_ids).find_each do |item|
+ item.sync_later
+ rescue => e
+ say "Could not schedule a sync for Plaid item #{item.id} (#{e.message}); it refreshes on its next sync"
+ end
+ end
+end
diff --git a/test/migrations/remove_plaid_holdings_ahead_of_their_snapshot_migration_test.rb b/test/migrations/remove_plaid_holdings_ahead_of_their_snapshot_migration_test.rb
new file mode 100644
index 0000000000..d1bcc4d290
--- /dev/null
+++ b/test/migrations/remove_plaid_holdings_ahead_of_their_snapshot_migration_test.rb
@@ -0,0 +1,237 @@
+# frozen_string_literal: true
+
+require "test_helper"
+require Rails.root.join("db/migrate/20261118090002_remove_plaid_holdings_ahead_of_their_snapshot")
+
+# The old Plaid holdings processor dated each row by its own price date, or
+# today when it had none. A row it left later than the snapshot the processor
+# now writes stays the account's newest provider date, so the readers of
+# current holdings see only that stale row until the price dates catch up.
+class RemovePlaidHoldingsAheadOfTheirSnapshotMigrationTest < ActiveSupport::TestCase
+ setup do
+ @plaid_account = plaid_accounts(:one)
+ @account = @plaid_account.current_account
+ @plaid_provider = AccountProvider.create!(account: @account, provider: @plaid_account)
+ @plaid_account.reload
+ @snapshot_date = Date.current - 1
+ @aapl, @msft = securities(:aapl), securities(:msft)
+ @payload = [
+ { "security_id" => "a", "quantity" => 10, "institution_price" => 50, "iso_currency_code" => "USD",
+ "institution_price_as_of" => @snapshot_date.to_s },
+ { "security_id" => "b", "quantity" => 5, "institution_price" => 50, "iso_currency_code" => "USD" }
+ ]
+ @plaid_account.update!(raw_holdings_payload: { "holdings" => @payload })
+ end
+
+ # What the old processor wrote for this payload: AAPL on its price date, the
+ # undated MSFT on the day of that sync, at the quantity it had then.
+ test "a Plaid row the old processor left after the snapshot is removed, so the next sync is current" do
+ plaid_row(@aapl, @snapshot_date, 10)
+ stale = plaid_row(@msft, Date.current, 9)
+
+ run_migration
+
+ assert_not Holding.exists?(stale.id)
+ sync_holdings
+ current = @account.current_holdings.to_h { |holding| [ holding.security_id, holding.qty.to_i ] }
+ assert_equal({ @aapl.id => 10, @msft.id => 5 }, current)
+ end
+
+ test "a Plaid row priced ahead of today is removed" do
+ future = plaid_row(@aapl, Date.current + 1, 10)
+
+ run_migration
+
+ assert_not Holding.exists?(future.id)
+ end
+
+ test "Plaid rows on or before the snapshot date are kept" do
+ on = plaid_row(@aapl, @snapshot_date, 10)
+ before = plaid_row(@msft, @snapshot_date - 3, 5)
+
+ run_migration
+
+ assert Holding.exists?(on.id)
+ assert Holding.exists?(before.id)
+ end
+
+ test "another provider's later row is kept" do
+ item = SimplefinItem.create!(family: @account.family, name: "SF", access_url: "https://example.com/access")
+ simplefin_account = SimplefinAccount.create!(simplefin_item: item, name: "Broker", account_id: "sf_1",
+ currency: "USD", account_type: "investment", current_balance: 0)
+ other = AccountProvider.create!(account: @account, provider: simplefin_account)
+ later = @account.holdings.create!(security: @msft, date: Date.current, qty: 9, price: 50, amount: 450,
+ currency: "USD", account_provider_id: other.id)
+
+ run_migration
+
+ assert Holding.exists?(later.id)
+ end
+
+ test "a row with no provider is kept" do
+ calculated = @account.holdings.create!(security: @msft, date: Date.current, qty: 9, price: 50, amount: 450, currency: "USD")
+
+ run_migration
+
+ assert Holding.exists?(calculated.id)
+ end
+
+ # No usable price date in the payload: the processor writes on today, so only
+ # rows after today are ahead of it.
+ test "with no usable price date, only Plaid rows after today are removed" do
+ @plaid_account.update!(raw_holdings_payload: { "holdings" => [ @payload.second.merge("institution_price_as_of" => "not a date") ] })
+ today = plaid_row(@msft, Date.current, 9)
+ future = plaid_row(@aapl, Date.current + 2, 10)
+
+ run_migration
+
+ assert Holding.exists?(today.id)
+ assert_not Holding.exists?(future.id)
+ end
+
+ # The migration reads the snapshot date its own way; it must agree with the
+ # processor's, or it would remove rows the processor still writes.
+ test "its snapshot date is the processor's" do
+ payloads = [
+ { "holdings" => @payload },
+ { "holdings" => [ { "institution_price_as_of" => (Date.current + 3).to_s }, { "institution_price_as_of" => (Date.current - 5).to_s } ] },
+ { "holdings" => [ { "institution_price_as_of" => "garbage" }, { "institution_price_as_of" => "" } ] },
+ { "holdings" => [] },
+ {}
+ ]
+
+ payloads.each do |payload|
+ @plaid_account.update!(raw_holdings_payload: payload)
+ assert_equal @plaid_account.holdings_snapshot_date,
+ RemovePlaidHoldingsAheadOfTheirSnapshot.snapshot_date(payload), payload.inspect
+ end
+ end
+
+ # Where Active Record encryption is configured, PlaidAccount encrypts the
+ # payload, so a raw read sees ciphertext and no price dates. The migration
+ # reads it as the model does.
+ test "an encrypted payload is read through encryption" do
+ ActiveRecordEncryptionConfig.stubs(:ready?).returns(true)
+ write_encrypted_payload("holdings" => @payload)
+ plaid_row(@aapl, @snapshot_date, 10)
+ stale = plaid_row(@msft, Date.current, 9)
+
+ run_migration
+
+ assert_not Holding.exists?(stale.id)
+ end
+
+ # The scan runs in batches; every Plaid account is still reached.
+ test "every Plaid account is scanned when the scan is batched" do
+ second = PlaidAccount.create!(plaid_item: @plaid_account.plaid_item, plaid_id: "acc_mock_2", plaid_type: "investment",
+ name: "Second Plaid", currency: "USD", current_balance: 100,
+ raw_holdings_payload: { "holdings" => @payload })
+ second_account = Account.create!(family: @account.family, name: "Second", balance: 100, currency: "USD",
+ accountable: Investment.new)
+ second_provider = AccountProvider.create!(account: second_account, provider: second)
+ stale_one = plaid_row(@msft, Date.current, 9)
+ stale_two = second_account.holdings.create!(security: @msft, date: Date.current, qty: 9, price: 50, amount: 450,
+ currency: "USD", account_provider_id: second_provider.id)
+
+ ActiveRecord::Migration.suppress_messages do
+ RemovePlaidHoldingsAheadOfTheirSnapshot.new.remove_stale_rows(batch_size: 1)
+ end
+
+ assert_not Holding.exists?(stale_one.id)
+ assert_not Holding.exists?(stale_two.id)
+ end
+
+ test "running it twice removes nothing more" do
+ plaid_row(@aapl, @snapshot_date, 10)
+ plaid_row(@msft, Date.current, 9)
+
+ run_migration
+ assert_no_difference -> { Holding.count } do
+ run_migration
+ end
+ end
+
+ # A correction on a removed row goes to the row the next sync carries
+ # corrections from: the latest one on or before the snapshot date.
+ test "a correction on a removed row survives into the next sync" do
+ plaid_row(@aapl, @snapshot_date, 10)
+ earlier = plaid_row(@msft, @snapshot_date - 3, 5)
+ stale = plaid_row(@msft, Date.current, 9)
+ stale.set_manual_cost_basis!(42)
+ assert_not earlier.reload.cost_basis_locked
+
+ run_migration
+
+ assert_not Holding.exists?(stale.id)
+ assert_equal [ 42, true ], [ earlier.reload.cost_basis.to_i, earlier.cost_basis_locked ]
+ sync_holdings
+ msft = @account.current_holdings.find_by!(security: @msft)
+ assert_equal [ @snapshot_date, 42, true ], [ msft.date, msft.cost_basis.to_i, msft.cost_basis_locked ]
+ end
+
+ # Balances and the account's history were computed with the removed rows, so
+ # an item that lost rows is synced again to rebuild them.
+ test "a sync is scheduled for an item whose rows were removed" do
+ plaid_row(@msft, Date.current, 9)
+
+ assert_difference -> { @plaid_account.plaid_item.syncs.count }, 1 do
+ run_migration
+ end
+ end
+
+ test "no sync is scheduled when nothing is removed" do
+ plaid_row(@aapl, @snapshot_date, 10)
+
+ assert_no_difference -> { Sync.count } do
+ run_migration
+ end
+ end
+
+ test "a sync that cannot be scheduled does not undo the removal" do
+ stale = plaid_row(@msft, Date.current, 9)
+ PlaidItem.any_instance.stubs(:sync_later).raises(StandardError, "queue unavailable")
+
+ run_migration
+
+ assert_not Holding.exists?(stale.id)
+ end
+
+ # Each account's DELETE commits on its own, so its row locks are released
+ # as it goes rather than held until the whole scan ends.
+ test "it runs outside a single migration transaction" do
+ assert RemovePlaidHoldingsAheadOfTheirSnapshot.disable_ddl_transaction
+ end
+
+ private
+ def plaid_row(security, date, qty)
+ @account.holdings.create!(security: security, date: date, qty: qty, price: 50, amount: qty * 50,
+ currency: "USD", account_provider_id: @plaid_provider.id)
+ end
+
+ def write_encrypted_payload(payload)
+ encrypted = Class.new(ActiveRecord::Base) do
+ self.table_name = "plaid_accounts"
+ def self.name = "EncryptedPlaidAccountForTest"
+ encrypts :raw_holdings_payload
+ end
+ encrypted.select(:id).find(@plaid_account.id).update!(raw_holdings_payload: payload)
+
+ raw = ActiveRecord::Base.connection.select_value(
+ ActiveRecord::Base.sanitize_sql_array([ "SELECT raw_holdings_payload::text FROM plaid_accounts WHERE id = ?", @plaid_account.id ])
+ )
+ assert_no_match(/institution_price_as_of/, raw, "the payload must be stored encrypted, or this proves nothing")
+ end
+
+ def sync_holdings
+ resolver = PlaidAccount::Investments::SecurityResolver.new(@plaid_account)
+ resolver.stubs(:resolve).with(plaid_security_id: "a").returns(OpenStruct.new(security: @aapl))
+ resolver.stubs(:resolve).with(plaid_security_id: "b").returns(OpenStruct.new(security: @msft))
+ PlaidAccount::Investments::HoldingsProcessor.new(@plaid_account, security_resolver: resolver).process
+ end
+
+ def run_migration
+ ActiveRecord::Migration.suppress_messages do
+ RemovePlaidHoldingsAheadOfTheirSnapshot.new.up
+ end
+ end
+end
diff --git a/test/models/plaid_account/investments/holdings_processor_test.rb b/test/models/plaid_account/investments/holdings_processor_test.rb
index d5e9d03501..e55d8d5f1b 100644
--- a/test/models/plaid_account/investments/holdings_processor_test.rb
+++ b/test/models/plaid_account/investments/holdings_processor_test.rb
@@ -43,7 +43,7 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
.with(plaid_security_id: "456")
.returns(
OpenStruct.new(
- security: securities(:aapl),
+ security: securities(:msft),
cash_equivalent?: false,
brokerage_cash?: false
)
@@ -55,19 +55,22 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
processor.process
end
- holdings = Holding.where(account: @plaid_account.current_account).order(:date)
-
- assert_equal 100, holdings.first.qty
- assert_equal 100, holdings.first.price
- assert_equal "USD", holdings.first.currency
- assert_equal securities(:aapl), holdings.first.security
- assert_equal 1.day.ago.to_date, holdings.first.date
-
- assert_equal 200, holdings.second.qty
- assert_equal 200, holdings.second.price
- assert_equal "USD", holdings.second.currency
- assert_equal securities(:aapl), holdings.second.security
- assert_equal Date.current, holdings.second.date
+ # Both rows share the snapshot's date, so they are found by security
+ # rather than by their position in a date order
+ holdings = Holding.where(account: @plaid_account.current_account)
+ dated = holdings.find_by!(security: securities(:aapl))
+ undated = holdings.find_by!(security: securities(:msft))
+
+ assert_equal 100, dated.qty
+ assert_equal 100, dated.price
+ assert_equal "USD", dated.currency
+ assert_equal 1.day.ago.to_date, dated.date
+
+ assert_equal 200, undated.qty
+ assert_equal 200, undated.price
+ assert_equal "USD", undated.currency
+ # The undated entry is written on the snapshot's date, not on today
+ assert_equal 1.day.ago.to_date, undated.date
end
test "uses the supplied snapshot currency when a holding omits its own currency" do
@@ -111,10 +114,10 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
assert_equal "EUR", holding.currency
end
- # Plaid does not delete future holdings because it doesn't support holdings deletion
- # (PlaidAdapter#can_delete_holdings? returns false). This test verifies that future
- # holdings are NOT deleted when processing Plaid holdings data.
- test "does not delete future holdings when processing Plaid holdings" do
+ # Users cannot delete Plaid holdings (PlaidAdapter#can_delete_holdings? is
+ # false), but a sync retires Plaid's own rows dated after its snapshot: they
+ # would stay the newest provider date and hide the snapshot just written.
+ test "retires Plaid's own holdings later than the snapshot" do
account = @plaid_account.current_account
# Create account_provider
@@ -126,7 +129,7 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
# Create a third security for testing
third_security = Security.create!(ticker: "GOOGL", name: "Google", exchange_operating_mic: "XNAS", country_code: "US")
- # Create a future AAPL holding that should NOT be deleted
+ # A later AAPL row from an earlier sync whose snapshot was today
future_aapl_holding = account.holdings.create!(
security: securities(:aapl),
date: Date.current,
@@ -137,7 +140,8 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
account_provider_id: account_provider.id
)
- # Plaid returns holdings from yesterday - future holdings should remain
+ # Plaid returns holdings priced one and two days ago, so the snapshot is
+ # yesterday's and today's holding is later than it
test_investments_payload = {
securities: [],
holdings: [
@@ -146,21 +150,21 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
"quantity" => 50,
"institution_price" => 50,
"iso_currency_code" => "USD",
- "institution_price_as_of" => Date.current
+ "institution_price_as_of" => 1.day.ago.to_date
},
{
"security_id" => "clean",
"quantity" => 75,
"institution_price" => 75,
"iso_currency_code" => "USD",
- "institution_price_as_of" => 1.day.ago.to_date
+ "institution_price_as_of" => 2.days.ago.to_date
},
{
"security_id" => "past",
"quantity" => 100,
"institution_price" => 100,
"iso_currency_code" => "USD",
- "institution_price_as_of" => 1.day.ago.to_date
+ "institution_price_as_of" => 2.days.ago.to_date
}
],
transactions: []
@@ -184,14 +188,12 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
processor = PlaidAccount::Investments::HoldingsProcessor.new(@plaid_account, security_resolver: @security_resolver)
processor.process
- # Should have created 3 new holdings PLUS the existing future holding (total 4)
- assert_equal 4, account.holdings.count
-
- # Future AAPL holding should still exist (NOT deleted)
- assert account.holdings.exists?(future_aapl_holding.id)
+ assert_equal 3, account.holdings.count
+ assert_not account.holdings.exists?(future_aapl_holding.id)
+ assert_equal 1.day.ago.to_date, account.latest_provider_holdings_snapshot_date
# Should have the correct holdings from Plaid
- assert account.holdings.exists?(security: securities(:msft), date: Date.current, qty: 50)
+ assert account.holdings.exists?(security: securities(:msft), date: 1.day.ago.to_date, qty: 50)
assert account.holdings.exists?(security: third_security, date: 1.day.ago.to_date, qty: 75)
assert account.holdings.exists?(security: securities(:aapl), date: 1.day.ago.to_date, qty: 100)
end
@@ -366,4 +368,348 @@ class PlaidAccount::Investments::HoldingsProcessorTest < ActiveSupport::TestCase
holding = account.holdings.find_by(security: securities(:aapl))
assert_equal "EUR", holding.currency # Should use account's currency
end
+
+ # Plaid dates each holding by its own price date. These run the processor on
+ # a payload and read the result through the readers of "current holdings",
+ # which take the provider rows on the account's single newest date.
+
+ test "holdings priced on different days all land on the snapshot date and are current" do
+ snapshot_date = Date.current - 1
+ a, b = securities(:aapl), securities(:msft)
+ link_account_provider!
+
+ process_holdings(
+ "a" => [ a, { "quantity" => 10, "institution_price_as_of" => snapshot_date.to_s } ],
+ "b" => [ b, { "quantity" => 5, "institution_price_as_of" => (snapshot_date - 3).to_s } ]
+ )
+
+ assert_equal [ a.id, b.id ].sort, account.current_holdings.pluck(:security_id).sort
+ assert_equal [ snapshot_date ], account.holdings.distinct.pluck(:date)
+
+ snapshot = Holding::PortfolioSnapshot.new(account)
+ assert_equal 5, snapshot.to_h[b.id]
+ assert_equal snapshot_date, snapshot.effective_dates[b.id]
+ end
+
+ test "a holding reported at zero with a lagging price date lands on the snapshot date and is not current" do
+ snapshot_date = Date.current - 1
+ a, b = securities(:aapl), securities(:msft)
+ link_account_provider!
+
+ process_holdings(
+ "a" => [ a, { "quantity" => 10, "institution_price_as_of" => snapshot_date.to_s } ],
+ "b" => [ b, { "quantity" => 0, "institution_price_as_of" => (snapshot_date - 3).to_s } ]
+ )
+
+ b_holding = account.holdings.find_by!(security: b)
+ assert_equal snapshot_date, b_holding.date
+ assert_equal 0, b_holding.qty
+ assert_equal [ a.id ], account.current_holdings.pluck(:security_id)
+
+ snapshot = Holding::PortfolioSnapshot.new(account)
+ assert_equal 0, snapshot.to_h.fetch(b.id)
+ assert_equal snapshot_date, snapshot.effective_dates[b.id]
+ end
+
+ test "a security sold to zero replaces its earlier quantity on the snapshot date" do
+ snapshot_date = Date.current - 1
+ a, b = securities(:aapl), securities(:msft)
+ account_provider = link_account_provider!
+ account.holdings.create!(
+ security: b, date: snapshot_date, qty: 10, price: 50, amount: 500,
+ currency: "USD", account_provider_id: account_provider.id
+ )
+ assert_includes account.current_holdings.pluck(:security_id), b.id
+
+ process_holdings(
+ "a" => [ a, { "quantity" => 10, "institution_price_as_of" => snapshot_date.to_s } ],
+ "b" => [ b, { "quantity" => 0, "institution_price_as_of" => (snapshot_date - 3).to_s } ]
+ )
+
+ assert_not_includes account.current_holdings.pluck(:security_id), b.id
+ assert_equal 0, account.holdings.find_by!(security: b, date: snapshot_date).qty
+ end
+
+ test "a holding priced ahead of today lands on the snapshot date" do
+ snapshot_date = Date.current - 1
+ a, b = securities(:aapl), securities(:msft)
+ link_account_provider!
+
+ process_holdings(
+ "a" => [ a, { "quantity" => 10, "institution_price_as_of" => snapshot_date.to_s } ],
+ "b" => [ b, { "quantity" => 5, "institution_price_as_of" => (Date.current + 1).to_s } ]
+ )
+
+ assert_equal [ a.id, b.id ].sort, account.current_holdings.pluck(:security_id).sort
+ assert_equal [ snapshot_date ], account.holdings.distinct.pluck(:date)
+ assert_equal snapshot_date, account.latest_provider_holdings_snapshot_date
+ end
+
+ test "an undated holding takes the snapshot date, not today" do
+ snapshot_date = Date.current - 1
+ a, b = securities(:aapl), securities(:msft)
+ link_account_provider!
+
+ process_holdings(
+ "a" => [ a, { "quantity" => 10, "institution_price_as_of" => snapshot_date.to_s } ],
+ "b" => [ b, { "quantity" => 5 } ]
+ )
+
+ assert_equal [ a.id, b.id ].sort, account.current_holdings.pluck(:security_id).sort
+ assert_equal [ snapshot_date ], account.holdings.distinct.pluck(:date)
+ end
+
+ test "a security from an earlier snapshot is not current and its row is kept" do
+ snapshot_date = Date.current - 1
+ a, b = securities(:aapl), securities(:msft)
+ c = Security.create!(ticker: "GOOGL", name: "Google", exchange_operating_mic: "XNAS", country_code: "US")
+ account_provider = link_account_provider!
+ earlier = account.holdings.create!(
+ security: c, date: snapshot_date - 1, qty: 3, price: 50, amount: 150,
+ currency: "USD", account_provider_id: account_provider.id
+ )
+
+ process_holdings(
+ "a" => [ a, { "quantity" => 10, "institution_price_as_of" => snapshot_date.to_s } ],
+ "b" => [ b, { "quantity" => 5, "institution_price_as_of" => (snapshot_date - 3).to_s } ]
+ )
+
+ assert_not_includes account.current_holdings.pluck(:security_id), c.id
+ assert_equal 3, earlier.reload.qty
+ assert_equal snapshot_date - 1, earlier.date
+ end
+
+ test "a payload priced on one day is written on that day" do
+ price_date = Date.current - 4
+ link_account_provider!
+
+ process_holdings(
+ "a" => [ securities(:aapl), { "quantity" => 10, "institution_price_as_of" => price_date.to_s } ],
+ "b" => [ securities(:msft), { "quantity" => 5, "institution_price_as_of" => price_date.to_s } ]
+ )
+
+ assert_equal [ price_date, price_date ], account.holdings.pluck(:date)
+ end
+
+ test "with no usable price date, holdings land on today" do
+ c = Security.create!(ticker: "GOOGL", name: "Google", exchange_operating_mic: "XNAS", country_code: "US")
+ link_account_provider!
+
+ process_holdings(
+ "a" => [ securities(:aapl), { "quantity" => 10 } ],
+ "b" => [ securities(:msft), { "quantity" => 5, "institution_price_as_of" => "not a date" } ],
+ "c" => [ c, { "quantity" => 3, "institution_price_as_of" => (Date.current + 1).to_s } ]
+ )
+
+ assert_equal [ Date.current ] * 3, account.holdings.pluck(:date)
+ end
+
+ # A malformed price date is dropped from the snapshot date silently, and with
+ # nothing else usable the whole sync lands on today. Support needs to see why.
+ test "an unparseable price date is recorded once per sync for support" do
+ account_provider = link_account_provider!
+
+ assert_difference -> { DebugLogEntry.where(category: "provider_sync", provider_key: "plaid").count }, 1 do
+ process_holdings(
+ "a" => [ securities(:aapl), { "quantity" => 10, "institution_price_as_of" => "not a date" } ],
+ "b" => [ securities(:msft), { "quantity" => 5, "institution_price_as_of" => "31/02/2026" } ]
+ )
+ end
+
+ entry = DebugLogEntry.where(provider_key: "plaid").order(:created_at).last
+ assert_equal "warn", entry.level
+ assert_equal account_provider, entry.account_provider
+ assert_equal account.family, entry.family
+ assert_equal [ "not a date", "31/02/2026" ], entry.metadata["unparseable_dates"]
+ assert_equal Date.current.iso8601, entry.metadata["snapshot_date"]
+ end
+
+ test "missing, blank and future price dates record nothing" do
+ link_account_provider!
+
+ assert_no_difference -> { DebugLogEntry.where(provider_key: "plaid").count } do
+ process_holdings(
+ "a" => [ securities(:aapl), { "quantity" => 10 } ],
+ "b" => [ securities(:msft), { "quantity" => 5, "institution_price_as_of" => "" } ],
+ "c" => [ Security.create!(ticker: "GOOGL", name: "Google", exchange_operating_mic: "XNAS", country_code: "US"),
+ { "quantity" => 3, "institution_price_as_of" => (Date.current + 1).to_s } ]
+ )
+ end
+ end
+
+ # A sync can be dated before the last one: one with no usable price date
+ # lands on today, and the next, dated, sync goes on its newest price date.
+ test "a snapshot dated before the last sync becomes the current one" do
+ snapshot_date = Date.current - 1
+ a, b = securities(:aapl), securities(:msft)
+ link_account_provider!
+
+ process_holdings("a" => [ a, { "quantity" => 10 } ], "b" => [ b, { "quantity" => 5 } ])
+ assert_equal Date.current, account.latest_provider_holdings_snapshot_date
+
+ process_holdings(
+ "a" => [ a, { "quantity" => 12, "institution_price_as_of" => snapshot_date.to_s } ],
+ "b" => [ b, { "quantity" => 7, "institution_price_as_of" => snapshot_date.to_s } ]
+ )
+
+ assert_equal snapshot_date, account.latest_provider_holdings_snapshot_date
+ assert_equal({ a.id => 12, b.id => 7 }, account.current_holdings.to_h { |holding| [ holding.security_id, holding.qty.to_i ] })
+ end
+
+ # The retired rows were the current ones, so a correction the user made
+ # there is moved onto the snapshot row rather than lost with them.
+ test "a cost basis locked on a retired row moves to the snapshot row" do
+ snapshot_date = Date.current - 1
+ a = securities(:aapl)
+ link_account_provider!
+ process_holdings("a" => [ a, { "quantity" => 10 } ])
+ account.holdings.find_by!(security: a, date: Date.current).set_manual_cost_basis!(42)
+
+ process_holdings("a" => [ a, { "quantity" => 12, "institution_price_as_of" => snapshot_date.to_s } ])
+
+ holding = account.current_holdings.sole
+ assert_equal snapshot_date, holding.date
+ assert_equal [ 42, "manual", true ], [ holding.cost_basis.to_i, holding.cost_basis_source, holding.cost_basis_locked ]
+ end
+
+ test "a security remapped on a retired row stays remapped on the snapshot row" do
+ snapshot_date = Date.current - 1
+ msft = securities(:msft)
+ chosen = Security.create!(ticker: "MSFT2", name: "Chosen", exchange_operating_mic: "XNAS", country_code: "US")
+ link_account_provider!
+ process_holdings("b" => [ msft, { "quantity" => 5 } ])
+ account.holdings.find_by!(security: msft, date: Date.current).remap_security!(chosen)
+
+ process_holdings("b" => [ msft, { "quantity" => 7, "institution_price_as_of" => snapshot_date.to_s } ])
+
+ holding = account.current_holdings.sole
+ assert_equal [ snapshot_date, chosen.id, msft.id, true, 7 ],
+ [ holding.date, holding.security_id, holding.provider_security_id, holding.security_locked, holding.qty.to_i ]
+ end
+
+ # The snapshot date can already hold a row of the chosen security. The
+ # snapshot row is then merged into it, as remap_security! merges, instead
+ # of taking the same security and date and failing the sync on the index.
+ test "a remap carried onto a date that already holds the chosen security merges into it" do
+ snapshot_date = Date.current - 1
+ msft = securities(:msft)
+ chosen = Security.create!(ticker: "MSFT2", name: "Chosen", exchange_operating_mic: "XNAS", country_code: "US")
+ link_account_provider!
+ process_holdings("b" => [ msft, { "quantity" => 5 } ])
+ account.holdings.find_by!(security: msft, date: Date.current).remap_security!(chosen)
+ existing = account.holdings.create!(security: chosen, date: snapshot_date, qty: 3, price: 50, amount: 150, currency: "USD")
+
+ process_holdings("b" => [ msft, { "quantity" => 7, "institution_price_as_of" => snapshot_date.to_s } ])
+
+ on_snapshot = account.holdings.where(date: snapshot_date)
+ assert_equal [ existing.id ], on_snapshot.pluck(:id)
+ existing.reload
+ assert_equal [ chosen.id, 10, 500, msft.id, true ],
+ [ existing.security_id, existing.qty.to_i, existing.amount.to_i, existing.provider_security_id, existing.security_locked ]
+ end
+
+ # Another provider's row is that provider's position; a carried remap must
+ # not fold Plaid's units into it.
+ test "a remap carried onto a date where another provider holds the chosen security leaves that row alone" do
+ snapshot_date = Date.current - 1
+ msft = securities(:msft)
+ chosen = Security.create!(ticker: "MSFT2", name: "Chosen", exchange_operating_mic: "XNAS", country_code: "US")
+ plaid = link_account_provider!
+ item = SimplefinItem.create!(family: account.family, name: "SF", access_url: "https://example.com/access")
+ simplefin_account = SimplefinAccount.create!(simplefin_item: item, name: "Broker", account_id: "sf_1",
+ currency: "USD", account_type: "investment", current_balance: 0)
+ other_provider = AccountProvider.create!(account: account, provider: simplefin_account)
+ process_holdings("b" => [ msft, { "quantity" => 5 } ])
+ account.holdings.find_by!(security: msft, date: Date.current).remap_security!(chosen)
+ other = account.holdings.create!(security: chosen, date: snapshot_date, qty: 3, price: 50, amount: 150,
+ currency: "USD", account_provider_id: other_provider.id)
+
+ process_holdings("b" => [ msft, { "quantity" => 7, "institution_price_as_of" => snapshot_date.to_s } ])
+
+ other.reload
+ assert_equal [ 3, 150, false, other_provider.id ], [ other.qty.to_i, other.amount.to_i, other.security_locked, other.account_provider_id ]
+ plaid_row = account.holdings.find_by!(date: snapshot_date, account_provider_id: plaid.id)
+ assert_equal [ msft.id, 7 ], [ plaid_row.security_id, plaid_row.qty.to_i ]
+ end
+
+ test "of several retired rows, the latest correction wins" do
+ snapshot_date = Date.current - 2
+ a = securities(:aapl)
+ provider = link_account_provider!
+ [ [ Date.current - 1, 30 ], [ Date.current, 42 ] ].each do |date, basis|
+ account.holdings.create!(security: a, date: date, qty: 10, price: 50, amount: 500, currency: "USD",
+ account_provider_id: provider.id, provider_security_id: a.id,
+ cost_basis: basis, cost_basis_source: "manual", cost_basis_locked: true)
+ end
+
+ process_holdings("a" => [ a, { "quantity" => 12, "institution_price_as_of" => snapshot_date.to_s } ])
+
+ assert_equal 42, account.current_holdings.sole.cost_basis.to_i
+ end
+
+ test "an uncorrected retired row leaves the snapshot row as the sync wrote it" do
+ snapshot_date = Date.current - 1
+ a = securities(:aapl)
+ provider = link_account_provider!
+ account.holdings.create!(security: a, date: Date.current, qty: 10, price: 50, amount: 500, currency: "USD",
+ account_provider_id: provider.id, provider_security_id: a.id,
+ cost_basis: 30, cost_basis_source: "provider")
+
+ process_holdings("a" => [ a, { "quantity" => 12, "institution_price_as_of" => snapshot_date.to_s } ])
+
+ holding = account.current_holdings.sole
+ assert_equal [ nil, false, false ], [ holding.cost_basis, holding.cost_basis_locked, holding.security_locked ]
+ end
+
+ test "later rows of another provider or with no provider are kept" do
+ snapshot_date = Date.current - 1
+ link_account_provider!
+ item = SimplefinItem.create!(family: account.family, name: "SF", access_url: "https://example.com/access")
+ simplefin_account = SimplefinAccount.create!(simplefin_item: item, name: "Broker", account_id: "sf_1",
+ currency: "USD", account_type: "investment", current_balance: 0)
+ other_provider = AccountProvider.create!(account: account, provider: simplefin_account)
+ google = Security.create!(ticker: "GOOGL", name: "Google", exchange_operating_mic: "XNAS", country_code: "US")
+ other = account.holdings.create!(security: google, date: Date.current, qty: 3, price: 50, amount: 150,
+ currency: "USD", account_provider_id: other_provider.id)
+ calculated = account.holdings.create!(security: google, date: Date.current + 1, qty: 3, price: 50, amount: 150, currency: "USD")
+
+ process_holdings("a" => [ securities(:aapl), { "quantity" => 10, "institution_price_as_of" => snapshot_date.to_s } ])
+
+ assert account.holdings.exists?(other.id)
+ assert account.holdings.exists?(calculated.id)
+ end
+
+ # Without an account provider the rows are written with none, like
+ # calculated rows; nothing later may be removed by matching a nil provider.
+ test "with no account provider no later row is removed" do
+ google = Security.create!(ticker: "GOOGL", name: "Google", exchange_operating_mic: "XNAS", country_code: "US")
+ calculated = account.holdings.create!(security: google, date: Date.current, qty: 3, price: 50, amount: 150, currency: "USD")
+
+ process_holdings("a" => [ securities(:aapl), { "quantity" => 10, "institution_price_as_of" => (Date.current - 1).to_s } ])
+
+ assert account.holdings.exists?(calculated.id)
+ end
+
+ private
+ def account
+ @plaid_account.current_account
+ end
+
+ def link_account_provider!
+ AccountProvider.create!(account: account, provider: @plaid_account).tap { @plaid_account.reload }
+ end
+
+ # entries: { plaid_security_id => [security, holding attributes] }
+ def process_holdings(entries)
+ holdings = entries.map do |plaid_security_id, (security, attributes)|
+ @security_resolver.stubs(:resolve)
+ .with(plaid_security_id: plaid_security_id)
+ .returns(OpenStruct.new(security: security))
+
+ { "security_id" => plaid_security_id, "institution_price" => 50, "iso_currency_code" => "USD" }.merge(attributes)
+ end
+
+ @plaid_account.update!(raw_holdings_payload: { "holdings" => holdings })
+ PlaidAccount::Investments::HoldingsProcessor.new(@plaid_account, security_resolver: @security_resolver).process
+ end
end
diff --git a/test/models/plaid_account/processor_test.rb b/test/models/plaid_account/processor_test.rb
index ce9a581625..529aa4df8e 100644
--- a/test/models/plaid_account/processor_test.rb
+++ b/test/models/plaid_account/processor_test.rb
@@ -335,6 +335,71 @@ class PlaidAccount::ProcessorTest < ActiveSupport::TestCase
assert_equal Date.current, current_anchor.entry.date
end
+ test "an investment's holdings are written on its balance anchor's date" do
+ PlaidAccount::Investments::TransactionsProcessor.any_instance.stubs(:process)
+ PlaidAccount::Transactions::Processor.any_instance.stubs(:process)
+ expect_no_liability_processor_calls
+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)
+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)
+
+ snapshot_date = Date.current - 1
+ securities_by_plaid_id = {
+ "a" => securities(:aapl),
+ "b" => securities(:msft),
+ "c" => Security.create!(ticker: "GOOGL", name: "Google", exchange_operating_mic: "XNAS", country_code: "US"),
+ "e" => Security.create!(ticker: "AMZN", name: "Amazon", exchange_operating_mic: "XNAS", country_code: "US")
+ }
+ securities_by_plaid_id.each do |plaid_security_id, security|
+ PlaidAccount::Investments::SecurityResolver.any_instance.stubs(:resolve)
+ .with(plaid_security_id: plaid_security_id)
+ .returns(OpenStruct.new(security: security))
+ end
+
+ @plaid_account.update!(
+ plaid_type: "investment",
+ raw_holdings_payload: { "holdings" => [
+ { "security_id" => "a", "quantity" => "10", "institution_price" => "90", "iso_currency_code" => "USD", "institution_price_as_of" => snapshot_date.to_s },
+ { "security_id" => "b", "quantity" => "5", "institution_price" => "20", "iso_currency_code" => "USD", "institution_price_as_of" => (snapshot_date - 3).to_s },
+ { "security_id" => "c", "quantity" => "2", "institution_price" => "30", "iso_currency_code" => "USD", "institution_price_as_of" => (Date.current + 1).to_s },
+ { "security_id" => "e", "quantity" => "1", "institution_price" => "40", "iso_currency_code" => "USD" }
+ ] }
+ )
+
+ PlaidAccount::Processor.new(@plaid_account).process
+
+ account = @plaid_account.current_account
+ anchor_date = account.valuations.current_anchor.first.entry.date
+ assert_equal snapshot_date, anchor_date
+ assert_equal securities_by_plaid_id.values.map(&:id).sort, account.holdings.pluck(:security_id).sort
+ assert_equal [ anchor_date ], account.holdings.distinct.pluck(:date)
+ end
+
+ test "the anchor and the holdings both take the account's holdings snapshot date" do
+ PlaidAccount::Investments::TransactionsProcessor.any_instance.stubs(:process)
+ PlaidAccount::Transactions::Processor.any_instance.stubs(:process)
+ expect_no_liability_processor_calls
+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:balance).returns(1000)
+ PlaidAccount::Investments::BalanceCalculator.any_instance.stubs(:cash_balance).returns(100)
+ PlaidAccount::Investments::SecurityResolver.any_instance.stubs(:resolve).returns(OpenStruct.new(security: securities(:aapl)))
+
+ @plaid_account.update!(
+ plaid_type: "investment",
+ raw_holdings_payload: { "holdings" => [
+ { "security_id" => "a", "quantity" => "10", "institution_price" => "90", "iso_currency_code" => "USD", "institution_price_as_of" => (Date.current - 1).to_s }
+ ] }
+ )
+ # A date no rule over this payload would produce, so both readers can
+ # only arrive at it through the one method.
+ snapshot_date = Date.current - 7
+ @plaid_account.stubs(:holdings_snapshot_date).returns(snapshot_date)
+
+ PlaidAccount::Processor.new(@plaid_account).process
+
+ account = @plaid_account.current_account
+ assert_equal snapshot_date, account.valuations.current_anchor.first.entry.date
+ assert_equal [ snapshot_date ], account.holdings.pluck(:date)
+ end
+
test "an investment snapshot dated behind the anchor is recorded on its own date and leaves the anchor alone" do
PlaidAccount::Investments::TransactionsProcessor.any_instance.stubs(:process)
PlaidAccount::Investments::HoldingsProcessor.any_instance.stubs(:process)