Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Keep SnapTrade card balances and purchases in Sure's signs (#5380)

jezmor3092a5a6853a
diff --git a/app/models/account/current_balance_manager.rb b/app/models/account/current_balance_manager.rb
index 0d106efa14..e15a33d18b 100644
--- a/app/models/account/current_balance_manager.rb
+++ b/app/models/account/current_balance_manager.rb
@@ -195,27 +195,10 @@ class Account::CurrentBalanceManager
# between the standing anchor and the new reading. Only meaningful for :cash.
def ledger_explains?(older_entry, new_balance, date)
return false unless Rails.configuration.x.balance.reuse_explained_anchor
- return false unless account.balance_type == :cash
- return false unless older_entry.currency == account.currency
-
- # Ignore entries the anchor already included: its own timestamp is the watermark.
- # A split child inherits its parent's timestamp; the parent was the flow the anchor
- # could have seen, and the child rows are created later by the split.
- flows = account.entries
- .excluding_pending
- .excluding_split_parents
- .where(date: older_entry.date..date)
- .where.not(entryable_type: "Valuation")
- .where(
- "entries.date > :anchor_date OR " \
- "COALESCE((SELECT pe.created_at FROM entries pe WHERE pe.id = entries.parent_entry_id), entries.created_at) > :anchor_written_at",
- anchor_date: older_entry.date, anchor_written_at: older_entry.updated_at
- )
- .pluck(:currency, :amount)
-
- return false unless flows.all? { |currency, _| currency == account.currency }
-
- net = flows.sum { |_, amount| amount }
+
+ net = Account::LedgerFlows.new(account).net_since(older_entry, date)
+ return false if net.nil?
+
expected = older_entry.amount + (account.asset? ? -net : net)
tolerance = BigDecimal(Money::Currency.new(account.currency).step.to_s)
diff --git a/app/models/account/ledger_flows.rb b/app/models/account/ledger_flows.rb
new file mode 100644
index 0000000000..a091b4a79a
--- /dev/null
+++ b/app/models/account/ledger_flows.rb
@@ -0,0 +1,46 @@
+# The imported transactions and trades a balance reading had not seen yet.
+class Account::LedgerFlows
+ def initialize(account)
+ @account = account
+ end
+
+ # Their sum through `date`, as entry amounts. Nil when that can't be judged:
+ # the account isn't :cash, or a flow or the reading is in another currency.
+ # With `before`, a later reading dated `date`, only flows that reading had
+ # already seen count, so walking back through readings uses each flow once.
+ def net_since(reading, date, before: nil)
+ return unless account.balance_type == :cash
+ return unless reading.currency == account.currency
+
+ # Ignore entries the reading already included: its own timestamp is the watermark.
+ # A split child inherits its parent's timestamp; the parent was the flow the reading
+ # could have seen, and the child rows are created later by the split.
+ flows = account.entries
+ .excluding_pending
+ .excluding_split_parents
+ .where(date: reading.date..date)
+ .where.not(entryable_type: "Valuation")
+ .where(
+ "entries.date > :reading_date OR " \
+ "COALESCE((SELECT pe.created_at FROM entries pe WHERE pe.id = entries.parent_entry_id), entries.created_at) > :reading_written_at",
+ reading_date: reading.date, reading_written_at: reading.updated_at
+ )
+
+ if before
+ flows = flows.where(
+ "entries.date < :later_date OR " \
+ "COALESCE((SELECT pe.created_at FROM entries pe WHERE pe.id = entries.parent_entry_id), entries.created_at) <= :later_written_at",
+ later_date: before.date, later_written_at: before.updated_at
+ )
+ end
+
+ flows = flows.pluck(:currency, :amount)
+
+ return unless flows.all? { |currency, _| currency == account.currency }
+
+ flows.sum { |_, amount| amount }
+ end
+
+ private
+ attr_reader :account
+end
diff --git a/app/models/snaptrade_account/activities_processor.rb b/app/models/snaptrade_account/activities_processor.rb
index d6c7af6d5b..32238ff1fe 100644
--- a/app/models/snaptrade_account/activities_processor.rb
+++ b/app/models/snaptrade_account/activities_processor.rb
@@ -80,6 +80,12 @@ class SnaptradeAccount::ActivitiesProcessor
"DISTRIBUTION" => { category: :cash, label: "Dividend", cash_flow: :inflow },
"SUBSTITUTE_DIVIDEND" => { category: :cash, label: "Dividend", cash_flow: :inflow },
+ # Card accounts (SnapTrade's LOC category) sign these from the account's
+ # perspective: purchases negative, refunds and payments positive.
+ "POSDEBIT" => { category: :cash, label: "Other", cash_flow: :outflow },
+ "POSCREDIT" => { category: :cash, label: "Other", cash_flow: :inflow },
+ "PAYMENT" => { category: :cash, label: "Other", cash_flow: :invert },
+
# Card activities (Wealthsimple). Direction comes from the description, see normalize_card_activity.
"CREDIT_CARD" => { category: :cash, label: "Other", cash_flow: :card },
"PREPAID_CARD" => { category: :cash, label: "Other", cash_flow: :card }
@@ -575,11 +581,19 @@ class SnaptradeAccount::ActivitiesProcessor
date: activity_date,
name: description,
source: "snaptrade",
+ kind: card_payment_kind(activity_type),
investment_activity_label: label_from_type(activity_type)
)
@transactions_count += 1 if result
end
+ # A card PAYMENT is money arriving from another account. Unpaired, a
+ # standard inflow would count as income; this is the kind the card leg of a
+ # matched payment takes, so pairing it later changes nothing.
+ def card_payment_kind(activity_type)
+ "funds_movement" if activity_type&.upcase == "PAYMENT" && account.accountable_type == "CreditCard"
+ end
+
# The cash a row names: its amount, or its net amount when the amount is
# missing or zero. Nil when it names none.
def cash_amount(data)
diff --git a/app/models/snaptrade_account/liability_sign_repair.rb b/app/models/snaptrade_account/liability_sign_repair.rb
new file mode 100644
index 0000000000..f9c54fb6ac
--- /dev/null
+++ b/app/models/snaptrade_account/liability_sign_repair.rb
@@ -0,0 +1,81 @@
+# Syncs before liability balances were negated stored a card's readings as
+# SnapTrade sends them: owed as negative, credit as positive. Each day's
+# reading stays behind as a reconciliation, and the balance history resets to
+# every one of them, so a wrong-signed reading left anywhere shows as a jump
+# that never happened.
+#
+# Such readings can only be there from before the fix, so the repair runs
+# until it has judged every one, is then marked done, and runs under a lock so
+# overlapping syncs can't both turn them. The ledger decides each reading's
+# sign, newest first: a later reading less what was imported in between is
+# the balance on the earlier one's date, and a reading of the opposite sign is
+# turned around. Each interval counts only the flows the later reading had
+# seen, so none counts twice. A loan's balance doesn't move with its
+# transactions, so for one the later reading itself is that balance. A walk
+# that meets a reading it can't judge (a flow in another currency) stops
+# there, unmarked, and the next sync tries again.
+#
+# Only readings a sync could have written are candidates: those recorded since
+# SnapTrade was linked and never edited. A reading entered by hand in Sure's
+# signs already agrees with the ledger and is left as it is.
+class SnaptradeAccount::LiabilitySignRepair
+ def initialize(snaptrade_account, account)
+ @snaptrade_account = snaptrade_account
+ @account = account
+ end
+
+ # `balance` is the current reading in Sure's signs, as of `date`.
+ def run(balance, date)
+ return if snaptrade_account.liability_signs_fixed_at?
+
+ SnaptradeAccount.transaction do
+ locked = SnaptradeAccount.lock.find(snaptrade_account.id)
+ next if locked.liability_signs_fixed_at?
+
+ done = account.liability? ? repair_readings(balance, date) : true
+
+ # A walk that stopped short is tried again on the next sync
+ locked.update_columns(liability_signs_fixed_at: Time.current) if done
+ end
+ end
+
+ private
+ attr_reader :snaptrade_account, :account
+
+ # True when every candidate reading was judged
+ def repair_readings(balance, date)
+ flows = Account::LedgerFlows.new(account)
+ later_balance = balance
+ later_date = date
+ later_reading = nil
+
+ readings.each do |reading|
+ net = account.balance_type == :non_cash ? 0 : flows.net_since(reading, later_date, before: later_reading)
+ return false if net.nil?
+
+ derived = later_balance - net
+ if reading.amount.nonzero? && derived.nonzero? && reading.amount.positive? != derived.positive?
+ # Leaves updated_at alone: it marks which flows the reading had seen.
+ reading.update_columns(amount: -reading.amount)
+ end
+
+ later_balance = reading.amount
+ later_date = reading.date
+ later_reading = reading
+ end
+
+ true
+ end
+
+ def readings
+ linked_at = snaptrade_account.account_provider&.created_at
+ return Entry.none unless linked_at
+
+ account.entries
+ .where(entryable_type: "Valuation", entryable_id: Valuation.where(kind: %w[current_anchor reconciliation]).select(:id))
+ .where(created_at: linked_at..)
+ .where(user_modified: false)
+ .where("entries.locked_attributes = '{}'::jsonb")
+ .order(date: :desc, created_at: :desc)
+ end
+end
diff --git a/app/models/snaptrade_account/processor.rb b/app/models/snaptrade_account/processor.rb
index 4aa0dead48..942c85430b 100644
--- a/app/models/snaptrade_account/processor.rb
+++ b/app/models/snaptrade_account/processor.rb
@@ -40,6 +40,12 @@ class SnaptradeAccount::Processor
end
if anchor_balance
+ # Missing activities would make the ledger misjudge the old readings'
+ # signs, whether the fetch failed (keeping the last payload) or some
+ # failed to import; the repair waits for a sync that brings all of them in.
+ if activities_ok && !snaptrade_account.activities_fetch_failed? && !snaptrade_account.activities_fetch_pending?
+ SnaptradeAccount::LiabilitySignRepair.new(snaptrade_account, account).run(anchor_balance, date)
+ end
account.set_current_balance(
anchor_balance,
date: date,
@@ -63,6 +69,13 @@ class SnaptradeAccount::Processor
total_balance = calculate_total_balance
cash_balance = calculate_cash_balance
+ # SnapTrade reports a card's debt as a negative balance; Sure stores what's
+ # owed on a liability as a positive one.
+ if account.liability?
+ total_balance = -total_balance
+ cash_balance = -cash_balance
+ end
+
Rails.logger.debug "SnaptradeAccount::Processor - Balance update: total=#{total_balance}, cash=#{cash_balance}"
# Update the cached fields on the account
diff --git a/app/models/snaptrade_item/importer.rb b/app/models/snaptrade_item/importer.rb
index 540165904d..870973d3ba 100644
--- a/app/models/snaptrade_item/importer.rb
+++ b/app/models/snaptrade_item/importer.rb
@@ -324,11 +324,14 @@ class SnaptradeItem::Importer
stats["activities_found"] = stats.fetch("activities_found", 0) + all_activities.size
end
+ # The liability sign repair only trusts activities a successful fetch brought in
+ snaptrade_account.update_columns(activities_fetch_failed: false) if snaptrade_account.activities_fetch_failed?
all_activities.size
rescue => e
Rails.logger.error "SnaptradeItem::Importer - Failed to fetch activities: #{e.class} - #{e.message}"
Rails.logger.error e.backtrace.first(5).join("\n") if e.backtrace
register_error(e, context: "activities", account_id: snaptrade_account.id)
+ snaptrade_account.update_columns(activities_fetch_failed: true)
# nil, not 0: a fetch that failed is not SnapTrade still syncing, and
# must not queue the background job to repeat it.
nil
diff --git a/db/migrate/20261121020000_add_liability_sign_repair_to_snaptrade_accounts.rb b/db/migrate/20261121020000_add_liability_sign_repair_to_snaptrade_accounts.rb
new file mode 100644
index 0000000000..9f0b85db78
--- /dev/null
+++ b/db/migrate/20261121020000_add_liability_sign_repair_to_snaptrade_accounts.rb
@@ -0,0 +1,6 @@
+class AddLiabilitySignRepairToSnaptradeAccounts < ActiveRecord::Migration[8.1]
+ def change
+ add_column :snaptrade_accounts, :liability_signs_fixed_at, :datetime
+ add_column :snaptrade_accounts, :activities_fetch_failed, :boolean, default: false, null: false
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 088e60b8a1..e1bdd79def 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2562,6 +2562,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_24_120100) do
t.string "account_number"
t.string "account_status"
t.string "account_type"
+ t.boolean "activities_fetch_failed", default: false, null: false
t.boolean "activities_fetch_pending", default: false
t.string "brokerage_name"
t.decimal "cash_balance", precision: 19, scale: 4
@@ -2571,6 +2572,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_24_120100) do
t.jsonb "institution_metadata"
t.datetime "last_activities_sync"
t.datetime "last_holdings_sync"
+ t.datetime "liability_signs_fixed_at"
t.string "name"
t.string "provider"
t.jsonb "raw_activities_payload", default: []
diff --git a/test/models/snaptrade_account/activities_processor_test.rb b/test/models/snaptrade_account/activities_processor_test.rb
index bdcd9089b6..90d9c973da 100644
--- a/test/models/snaptrade_account/activities_processor_test.rb
+++ b/test/models/snaptrade_account/activities_processor_test.rb
@@ -387,6 +387,53 @@ class SnaptradeAccount::ActivitiesProcessorTest < ActiveSupport::TestCase
assert_equal "Dividend", sub_div.entryable.investment_activity_label
end
+ test "processes card purchases as outflows and refunds and payments as inflows" do
+ process_activities(
+ build_cash_activity(id: "purchase_001", type: "POSDEBIT", amount: -32.73, settlement_date: Date.current.to_s),
+ build_cash_activity(id: "refund_001", type: "POSCREDIT", amount: 10.00, settlement_date: Date.current.to_s),
+ build_cash_activity(id: "payment_001", type: "PAYMENT", amount: 500.00, settlement_date: Date.current.to_s)
+ )
+
+ assert_equal 32.73, snaptrade_entry("purchase_001").amount.to_f
+ assert_equal(-10.00, snaptrade_entry("refund_001").amount.to_f)
+ assert_equal(-500.00, snaptrade_entry("payment_001").amount.to_f)
+ end
+
+ test "a card payment with no matched bank side is a transfer, not income" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ @snaptrade_account.reload
+
+ process_activities(
+ build_cash_activity(id: "payment_002", type: "PAYMENT", amount: 500.00, settlement_date: Date.current.to_s),
+ build_cash_activity(id: "purchase_002", type: "POSDEBIT", amount: -32.73, settlement_date: Date.current.to_s)
+ )
+
+ payment = card.entries.find_by!(external_id: "payment_002", source: "snaptrade")
+ assert_equal(-500.00, payment.amount.to_f)
+ assert_equal "funds_movement", payment.entryable.kind
+ assert_equal "standard", card.entries.find_by!(external_id: "purchase_002", source: "snaptrade").entryable.kind
+ end
+
+ # SnapTrade links a line of credit without "card" in its type as a Loan.
+ # Account::ProviderImportAdapter already classifies money into a linked Loan
+ # as loan_payment (a transfer kind), so only cards needed card_payment_kind.
+ test "a payment into a line of credit linked as a loan is a loan payment, not income" do
+ loan = @family.accounts.create!(name: "Line of credit", balance: 0, currency: "USD", accountable: Loan.new)
+ @snaptrade_account.ensure_account_provider!(loan)
+ @snaptrade_account.reload
+
+ process_activities(
+ build_cash_activity(id: "payment_003", type: "PAYMENT", amount: 300.00, settlement_date: Date.current.to_s),
+ build_cash_activity(id: "purchase_003", type: "POSDEBIT", amount: -40.00, settlement_date: Date.current.to_s)
+ )
+
+ payment = loan.entries.find_by!(external_id: "payment_003", source: "snaptrade").entryable
+ assert_equal "loan_payment", payment.kind
+ assert_includes Transaction::TRANSFER_KINDS, payment.kind
+ assert_equal "standard", loan.entries.find_by!(external_id: "purchase_003", source: "snaptrade").entryable.kind
+ end
+
test "processes cash FEE and TAX as positive outflow and INTEREST as negative inflow" do
process_activities(
build_cash_activity(id: "fee_001", type: "FEE", amount: -25.00, settlement_date: Date.current.to_s),
diff --git a/test/models/snaptrade_account_processor_test.rb b/test/models/snaptrade_account_processor_test.rb
index 39b06f4edf..0235b38e75 100644
--- a/test/models/snaptrade_account_processor_test.rb
+++ b/test/models/snaptrade_account_processor_test.rb
@@ -1001,6 +1001,331 @@ class SnaptradeAccountProcessorTest < ActiveSupport::TestCase
# === Full Account Sync Integration ===
+ test "processor stores a card's negative SnapTrade balance as a positive amount owed" do
+ card = @family.accounts.create!(
+ name: "Test Card",
+ balance: 0,
+ currency: "USD",
+ accountable: CreditCard.new
+ )
+ @snaptrade_account.ensure_account_provider!(card)
+ @snaptrade_account.update!(
+ currency: "USD",
+ current_balance: BigDecimal("-1455.44"),
+ cash_balance: BigDecimal("-1455.44"),
+ raw_holdings_payload: [],
+ raw_activities_payload: [
+ {
+ "id" => "card_purchase",
+ "type" => "POSDEBIT",
+ "amount" => "-32.73",
+ "description" => "Safeway",
+ "settlement_date" => Date.current.to_s,
+ "currency" => "USD"
+ }
+ ]
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ card.reload
+ assert_equal BigDecimal("1455.44"), card.balance
+ assert_equal BigDecimal("1455.44"), card.cash_balance
+ assert_equal BigDecimal("32.73"), card.entries.find_by!(external_id: "card_purchase").amount
+ end
+
+ # A card synced before the sign fix holds its reading as SnapTrade sent it.
+ test "a card's anchor from before the sign fix is turned around, not kept beside the new reading" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-1400.00"), date: Date.current - 5)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-1455.44"), cash_balance: BigDecimal("-1455.44"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ card.reload
+ readings = card.entries.where(entryable_type: "Valuation").order(:date).pluck(:amount)
+ assert_equal BigDecimal("1455.44"), card.balance
+ assert readings.none?(&:negative?), "no reading keeps the old sign: #{readings.map(&:to_s)}"
+ assert_includes readings, BigDecimal("1400.00")
+ assert_not_nil @snaptrade_account.reload.liability_signs_fixed_at
+ end
+
+ test "a card in credit keeps its negative anchor" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-20.00"), date: Date.current - 5)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("15.00"), cash_balance: BigDecimal("15.00"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ assert_equal BigDecimal("-15.00"), card.reload.balance
+ assert_includes card.entries.where(entryable_type: "Valuation").pluck(:amount), BigDecimal("-20.00")
+ end
+
+ test "a card's credit anchor from before the sign fix is turned around" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("20.00"), date: Date.current - 5)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-10.00"), cash_balance: BigDecimal("-10.00"),
+ raw_holdings_payload: [],
+ raw_activities_payload: [
+ {
+ "id" => "card_purchase",
+ "type" => "POSDEBIT",
+ "amount" => "-30.00",
+ "description" => "Safeway",
+ "settlement_date" => (Date.current - 2).to_s,
+ "currency" => "USD"
+ }
+ ]
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ card.reload
+ readings = card.entries.where(entryable_type: "Valuation").pluck(:amount)
+ assert_equal BigDecimal("10.00"), card.balance
+ assert_includes readings, BigDecimal("-20.00")
+ assert_not_includes readings, BigDecimal("20.00")
+ end
+
+ test "a card that went from credit to owing keeps its negative anchor" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-20.00"), date: Date.current - 5)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-10.00"), cash_balance: BigDecimal("-10.00"),
+ raw_holdings_payload: [],
+ raw_activities_payload: [
+ {
+ "id" => "card_purchase",
+ "type" => "POSDEBIT",
+ "amount" => "-30.00",
+ "description" => "Safeway",
+ "settlement_date" => (Date.current - 2).to_s,
+ "currency" => "USD"
+ }
+ ]
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ card.reload
+ readings = card.entries.where(entryable_type: "Valuation").pluck(:amount)
+ assert_equal BigDecimal("10.00"), card.balance
+ assert_includes readings, BigDecimal("-20.00")
+ assert_not_includes readings, BigDecimal("20.00")
+ end
+
+ test "after its first sync since the fix, a card's anchor is never turned around" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-20.00"), date: Date.current - 5)
+ # A $30 purchase that never arrived from SnapTrade: the ledger alone would
+ # say the card owed money on the anchor's date.
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-10.00"), cash_balance: BigDecimal("-10.00"),
+ raw_holdings_payload: [], raw_activities_payload: [], liability_signs_fixed_at: 1.day.ago
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ readings = card.reload.entries.where(entryable_type: "Valuation").pluck(:amount)
+ assert_equal BigDecimal("10.00"), card.balance
+ assert_includes readings, BigDecimal("-20.00")
+ assert_not_includes readings, BigDecimal("20.00")
+ end
+
+ test "a sync that finds the correction already done by an overlapping sync leaves the anchor alone" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-1400.00"), date: Date.current - 5)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-1455.44"), cash_balance: BigDecimal("-1455.44"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+ processor = SnaptradeAccount::Processor.new(@snaptrade_account.reload)
+ SnaptradeAccount.where(id: @snaptrade_account.id).update_all(liability_signs_fixed_at: Time.current)
+
+ processor.process
+
+ assert_includes card.reload.entries.where(entryable_type: "Valuation").pluck(:amount), BigDecimal("-1400.00")
+ end
+
+ test "a loan's anchor from before the sign fix is turned around" do
+ loan = @family.accounts.create!(name: "Line of credit", balance: 0, currency: "USD", accountable: Loan.new)
+ @snaptrade_account.ensure_account_provider!(loan)
+ loan.set_current_balance(BigDecimal("-100.00"), date: Date.current - 5)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-100.00"), cash_balance: BigDecimal("-100.00"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ readings = loan.reload.entries.where(entryable_type: "Valuation").pluck(:amount)
+ assert_equal BigDecimal("100.00"), loan.balance
+ assert readings.none?(&:negative?), "no reading keeps the old sign: #{readings.map(&:to_s)}"
+ assert_not_nil @snaptrade_account.reload.liability_signs_fixed_at
+ end
+
+ test "every reading a card's syncs left before the sign fix is turned around" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-1400.00"), date: Date.current - 6)
+ card.set_current_balance(BigDecimal("-1450.00"), date: Date.current - 5)
+ assert_equal 1, card.valuations.reconciliation.count
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-1455.44"), cash_balance: BigDecimal("-1455.44"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ readings = card.reload.entries.where(entryable_type: "Valuation").order(:date).pluck(:amount)
+ assert_equal [ BigDecimal("1400.00"), BigDecimal("1450.00"), BigDecimal("1455.44") ], readings
+ end
+
+ test "a reading entered by hand in Sure's signs is kept while the sync's readings around it are turned" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-1400.00"), date: Date.current - 6)
+ card.create_reconciliation(balance: BigDecimal("1420.00"), date: Date.current - 3)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-1455.44"), cash_balance: BigDecimal("-1455.44"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ readings = card.reload.entries.where(entryable_type: "Valuation").order(:date).pluck(:amount)
+ assert_equal [ BigDecimal("1400.00"), BigDecimal("1420.00"), BigDecimal("1455.44") ], readings
+ end
+
+ test "readings recorded before SnapTrade was linked are left alone" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ card.entries.create!(
+ date: Date.current - 7, name: "Manual balance update", amount: BigDecimal("-50.00"), currency: "USD",
+ entryable: Valuation.new(kind: "reconciliation"), created_at: 2.days.ago
+ )
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-1400.00"), date: Date.current - 6)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-1455.44"), cash_balance: BigDecimal("-1455.44"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ readings = card.reload.entries.where(entryable_type: "Valuation").order(:date).pluck(:amount)
+ assert_equal [ BigDecimal("-50.00"), BigDecimal("1400.00"), BigDecimal("1455.44") ], readings
+ end
+
+ test "old readings are not judged from an import that left activities out" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ # A credit carried over from before; the $30 purchase since brings it to $10 owed
+ card.set_current_balance(BigDecimal("-20.00"), date: Date.current - 5)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-10.00"), cash_balance: BigDecimal("-10.00"),
+ raw_holdings_payload: [],
+ raw_activities_payload: [
+ {
+ "id" => "card_purchase",
+ "type" => "POSDEBIT",
+ "amount" => "-30.00",
+ "description" => "Safeway",
+ "settlement_date" => (Date.current - 2).to_s,
+ "currency" => "USD"
+ }
+ ]
+ )
+
+ SnaptradeAccount::ActivitiesProcessor.any_instance.stubs(:process).returns({ trades: 0, transactions: 0, failed: 1 })
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ assert_includes card.reload.entries.where(entryable_type: "Valuation").pluck(:amount), BigDecimal("-20.00")
+ assert_nil @snaptrade_account.reload.liability_signs_fixed_at
+
+ SnaptradeAccount::ActivitiesProcessor.any_instance.unstub(:process)
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ assert_includes card.reload.entries.where(entryable_type: "Valuation").pluck(:amount), BigDecimal("-20.00")
+ assert_not_nil @snaptrade_account.reload.liability_signs_fixed_at
+ end
+
+ # A failed fetch keeps the last payload, which can process cleanly but still
+ # miss the purchase that explains the change.
+ test "old readings are not judged after an activities fetch that failed" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ # A credit carried over from before; an unfetched $30 purchase brings it to $10 owed
+ card.set_current_balance(BigDecimal("-20.00"), date: Date.current - 5)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-10.00"), cash_balance: BigDecimal("-10.00"),
+ raw_holdings_payload: [], raw_activities_payload: [], activities_fetch_failed: true
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ assert_includes card.reload.entries.where(entryable_type: "Valuation").pluck(:amount), BigDecimal("-20.00")
+ assert_nil @snaptrade_account.reload.liability_signs_fixed_at
+ end
+
+ # jjmata's example: a refund imported after the latest reading belongs to the
+ # interval after it, not also to the one before.
+ test "each interval counts only the flows its later reading had seen" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ @snaptrade_account.account_provider.update_columns(created_at: 4.days.ago)
+ travel_to 3.days.ago do
+ card.set_current_balance(BigDecimal("20.00"), date: Date.current) # a $20 credit, stored pre-fix as +20
+ end
+ travel_to 2.days.ago do
+ card.entries.create!(date: Date.current, name: "Purchase", amount: BigDecimal("30.00"), currency: "USD", entryable: Transaction.new)
+ card.set_current_balance(BigDecimal("-10.00"), date: Date.current) # $10 owed, stored pre-fix as -10
+ end
+ travel_to 2.days.ago + 1.hour do
+ card.entries.create!(date: Date.current, name: "Refund", amount: BigDecimal("-50.00"), currency: "USD", entryable: Transaction.new)
+ end
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("40.00"), cash_balance: BigDecimal("40.00"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ readings = card.reload.entries.where(entryable_type: "Valuation").order(:date).pluck(:amount)
+ assert_equal [ BigDecimal("-20.00"), BigDecimal("10.00"), BigDecimal("-40.00") ], readings
+ end
+
+ test "a repair that stops at a reading it can't judge is tried again, not marked done" do
+ card = @family.accounts.create!(name: "Test Card", balance: 0, currency: "USD", accountable: CreditCard.new)
+ @snaptrade_account.ensure_account_provider!(card)
+ card.set_current_balance(BigDecimal("-1400.00"), date: Date.current - 6)
+ card.set_current_balance(BigDecimal("-1450.00"), date: Date.current - 5)
+ # A flow in another currency between the two readings: the ledger can't judge the older one
+ card.entries.create!(date: Date.current - 6, name: "Abroad", amount: BigDecimal("20.00"), currency: "EUR", entryable: Transaction.new)
+ @snaptrade_account.update!(
+ currency: "USD", current_balance: BigDecimal("-1455.44"), cash_balance: BigDecimal("-1455.44"),
+ raw_holdings_payload: [], raw_activities_payload: []
+ )
+
+ SnaptradeAccount::Processor.new(@snaptrade_account.reload).process
+
+ readings = card.reload.entries.where(entryable_type: "Valuation").order(:date).pluck(:amount)
+ assert_equal [ BigDecimal("-1400.00"), BigDecimal("1450.00"), BigDecimal("1455.44") ], readings
+ assert_nil @snaptrade_account.reload.liability_signs_fixed_at
+ end
+
test "processor synchronizes balances, holdings, and activities end-to-end without cash distortion" do
security = securities(:aapl)
diff --git a/test/models/snaptrade_item/importer_test.rb b/test/models/snaptrade_item/importer_test.rb
index d5b1c08a57..1512860736 100644
--- a/test/models/snaptrade_item/importer_test.rb
+++ b/test/models/snaptrade_item/importer_test.rb
@@ -120,4 +120,15 @@ class SnaptradeItem::ImporterTest < ActiveSupport::TestCase
assert_not @snaptrade_account.reload.activities_fetch_pending?
end
+
+ # The liability sign repair only judges history from a fetch that succeeded
+ test "a failed activities fetch is recorded, and the next successful one clears it" do
+ @provider.stubs(:get_account_activities).raises(Provider::Snaptrade::ApiError.new("hit the page cap"))
+ @importer.send(:import_activities, @snaptrade_account)
+ assert @snaptrade_account.reload.activities_fetch_failed?
+
+ @provider.stubs(:get_account_activities).returns([])
+ @importer.send(:import_activities, @snaptrade_account)
+ assert_not @snaptrade_account.reload.activities_fetch_failed?
+ end
end