Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(trade-republic): book order cash legs at the detail total (#4104)

Simone3c476cf2000a
diff --git a/app/models/trade_republic_account/activities_processor.rb b/app/models/trade_republic_account/activities_processor.rb
index 9476650064..f6322d03d1 100644
--- a/app/models/trade_republic_account/activities_processor.rb
+++ b/app/models/trade_republic_account/activities_processor.rb
@@ -8,6 +8,7 @@ class TradeRepublicAccount::ActivitiesProcessor
ROUND_UP_EVENT_TYPE = "SPARE_CHANGE_AGGREGATE"
SAVINGS_PLAN_INVOICE_EVENT_TYPE = "SAVINGS_PLAN_INVOICE_CREATED"
SAVINGS_PLAN_EXECUTION_EVENT_TYPES = %w[TRADING_SAVINGSPLAN_EXECUTED SAVINGS_PLAN_EXECUTED].freeze
+ SETTLEMENT_AMOUNT_TOLERANCE = BigDecimal("0.01")
ACTIVITY_LABELS_BY_KEY = {
"contribution" => "Contribution",
"withdrawal" => "Withdrawal",
@@ -363,23 +364,28 @@ class TradeRepublicAccount::ActivitiesProcessor
true
end
- # The timeline list amount is what Trade Republic booked against the cash
- # balance, fees and taxes included. Unlike cash movements (see
+ # The cash leg of an order. The detail total ("Total" / "Summe") is what
+ # Trade Republic books against the cash balance, fees and taxes included.
+ # The timeline list amount usually matches it, but not for some sales with
+ # withheld tax (#4057), so the detail total wins once the detail is
+ # fetched; before that, `amount` is the list amount anyway.
+ # The list amount still gives the direction: unlike cash movements (see
# import_cash_movement), order executions carry a consistent sign across
- # topics: negative for buys, positive for sales. Payloads that only carry
- # a magnitude fall back to the traded quantity; without either signal the
- # direction is unknown and nothing is booked.
+ # topics, negative for buys and positive for sales. Payloads that only
+ # carry a magnitude fall back to the traded quantity; without either
+ # signal the direction is unknown and nothing is booked.
# Buys count as investment contributions in budgets; sale proceeds are a
# funds movement rather than income. Neither gets a category.
def import_order_settlement(event, detail, external_id, date)
signed_amount = parse_decimal(detail[:signed_amount])
- amount = signed_amount || parse_decimal(detail[:amount])
+ amount = parse_decimal(detail[:amount])&.nonzero? || signed_amount
return false unless amount && !amount.zero?
quantity = parse_decimal(detail[:quantity])
return false if signed_amount.nil? && (quantity.nil? || quantity.zero?)
outflow = signed_amount ? signed_amount.negative? : quantity.positive?
+ capture_settlement_amount_mismatch(event, external_id, signed_amount, outflow ? amount.abs : -amount.abs)
import_cash_movement(
event,
@@ -394,6 +400,28 @@ class TradeRepublicAccount::ActivitiesProcessor
)
end
+ # Records an order whose list amount and detail total differ, when the
+ # booked amount changes (a new entry or a correction), not on every sync.
+ def capture_settlement_amount_mismatch(event, external_id, list_amount, booked_amount)
+ return if list_amount.nil? || (list_amount.abs - booked_amount.abs).abs <= SETTLEMENT_AMOUNT_TOLERANCE
+ return if account.entries.where(external_id: external_id, source: "trade_republic").pick(:amount) == booked_amount
+
+ DebugLogEntry.capture(
+ category: "sync",
+ level: "info",
+ message: "Trade Republic order booked at its detail total instead of the timeline amount",
+ source: "trade_republic",
+ family: @trade_republic_account.trade_republic_item.family,
+ provider_key: "trade_republic",
+ account: account,
+ metadata: {
+ event_id: event[:id],
+ timeline_amount: list_amount.abs.to_s("F"),
+ detail_amount: booked_amount.abs.to_s("F")
+ }
+ )
+ end
+
# The label key names the entry (in the sync's locale) when Trade Republic
# sends no title, and picks the stored activity label.
def import_labeled_cash_movement(event, detail, external_id, date, label_key, sign:, kind: nil, settles_trade: false)
diff --git a/test/models/trade_republic_account_activities_processor_test.rb b/test/models/trade_republic_account_activities_processor_test.rb
index d5e9b32fda..e16335e03c 100644
--- a/test/models/trade_republic_account_activities_processor_test.rb
+++ b/test/models/trade_republic_account_activities_processor_test.rb
@@ -1022,6 +1022,49 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCase
assert find_trade("trade_republic_event_evt_btc")
end
+ test "a sale's cash leg uses the detail total when the timeline amount differs" do
+ cash_account, cash_sure = create_linked_cash_account!
+ # A sale with withheld tax (#4057): the timeline list says 81.33, while the
+ # detail total and the account statement say 80.87.
+ sell = net_sale_event(detail_amount: "80.87")
+ @tr_account.update!(raw_timeline_payload: [ sell ])
+
+ assert_difference -> { DebugLogEntry.where(message: SETTLEMENT_MISMATCH_MESSAGE).count }, 1 do
+ TradeRepublicAccount::ActivitiesProcessor.new(@tr_account.reload).process
+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process
+ end
+
+ assert_equal BigDecimal("-80.87"), find_trade("trade_republic_event_evt_net_sell").amount
+ assert_equal BigDecimal("-80.87"), cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_net_sell").amount
+ assert_equal BigDecimal("80.87"), @account.entries.find_by!(external_id: "trade_republic_settlement_evt_net_sell").amount
+ assert_equal 0, @account.entries.sum(:amount)
+
+ log = DebugLogEntry.where(message: SETTLEMENT_MISMATCH_MESSAGE).order(:created_at).last
+ assert_equal "81.33", log.metadata["timeline_amount"]
+ assert_equal "80.87", log.metadata["detail_amount"]
+
+ assert_no_difference -> { DebugLogEntry.where(message: SETTLEMENT_MISMATCH_MESSAGE).count } do
+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process
+ end
+ end
+
+ test "a sale booked before its detail arrived is corrected to the detail total" do
+ cash_account, cash_sure = create_linked_cash_account!
+ # Without the detail, the amount is the timeline list amount.
+ @tr_account.update!(raw_timeline_payload: [ net_sale_event(detail_amount: "81.33") ])
+
+ assert_no_difference -> { DebugLogEntry.where(message: SETTLEMENT_MISMATCH_MESSAGE).count } do
+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process
+ end
+ assert_equal BigDecimal("-81.33"), cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_net_sell").amount
+
+ @tr_account.update!(raw_timeline_payload: [ net_sale_event(detail_amount: "80.87") ])
+ TradeRepublicAccount::ActivitiesProcessor.new(cash_account.reload).process
+
+ assert_equal BigDecimal("-80.87"), cash_sure.entries.find_by!(external_id: "trade_republic_event_evt_net_sell").amount
+ assert_equal 1, cash_sure.entries.where(external_id: "trade_republic_event_evt_net_sell").count
+ end
+
test "split accounts settle buys and sells against the cash account" do
cash_account, cash_sure = create_linked_cash_account!
buy = order_execution_detail(event_id: "evt_settle_buy", quantity: "2.0", isin: "IE00B5BMR087", amount: "1024.92")
@@ -1906,4 +1949,13 @@ class TradeRepublicAccountActivitiesProcessorTest < ActiveSupport::TestCase
def find_trade(external_id)
@account.entries.find_by(external_id: external_id)
end
+
+ SETTLEMENT_MISMATCH_MESSAGE = "Trade Republic order booked at its detail total instead of the timeline amount"
+
+ # The timeline list amount stays 81.33; detail_amount is what the event's
+ # detail reports as its total.
+ def net_sale_event(detail_amount:)
+ order_execution_detail(event_id: "evt_net_sell", quantity: "-3.90625", isin: "GB00BD9G2S12", amount: detail_amount)
+ .deep_merge(title: "Gates Industrial", subtitle: "Sell Order", detail: { signed_amount: 81.33, fees: "1.0", taxes: "1.72" })
+ end
end