The personal finance app for everyone (by everyone)
Ruby
Edit a lot's cost, and merge opening lots on remap (#4901)
jaysbeekay0b8c6961516d
diff --git a/app/controllers/holding_lots_controller.rb b/app/controllers/holding_lots_controller.rbnew file mode 100644index 0000000000..e44e6d9697--- /dev/null+++ b/app/controllers/holding_lots_controller.rb@@ -0,0 +1,84 @@+# The cost of one lot of a holding's position. Only a lot a trade acquired is+# editable: the opening lot stays out of the position's figure, so a cost set+# on it would change nothing the user can see. Nor can a cost be set on any+# lot while the provider supplies the position's cost, since restatement+# leaves the provider's rows alone; a cost set earlier can still be cleared,+# as fifo disposals still read it. A change is restated into the holdings+# straight away, as a price sync is, and the two commit together or not at+# all.+class HoldingLotsController < ApplicationController+ before_action :set_holding+ before_action :require_holding_write_permission!+ before_action :refuse_provider_cost!, only: :update+ before_action :set_lot++ def update+ # Strict, since String#to_d reads "abc" as 0 and "12abc" as 12.+ total = BigDecimal(lot_params[:total_cost_basis].to_s, exception: false)++ # The provider-cost refusal is checked again under the lock, against the+ # holding as it is now.+ updated = total && restating { [email protected]_cost_position? && @lot.update(manual_total_cost: total) }++ if updated+ flash[:notice] = t(".success")+ else+ flash[:alert] = t(".error")+ end++ redirect_to account_path(@holding.account, tab: "holdings")+ end++ def unlock+ restating { @lot.unlock_cost! }++ redirect_to account_path(@holding.account, tab: "holdings"), notice: t(".success")+ end++ private+ def set_holding+ @holding = Current.family.holdings+ .joins(:account)+ .merge(Account.accessible_by(Current.user))+ .find(params[:holding_id])+ end++ def require_holding_write_permission!+ require_account_permission!(@holding.account)+ end++ def refuse_provider_cost!+ return unless @holding.provider_cost_position?++ redirect_to account_path(@holding.account, tab: "holdings"), alert: t("holding_lots.provider_cost")+ end++ def set_lot+ @lot = HoldingLot.derived.where(account_id: @holding.account_id, security_id: @holding.security_id).find(params[:id])+ end++ def lot_params+ params.require(:holding_lot).permit(:total_cost_basis)+ end++ # Changes the lot and restates the position in one transaction under the+ # account row lock, taken first as a sync takes it, so a failed+ # restatement rolls the lot back and an edit and a sync of the same account+ # do not interleave. The holding and the lot are read again once the lock+ # is held, since a remap may have moved them while the request waited.+ # Restates only when the change is saved; returns whether it was.+ def restating+ account = @holding.account++ account.with_lock do+ @holding.reload+ set_lot+ changed = yield+ if changed+ strategy = account.linked? ? :reverse : :forward+ Balance::Materializer.new(account, strategy: strategy, security_ids: [ @holding.security_id ]).materialize_balances+ end+ changed+ end+ end+enddiff --git a/app/controllers/holdings_controller.rb b/app/controllers/holdings_controller.rbindex a02c1eae7a..98ed94a9e5 100644--- a/app/controllers/holdings_controller.rb+++ b/app/controllers/holdings_controller.rb@@ -13,6 +13,13 @@ class HoldingsController < ApplicationControllerdef show@last_price_updated = @holding.security.prices.maximum(:updated_at)+ @lots = @holding.open_lots.to_a+ # The lots partial gates its edit affordances on these, as+ # HoldingLotsController refuses the writes: a read-only share edits+ # nothing, and under a provider's cost a lot's manual cost can only be+ # cleared.+ @lots_provider_cost = @lots.any? && @holding.provider_cost_position?+ @can_write_lots = Account.writable_by(Current.user).exists?(id: @holding.account_id)enddef update@@ -88,15 +95,18 @@ class HoldingsController < ApplicationControllernew_security.save!- @holding.remap_security!(new_security)-- # Re-materialize holdings with the new security's prices.- # Reload account to avoid stale associations from remap_security!.+ # The remap and the re-materialization with the new security's prices+ # commit together under the account row lock, taken first as a sync and a+ # lot edit take it. The materializer's own lock! reloads the account, so+ # it reads no associations cached before the remap.# The around_action :switch_timezone already sets the family timezone# for this request, so Date.current is correct here.account = Account.find(@holding.account_id)- strategy = account.linked? ? :reverse : :forward- Balance::Materializer.new(account, strategy: strategy, security_ids: [ new_security.id ]).materialize_balances+ account.with_lock do+ @holding.remap_security!(new_security)+ strategy = account.linked? ? :reverse : :forward+ Balance::Materializer.new(account, strategy: strategy, security_ids: [ new_security.id ]).materialize_balances+ endflash[:notice] = t(".success")@@ -145,7 +155,21 @@ class HoldingsController < ApplicationControllerenddef reset_security- @holding.reset_security_to_provider!+ security_ids = [ @holding.security_id, @holding.provider_security_id ]+ reset = @holding.provider_security_id.present?++ # The reset and the re-materialization of both securities, as a remap+ # re-materializes its target, commit together under the account row lock,+ # so the lots and holdings each takes back match before the next sync.+ account = Account.find(@holding.account_id)+ account.with_lock do+ @holding.reset_security_to_provider!+ if reset+ strategy = account.linked? ? :reverse : :forward+ Balance::Materializer.new(account, strategy: strategy, security_ids: security_ids).materialize_balances+ end+ end+flash[:notice] = t(".success")respond_to do |format|diff --git a/app/models/balance/chart_series_builder.rb b/app/models/balance/chart_series_builder.rbindex dce9f8dea7..cd09821244 100644--- a/app/models/balance/chart_series_builder.rb+++ b/app/models/balance/chart_series_builder.rb@@ -289,7 +289,7 @@ class Balance::ChartSeriesBuilderON accounts.active_until_date IS NULL OR d.date <= accounts.active_until_dateLEFT JOIN account_securities sec ON sec.account_id = accounts.idLEFT JOIN LATERAL (- SELECT h.amount, h.qty, h.currency+ SELECT h.date, h.amount, h.qty, h.currencyFROM holdings hWHERE h.account_id = accounts.idAND h.security_id = sec.security_id@@ -301,6 +301,10 @@ class Balance::ChartSeriesBuilder-- gap-filled holding rows (weekends, price-history gaps) are persisted without-- cost_basis even though the position and basis are unchanged, so the basis is-- carried forward from the last real snapshot instead of zeroing those points.+ -- A calculated zero carries the same way, except past a later row the+ -- materializer cleared as unknown (a transfer in): no cost, no source and not+ -- a provider's row. A provider's row is never written by the materializer,+ -- so a missing cost there does not stop the carry.LEFT JOIN LATERAL (SELECT h2.cost_basisFROM holdings h2@@ -308,7 +312,24 @@ class Balance::ChartSeriesBuilderAND h2.security_id = sec.security_idAND h2.date <= d.dateAND h2.cost_basis IS NOT NULL- AND (h2.cost_basis_locked OR h2.cost_basis > 0)+ AND (+ h2.cost_basis_locked+ OR h2.cost_basis > 0+ OR (+ h2.cost_basis_source = 'calculated'+ AND NOT EXISTS (+ SELECT 1+ FROM holdings cleared+ WHERE cleared.account_id = h2.account_id+ AND cleared.security_id = h2.security_id+ AND cleared.date > h2.date+ AND cleared.date <= last_h.date+ AND cleared.cost_basis IS NULL+ AND cleared.cost_basis_source IS NULL+ AND cleared.account_provider_id IS NULL+ )+ )+ )ORDER BY h2.date DESCLIMIT 1) last_basis ON TRUEdiff --git a/app/models/balance/materializer.rb b/app/models/balance/materializer.rbindex 596ffc4ad3..1eb75a3607 100644--- a/app/models/balance/materializer.rb+++ b/app/models/balance/materializer.rb@@ -15,6 +15,11 @@ class Balance::Materializerdef materialize_balancesBalance.transaction do+ # Every materialization of an account -- a sync, or a lot edit's+ # restatement -- locks the account row before writing anything, so two of+ # them serialise in one lock order rather than deadlocking on each other's+ # holding rows.+ account.lock!materialize_holdingscalculate_balancesdiff --git a/app/models/holding.rb b/app/models/holding.rbindex e0112c6626..3742ff969e 100644--- a/app/models/holding.rb+++ b/app/models/holding.rb@@ -51,9 +51,11 @@ class Holding < ApplicationRecord# The stored per-share cost when it is a real value:# - If locked (user-set), trust the value even if 0 (valid for airdrops)+ # - If worked out from the trades and lots, trust 0 too: a lot the user+ # says cost nothing, or a buy at a price of 0# - Otherwise require positive since providers sometimes return 0 when unknowndef known_cost_basis- cost_basis if cost_basis.present? && (cost_basis_locked? || cost_basis.positive?)+ cost_basis if cost_basis.present? && (cost_basis_locked? || cost_basis.positive? || cost_basis_source == "calculated")end# Returns average cost per share, or nil if unknown.@@ -244,6 +246,26 @@ class Holding < ApplicationRecordnew_priority >= cost_basis_source_priorityend+ # The position's open lots, the opening lot first and then by acquisition.+ # The stored lots are the position as it stands, so only its latest row+ # shows them, and only while they add up to it (HoldingLot.in_partition).+ def open_lots+ return HoldingLot.none unless date == account.holdings.where(security_id: security_id).maximum(:date)+ return HoldingLot.none unless HoldingLot.in_partition([ account_id ], [ security_id ]).include?([ account_id, security_id ])++ HoldingLot.where(account_id: account_id, security_id: security_id).where("qty > 0")+ .order(Arel.sql("acquired_on ASC NULLS FIRST"), :created_at)+ end++ # Whether the provider supplies the position's cost: its latest row, the one+ # its lots describe, holds a provider's figure. Restatement leaves a+ # provider's rows alone, so a lot cost set under it would change nothing the+ # position shows.+ def provider_cost_position?+ latest = account.holdings.where(security_id: security_id).order(date: :desc, id: :asc).first+ latest.present? && latest.cost_basis_source == "provider" && latest.known_cost_basis.present?+ end+# Set cost_basis from user input (locks the value)def set_manual_cost_basis!(value)update!(diff --git a/app/models/holding/forward_calculator.rb b/app/models/holding/forward_calculator.rbindex 480f0fef0f..59398e2be6 100644--- a/app/models/holding/forward_calculator.rb+++ b/app/models/holding/forward_calculator.rb@@ -114,12 +114,14 @@ class Holding::ForwardCalculatortrade = trade_entry.entryablesecurity_id = trade.security_idprevious_quantity = portfolio[security_id] || 0+ manual_cost = manual_unit_cost(trade_entry)- if trade.internal_movement?+ if trade.internal_movement? && manual_cost.nil?# An inbound transfer brings in units at a price nothing here knows, so- # it makes the whole position's cost basis unknowable. An outbound- # transfer only removes units, so relieve them at the running average- # (like a sell) rather than leaving them to contaminate a later buy.+ # it makes the whole position's cost basis unknowable, unless the user+ # has said what its lot cost. An outbound transfer only removes units,+ # so relieve them at the running average (like a sell) rather than+ # leaving them to contaminate a later buy.if trade.qty.positive?@transferred_security_ids << security_id@lot_books[security_id].add_unknown(trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)@@ -127,7 +129,8 @@ class Holding::ForwardCalculator@lot_books[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty)endelse- @lot_books[security_id].apply(effective_trade_price(trade, date: trade_entry.date), trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)+ 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)endportfolio[security_id] = previous_quantity + trade.qty@@ -149,11 +152,12 @@ class Holding::ForwardCalculator@lot_books[security_id].average_costend- # Under fifo a transfer-in stops mattering once its lot is sold, so the- # book answers; under average it is unknown until the position closes.+ # Under fifo a transfer-in or an unpriced buy stops mattering once its lot+ # is sold, so the book answers; under average either is unknown until the+ # position closes.def cost_unknown?(security_id)return @lot_books[security_id].unknown_cost? if account.cost_basis_fifo?- @transferred_security_ids.include?(security_id)+ @transferred_security_ids.include?(security_id) || @lot_books[security_id].unpriced?endenddiff --git a/app/models/holding/lot_book.rb b/app/models/holding/lot_book.rbindex e2a7ded1d2..1ac3e80561 100644--- a/app/models/holding/lot_book.rb+++ b/app/models/holding/lot_book.rb@@ -137,6 +137,13 @@ class Holding::LotBook@total_cost / @total_qtyend+ # Whether the pool took a buy at a price nothing here knows (no rate for its+ # currency on the day), which leaves the average unknown until the position+ # closes.+ def unpriced?+ @unknown+ end+# An open lot a trade brought in at a cost nothing here knows.def unknown_cost?@lots.any? { |lot| lot.source_id && lot.unit_cost.nil? }diff --git a/app/models/holding/reverse_calculator.rb b/app/models/holding/reverse_calculator.rbindex 121ad38ca2..3130c0ee65 100644--- a/app/models/holding/reverse_calculator.rb+++ b/app/models/holding/reverse_calculator.rb@@ -197,10 +197,12 @@ class Holding::ReverseCalculatorsecurity_id = trade.security_idprevious_position = positions[security_id]positions[security_id] += trade.qty+ manual_cost = manual_unit_cost(trade_entry)- if trade.internal_movement?- # Inbound transfers make the basis unknown from that date on; outbound- # transfers only remove units, so relieve them at the running average.+ if trade.internal_movement? && manual_cost.nil?+ # Inbound transfers make the basis unknown from that date on, unless+ # the user has said what the lot cost; outbound transfers only remove+ # units, so relieve them at the running average.if trade.qty.positive?open_unknown_start[security_id] ||= trade_entry.date@lot_books[security_id].add_unknown(trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)@@ -212,7 +214,8 @@ class Holding::ReverseCalculatorbook = @lot_books[security_id]# 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.- book.apply(effective_trade_price(trade, date: trade_entry.date), trade.qty, source_id: trade_entry.id, acquired_on: trade_entry.date)+ 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)# 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@@ -270,20 +273,24 @@ class Holding::ReverseCalculatorevents.sort_by { |date, kind, index, _| [ date, kind, index ] }.map(&:last)end- # [date, cost basis, whether an open lot's cost is unknown]. A transfer-in- # leaves the average where it was, so its entry repeats the last figure.+ # [date, cost basis, whether the cost is unknown]: under fifo, whether an+ # open lot's cost is; under average, whether the pool took an unpriced buy.+ # A transfer-in leaves the average where it was, so its entry repeats the+ # last figure.def record_cost_basis(security_id, date)book = @lot_books[security_id]- @cost_basis_snapshots[security_id] << [ date, book.average_cost, account.cost_basis_fifo? && book.unknown_cost? ]+ unknown = account.cost_basis_fifo? ? book.unknown_cost? : book.unpriced?+ @cost_basis_snapshots[security_id] << [ date, book.average_cost, unknown ]end- # Under fifo a transfer-in stops mattering once its lot is sold, so the- # book's own answer on the day counts; under average it is unknown until- # the position closes.+ # Under fifo a transfer-in or an unpriced buy stops mattering once its lot+ # is sold, so the book's own answer on the day counts; under average either+ # is unknown until the position closes.def transferred_by?(security_id, date)- return cost_basis_snapshot(security_id, date)&.last || false if account.cost_basis_fifo?+ recorded = cost_basis_snapshot(security_id, date)&.last || false+ return recorded if account.cost_basis_fifo?- @unknown_spans[security_id].any? { |start, stop| start <= date && (stop.nil? || date < stop) }+ recorded || @unknown_spans[security_id].any? { |start, stop| start <= date && (stop.nil? || date < stop) }enddef cost_basis_for(security_id, date)diff --git a/app/models/holding/trade_calculator_helpers.rb b/app/models/holding/trade_calculator_helpers.rbindex b7b8812183..eca1169150 100644--- a/app/models/holding/trade_calculator_helpers.rb+++ b/app/models/holding/trade_calculator_helpers.rb@@ -11,6 +11,25 @@ module Holding::TradeCalculatorHelpersbooks.filter_map { |security_id, book| [ security_id, book.disposals ] if book.respond_to?(:disposals) }.to_hend+ # The cost per unit the user set for the lot an acquisition opened: the+ # parcel's total over the units the trade brought in, so later splits and+ # sales scale it like any other lot cost. nil where the lot has none.+ def manual_unit_cost(trade_entry)+ trade = trade_entry.entryable+ return unless trade.qty&.positive?++ total = manual_lot_costs[trade_entry.id]+ total / trade.qty if total+ end++ # Keyed by the acquiring entry, which is unique in the account. Not scoped+ # to the run's securities: a trade can move to another security before+ # its lot does, and its lot's figure still applies to it.+ def manual_lot_costs+ @manual_lot_costs ||= HoldingLot.derived.where(account_id: account.id).where.not(manual_total_cost: nil)+ .pluck(:source_entry_id, :manual_total_cost).to_h+ end+# Converts a trade's price into the account's currency at the rate of the# day it was made, or nil when there is no rate for that day.def converted_trade_price(trade, date:)diff --git a/app/models/holding_lot.rb b/app/models/holding_lot.rbindex b4eaa91c00..9b3d523c76 100644--- a/app/models/holding_lot.rb+++ b/app/models/holding_lot.rb@@ -8,13 +8,45 @@ class HoldingLot < ApplicationRecordbelongs_to :source_entry, class_name: "Entry", optional: truebelongs_to :origin_security, class_name: "Security", optional: true+ # A cost per unit is stored with 15 digits before the point, as a+ # holding's cost basis is, so it stays below 10^15.+ MAX_UNIT_COST = BigDecimal("1e15")+scope :derived, -> { where.not(source_entry_id: nil) }scope :opening, -> { where(source_entry_id: nil) }+ validates :manual_total_cost, numericality: { greater_than_or_equal_to: 0, less_than: BigDecimal("1e15") }, allow_nil: true+ validate :manual_unit_cost_fits, if: :manual_total_cost+def opening?source_entry_id.nil?end+ # What the user says the parcel cost when it was acquired, in the account's+ # currency. The calculators spread it over the acquiring trade's quantity,+ # so it holds through later splits and sales.+ def set_manual_total_cost!(total)+ update!(manual_total_cost: total)+ end++ def unlock_cost!+ update!(manual_total_cost: nil)+ end++ def manual_cost?+ !manual_total_cost.nil?+ end++ # The places the cost editor shows a saved total to: the currency's, or as+ # many as the column keeps when the total needs them, so saving the form+ # unchanged keeps it.+ def manual_total_cost_precision+ places = Money::Currency.new(currency).default_precision+ return places if manual_total_cost.nil? || manual_total_cost.round(places) == manual_total_cost++ self.class.columns_hash["manual_total_cost"].scale+ end+class << self# Replaces an account's lots with `rows`, within `security_ids` when given,# keeping each lot's row (and id) by its key: the source entry for a derived@@ -57,14 +89,27 @@ class HoldingLot < ApplicationRecordlots.filter_map { |key, qty| key if held[key] == qty }.to_setend- # Moves lots to another security with their trades. Lots are never merged:- # derived lots keep their own rows, and an opening lot moves only where the- # target has none, since the target's own is restated over the moved units- # at the next materialization.+ # Moves lots to another security with their trades. Derived lots keep+ # their own rows. An opening lot moved onto a position with its own is+ # merged into it: the quantities add, and the cost stays only where both+ # sides know it and agree, in the same currency, since one figure cannot+ # stand for two different ones. An opening lot with no units (a clamp+ # records one) has no cost to weigh, so it is dropped rather than merged;+ # moved onto one, the units keep their own cost and the lot is no longer a+ # clamp. The merged lot keeps the target's origin until the next+ # materialization, which restates it from the latest provider snapshot.def move!(derived:, opening:, to:)derived.update_all(security_id: to.id, updated_at: Time.current)opening.find_each do |lot|- if where(account_id: lot.account_id, security_id: to.id).opening.exists?+ target = where(account_id: lot.account_id, security_id: to.id).opening.first+ if target && lot.qty.zero?+ lot.delete+ elsif target&.qty&.zero?+ target.update_columns(qty: lot.qty, unit_cost: lot.unit_cost, currency: lot.currency, clamped: false, updated_at: Time.current)+ lot.delete+ elsif target+ unit_cost = target.unit_cost if lot.unit_cost && lot.unit_cost == target.unit_cost && lot.currency == target.currency+ target.update_columns(qty: target.qty + lot.qty, unit_cost: unit_cost, updated_at: Time.current)lot.deleteelselot.update_columns(security_id: to.id, updated_at: Time.current)@@ -72,4 +117,13 @@ class HoldingLot < ApplicationRecordendendend++ private+ # The calculators divide the total by the acquiring trade's quantity.+ def manual_unit_cost_fits+ qty = source_entry&.trade&.qty+ return unless qty&.positive?++ errors.add(:manual_total_cost, :less_than, count: MAX_UNIT_COST * qty) if manual_total_cost / qty >= MAX_UNIT_COST+ endenddiff --git a/app/views/holdings/_lot_summary.html.erb b/app/views/holdings/_lot_summary.html.erbnew file mode 100644index 0000000000..ad024155fc--- /dev/null+++ b/app/views/holdings/_lot_summary.html.erb@@ -0,0 +1,21 @@+<%# locals: (lot:, editable:) %>++<span class="text-secondary">+ <%= lot.opening? ? t("holdings.lots.opening") : l(lot.acquired_on, format: :long) %>+ ·+ <span class="privacy-sensitive"><%= t("holdings.holding.shares", qty: format_quantity(lot.qty, exact: true)) %></span>+</span>+<span class="text-primary flex items-center gap-1">+ <span class="privacy-sensitive">+ <%= lot.unit_cost ? t("holdings.lots.per_unit", amount: format_money(Money.new(lot.unit_cost, lot.currency))) : t("holdings.lots.unknown") %>+ </span>+ <% if lot.manual_cost? %>+ <%= icon "lock", size: "xs", class: "text-secondary" %>+ <% end %>+ <% if editable %>+ <%# Unnamed group-open: matches ANY open ancestor disclosure (the+ Overview panel itself); follow the component's own chevron+ idiom so the pencil lights with THIS row's details only. %>+ <%= icon "pencil", size: "xs", class: "text-secondary [details[open]>summary_&]:text-primary" %>+ <% end %>+</span>diff --git a/app/views/holdings/_lot_unlock.html.erb b/app/views/holdings/_lot_unlock.html.erbnew file mode 100644index 0000000000..44bffaefc6--- /dev/null+++ b/app/views/holdings/_lot_unlock.html.erb@@ -0,0 +1,8 @@+<%# locals: (holding:, lot:) %>++<%= render DS::Button.new(text: t("holdings.lots.unlock"),+ variant: :ghost,+ size: :sm,+ href: unlock_holding_lot_path(holding, lot),+ method: :post,+ form: { data: { turbo_frame: "_top" } }) %>diff --git a/app/views/holdings/_lots.html.erb b/app/views/holdings/_lots.html.erbnew file mode 100644index 0000000000..40a93d8766--- /dev/null+++ b/app/views/holdings/_lots.html.erb@@ -0,0 +1,61 @@+<%# locals: (holding:, lots:, can_edit:, provider_cost: false) %>++<div class="space-y-2 pt-1">+ <p class="text-xs text-secondary"><%= t("holdings.lots.title") %></p>+ <% if provider_cost %>+ <p class="text-xs text-secondary">+ <%= t("holdings.lots.provider_cost_hint") %>+ <%= t("holdings.lots.provider_cost_clear_hint") if can_edit && lots.any?(&:manual_cost?) %>+ </p>+ <% end %>+ <ul class="space-y-2">+ <% lots.each do |lot| %>+ <li data-lot-id="<%= lot.id %>" class="rounded-lg border border-secondary px-3 py-2 text-sm">+ <% if can_edit && !provider_cost && !lot.opening? %>+ <%= render DS::Disclosure.new(variant: :bare, summary_class: "list-none flex items-center justify-between gap-2 focus-ring cursor-pointer") do |disclosure| %>+ <% disclosure.with_summary_content do %>+ <%= render "holdings/lot_summary", lot: lot, editable: true %>+ <% end %>++ <div class="mt-3 space-y-3">+ <%= styled_form_with url: holding_lot_path(holding, lot),+ method: :patch,+ scope: :holding_lot,+ namespace: dom_id(lot),+ class: "space-y-3",+ data: { turbo_frame: "_top" } do |f| %>+ <%= f.money_field :total_cost_basis,+ label: t("holdings.lots.total_cost_label"),+ hide_currency: true,+ currency_value_override: lot.currency,+ value: lot.manual_total_cost,+ precision: lot.manual_total_cost_precision,+ required: true,+ placeholder: "0.00",+ input_class: "privacy-sensitive privacy-sensitive-interactive",+ step: "any",+ min: 0 %>+ <p class="text-xs text-secondary"><%= t("holdings.lots.total_cost_hint") %></p>+ <div class="flex justify-end">+ <%= render DS::Button.new(text: t("holdings.lots.save"), type: "submit") %>+ </div>+ <% end %>+ <% if lot.manual_cost? %>+ <%= render "holdings/lot_unlock", holding: holding, lot: lot %>+ <% end %>+ </div>+ <% end %>+ <% else %>+ <div class="flex items-center justify-between gap-2">+ <%= render "holdings/lot_summary", lot: lot, editable: false %>+ </div>+ <% if can_edit && provider_cost && lot.manual_cost? %>+ <div class="mt-2">+ <%= render "holdings/lot_unlock", holding: holding, lot: lot %>+ </div>+ <% end %>+ <% end %>+ </li>+ <% end %>+ </ul>+</div>diff --git a/app/views/holdings/show.html.erb b/app/views/holdings/show.html.erbindex a9050db030..6d1ea3f16a 100644--- a/app/views/holdings/show.html.erb+++ b/app/views/holdings/show.html.erb@@ -127,6 +127,9 @@<%= render "holdings/cost_basis_form", holding: @holding, context: :drawer, cancel_action: "drawer-cost-basis#toggle" %></div></div>+ <% if @lots.any? %>+ <%= render "holdings/lots", holding: @holding, lots: @lots, can_edit: @can_write_lots, provider_cost: @lots_provider_cost %>+ <% end %><div class="flex items-center justify-between text-sm"><dt class="text-secondary"><%= t(".book_value_label") %></dt><dd class="text-primary">diff --git a/config/locales/views/holding_lots/en.yml b/config/locales/views/holding_lots/en.ymlnew file mode 100644index 0000000000..6db9532f54--- /dev/null+++ b/config/locales/views/holding_lots/en.yml@@ -0,0 +1,10 @@+---+en:+ holding_lots:+ provider_cost: Your provider supplies this position's cost, so its lot costs+ cannot be set.+ update:+ success: Lot cost updated.+ error: Enter what the parcel cost in total, zero or more.+ unlock:+ success: Manual cost cleared.diff --git a/config/locales/views/holdings/en.yml b/config/locales/views/holdings/en.ymlindex 88399be4df..3ef2a9cecd 100644--- a/config/locales/views/holdings/en.yml+++ b/config/locales/views/holdings/en.yml@@ -55,6 +55,19 @@ en:other: "%{count} positions"return: Total returnweight: Weight+ lots:+ title: Lots+ opening: Held before the first trade+ unknown: Unknown per unit+ per_unit: "%{amount} per unit"+ total_cost_label: Total paid for this lot+ total_cost_hint: What the whole parcel cost when you acquired it. Deleting+ its trade removes the lot and the cost you set.+ save: Save+ unlock: Clear the manual cost+ provider_cost_hint: Your provider supplies this position's cost, so its+ lot costs cannot be set.+ provider_cost_clear_hint: A cost you set earlier can still be cleared.missing_price_tooltip:description: This investment has missing values and we could not calculateits returns or value.diff --git a/config/routes.rb b/config/routes.rbindex dc5755dcff..87d31155c2 100644--- a/config/routes.rb+++ b/config/routes.rb@@ -589,6 +589,10 @@ Rails.application.routes.draw dopost :reset_securitypost :sync_pricesend++ resources :lots, only: :update, controller: "holding_lots" do+ post :unlock, on: :member+ endendresources :trades, only: %i[show new create update destroy] domember dodiff --git a/db/migrate/20261024120000_add_manual_total_cost_to_holding_lots.rb b/db/migrate/20261024120000_add_manual_total_cost_to_holding_lots.rbnew file mode 100644index 0000000000..33006b381e--- /dev/null+++ b/db/migrate/20261024120000_add_manual_total_cost_to_holding_lots.rb@@ -0,0 +1,6 @@+class AddManualTotalCostToHoldingLots < ActiveRecord::Migration[8.1]+ def change+ add_column :holding_lots, :manual_total_cost, :decimal, precision: 19, scale: 4+ add_check_constraint :holding_lots, "manual_total_cost >= 0", name: "holding_lots_manual_total_cost_non_negative"+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex cd5fe27037..2ada0e6100 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -1214,6 +1214,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) dot.boolean "clamped", default: false, null: falset.datetime "created_at", null: falset.string "currency", null: false+ t.decimal "manual_total_cost", precision: 19, scale: 4t.uuid "origin_security_id"t.decimal "qty", precision: 34, scale: 18, null: falset.uuid "security_id", null: false@@ -1225,6 +1226,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) dot.index ["origin_security_id"], name: "index_holding_lots_on_origin_security_id"t.index ["security_id"], name: "index_holding_lots_on_security_id"t.index ["source_entry_id"], name: "index_holding_lots_on_source_entry_id"+ t.check_constraint "manual_total_cost >= 0::numeric", name: "holding_lots_manual_total_cost_non_negative"t.check_constraint "qty >= 0::numeric", name: "holding_lots_qty_non_negative"enddiff --git a/test/controllers/holding_lots_controller_test.rb b/test/controllers/holding_lots_controller_test.rbnew file mode 100644index 0000000000..a0a67aa0d9--- /dev/null+++ b/test/controllers/holding_lots_controller_test.rb@@ -0,0 +1,340 @@+require "test_helper"++class HoldingLotsControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper++ setup do+ sign_in @user = users(:family_admin)+ @account = accounts(:investment)+ @security = Security.create!(ticker: "LOTC", name: "LOTC")+ Security::Price.insert_all((2.days.ago.to_date..Date.current).map { |date| { security_id: @security.id, date: date, price: 30, currency: "USD" } })+ create_trade(@security, account: @account, qty: 60, price: 12, date: 2.days.ago.to_date)+ @buy = create_trade(@security, account: @account, qty: 40, price: 20, date: 1.day.ago.to_date)+ materialize+ @holding = @account.holdings.find_by!(security: @security, date: Date.current)+ @lot = HoldingLot.find_by!(source_entry: @buy)+ end++ test "update sets one lot's cost, locks it and restates the position" do+ assert_equal BigDecimal("15.2"), @holding.cost_basis++ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }++ assert_redirected_to account_path(@account, tab: "holdings")+ assert_equal 600, @lot.reload.manual_total_cost+ assert_equal BigDecimal("13.2"), @holding.reload.cost_basis, "(720 + 600) / 100, without waiting for a sync"+ end++ # A restatement and a sync of the same account both lock the account row+ # before writing any holdings, so they serialise in one lock order. The lot+ # change is made under that lock too.+ # A remap can commit while the request waits for the account lock; the+ # request then acts on where the holding and its lot are now.+ test "an edit made while a remap moves the lot restates the security it moved to" do+ moved_to = securities(:msft)+ Account.any_instance.stubs(:lock!).with do |*|+ Holding.where(id: @holding.id).update_all(security_id: moved_to.id)+ HoldingLot.where(id: @lot.id).update_all(security_id: moved_to.id)+ true+ end.returns(true)+ materializer = stub(materialize_balances: true)+ Balance::Materializer.expects(:new).with(anything, has_entry(security_ids: [ moved_to.id ])).returns(materializer)++ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }++ assert_equal 600, @lot.reload.manual_total_cost+ end++ # The provider-cost refusal is checked again under the lock, since a sync+ # or remap may have handed the position a provider's cost while it waited.+ test "an edit is refused if the provider's cost arrives while it waits for the lock" do+ Account.any_instance.stubs(:lock!).with do |*|+ Holding.where(id: @holding.id).update_all(cost_basis: 18, cost_basis_source: "provider")+ true+ end.returns(true)++ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }++ assert_nil @lot.reload.manual_total_cost+ end++ test "an edit changes the lot and restates under the account's row lock, taken first" do+ expect_locked_restate(:update)++ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }++ assert_redirected_to account_path(@account, tab: "holdings")+ end++ test "an unlock changes the lot and restates under the account's row lock, taken first" do+ expect_locked_restate(:unlock_cost!)++ post unlock_holding_lot_path(@holding, @lot)++ assert_redirected_to account_path(@account, tab: "holdings")+ end++ # The new cost and the holdings restated from it are one change: a+ # restatement that fails leaves the lot as it was.+ test "an edit whose restatement fails leaves the lot's cost unchanged" do+ Balance::Materializer.any_instance.stubs(:materialize_balances).raises(RuntimeError, "restatement failed")++ assert_raises(RuntimeError) do+ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }+ end++ assert_nil @lot.reload.manual_total_cost+ end++ test "an unlock whose restatement fails leaves the lot's cost unchanged" do+ @lot.set_manual_total_cost!(600)+ Balance::Materializer.any_instance.stubs(:materialize_balances).raises(RuntimeError, "restatement failed")++ assert_raises(RuntimeError) do+ post unlock_holding_lot_path(@holding, @lot)+ end++ assert_equal 600, @lot.reload.manual_total_cost+ end++ # Restatement leaves a provider's rows alone, so a lot cost set under a+ # provider's figure would change nothing the position shows. A cost set+ # before the provider supplied one can still be cleared, since a fifo+ # account's disposals still read it.+ test "a lot cost cannot be set while the provider supplies the position's cost, only cleared" do+ @lot.set_manual_total_cost!(500)+ @holding.update_columns(cost_basis: 18, cost_basis_source: "provider")++ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }+ assert_redirected_to account_path(@account, tab: "holdings")+ assert_equal I18n.t("holding_lots.provider_cost"), flash[:alert]+ assert_equal 500, @lot.reload.manual_total_cost++ post unlock_holding_lot_path(@holding, @lot)+ assert_redirected_to account_path(@account, tab: "holdings")+ assert_equal I18n.t("holding_lots.unlock.success"), flash[:notice]+ assert_nil @lot.reload.manual_total_cost+ end++ # The position's latest row decides, whichever row the request names.+ test "an earlier row of a provider-cost position does not open the editor" do+ @holding.update_columns(cost_basis: 18, cost_basis_source: "provider")+ earlier = @account.holdings.find_by!(security: @security, date: 1.day.ago.to_date)++ patch holding_lot_path(earlier, @lot), params: { holding_lot: { total_cost_basis: "600" } }++ assert_equal I18n.t("holding_lots.provider_cost"), flash[:alert]+ assert_nil @lot.reload.manual_total_cost+ end++ test "the drawer offers the lot editor for a calculated cost, not a provider's" do+ get holding_path(@holding)+ assert_select "li[data-lot-id='#{@lot.id}'] details", 1+ assert_select "form[action='#{holding_lot_path(@holding, @lot)}']", 1+ assert_select "p", text: /#{Regexp.escape(I18n.t("holdings.lots.provider_cost_hint"))}/, count: 0++ @holding.update_columns(cost_basis: 18, cost_basis_source: "provider")+ get holding_path(@holding)+ assert_select "li[data-lot-id='#{@lot.id}']", 1+ assert_select "li[data-lot-id] details", 0+ assert_select "form[action='#{holding_lot_path(@holding, @lot)}']", 0+ assert_select "form[action='#{unlock_holding_lot_path(@holding, @lot)}']", 0, "no manual cost to clear"+ assert_select "p", text: /#{Regexp.escape(I18n.t("holdings.lots.provider_cost_hint"))}/, count: 1+ assert_select "p", text: /#{Regexp.escape(I18n.t("holdings.lots.provider_cost_clear_hint"))}/, count: 0+ end++ # Under a provider's cost, a lot's manual cost can only be cleared.+ test "the drawer offers only the clear control for a manual cost under a provider's" do+ @lot.set_manual_total_cost!(500)+ @holding.update_columns(cost_basis: 18, cost_basis_source: "provider")++ get holding_path(@holding)++ assert_select "form[action='#{holding_lot_path(@holding, @lot)}'][method='post'] input[name='holding_lot[total_cost_basis]']", 0+ assert_select "li[data-lot-id='#{@lot.id}'] form[action='#{unlock_holding_lot_path(@holding, @lot)}']", 1+ assert_select "p", text: /#{Regexp.escape(I18n.t("holdings.lots.provider_cost_clear_hint"))}/, count: 1+ end++ test "a read-only share is not offered the clear control under a provider's cost" do+ @lot.set_manual_total_cost!(500)+ @holding.update_columns(cost_basis: 18, cost_basis_source: "provider")+ Account.stubs(:writable_by).returns(Account.none)++ get holding_path(@holding)++ assert_select "form[action='#{unlock_holding_lot_path(@holding, @lot)}']", 0+ assert_select "p", text: /#{Regexp.escape(I18n.t("holdings.lots.provider_cost_clear_hint"))}/, count: 0+ end++ test "resubmitting the same lot id updates it in place and never duplicates" do+ id, created_at = @lot.id, @lot.created_at++ assert_no_difference "HoldingLot.count" do+ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "720" } }+ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }+ end++ lot = HoldingLot.find_by!(source_entry: @buy)+ assert_equal [ id, created_at, 600 ], [ lot.id, lot.created_at, lot.manual_total_cost ]+ end++ test "unlock returns the lot to its trade's cost" do+ @lot.set_manual_total_cost!(600)+ materialize++ post unlock_holding_lot_path(@holding, @lot)++ assert_redirected_to account_path(@account, tab: "holdings")+ assert_equal "Manual cost cleared.", flash[:notice], "a lot with no trade price returns to unknown, not a price"+ assert_nil @lot.reload.manual_total_cost+ assert_equal BigDecimal("15.2"), @holding.reload.cost_basis+ end++ test "another family's lot id is 404" do+ other = families(:empty).accounts.create!(name: "Other", balance: 0, currency: "USD", accountable: Investment.new)+ other_lot = HoldingLot.create!(account: other, security: @security, source_entry: create_trade(@security, account: other, qty: 1, price: 10, date: Date.current), qty: 1, currency: "USD")++ patch holding_lot_path(@holding, other_lot), params: { holding_lot: { total_cost_basis: "5" } }++ assert_response :not_found+ assert_nil other_lot.reload.manual_total_cost+ end++ test "an opening lot is not editable" do+ opening = HoldingLot.create!(account: @account, security: @security, origin_security: @security, qty: 0, currency: "USD")++ patch holding_lot_path(@holding, opening), params: { holding_lot: { total_cost_basis: "5" } }++ assert_response :not_found+ assert_nil opening.reload.manual_total_cost+ end++ test "a negative, blank, non-numeric, non-finite or oversized total is rejected and the lot is unchanged" do+ [ "-1", "", "abc", "12abc", "Infinity", "NaN", "10000000000000000" ].each do |total|+ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: total } }++ assert_redirected_to account_path(@account, tab: "holdings")+ assert_equal I18n.t("holding_lots.update.error"), flash[:alert]+ assert_nil @lot.reload.manual_total_cost, total.inspect+ end+ end++ # The cost per unit is stored with 15 digits before the point, as a+ # holding's cost basis is; on half a unit that bound comes before the+ # total's own.+ test "a total is accepted only while its cost per unit fits below 10^15" do+ entry = create_trade(@security, account: @account, qty: BigDecimal("0.5"), price: 1, date: Date.current)+ materialize+ half = HoldingLot.find_by!(source_entry: entry)++ patch holding_lot_path(@holding, half), params: { holding_lot: { total_cost_basis: "500000000000000" } }+ assert_equal I18n.t("holding_lots.update.error"), flash[:alert], "10^15 a unit"+ assert_nil half.reload.manual_total_cost++ patch holding_lot_path(@holding, half), params: { holding_lot: { total_cost_basis: "499999999999999.9999" } }+ assert_equal I18n.t("holding_lots.update.success"), flash[:notice]+ assert_equal BigDecimal("499999999999999.9999"), half.reload.manual_total_cost+ end++ test "a total is accepted only while it fits its column, however many units it spreads over" do+ entry = create_trade(@security, account: @account, qty: 2_000_000, price: 1, date: Date.current)+ materialize+ big = HoldingLot.find_by!(source_entry: entry)++ patch holding_lot_path(@holding, big), params: { holding_lot: { total_cost_basis: "1000000000000000" } }+ assert_equal I18n.t("holding_lots.update.error"), flash[:alert]+ assert_nil big.reload.manual_total_cost++ patch holding_lot_path(@holding, big), params: { holding_lot: { total_cost_basis: "999999999999999.9999" } }+ assert_equal I18n.t("holding_lots.update.success"), flash[:notice]+ assert_equal BigDecimal("999999999999999.9999"), big.reload.manual_total_cost+ end++ test "qty and acquired_on are not permitted on a derived lot" do+ before = [ @lot.qty, @lot.acquired_on ]++ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600", qty: "1", acquired_on: "2000-01-01" } }++ assert_equal before, [ @lot.reload.qty, @lot.acquired_on ]+ assert_equal 600, @lot.manual_total_cost+ end++ test "a read-only member cannot edit a lot" do+ @account.account_shares.create!(user: users(:family_member), permission: "read_only", include_in_finances: true)+ sign_in users(:family_member)++ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }++ assert_equal I18n.t("accounts.not_authorized"), flash[:alert]+ assert_nil @lot.reload.manual_total_cost+ end++ test "the drawer lists the position's lots, and only while they add up to it" do+ get holding_path(@holding)+ assert_select "form[action='#{holding_lot_path(@holding, @lot)}']", count: 1+ # The row shows a cost per unit while its editor takes the lot's total.+ assert_select "summary", text: /\$20\.00 per unit/++ @lot.update_columns(qty: @lot.qty - 1)+ get holding_path(@holding)+ assert_select "form[action='#{holding_lot_path(@holding, @lot)}']", count: 0+ end++ # The lots are today's: an earlier row of the same position, even one that+ # held the same quantity, does not offer them.+ test "an earlier holding of the position lists no lots" do+ earlier = @account.holdings.find_by!(security: @security, date: 1.day.ago.to_date)+ assert_equal @holding.qty, earlier.qty, "the quantity alone cannot tell them apart"++ get holding_path(earlier)+ assert_select "form[action^='#{holding_path(earlier)}/lots']", count: 0+ get holding_path(@holding)+ assert_select "form[action='#{holding_lot_path(@holding, @lot)}']", count: 1+ end++ # The editor shows a saved total to the places it was stored at, so saving+ # the form unchanged keeps it.+ test "the cost editor reopens a sub-cent total as it was saved" do+ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600.0001" } }+ get holding_path(@holding)+ assert_select "input[name='holding_lot[total_cost_basis]'][value='600.0001']", count: 1++ patch holding_lot_path(@holding, @lot), params: { holding_lot: { total_cost_basis: "600" } }+ get holding_path(@holding)+ assert_select "input[name='holding_lot[total_cost_basis]'][value='600.00']", count: 1+ end++ test "a lot row discloses a form only where it can be edited" do+ opening = HoldingLot.create!(account: @account, security: @security, origin_security: @security, qty: 5, currency: "USD")+ @holding.update_columns(qty: @holding.qty + 5)++ get holding_path(@holding)++ assert_select "li[data-lot-id='#{@lot.id}'] details", 1+ assert_select "li[data-lot-id='#{opening.id}'] details", 0+ assert_select "li[data-lot-id='#{opening.id}']", text: /#{I18n.t("holdings.lots.opening")}/+ end++ test "a read-only share shows every lot without a disclosure" do+ Account.stubs(:writable_by).returns(Account.none)++ get holding_path(@holding)++ assert_select "li[data-lot-id='#{@lot.id}']", 1+ assert_select "li[data-lot-id] details", 0+ end++ private+ # Mocha verifies these at teardown, so a request that skips the lock, the+ # change or the restatement fails.+ def expect_locked_restate(change)+ order = sequence("restate")+ Account.any_instance.expects(:lock!).at_least_once.in_sequence(order).returns(true)+ HoldingLot.any_instance.expects(change).in_sequence(order).returns(true)+ Holding::Materializer.any_instance.expects(:materialize_holdings).in_sequence(order).returns([])+ end++ def materialize+ Holding::Materializer.new(@account.reload, strategy: :forward, security_ids: [ @security.id ]).materialize_holdings+ end+enddiff --git a/test/controllers/holdings_controller_test.rb b/test/controllers/holdings_controller_test.rbindex 73def80b46..2d940407f1 100644--- a/test/controllers/holdings_controller_test.rb+++ b/test/controllers/holdings_controller_test.rb@@ -1,6 +1,8 @@require "test_helper"class HoldingsControllerTest < ActionDispatch::IntegrationTest+ include EntriesTestHelper+setup dosign_in users(:family_admin)@account = accounts(:investment)@@ -264,6 +266,78 @@ class HoldingsControllerTest < ActionDispatch::IntegrationTestassert_equal securities(:aapl), @holding.reload.securityend+ # A remap onto a position with its own opening lot merges the two. The+ # reset restates both securities, as a remap restates its target, so the+ # lots match the holdings straight away rather than at the next sync.+ test "reset_security restates both securities' lots" do+ account = users(:family_admin).family.accounts.create!(name: "Reset lots", balance: 1000, cash_balance: 1000, currency: "USD", accountable: Investment.new)+ item = users(:family_admin).family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")+ provider = AccountProvider.create!(account: account, provider: item.coinstats_accounts.create!(name: "Provider", currency: "USD"))+ original = Security.create!(ticker: "RSTA", name: "RSTA")+ replacement = Security.create!(ticker: "RSTB", name: "RSTB")+ [ original, replacement ].each do |security|+ Security::Price.insert_all((5.days.ago.to_date..Date.current).map { |date| { security_id: security.id, date: date, price: 30, currency: "USD" } })+ end+ create_trade(original, account: account, qty: 10, price: 40, date: 3.days.ago.to_date)+ provider_row = account.holdings.create!(security: original, date: Date.current, qty: 15, price: 30, amount: 450, currency: "USD", account_provider: provider)+ account.holdings.create!(security: replacement, date: Date.current, qty: 6, price: 30, amount: 180, currency: "USD", account_provider: provider)+ Holding::Materializer.new(account, strategy: :reverse).materialize_holdings+ assert_equal [ 5, 6 ], [ original, replacement ].map { |security| HoldingLot.opening.find_by!(security: security).qty }++ provider_row.remap_security!(replacement)+ Holding::Materializer.new(account.reload, strategy: :reverse).materialize_holdings+ merged = account.holdings.find_by!(security: replacement, date: Date.current)++ post reset_security_holding_path(merged)++ assert_redirected_to account_path(account, tab: "holdings")+ assert_not HoldingLot.exists?(security: replacement), "the replacement holds nothing once its row is reset"+ assert_equal [ [ account.id, original.id ] ].to_set, HoldingLot.in_partition([ account.id ], [ original.id ]),+ "the original's lots add up to its position again"+ end++ # The reset and its restatement are one change: a restatement that fails+ # leaves the holding, its trades and its lots where they were.+ test "a reset whose restatement fails is not applied" do+ @holding.account.update!(plaid_account: plaid_accounts(:one))+ @holding.update!(security: securities(:msft), provider_security: securities(:aapl), security_locked: true)+ Balance::Materializer.any_instance.stubs(:materialize_balances).raises(RuntimeError, "restatement failed")++ assert_raises(RuntimeError) { post reset_security_holding_path(@holding) }++ @holding.reload+ assert_equal [ securities(:msft), securities(:aapl) ], [ @holding.security, @holding.provider_security ]+ end++ test "a remap whose restatement fails is not applied" do+ original = @holding.security+ Balance::Materializer.any_instance.stubs(:materialize_balances).raises(RuntimeError, "restatement failed")++ assert_raises(RuntimeError) { patch remap_security_holding_path(@holding), params: { security_id: "MSFT|XNAS" } }++ assert_equal original, @holding.reload.security+ end++ # Both take the account row lock before any write, as a sync and a lot edit+ # do, so they serialise with them in one lock order.+ test "a reset locks the account before changing anything" do+ linked_remapped_holding+ expect_locked_change(:reset_security_to_provider!)++ post reset_security_holding_path(@holding)++ assert_redirected_to account_path(@holding.account, tab: "holdings")+ end++ test "a remap locks the account before changing anything" do+ linked_remapped_holding+ expect_locked_change(:remap_security!)++ patch remap_security_holding_path(@holding), params: { security_id: "NVDA|XNAS" }++ assert_redirected_to account_path(@holding.account, tab: "holdings")+ end+test "remap_security brings offline security back online" do# Given: the target security is marked offline (e.g. created by a failed QIF import)msft = securities(:msft)@@ -320,4 +394,19 @@ class HoldingsControllerTest < ActionDispatch::IntegrationTestassert_redirected_to account_path(@holding.account, tab: "holdings")assert_equal "Yahoo Finance rate limit exceeded", flash[:alert]end++ private+ def linked_remapped_holding+ @holding.account.update!(plaid_account: plaid_accounts(:one))+ @holding.update!(security: securities(:msft), provider_security: securities(:aapl), security_locked: true)+ end++ # Mocha verifies these at teardown, so a request that skips the lock, the+ # change or the restatement fails.+ def expect_locked_change(change)+ order = sequence(change.to_s)+ Account.any_instance.expects(:lock!).at_least_once.in_sequence(order).returns(true)+ Holding.any_instance.expects(change).in_sequence(order).returns(true)+ Balance::Materializer.any_instance.expects(:materialize_balances).in_sequence(order)+ endenddiff --git a/test/models/balance/chart_series_builder_test.rb b/test/models/balance/chart_series_builder_test.rbindex 41decb5575..29d2666781 100644--- a/test/models/balance/chart_series_builder_test.rb+++ b/test/models/balance/chart_series_builder_test.rb@@ -474,6 +474,25 @@ class Balance::ChartSeriesBuilderTest < ActiveSupport::TestCaseassert_equal [ 1000 ], builder.gains_series.map { |v| v.value.amount }end+ # A zero the trades worked out (a lot the user says cost nothing) is a cost,+ # unlike a provider's zero, which stands for unknown.+ test "gains series counts a calculated zero cost basis" do+ account = accounts(:investment)+ account.holdings.destroy_all++ create_holding(account: account, security: securities(:aapl), date: Date.current, qty: 10, price: 100, cost_basis: 0)+ account.holdings.update_all(cost_basis_source: "calculated")++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: Date.current, end_date: Date.current),+ interval: "1 day"+ )++ assert_equal [ 1000 ], builder.gains_series.map { |v| v.value.amount }+ end+test "gains series converts holding gains to target currency with locf rates" dofamily = families(:dylan_family)account = family.accounts.create!(@@ -532,6 +551,61 @@ class Balance::ChartSeriesBuilderTest < ActiveSupport::TestCaseassert_equal expected, builder.gains_series.map { |v| v.value.amount }end+ # A later row the materializer cleared as unknown (a transfer in: no cost,+ # no source, not a provider's row) stops a calculated zero carrying, so the+ # position's value is not all counted as gain.+ test "gains series does not carry a calculated zero basis onto a later unknown one" do+ account = accounts(:investment)+ account.holdings.destroy_all+ security = securities(:aapl)++ create_holding(account: account, security: security, date: 2.days.ago.to_date, qty: 10, price: 100, cost_basis: 0)+ .update_columns(cost_basis_source: "calculated")+ create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 15, price: 100, cost_basis: nil)+ create_holding(account: account, security: security, date: Date.current, qty: 15, price: 110, cost_basis: nil)++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),+ interval: "1 day"+ )++ expected = [+ 1000, # 1000 - 0: a free acquisition's whole value is gain+ 0, # unknown basis, counted as no gain rather than 1500+ 0 # unknown basis, not 1650+ ]++ assert_equal expected, builder.gains_series.map { |v| v.value.amount }+ end++ # The materializer leaves a provider's row alone, so a provider row with no+ # cost after a free acquisition is not an unknown basis: the zero carries.+ test "gains series carries a calculated zero basis onto a provider row without a cost" do+ account = accounts(:investment)+ account.holdings.destroy_all+ security = securities(:aapl)+ item = account.family.coinstats_items.create!(name: "CoinStats", api_key: "test-key")+ provider = AccountProvider.create!(account: account, provider: item.coinstats_accounts.create!(name: "Provider", currency: "USD"))++ create_holding(account: account, security: security, date: 2.days.ago.to_date, qty: 10, price: 100, cost_basis: 0)+ .update_columns(cost_basis_source: "calculated")+ create_holding(account: account, security: security, date: 1.day.ago.to_date, qty: 10, price: 100, cost_basis: 0)+ .update_columns(cost_basis_source: "calculated")+ create_holding(account: account, security: security, date: Date.current, qty: 10, price: 110, cost_basis: nil)+ .update_columns(account_provider_id: provider.id)++ builder = Balance::ChartSeriesBuilder.new(+ account_ids: [ account.id ],+ currency: "USD",+ period: Period.custom(start_date: 2.days.ago.to_date, end_date: Date.current),+ interval: "1 day"+ )++ assert_equal [ 1000, 1000, 1100 ], builder.gains_series.map { |v| v.value.amount }+ end+test "gains series values carry trend vs previous point" doaccount = accounts(:investment)account.holdings.destroy_alldiff --git a/test/models/balance/materializer_test.rb b/test/models/balance/materializer_test.rbindex 72ba99d545..a4ba9bc275 100644--- a/test/models/balance/materializer_test.rb+++ b/test/models/balance/materializer_test.rb@@ -14,6 +14,16 @@ class Balance::MaterializerTest < ActiveSupport::TestCase)end+ # A sync and a lot edit's restatement both take the account row lock before+ # writing holdings, so they cannot deadlock on each other's rows.+ test "materializing takes the account row lock before writing holdings" do+ order = sequence("materialize")+ Account.any_instance.expects(:lock!).in_sequence(order).returns(true)+ Holding::Materializer.any_instance.expects(:materialize_holdings).in_sequence(order).returns([])++ Balance::Materializer.new(@account, strategy: :forward).materialize_balances+ end+test "syncs balances" doHolding::Materializer.any_instance.expects(:materialize_holdings).returns([]).oncediff --git a/test/models/holding/lot_book_test.rb b/test/models/holding/lot_book_test.rbindex 3a992f7ab9..eea4a4f279 100644--- a/test/models/holding/lot_book_test.rb+++ b/test/models/holding/lot_book_test.rb@@ -69,6 +69,10 @@ class Holding::LotBookTest < ActiveSupport::TestCasedef add_unknown(*, **); enddef settle_opening(*, **); end++ def unpriced?+ @unknown+ endendTHIRD = BigDecimal("10") / 3diff --git a/test/models/holding_lot_test.rb b/test/models/holding_lot_test.rbindex d35b1a17a1..4fa8ba5f9d 100644--- a/test/models/holding_lot_test.rb+++ b/test/models/holding_lot_test.rb@@ -592,7 +592,7 @@ class HoldingLotTest < ActiveSupport::TestCaseendend- test "remap onto a position with its own opening lot leaves one opening lot there" do+ test "remap onto a position with its own opening lot merges the two" dosetup_accountold_security = priced_security("LOTQ", 30)new_security = priced_security("LOTW", 30)@@ -602,8 +602,269 @@ class HoldingLotTest < ActiveSupport::TestCaseholding.remap_security!(new_security)- assert_equal [ kept.id ], HoldingLot.opening.where(security: new_security).pluck(:id)- assert_not HoldingLot.exists?(moved.id), "restated into the target's opening lot by the next materialization"+ assert_equal [ kept.id ], HoldingLot.opening.where(security: new_security).pluck(:id), "the target keeps its row"+ assert_equal 10, kept.reload.qty, "4 moved onto the target's 6"+ assert_not HoldingLot.exists?(moved.id)+ end++ test "merged opening lot keeps its cost only when both sides agree" do+ [ [ 25, 25, 25 ], [ 25, 30, nil ], [ nil, 30, nil ], [ 25, nil, nil ] ].each do |moved_cost, kept_cost, merged_cost|+ setup_account+ old_security = priced_security("LOTM#{moved_cost}#{kept_cost}", 30)+ new_security = priced_security("LOTK#{moved_cost}#{kept_cost}", 30)+ holding = @account.holdings.create!(security: old_security, date: d(10), qty: 4, price: 30, amount: 120, currency: "USD")+ opening_lot(old_security, 4).update!(unit_cost: moved_cost)+ kept = opening_lot(new_security, 6)+ kept.update!(unit_cost: kept_cost)++ holding.remap_security!(new_security)++ message = "moved #{moved_cost.inspect} onto #{kept_cost.inspect}"+ if merged_cost.nil?+ assert_nil kept.reload.unit_cost, message+ else+ assert_equal merged_cost, kept.reload.unit_cost, message+ end+ end+ end++ test "merged opening lot drops its cost when the two costs are in different currencies" do+ setup_account+ old_security = priced_security("LOTMC", 30)+ new_security = priced_security("LOTKC", 30)+ holding = @account.holdings.create!(security: old_security, date: d(10), qty: 4, price: 30, amount: 120, currency: "USD")+ opening_lot(old_security, 4).update!(unit_cost: 25, currency: "EUR")+ kept = opening_lot(new_security, 6)+ kept.update!(unit_cost: 25)++ holding.remap_security!(new_security)++ assert_equal 10, kept.reload.qty+ assert_nil kept.unit_cost, "25 EUR and 25 USD are not one cost"+ end++ # A lot with no units has no cost to disagree with, and a clamp row is+ # exactly that.+ test "merging an opening lot with no units leaves the target's cost" do+ setup_account+ old_security = priced_security("LOTZ", 30)+ new_security = priced_security("LOTY", 30)+ holding = @account.holdings.create!(security: old_security, date: d(10), qty: 0, price: 30, amount: 0, currency: "USD")+ empty = opening_lot(old_security, 0)+ empty.update!(clamped: true)+ kept = opening_lot(new_security, 5)+ kept.update!(unit_cost: 50)++ holding.remap_security!(new_security)++ assert_equal [ 5, 50 ], [ kept.reload.qty, kept.unit_cost ]+ assert_not HoldingLot.exists?(empty.id)+ end++ # A clamp row holds no units, so the units moved onto it keep their cost,+ # and the merged lot is no longer a clamp.+ test "merging an opening lot onto a clamp row keeps the moved lot's cost" do+ setup_account+ old_security = priced_security("LOTZ", 30)+ new_security = priced_security("LOTY", 30)+ holding = @account.holdings.create!(security: old_security, date: d(10), qty: 10, price: 30, amount: 300, currency: "USD")+ opening_lot(old_security, 10).update!(unit_cost: 5)+ clamp = opening_lot(new_security, 0)+ clamp.update!(clamped: true)++ holding.remap_security!(new_security)++ assert_equal [ 10, 5, false ], [ clamp.reload.qty, clamp.unit_cost, clamp.clamped ]+ end++ # With nothing to merge into, the clamp row moves as any opening lot does.+ # Dropping it would lose the flag that keeps the position's basis unknown.+ test "an opening lot with no units and no target moves with its clamp" do+ setup_account+ old_security = priced_security("LOTZ", 30)+ new_security = priced_security("LOTY", 30)+ holding = @account.holdings.create!(security: old_security, date: d(10), qty: 0, price: 30, amount: 0, currency: "USD")+ empty = opening_lot(old_security, 0)+ empty.update!(clamped: true)++ holding.remap_security!(new_security)++ assert_equal [ new_security.id, true ], [ empty.reload.security_id, empty.clamped ]+ end++ # The drop is keyed on the units, not the clamp: an unclamped lot with no+ # units is dropped as well.+ test "an unclamped opening lot with no units is dropped, not merged" do+ setup_account+ old_security = priced_security("LOTZ", 30)+ new_security = priced_security("LOTY", 30)+ holding = @account.holdings.create!(security: old_security, date: d(10), qty: 0, price: 30, amount: 0, currency: "USD")+ empty = opening_lot(old_security, 0)+ kept = opening_lot(new_security, 5)+ kept.update!(unit_cost: 50)++ holding.remap_security!(new_security)++ assert_equal [ 5, 50 ], [ kept.reload.qty, kept.unit_cost ]+ assert_not HoldingLot.exists?(empty.id)+ end++ # --- User-set lot cost --------------------------------------------------------++ test "a user-set cost on a transfer-in lot resolves the position, forward" do+ travel_to TODAY do+ setup_account+ security = priced_security("LOTU", 30)+ transfer = trade(security, 60, 30, 2, label: Trade::TRANSFER_LABEL)+ trade(security, 40, 20, 3)+ materialize(:forward)+ assert_nil @account.holdings.find_by!(security: security, date: d(10)).cost_basis, "unknown before"++ HoldingLot.find_by!(source_entry: transfer).set_manual_total_cost!(720)+ materialize(:forward)++ assert_equal BigDecimal("15.2"), @account.holdings.find_by!(security: security, date: d(10)).cost_basis+ assert_equal 12, HoldingLot.find_by!(source_entry: transfer).unit_cost+ end+ end++ test "a user-set cost on a transfer-in lot resolves the position, reverse" do+ travel_to TODAY do+ setup_account+ link_account+ security = priced_security("LOTV", 30)+ transfer = trade(security, 60, 30, 2, label: Trade::TRANSFER_LABEL)+ trade(security, 40, 20, 3)+ provider_holding(security, 100, nil)+ materialize(:reverse)+ # d(10) is the provider's own row, which the materializer leaves alone.+ assert_nil @account.holdings.find_by!(security: security, date: d(9)).cost_basis, "unknown before"++ HoldingLot.find_by!(source_entry: transfer).set_manual_total_cost!(720)+ materialize(:reverse)++ assert_equal BigDecimal("15.2"), @account.holdings.find_by!(security: security, date: d(9)).cost_basis+ end+ end++ test "a user-set cost replaces a buy's price, and unlocking returns it to the trade" do+ travel_to TODAY do+ setup_account+ security = priced_security("LOTP", 30)+ trade(security, 60, 12, 2)+ buy = trade(security, 40, 20, 3)+ materialize(:forward)+ assert_equal BigDecimal("15.2"), @account.holdings.find_by!(security: security, date: d(10)).cost_basis++ lot = HoldingLot.find_by!(source_entry: buy)+ lot.set_manual_total_cost!(600)+ materialize(:forward)+ assert_equal BigDecimal("13.2"), @account.holdings.find_by!(security: security, date: d(10)).cost_basis, "(720 + 600) / 100"++ lot.reload.unlock_cost!+ materialize(:forward)+ assert_equal BigDecimal("15.2"), @account.holdings.find_by!(security: security, date: d(10)).cost_basis+ assert_nil lot.reload.manual_total_cost+ end+ end++ test "a user-set lot cost survives a split and a partial sale" do+ travel_to TODAY do+ setup_account+ security = priced_security("LOTS", 30)+ buy = trade(security, 10, 100, 2)+ Security::Split.create!(security: security, ex_date: d(4), numerator: 2, denominator: 1, source: "manual")+ trade(security, -5, 90, 6)+ materialize(:forward)+ lot = HoldingLot.find_by!(source_entry: buy)+ assert_equal [ 15, 50 ], [ lot.qty, lot.unit_cost ], "20 after the split, 5 sold"++ lot.set_manual_total_cost!(1500)+ materialize(:forward)++ assert_equal 75, lot.reload.unit_cost, "1500 over the 10 bought, halved by the split"+ assert_equal 75, @account.holdings.find_by!(security: security, date: d(10)).cost_basis+ end+ end++ test "a whole-position lock outranks a user-set lot cost" do+ travel_to TODAY do+ setup_account+ security = priced_security("LOTL", 30)+ buy = trade(security, 10, 20, 2)+ materialize(:forward)+ @account.holdings.find_by!(security: security, date: d(10)).set_manual_cost_basis!(99)++ HoldingLot.find_by!(source_entry: buy).set_manual_total_cost!(150)+ materialize(:forward)++ assert_equal 99, @account.holdings.find_by!(security: security, date: d(10)).cost_basis+ end+ end++ test "a user-set lot cost of zero is the holding's cost, alone and in a batch" do+ travel_to TODAY do+ setup_account+ security = priced_security("LOTN", 60)+ buy = trade(security, 10, 50, 2)+ materialize(:forward)++ HoldingLot.find_by!(source_entry: buy).set_manual_total_cost!(0)+ materialize(:forward)++ holding = @account.holdings.find_by!(security: security, date: d(10))+ assert_equal [ 0, "calculated", false ], [ holding.cost_basis, holding.cost_basis_source, holding.cost_basis_locked ]+ assert_equal Money.new(0, "USD"), holding.avg_cost++ batched = Holding.find(holding.id)+ Holding.preload_avg_costs([ batched ])+ assert_equal Money.new(0, "USD"), batched.avg_cost+ end+ end++ # With no rate for the buy's currency, the trade's own price converts to+ # nothing, so clearing the user's figure leaves the cost unknown.+ test "clearing a lot cost whose buy has no rate leaves the basis unknown, forward" do+ travel_to TODAY do+ setup_account+ security = priced_security("LOTX", 60)+ buy = create_trade(security, account: @account, qty: 10, price: 45, currency: "EUR", date: d(2))+ lot_cost_set_then_cleared(security, buy, date: d(10)) { materialize(:forward) }+ end+ end++ test "clearing a lot cost whose buy has no rate leaves the basis unknown, reverse" do+ travel_to TODAY do+ setup_account+ link_account+ security = priced_security("LOTW", 60)+ buy = create_trade(security, account: @account, qty: 10, price: 45, currency: "EUR", date: d(2))+ provider_holding(security, 10, nil)+ # d(10) is the provider's own row, which the materializer leaves alone.+ lot_cost_set_then_cleared(security, buy, date: d(9)) { materialize(:reverse) }+ end+ end++ # A trade can move to another security before its lot does, and a run+ # scoped to the new security still reads the user's figure for it.+ test "a user-set lot cost holds for a trade moved ahead of its lot" do+ travel_to TODAY do+ setup_account+ link_account+ old_security = priced_security("LOTA", 60)+ new_security = priced_security("LOTB", 60)+ buy = trade(old_security, 10, 80, 2)+ provider_holding(old_security, 10, nil)+ materialize(:reverse)+ HoldingLot.find_by!(source_entry: buy).set_manual_total_cost!(500)++ Trade.where(id: buy.entryable_id).update_all(security_id: new_security.id)+ @account.holdings.where(security: old_security).update_all(security_id: new_security.id)+ assert_equal old_security.id, HoldingLot.find_by!(source_entry: buy).security_id, "the lot has not moved"+ materialize(:reverse, security_ids: [ new_security.id ])++ assert_equal 50, @account.holdings.find_by!(security: new_security, date: d(9)).cost_basis+ endend# A run scoped to one security (a remap, a price sync) books lots for that@@ -694,6 +955,21 @@ class HoldingLotTest < ActiveSupport::TestCaseprovider_holding(@gapped, 3, nil)end+ def lot_cost_set_then_cleared(security, buy, date:)+ yield+ lot = HoldingLot.find_by!(source_entry: buy)+ lot.set_manual_total_cost!(500)+ yield+ assert_equal 50, @account.holdings.find_by!(security: security, date: date).cost_basis++ lot.reload.unlock_cost!+ yield++ holding = @account.holdings.find_by!(security: security, date: date)+ assert_nil holding.cost_basis+ assert_nil holding.avg_cost+ end+def materialize(strategy, security_ids: nil)Holding::Materializer.new(@account.reload, strategy: strategy, security_ids: security_ids).materialize_holdingsend