The personal finance app for everyone (by everyone)
Ruby
Make the cost basis editor read "per share × quantity = total" (#4184)
GFRae04c597e448
diff --git a/app/components/DS/popover_controller.js b/app/components/DS/popover_controller.jsindex 18a96c03ed..d020b65c46 100644--- a/app/components/DS/popover_controller.js+++ b/app/components/DS/popover_controller.js@@ -64,7 +64,12 @@ export default class extends Controller {if (!this.show) this.close();};+ // A click in a modal dialog opened on top of the panel (e.g. the+ // data-turbo-confirm dialog of a form inside it) is not outside the panel.handleOutsideClick = (event) => {+ const dialog = event.target.closest?.("dialog[open]");+ if (dialog && !dialog.contains(this.element)) return;+if (this.show && !this.element.contains(event.target)) this.close();};@@ -85,14 +90,17 @@ export default class extends Controller {}};- close() {+ // Used as an action (a Cancel button in the panel), close() returns focus+ // to the trigger like Escape does, instead of dropping it to <body>.+ close(event) {this.contentTarget.classList.add("hidden");this.buttonTarget.setAttribute("aria-expanded", "false");+ if (event) this.buttonTarget.focus();}focusFirstElement() {const focusableElements =- 'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])';+ 'button, [href], input:not([type="hidden"]), select, textarea, [tabindex]:not([tabindex="-1"])';const firstFocusableElement =this.contentTarget.querySelectorAll(focusableElements)[0];if (firstFocusableElement) {diff --git a/app/controllers/holdings_controller.rb b/app/controllers/holdings_controller.rbindex 250cb72540..c3e0ba6008 100644--- a/app/controllers/holdings_controller.rb+++ b/app/controllers/holdings_controller.rb@@ -15,12 +15,17 @@ class HoldingsController < ApplicationControllerenddef update- total_cost_basis = holding_params[:cost_basis].to_d+ # The editor sends the per-share cost, which is what cost_basis stores, so a+ # price below a cent is not lost to a total rounded to cents. A total is still+ # accepted and divided by the quantity. Zero is valid for gifted/inherited shares,+ # an empty field is not: it would lock an unknown basis as 0.+ per_share_cost = if holding_params.key?(:per_share_cost_basis)+ holding_params[:per_share_cost_basis].presence&.to_d+ elsif @holding.qty.positive? && (total_cost_basis = holding_params[:cost_basis].presence)+ total_cost_basis.to_d / @holding.qty+ end- if total_cost_basis >= 0 && @holding.qty.positive?- # Convert total cost basis to per-share cost (the cost_basis field stores per-share)- # Zero is valid for gifted/inherited shares- per_share_cost = total_cost_basis / @holding.qty+ if per_share_cost && per_share_cost >= 0 && @holding.qty.positive?@holding.set_manual_cost_basis!(per_share_cost)flash[:notice] = t(".success")else@@ -181,6 +186,6 @@ class HoldingsController < ApplicationControllerenddef holding_params- params.require(:holding).permit(:cost_basis)+ params.require(:holding).permit(:cost_basis, :per_share_cost_basis)endenddiff --git a/app/javascript/controllers/cost_basis_form_controller.js b/app/javascript/controllers/cost_basis_form_controller.jsindex 4f91f4fe0b..b32652a73b 100644--- a/app/javascript/controllers/cost_basis_form_controller.js+++ b/app/javascript/controllers/cost_basis_form_controller.js@@ -1,31 +1,45 @@import { Controller } from "@hotwired/stimulus"import parseLocaleFloat from "utils/parse_locale_float"+// cost_basis stores the per-share cost with four decimals.+const PER_SHARE_DECIMALS = 4+// Handles bidirectional conversion between total cost basis and per-share cost-// in the manual cost basis entry form.+// in the manual cost basis entry form. Only the per-share field is submitted.export default class extends Controller {- static targets = ["total", "perShare", "perShareValue"]+ static targets = ["total", "perShare"]static values = { qty: Number }// Called when user types in the total cost basis field- // Updates the per-share display and input to show the calculated value+ // Updates the per-share field with the calculated value, keeping up to four+ // decimals so a price below a cent is not saved as 0.00updatePerShare() {+ // An empty total empties the submitted per-share field instead of saving 0+ if (this.totalTarget.value.trim() === "") {+ this.perShareTarget.value = ""+ return+ }+const total = parseLocaleFloat(this.totalTarget.value)const qty = this.qtyValue || 1- const perShare = qty > 0 ? (total / qty).toFixed(2) : "0.00"- this.perShareValueTarget.textContent = perShare- if (this.hasPerShareTarget) {- this.perShareTarget.value = perShare- }+ this.perShareTarget.value = qty > 0 ? this.#formatPerShare(total / qty) : "0.00"}// Called when user types in the per-share field// Updates the total cost basis field with the calculated valueupdateTotal() {+ if (this.perShareTarget.value.trim() === "") {+ this.totalTarget.value = ""+ return+ }+const perShare = parseLocaleFloat(this.perShareTarget.value)const qty = this.qtyValue || 1- const total = (perShare * qty).toFixed(2)- this.totalTarget.value = total- this.perShareValueTarget.textContent = perShare.toFixed(2)+ this.totalTarget.value = (perShare * qty).toFixed(2)+ }++ // At least two decimals, more only when the value needs them.+ #formatPerShare(value) {+ return value.toFixed(PER_SHARE_DECIMALS).replace(/0{1,2}$/, "")}}diff --git a/app/javascript/controllers/drawer_cost_basis_controller.js b/app/javascript/controllers/drawer_cost_basis_controller.jsindex 972db5940e..30dc0cb615 100644--- a/app/javascript/controllers/drawer_cost_basis_controller.js+++ b/app/javascript/controllers/drawer_cost_basis_controller.js@@ -1,34 +1,20 @@import { Controller } from "@hotwired/stimulus"-import parseLocaleFloat from "utils/parse_locale_float"-// Handles the inline cost basis editor in the holding drawer.-// Shows/hides the form and handles bidirectional total <-> per-share conversion.+// Shows/hides the inline cost basis editor in the holding drawer.+// The total <-> per-share conversion lives in cost_basis_form_controller.export default class extends Controller {- static targets = ["form", "total", "perShare", "perShareValue"]- static values = { qty: Number }+ static targets = ["form", "opener"]+ // Opening moves focus into the editor, closing (pencil or Cancel) returns it+ // to the pencil, so focus never drops to <body> with the hidden form.toggle(event) {event.preventDefault()- this.formTarget.classList.toggle("hidden")- }+ const hidden = this.formTarget.classList.toggle("hidden")- // Called when user types in total cost basis field- updatePerShare() {- const total = parseLocaleFloat(this.totalTarget.value)- const qty = this.qtyValue || 1- const perShare = qty > 0 ? (total / qty).toFixed(2) : "0.00"- this.perShareValueTarget.textContent = perShare- if (this.hasPerShareTarget) {- this.perShareTarget.value = perShare+ if (hidden) {+ this.openerTarget.focus()+ } else {+ this.formTarget.querySelector("input:not([type='hidden'])")?.focus()}}-- // Called when user types in per-share field- updateTotal() {- const perShare = parseLocaleFloat(this.perShareTarget.value)- const qty = this.qtyValue || 1- const total = (perShare * qty).toFixed(2)- this.totalTarget.value = total- this.perShareValueTarget.textContent = perShare.toFixed(2)- }}diff --git a/app/javascript/controllers/money_field_controller.js b/app/javascript/controllers/money_field_controller.jsindex cc44979704..ce4d45afc0 100644--- a/app/javascript/controllers/money_field_controller.js+++ b/app/javascript/controllers/money_field_controller.js@@ -67,8 +67,11 @@ export default class extends Controller {event.preventDefault();const precision = this.#pastePrecision();+ // Unrounded, but never in exponent notation (0.000000123, not 1.23e-7).this.amountTarget.value =- precision === null ? String(parsed) : parsed.toFixed(precision);+ precision === null+ ? parsed.toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 20 })+ : parsed.toFixed(precision);// auto_submit_form listens for "change" on number inputs while validation// and the goal form's suggestion listen for "input", and assigning .value@@ -94,10 +97,13 @@ export default class extends Controller {// currency selection without a second lookup. BTC's step arrives as// "1.0e-08", so the decimal count is derived numerically rather than by// counting characters. Returns null when the step declares no precision —- // step="any", which the trade amount, price and fee fields use — so the- // pasted value is written unrounded instead of being truncated to a default- // that would drop a sub-cent crypto price to "0.00".+ // step="any", which the trade amount, price and fee fields and the cost basis+ // editor use — so the pasted value is written unrounded instead of being+ // truncated to a default or display precision that would drop a sub-cent+ // price to "0.00". step="any" wins over the precision value for that reason.#pastePrecision() {+ if (this.amountTarget.step === "any") return null;+if (this.hasPrecisionValue && Number.isInteger(this.precisionValue)) {return this.precisionValue;}diff --git a/app/models/holding.rb b/app/models/holding.rbindex cf81d61a34..ad9620e8e2 100644--- a/app/models/holding.rb+++ b/app/models/holding.rb@@ -41,6 +41,13 @@ class Holding < ApplicationRecordaccount.balance.zero? ? 1 : amount_in_account_currency / account.balance * 100end+ # The stored per-share cost when it is a real value:+ # - If locked (user-set), trust the value even if 0 (valid for airdrops)+ # - Otherwise require positive since providers sometimes return 0 when unknown+ def known_cost_basis+ cost_basis if cost_basis.present? && (cost_basis_locked? || cost_basis.positive?)+ end+# Returns average cost per share, or nil if unknown.## Uses pre-computed cost_basis if available (set during materialization),@@ -48,13 +55,7 @@ class Holding < ApplicationRecord# basis cannot be determined (no trades and no provider cost_basis).def avg_cost# Use stored cost_basis if available (eliminates N+1 queries)- # - If locked (user-set), trust the value even if 0 (valid for airdrops)- # - Otherwise require positive since providers sometimes return 0 when unknown- if cost_basis.present?- if cost_basis_locked? || cost_basis.positive?- return Money.new(cost_basis, currency)- end- end+ return Money.new(known_cost_basis, currency) if known_cost_basis# Fallback to calculation for holdings without pre-computed cost_basiscalculate_avg_costdiff --git a/app/views/holdings/_cost_basis_cell.html.erb b/app/views/holdings/_cost_basis_cell.html.erbindex 4ae265df4d..559a938442 100644--- a/app/views/holdings/_cost_basis_cell.html.erb+++ b/app/views/holdings/_cost_basis_cell.html.erb@@ -1,13 +1,5 @@<%# locals: (holding:, editable: true) %>-<%- # Pre-calculate values for the form- # Note: cost_basis field stores per-share cost, so calculate total for display- current_per_share = holding.cost_basis.present? && holding.cost_basis.positive? ? holding.cost_basis : nil- current_total = current_per_share && holding.qty.positive? ? (current_per_share * holding.qty).round(2) : nil- currency = Money::Currency.new(holding.currency)-%>-<%= turbo_frame_tag dom_id(holding, :cost_basis) do %><% if holding.cost_basis_locked? && !editable %><%# Locked and not editable (from holdings list) - just show value, right-aligned %>@@ -35,73 +27,11 @@<% end %><% end %><% popover.with_custom_content do %>- <div class="p-4 min-w-[280px]"- data-controller="cost-basis-form"- data-cost-basis-form-qty-value="<%= holding.qty %>">+ <div class="p-4 min-w-70 text-left"><h4 class="font-medium text-sm mb-3">- <%= t(".set_cost_basis_header", ticker: holding.ticker, qty: format_quantity(holding.qty)) %>+ <%= t(".set_cost_basis_header", ticker: holding.ticker) %></h4>- <%- form_data = { turbo: false }- if holding.avg_cost- form_data[:turbo_confirm] = {- title: t(".overwrite_confirm_title"),- body: t(".overwrite_confirm_body", current: format_money(holding.avg_cost))- }- end- %>- <%= styled_form_with model: holding,- url: holding_path(holding),- method: :patch,- class: "space-y-3",- data: form_data do |f| %>- <!-- Primary: Total cost basis (custom input, no spinners) -->- <div class="form-field">- <div class="form-field__body">- <label class="form-field__label"><%= t(".total_cost_basis_label") %></label>- <div class="flex items-center gap-1">- <span class="text-secondary text-sm font-medium"><%= currency.symbol %></span>- <input type="number" step="any"- name="holding[cost_basis]"- class="form-field__input grow"- placeholder="0.00"- autocomplete="off"- value="<%= sprintf("%.2f", current_total) if current_total %>"- data-action="input->cost-basis-form#updatePerShare"- data-cost-basis-form-target="total">- <span class="text-secondary text-sm"><%= currency.iso_code %></span>- </div>- </div>- </div>- <p class="text-xs text-secondary -mt-2" data-cost-basis-form-target="perShareDisplay">- = <%= currency.symbol %><span data-cost-basis-form-target="perShareValue"><%= number_with_precision(current_per_share, precision: 2) || "0.00" %></span> <%= t(".per_share") %>- </p>-- <!-- Alternative: Per-share input -->- <div class="pt-2 border-t border-tertiary">- <label class="text-xs text-secondary block mb-1"><%= t(".or_per_share_label") %></label>- <div class="flex items-center gap-1">- <span class="text-secondary text-sm font-medium"><%= currency.symbol %></span>- <input type="number" step="any"- class="form-field__input grow"- placeholder="0.00"- autocomplete="off"- value="<%= sprintf("%.2f", current_per_share) if current_per_share %>"- data-action="input->cost-basis-form#updateTotal"- data-cost-basis-form-target="perShare">- <span class="text-secondary text-sm"><%= currency.iso_code %></span>- </div>- </div>-- <div class="flex justify-end gap-2 pt-2">- <button type="button"- class="inline-flex items-center gap-1 px-2 py-1 rounded-md text-sm font-medium text-primary button-bg-secondary-strong hover:button-bg-secondary-strong-hover"- data-action="click->DS--popover#close">- <%= t(".cancel") %>- </button>- <%= f.submit t(".save"), class: "inline-flex items-center gap-1 px-2 py-1 rounded-md text-sm font-medium text-inverse bg-inverse hover:bg-inverse-hover" %>- </div>- <% end %>+ <%= render "holdings/cost_basis_form", holding: holding, context: :popover, cancel_action: "DS--popover#close" %></div><% end %><% end %>diff --git a/app/views/holdings/_cost_basis_form.html.erb b/app/views/holdings/_cost_basis_form.html.erbnew file mode 100644index 0000000000..f6e646fab0--- /dev/null+++ b/app/views/holdings/_cost_basis_form.html.erb@@ -0,0 +1,74 @@+<%# locals: (holding:, context:, cancel_action:) %>++<%+ # cost_basis stores the per-share cost with four decimals, so the form submits+ # the per-share field; the total only helps to fill it in. The per-share field+ # shows as many of those decimals as the stored value uses, at least two (also+ # for zero-decimal currencies such as JPY), so saving unchanged keeps the basis.+ # A user-set basis of 0 (e.g. shares received for free) is a real value and is+ # shown as 0.00; an unknown basis leaves the fields empty (Holding#known_cost_basis).+ # Both fields use step="any", so money_field leaves pastes unrounded: a+ # per-share price below a cent (10 x 0.0049) gives the same basis as typing it.+ # The per-share field is required, so an emptied editor is not submitted (and+ # does not ask to overwrite the basis only to be rejected).+ current_per_share = holding.known_cost_basis+ per_share_precision = current_per_share ? current_per_share.round(4).to_s("F").split(".").last.sub(/0+\z/, "").length.clamp(2, 4) : 2+ current_total = current_per_share && holding.qty.positive? ? (current_per_share * holding.qty).round(2) : nil++ # Turbo submits the form, so the overwrite confirmation shows; "_top" leaves+ # the holdings-list frame and the drawer for the redirect to the account.+ form_data = { turbo_frame: "_top" }+ if holding.avg_cost+ form_data[:turbo_confirm] = {+ title: t("holdings.cost_basis_cell.overwrite_confirm_title"),+ body: t("holdings.cost_basis_cell.overwrite_confirm_body", current: format_money(holding.avg_cost))+ }+ end+%>++<%= styled_form_with model: holding,+ url: holding_path(holding),+ method: :patch,+ namespace: dom_id(holding, "#{context}_cost_basis"),+ class: "space-y-3",+ data: form_data.merge(controller: "cost-basis-form", cost_basis_form_qty_value: holding.qty) do |f| %>+ <%# Laid out like an invoice line: per share x quantity = total. Only the+ per-share cost is submitted; the total field just helps to fill it in. %>+ <%= f.money_field :per_share_cost_basis,+ label: t("holdings.cost_basis_cell.per_share_label"),+ name: f.field_name(:per_share_cost_basis),+ hide_currency: true,+ currency_value_override: holding.currency,+ value: current_per_share,+ precision: per_share_precision,+ required: true,+ placeholder: "0.00",+ input_class: "privacy-sensitive privacy-sensitive-interactive",+ step: "any",+ min: 0,+ amount_data: { action: "input->cost-basis-form#updateTotal", cost_basis_form_target: "perShare" } %>++ <p class="flex items-center gap-2 px-3 text-sm">+ <span class="text-secondary">×</span>+ <span class="text-primary privacy-sensitive"><%= t("holdings.holding.shares", qty: format_quantity(holding.qty, exact: true)) %></span>+ </p>++ <%# The holding stores the per-share cost, so neither field is bound to it. %>+ <%= f.money_field :total_cost_basis,+ label: safe_join([ tag.span("=", class: "text-secondary"), t("holdings.cost_basis_cell.total_cost_basis_label") ], " "),+ name: nil,+ hide_currency: true,+ currency_value_override: holding.currency,+ value: current_total,+ precision: 2,+ placeholder: "0.00",+ input_class: "privacy-sensitive privacy-sensitive-interactive",+ step: "any",+ min: 0,+ amount_data: { action: "input->cost-basis-form#updatePerShare", cost_basis_form_target: "total" } %>++ <div class="flex justify-end gap-2 pt-2">+ <%= render DS::Button.new(text: t("holdings.cost_basis_cell.cancel"), variant: :secondary, data: { action: cancel_action }) %>+ <%= render DS::Button.new(text: t("holdings.cost_basis_cell.save"), type: "submit") %>+ </div>+<% end %>diff --git a/app/views/holdings/show.html.erb b/app/views/holdings/show.html.erbindex 14d7cfd5c9..2fde086f69 100644--- a/app/views/holdings/show.html.erb+++ b/app/views/holdings/show.html.erb@@ -103,12 +103,7 @@<dd class="text-primary"><%= @holding.weight ? number_to_percentage(@holding.weight, precision: 2) : t(".unknown") %></dd></div><%# Average Cost with inline editor %>- <%- currency = Money::Currency.new(@holding.currency)- current_per_share = @holding.cost_basis.present? && @holding.cost_basis.positive? ? @holding.cost_basis : nil- current_total = current_per_share && @holding.qty.positive? ? (current_per_share * @holding.qty).round(2) : nil- %>- <div data-controller="drawer-cost-basis" data-drawer-cost-basis-qty-value="<%= @holding.qty %>">+ <div data-controller="drawer-cost-basis"><div class="flex items-center justify-between text-sm"><dt class="text-secondary"><%= t(".avg_cost_label") %></dt><dd class="text-primary flex items-center gap-1">@@ -119,75 +114,17 @@<% if @holding.cost_basis_source.present? %><span class="text-xs text-secondary">(<%= @holding.cost_basis_source_label %>)</span><% end %>- <button type="button" class="ml-1" data-action="click->drawer-cost-basis#toggle">+ <button type="button" class="ml-1" data-action="click->drawer-cost-basis#toggle" data-drawer-cost-basis-target="opener"><%= icon "pencil", size: "xs", class: "text-secondary hover:text-primary" %></button></dd></div><%# Inline cost basis editor (hidden by default) %><div class="hidden mt-3 space-y-3" data-drawer-cost-basis-target="form">- <%- drawer_form_data = { turbo: false }- if @holding.avg_cost- drawer_form_data[:turbo_confirm] = {- title: t("holdings.cost_basis_cell.overwrite_confirm_title"),- body: t("holdings.cost_basis_cell.overwrite_confirm_body", current: format_money(@holding.avg_cost))- }- end- %>- <%= styled_form_with model: @holding,- url: holding_path(@holding),- method: :patch,- class: "space-y-3",- data: drawer_form_data do |f| %>- <p class="text-xs text-secondary mb-2">- <%= t("holdings.cost_basis_cell.set_cost_basis_header", ticker: @holding.ticker, qty: format_quantity(@holding.qty, exact: true)) %>- </p>- <!-- Total cost basis input -->- <div class="form-field">- <div class="form-field__body">- <label class="form-field__label"><%= t("holdings.cost_basis_cell.total_cost_basis_label") %></label>- <div class="flex items-center gap-1">- <span class="text-secondary text-sm font-medium"><%= currency.symbol %></span>- <input type="number" step="any"- name="holding[cost_basis]"- class="form-field__input grow"- placeholder="0.00"- autocomplete="off"- value="<%= sprintf("%.2f", current_total) if current_total %>"- data-action="input->drawer-cost-basis#updatePerShare"- data-drawer-cost-basis-target="total">- <span class="text-secondary text-sm"><%= currency.iso_code %></span>- </div>- </div>- </div>- <p class="text-xs text-secondary -mt-2">- = <%= currency.symbol %><span data-drawer-cost-basis-target="perShareValue"><%= number_with_precision(current_per_share, precision: 2) || "0.00" %></span> <%= t("holdings.cost_basis_cell.per_share") %>- </p>- <!-- Per-share input -->- <div class="pt-2 border-t border-tertiary">- <label class="text-xs text-secondary block mb-1"><%= t("holdings.cost_basis_cell.or_per_share_label") %></label>- <div class="flex items-center gap-1">- <span class="text-secondary text-sm font-medium"><%= currency.symbol %></span>- <input type="number" step="any"- class="form-field__input grow"- placeholder="0.00"- autocomplete="off"- value="<%= sprintf("%.2f", current_per_share) if current_per_share %>"- data-action="input->drawer-cost-basis#updateTotal"- data-drawer-cost-basis-target="perShare">- <span class="text-secondary text-sm"><%= currency.iso_code %></span>- </div>- </div>- <div class="flex justify-end gap-2 pt-2">- <button type="button"- class="inline-flex items-center gap-1 px-3 py-2 rounded-lg text-sm font-medium text-primary button-bg-secondary-strong hover:button-bg-secondary-strong-hover"- data-action="click->drawer-cost-basis#toggle">- <%= t("holdings.cost_basis_cell.cancel") %>- </button>- <%= f.submit t("holdings.cost_basis_cell.save") %>- </div>- <% end %>+ <p class="text-xs text-secondary">+ <%= t("holdings.cost_basis_cell.set_cost_basis_header", ticker: @holding.ticker) %>+ </p>+ <%= render "holdings/cost_basis_form", holding: @holding, context: :drawer, cancel_action: "drawer-cost-basis#toggle" %></div></div><div class="flex items-center justify-between text-sm">diff --git a/app/views/shared/_money_field.html.erb b/app/views/shared/_money_field.html.erbindex 27f2d19fb1..78540a1b54 100644--- a/app/views/shared/_money_field.html.erb+++ b/app/views/shared/_money_field.html.erb@@ -68,7 +68,8 @@"auto-submit-form-target": ("auto" if options[:auto_submit]),action: [ options.dig(:amount_data, :action), "paste->money-field#pasteAmount" ].compact.join(" ")}.compact),- required: options[:required] %>+ required: options[:required],+ **options.slice(:name) %></div><% unless options[:hide_currency] %>diff --git a/config/locales/views/holdings/ca.yml b/config/locales/views/holdings/ca.ymlindex a28f73e47a..b7bbb0ba80 100644--- a/config/locales/views/holdings/ca.yml+++ b/config/locales/views/holdings/ca.yml@@ -5,13 +5,12 @@ ca:brokerage_cash: Efectiu del brokercost_basis_cell:cancel: Cancel·la- or_per_share_label: 'O introdueix per acció:'+ per_share_label: "Per acció"overwrite_confirm_body: Això reemplaçarà el cost base actual de %{current}.overwrite_confirm_title: Reemplaça el cost base?- per_share: per acciósave: Desaset: Estableix- set_cost_basis_header: Estableix el cost base per a %{ticker} (%{qty} accions)+ set_cost_basis_header: Estableix el cost base per a %{ticker}total_cost_basis_label: Cost base totalunknown: "--"cost_basis_sources:diff --git a/config/locales/views/holdings/de.yml b/config/locales/views/holdings/de.ymlindex 8a50740587..bef1ee2f79 100644--- a/config/locales/views/holdings/de.yml+++ b/config/locales/views/holdings/de.yml@@ -24,10 +24,9 @@ de:provider: Vom Providercost_basis_cell:unknown: "--"- set_cost_basis_header: "Einstandspreis für %{ticker} setzen (%{qty} Anteile)"+ set_cost_basis_header: "Einstandspreis für %{ticker} setzen"total_cost_basis_label: Gesamter Einstandspreis- or_per_share_label: "Oder pro Anteil eingeben:"- per_share: pro Anteil+ per_share_label: "Pro Anteil"cancel: Abbrechensave: Speichernoverwrite_confirm_title: Einstandspreis überschreiben?diff --git a/config/locales/views/holdings/en.yml b/config/locales/views/holdings/en.ymlindex 3820fcf64c..8099b6c1aa 100644--- a/config/locales/views/holdings/en.yml+++ b/config/locales/views/holdings/en.yml@@ -29,10 +29,9 @@ en:cost_basis_cell:unknown: "--"set: Set- set_cost_basis_header: "Set cost basis for %{ticker} (%{qty} shares)"+ set_cost_basis_header: "Set cost basis for %{ticker}"total_cost_basis_label: Total cost basis- or_per_share_label: "Or enter per share:"- per_share: per share+ per_share_label: "Per share"cancel: Cancelsave: Saveoverwrite_confirm_title: Overwrite cost basis?diff --git a/config/locales/views/holdings/es.yml b/config/locales/views/holdings/es.ymlindex d02bd988ca..3380bdd35f 100644--- a/config/locales/views/holdings/es.yml+++ b/config/locales/views/holdings/es.yml@@ -29,10 +29,9 @@ es:cost_basis_cell:unknown: --set: Establecer- set_cost_basis_header: Establecer base de costes para %{ticker} (%{qty} acciones)+ set_cost_basis_header: Establecer base de costes para %{ticker}total_cost_basis_label: Base de costes total- or_per_share_label: 'O introduce por acción:'- per_share: por acción+ per_share_label: "Por acción"cancel: Cancelarsave: Guardaroverwrite_confirm_title: ¿Sobrescribir base de costes?diff --git a/config/locales/views/holdings/fr.yml b/config/locales/views/holdings/fr.ymlindex 1d6d136d44..439f864591 100644--- a/config/locales/views/holdings/fr.yml+++ b/config/locales/views/holdings/fr.yml@@ -5,13 +5,12 @@ fr:brokerage_cash: Liquidités de courtagecost_basis_cell:cancel: Annuler- or_per_share_label: 'Ou saisir par action :'+ per_share_label: "Par action"overwrite_confirm_body: Cela remplacera le coût de revient actuel de %{current}.overwrite_confirm_title: Écraser le coût de revient ?- per_share: par actionsave: Enregistrerset: Définir- set_cost_basis_header: Définir le coût de revient pour %{ticker} (%{qty} actions)+ set_cost_basis_header: Définir le coût de revient pour %{ticker}total_cost_basis_label: Coût de revient totalunknown: "--"cost_basis_sources:diff --git a/config/locales/views/holdings/hu.yml b/config/locales/views/holdings/hu.ymlindex 0346320e9d..025ebcf4eb 100644--- a/config/locales/views/holdings/hu.yml+++ b/config/locales/views/holdings/hu.yml@@ -29,10 +29,9 @@ hu:cost_basis_cell:unknown: "--"set: Megadás- set_cost_basis_header: "Bekerülési érték megadása: %{ticker} (%{qty} részvény)"+ set_cost_basis_header: "Bekerülési érték megadása: %{ticker}"total_cost_basis_label: Teljes bekerülési érték- or_per_share_label: "Vagy add meg részvényenként:"- per_share: részvényenként+ per_share_label: "Részvényenként"cancel: Mégsesave: Mentésoverwrite_confirm_title: Felülírja a bekerülési értéket?diff --git a/config/locales/views/holdings/it.yml b/config/locales/views/holdings/it.ymlindex 97f3bc2b0f..a800b80c01 100644--- a/config/locales/views/holdings/it.yml+++ b/config/locales/views/holdings/it.yml@@ -29,10 +29,9 @@ it:cost_basis_cell:unknown: "--"set: Imposta- set_cost_basis_header: "Imposta costo base per %{ticker} (%{qty} azioni)"+ set_cost_basis_header: "Imposta costo base per %{ticker}"total_cost_basis_label: Costo base totale- or_per_share_label: "Oppure inserisci per azione:"- per_share: per azione+ per_share_label: "Per azione"cancel: Annullasave: Salvaoverwrite_confirm_title: Sovrascrivere il costo base?diff --git a/config/locales/views/holdings/nl.yml b/config/locales/views/holdings/nl.ymlindex 42e6be074e..b7d3286665 100644--- a/config/locales/views/holdings/nl.yml+++ b/config/locales/views/holdings/nl.yml@@ -16,10 +16,9 @@ nl:provider: Van providercost_basis_cell:unknown: "--"- set_cost_basis_header: "Kostprijs instellen voor %{ticker} (%{qty} aandelen)"+ set_cost_basis_header: "Kostprijs instellen voor %{ticker}"total_cost_basis_label: Totale kostprijs- or_per_share_label: "Of voer per aandeel in:"- per_share: per aandeel+ per_share_label: "Per aandeel"cancel: Annulerensave: Opslaanoverwrite_confirm_title: Kostprijs overschrijven?diff --git a/config/locales/views/holdings/pl.yml b/config/locales/views/holdings/pl.ymlindex 1c53db8847..2a8a2b723c 100644--- a/config/locales/views/holdings/pl.yml+++ b/config/locales/views/holdings/pl.yml@@ -5,14 +5,13 @@ pl:brokerage_cash: Gotówka maklerskacost_basis_cell:cancel: Anuluj- or_per_share_label: 'Lub wpisz na akcję:'+ per_share_label: "Na akcję"overwrite_confirm_body: Spowoduje to zastąpienie aktualnego kosztu bazowegowynoszącego %{current}.overwrite_confirm_title: Nadpisać koszt bazowy?- per_share: na akcjęsave: Zapiszset: Ustaw- set_cost_basis_header: Ustaw koszt bazowy dla %{ticker} (%{qty} akcji)+ set_cost_basis_header: Ustaw koszt bazowy dla %{ticker}total_cost_basis_label: Łączny koszt bazowyunknown: "--"cost_basis_sources:diff --git a/config/locales/views/holdings/pt-PT.yml b/config/locales/views/holdings/pt-PT.ymlindex e8cc1d2b51..73bdffe5cb 100644--- a/config/locales/views/holdings/pt-PT.yml+++ b/config/locales/views/holdings/pt-PT.yml@@ -29,10 +29,9 @@ pt-PT:cost_basis_cell:unknown: "--"set: Definir- set_cost_basis_header: "Definir base de custo para %{ticker} (%{qty} ações)"+ set_cost_basis_header: "Definir base de custo para %{ticker}"total_cost_basis_label: Base de custo total- or_per_share_label: "Ou introduzir por ação:"- per_share: por ação+ per_share_label: "Por ação"cancel: Cancelarsave: Guardaroverwrite_confirm_title: Substituir base de custo?diff --git a/config/locales/views/holdings/ru.yml b/config/locales/views/holdings/ru.ymlindex 3ec1e0c337..b541a50268 100644--- a/config/locales/views/holdings/ru.yml+++ b/config/locales/views/holdings/ru.yml@@ -5,13 +5,12 @@ ru:brokerage_cash: Денежные средства на брокерском счётеcost_basis_cell:cancel: Отмена- or_per_share_label: 'Или введите за акцию:'+ per_share_label: "За акцию"overwrite_confirm_body: Это заменит текущую стоимость приобретения %{current}.overwrite_confirm_title: Перезаписать стоимость приобретения?- per_share: за акциюsave: Сохранитьset: Установить- set_cost_basis_header: Установить стоимость приобретения для %{ticker} (%{qty} акций)+ set_cost_basis_header: Установить стоимость приобретения для %{ticker}total_cost_basis_label: Общая стоимость приобретенияunknown: "--"cost_basis_sources:diff --git a/config/locales/views/holdings/tr.yml b/config/locales/views/holdings/tr.ymlindex 58e7bf779b..f00327145d 100644--- a/config/locales/views/holdings/tr.yml+++ b/config/locales/views/holdings/tr.yml@@ -5,13 +5,12 @@ tr:brokerage_cash: Aracı kurum nakiticost_basis_cell:cancel: İptal- or_per_share_label: 'Veya hisse başına girin:'+ per_share_label: "Hisse başına"overwrite_confirm_body: Bu işlem, mevcut %{current} maliyet bazını değiştirecektir.overwrite_confirm_title: Maliyet bazının üzerine yazılsın mı?- per_share: hisse başınasave: Kaydetset: Ayarla- set_cost_basis_header: "%{ticker} için maliyet bazını ayarla (%{qty} hisse)"+ set_cost_basis_header: "%{ticker} için maliyet bazını ayarla"total_cost_basis_label: Toplam maliyet bazıunknown: "--"cost_basis_sources:diff --git a/config/locales/views/holdings/uk.yml b/config/locales/views/holdings/uk.ymlindex c2870a4f91..ce78e0c032 100644--- a/config/locales/views/holdings/uk.yml+++ b/config/locales/views/holdings/uk.yml@@ -29,10 +29,9 @@ uk:cost_basis_cell:unknown: "--"set: "Встановити"- set_cost_basis_header: "Встановити базову вартість для %{ticker} (%{qty} акцій)"+ set_cost_basis_header: "Встановити базову вартість для %{ticker}"total_cost_basis_label: "Загальна базова вартість"- or_per_share_label: "Або введіть за акцію:"- per_share: "за акцію"+ per_share_label: "За акцію"cancel: "Скасувати"save: "Зберегти"overwrite_confirm_title: "Перезаписати базову вартість?"diff --git a/config/locales/views/holdings/vi.yml b/config/locales/views/holdings/vi.ymlindex 2475b3106c..28891d70cf 100644--- a/config/locales/views/holdings/vi.yml+++ b/config/locales/views/holdings/vi.yml@@ -29,10 +29,9 @@ vi:cost_basis_cell:unknown: "--"set: Đặt- set_cost_basis_header: "Đặt giá vốn cho %{ticker} (%{qty} cổ phiếu)"+ set_cost_basis_header: "Đặt giá vốn cho %{ticker}"total_cost_basis_label: Tổng giá vốn- or_per_share_label: "Hoặc nhập mỗi cổ phiếu:"- per_share: mỗi cổ phiếu+ per_share_label: "Mỗi cổ phiếu"cancel: Hủysave: Lưuoverwrite_confirm_title: Ghi đè giá vốn?diff --git a/config/locales/views/holdings/zh-CN.yml b/config/locales/views/holdings/zh-CN.ymlindex ac8b5480b3..d1ead336ea 100644--- a/config/locales/views/holdings/zh-CN.yml+++ b/config/locales/views/holdings/zh-CN.yml@@ -29,10 +29,9 @@ zh-CN:cost_basis_cell:unknown: --set: 设置- set_cost_basis_header: 为 %{ticker}(%{qty} 股)设置成本基础+ set_cost_basis_header: 为 %{ticker} 设置成本基础total_cost_basis_label: 总成本基础- or_per_share_label: 或输入每股:- per_share: 每股+ per_share_label: "每股"cancel: 取消save: 保存overwrite_confirm_title: 覆盖成本基础?diff --git a/config/locales/views/holdings/zh-TW.yml b/config/locales/views/holdings/zh-TW.ymlindex 87e155005c..4e0aac9fa8 100644--- a/config/locales/views/holdings/zh-TW.yml+++ b/config/locales/views/holdings/zh-TW.yml@@ -29,10 +29,9 @@ zh-TW:cost_basis_cell:unknown: --set: 設定- set_cost_basis_header: 設定 %{ticker} 的成本基礎(%{qty} 股)+ set_cost_basis_header: 設定 %{ticker} 的成本基礎total_cost_basis_label: 總成本基礎- or_per_share_label: 或輸入每股金額:- per_share: /股+ per_share_label: "每股"cancel: 取消save: 儲存overwrite_confirm_title: 要覆蓋成本基礎嗎?diff --git a/test/controllers/holdings_controller_test.rb b/test/controllers/holdings_controller_test.rbindex f3113fc8c8..b658489a26 100644--- a/test/controllers/holdings_controller_test.rb+++ b/test/controllers/holdings_controller_test.rb@@ -75,6 +75,132 @@ class HoldingsControllerTest < ActionDispatch::IntegrationTestassert @holding.cost_basis_locked?end+ test "updates cost basis with the submitted per-share cost" do+ @holding.update!(qty: 10, cost_basis: nil, cost_basis_source: nil, cost_basis_locked: false)++ # 10 x 0.0049 is 0.049, which a total rounded to cents would turn into 0.005+ patch holding_path(@holding), params: { holding: { per_share_cost_basis: "0.0049" } }++ @holding.reload+ assert_equal BigDecimal("0.0049"), @holding.cost_basis+ assert_equal "manual", @holding.cost_basis_source+ assert @holding.cost_basis_locked?+ end++ test "an empty cost basis is not saved as zero" do+ @holding.update!(qty: 10, cost_basis: nil, cost_basis_source: nil, cost_basis_locked: false)++ patch holding_path(@holding), params: { holding: { per_share_cost_basis: "" } }++ @holding.reload+ assert_nil @holding.cost_basis+ assert_not @holding.cost_basis_locked?+ assert_equal I18n.t("holdings.update.error"), flash[:alert]+ end++ test "cost basis editor shows the stored decimals of a per-share cost below a cent" do+ @holding.update!(qty: 10, cost_basis: 0.0049, cost_basis_locked: true)++ get holding_path(@holding)++ form_id = "#{dom_id(@holding, :drawer_cost_basis)}_holding"+ assert_select "##{form_id}_per_share_cost_basis[value='0.0049']"+ assert_select "##{form_id}_total_cost_basis[value='0.05']"+ end++ test "cost basis editor reads per share times quantity equals total" do+ @holding.update!(qty: 10, cost_basis: 12.5)++ get holding_path(@holding)++ form_id = "#{dom_id(@holding, :drawer_cost_basis)}_holding"+ assert_select "form[data-controller=cost-basis-form]" do |forms|+ rows = forms.first.element_children.select { |node| node.matches?(".form-field, p") }+ assert_equal 3, rows.size+ assert rows[0].at_css("input##{form_id}_per_share_cost_basis[name='holding[per_share_cost_basis]'][value='12.50']")+ assert_equal "× 10 shares", rows[1].text.squish+ assert rows[2].at_css("input##{form_id}_total_cost_basis:not([name])[value='125.00']")+ end+ assert_select "label[for=#{form_id}_per_share_cost_basis]", text: /\A\s*#{I18n.t("holdings.cost_basis_cell.per_share_label")}\s*\*\s*\z/+ assert_select "input##{form_id}_per_share_cost_basis[required]"+ assert_select "label[for=#{form_id}_total_cost_basis]", text: "= #{I18n.t("holdings.cost_basis_cell.total_cost_basis_label")}"+ assert_select "[data-cost-basis-form-target=perShareValue]", count: 0+ end++ test "cost basis editor keeps two decimals for zero-decimal currencies" do+ @holding.update!(qty: 2, cost_basis: 12.2, currency: "JPY")++ get holding_path(@holding)++ form_id = "#{dom_id(@holding, :drawer_cost_basis)}_holding"+ assert_select "##{form_id}_total_cost_basis[value='24.40']"+ assert_select "##{form_id}_per_share_cost_basis[value='12.20']"+ end++ # money_field#pasteAmount leaves pastes unrounded on step="any" fields.+ test "cost basis editor does not round pasted values to its display decimals" do+ get holding_path(@holding)++ assert_select "form[data-controller=cost-basis-form] [data-controller=money-field]", count: 2+ assert_select "form[data-controller=cost-basis-form] input[step=any]", count: 2+ end++ test "cost basis editor blurs its values in privacy mode" do+ get holding_path(@holding)++ assert_select "form[data-controller=cost-basis-form]" do+ assert_select "input.privacy-sensitive.privacy-sensitive-interactive", count: 2+ assert_select "span.privacy-sensitive", text: /shares\z/, count: 1+ end+ end++ test "cost basis editor submits through Turbo so the overwrite confirmation shows" do+ @holding.update!(qty: 10, cost_basis: 12.5, cost_basis_locked: true)++ get holding_path(@holding)++ assert_select "form[data-controller=cost-basis-form][data-turbo-frame=_top][data-turbo-confirm]"+ assert_select "form[data-controller=cost-basis-form][data-turbo=false]", count: 0+ end++ test "cost basis editor shows a stored zero basis instead of placeholders" do+ @holding.update!(qty: 10, cost_basis: 0, cost_basis_locked: true)++ get holding_path(@holding)++ form_id = "#{dom_id(@holding, :drawer_cost_basis)}_holding"+ assert_select "##{form_id}_per_share_cost_basis[value='0.00']"+ assert_select "##{form_id}_total_cost_basis[value='0.00']"+ end++ test "cost basis editor leaves the fields empty for an unknown zero basis" do+ # Providers report 0 when they don't know the basis; avg_cost then falls+ # back to the trades, so the editor must not offer 0 for saving.+ @holding.update!(qty: 10, cost_basis: 0, cost_basis_locked: false)++ get holding_path(@holding)++ form_id = "#{dom_id(@holding, :drawer_cost_basis)}_holding"+ assert_select "##{form_id}_per_share_cost_basis:not([value])"+ assert_select "##{form_id}_total_cost_basis:not([value])"+ end++ test "cost basis editor keeps the equation operators readable" do+ get holding_path(@holding)++ assert_select "form[data-controller=cost-basis-form] [aria-hidden]", count: 0+ end++ test "cost basis editor in the holdings list uses its own field ids" do+ holding = @account.current_holdings.first+ holding.update!(cost_basis_locked: false)++ get holdings_url(account_id: @account.id)++ assert_select "##{dom_id(holding, :popover_cost_basis)}_holding_per_share_cost_basis[name='holding[per_share_cost_basis]']", count: 1+ assert_select "[id^=drawer_cost_basis_]", count: 0+ end+test "unlock_cost_basis removes lock" do# Given: locked holding@holding.update!(cost_basis: 50.0, cost_basis_source: "manual", cost_basis_locked: true)diff --git a/test/system/holding_cost_basis_test.rb b/test/system/holding_cost_basis_test.rbnew file mode 100644index 0000000000..29e1c58d3f--- /dev/null+++ b/test/system/holding_cost_basis_test.rb@@ -0,0 +1,200 @@+require "application_system_test_case"++class HoldingCostBasisTest < ApplicationSystemTestCase+ setup do+ sign_in @user = users(:family_admin)+ @user.update!(show_sidebar: false, show_ai_sidebar: false)++ @holding = holdings(:one)+ @holding.update!(qty: 10_000, cost_basis: nil, cost_basis_source: nil, cost_basis_locked: false)+ end++ # Per share 0.0049 x 10,000 shares = 49. Rounding the pasted price to the+ # fields' two display decimals turned it into 0.00 and saved a basis of 0.+ test "a sub-cent per-share price saves the same basis typed or pasted" do+ open_cost_basis_editor+ find(per_share_field).fill_in(with: "0.0049")+ assert_field total_field_id, with: "49.00"+ save_cost_basis++ assert_equal BigDecimal("0.0049"), @holding.reload.cost_basis++ @holding.update!(cost_basis: nil, cost_basis_source: nil, cost_basis_locked: false)++ open_cost_basis_editor+ paste_into per_share_field, "0.0049"+ assert_field per_share_field_id, with: "0.0049"+ assert_field total_field_id, with: "49.00"+ save_cost_basis++ assert_equal BigDecimal("0.0049"), @holding.reload.cost_basis+ end++ # 10 x 0.0049 = 0.049. A total rounded to cents (0.05) saved 0.005 per share,+ # also when the form was saved unchanged.+ test "a sub-cent per-share price survives a total below a cent and an unchanged save" do+ @holding.update!(qty: 10)++ open_cost_basis_editor+ find(per_share_field).fill_in(with: "0.0049")+ assert_field total_field_id, with: "0.05"+ save_cost_basis++ assert_equal BigDecimal("0.0049"), @holding.reload.cost_basis++ open_cost_basis_editor+ assert_field per_share_field_id, with: "0.0049"+ save_cost_basis++ assert_equal BigDecimal("0.0049"), @holding.reload.cost_basis+ end++ test "a total fills in the per-share cost with up to four decimals" do+ @holding.update!(qty: 3)++ open_cost_basis_editor+ find("##{total_field_id}").fill_in(with: "49")+ assert_field per_share_field_id, with: "16.3333"+ save_cost_basis++ assert_equal BigDecimal("16.3333"), @holding.reload.cost_basis+ end++ # Clearing a field must clear the other one too: an empty total used to put+ # 0.00 into the submitted per-share field and lock an unknown basis as 0.+ test "clearing either field leaves the other empty and saves no basis" do+ @holding.update!(qty: 10)++ open_cost_basis_editor+ find("##{total_field_id}").fill_in(with: "49")+ assert_field per_share_field_id, with: "4.90"+ find("##{total_field_id}").fill_in(with: "", fill_options: { clear: :backspace })+ assert_field per_share_field_id, with: ""++ find(per_share_field).fill_in(with: "4.9")+ assert_field total_field_id, with: "49.00"+ find(per_share_field).fill_in(with: "", fill_options: { clear: :backspace })+ assert_field total_field_id, with: ""++ find(per_share_field).ancestor("form").click_on I18n.t("holdings.cost_basis_cell.save")+ assert_selector per_share_field+ assert_no_selector "#confirm-dialog[open]"++ assert_nil @holding.reload.cost_basis+ assert_not @holding.cost_basis_locked?+ end++ # The total field shows two decimals but is step="any", so a pasted total+ # below a cent is kept as pasted and gives the exact per-share cost.+ test "a pasted total is not rounded to the total field's two decimals" do+ @holding.update!(qty: 10)++ open_cost_basis_editor+ paste_into "##{total_field_id}", "0.049"+ assert_field total_field_id, with: "0.049"+ assert_field per_share_field_id, with: "0.0049"+ save_cost_basis++ assert_equal BigDecimal("0.0049"), @holding.reload.cost_basis++ # Unrounded pastes are written out, not in exponent notation (1.2e-7).+ open_cost_basis_editor+ paste_into per_share_field, "0.00000012"+ assert_field per_share_field_id, with: "0.00000012"+ end++ test "cancelling the confirmation keeps the holdings-list editor open and Cancel refocuses its trigger" do+ @holding.update!(qty: 10, cost_basis: 12.5, cost_basis_source: "manual", cost_basis_locked: false)++ visit account_path(@holding.account, tab: "holdings")+ trigger = find("##{dom_id(@holding, :cost_basis)} [data-DS--popover-target='button']")+ trigger.click+ field = "##{dom_id(@holding, :popover_cost_basis)}_holding_per_share_cost_basis"+ find(field).fill_in(with: "20")+ find(field).ancestor("form").click_on I18n.t("holdings.cost_basis_cell.save")++ within("#confirm-dialog") { find("button[value=cancel]").click }+ assert_no_selector "#confirm-dialog[open]"+ assert_field field.delete_prefix("#"), with: "20"++ find(field).ancestor("form").click_on I18n.t("holdings.cost_basis_cell.cancel")+ assert_no_selector field+ assert page.evaluate_script("document.activeElement.matches(\"##{dom_id(@holding, :cost_basis)} [data-DS--popover-target='button']\")")+ assert_equal BigDecimal("12.5"), @holding.reload.cost_basis+ end++ test "overwriting a cost basis asks first and keeps it when cancelled" do+ @holding.update!(qty: 10, cost_basis: 12.5, cost_basis_source: "manual", cost_basis_locked: true)++ open_cost_basis_editor+ find(per_share_field).fill_in(with: "20")+ find(per_share_field).ancestor("form").click_on I18n.t("holdings.cost_basis_cell.save")++ within "#confirm-dialog" do+ assert_text I18n.t("holdings.cost_basis_cell.overwrite_confirm_title")+ find("button[value=cancel]").click+ end++ assert_equal BigDecimal("12.5"), @holding.reload.cost_basis++ save_cost_basis+ assert_equal BigDecimal("20"), @holding.reload.cost_basis+ end++ test "the drawer editor moves focus in on open and back to the pencil on cancel" do+ open_cost_basis_editor+ assert_equal per_share_field_id, active_element_id++ find(per_share_field).ancestor("form").click_on I18n.t("holdings.cost_basis_cell.cancel")+ assert_no_selector per_share_field+ assert page.evaluate_script("document.activeElement.matches('[data-drawer-cost-basis-target=opener]')")+ end++ private+ def active_element_id+ page.evaluate_script("document.activeElement.id")+ end++ def form_id+ "#{dom_id(@holding, :drawer_cost_basis)}_holding"+ end++ def per_share_field_id+ "#{form_id}_per_share_cost_basis"+ end++ def total_field_id+ "#{form_id}_total_cost_basis"+ end++ def per_share_field+ "##{per_share_field_id}"+ end++ def open_cost_basis_editor+ visit holding_path(@holding)+ find("[data-action='click->drawer-cost-basis#toggle']").click+ assert_selector per_share_field+ end++ # A holding that already has a basis asks before overwriting it.+ def save_cost_basis+ form = find(per_share_field).ancestor("form")+ confirm = form["data-turbo-confirm"].present?+ form.click_on I18n.t("holdings.cost_basis_cell.save")+ within("#confirm-dialog") { find("button[value=confirm]", visible: true).click } if confirm+ assert_no_selector per_share_field+ end++ # Fires a real paste event so money_field#pasteAmount handles it, as it+ # does for a value copied from a statement or spreadsheet.+ def paste_into(selector, text)+ page.execute_script(<<~JS, find(selector), text)+ const [input, text] = arguments+ const data = new DataTransfer()+ data.setData("text/plain", text)+ input.focus()+ input.dispatchEvent(new ClipboardEvent("paste", { clipboardData: data, bubbles: true, cancelable: true }))+ JS+ end+end