Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Let a FIFO sale name its lot, and read open lots in the fallback (#4903)

jaysbeekay5364ae5131b7
diff --git a/app/controllers/holdings_controller.rb b/app/controllers/holdings_controller.rb
index 98ed94a9e5..f63b7f9753 100644
--- a/app/controllers/holdings_controller.rb
+++ b/app/controllers/holdings_controller.rb
@@ -6,7 +6,9 @@ class HoldingsController < ApplicationController
def index
@account = accessible_accounts.find(params[:account_id])
- @current_holdings = @account.current_holdings.includes(:security)
+ # Every row shows its average cost; load them together, not per row.
+ @current_holdings = @account.current_holdings.includes(:security).to_a
+ Holding.preload_avg_costs(@current_holdings)
@negative_positions = @account.negative_positions
@trade_republic_categories = trade_republic_categories_for(@account)
end
diff --git a/app/controllers/trades_controller.rb b/app/controllers/trades_controller.rb
index 0ac5661aea..491b737a7d 100644
--- a/app/controllers/trades_controller.rb
+++ b/app/controllers/trades_controller.rb
@@ -101,7 +101,7 @@ class TradesController < ApplicationController
def entry_params
params.require(:entry).permit(
:name, :date, :amount, :currency, :excluded, :notes, :nature,
- entryable_attributes: [ :id, :qty, :price, :fee, :investment_activity_label ]
+ entryable_attributes: [ :id, :qty, :price, :fee, :investment_activity_label, :lot_source_entry_id ]
)
end
diff --git a/app/models/holding.rb b/app/models/holding.rb
index eabe32c33f..8cfd42c521 100644
--- a/app/models/holding.rb
+++ b/app/models/holding.rb
@@ -79,6 +79,35 @@ class Holding < ApplicationRecord
calculate_avg_cost
end
+ # The avg-cost fallback for holdings in accounts that sell by fifo, by
+ # holding id.
+ # What a fifo position holds is its open lots, not a share of every
+ # purchase, so the figure is their mean, as Holding::LotBook#average_cost
+ # gives it; the opening lot stays out, as it does there. The stored lots
+ # are the position as it stands, so they answer only for its latest row,
+ # and only while they add up to it (HoldingLot.in_partition). Any other
+ # 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)
+ return {} if holdings.empty?
+
+ account_ids = holdings.map(&:account_id).uniq
+ security_ids = holdings.map(&:security_id).uniq
+ readable = 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")
+ .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 ]
+ end
+ end
+
# The rate a trade carries itself (extra["exchange_rate"], e.g. IBKR's
# fx_rate_to_base) comes before the table's, as in the calculators and
# Balance::SyncCache; a trade in the account's own currency converts at 1.
@@ -100,9 +129,11 @@ class Holding < ApplicationRecord
# #calculate_avg_cost for every holding given, in one query: the same
# trades, rates, fees, internal-movement and lot rules (a user-costed lot
- # counts at its cost; a clamped position has none), read through the same SQL
- # (.avg_cost_rates_join, .avg_cost_totals_sql, .avg_cost_from_totals), so
- # the batch cannot answer differently from the holding on its own. Holdings
+ # counts at its cost; a clamped position has none), read through the same
+ # SQL (.avg_cost_rates_join, .avg_cost_totals_sql, .avg_cost_from_totals),
+ # so the batch cannot answer differently from the holding on its own.
+ # Holdings in accounts that sell by fifo read their open lots instead, all
+ # of them together through .fifo_avg_costs, in a few more queries. Holdings
# with a stored cost basis are skipped, since #avg_cost never reaches the
# fallback for them. So are holdings with unsaved changes, unsaved ones
# included: the query reads the stored row, which is not what they hold.
@@ -138,13 +169,27 @@ class Holding < ApplicationRecord
AND clamped_lots.clamped
))
SQL
+ Arel.sql("BOOL_OR(accounts.cost_basis_method = 'fifo')"),
*avg_cost_totals_sql(lots: true)
)
.index_by(&:first)
+ # The account decides fifo. A holding with no row (no buy dated on or
+ # before it, as with a provider row that predates its trade) still reads
+ # its lots, so its account is looked up; nothing extra runs otherwise.
+ unrowed = pending.reject { |holding| rows.key?(holding.id) }
+ fifo_account_ids = unrowed.any? ? Account.where(id: unrowed.map(&:account_id).uniq, cost_basis_method: "fifo").pluck(:id).to_set : Set.new
+ lot_costs = fifo_avg_costs(pending.select { |holding| rows.key?(holding.id) ? rows[holding.id][3] : fifo_account_ids.include?(holding.account_id) })
+
pending.each do |holding|
- _id, internal_movement, clamped, total_cost, total_qty, rate_missing = rows[holding.id]
- value = avg_cost_from_totals(total_cost, total_qty, rate_missing, holding.currency) unless internal_movement || clamped
+ _id, internal_movement, clamped, _fifo, total_cost, total_qty, rate_missing = rows[holding.id]
+ value = if clamped
+ nil
+ elsif lot_costs.key?(holding.id)
+ lot_costs[holding.id]
+ elsif !internal_movement
+ avg_cost_from_totals(total_cost, total_qty, rate_missing, holding.currency)
+ end
holding.preload_avg_cost(value)
end
end
@@ -472,6 +517,7 @@ class Holding < ApplicationRecord
# Fewer units than the trades bought (see Holding::ReverseCalculator), so
# no figure drawn from those trades is the position's.
return nil if HoldingLot.where(account_id: account_id, security_id: security_id, clamped: true).exists?
+ return self.class.fifo_avg_costs([ self ])[id] if account.cost_basis_fifo?
trades = account.trades
.with_entry
diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rb
index 59398e2be6..a833d3a722 100644
--- a/app/models/holding/forward_calculator.rb
+++ b/app/models/holding/forward_calculator.rb
@@ -130,7 +130,8 @@ class Holding::ForwardCalculator
end
else
price = manual_cost || effective_trade_price(trade, date: trade_entry.date)
- @lot_books[security_id].apply(price, trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)
+ @lot_books[security_id].apply(price, trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date,
+ lot_source_id: trade.lot_source_entry_id)
end
portfolio[security_id] = previous_quantity + trade.qty
diff --git a/app/models/holding/lot_book.rb b/app/models/holding/lot_book.rb
index 1ac3e80561..a99a4365dc 100644
--- a/app/models/holding/lot_book.rb
+++ b/app/models/holding/lot_book.rb
@@ -32,6 +32,10 @@
# Under fifo the figure is the mean of the open lots a trade acquired rather
# than the pool, since what remains is no longer a pro-rata share of what was
# bought. The opening lot stays out of it, as it stays out of the pool.
+#
+# A sale under fifo can name the lot it sold from: that lot is consumed first,
+# and the rest oldest first. A name that matches no open lot is ignored, and
+# under average there is no per-lot consumption to direct.
class Holding::LotBook
Lot = Data.define(:source_id, :acquired_on, :qty, :unit_cost)
# `lot_source_id` and `unit_cost` are nil for the opening lot and for units
@@ -59,13 +63,17 @@ class Holding::LotBook
end
# Applies a trade by its signed quantity: positive is a buy, negative a sell.
- def apply(price, qty, source_id: nil, acquired_on: nil)
+ def apply(price, qty, source_id: nil, acquired_on: nil, lot_source_id: nil)
return if qty.nil?
qty = qty.to_d
return if qty.zero?
- qty.positive? ? buy(price, qty, source_id: source_id, acquired_on: acquired_on) : sell(qty, sale_id: source_id)
+ if qty.positive?
+ buy(price, qty, source_id: source_id, acquired_on: acquired_on)
+ else
+ sell(qty, sale_id: source_id, lot_source_id: lot_source_id)
+ end
end
def buy(price, qty, source_id: nil, acquired_on: nil)
@@ -93,11 +101,11 @@ class Holding::LotBook
# A sale with no `sale_id` (a transfer out) consumes lots without recording
# a disposal: it realises nothing.
- def sell(qty, sale_id: nil)
+ def sell(qty, sale_id: nil, lot_source_id: nil)
qty = qty&.to_d
return if qty.nil? || qty.zero?
- @fifo ? consume_oldest(qty.abs, sale_id) : relieve_lots(qty.abs)
+ @fifo ? consume_oldest(qty.abs, sale_id, lot_source_id) : relieve_lots(qty.abs)
return if @total_qty.zero?
# Relieve at the current average cost so the per-share average is unchanged.
@@ -197,15 +205,23 @@ class Holding::LotBook
end
# Lots are booked in the order they were acquired, the opening lot first,
- # so the oldest is the first open one.
- def consume_oldest(qty, sale_id)
+ # so the oldest is the first open one. A named lot is taken out of turn,
+ # and what is left of it keeps its place.
+ def consume_oldest(qty, sale_id, named = nil)
+ named_index = named && @lots.index { |lot| lot.source_id == named }
+ order = [ named_index, *@lots.each_index.reject { |i| i == named_index } ].compact
left = qty
+ taken = Array.new(@lots.size, BigDecimal("0"))
+ order.each do |i|
+ lot = @lots[i]
+ taken[i] = [ left, lot.qty ].min
+ left -= taken[i]
+ record_disposal(sale_id, lot.source_id, taken[i], lot.unit_cost) if taken[i].positive?
+ end
+
open = []
- @lots.each do |lot|
- taken = [ left, lot.qty ].min
- left -= taken
- record_disposal(sale_id, lot.source_id, taken, lot.unit_cost) if taken.positive?
- rest = lot.with(qty: lot.qty - taken)
+ @lots.each_with_index do |lot, i|
+ rest = lot.with(qty: lot.qty - taken[i])
rest.qty.positive? ? open << rest : @closed << rest
end
@lots = open
diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rb
index ed76272c00..84483bf230 100644
--- a/app/models/holding/reverse_calculator.rb
+++ b/app/models/holding/reverse_calculator.rb
@@ -215,7 +215,8 @@ class Holding::ReverseCalculator
# Buys raise the basis; sells relieve quantity at the running average, and a
# full liquidation resets it so a later repurchase starts from a clean basis.
price = manual_cost || effective_trade_price(trade, date: trade_entry.date)
- book.apply(price, trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)
+ book.apply(price, trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date,
+ lot_source_id: trade.lot_source_entry_id)
# Record the basis after each trade — including nil once a position is fully
# closed — so cost_basis_for returns nil for the sold-out span instead of a
diff --git a/app/models/holding_lot_disposal.rb b/app/models/holding_lot_disposal.rb
index e23840296d..fc2d184457 100644
--- a/app/models/holding_lot_disposal.rb
+++ b/app/models/holding_lot_disposal.rb
@@ -21,6 +21,11 @@ class HoldingLotDisposal < ApplicationRecord
end
transaction do
+ # READ COMMITTED would let a request-initiated restate and a background
+ # sync of the same account both delete, then both insert: duplicate
+ # disposals whose cost sums exceed the sale. The account row lock
+ # serialises the replace, as the family advisory lock does elsewhere.
+ account.lock!
scope.delete_all
insert_all(rows) if rows.any?
end
diff --git a/app/models/trade.rb b/app/models/trade.rb
index e3436da84e..d5b6e7a33f 100644
--- a/app/models/trade.rb
+++ b/app/models/trade.rb
@@ -6,6 +6,9 @@ class Trade < ApplicationRecord
belongs_to :security
belongs_to :category, optional: true
+ # The acquisition a sale says it sold from. Set by the user, never by a
+ # provider, so it stays editable on a linked sale.
+ belongs_to :lot_source_entry, class_name: "Entry", optional: true
# Use the same activity labels as Transaction
ACTIVITY_LABELS = Transaction::ACTIVITY_LABELS.dup.freeze
@@ -54,6 +57,7 @@ class Trade < ApplicationRecord
end
validate :exchange_rate_must_be_valid
+ validate :lot_source_entry_must_be_a_lot_choice, if: -> { lot_source_entry_id_changed? && lot_source_entry_id }
# Trade types for categorization
def buy?
@@ -70,6 +74,27 @@ class Trade < ApplicationRecord
INTERNAL_MOVEMENT_LABELS.include?(investment_activity_label)
end
+ # The acquisitions this sale can name as the lot it sold from: buys and
+ # transfers-in of its security, in its account, that the replay applies
+ # before it (an earlier date, or the same date and entered no later: a
+ # purchase stamped with the sale's own created_at replays first, see
+ # Holding::PortfolioCache#trades), leaving out a lot sales dated before it had already
+ # emptied. Only a sale in an account that sells by fifo has any, since under
+ # average a sale relieves every lot pro rata. The choice the sale already
+ # holds is always among them, so an edit keeps it, and is replayed only
+ # while it names a lot that is still open; a new choice must be open by then.
+ def lot_choices
+ return Entry.none unless sell? && !internal_movement? && entry&.account&.cost_basis_fifo?
+
+ acquisitions = entry.account.entries
+ .where(entryable_type: "Trade", entryable_id: Trade.where(security_id: security_id).where("qty > 0").select(:id))
+ before_sale = acquisitions
+ .where("(entries.date, entries.created_at) <= (:date, :created_at)",
+ date: entry.date, created_at: entry.created_at || Time.current)
+ .where.not(id: lots_emptied_before_sale)
+ before_sale.or(acquisitions.where(id: attribute_in_database(:lot_source_entry_id))).chronological
+ end
+
class << self
def build_name(type, qty, ticker)
prefix = type == "buy" ? "Buy" : "Sell"
@@ -192,6 +217,42 @@ class Trade < ApplicationRecord
private
+ # Acquisitions whose lot is now empty and was emptied before this sale:
+ # no sale dated on or after it took anything from the lot.
+ #
+ # A transfer out consumes lots without recording a disposal, so once one
+ # replays at or after this sale an empty lot no longer says when it was
+ # emptied. Nothing is excluded then: a lot that turns out to be empty
+ # falls back to the account's method when the sale replays.
+ def lots_emptied_before_sale
+ later_transfers_out = on_or_after_sale(
+ entry.account.entries.where(entryable_type: "Trade",
+ entryable_id: Trade.where(security_id: security_id, investment_activity_label: INTERNAL_MOVEMENT_LABELS)
+ .where("qty < 0").select(:id))
+ )
+ return HoldingLot.none.select(:source_entry_id) if later_transfers_out.exists?
+
+ later_disposals = on_or_after_sale(
+ HoldingLotDisposal.joins(:sale_entry).where(account_id: entry.account_id).where.not(lot_source_entry_id: nil)
+ )
+ HoldingLot.derived.where(account_id: entry.account_id, qty: 0)
+ .where.not(source_entry_id: later_disposals.select(:lot_source_entry_id))
+ .select(:source_entry_id)
+ end
+
+ # Entries replay by date, then in the order they were entered (see
+ # Holding::PortfolioCache#trades), so a same-day entry made earlier has
+ # already run by the time this sale does. `scope` must expose `entries`.
+ def on_or_after_sale(scope)
+ if entry.persisted?
+ scope.where("(entries.date, entries.created_at, entries.id) >= (:date, :created_at, :id)",
+ date: entry.date, created_at: entry.created_at, id: entry.id)
+ else
+ scope.where("(entries.date, entries.created_at) >= (:date, :created_at)",
+ date: entry.date, created_at: Time.current)
+ end
+ end
+
def exchange_rate_must_be_valid
if extra&.dig("exchange_rate_invalid")
errors.add(:exchange_rate, "must be a number")
@@ -203,6 +264,10 @@ class Trade < ApplicationRecord
end
end
+ def lot_source_entry_must_be_a_lot_choice
+ errors.add(:lot_source_entry, :invalid) unless lot_choices.exists?(id: lot_source_entry_id)
+ end
+
# The position the disposal is measured against: the latest snapshot for
# this security on or before the disposal's date.
#
diff --git a/app/views/trades/show.html.erb b/app/views/trades/show.html.erb
index c7eb478221..f054f89f9a 100644
--- a/app/views/trades/show.html.erb
+++ b/app/views/trades/show.html.erb
@@ -72,6 +72,20 @@
<% end %>
<% end %>
<% end %>
+ <% lot_choices = trade.lot_choices.includes(:entryable).to_a %>
+ <% if lot_choices.any? %>
+ <%= styled_form_with model: @entry,
+ url: trade_path(@entry),
+ class: "mt-2",
+ data: { controller: "auto-submit-form" } do |f| %>
+ <%= f.fields_for :entryable do |ef| %>
+ <%= ef.select :lot_source_entry_id,
+ lot_choices.map { |lot| [ t(".lot_option", date: l(lot.date, format: :long), qty: format_quantity(lot.trade.qty, exact: true), price: lot.trade.price_money.format), lot.id ] },
+ { label: t(".lot_label"), include_blank: t(".lot_oldest_first") },
+ { "data-auto-submit-form-target": "auto" } %>
+ <% end %>
+ <% end %>
+ <% end %>
</div>
<% end %>
<% dialog.with_section(title: t(".additional")) do %>
diff --git a/config/locales/views/trades/en.yml b/config/locales/views/trades/en.yml
index fe50d3a749..a8f3a299a1 100644
--- a/config/locales/views/trades/en.yml
+++ b/config/locales/views/trades/en.yml
@@ -60,6 +60,9 @@ en:
date_label: Date
delete: Delete
fee_label: Transaction fee
+ lot_label: Sold from lot
+ lot_oldest_first: Oldest first
+ lot_option: "%{date} · %{qty} at %{price}"
delete_subtitle: This action cannot be undone
delete_title: Delete Trade
details: Details
diff --git a/db/migrate/20261024140000_add_lot_source_entry_to_trades.rb b/db/migrate/20261024140000_add_lot_source_entry_to_trades.rb
new file mode 100644
index 0000000000..f81856ec4c
--- /dev/null
+++ b/db/migrate/20261024140000_add_lot_source_entry_to_trades.rb
@@ -0,0 +1,5 @@
+class AddLotSourceEntryToTrades < ActiveRecord::Migration[8.1]
+ def change
+ add_reference :trades, :lot_source_entry, type: :uuid, foreign_key: { to_table: :entries, on_delete: :nullify }
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 2ada0e6100..d2253b8993 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2865,12 +2865,14 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) do
t.decimal "fee", precision: 19, scale: 4, default: "0.0", null: false
t.string "investment_activity_label"
t.jsonb "locked_attributes", default: {}
+ t.uuid "lot_source_entry_id"
t.decimal "price", precision: 19, scale: 10
t.decimal "qty", precision: 34, scale: 18
t.uuid "security_id", null: false
t.datetime "updated_at", null: false
t.index ["extra"], name: "index_trades_on_extra", using: :gin
t.index ["investment_activity_label"], name: "index_trades_on_investment_activity_label"
+ t.index ["lot_source_entry_id"], name: "index_trades_on_lot_source_entry_id"
t.index ["security_id"], name: "index_trades_on_security_id"
end
@@ -3351,6 +3353,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) do
add_foreign_key "tool_calls", "messages"
add_foreign_key "trade_republic_accounts", "trade_republic_items"
add_foreign_key "trade_republic_items", "families"
+ add_foreign_key "trades", "entries", column: "lot_source_entry_id", on_delete: :nullify
add_foreign_key "trades", "securities"
add_foreign_key "trading212_accounts", "trading212_items"
add_foreign_key "trading212_items", "families"
diff --git a/test/controllers/holdings_controller_test.rb b/test/controllers/holdings_controller_test.rb
index 2d940407f1..2453d00db4 100644
--- a/test/controllers/holdings_controller_test.rb
+++ b/test/controllers/holdings_controller_test.rb
@@ -1,6 +1,7 @@
require "test_helper"
class HoldingsControllerTest < ActionDispatch::IntegrationTest
+ include SqlQueryCapture
include EntriesTestHelper
setup do
@@ -14,6 +15,29 @@ class HoldingsControllerTest < ActionDispatch::IntegrationTest
assert_response :success
end
+ # Each row shows its average cost, so the list loads them all together
+ # rather than running the per-holding fallback once per row.
+ test "the holdings list reads every row's average cost together" do
+ trade_queries = [ 2, 4 ].map do |count|
+ account = @account.family.accounts.create!(name: "Batch #{count}", balance: 0, cash_balance: 0, currency: "USD",
+ accountable: Investment.new, cost_basis_method: "fifo")
+ count.times do |i|
+ security = Security.create!(ticker: "HB#{count}#{i}", name: "HB#{count}#{i}")
+ entry = account.entries.create!(name: "Buy", date: 2.days.ago.to_date, amount: 100, currency: "USD",
+ entryable: Trade.new(security: security, qty: 10, price: 10, currency: "USD"))
+ HoldingLot.create!(account: account, security: security, source_entry: entry, qty: 10, unit_cost: 10,
+ currency: "USD", acquired_on: entry.date)
+ account.holdings.create!(security: security, date: Date.current, qty: 10, price: 12, amount: 120, currency: "USD")
+ end
+
+ queries = capture_sql_queries { get holdings_url(account_id: account.id) }
+ assert_response :success
+ queries.count { |sql| sql.include?('FROM "trades"') || sql.include?('FROM "holding_lots"') }
+ end
+
+ assert_equal trade_queries.first, trade_queries.last
+ end
+
test "warns about positions that went below zero" do
# An import that records a sale without its purchase, as a provider or CSV can.
@account.entries.create!(
diff --git a/test/controllers/trades_controller_test.rb b/test/controllers/trades_controller_test.rb
index 7cb4bed243..a8ff91f678 100644
--- a/test/controllers/trades_controller_test.rb
+++ b/test/controllers/trades_controller_test.rb
@@ -1,7 +1,7 @@
require "test_helper"
class TradesControllerTest < ActionDispatch::IntegrationTest
- include EntryableResourceInterfaceTest
+ include EntryableResourceInterfaceTest, EntriesTestHelper
include GoalPledgeTestHelper
setup do
@@ -537,6 +537,41 @@ class TradesControllerTest < ActionDispatch::IntegrationTest
assert @entry.protected_from_sync?, "Entry should be protected from sync"
end
+ test "the drawer offers the lot choice only on a fifo sale" do
+ account, buy, sale = lot_choice_account
+ lot_select = "select[name='entry[entryable_attributes][lot_source_entry_id]']"
+
+ get trade_url(sale)
+ assert_select lot_select, count: 0
+
+ account.update!(cost_basis_method: "fifo")
+ get trade_url(sale)
+ assert_select "#{lot_select} option[value='#{buy.id}']", count: 1
+
+ get trade_url(buy)
+ assert_select lot_select, count: 0
+ end
+
+ test "naming a lot on a sale saves it and restates the account" do
+ account, buy, sale = lot_choice_account(method: "fifo")
+
+ patch trade_url(sale), params: { entry: { entryable_attributes: { id: sale.entryable_id, lot_source_entry_id: buy.id } } }
+
+ assert_redirected_to account_url(account)
+ assert_enqueued_with job: SyncJob
+ assert_equal buy.id, sale.trade.reload.lot_source_entry_id
+ end
+
+ test "naming another account's lot on a sale is refused" do
+ _account, _buy, sale = lot_choice_account(method: "fifo")
+ other = families(:empty).accounts.create!(name: "Other", balance: 0, currency: "USD", accountable: Investment.new, cost_basis_method: "fifo")
+ theirs = create_trade(sale.trade.security, account: other, qty: 5, price: 10, date: 3.days.ago.to_date)
+
+ patch trade_url(sale), params: { entry: { entryable_attributes: { id: sale.entryable_id, lot_source_entry_id: theirs.id } } }
+
+ assert_response :unprocessable_entity
+ assert_nil sale.trade.reload.lot_source_entry_id
+ end
# we-promise/sure#4226: a deposit with no "from" account books a standalone
# inflow on the investment account, which must resolve its pledge.
@@ -564,6 +599,15 @@ class TradesControllerTest < ActionDispatch::IntegrationTest
end
private
+ def lot_choice_account(method: "average")
+ account = accounts(:investment)
+ account.update!(cost_basis_method: method)
+ security = Security.create!(ticker: "LOTN", name: "LOTN")
+ buy = create_trade(security, account: account, qty: 40, price: 20, date: 3.days.ago.to_date)
+ sale = create_trade(security, account: account, qty: -10, price: 25, date: 1.day.ago.to_date)
+ [ account, buy, sale ]
+ end
+
# family_member gets the investment account with full control; fixtures
# already share depository with full control and credit_card read-only,
# and leave connected private to family_admin.
diff --git a/test/models/holding_lot_disposal_test.rb b/test/models/holding_lot_disposal_test.rb
index abaed87a21..20da1f1e56 100644
--- a/test/models/holding_lot_disposal_test.rb
+++ b/test/models/holding_lot_disposal_test.rb
@@ -90,6 +90,366 @@ class HoldingLotDisposalTest < ActiveSupport::TestCase
# --- The Example from the lot cost basis proposal ---------------------------
# 60 bought at $12, 40 at $20; 40 sold at $25.
+ # --- A named lot ------------------------------------------------------------
+
+ test "under fifo a sale naming a lot consumes it first, then the oldest" do
+ book = Holding::LotBook.new(method: "fifo")
+ book.apply(BigDecimal("12"), 60, source_id: "first")
+ book.apply(BigDecimal("20"), 40, source_id: "second")
+
+ book.apply(BigDecimal("25"), -70, source_id: "sale", lot_source_id: "second")
+
+ assert_equal [ [ "second", 40, 20 ], [ "first", 30, 12 ] ], book.disposals.map { |d| [ d.lot_source_id, d.qty, d.unit_cost ] }
+ assert_equal [ [ "first", 30 ] ], book.lots.map { |lot| [ lot.source_id, lot.qty ] }
+ end
+
+ test "what is left of a named lot keeps its place, so the next sale still takes the oldest" do
+ book = Holding::LotBook.new(method: "fifo")
+ book.apply(BigDecimal("12"), 60, source_id: "first")
+ book.apply(BigDecimal("20"), 40, source_id: "second")
+ book.apply(BigDecimal("25"), -10, source_id: "named", lot_source_id: "second")
+
+ book.apply(BigDecimal("25"), -10, source_id: "unnamed")
+
+ assert_equal [ [ "named", "second" ], [ "unnamed", "first" ] ], book.disposals.map { |d| [ d.sale_id, d.lot_source_id ] }
+ assert_equal [ [ "first", 50 ], [ "second", 30 ] ], book.lots.map { |lot| [ lot.source_id, lot.qty ] }
+ end
+
+ test "under average a named lot is ignored" do
+ book = Holding::LotBook.new
+ book.apply(BigDecimal("12"), 60, source_id: "first")
+ book.apply(BigDecimal("20"), 40, source_id: "second")
+
+ book.apply(BigDecimal("25"), -40, source_id: "sale", lot_source_id: "second")
+
+ assert_equal [ [ "first", 36 ], [ "second", 24 ] ], book.lots.map { |lot| [ lot.source_id, lot.qty ] }
+ assert_equal BigDecimal("15.2"), book.average_cost
+ end
+
+ test "naming the $20 lot realizes $200 and leaves $12 avg, forward and reverse" do
+ travel_to TODAY do
+ %i[forward reverse].each do |strategy|
+ setup_account(method: "fifo")
+ @security = priced_security("NAM#{strategy.to_s[0]}", 30)
+ trade(@security, 60, 12, 2)
+ twenty = trade(@security, 40, 20, 4)
+ sale = trade(@security, -40, 25, 6)
+ if strategy == :reverse
+ link_account
+ @account.holdings.create!(security: @security, date: d(10), qty: 60, price: 30, amount: 1800, currency: "USD",
+ account_provider: @account_provider)
+ end
+ materialize(strategy)
+ assert_equal 520, gain(sale), "#{strategy}: oldest first without a name"
+
+ name_lot(sale, twenty)
+ materialize(strategy)
+
+ assert_equal 200, gain(sale), strategy
+ assert_equal 12, @account.holdings.find_by!(security: @security, date: d(9)).cost_basis, strategy
+ end
+ end
+ end
+
+ test "naming a lot larger than its open qty consumes the rest by the account method" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMR", 30)
+ trade(security, 60, 12, 2)
+ twenty = trade(security, 40, 20, 4)
+ sale = trade(security, -70, 25, 6)
+ name_lot(sale, twenty)
+ materialize(:forward)
+
+ assert_equal 1750 - 1160, gain(sale), "40 x $20 named, then 30 x $12 oldest = $1,160"
+ assert_equal 12, @account.holdings.find_by!(security: security, date: d(10)).avg_cost.amount
+ end
+ end
+
+ test "a named lot that is no longer open falls back to oldest first" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMC", 30)
+ trade(security, 60, 12, 2)
+ twenty = trade(security, 40, 20, 4)
+ name_lot(trade(security, -40, 25, 5), twenty)
+ later = trade(security, -20, 25, 6)
+ name_lot(later, twenty)
+ materialize(:forward)
+
+ assert_equal 500 - 240, gain(later), "the $20 lot is gone, so 20 x $12"
+ end
+ end
+
+ test "an average account ignores a named lot" do
+ travel_to TODAY do
+ setup_account
+ sale = example_trades
+ twenty = @account.entries.find_by!(date: d(4))
+ Trade.find(sale.entryable_id).update_columns(lot_source_entry_id: twenty.id)
+
+ assert_no_difference "HoldingLotDisposal.count" do
+ materialize(:forward)
+ end
+ assert_equal [ 392, BigDecimal("15.2") ], [ gain(sale), avg_cost_on(d(10)) ]
+ end
+ end
+
+ test "naming another account's lot is rejected" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMX", 30)
+ sale = trade(security, -10, 25, 6)
+ mine = @account
+ setup_account(method: "fifo")
+ theirs = trade(security, 40, 20, 4)
+ sale_trade = Trade.find(sale.entryable_id)
+
+ assert_not sale_trade.update(lot_source_entry: theirs)
+ assert sale_trade.errors.of_kind?(:lot_source_entry, :invalid)
+ assert_nil sale_trade.reload.lot_source_entry_id
+ assert_equal mine, sale.account
+ end
+ end
+
+ test "a sale can name only an earlier acquisition of its own security, in a fifo account" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMV", 30)
+ other_security = priced_security("NAMW", 30)
+ earlier = trade(security, 40, 20, 4)
+ later = trade(security, 40, 20, 7)
+ other = trade(other_security, 40, 20, 4)
+ another_sale = trade(security, -1, 25, 5)
+ same_day = trade(security, 5, 20, 6)
+ sale_entry = trade(security, -10, 25, 6)
+ entered_in_order(same_day, sale_entry)
+ sale = Trade.find(sale_entry.entryable_id)
+
+ [ later, other, another_sale ].each do |entry|
+ assert_not sale.update(lot_source_entry: entry), entry.name
+ sale.reload
+ end
+ assert sale.update(lot_source_entry: same_day), "an acquisition on the sale's own date"
+ assert sale.update(lot_source_entry: earlier)
+ assert_not Trade.find(earlier.entryable_id).update(lot_source_entry: earlier), "a buy names no lot"
+ transfer_out = Trade.find(trade(security, -1, 25, 6).entryable_id)
+ transfer_out.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ assert_not transfer_out.update(lot_source_entry: earlier), "a transfer out names no lot"
+
+ sale.update_columns(lot_source_entry_id: nil)
+ @account.update!(cost_basis_method: "average")
+ assert_not sale.reload.update(lot_source_entry: earlier), "an average account names no lot"
+ end
+ end
+
+ # The book replays a day's trades in the order they were entered, so a buy
+ # entered after the sale on its day is not yet a lot when the sale runs.
+ test "a same-day buy is offered only when it was entered before the sale" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMS", 30)
+ trade(security, 10, 20, 2)
+ before, sale, after = [ [ 5, 22 ], [ -3, 25 ], [ 4, 24 ] ].map { |qty, price| trade(security, qty, price, 6) }
+ entered_in_order(before, sale, after)
+
+ choices = Trade.find(sale.entryable_id).lot_choices.to_a
+ assert_includes choices, before
+ assert_not_includes choices, after
+ assert_not Trade.find(sale.entryable_id).update(lot_source_entry: after), "a buy the sale replays before"
+ end
+ end
+
+ # Rows imported together share a created_at, so a sell-to-cover on the day of
+ # its vest has nothing but the ids to order it; the vest is offered, and the
+ # replay sells from it, whichever id is lower.
+ test "a same-day buy stamped with the sale's created_at is offered and sold from" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMV", 30)
+ trade(security, 10, 20, 2)
+ sale = trade(security, -3, 25, 6)
+ vest = trade(security, 5, 22, 6)
+ Entry.where(id: [ sale.id, vest.id ]).update_all(created_at: TODAY)
+ Entry.where(id: sale.id).update_all(id: "00000000-0000-0000-0000-000000000001")
+ Entry.where(id: vest.id).update_all(id: "ffffffff-ffff-ffff-ffff-ffffffffffff")
+ vest_id = "ffffffff-ffff-ffff-ffff-ffffffffffff"
+
+ sale_trade = Trade.find(sale.entryable_id)
+ assert_includes sale_trade.lot_choices.pluck(:id), vest_id
+ sale_trade.update!(lot_source_entry_id: vest_id)
+
+ materialize(:forward)
+
+ assert_equal [ [ vest_id, 3 ] ], HoldingLotDisposal.where(sale_entry_id: "00000000-0000-0000-0000-000000000001").pluck(:lot_source_entry_id, :qty).map { |id, qty| [ id, qty.to_i ] }
+ end
+ end
+
+ test "a sale's held choice stays offered even once the replay no longer reaches it first" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMU", 30)
+ trade(security, 10, 20, 2)
+ sale = trade(security, -3, 25, 6)
+ after = trade(security, 4, 24, 6)
+ entered_in_order(sale, after)
+ Trade.where(id: sale.entryable_id).update_all(lot_source_entry_id: after.id)
+
+ assert_includes Trade.find(sale.entryable_id).lot_choices.to_a, after
+ end
+ end
+
+ test "a named same-day lot entered before the sale is the one it sells from" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMT", 30)
+ trade(security, 10, 20, 2)
+ same_day = trade(security, 5, 22, 6)
+ sale = trade(security, -3, 25, 6)
+ entered_in_order(same_day, sale)
+ name_lot(sale, same_day)
+
+ materialize(:forward)
+
+ assert_equal [ [ same_day.id, 3 ] ], HoldingLotDisposal.where(sale_entry_id: sale.id).pluck(:lot_source_entry_id, :qty).map { |id, qty| [ id, qty.to_i ] }
+ end
+ end
+
+ test "editing a sale keeps a choice it already holds, even one it could no longer make" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMK", 30)
+ twenty = trade(security, 40, 20, 4)
+ sale = trade(security, -10, 25, 6)
+ name_lot(sale, twenty)
+ @account.update!(cost_basis_method: "average")
+ sale_trade = Trade.find(sale.entryable_id)
+ assert_empty sale_trade.lot_choices, "an average account offers none"
+
+ assert sale_trade.update(qty: -5, price: 26)
+ assert_equal twenty.id, sale_trade.reload.lot_source_entry_id
+ end
+ end
+
+ # A lot earlier sales emptied cannot be sold from, so it is not offered; a
+ # lot the sale itself (or a later one) emptied was still open on its date.
+ test "a sale is offered only the lots still open on its date" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMO", 30)
+ first = trade(security, 10, 20, 2)
+ first_sale = trade(security, -10, 25, 3)
+ second = trade(security, 10, 22, 4)
+ later_sale = trade(security, -5, 25, 6)
+ materialize(:forward)
+
+ assert_equal [ first ], Trade.find(first_sale.entryable_id).lot_choices.to_a, "the lot this sale emptied"
+ assert_equal [ second ], Trade.find(later_sale.entryable_id).lot_choices.to_a, "the lot an earlier sale emptied was offered"
+ assert_not Trade.find(later_sale.entryable_id).update(lot_source_entry: first), "a sold-out lot can be named by a crafted submit"
+ end
+ end
+
+ # Two sales on one day replay in the order they were entered, so a lot the
+ # first one emptied is gone before the second runs. Offering it would let
+ # the second name a lot the replay can no longer find, and the book would
+ # fall back to oldest-first without saying so.
+ test "a lot an earlier sale on the same day emptied is not offered" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMS", 30)
+ first = trade(security, 10, 20, 2)
+ second = trade(security, 10, 22, 3)
+ first_sale = trade(security, -10, 25, 5)
+ later_sale = trade(security, -5, 25, 5)
+ entered_in_order(first_sale, later_sale)
+ materialize(:forward)
+
+ assert_equal [ first, second ], Trade.find(first_sale.entryable_id).lot_choices.to_a, "both lots are open when the first sale runs"
+ assert_equal [ second ], Trade.find(later_sale.entryable_id).lot_choices.to_a, "the lot the earlier sale that day emptied was offered"
+ assert_not Trade.find(later_sale.entryable_id).update(lot_source_entry: first)
+ end
+ end
+
+ # A transfer out consumes lots without recording a disposal, so a lot it
+ # emptied after the sale looks the same as one emptied before it. The lot
+ # was still open on the sale's date, so it stays offered and can be named.
+ test "a lot a later transfer out emptied is still offered" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMT", 30)
+ trade(security, 10, 20, 2)
+ second = trade(security, 10, 22, 3)
+ sale = trade(security, -5, 25, 4)
+ transfer_out(security, -15, 6)
+ materialize(:forward)
+
+ assert_equal 0, HoldingLot.derived.find_by!(source_entry_id: second.id).qty, "the transfer out empties the lot"
+ assert_includes Trade.find(sale.entryable_id).lot_choices.to_a, second
+ assert Trade.find(sale.entryable_id).update(lot_source_entry: second), "a lot open on the sale's date can be named"
+ end
+ end
+
+ test "lots a transfer out emptied before the sale are not offered" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMU", 30)
+ first = trade(security, 10, 20, 2)
+ second = trade(security, 10, 22, 3)
+ transfer_out(security, -20, 4)
+ third = trade(security, 10, 24, 5)
+ sale = trade(security, -5, 25, 6)
+ materialize(:forward)
+
+ assert_equal [ third ], Trade.find(sale.entryable_id).lot_choices.to_a
+ assert_not Trade.find(sale.entryable_id).update(lot_source_entry: first)
+ end
+ end
+
+ # An opening lot has no acquisition, and an empty one (a clamp records
+ # one) must not empty the list with it.
+ test "an empty opening lot leaves the sale's choices alone" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMZ", 30)
+ buy = trade(security, 10, 20, 2)
+ materialize(:forward)
+ HoldingLot.create!(account: @account, security: security, origin_security: security, qty: 0, currency: "USD", clamped: true)
+ # Entered since the last sync, so no disposal is dated on or after it.
+ sale = trade(security, -5, 25, 6)
+
+ assert_equal [ buy ], Trade.find(sale.entryable_id).lot_choices.to_a
+ end
+ end
+
+ test "a sale's held choice stays offered once its lot is sold out" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMH", 30)
+ first = trade(security, 10, 20, 2)
+ trade(security, -10, 25, 3)
+ second = trade(security, 10, 22, 4)
+ later_sale = Trade.find(trade(security, -5, 25, 6).entryable_id)
+ later_sale.update_columns(lot_source_entry_id: first.id)
+ materialize(:forward)
+
+ assert_equal [ first, second ], later_sale.reload.lot_choices.to_a
+ end
+ end
+
+ test "deleting the named acquisition clears the choice" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ security = priced_security("NAMD", 30)
+ twenty = trade(security, 40, 20, 4)
+ sale = trade(security, -10, 25, 6)
+ name_lot(sale, twenty)
+
+ twenty.destroy!
+
+ assert_nil Trade.find(sale.entryable_id).lot_source_entry_id
+ end
+ end
+
test "fifo consumes the oldest lot first" do
travel_to TODAY do
average = example(method: "average")
@@ -223,6 +583,98 @@ class HoldingLotDisposalTest < ActiveSupport::TestCase
end
end
+ # --- The avg-cost fallback on a fifo account --------------------------------
+
+ test "a linked fifo account's current row falls back to the open lots" do
+ travel_to TODAY do
+ linked_example(method: "average")
+ assert_nil current_row.cost_basis
+ assert_equal BigDecimal("15.2"), fallback_cost(current_row), "average: the pool, unchanged"
+
+ twenty, sale = linked_example(method: "fifo")
+ assert_nil current_row.cost_basis, "the provider gives no cost, so the fallback answers"
+ assert_in_delta BigDecimal("17.3333"), fallback_cost(current_row), BigDecimal("0.0001")
+
+ name_lot(sale, twenty)
+ materialize(:reverse)
+ assert_equal 12, fallback_cost(current_row)
+ end
+ end
+
+ test "a fifo row the lots cannot describe is unknown, not the pooled average" do
+ travel_to TODAY do
+ linked_example(method: "fifo")
+ earlier = @account.holdings.find_by!(security: @security, date: d(9))
+ earlier.update_columns(cost_basis: nil)
+ assert_nil fallback_cost(earlier), "an earlier row: the lots are today's"
+
+ lot = HoldingLot.derived.where(account: @account).where("qty > 0").first
+ lot.update_columns(qty: lot.qty - 1)
+ assert_nil fallback_cost(current_row), "lots out of partition"
+ end
+ end
+
+ test "a sold-off transfer-in no longer blanks a fifo fallback" do
+ travel_to TODAY do
+ figures = %w[average fifo].map do |method|
+ setup_account(method: method)
+ link_account
+ @security = priced_security("LFT#{method[0]}", 30)
+ trade(@security, 10, 30, 2).entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ trade(@security, 10, 12, 3)
+ trade(@security, -10, 30, 5)
+ @account.holdings.create!(security: @security, date: d(10), qty: 10, price: 30, amount: 300, currency: "USD",
+ account_provider: @account_provider)
+ materialize(:reverse)
+ fallback_cost(current_row)
+ end
+
+ assert_equal [ nil, 12 ], figures
+ end
+ end
+
+ test "an open transfer-in lot with no cost leaves the fifo fallback unknown" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ link_account
+ @security = priced_security("LFU", 30)
+ trade(@security, 10, 30, 2).entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ trade(@security, 10, 12, 3)
+ @account.holdings.create!(security: @security, date: d(10), qty: 20, price: 30, amount: 600, currency: "USD",
+ account_provider: @account_provider)
+ materialize(:reverse)
+
+ assert_nil fallback_cost(current_row)
+ end
+ end
+
+ test "units held before the first trade stay out of the fifo fallback, as they stay out of the book" do
+ travel_to TODAY do
+ build_reverse_fixture(pre_history: 5)
+ materialize(:reverse)
+ assert HoldingLot.opening.where(account: @account).sole.qty.positive?, "1 of the 5 is still open"
+
+ assert_equal 150, fallback_cost(current_row)
+ assert_equal 150, @account.holdings.find_by!(security: @security, date: d(9)).cost_basis, "the calculators' figure"
+ end
+ end
+
+ test "a clamped fifo position stays unknown" do
+ travel_to TODAY do
+ setup_account(method: "fifo")
+ link_account
+ @security = priced_security("LFK", 30)
+ trade(@security, 5, 100, 2)
+ trade(@security, 5, 150, 3)
+ @account.holdings.create!(security: @security, date: d(10), qty: 3, price: 30, amount: 90, currency: "USD",
+ account_provider: @account_provider)
+ materialize(:reverse)
+ assert HoldingLot.where(account: @account, clamped: true).exists?
+
+ assert_nil fallback_cost(current_row)
+ end
+ end
+
test "realized gain reads the persisted consumption, not the post-sale snapshot" do
travel_to TODAY do
setup_account(method: "fifo")
@@ -400,12 +852,6 @@ class HoldingLotDisposalTest < ActiveSupport::TestCase
account_provider: @account_provider)
end
- # Under travel_to every entry shares one created_at; spread them out in the
- # order given.
- def entered_in_order(*entries)
- entries.each_with_index { |entry, index| entry.update_columns(created_at: TODAY - (entries.size - index).minutes) }
- end
-
def materialize(strategy)
Holding::Materializer.new(@account.reload, strategy: strategy).materialize_holdings
end
@@ -413,4 +859,48 @@ class HoldingLotDisposalTest < ActiveSupport::TestCase
def gain(entry)
Trade.find(entry.entryable_id).realized_gain_loss&.value&.amount
end
+
+ # The clock is frozen, so entries made one after another share a created_at
+ # and the replay would order them by id; set the order they were entered.
+ def entered_in_order(*entries)
+ entries.each_with_index { |entry, index| entry.update_columns(created_at: TODAY + index.seconds) }
+ end
+
+ def transfer_out(security, qty, day)
+ entry = trade(security, qty, 25, day)
+ entry.entryable.update!(investment_activity_label: Trade::TRANSFER_LABEL)
+ entry
+ end
+
+ def name_lot(sale, lot)
+ Trade.find(sale.entryable_id).update!(lot_source_entry: lot)
+ end
+
+ def avg_cost_on(date)
+ @account.holdings.find_by!(security: @security, date: date).avg_cost.amount
+ end
+
+ # The Example on a linked account whose provider holds the remaining 60
+ # and gives no cost for them.
+ def linked_example(method:)
+ setup_account(method: method)
+ link_account
+ @security = priced_security("LFX#{method[0]}", 30)
+ trade(@security, 60, 12, 2)
+ twenty = trade(@security, 40, 20, 4)
+ sale = trade(@security, -40, 25, 6)
+ @account.holdings.create!(security: @security, date: d(10), qty: 60, price: 30, amount: 1800, currency: "USD",
+ account_provider: @account_provider)
+ materialize(:reverse)
+ [ twenty, sale ]
+ end
+
+ def current_row
+ @account.holdings.find_by!(security: @security, date: d(10))
+ end
+
+ # Holding#avg_cost on a fresh copy, so no earlier answer is reused.
+ def fallback_cost(holding)
+ Holding.find(holding.id).avg_cost&.amount
+ end
end
diff --git a/test/models/holding_test.rb b/test/models/holding_test.rb
index f2791b7cfa..da7d8dd41a 100644
--- a/test/models/holding_test.rb
+++ b/test/models/holding_test.rb
@@ -295,6 +295,55 @@ class HoldingTest < ActiveSupport::TestCase
assert_equal own, batched, "the batch disagrees with #avg_cost"
end
+ # A fifo position holds its open lots, so with no stored cost its fallback
+ # is their mean, as #calculate_avg_cost gives it: 20 here, where the
+ # average method would say 15. The batch reads every fifo holding's lots together, so a page of them
+ # costs the same few queries however many there are.
+ test "the batch answers a fifo holding from its open lots, in a fixed number of queries" do
+ @account.update!(cost_basis_method: "fifo")
+ queries_for = ->(count) do
+ holdings = Array.new(count) do |i|
+ security = create_security("FIFO#{count}#{i}", prices: (0..3).map { |d| { date: d.days.ago.to_date, price: 30 } })
+ create_trade(security, account: @account, qty: 10, price: 10, date: 3.days.ago.to_date)
+ create_trade(security, account: @account, qty: 10, price: 20, date: 2.days.ago.to_date)
+ create_trade(security, account: @account, qty: -10, price: 30, date: 1.day.ago.to_date)
+ security
+ end
+ Holding::Materializer.new(@account.reload, strategy: :forward).materialize_holdings
+ # The fallback is for a position with no stored cost, as a provider's
+ # often is; the materializer stores one, so take it away.
+ batch = holdings.map { |security| @account.holdings.where(security: security).order(:date).last }
+ Holding.where(id: batch.map(&:id)).update_all(cost_basis: nil)
+ batch.each(&:reload)
+
+ queries = capture_sql_queries { Holding.preload_avg_costs(batch) }
+ batch.each do |holding|
+ assert_equal BigDecimal("20"), holding.avg_cost&.amount, "the batch's figure for #{holding.ticker}"
+ assert_equal BigDecimal("20"), Holding.find(holding.id).avg_cost&.amount, "#avg_cost for #{holding.ticker}"
+ end
+ queries.size
+ end
+
+ assert_equal queries_for.(1), queries_for.(3)
+ end
+
+ # The account decides fifo, not the trades joined up to the holding's date:
+ # a provider's row can predate the trade behind lots it already holds.
+ test "the batch answers a fifo holding whose row predates its trades" do
+ @account.update!(cost_basis_method: "fifo")
+ security = create_security("FIFOE", prices: [ { date: Date.current, price: 30 } ])
+ buy = create_trade(security, account: @account, qty: 10, price: 20, date: Date.current)
+ HoldingLot.create!(account: @account, security: security, source_entry: buy, qty: 10, unit_cost: 20,
+ currency: "USD", acquired_on: Date.current)
+ holding = @account.holdings.create!(security: security, date: 1.day.ago.to_date, qty: 10, price: 30, amount: 300, currency: "USD")
+
+ batch = [ Holding.find(holding.id) ]
+ Holding.preload_avg_costs(batch)
+
+ assert_equal BigDecimal("20"), Holding.find(holding.id).avg_cost&.amount, "#avg_cost"
+ assert_equal BigDecimal("20"), batch.first.avg_cost&.amount, "the batch's figure"
+ end
+
test "the batch leaves a stored cost basis alone and does not query for it" do
@amzn.update!(cost_basis: 100)
create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: Date.current)