The personal finance app for everyone (by everyone)
Ruby
Report open lots in the API, assistant and export (#4904)
jaysbeekay078c11ba0282
diff --git a/app/controllers/api/v1/trades_controller.rb b/app/controllers/api/v1/trades_controller.rbindex f94c566ca0..fdf77bc1b5 100644--- a/app/controllers/api/v1/trades_controller.rb+++ b/app/controllers/api/v1/trades_controller.rb@@ -12,7 +12,7 @@ class Api::V1::TradesController < Api::V1::BaseControllertrades_query = family.trades.visibletrades_query = apply_filters(trades_query)- trades_query = trades_query.includes({ entry: :account }, :security, :category).reverse_chronological+ trades_query = trades_query.includes({ entry: :account }, :security, :category, :lot_source_entry).reverse_chronological@pagy, @trades = pagy(trades_query,diff --git a/app/models/assistant/function/get_holdings.rb b/app/models/assistant/function/get_holdings.rbindex f349087ec9..ff5fbb74a5 100644--- a/app/models/assistant/function/get_holdings.rb+++ b/app/models/assistant/function/get_holdings.rb@@ -21,6 +21,11 @@ class Assistant::Function::GetHoldings < Assistant::FunctionNote: This function only returns holdings from Investment and Crypto accounts.+ Each holding's `lots` lists the parcels it is made of, oldest first:+ when each was acquired, how many units are still held and what each+ unit cost (`opening` is units held before the first recorded trade).+ It is null when the recorded lots do not add up to the holding.+Note on pagination:This function can be paginated. You can expect the following properties in the response:@@ -92,6 +97,9 @@ class Assistant::Function::GetHoldings < Assistant::Functiontotal_value = holdings_query.sum(:amount)+ paginated_holdings = paginated_holdings.to_a+ open_lots = Holding.open_lots_for(paginated_holdings)+normalized_holdings = paginated_holdings.map do |holding|{ticker: holding.ticker,@@ -104,6 +112,7 @@ class Assistant::Function::GetHoldings < Assistant::Functionweight: holding.weight&.round(2),average_cost: holding.avg_cost&.to_f,formatted_average_cost: holding.avg_cost&.format,+ lots: open_lots[holding.id]&.map { |lot| normalized_lot(lot) },account: holding.account.name,date: holding.date}@@ -120,6 +129,20 @@ class Assistant::Function::GetHoldings < Assistant::Functionendprivate+ # One open lot of a position: the opening lot (units held before the first+ # trade) has no acquisition date and, unless the user set one, no cost.+ def normalized_lot(lot)+ unit_cost = lot.unit_cost && Money.new(lot.unit_cost, lot.currency)+ {+ opening: lot.opening?,+ acquired_on: lot.acquired_on,+ quantity: lot.qty.to_f,+ unit_cost: unit_cost&.amount&.to_f,+ formatted_unit_cost: unit_cost&.format,+ manual_cost: lot.manual_cost?+ }+ end+def default_page_sizeself.class.default_page_sizeenddiff --git a/app/models/family/data_exporter.rb b/app/models/family/data_exporter.rbindex 8b3837c145..dfb58c697b 100644--- a/app/models/family/data_exporter.rb+++ b/app/models/family/data_exporter.rb@@ -484,8 +484,18 @@ class Family::DataExporter}.to_jsonend- # Export trades with full data- @family.trades.includes(:security, entry: :account).find_each do |trade|+ # Export trades with full data. Lots are rebuilt from trades on sync, so+ # a trade carries only what the user set on its lot: the lot's total+ # cost, and, on a sale, the trade whose lot it names to sell from. Trades+ # go in the order Holding::PortfolioCache#trades replays them: by date,+ # then as entered, buys before sales entered together. An import stamps+ # entries in file order, so the file's order is the imported replay+ # order, and a named lot, which replays before its sale, is always+ # ahead of it, even when an import arrives in chunks.+ lot_total_costs = HoldingLot.derived.joins(:account).where(accounts: { family_id: @family.id })+ .where.not(manual_total_cost: nil).pluck(:source_entry_id, :manual_total_cost).to_h+ @family.trades.includes(:security, :lot_source_entry, entry: :account)+ .order(Arel.sql("entries.date ASC, entries.created_at ASC, CASE WHEN trades.qty < 0 THEN 1 ELSE 0 END ASC, entries.id ASC")).each do |trade|lines << {type: "Trade",data: {@@ -501,6 +511,8 @@ class Family::DataExporterprice: trade.price,amount: trade.entry.amount,currency: trade.currency,+ lot_total_cost: lot_total_costs[trade.entry.id],+ lot_source_trade_id: trade.lot_source_entry&.entryable_id,created_at: trade.created_at,updated_at: trade.updated_at}diff --git a/app/models/family/data_importer.rb b/app/models/family/data_importer.rbindex d787f0630d..48cba61537 100644--- a/app/models/family/data_importer.rb+++ b/app/models/family/data_importer.rb@@ -375,9 +375,10 @@ class Family::DataImporternotes: data["notes"],status: importable_account_status(data["status"]))+ # A file from before the setting existed leaves the account's own.+ account.cost_basis_method = data["cost_basis_method"] if Account.cost_basis_methods.key?(data["cost_basis_method"])# Older exports predate the choice and keep the account's own.account.logo_selection = data["logo_selection"] if Account.logo_selections.key?(data["logo_selection"])- account.cost_basis_method = data["cost_basis_method"] if Account.cost_basis_methods.key?(data["cost_basis_method"])account.save!@@ -1169,6 +1170,8 @@ class Family::DataImporterenddef import_trades(records)+ imported = {}+records.each do |record|data = record["data"]old_id = data["id"]@@ -1219,9 +1222,80 @@ class Family::DataImporterendentry.save!+ imported[old_id] = entry+ import_lot_total_cost(entry, data["lot_total_cost"])@created_entry_ids << entry.id if createdincrement_summary("Trade", created ? :created : :updated)end++ import_lot_sources(records, imported)+ end++ # The lot is rebuilt from its trade on the next sync, which keeps a cost+ # already on the row, so the user's cost is seeded on the row now. A file+ # without one clears a cost an earlier import of this trade set. A value+ # the lot cannot hold drops the cost, not the trade.+ def import_lot_total_cost(entry, raw)+ trade = entry.trade+ # Only a buy's entry keys a lot (source_entry_id is the acquiring+ # trade's entry), so a sell never queries. A buy's lookup is per row+ # and indexed, with no chunk-wide load.+ lot = trade.qty.positive? ? HoldingLot.find_by(account_id: entry.account_id, source_entry_id: entry.id) : nil++ if raw.blank?+ lot.unlock_cost! if lot&.manual_cost?+ return+ end++ total = BigDecimal(raw.to_s, exception: false)+ return invalid_record!("Trade", "lot_total_cost", raw) unless total&.finite? && !total.negative? && trade.qty.positive?++ lot ||= HoldingLot.new(account_id: entry.account_id, source_entry: entry, security: trade.security,+ acquired_on: entry.date, qty: trade.qty, currency: entry.account.currency)+ lot.manual_total_cost = total+ invalid_record!("Trade", "lot_total_cost", raw) unless lot.save+ end++ # A sale names its lot by the acquiring trade, which the export writes+ # ahead of it: in this file, or in an earlier chunk of the same session.+ # The choice is restored as stored, whatever the account's method, since+ # an average account keeps but ignores it (Trade#lot_choices); it must+ # still be a sale, not a transfer out, naming an acquisition of its+ # security, in its account, that replays before it: an earlier date, or+ # the same date and entered no later. Entries are stamped in file order,+ # so a same-day lot listed after its sale is refused. A file without one+ # clears an earlier import's choice.+ def import_lot_sources(records, imported)+ unnamed = []++ records.each do |record|+ data = record["data"]+ row = imported[data["id"]]+ next unless row++ source_id = data["lot_source_trade_id"]+ if source_id.blank?+ unnamed << row.entryable_id+ next+ end++ source = imported[source_id] || session_imported_entry(row.account, "Trade", source_id)+ if source && lot_source_for?(row, source)+ Trade.where(id: row.entryable_id).update_all(lot_source_entry_id: source.id)+ else+ invalid_record!("Trade", "lot_source_trade_id", source_id)+ end+ end++ Trade.where(id: unnamed).where.not(lot_source_entry_id: nil).update_all(lot_source_entry_id: nil) if unnamed.any?+ end++ # The rule Trade#lot_choices applies to a sale and its lot, short of the+ # account's method and of whether the lot is still open.+ def lot_source_for?(sale, source)+ sale.trade.qty.negative? && !sale.trade.internal_movement? && source.trade.qty.positive? &&+ source.account_id == sale.account_id && source.trade.security_id == sale.trade.security_id &&+ ([ source.date, source.created_at ] <=> [ sale.date, sale.created_at ]) <= 0enddef import_holdings(records)diff --git a/app/models/holding.rb b/app/models/holding.rbindex 8cfd42c521..fcdb1386a0 100644--- a/app/models/holding.rb+++ b/app/models/holding.rb@@ -89,22 +89,37 @@ class Holding < ApplicationRecord# row, or an open lot with no cost, is unknown: the trades' pooled average# is the average method's figure, not this one.def self.fifo_avg_costs(holdings)+ open_lots = open_lots_for(holdings)++ holdings.to_h do |holding|+ open = open_lots[holding.id]&.reject(&:opening?)+ value = if open&.any? && open.none? { |lot| lot.unit_cost.nil? }+ Money.new(open.sum { |lot| lot.qty * lot.unit_cost } / open.sum(&:qty), holding.currency)+ end+ [ holding.id, value ]+ end+ end++ # Each holding's open lots, by holding id, the opening lot first and then by+ # acquisition: an array for the position's latest row while its stored lots+ # add up to it (HoldingLot.in_partition), and nil for any other row, since+ # the lots are the position as it stands. Four queries for any number of+ # holdings.+ def self.open_lots_for(holdings)return {} if holdings.empty?account_ids = holdings.map(&:account_id).uniqsecurity_ids = holdings.map(&:security_id).uniqreadable = HoldingLot.in_partition(account_ids, security_ids)latest = Holding.where(account_id: account_ids, security_id: security_ids).group(:account_id, :security_id).maximum(:date)- lots = HoldingLot.derived.where(account_id: account_ids, security_id: security_ids).where("qty > 0")+ lots = HoldingLot.where(account_id: account_ids, security_id: security_ids).where("holding_lots.qty > 0")+ .left_joins(:source_entry).select("holding_lots.*, entries.entryable_id AS trade_id")+ .order(Arel.sql("holding_lots.acquired_on ASC NULLS FIRST"), "holding_lots.created_at").group_by { |lot| [ lot.account_id, lot.security_id ] }holdings.to_h do |holding|key = [ holding.account_id, holding.security_id ]- open = lots.fetch(key, [])- value = if readable.include?(key) && latest[key] == holding.date && open.any? && open.none? { |lot| lot.unit_cost.nil? }- Money.new(open.sum { |lot| lot.qty * lot.unit_cost } / open.sum(&:qty), holding.currency)- end- [ holding.id, value ]+ [ holding.id, (lots.fetch(key, []) if readable.include?(key) && latest[key] == holding.date) ]endenddiff --git a/app/models/holding/cost_basis_tracker.rb b/app/models/holding/cost_basis_tracker.rbdeleted file mode 100644index a3e1521ff5..0000000000--- a/app/models/holding/cost_basis_tracker.rb+++ /dev/null@@ -1,7 +0,0 @@-# The pre-lot weighted-average tracker's name, kept only as the subject of the-# parity suite: cost_basis_tracker_test.rb and the oracle block in-# lot_book_test.rb assert Holding::LotBook reproduces its figures to the last-# digit. No production code constructs it — the calculators use LotBook-# directly.-class Holding::CostBasisTracker < Holding::LotBook-enddiff --git a/app/views/api/v1/holdings/_holding.json.jbuilder b/app/views/api/v1/holdings/_holding.json.jbuilderindex 27cfb4f293..11a36640f1 100644--- a/app/views/api/v1/holdings/_holding.json.jbuilder+++ b/app/views/api/v1/holdings/_holding.json.jbuilder@@ -23,5 +23,13 @@ endavg = holding.avg_costjson.avg_cost avg ? avg.format : nil+# The position's open lots on its latest row; null on any other row.+lots = local_assigns.fetch(:lots) { Holding.open_lots_for([ holding ])[holding.id] }+if lots+ json.lots lots, partial: "api/v1/holdings/lot", as: :lot+else+ json.lots nil+end+json.created_at holding.created_at.iso8601json.updated_at holding.updated_at.iso8601diff --git a/app/views/api/v1/holdings/_lot.json.jbuilder b/app/views/api/v1/holdings/_lot.json.jbuildernew file mode 100644index 0000000000..4aadd4353b--- /dev/null+++ b/app/views/api/v1/holdings/_lot.json.jbuilder@@ -0,0 +1,9 @@+# frozen_string_literal: true++json.id lot.id+json.opening lot.opening?+json.acquired_on lot.acquired_on&.iso8601+json.qty lot.qty+json.unit_cost lot.unit_cost && Money.new(lot.unit_cost, lot.currency).format+json.manual_cost lot.manual_cost?+json.trade_id lot.trade_iddiff --git a/app/views/api/v1/holdings/index.json.jbuilder b/app/views/api/v1/holdings/index.json.jbuilderindex 589fe80b1c..f6e4475515 100644--- a/app/views/api/v1/holdings/index.json.jbuilder+++ b/app/views/api/v1/holdings/index.json.jbuilder@@ -1,7 +1,8 @@# frozen_string_literal: true+lots = Holding.open_lots_for(@holdings.to_a)json.holdings @holdings do |holding|- json.partial! "holding", holding: holding+ json.partial! "holding", holding: holding, lots: lots[holding.id]endjson.pagination dodiff --git a/app/views/api/v1/trades/_trade.json.jbuilder b/app/views/api/v1/trades/_trade.json.jbuilderindex 29b3acb3a8..05d15e4e75 100644--- a/app/views/api/v1/trades/_trade.json.jbuilder+++ b/app/views/api/v1/trades/_trade.json.jbuilder@@ -9,6 +9,7 @@ json.notes trade.entry.notesjson.qty trade.qtyjson.price trade.price_money.formatjson.investment_activity_label trade.investment_activity_label+json.lot_source_trade_id trade.lot_source_entry&.entryable_idjson.account dojson.id trade.entry.account.iddiff --git a/docs/api/openapi.yaml b/docs/api/openapi.yamlindex ea27d10cf6..aec838eed8 100644--- a/docs/api/openapi.yaml+++ b/docs/api/openapi.yaml@@ -3224,6 +3224,13 @@ components:investment_activity_label:type: stringnullable: true+ lot_source_trade_id:+ type: string+ format: uuid+ nullable: true+ description: For a sale, the trade whose lot it names to sell from first.+ It applies only while the account sells by FIFO; an account that sells+ by average keeps it but sells from the pooled average.account:"$ref": "#/components/schemas/Account"security:@@ -3318,12 +3325,54 @@ components:avg_cost:type: stringnullable: true+ lots:+ type: array+ nullable: true+ description: The position's open lots, the opening lot first and then by+ acquisition. Present only on the position's latest row, while its lots+ add up to the holding; null otherwise.+ items:+ "$ref": "#/components/schemas/HoldingLot"created_at:type: stringformat: date-timeupdated_at:type: stringformat: date-time+ HoldingLot:+ type: object+ required:+ - id+ - opening+ - qty+ - manual_cost+ properties:+ id:+ type: string+ format: uuid+ opening:+ type: boolean+ description: Units held before the first imported trade+ acquired_on:+ type: string+ format: date+ nullable: true+ description: Null for the opening lot+ qty:+ type: string+ description: Units of the lot still held+ unit_cost:+ type: string+ nullable: true+ description: Formatted cost per unit; null when unknown+ manual_cost:+ type: boolean+ description: Whether the cost was set by the user+ trade_id:+ type: string+ format: uuid+ nullable: true+ description: The trade that acquired the lot; null for the opening lotHoldingCollection:type: objectrequired:diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rbindex 713d6e0083..f770738168 100644--- a/spec/swagger_helper.rb+++ b/spec/swagger_helper.rb@@ -1752,6 +1752,7 @@ RSpec.configure do |config|qty: { type: :string },price: { type: :string },investment_activity_label: { type: :string, nullable: true },+ lot_source_trade_id: { type: :string, format: :uuid, nullable: true, description: 'For a sale, the trade whose lot it names to sell from first. It applies only while the account sells by FIFO; an account that sells by average keeps it but sells from the pooled average.' },account: { '$ref' => '#/components/schemas/Account' },security: {type: :object,@@ -1807,10 +1808,29 @@ RSpec.configure do |config|}},avg_cost: { type: :string, nullable: true },+ lots: {+ type: :array,+ nullable: true,+ description: "The position's open lots, the opening lot first and then by acquisition. Present only on the position's latest row, while its lots add up to the holding; null otherwise.",+ items: { '$ref' => '#/components/schemas/HoldingLot' }+ },created_at: { type: :string, format: :'date-time' },updated_at: { type: :string, format: :'date-time' }}},+ HoldingLot: {+ type: :object,+ required: %w[id opening qty manual_cost],+ properties: {+ id: { type: :string, format: :uuid },+ opening: { type: :boolean, description: 'Units held before the first imported trade' },+ acquired_on: { type: :string, format: :date, nullable: true, description: 'Null for the opening lot' },+ qty: { type: :string, description: 'Units of the lot still held' },+ unit_cost: { type: :string, nullable: true, description: 'Formatted cost per unit; null when unknown' },+ manual_cost: { type: :boolean, description: 'Whether the cost was set by the user' },+ trade_id: { type: :string, format: :uuid, nullable: true, description: 'The trade that acquired the lot; null for the opening lot' }+ }+ },HoldingCollection: {type: :object,required: %w[holdings pagination],diff --git a/test/controllers/api/v1/holdings_controller_test.rb b/test/controllers/api/v1/holdings_controller_test.rbindex 6cf51d966d..19cd0a18da 100644--- a/test/controllers/api/v1/holdings_controller_test.rb+++ b/test/controllers/api/v1/holdings_controller_test.rb@@ -3,6 +3,8 @@require "test_helper"class Api::V1::HoldingsControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper+setup do@user = users(:family_admin)@family = @user.family@@ -87,8 +89,87 @@ class Api::V1::HoldingsControllerTest < ActionDispatch::IntegrationTestassert_response :unauthorizedend+ test "a position's current row lists its open lots, oldest first" do+ current, first_buy, second_buy = lot_position+ HoldingLot.find_by!(source_entry: second_buy).set_manual_total_cost!(600)+ materialize(current.security)++ get api_v1_holding_url(current), headers: api_headers(@api_key)++ assert_response :success+ lots = JSON.parse(response.body)["lots"]+ assert_equal [ first_buy.date.iso8601, second_buy.date.iso8601 ], lots.map { |lot| lot["acquired_on"] }+ assert_equal [ "60.0", "40.0" ], lots.map { |lot| lot["qty"] }+ assert_equal [ "$12.00", "$15.00" ], lots.map { |lot| lot["unit_cost"] }, "the second lot's cost is the user's $600 over 40"+ assert_equal [ false, true ], lots.map { |lot| lot["manual_cost"] }+ assert_equal [ false, false ], lots.map { |lot| lot["opening"] }+ assert_equal [ first_buy.entryable_id, second_buy.entryable_id ], lots.map { |lot| lot["trade_id"] }+ end++ test "units held before the first trade are listed as the opening lot, first" do+ current, = lot_position+ HoldingLot.create!(account: @account, security: current.security, origin_security: current.security, qty: 5, currency: "USD")+ current.update_columns(qty: current.qty + 5)++ get api_v1_holding_url(current), headers: api_headers(@api_key)++ first = JSON.parse(response.body)["lots"].first+ assert_equal [ true, nil, "5.0", nil, nil ], first.values_at("opening", "acquired_on", "qty", "unit_cost", "trade_id")+ end++ # The stored lots are the position as it stands, so an earlier row, or a+ # position whose lots do not add up to it, has none to show.+ test "an earlier row, or a position its lots do not add up to, has null lots" do+ current, first_buy = lot_position+ earlier = @account.holdings.find_by!(security: current.security, date: first_buy.date)++ get api_v1_holding_url(earlier), headers: api_headers(@api_key)+ response_data = JSON.parse(response.body)+ assert response_data.key?("lots")+ assert_nil response_data["lots"]++ current.update_columns(qty: current.qty + 1)+ get api_v1_holding_url(current), headers: api_headers(@api_key)+ assert_nil JSON.parse(response.body)["lots"]+ end++ test "listing holdings reads lots in the same number of queries however many positions" do+ lot_position(ticker: "LOTA")+ one = holding_lot_queries { get api_v1_holdings_url, headers: api_headers(@api_key) }+ lot_position(ticker: "LOTB")+ lot_position(ticker: "LOTC")+ three = holding_lot_queries { get api_v1_holdings_url, headers: api_headers(@api_key) }++ assert_response :success+ assert_equal one, three+ assert_equal 3, JSON.parse(response.body)["holdings"].count { |holding| holding["lots"].present? }+ end+private+ # Two buys of one security, 60 at $12 two days ago and 40 at $20+ # yesterday, materialized as a sync does.+ def lot_position(ticker: "LOTS")+ security = Security.create!(ticker: ticker, name: ticker)+ Security::Price.insert_all((2.days.ago.to_date..Date.current).map { |date| { security_id: security.id, date: date, price: 30, currency: "USD" } })+ first_buy = create_trade(security, account: @account, qty: 60, price: 12, date: 2.days.ago.to_date)+ second_buy = create_trade(security, account: @account, qty: 40, price: 20, date: 1.day.ago.to_date)+ materialize(security)+ [ @account.holdings.find_by!(security: security, date: Date.current), first_buy, second_buy ]+ end++ def materialize(security)+ Holding::Materializer.new(@account.reload, strategy: :forward, security_ids: [ security.id ]).materialize_holdings+ end++ def holding_lot_queries+ count = 0+ counter = ->(*, payload) { count += 1 if payload[:sql].include?("holding_lots") }+ ActiveSupport::Notifications.subscribed(counter, "sql.active_record") { yield }+ count+ end++def api_headers(api_key){ "X-Api-Key" => api_key.display_key }enddiff --git a/test/controllers/api/v1/trades_controller_test.rb b/test/controllers/api/v1/trades_controller_test.rbindex 053aaca926..9bac620643 100644--- a/test/controllers/api/v1/trades_controller_test.rb+++ b/test/controllers/api/v1/trades_controller_test.rb@@ -3,6 +3,8 @@require "test_helper"class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper+setup do@user = users(:family_admin)@user.api_keys.active.destroy_all@@ -1093,6 +1095,26 @@ class Api::V1::TradesControllerTest < ActionDispatch::IntegrationTestassert trade_data.key?("notes")end++ test "a sale that names its lot reports the acquiring trade, in show and index" do+ @investment_account.update!(cost_basis_method: "fifo")+ security = Security.create!(ticker: "LOTAPI", name: "LOTAPI")+ buy = create_trade(security, account: @investment_account, qty: 40, price: 20, date: 3.days.ago.to_date)+ sale = create_trade(security, account: @investment_account, qty: -10, price: 25, date: 1.day.ago.to_date)+ other_sale = create_trade(security, account: @investment_account, qty: -5, price: 25, date: Date.current)+ sale.trade.update!(lot_source_entry: buy)++ get "/api/v1/trades/#{sale.entryable_id}", headers: api_headers(read_only_api_key)+ assert_response :success+ assert_equal buy.entryable_id, JSON.parse(response.body)["lot_source_trade_id"]++ get "/api/v1/trades", params: { account_id: @investment_account.id, per_page: 100 }, headers: api_headers(read_only_api_key)+ by_id = JSON.parse(response.body)["trades"].index_by { |trade| trade["id"] }+ assert_equal buy.entryable_id, by_id.fetch(sale.entryable_id)["lot_source_trade_id"]+ assert by_id.fetch(other_sale.entryable_id).key?("lot_source_trade_id")+ assert_nil by_id.fetch(other_sale.entryable_id)["lot_source_trade_id"]+ end+privatedef category_ids_from_every_sourcediff --git a/test/models/assistant/function/get_holdings_test.rb b/test/models/assistant/function/get_holdings_test.rbindex a2dbdcb2ae..cd3e429b37 100644--- a/test/models/assistant/function/get_holdings_test.rb+++ b/test/models/assistant/function/get_holdings_test.rb@@ -1,6 +1,8 @@require "test_helper"class Assistant::Function::GetHoldingsTest < ActiveSupport::TestCase+ include EntriesTestHelper+setup do@user = users(:family_admin)@fn = Assistant::Function::GetHoldings.new(@user)@@ -34,9 +36,60 @@ class Assistant::Function::GetHoldingsTest < ActiveSupport::TestCaseassert_equal [ "AAPL", "MSFT" ], tickers({})end+ # With no stored cost the figure is the fallback, which on a FIFO account+ # reads the open lots; the assistant must answer what the drawer shows.+ test "get_holdings average_cost equals the drawer figure" do+ fifo_position+ @holding.update_columns(cost_basis: nil, cost_basis_source: nil)+ drawer = Holding.find(@holding.id).avg_cost++ row = lot_row++ assert_in_delta BigDecimal("17.3333"), drawer.amount, BigDecimal("0.0001"), "precondition: the drawer reads the open lots"+ assert_equal drawer.amount.to_f, row[:average_cost]+ assert_equal drawer.format, row[:formatted_average_cost]+ end++ test "get_holdings lists a position's open lots, oldest first" do+ fifo_position+ lots = lot_row[:lots]++ assert_equal [ @first_buy.date, @second_buy.date ], lots.map { |lot| lot[:acquired_on] }+ assert_equal [ 20.0, 40.0 ], lots.map { |lot| lot[:quantity] }+ assert_equal [ 12.0, 20.0 ], lots.map { |lot| lot[:unit_cost] }+ assert_equal [ "$12.00", "$20.00" ], lots.map { |lot| lot[:formatted_unit_cost] }+ assert_equal [ false, false ], lots.map { |lot| lot[:opening] }+ end++ test "get_holdings gives no lots for a position its lots do not add up to" do+ fifo_position+ @holding.update_columns(qty: @holding.qty + 1)++ row = lot_row+ assert row.key?(:lots)+ assert_nil row[:lots]+ end+privatedef tickers(params)@fn.call({ "page" => 1 }.merge(params))[:holdings].map { |row| row[:ticker] }.uniq.sortend++ # 60 at $12, then 40 at $20, then 40 sold: FIFO keeps 20 at $12 and 40 at+ # $20 ($17.33 a unit), where the pooled average is $15.20.+ def fifo_position+ @account.update!(cost_basis_method: "fifo")+ @security = Security.create!(ticker: "LOTG", name: "LOTG")+ Security::Price.insert_all((3.days.ago.to_date..Date.current).map { |date| { security_id: @security.id, date: date, price: 30, currency: "USD" } })+ @first_buy = create_trade(@security, account: @account, qty: 60, price: 12, date: 3.days.ago.to_date)+ @second_buy = create_trade(@security, account: @account, qty: 40, price: 20, date: 2.days.ago.to_date)+ create_trade(@security, account: @account, qty: -40, price: 25, date: 1.day.ago.to_date)+ Holding::Materializer.new(@account.reload, strategy: :forward, security_ids: [ @security.id ]).materialize_holdings+ @holding = @account.holdings.find_by!(security: @security, date: Date.current)+ end++ def lot_row+ @fn.call("accounts" => [ @account.name ])[:holdings].find { |row| row[:ticker] == "LOTG" }+ endenddiff --git a/test/models/family/data_importer_test.rb b/test/models/family/data_importer_test.rbindex a2071c68a1..f2e76841a6 100644--- a/test/models/family/data_importer_test.rb+++ b/test/models/family/data_importer_test.rb@@ -1,6 +1,8 @@require "test_helper"class Family::DataImporterTest < ActiveSupport::TestCase+ include EntriesTestHelper+setup do@family = families(:empty)end@@ -1547,6 +1549,160 @@ class Family::DataImporterTest < ActiveSupport::TestCaseassert imported_holding.security_lockedend+ # Derived lots are rebuilt on every sync, so the file carries only what the+ # user chose: a lot's cost, the lot a sale names, and the account's method.+ test "export then import round-trips a user-set lot basis and a named lot" do+ Family::DataImporter.new(@family, lot_export).import!++ account = @family.accounts.find_by!(name: "Lot Round Trip")+ Holding::Materializer.new(account, strategy: :forward).materialize_holdings+ trades = lot_trades(account)++ assert_equal "fifo", account.cost_basis_method+ assert_equal trades.fetch(40), trades.fetch(-10).trade.lot_source_entry, "the sale's named lot"+ lot = HoldingLot.find_by!(source_entry: trades.fetch(60))+ assert_equal 600, lot.manual_total_cost+ assert_equal 10, lot.unit_cost, "the user's 600 over 60 units, after re-materialization"+ assert_equal [ 60, 30 ], HoldingLot.where(account: account).order(:acquired_on).pluck(:qty).map(&:to_i), "the sale took the named lot, not the oldest"+ end++ # An account that sells by average keeps a stored choice and ignores it, so+ # an export taken after a switch still carries it.+ test "a named lot kept through a switch to average imports without failing the import" do+ Family::DataImporter.new(@family, lot_export(switch_to: "average")).import!++ account = @family.accounts.find_by!(name: "Lot Round Trip")+ trades = lot_trades(account)+ assert_equal "average", account.cost_basis_method+ assert_equal trades.fetch(40), trades.fetch(-10).trade.reload.lot_source_entry+ end++ test "a sale and the lot it names restore their link when each arrives in its own chunk" do+ lines = lot_export.split("\n")+ session = @family.import_sessions.create!(expected_chunks: lines.size)++ lines.each { |line| Family::DataImporter.new(@family, line, import_session: session).import! }++ trades = lot_trades(@family.accounts.find_by!(name: "Lot Round Trip"))+ assert_equal trades.fetch(40), trades.fetch(-10).trade.reload.lot_source_entry+ assert_equal 600, HoldingLot.find_by!(source_entry: trades.fetch(60)).manual_total_cost+ end++ # An import stamps entries in file order, so the file's order of a day's+ # trades becomes the order they replay in.+ test "a fifo round trip replays a day's trades in the order they were entered" do+ assert_equal 180, round_trip_cost_basis("fifo", [ [ 10, 100 ], [ 20, 200 ], [ -5, 100 ] ]),+ "the sale took the 10 at $100 entered first, leaving 5 at $100 and 20 at $200"+ end++ test "an average round trip replays a sell-off before a same-day repurchase entered after it" do+ assert_equal 20, round_trip_cost_basis("average", [ [ 1, 10 ], [ -1, 10 ], [ 1, 20 ] ]),+ "the sale closed the position, so the repurchase starts a fresh basis"+ end++ # Replay puts a same-day trade entered later after the sale, so the sale+ # cannot have sold from it.+ test "a same-day lot listed after the sale that names it is dropped and counted" do+ lines = lot_export.split("\n")+ trade_lines = lines.select { |line| JSON.parse(line)["type"] == "Trade" }+ sale_line = trade_lines.find { |line| JSON.parse(line).dig("data", "lot_source_trade_id") }+ lot_line = trade_lines.find { |line| JSON.parse(line).dig("data", "id") == JSON.parse(sale_line).dig("data", "lot_source_trade_id") }+ assert_operator lines.index(lot_line), :<, lines.index(sale_line), "precondition: the export lists the lot first"++ { "lot listed first" => lines, "sale listed first" => lines.map { |line| { lot_line => sale_line, sale_line => lot_line }.fetch(line, line) } }+ .each do |label, ordered|+ family = Family.create!(name: "Target #{label}", currency: "USD", locale: "en", date_format: "%Y-%m-%d")+ result = Family::DataImporter.new(family, ordered.join("\n")).import!+ sale = lot_trades(family.accounts.find_by!(name: "Lot Round Trip")).fetch(-10).trade++ if label == "lot listed first"+ assert_equal JSON.parse(lot_line).dig("data", "date"), JSON.parse(sale_line).dig("data", "date"), "precondition: bought the sale's day"+ assert_not_nil sale.lot_source_entry_id, label+ assert_equal 0, result[:summary].dig("trades", "skipped").to_i, label+ else+ assert_nil sale.lot_source_entry_id, label+ assert_equal 1, result[:summary].dig("trades", "skipped"), label+ end+ end+ end++ test "an unusable lot cost or lot name is dropped and counted, and the trade still imports" do+ # Each edit names the check that tells its drop from a clean import, where+ # the first buy's lot carries the user's 600 and the sale names the $20 lot.+ cases = {+ "a non-numeric cost" => [ ->(data) { data["lot_total_cost"] = "abc" if data["lot_total_cost"] }, :no_lot_cost ],+ "a negative cost" => [ ->(data) { data["lot_total_cost"] = "-5" if data["lot_total_cost"] }, :no_lot_cost ],+ "a cost on a sale" => [ ->(data) { data["lot_total_cost"] = "50" if data["qty"].to_d.negative? }, :only_the_buys_lot ],+ "an unknown named lot" => [ ->(data) { data["lot_source_trade_id"] = SecureRandom.uuid if data["lot_source_trade_id"] }, :no_choice ],+ "a sale naming itself" => [ ->(data) { data["lot_source_trade_id"] = data["id"] if data["lot_source_trade_id"] }, :no_choice ],+ "a sale dated before its lot" => [ ->(data) { data["date"] = 5.days.ago.to_date.iso8601 if data["lot_source_trade_id"] }, :no_choice ],+ "a sale of another security" => [ ->(data) { data.merge!("security_id" => SecureRandom.uuid, "ticker" => "OTHER#{SecureRandom.hex(2).upcase}") if data["lot_source_trade_id"] }, :no_choice ]+ }++ cases.each do |label, (edit, check)|+ family = Family.create!(name: "Target #{label}", currency: "USD", locale: "en", date_format: "%Y-%m-%d")++ result = Family::DataImporter.new(family, edit_trades(lot_export) { |data| edit.call(data) }).import!++ account = family.accounts.find_by!(name: "Lot Round Trip")+ trades = lot_trades(account)+ assert_equal 3, trades.size, "#{label}: a trade was lost"+ assert_equal 1, result[:summary].dig("trades", "skipped"), label+ case check+ when :no_lot_cost+ assert_equal 0, HoldingLot.where(account: account).count, "#{label}: the cost was seeded"+ when :only_the_buys_lot+ assert_equal [ trades.fetch(60).id ], HoldingLot.where(account: account).pluck(:source_entry_id), "#{label}: a sale got a lot"+ when :no_choice+ assert_nil trades.fetch(-10).trade.reload.lot_source_entry_id, "#{label}: the choice was stored"+ assert_equal 600, HoldingLot.find_by!(source_entry: trades.fetch(60)).manual_total_cost, "#{label}: the lot's cost went with it"+ end+ end+ end++ # A sale the user has since marked a transfer out names no lot, as the+ # drawer would not let it.+ # Labels are not in the export, so only a sale the user marked a transfer+ # out after a session's first import can meet this; the session refuses it.+ test "a session re-import refuses a named lot on a sale marked a transfer out" do+ session = @family.import_sessions.create!(expected_chunks: 2)+ export = lot_export+ Family::DataImporter.new(@family, export, import_session: session).import!+ trades = lot_trades(@family.accounts.find_by!(name: "Lot Round Trip"))+ sale = trades.fetch(-10).trade+ assert_equal trades.fetch(40).id, sale.lot_source_entry_id, "precondition: the first import named the lot"+ sale.update_columns(investment_activity_label: Trade::TRANSFER_LABEL)++ assert_raises(Family::DataImporter::InvalidRecordError) do+ Family::DataImporter.new(@family, export, import_session: session).import!+ end+ end++ test "a session import raises on an unusable lot cost" do+ session = @family.import_sessions.create!(expected_chunks: 1)++ assert_raises(Family::DataImporter::InvalidRecordError) do+ Family::DataImporter.new(@family, edit_trades(lot_export) { |data| data["lot_total_cost"] = "abc" if data["lot_total_cost"] }, import_session: session).import!+ end+ end++ test "re-importing without the cost method keeps the account's own, and without a lot's cost or name clears them" do+ session = @family.import_sessions.create!(expected_chunks: 2)+ export = lot_export+ Family::DataImporter.new(@family, export, import_session: session).import!++ cleared = edit_trades(export) { |data| data["lot_total_cost"] = nil; data["lot_source_trade_id"] = nil }+ cleared = cleared.split("\n").map { |line| JSON.parse(line) }.each { |record| record["data"].delete("cost_basis_method") if record["type"] == "Account" }.map(&:to_json).join("\n")+ Family::DataImporter.new(@family, cleared, import_session: session).import!++ account = @family.accounts.find_by!(name: "Lot Round Trip")+ trades = lot_trades(account)+ assert_equal 1, @family.accounts.where(name: "Lot Round Trip").count, "precondition: the re-import updated the account"+ assert_equal "fifo", account.cost_basis_method+ assert_nil HoldingLot.find_by!(source_entry: trades.fetch(60)).manual_total_cost+ assert_nil trades.fetch(-10).trade.reload.lot_source_entry_id+ end+test "round trips property details and address through full export" dosource_family = Family.create!(name: "Source Property Family", currency: "USD", locale: "en", date_format: "%Y-%m-%d")source_family.accounts.create!(@@ -3567,6 +3723,65 @@ class Family::DataImporterTest < ActiveSupport::TestCaseprivate+ # A FIFO account's export: 60 bought at $12 with the user's cost of $600,+ # 40 at $20, and a sale of 10 that names the $20 lot.+ def lot_export(switch_to: nil)+ source = Family.create!(name: "Lot Source", currency: "USD", locale: "en", date_format: "%Y-%m-%d")+ account = source.accounts.create!(name: "Lot Round Trip", accountable: Investment.new, balance: 0, cash_balance: 0, currency: "USD")+ account.update!(cost_basis_method: "fifo")+ security = Security.create!(ticker: "LRT#{SecureRandom.hex(3).upcase}", name: "Lot Round Trip")+ Security::Price.insert_all((3.days.ago.to_date..Date.current).map { |date| { security_id: security.id, date: date, price: 30, currency: "USD" } })+ first_buy = create_trade(security, account: account, qty: 60, price: 12, date: 3.days.ago.to_date)+ second_buy = create_trade(security, account: account, qty: 40, price: 20, date: 2.days.ago.to_date)+ # Sold on the day the named lot was bought, which a sale may do.+ sale = create_trade(security, account: account, qty: -10, price: 25, date: 2.days.ago.to_date)+ sale.trade.update!(lot_source_entry: second_buy)+ # The sale gets the lowest trade id, so an export ordered by date and id+ # alone would write it ahead of the lot it names, bought the same day.+ low_id = "00000000-0000-4000-8000-#{SecureRandom.hex(6)}"+ Trade.where(id: sale.entryable_id).update_all(id: low_id)+ sale.update_columns(entryable_id: low_id)+ Holding::Materializer.new(account.reload, strategy: :forward).materialize_holdings+ HoldingLot.find_by!(source_entry: first_buy).set_manual_total_cost!(600)+ account.update!(cost_basis_method: switch_to) if switch_to++ ndjson = nil+ Zip::File.open_buffer(Family::DataExporter.new(source).generate_export) { |zip| ndjson = zip.read("all.ndjson") }+ ndjson+ end++ # Exports a one-day run of trades entered in the given order, imports it+ # into a fresh family, and returns the imported position's cost basis.+ def round_trip_cost_basis(method, trades)+ source = Family.create!(name: "Order Source", currency: "USD", locale: "en", date_format: "%Y-%m-%d")+ account = source.accounts.create!(name: "Order Round Trip", accountable: Investment.new, balance: 0, cash_balance: 0, currency: "USD")+ account.update!(cost_basis_method: method)+ security = Security.create!(ticker: "ORT#{SecureRandom.hex(3).upcase}", name: "Order Round Trip")+ day = 2.days.ago.to_date+ Security::Price.insert_all((day..Date.current).map { |date| { security_id: security.id, date: date, price: 30, currency: "USD" } })+ trades.each_with_index do |(qty, price), index|+ create_trade(security, account: account, qty: qty, price: price, date: day)+ .update_columns(created_at: 1.hour.ago + index.minutes)+ end++ ndjson = nil+ Zip::File.open_buffer(Family::DataExporter.new(source).generate_export) { |zip| ndjson = zip.read("all.ndjson") }+ target = Family.create!(name: "Order Target", currency: "USD", locale: "en", date_format: "%Y-%m-%d")+ Family::DataImporter.new(target, ndjson).import!++ imported = target.accounts.find_by!(name: "Order Round Trip")+ Holding::Materializer.new(imported, strategy: :forward).materialize_holdings+ imported.holdings.where(date: day).sole.cost_basis+ end++ def edit_trades(ndjson)+ ndjson.split("\n").map { |line| JSON.parse(line) }.each { |record| yield record["data"] if record["type"] == "Trade" }.map(&:to_json).join("\n")+ end++ def lot_trades(account)+ account.entries.where(entryable_type: "Trade").includes(:entryable).index_by { |entry| entry.trade.qty.to_i }+ end+def build_ndjson(records)records.map(&:to_json).join("\n")enddiff --git a/test/models/holding/cost_basis_tracker_test.rb b/test/models/holding/cost_basis_tracker_test.rbdeleted file mode 100644index 0ba17761af..0000000000--- a/test/models/holding/cost_basis_tracker_test.rb+++ /dev/null@@ -1,127 +0,0 @@-require "test_helper"--class Holding::CostBasisTrackerTest < ActiveSupport::TestCase- setup do- @tracker = Holding::CostBasisTracker.new- end-- test "average cost is nil with no trades" do- assert_nil @tracker.average_cost- end-- test "weighted average across multiple buys" do- @tracker.apply(BigDecimal("100"), BigDecimal("10"))- @tracker.apply(BigDecimal("200"), BigDecimal("10"))-- assert_equal BigDecimal("150"), @tracker.average_cost- end-- test "a partial sell leaves the per-share average unchanged" do- @tracker.apply(BigDecimal("100"), BigDecimal("10"))- @tracker.apply(BigDecimal("200"), BigDecimal("10")) # avg 150-- # Sell price is irrelevant to cost basis; shares are relieved at the average.- @tracker.apply(BigDecimal("999"), BigDecimal("-5"))-- assert_equal BigDecimal("150"), @tracker.average_cost- end-- test "cost basis resets after a full liquidation and repurchase" do- @tracker.apply(BigDecimal("100"), BigDecimal("10"))- @tracker.apply(BigDecimal("300"), BigDecimal("-10")) # fully sold-- assert_nil @tracker.average_cost-- @tracker.apply(BigDecimal("300"), BigDecimal("10")) # repurchased-- # Only the repurchased lot is held — not (100 + 300) / 2 = 200.- assert_equal BigDecimal("300"), @tracker.average_cost- end-- # Skipping a buy whose price is unknown would average the known buys over- # fewer units than are held.- test "a buy at an unknown price makes the average unknown until the position closes" do- @tracker.apply(BigDecimal("100"), BigDecimal("10"))- @tracker.apply(nil, BigDecimal("10"))- assert_nil @tracker.average_cost-- @tracker.apply(BigDecimal("999"), BigDecimal("-5"))- assert_nil @tracker.average_cost, "a partial sell does not make it known"-- @tracker.apply(BigDecimal("999"), BigDecimal("-15"))- @tracker.apply(BigDecimal("120"), BigDecimal("4"))- assert_equal BigDecimal("120"), @tracker.average_cost, "a repurchase after a full close starts clean"- end-- test "over-selling cannot drive quantity or basis negative" do- @tracker.apply(BigDecimal("100"), BigDecimal("5"))- @tracker.apply(BigDecimal("100"), BigDecimal("-10")) # sell more than held-- assert_nil @tracker.average_cost- end-- test "selling with no position is a no-op" do- @tracker.apply(BigDecimal("100"), BigDecimal("-5"))-- assert_nil @tracker.average_cost- end-- test "coerces float quantities so a full liquidation still resets" do- # Float inputs must not accumulate rounding error that leaves a tiny- # residual quantity and bypasses the reset-on-full-liquidation.- @tracker.apply(100.0, 10.0)- @tracker.apply(300.0, -10.0)-- assert_nil @tracker.average_cost-- @tracker.apply(300.0, 10.0)-- assert_equal BigDecimal("300"), @tracker.average_cost- end-- # A split changes how many shares the money bought, not how much it cost.- # Quantity is read back by selling down: the position empties (and the- # average resets to nil) on exactly the last share, and not one before it.- test "a 2-for-1 split doubles the shares, keeps the total cost and halves the average" do- @tracker.apply(BigDecimal("100"), BigDecimal("10")) # 1,000 for 10-- @tracker.split(2)-- assert_equal BigDecimal("50"), @tracker.average_cost- @tracker.apply(BigDecimal("1"), BigDecimal("-19"))- assert_equal BigDecimal("50"), @tracker.average_cost, "20 shares after the split, so 19 sold leaves one"- @tracker.apply(BigDecimal("1"), BigDecimal("-1"))- assert_nil @tracker.average_cost- end-- test "a 1-for-10 reverse split cuts the shares and keeps the total cost" do- @tracker.apply(BigDecimal("5"), BigDecimal("100")) # 500 for 100-- @tracker.split(Rational(1, 10))-- assert_equal BigDecimal("50"), @tracker.average_cost- @tracker.apply(BigDecimal("1"), BigDecimal("-9"))- assert_equal BigDecimal("50"), @tracker.average_cost, "10 shares after the split, so 9 sold leaves one"- @tracker.apply(BigDecimal("1"), BigDecimal("-1"))- assert_nil @tracker.average_cost- end-- # Multiplying a BigDecimal by Rational(1, 3) rounds at 32 digits: three- # shares became 0.999..., and the average 30.000...03. (A sale would not- # show it: the over-sell guard clears the position either way.)- test "a 1-for-3 reverse split of three shares leaves exactly one, at exactly three times the cost" do- @tracker.apply(BigDecimal("10"), BigDecimal("3"))-- @tracker.split(Rational(1, 3))-- assert_equal BigDecimal("30"), @tracker.average_cost- end-- test "a split with nothing held leaves nothing held" do- @tracker.split(2)-- assert_nil @tracker.average_cost- @tracker.apply(BigDecimal("30"), BigDecimal("1"))- assert_equal BigDecimal("30"), @tracker.average_cost- end-enddiff --git a/test/models/holding/lot_book_test.rb b/test/models/holding/lot_book_test.rbindex eea4a4f279..c6ea269097 100644--- a/test/models/holding/lot_book_test.rb+++ b/test/models/holding/lot_book_test.rb@@ -4,8 +4,8 @@ require "minitest/mock"class Holding::LotBookTest < ActiveSupport::TestCaseinclude EntriesTestHelper- # Holding::CostBasisTracker exactly as it stood before the lot book, kept here- # as the oracle: under the average method the lot book must give the same+ # The pre-lot tracker implementation, copied exactly and kept here as the+ # oracle: under the average method the lot book must give the same# figure at every step, to the last digit.class ReferenceTrackerdef initialize@@ -237,8 +237,10 @@ class Holding::LotBookTest < ActiveSupport::TestCaseassert_equal %w[buy transfer], book.lots.map(&:source_id)end- test "the tracker keeps its public interface" do- tracker = Holding::CostBasisTracker.new+ # The name Holding::CostBasisTracker is gone with this PR: the alias existed+ # only for the parity suite's oracle, which now lives on the copied class.+ test "the lot book keeps the tracker's public interface" do+ tracker = Holding::LotBook.newtracker.apply(BigDecimal("100"), BigDecimal("10"))tracker.buy(BigDecimal("200"), BigDecimal("10"))tracker.sell(BigDecimal("-5"))