The personal finance app for everyone (by everyone)
Ruby
fix(reports): a transfer out is not a sale (#3192)
buzzromain4fbc0a4eb175
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex d02169a59e..dd498fb6b4 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -521,6 +521,12 @@ class ReportsController < ApplicationController.where(entries: { date: @period.date_range }).merge(Account.included_in_reports).where("trades.qty < 0")+ # A transfer out has the same negative quantity as a sale and would be+ # counted and listed as one. Nothing was sold, so it belongs in neither.+ .where(+ "trades.investment_activity_label IS NULL OR trades.investment_activity_label NOT IN (?)",+ Trade::INTERNAL_MOVEMENT_LABELS+ ).includes(:security, entry: { account: :accountable }).to_adiff --git a/app/models/trade.rb b/app/models/trade.rbindex a0c6df58a5..a07575b6a1 100644--- a/app/models/trade.rb+++ b/app/models/trade.rb@@ -10,6 +10,21 @@ class Trade < ApplicationRecord# Use the same activity labels as TransactionACTIVITY_LABELS = Transaction::ACTIVITY_LABELS.dup.freeze+ # The labels that mean the asset went somewhere else you own rather than+ # being bought or sold.+ #+ # Deliberately NOT `Transaction::INTERNAL_MOVEMENT_LABELS`, which also holds+ # "Exchange". On cash that means a currency exchange and is internal; on a+ # security the label covers "currency **or security** exchanges"+ # (docs/onboarding/guide.md), and a security-for-security exchange can+ # dispose of an appreciated asset.+ #+ # The two errors are not symmetrical. Listing a movement that was not a sale+ # is visible and correctable; erasing a realized gain is neither — it simply+ # is not there. So only labels that unambiguously preserve ownership are+ # excluded, and an ambiguous one is left where the user can see it.+ INTERNAL_MOVEMENT_LABELS = %w[Transfer Sweep\ In Sweep\ Out].freeze+validates :qty, presence: truevalidates :price, :currency, presence: truevalidates :investment_activity_label, inclusion: { in: ACTIVITY_LABELS }, allow_nil: true@@ -44,6 +59,12 @@ class Trade < ApplicationRecordqty.negative?end+ # A negative quantity that left for another account you own. It looks exactly+ # like a sale — same sign, same shape — and only the label tells them apart.+ def internal_movement?+ INTERNAL_MOVEMENT_LABELS.include?(investment_activity_label)+ end+class << selfdef build_name(type, qty, ticker)prefix = type == "buy" ? "Buy" : "Sell"@@ -91,6 +112,10 @@ class Trade < ApplicationRecorddef calculate_realized_gain_lossreturn nil unless sell?+ # Moving an asset to another account you own realises nothing. Without+ # this the cost basis is compared against the day's price and the+ # difference is booked as a gain the user never made.+ return nil if internal_movement?# Use preloaded holdings if available (set by reports controller to avoid N+1)# Treat defined-but-empty preload as authoritative to prevent DB fallbackdiff --git a/test/controllers/reports_controller_test.rb b/test/controllers/reports_controller_test.rbindex 442efae1d1..62e1031ee7 100644--- a/test/controllers/reports_controller_test.rb+++ b/test/controllers/reports_controller_test.rb@@ -598,4 +598,31 @@ class ReportsControllerTest < ActionDispatch::IntegrationTestassert_select "button[disabled][aria-label=?]", I18n.t("reports.index.next_period")end++ test "a transfer out is not listed among the period's sales" do+ account = @family.accounts.create!(name: "Wallet", balance: 100, currency: "USD",+ accountable: Investment.new)+ security = Security.find_or_create_by!(ticker: "MOVE") { |sec| sec.name = "Movable" }+ Holding.create!(account: account, security: security, date: 10.days.ago.to_date,+ qty: 100, price: 2, amount: 200, currency: "USD", cost_basis: 1)++ %w[Transfer Sell].each do |label|+ account.entries.create!(+ date: 3.days.ago.to_date, name: "out #{label}", amount: 0, currency: "USD",+ entryable: Trade.new(security: security, qty: -40, price: 3, currency: "USD",+ investment_activity_label: label)+ )+ end++ # `period_type`, not `period` — the controller reads the former, so the+ # latter silently fell back to the current month and the trades dated+ # three days ago dropped out of range on the 1st to the 3rd.+ get reports_path(period_type: :custom, start_date: 30.days.ago.to_date, end_date: Date.current)+ assert_response :success++ # A transfer out carries the same negative quantity as a sale. Counting it+ # as one both inflates the number of sales and books a gain nobody made.+ assert_match I18n.t("reports.investment_performance.sells_count", count: 1), response.body+ assert_no_match(/#{Regexp.escape(I18n.t("reports.investment_performance.sells_count", count: 2))}/, response.body)+ endenddiff --git a/test/models/trade_test.rb b/test/models/trade_test.rbindex 6223a5fc7a..a81905230a 100644--- a/test/models/trade_test.rb+++ b/test/models/trade_test.rb@@ -93,4 +93,69 @@ class TradeTest < ActiveSupport::TestCaseassert_equal BigDecimal("1.1234567890"), trade.priceend++ test "a transfer out realises nothing, however it is priced" do+ account, security = position_with_known_cost_basis++ moved = build_negative_trade(account, security, label: "Transfer")+ sold = build_negative_trade(account, security, label: "Sell")++ # Same sign, same shape, same price — only the label separates a sale from+ # coins walking to another wallet you own.+ assert_nil moved.realized_gain_loss+ assert_not_nil sold.realized_gain_loss+ end++ test "every internal movement label realises nothing" do+ account, security = position_with_known_cost_basis++ Trade::INTERNAL_MOVEMENT_LABELS.each do |label|+ trade = build_negative_trade(account, security, label: label)+ assert_nil trade.realized_gain_loss, "#{label} should not realise a gain"+ end+ end++ private+ # A position whose cost basis is known, which is what makes a fabricated+ # gain possible: without one, realized_gain_loss returns nil for any reason.+ def position_with_known_cost_basis+ family = families(:empty)+ account = family.accounts.create!(name: "Wallet", balance: 100, currency: "USD",+ accountable: Investment.new)+ security = Security.find_or_create_by!(ticker: "MOVE") { |s| s.name = "Movable" }+ Holding.create!(account: account, security: security, date: 10.days.ago.to_date,+ qty: 100, price: 2, amount: 200, currency: "USD", cost_basis: 1)++ [ account, security ]+ end++ def build_negative_trade(account, security, label:)+ account.entries.create!(+ date: 3.days.ago.to_date, name: "out #{label}", amount: 0, currency: "USD",+ entryable: Trade.new(security: security, qty: -40, price: 3, currency: "USD",+ investment_activity_label: label)+ ).entryable+ end++ # "Exchange" means a currency exchange on cash and is internal there. On a+ # security the label covers currency *or security* exchanges, and a+ # security-for-security exchange can dispose of an appreciated asset — so+ # borrowing Transaction's list erased a realized gain with nothing to show+ # for it.+ test "an exchange is not treated as an internal movement on a trade" do+ assert_not Trade.new(investment_activity_label: "Exchange").internal_movement?+ end++ test "the labels that unambiguously preserve ownership still are" do+ %w[Transfer Sweep\ In Sweep\ Out].each do |label|+ assert Trade.new(investment_activity_label: label).internal_movement?, label+ end+ end++ # The two lists are deliberately different; this fails if one is ever+ # aliased back onto the other.+ test "a trade does not borrow the cash list" do+ assert_includes Transaction::INTERNAL_MOVEMENT_LABELS, "Exchange"+ assert_not_includes Trade::INTERNAL_MOVEMENT_LABELS, "Exchange"+ endend