Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(sharesight): drop sold positions, sync settlement accounts (#4856)

Saim Shafique2f39220ba267
diff --git a/app/models/sharesight_account/cash_router.rb b/app/models/sharesight_account/cash_router.rb
index dd74f678ec..59034e5955 100644
--- a/app/models/sharesight_account/cash_router.rb
+++ b/app/models/sharesight_account/cash_router.rb
@@ -19,12 +19,16 @@ class SharesightAccount::CashRouter
# One offset entry, for one record or a day's trades settled together.
Unit = Struct.new(:key, :kind, :date, :currency, :amount, :target, :leftover, :description, :bank_entry, keyword_init: true)
- attr_reader :notices
+ attr_reader :notices, :touched_accounts
def initialize(sharesight_account, movements)
@sharesight_account = sharesight_account
@movements = movements
@notices = []
+ # Manual settlement accounts this run booked counterparts into, or removed
+ # stale counterparts from. Their stored balance changed, so they need
+ # their own sync once the portfolio accounts are done.
+ @touched_accounts = Set.new
end
def route
@@ -191,6 +195,9 @@ class SharesightAccount::CashRouter
nil
elsif unit.target && !bank_fed?(unit.target)
counterpart = book_counterpart(unit)
+ # A target that isn't bank-fed is a manual account by definition
+ # (manual? is just !linked?), so no extra check is needed here.
+ @touched_accounts << unit.target
link_transfer!(leg, counterpart)
counterpart.id
end
@@ -248,11 +255,19 @@ class SharesightAccount::CashRouter
# By entry id, since a counterpart keeps its external id when the settlement
# account changes, and the old account's copy has to go.
def remove_stale_counterparts(current)
- Entry.joins(:account)
+ stale = Entry.joins(:account)
.where(accounts: { family_id: account.family_id }, source: "sharesight")
.where("entries.external_id LIKE ?", "#{Entry.sanitize_sql_like("#{COUNTERPART_PREFIX}#{@sharesight_account.id}_")}%")
.where.not(id: current)
- .destroy_all
+
+ # The old settlement account's copy goes with the counterpart, so its
+ # balance changes too — whether it is still a manual account or has
+ # since been linked to a bank feed.
+ Account.where(id: stale.distinct.pluck(:account_id)).each do |old_account|
+ @touched_accounts << old_account
+ end
+
+ stale.destroy_all
end
def report_unsettled(units)
diff --git a/app/models/sharesight_account/holdings_processor.rb b/app/models/sharesight_account/holdings_processor.rb
index dcd7a142a8..43e57fe8e0 100644
--- a/app/models/sharesight_account/holdings_processor.rb
+++ b/app/models/sharesight_account/holdings_processor.rb
@@ -8,6 +8,9 @@ class SharesightAccount::HoldingsProcessor
def process
return unless account.present?
+ # What current holdings showed before this run.
+ @last_snapshot_date = account.latest_provider_holdings_snapshot_date
+
Array(@sharesight_account.raw_holdings_payload).each do |holding|
process_holding(holding)
end
@@ -32,8 +35,9 @@ class SharesightAccount::HoldingsProcessor
quantity = parse_decimal(holding["quantity"])
# Sold holdings come back with no units, and "limited" ones (hidden on
# cheaper plans) have no numbers at all.
- return unless quantity&.positive?
+ return if quantity.nil?
return if holding["limited"]
+ return if quantity.negative?
security = resolve_security(instrument["code"], instrument["market_code"], instrument["name"])
return unless security
@@ -41,16 +45,20 @@ class SharesightAccount::HoldingsProcessor
currency, price = holding_price(holding, quantity)
return unless price
- date = Date.current
+ # A sold position current holdings still shows gets a zero row for today,
+ # so it drops out (one from earlier today is updated, since the external
+ # id has the date in it). Anything sold before that is skipped, or every
+ # sync would add a row for positions sold long ago.
+ return if quantity.zero? && !still_held?(security)
import_adapter.import_holding(
security: security,
quantity: quantity,
amount: quantity * price,
currency: currency,
- date: date,
+ date: Date.current,
price: price,
- external_id: "sharesight_holding_#{@sharesight_account.sharesight_account_id}_#{holding['id']}_#{date}",
+ external_id: "sharesight_holding_#{@sharesight_account.sharesight_account_id}_#{holding['id']}_#{Date.current}",
source: "sharesight",
account_provider_id: @sharesight_account.account_provider&.id,
delete_future_holdings: false
@@ -68,15 +76,30 @@ class SharesightAccount::HoldingsProcessor
end
# Use the instrument's own price and currency when we have both, otherwise
- # the holding's value per unit in the portfolio's currency.
+ # the holding's value per unit in the portfolio's currency. A sold holding
+ # has no units to divide by, so it keeps the instrument price (or zero
+ # when even that is missing) instead of resolving value per unit.
def holding_price(holding, quantity)
price = parse_decimal(holding["instrument_price"])
currency = @sharesight_account.holding_currencies[holding["id"].to_s]
return [ currency, price ] if currency && price
+ return [ currency || portfolio_currency, price || BigDecimal("0") ] if quantity.zero?
value = parse_decimal(holding["value"])
return [ portfolio_currency, value / quantity ] if value
[ portfolio_currency, price ]
end
+
+ # Whether it has units on the last snapshot, in any currency, since the
+ # open row may have been priced in another one. A row the user remapped to
+ # another security still counts through its provider security.
+ def still_held?(security)
+ return false unless @last_snapshot_date
+
+ held = account.holdings
+ .where(date: @last_snapshot_date, account_provider_id: @sharesight_account.account_provider&.id)
+ .where.not(qty: 0)
+ held.where(security: security).or(held.where(provider_security: security)).exists?
+ end
end
diff --git a/app/models/sharesight_account/processor.rb b/app/models/sharesight_account/processor.rb
index b31e70f1a9..4003233377 100644
--- a/app/models/sharesight_account/processor.rb
+++ b/app/models/sharesight_account/processor.rb
@@ -5,8 +5,15 @@ class SharesightAccount::Processor
attr_reader :sharesight_account
+ # Settlement accounts the router booked counterparts into, or removed stale
+ # counterparts from, on this run — kept even when a later step fails, since
+ # the router's writes are already committed and those balances still need
+ # their own sync.
+ attr_reader :touched_accounts
+
def initialize(sharesight_account)
@sharesight_account = sharesight_account
+ @touched_accounts = []
end
def process
@@ -17,13 +24,17 @@ class SharesightAccount::Processor
activities = SharesightAccount::ActivitiesProcessor.new(sharesight_account)
result = activities.process
router = SharesightAccount::CashRouter.new(sharesight_account, activities.movements)
- router.route
+ begin
+ router.route
+ ensure
+ @touched_accounts = router.touched_accounts.to_a
+ end
SharesightAccount::FundingMirror.new(sharesight_account).mirror
update_account_balance!
account.broadcast_sync_complete
- result.merge(notices: router.notices + drift_notices)
+ result.merge(notices: router.notices + drift_notices, settlement_accounts: @touched_accounts)
end
private
diff --git a/app/models/sharesight_item.rb b/app/models/sharesight_item.rb
index 98783040a2..65009d8ea2 100644
--- a/app/models/sharesight_item.rb
+++ b/app/models/sharesight_item.rb
@@ -52,8 +52,9 @@ class SharesightItem < ApplicationRecord
next unless account
next if account.pending_deletion? || account.disabled?
+ processor = SharesightAccount::Processor.new(sharesight_account)
begin
- result = SharesightAccount::Processor.new(sharesight_account).process
+ result = processor.process
results << { sharesight_account_id: sharesight_account.id, success: true, result: result }
rescue => e
DebugLogEntry.capture(
@@ -65,19 +66,38 @@ class SharesightItem < ApplicationRecord
provider_key: "sharesight",
account_provider_id: sharesight_account.account_provider&.id
)
- results << { sharesight_account_id: sharesight_account.id, success: false, error: e.message }
+ # The router's writes are already committed, so the settlement
+ # accounts it touched still need their own sync even though this
+ # account failed — a retry can't rediscover a counterpart that was
+ # already removed.
+ results << {
+ sharesight_account_id: sharesight_account.id,
+ success: false,
+ error: e.message,
+ settlement_accounts: processor.touched_accounts
+ }
end
end
end
- def schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil)
- accounts.reject { |account| account.pending_deletion? || account.disabled? }.each_with_object([]) do |account, results|
+ def schedule_account_syncs(parent_sync: nil, window_start_date: nil, window_end_date: nil, extra_accounts: [])
+ portfolio_accounts = accounts
+ portfolio_account_ids = portfolio_accounts.map(&:id).to_set
+ (portfolio_accounts + Array(extra_accounts)).uniq.reject { |account| account.pending_deletion? || account.disabled? }.each_with_object([]) do |account, results|
begin
- account.sync_later(
- parent_sync: parent_sync,
- window_start_date: window_start_date,
- window_end_date: window_end_date
- )
+ if portfolio_account_ids.include?(account.id)
+ account.sync_later(
+ parent_sync: parent_sync,
+ window_start_date: window_start_date,
+ window_end_date: window_end_date
+ )
+ else
+ # Settlement accounts the router just changed can carry entries
+ # dated before this sync's window, so they sync over the full range
+ # instead of the window — otherwise the pre-window change never
+ # reaches their balance.
+ account.sync_later(parent_sync: parent_sync)
+ end
results << { account_id: account.id, success: true }
rescue => e
DebugLogEntry.capture(
diff --git a/app/models/sharesight_item/syncer.rb b/app/models/sharesight_item/syncer.rb
index 317d061a1c..6bffe3ea14 100644
--- a/app/models/sharesight_item/syncer.rb
+++ b/app/models/sharesight_item/syncer.rb
@@ -39,7 +39,8 @@ class SharesightItem::Syncer
sharesight_item.schedule_account_syncs(
parent_sync: sync,
window_start_date: sync.window_start_date,
- window_end_date: sync.window_end_date
+ window_end_date: sync.window_end_date,
+ extra_accounts: settlement_accounts(results)
)
account_ids = linked_accounts.includes(:account).filter_map { |sa| sa.account&.id }
@@ -79,4 +80,15 @@ class SharesightItem::Syncer
details: notices
)
end
+
+ # Manual settlement accounts the router just booked into, or removed stale
+ # counterparts from. Their stored balance changed, so they need their own
+ # sync once the portfolio accounts are done — including when the portfolio
+ # account itself failed after the router's writes were committed, since a
+ # retry can't rediscover a counterpart that was already removed.
+ def settlement_accounts(results)
+ Array(results).flat_map do |result|
+ Array(result.dig(:result, :settlement_accounts)) + Array(result[:settlement_accounts])
+ end.compact.uniq
+ end
end
diff --git a/test/models/sharesight_account/cash_router_test.rb b/test/models/sharesight_account/cash_router_test.rb
index 5e0a69f507..d65c8c2fa5 100644
--- a/test/models/sharesight_account/cash_router_test.rb
+++ b/test/models/sharesight_account/cash_router_test.rb
@@ -123,6 +123,28 @@ class SharesightAccount::CashRouterTest < ActiveSupport::TestCase
assert_equal BigDecimal("-30"), @bank.entries.find_by!(external_id: "sharesight_counterpart_#{@sharesight_account.id}_payout_50").amount
end
+ test "a manual settlement account that took counterparts is reported for its own sync" do
+ result = process
+
+ assert_equal [ @bank ], result[:settlement_accounts]
+ end
+
+ test "a bank-fed settlement account is not reported" do
+ bank_fed!
+
+ assert_empty process[:settlement_accounts]
+ end
+
+ test "switching manual settlement accounts reports both the old and the new account" do
+ process
+ ing = @family.accounts.create!(name: "ING Savings", balance: 0, currency: "AUD", accountable: Depository.new)
+ @sharesight_account.update!(settlement_account: ing)
+
+ result = process
+
+ assert_equal [ @bank, ing ].map(&:id).sort, result[:settlement_accounts].map(&:id).sort
+ end
+
test "a reinvested dividend's leftover is linked when the bank feed shows it" do
bank_fed!
@sharesight_account.update!(raw_payouts_payload: [ REINVESTED ])
@@ -203,6 +225,17 @@ class SharesightAccount::CashRouterTest < ActiveSupport::TestCase
assert_linked offset("trade_1"), ing.entries.find_by!(external_id: "sharesight_counterpart_#{@sharesight_account.id}_trade_1")
end
+ test "an account that lost a counterpart is reported even after it is linked to a bank feed" do
+ process
+ ing = @family.accounts.create!(name: "ING Savings", balance: 0, currency: "AUD", accountable: Depository.new)
+ @sharesight_account.update!(settlement_account: ing)
+ bank_fed!
+
+ result = process
+
+ assert_includes result[:settlement_accounts], @bank
+ end
+
test "untracked cash is offset without a counterpart anywhere" do
@sharesight_account.update!(cash_mode: "untracked", settlement_account: nil)
diff --git a/test/models/sharesight_account/processor_test.rb b/test/models/sharesight_account/processor_test.rb
index e936fef345..28dc5d861b 100644
--- a/test/models/sharesight_account/processor_test.rb
+++ b/test/models/sharesight_account/processor_test.rb
@@ -87,6 +87,8 @@ class SharesightAccount::ProcessorTest < ActiveSupport::TestCase
end
test "imports held units at Sharesight's price in each instrument's currency" do
+ # OLD was held until yesterday, so today's zero row is written to close it out.
+ seed_holding("OLD", qty: 50, price: 40, date: Date.current - 1)
process
holdings = @account.holdings.where(date: Date.current).includes(:security).to_h do |holding|
@@ -95,11 +97,103 @@ class SharesightAccount::ProcessorTest < ActiveSupport::TestCase
assert_equal({
"VAS" => [ BigDecimal("100"), BigDecimal("105"), "AUD" ],
"AAPL" => [ BigDecimal("10"), BigDecimal("290"), "USD" ],
+ # Fully sold: a zero-quantity row for today, so the position drops out
+ # of current holdings instead of lingering on the previous day's row.
+ "OLD" => [ BigDecimal("0"), BigDecimal("40"), "AUD" ],
"BTC" => [ BigDecimal("0.25"), BigDecimal("116367.4"), "AUD" ]
}, holdings)
assert_equal "XNAS", @account.holdings.joins(:security).find_by(securities: { ticker: "AAPL" }).security.exchange_operating_mic
end
+ test "a fully sold holding leaves current holdings" do
+ seed_holding("OLD", qty: 50, price: 40, date: Date.current - 1)
+ # Only the sold holding in the payload: without the zero row, no
+ # holdings are written for today, so current holdings would fall back
+ # to yesterday's row and still list OLD.
+ sold_holding = HOLDINGS.find { |holding| holding.dig("instrument", "code") == "OLD" }
+ @sharesight_account.update!(raw_holdings_payload: [ sold_holding ])
+ process
+
+ assert_not_includes @account.reload.current_holdings.map { |holding| holding.security.ticker }, "OLD"
+ end
+
+ test "a holding sold long ago gains no new zero row on the next sync" do
+ # The sale was already closed out by an earlier sync's zero row.
+ seed_holding("OLD", qty: 0, price: 40, date: Date.current - 1)
+ process
+
+ old_rows = @account.holdings.where(security: Security.find_by!(ticker: "OLD"))
+ assert_equal 1, old_rows.count
+ assert_nil old_rows.find_by(date: Date.current)
+ end
+
+ test "a holding already sold before the first sync writes no zero row" do
+ process
+
+ assert_empty @account.holdings.where(security: Security.find_by!(ticker: "OLD"))
+ end
+
+ test "a holding sold between two syncs on the same day is zeroed instead of keeping its morning quantity" do
+ morning = HOLDINGS.map do |holding|
+ holding.dig("instrument", "code") == "OLD" ? holding.merge("quantity" => 10.0, "value" => 400.0) : holding
+ end
+ @sharesight_account.update!(raw_holdings_payload: morning)
+ process
+
+ sold = @account.holdings.find_by!(date: Date.current, security: Security.find_by!(ticker: "OLD"))
+ assert_equal BigDecimal("10"), sold.qty
+
+ @sharesight_account.update!(raw_holdings_payload: HOLDINGS)
+ process
+
+ assert_equal BigDecimal("0"), sold.reload.qty
+ assert_not_includes @account.reload.current_holdings.map { |holding| holding.security.ticker }, "OLD"
+ end
+
+ test "a sold holding is closed even if it was held in another currency" do
+ # With no instrument price, a held USD position is priced from its value in AUD.
+ aapl = HOLDINGS.find { |holding| holding.dig("instrument", "code") == "AAPL" }.merge("instrument_price" => nil)
+ travel_to(1.day.ago) do
+ @sharesight_account.update!(raw_holdings_payload: [ aapl.merge("quantity" => 10.0, "value" => 4500.0) ])
+ process
+ end
+ assert_equal [ "AUD" ], @account.holdings.pluck(:currency)
+
+ @sharesight_account.update!(raw_holdings_payload: [ aapl.merge("quantity" => 0.0, "value" => 0.0) ])
+ process
+
+ assert_empty @account.reload.current_holdings
+ end
+
+ test "a remapped holding is closed when it's sold" do
+ sold = HOLDINGS.find { |holding| holding.dig("instrument", "code") == "OLD" }
+ travel_to(1.day.ago) do
+ @sharesight_account.update!(raw_holdings_payload: [ sold.merge("quantity" => 10.0, "value" => 400.0) ])
+ process
+ end
+ held = @account.holdings.find_by!(security: Security.find_by!(ticker: "OLD"))
+ held.remap_security!(Security.create!(ticker: "OLDX", exchange_operating_mic: "XASX"))
+
+ @sharesight_account.update!(raw_holdings_payload: [ sold ])
+ process
+
+ assert_empty @account.reload.current_holdings
+ end
+
+ test "a holding missing from the last snapshot gets no zero row" do
+ # OLD's last row is older than the last snapshot, so current holdings already leaves it out.
+ seed_holding("OLD", qty: 50, price: 40, date: Date.current - 30)
+ seed_holding("VAS", qty: 100, price: 105, date: Date.current - 1)
+ sold = HOLDINGS.find { |holding| holding.dig("instrument", "code") == "OLD" }
+ vas = HOLDINGS.find { |holding| holding.dig("instrument", "code") == "VAS" }
+ @sharesight_account.update!(raw_holdings_payload: [ sold, vas.merge("limited" => true) ])
+
+ process
+
+ assert_nil @account.holdings.find_by(date: Date.current)
+ assert_equal [ "VAS" ], @account.reload.current_holdings.map { |holding| holding.security.ticker }
+ end
+
test "books buys, sells and opening balances, skipping splits" do
result = process
@@ -283,6 +377,16 @@ class SharesightAccount::ProcessorTest < ActiveSupport::TestCase
SharesightAccount::Processor.new(@sharesight_account.reload).process
end
+ # A Sharesight holding row as an earlier sync left it, so the zero-row
+ # gate has something to look at.
+ def seed_holding(ticker, qty:, price:, date:)
+ @account.holdings.create!(
+ security: Security.find_by!(ticker: ticker),
+ qty: qty, price: price, amount: qty * price, currency: "AUD",
+ date: date, account_provider_id: @sharesight_account.account_provider&.id
+ )
+ end
+
def trade(external_id)
@account.entries.find_by!(external_id: external_id, entryable_type: "Trade")
end
diff --git a/test/models/sharesight_item/syncer_test.rb b/test/models/sharesight_item/syncer_test.rb
index 79c1fa20d1..cde979b423 100644
--- a/test/models/sharesight_item/syncer_test.rb
+++ b/test/models/sharesight_item/syncer_test.rb
@@ -22,4 +22,64 @@ class SharesightItem::SyncerTest < ActiveSupport::TestCase
assert @item.reload.pending_account_setup?
end
+
+ test "a manual settlement account that took counterparts gets its own sync" do
+ bank, account, sharesight_account = setup_portfolio_with_manual_settlement
+ @item.expects(:import_latest_data)
+ SharesightItem::Syncer.new(@item).perform_sync(@sync)
+
+ assert bank.entries.find_by(external_id: "sharesight_counterpart_#{sharesight_account.id}_trade_1"),
+ "the router never booked the counterpart into the settlement account"
+ assert bank.syncs.exists?, "the manual settlement account was never synced"
+ assert account.syncs.exists?
+ end
+
+ test "a settlement account touched before a portfolio failure still gets its own sync" do
+ bank, _account, sharesight_account = setup_portfolio_with_manual_settlement
+ @item.expects(:import_latest_data)
+ # The broadcast fails after the router already booked the counterpart.
+ Account.any_instance.stubs(:broadcast_sync_complete).raises(RuntimeError, "broadcast boom")
+
+ SharesightItem::Syncer.new(@item).perform_sync(@sync)
+
+ assert bank.entries.find_by(external_id: "sharesight_counterpart_#{sharesight_account.id}_trade_1"),
+ "the router never booked the counterpart into the settlement account"
+ assert bank.syncs.exists?, "the settlement account was never synced after the portfolio failed"
+ end
+
+ test "a settlement account touched by the router syncs over the full range, not the sync window" do
+ bank, _account, sharesight_account = setup_portfolio_with_manual_settlement
+ @item.expects(:import_latest_data)
+ windowed_sync = @item.syncs.create!(window_start_date: Date.new(2026, 9, 1), window_end_date: Date.current)
+
+ SharesightItem::Syncer.new(@item).perform_sync(windowed_sync)
+
+ # The portfolio account itself is queued for a full-range sync via
+ # set_current_balance, so it never receives the narrowed window.
+ assert_nil bank.syncs.first.window_start_date, "the settlement account was scheduled with the narrowed window"
+ end
+
+ private
+
+ # A linked Sharesight portfolio whose trades settle into a manual account.
+ def setup_portfolio_with_manual_settlement
+ bank = @item.family.accounts.create!(name: "Macquarie CMA", balance: 0, currency: "AUD", accountable: Depository.new)
+ account = @item.family.accounts.create!(name: "Shares", balance: 0, currency: "AUD", accountable: Investment.new)
+ sharesight_account = @item.sharesight_accounts.create!(
+ name: "Shares", sharesight_account_id: "42", currency: "AUD", current_balance: 2100, cash_balance: 0,
+ raw_holdings_payload: [
+ { "id" => 1, "quantity" => 20.0, "value" => 2100.0, "instrument_price" => 105.0,
+ "instrument" => { "code" => "VAS", "market_code" => "ASX", "currency_code" => "AUD" }, "instrument_currency" => { "code" => "AUD" } }
+ ],
+ raw_trades_payload: [
+ { "id" => 1, "transaction_type" => "BUY", "transaction_date" => "2026-09-01", "symbol" => "VAS", "market" => "ASX",
+ "quantity" => 10, "price" => 100.0, "exchange_rate" => 1.0, "holding_id" => 1, "state" => "confirmed" }
+ ],
+ raw_payouts_payload: [],
+ cash_mode: "settlement", settlement_account: bank
+ )
+ sharesight_account.ensure_account_provider!(account)
+ Security.find_or_create_by!(ticker: "VAS", exchange_operating_mic: "XASX")
+ [ bank, account, sharesight_account ]
+ end
end