Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Import closing prices for untracked securities through the API (#4785)

jaysbeekaya9db3ee44bc3
diff --git a/app/controllers/api/v1/security_prices_controller.rb b/app/controllers/api/v1/security_prices_controller.rb
index 5463f0f975..f72d89dce3 100644
--- a/app/controllers/api/v1/security_prices_controller.rb
+++ b/app/controllers/api/v1/security_prices_controller.rb
@@ -4,7 +4,10 @@ class Api::V1::SecurityPricesController < Api::V1::BaseController
include Pagy::Backend
include Api::V1::SecurityResourceFiltering
- before_action :ensure_read_scope
+ before_action :ensure_read_scope, only: %i[index show]
+ before_action :ensure_write_scope, only: :create
+ before_action :ensure_self_hosted, only: :create
+ before_action :reject_guest_writes!, only: :create
before_action :set_security_price, only: :show
def index
@@ -26,7 +29,70 @@ class Api::V1::SecurityPricesController < Api::V1::BaseController
render :show
end
+ # Stores closing prices for one security no provider tracks, traded in an
+ # account the caller can write to, or held in a linked one.
+ # The rows are shared by every family holding that security, which is why
+ # this is limited to self-hosted instances.
+ def create
+ security, accounts = writable_security_and_accounts
+
+ @result = security.import_manual_prices!(price_rows, accounts: accounts)
+ @security = security
+ accounts.find_each(&:sync_later)
+
+ render :create
+ rescue Security::ManualPriceImport::Invalid => e
+ render_json({ error: "validation_failed", message: "Prices were not imported", errors: e.errors }, status: :unprocessable_entity)
+ end
+
private
+ def ensure_write_scope
+ authorize_scope!(:write)
+ end
+
+ def ensure_self_hosted
+ return if self_hosted?
+
+ render_json({
+ error: "self_hosted_only",
+ message: "Security prices are shared across families, so importing them is only available on self-hosted instances"
+ }, status: :forbidden)
+ end
+
+ # The security and the caller's writable accounts eligible to price it.
+ # Unknown, malformed and unreachable ids all get the same 404.
+ def writable_security_and_accounts
+ security_id = params.require(:security_id).to_s
+ security = Security.find_by(id: security_id) if valid_uuid?(security_id)
+ accounts = writable_accounts_referencing(security) if security
+ raise ActiveRecord::RecordNotFound, "Security not found" unless accounts&.exists?
+
+ [ security, accounts ]
+ end
+
+ # Only accounts whose position survives the sync this request queues: one
+ # with a trade in the security, or a linked account, whose holdings come
+ # from its provider and whose reverse sync never purges. An unlinked
+ # account's forward sync rebuilds holdings from trades and deletes every
+ # other non-provider row (Holding::Materializer#purge_stale_holdings), so
+ # a holding no trade backs would be removed rather than revalued.
+ def writable_accounts_referencing(security)
+ writable = current_resource_owner.family.accounts.visible.writable_by(current_resource_owner).select(:id)
+ traded = Account.where(id: Trade.joins(:entry).where(security: security).select("entries.account_id"))
+ provider_held = Account.where(id: Holding.where(security: security).select(:account_id))
+ .where(id: Account.linked.select(:id))
+
+ Account.where(id: writable).and(traded.or(provider_held))
+ end
+
+ def price_rows
+ rows = params[:prices]
+ unless rows.is_a?(Array)
+ raise Security::ManualPriceImport::Invalid.new([ { index: nil, message: "prices must be a list" } ])
+ end
+
+ rows.map { |row| row.is_a?(ActionController::Parameters) ? row.permit(:date, :price, :currency).to_h : row }
+ end
def set_security_price
raise ActiveRecord::RecordNotFound, "Security price not found" unless valid_uuid?(params[:id])
diff --git a/app/models/security.rb b/app/models/security.rb
index e69813c225..e5753d5006 100644
--- a/app/models/security.rb
+++ b/app/models/security.rb
@@ -255,6 +255,11 @@ class Security < ApplicationRecord
Money.new(@current_price.price, @current_price.currency)
end
+ # Stores user-supplied closes for a security no provider tracks. See Security::ManualPriceImport.
+ def import_manual_prices!(rows, accounts:)
+ Security::ManualPriceImport.new(security: self, rows: rows, accounts: accounts).import!
+ end
+
# How many shares one share held at the close of `from` has become by the
# close of `to`: the product of the ratios of splits whose ex-date falls
# after `from` and on or before `to`. 1 when there are none.
diff --git a/app/models/security/manual_price_import.rb b/app/models/security/manual_price_import.rb
new file mode 100644
index 0000000000..62cdd22006
--- /dev/null
+++ b/app/models/security/manual_price_import.rb
@@ -0,0 +1,189 @@
+# Writes user-supplied daily closes for a security no provider tracks. Rows land in the shared security_prices table,
+# so they value every family holding the security, not just the caller's.
+#
+# All rows are validated before any is written, and the write is one upsert:
+# a request either stores every close or none.
+class Security::ManualPriceImport
+ MAX_ROWS = 1000
+
+ Result = Data.define(:currency, :created, :updated, :start_date, :end_date)
+
+ class Invalid < StandardError
+ attr_reader :errors
+
+ def initialize(errors)
+ @errors = errors
+ super(errors.map { |e| e[:message] }.join("; "))
+ end
+ end
+
+ # `accounts` are the caller's accounts trading the security, or holding it
+ # in a linked account. A security with no prices yet takes its currency from
+ # their trades, or failing that their holdings.
+ def initialize(security:, rows:, accounts:)
+ @security = security
+ @rows = rows
+ @accounts = accounts
+ end
+
+ def import!
+ raise Invalid.new([ error(nil, "prices must contain at least one row") ]) if rows.empty?
+ raise Invalid.new([ error(nil, "a request can carry at most #{MAX_ROWS} prices") ]) if rows.size > MAX_ROWS
+
+ parsed, errors = parse_rows
+
+ # The unique key includes currency, so two first imports in different
+ # currencies would not conflict. The security's row lock is held from the
+ # eligibility and currency checks through the upsert, so a resolver that
+ # assigns a provider, or another import, cannot slip in between.
+ security.with_lock do
+ raise Invalid.new([ error(nil, "prices cannot be imported for a cash position") ]) if security.cash?
+ raise Invalid.new([ error(nil, "prices can only be imported for a security no provider tracks") ]) unless untracked?
+ # Every bad row is reported at once: a row that parsed can still carry
+ # the wrong currency beside one that did not parse.
+ errors = (errors + currency_errors(parsed)).sort_by { |e| e[:index] || -1 }
+ raise Invalid.new(errors) if errors.any?
+
+ write(parsed)
+ end
+ end
+
+ private
+ attr_reader :security, :rows, :accounts
+
+ ParsedRow = Data.define(:index, :date, :price, :currency)
+
+ # Offline with no reason and no assigned provider means no provider ever
+ # matched the ticker. Any other offline security is a listed one that is
+ # down for now ("health_check_failed", "provider_disabled",
+ # "resolution_pending"). The importer keeps non-provisional rows, so closes
+ # written there would outlast the provider's own once it came back.
+ def untracked?
+ security.offline? && security.offline_reason.blank? && security.price_provider.blank?
+ end
+
+ def parse_rows
+ errors = []
+ seen_dates = {}
+
+ parsed = rows.each_with_index.filter_map do |row, index|
+ unless row.is_a?(Hash)
+ errors << error(index, "row must be an object with date, price and currency")
+ next
+ end
+
+ date, date_error = parse_date(row["date"])
+ price, price_error = parse_price(row["price"])
+ currency = row["currency"].to_s.strip.upcase
+ currency_error = "currency must be an ISO 4217 code" unless Money::Currency.all.key?(currency.downcase)
+
+ message = date_error || price_error || currency_error
+ if message.nil? && seen_dates.key?(date)
+ message = "date appears more than once in this batch"
+ end
+
+ if message
+ errors << error(index, message)
+ next
+ end
+
+ seen_dates[date] = true
+ ParsedRow.new(index:, date:, price:, currency:)
+ end
+
+ [ parsed, errors ]
+ end
+
+ # Calendar dates only: Date.iso8601 also takes week ("2026-W10-1"),
+ # ordinal ("2026-070") and basic ("20260301") forms.
+ def parse_date(value)
+ raise ArgumentError unless value.to_s.match?(/\A\d{4}-\d{2}-\d{2}\z/)
+
+ date = Date.iso8601(value.to_s)
+ return [ nil, "date must not be in the future" ] if date > Date.current
+
+ [ date, nil ]
+ rescue ArgumentError
+ [ nil, "date must be an ISO 8601 date" ]
+ end
+
+ def parse_price(value)
+ price = BigDecimal(value.to_s)
+ return [ nil, "price must be greater than 0" ] unless price.positive?
+ return [ nil, "price must have at most 4 decimal places" ] unless price.round(4) == price
+ return [ nil, "price is too large" ] if price >= 10**15
+
+ [ price, nil ]
+ rescue ArgumentError, TypeError
+ [ nil, "price must be a number" ]
+ end
+
+ def currency_errors(parsed)
+ return [] if parsed.empty?
+
+ allowed = allowed_currencies
+ return [ error(nil, allowed[:error]) ] if allowed[:error]
+
+ batch_currency = parsed.first.currency
+ parsed.filter_map do |row|
+ if allowed[:currencies].exclude?(row.currency)
+ error(row.index, allowed[:message])
+ elsif row.currency != batch_currency
+ error(row.index, "every row in one request must use the same currency")
+ end
+ end
+ end
+
+ # A security's existing prices fix its currency. Without any, the caller's
+ # trades decide, then their holdings. Valuation reads a stored price for a
+ # date without choosing a currency, so a second currency is never added.
+ def allowed_currencies
+ existing = security.prices.distinct.order(:currency).pluck(:currency)
+ if existing.any?
+ noun = existing.one? ? "the currency" : "the currencies"
+ return { currencies: existing, message: "currency must be #{existing.to_sentence(two_words_connector: ' or ', last_word_connector: ' or ')}, #{noun} of this security's prices" }
+ end
+
+ currencies, source = position_currencies
+ if currencies.empty?
+ return { error: "no trade or holding of this security records a currency, so none can be chosen for its prices" }
+ end
+ if currencies.many?
+ return { error: "this security's #{source} are in more than one currency (#{currencies.join(', ')}); none can be chosen for its prices" }
+ end
+
+ { currencies: currencies, message: "currency must be #{currencies.first}, the currency of your #{source} in this security" }
+ end
+
+ def position_currencies
+ account_ids = accounts.select(:id)
+ from_trades = Trade.joins(:entry).where(security: security, entries: { account_id: account_ids })
+ .where.not(currency: nil).distinct.order(:currency).pluck(:currency)
+ return [ from_trades, "trades" ] if from_trades.any?
+
+ from_holdings = Holding.where(security: security, account_id: account_ids)
+ .where.not(currency: nil).distinct.order(:currency).pluck(:currency)
+ [ from_holdings, "holdings" ]
+ end
+
+ def write(parsed)
+ currency = parsed.first.currency
+ dates = parsed.map(&:date)
+
+ # xmax is 0 only on a row this statement inserted, so the counts hold
+ # even when another request writes the same dates concurrently.
+ inserted = Security::Price.upsert_all(
+ parsed.map { |row| { security_id: security.id, date: row.date, price: row.price, currency: currency, provisional: false } },
+ unique_by: %i[security_id date currency],
+ update_only: %i[price provisional],
+ returning: Arel.sql("(xmax = 0) AS inserted")
+ ).rows.flatten
+ created = inserted.count(true)
+
+ Result.new(currency:, created:, updated: inserted.size - created, start_date: dates.min, end_date: dates.max)
+ end
+
+ def error(index, message)
+ { index: index, message: message }
+ end
+end
diff --git a/app/views/api/v1/security_prices/create.json.jbuilder b/app/views/api/v1/security_prices/create.json.jbuilder
new file mode 100644
index 0000000000..153133f141
--- /dev/null
+++ b/app/views/api/v1/security_prices/create.json.jbuilder
@@ -0,0 +1,8 @@
+# frozen_string_literal: true
+
+json.security_id @security.id
+json.currency @result.currency
+json.created @result.created
+json.updated @result.updated
+json.start_date @result.start_date.iso8601
+json.end_date @result.end_date.iso8601
diff --git a/config/routes.rb b/config/routes.rb
index c218acf702..388a653689 100644
--- a/config/routes.rb
+++ b/config/routes.rb
@@ -831,7 +831,7 @@ Rails.application.routes.draw do
resources :rules, only: [ :index, :show ]
resources :rule_runs, only: [ :index, :show ]
resources :securities, only: [ :index, :show ]
- resources :security_prices, only: [ :index, :show ]
+ resources :security_prices, only: [ :index, :show, :create ]
resources :tags, only: [ :index, :show, :create, :update, :destroy ]
resources :transactions, only: [ :index, :show, :create, :update, :destroy ] do
diff --git a/docs/api/openapi.yaml b/docs/api/openapi.yaml
index 39ebc23fec..3382d7f5e8 100644
--- a/docs/api/openapi.yaml
+++ b/docs/api/openapi.yaml
@@ -3350,6 +3350,93 @@ components:
"$ref": "#/components/schemas/SecurityPrice"
pagination:
"$ref": "#/components/schemas/Pagination"
+ SecurityPriceImportRequest:
+ type: object
+ required:
+ - security_id
+ - prices
+ properties:
+ security_id:
+ type: string
+ format: uuid
+ description: An offline security no provider has ever matched (no offline_reason
+ or price_provider), traded in an account the caller can write to, or held
+ in a linked one
+ prices:
+ type: array
+ minItems: 1
+ maxItems: 1000
+ description: Daily closes, all in one currency. A date already stored is
+ replaced.
+ items:
+ type: object
+ required:
+ - date
+ - price
+ - currency
+ properties:
+ date:
+ type: string
+ format: date
+ description: Not after today in the family time zone
+ price:
+ type: string
+ description: Positive decimal with at most 4 decimal places
+ example: '12.3400'
+ currency:
+ type: string
+ description: ISO 4217 code; must match the security's existing prices,
+ or the caller's trades in it
+ SecurityPriceImportResult:
+ type: object
+ required:
+ - security_id
+ - currency
+ - created
+ - updated
+ - start_date
+ - end_date
+ properties:
+ security_id:
+ type: string
+ format: uuid
+ currency:
+ type: string
+ created:
+ type: integer
+ updated:
+ type: integer
+ start_date:
+ type: string
+ format: date
+ end_date:
+ type: string
+ format: date
+ SecurityPriceImportError:
+ type: object
+ required:
+ - error
+ - errors
+ properties:
+ error:
+ type: string
+ message:
+ type: string
+ errors:
+ type: array
+ items:
+ type: object
+ required:
+ - index
+ - message
+ properties:
+ index:
+ type: integer
+ nullable: true
+ description: Position of the offending row in prices, or null for
+ the request as a whole
+ message:
+ type: string
Money:
type: object
required:
@@ -9412,6 +9499,51 @@ paths:
application/json:
schema:
"$ref": "#/components/schemas/ErrorResponse"
+ post:
+ summary: Import closing prices for a security no provider tracks
+ description: Self-hosted instances only. Stores daily closes for an offline
+ security no provider has ever matched (no offline_reason, no price_provider)
+ that is traded in an account the caller can write to, or held in a linked
+ one. All rows are validated first and stored together, or none are. A date
+ already stored is replaced. Security prices are shared, so the closes also
+ value any other family holding the same security. The caller's affected accounts
+ are synced afterwards. Requires the read_write scope.
+ tags:
+ - Security Prices
+ security:
+ - apiKeyAuth: []
+ parameters: []
+ responses:
+ '200':
+ description: closes imported
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/SecurityPriceImportResult"
+ '403':
+ description: insufficient scope, a guest, or a managed instance
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '404':
+ description: security not found among the caller's writable accounts
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/ErrorResponse"
+ '422':
+ description: online security or invalid rows; nothing was stored
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/SecurityPriceImportError"
+ requestBody:
+ content:
+ application/json:
+ schema:
+ "$ref": "#/components/schemas/SecurityPriceImportRequest"
+ required: true
"/api/v1/security_prices/{id}":
parameters:
- name: id
diff --git a/spec/requests/api/v1/security_prices_spec.rb b/spec/requests/api/v1/security_prices_spec.rb
index 335cf1317b..3325c6db7b 100644
--- a/spec/requests/api/v1/security_prices_spec.rb
+++ b/spec/requests/api/v1/security_prices_spec.rb
@@ -50,6 +50,7 @@ RSpec.describe 'API V1 Security Prices', type: :request do
let(:account) do
Account.create!(
family: family,
+ owner: user,
name: 'Investment Account',
balance: 50_000,
currency: 'USD',
@@ -142,6 +143,68 @@ RSpec.describe 'API V1 Security Prices', type: :request do
run_test!
end
end
+
+ post 'Import closing prices for a security no provider tracks' do
+ description <<~DESC.squish
+ Self-hosted instances only. Stores daily closes for an offline security no provider has
+ ever matched (no offline_reason, no price_provider) that is traded in an account the caller can write to, or held in a linked one. All rows
+ are validated first and stored together, or none are. A date already stored is replaced.
+ Security prices are shared, so the closes also value any other family holding the same
+ security. The caller's affected accounts are synced afterwards. Requires the read_write scope.
+ DESC
+ tags 'Security Prices'
+ security [ { apiKeyAuth: [] } ]
+ consumes 'application/json'
+ produces 'application/json'
+ parameter name: :body, in: :body, required: true, schema: { '$ref' => '#/components/schemas/SecurityPriceImportRequest' }
+
+ let(:offline_security) do
+ Security.create!(ticker: 'MYFUND', name: 'Private fund', offline: true).tap do |offline|
+ account.entries.create!(
+ date: Date.current, name: 'Buy', amount: 120, currency: 'USD',
+ entryable: Trade.new(security: offline, qty: 10, price: 12, currency: 'USD')
+ )
+ end
+ end
+ let(:body) do
+ { security_id: offline_security.id, prices: [ { date: Date.current.iso8601, price: '12.3400', currency: 'USD' } ] }
+ end
+
+ before do
+ allow(Rails.application.config).to receive(:app_mode).and_return('self_hosted'.inquiry)
+ allow_any_instance_of(ApplicationController).to receive(:redis_connected?).and_return(true)
+ end
+
+ response '200', 'closes imported' do
+ schema '$ref' => '#/components/schemas/SecurityPriceImportResult'
+
+ run_test!
+ end
+
+ response '403', 'insufficient scope, a guest, or a managed instance' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ before { allow(Rails.application.config).to receive(:app_mode).and_return('managed'.inquiry) }
+
+ run_test!
+ end
+
+ response '404', 'security not found among the caller\'s writable accounts' do
+ schema '$ref' => '#/components/schemas/ErrorResponse'
+
+ let(:body) { { security_id: SecureRandom.uuid, prices: [ { date: Date.current.iso8601, price: '12', currency: 'USD' } ] } }
+
+ run_test!
+ end
+
+ response '422', 'online security or invalid rows; nothing was stored' do
+ schema '$ref' => '#/components/schemas/SecurityPriceImportError'
+
+ let(:body) { { security_id: offline_security.id, prices: [ { date: Date.current.iso8601, price: '-1', currency: 'USD' } ] } }
+
+ run_test!
+ end
+ end
end
path '/api/v1/security_prices/{id}' do
diff --git a/spec/swagger_helper.rb b/spec/swagger_helper.rb
index 41d3618659..7699f61a91 100644
--- a/spec/swagger_helper.rb
+++ b/spec/swagger_helper.rb
@@ -1823,6 +1823,59 @@ RSpec.configure do |config|
pagination: { '$ref' => '#/components/schemas/Pagination' }
}
},
+ SecurityPriceImportRequest: {
+ type: :object,
+ required: %w[security_id prices],
+ properties: {
+ security_id: { type: :string, format: :uuid, description: 'An offline security no provider has ever matched (no offline_reason or price_provider), traded in an account the caller can write to, or held in a linked one' },
+ prices: {
+ type: :array,
+ minItems: 1,
+ maxItems: 1000,
+ description: 'Daily closes, all in one currency. A date already stored is replaced.',
+ items: {
+ type: :object,
+ required: %w[date price currency],
+ properties: {
+ date: { type: :string, format: :date, description: 'Not after today in the family time zone' },
+ price: { type: :string, description: 'Positive decimal with at most 4 decimal places', example: '12.3400' },
+ currency: { type: :string, description: "ISO 4217 code; must match the security's existing prices, or the caller's trades in it" }
+ }
+ }
+ }
+ }
+ },
+ SecurityPriceImportResult: {
+ type: :object,
+ required: %w[security_id currency created updated start_date end_date],
+ properties: {
+ security_id: { type: :string, format: :uuid },
+ currency: { type: :string },
+ created: { type: :integer },
+ updated: { type: :integer },
+ start_date: { type: :string, format: :date },
+ end_date: { type: :string, format: :date }
+ }
+ },
+ SecurityPriceImportError: {
+ type: :object,
+ required: %w[error errors],
+ properties: {
+ error: { type: :string },
+ message: { type: :string },
+ errors: {
+ type: :array,
+ items: {
+ type: :object,
+ required: %w[index message],
+ properties: {
+ index: { type: :integer, nullable: true, description: 'Position of the offending row in prices, or null for the request as a whole' },
+ message: { type: :string }
+ }
+ }
+ }
+ }
+ },
Money: {
type: :object,
required: %w[amount currency formatted],
diff --git a/test/controllers/api/v1/security_prices_controller_test.rb b/test/controllers/api/v1/security_prices_controller_test.rb
index 156b97d32a..4039766d9b 100644
--- a/test/controllers/api/v1/security_prices_controller_test.rb
+++ b/test/controllers/api/v1/security_prices_controller_test.rb
@@ -188,9 +188,264 @@ class Api::V1::SecurityPricesControllerTest < ActionDispatch::IntegrationTest
api_key_without_read&.destroy
end
+ test "imports closes for an offline security the caller holds and syncs its accounts" do
+ security = offline_security_held_by(@account)
+ Account.any_instance.expects(:sync_later).once
+
+ with_self_hosting do
+ post api_v1_security_prices_url,
+ params: { security_id: security.id, prices: [ close(2.days.ago, "21.5"), close(1.day.ago, "22") ] },
+ headers: api_headers(write_key), as: :json
+ end
+
+ assert_response :success
+ body = JSON.parse(response.body)
+ assert_equal({ "security_id" => security.id, "currency" => "AUD", "created" => 2, "updated" => 0,
+ "start_date" => 2.days.ago.to_date.iso8601, "end_date" => 1.day.ago.to_date.iso8601 }, body)
+ assert_equal [ BigDecimal("21.5"), BigDecimal("22") ], security.prices.order(:date).pluck(:price)
+ end
+
+ test "resubmitting a date updates it" do
+ security = offline_security_held_by(@account)
+ security.prices.create!(date: 1.day.ago.to_date, price: 20, currency: "AUD")
+ Account.any_instance.stubs(:sync_later)
+
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: security.id, prices: [ close(1.day.ago, "24") ] },
+ headers: api_headers(write_key), as: :json
+ end
+
+ assert_response :success
+ assert_equal [ 0, 1 ], JSON.parse(response.body).values_at("created", "updated")
+ assert_equal BigDecimal("24"), security.prices.sole.price
+ end
+
+ test "a read-only key cannot import prices" do
+ security = offline_security_held_by(@account)
+
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: security.id, prices: [ close(1.day.ago, "20") ] },
+ headers: api_headers(@api_key), as: :json
+ end
+
+ assert_response :forbidden
+ assert_equal "insufficient_scope", JSON.parse(response.body)["error"]
+ assert_empty security.prices
+ end
+
+ test "managed mode refuses imports because prices are shared across families" do
+ security = offline_security_held_by(@account)
+
+ post api_v1_security_prices_url, params: { security_id: security.id, prices: [ close(1.day.ago, "20") ] },
+ headers: api_headers(write_key), as: :json
+
+ assert_response :forbidden
+ assert_equal "self_hosted_only", JSON.parse(response.body)["error"]
+ assert_empty security.prices
+ end
+
+ test "a security the caller cannot write to is not found, however it is named" do
+ other_offline = Security.create!(ticker: "OTHER#{SecureRandom.hex(3).upcase}", offline: true)
+ other_account = families(:empty).accounts.create!(name: "Theirs", accountable: Investment.new, balance: 1, currency: "AUD")
+ other_account.entries.create!(
+ date: 3.days.ago.to_date, name: "Buy", amount: 1, currency: "AUD",
+ entryable: Trade.new(security: other_offline, qty: 1, price: 1, currency: "AUD")
+ )
+ shared_read_only = offline_security_held_by(@account)
+ @account.update_columns(owner_id: users(:family_member).id)
+ AccountShare.create!(account: @account, user: @user, permission: "read_only")
+ # The caller does hold an offline security, so a lookup that lost the
+ # requested id would find this one instead of returning 404.
+ own_account = @family.accounts.create!(name: "Mine", owner: @user, accountable: Investment.new, balance: 1, currency: "AUD")
+ own_security = offline_security_held_by(own_account)
+
+ [ other_offline.id, shared_read_only.id, SecureRandom.uuid, "not-a-uuid" ].each do |security_id|
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: security_id, prices: [ close(1.day.ago, "20") ] },
+ headers: api_headers(write_key), as: :json
+ end
+
+ assert_response :not_found, "expected 404 for #{security_id}"
+ assert_equal "record_not_found", JSON.parse(response.body)["error"]
+ end
+ assert_empty other_offline.prices
+ assert_empty shared_read_only.prices
+ assert_empty own_security.prices
+ end
+
+ test "an online security is refused" do
+ Account.any_instance.expects(:sync_later).never
+ before = @security.prices.order(:date, :currency).pluck(:date, :currency, :price)
+
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: @security.id, prices: [ close(1.day.ago, "20", currency: "USD") ] },
+ headers: api_headers(write_key), as: :json
+ end
+
+ assert_response :unprocessable_entity
+ body = JSON.parse(response.body)
+ assert_equal "validation_failed", body["error"]
+ assert_equal [ { "index" => nil, "message" => "prices can only be imported for a security no provider tracks" } ], body["errors"]
+ assert_equal before, @security.prices.order(:date, :currency).pluck(:date, :currency, :price)
+ end
+
+ test "a bad row rejects the whole batch with its index" do
+ security = offline_security_held_by(@account)
+ Account.any_instance.expects(:sync_later).never
+
+ with_self_hosting do
+ post api_v1_security_prices_url,
+ params: { security_id: security.id, prices: [ close(2.days.ago, "21"), close(Date.current + 1, "22") ] },
+ headers: api_headers(write_key), as: :json
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal [ { "index" => 1, "message" => "date must not be in the future" } ], JSON.parse(response.body)["errors"]
+ assert_empty security.prices
+ end
+
+ # At 12:00 UTC on 7 Nov it is already 8 Nov in Auckland (UTC+13), so the
+ # family's today is importable and its tomorrow is not. Judged in UTC, the
+ # first row would be rejected as a future date.
+ test "the future-date check uses the family's time zone" do
+ @family.update!(timezone: "Pacific/Auckland")
+ security = offline_security_held_by(@account)
+ Account.any_instance.stubs(:sync_later)
+
+ travel_to Time.utc(2026, 11, 7, 12) do
+ with_self_hosting do
+ post api_v1_security_prices_url,
+ params: { security_id: security.id, prices: [ close(Date.new(2026, 11, 8), "21") ] },
+ headers: api_headers(write_key), as: :json
+ assert_response :ok
+
+ post api_v1_security_prices_url,
+ params: { security_id: security.id, prices: [ close(Date.new(2026, 11, 9), "22") ] },
+ headers: api_headers(write_key), as: :json
+ assert_response :unprocessable_entity
+ assert_equal [ { "index" => 0, "message" => "date must not be in the future" } ], JSON.parse(response.body)["errors"]
+ end
+ end
+
+ assert_equal [ [ Date.new(2026, 11, 8), 21 ] ], security.prices.pluck(:date, :price)
+ end
+
+ # An unlinked account's sync rebuilds its holdings from trades and deletes
+ # the rest, so accepting this import would queue a sync that removes the
+ # position being priced.
+ test "an unlinked account's holding with no trade behind it is not found" do
+ security = offline_security_held_without_trade(@account)
+ Account.any_instance.expects(:sync_later).never
+
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: security.id, prices: [ close(1.day.ago, "20") ] },
+ headers: api_headers(write_key), as: :json
+ end
+
+ assert_response :not_found
+ assert_empty security.prices
+ end
+
+ # A linked account's holdings come from its provider, and its (reverse) sync
+ # keeps them, so a holding there is enough.
+ test "a linked account's holding is enough, with no trade" do
+ linked = @family.accounts.create!(name: "Linked", owner: @user, accountable: Investment.new, balance: 200, currency: "AUD")
+ AccountProvider.create!(account: linked, provider: lunchflow_accounts(:investment_account))
+ security = offline_security_held_without_trade(linked)
+ Account.any_instance.expects(:sync_later).once
+
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: security.id, prices: [ close(1.day.ago, "21") ] },
+ headers: api_headers(write_key), as: :json
+ end
+
+ assert_response :ok
+ assert_equal [ BigDecimal("21") ], security.prices.pluck(:price)
+ end
+
+ # The sync the import queues, run for real: the trade-backed holding is
+ # rebuilt at the imported close rather than purged.
+ test "the queued sync revalues the position at the imported close" do
+ security = offline_security_held_by(@account)
+
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: security.id, prices: [ close(1.day.ago, "35") ] },
+ headers: api_headers(write_key), as: :json
+ end
+ assert_response :ok
+
+ Holding::Materializer.new(@account, strategy: :forward).materialize_holdings
+ holding = @account.holdings.find_by(security: security, date: 1.day.ago.to_date)
+
+ assert_not_nil holding, "the sync removed the priced position"
+ assert_equal BigDecimal("35"), holding.price
+ assert_equal BigDecimal("350"), holding.amount
+ end
+
+ # Security prices are shared across families, so a guest's read_write key
+ # must not write them, even through an account the guest could write to.
+ test "a guest cannot import prices" do
+ guest = users(:intro_user)
+ account = guest.family.accounts.create!(name: "Guest's", owner: guest, accountable: Investment.new, balance: 200, currency: "AUD")
+ security = offline_security_held_by(account)
+ key = ApiKey.create!(user: guest, name: "Guest Key", scopes: [ "read_write" ], source: "mobile", display_key: "guest_#{SecureRandom.hex(8)}")
+
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: security.id, prices: [ close(1.day.ago, "20") ] },
+ headers: api_headers(key), as: :json
+ end
+
+ assert_response :forbidden
+ assert_empty security.prices
+ end
+
+ test "prices must be a list" do
+ security = offline_security_held_by(@account)
+
+ with_self_hosting do
+ post api_v1_security_prices_url, params: { security_id: security.id, prices: "21" },
+ headers: api_headers(write_key), as: :json
+ end
+
+ assert_response :unprocessable_entity
+ assert_equal [ { "index" => nil, "message" => "prices must be a list" } ], JSON.parse(response.body)["errors"]
+ end
+
private
def api_headers(api_key)
{ "X-Api-Key" => api_key.plain_key }
end
+
+ def write_key
+ @write_key ||= ApiKey.create!(
+ user: @user,
+ name: "Test Write Key",
+ scopes: [ "read_write" ],
+ source: "mobile",
+ display_key: "test_write_#{SecureRandom.hex(8)}"
+ )
+ end
+
+ # A manual-ticker security as it arises: bought by a trade, which the
+ # account's holdings are built from.
+ def offline_security_held_by(account)
+ Security.create!(ticker: "MYFUND#{SecureRandom.hex(3).upcase}", name: "My Fund", offline: true).tap do |security|
+ account.entries.create!(
+ date: 3.days.ago.to_date, name: "Buy", amount: 200, currency: "AUD",
+ entryable: Trade.new(security: security, qty: 10, price: 20, currency: "AUD")
+ )
+ account.holdings.create!(security: security, date: 3.days.ago.to_date, qty: 10, price: 20, amount: 200, currency: "AUD")
+ end
+ end
+
+ def offline_security_held_without_trade(account)
+ Security.create!(ticker: "HELD#{SecureRandom.hex(3).upcase}", name: "Held Fund", offline: true).tap do |security|
+ account.holdings.create!(security: security, date: 3.days.ago.to_date, qty: 10, price: 20, amount: 200, currency: "AUD")
+ end
+ end
+
+ def close(date, price, currency: "AUD")
+ { date: date.to_date.iso8601, price: price, currency: currency }
+ end
end
diff --git a/test/models/security/manual_price_import_test.rb b/test/models/security/manual_price_import_test.rb
new file mode 100644
index 0000000000..c2b43dffbe
--- /dev/null
+++ b/test/models/security/manual_price_import_test.rb
@@ -0,0 +1,303 @@
+require "test_helper"
+require "ostruct"
+
+class Security::ManualPriceImportTest < ActiveSupport::TestCase
+ include ProviderTestHelper
+
+ setup do
+ @account = accounts(:investment)
+ @security = Security.create!(ticker: "MYFUND#{SecureRandom.hex(3).upcase}", name: "My Fund", offline: true)
+ @account.holdings.create!(security: @security, date: 3.days.ago.to_date, qty: 10, price: 20, amount: 200, currency: "AUD")
+ @accounts = Account.where(id: @account.id)
+ end
+
+ test "creates closes in the security's currency and reports what it wrote" do
+ result = import([ row(2.days.ago, "21.5"), row(1.day.ago, "22.25") ])
+
+ assert_equal "AUD", result.currency
+ assert_equal 2, result.created
+ assert_equal 0, result.updated
+ assert_equal 2.days.ago.to_date, result.start_date
+ assert_equal 1.day.ago.to_date, result.end_date
+ assert_equal [ BigDecimal("21.5"), BigDecimal("22.25") ], @security.prices.order(:date).pluck(:price)
+ end
+
+ test "a resubmitted date replaces the earlier close and clears provisional" do
+ existing = @security.prices.create!(date: 1.day.ago.to_date, price: 20, currency: "AUD", provisional: true)
+
+ result = import([ row(1.day.ago, "23") ])
+
+ assert_equal [ 0, 1 ], [ result.created, result.updated ]
+ existing.reload
+ assert_equal BigDecimal("23"), existing.price
+ assert_not existing.provisional
+ end
+
+ test "one bad row leaves every row in the batch unwritten" do
+ @security.prices.create!(date: 5.days.ago.to_date, price: 19, currency: "AUD")
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) do
+ import([ row(2.days.ago, "21"), row(5.days.ago, "18"), row(1.day.ago, "-1") ])
+ end
+
+ assert_equal [ { index: 2, message: "price must be greater than 0" } ], error.errors
+ assert_equal [ BigDecimal("19") ], @security.prices.pluck(:price)
+ end
+
+ test "a currency mismatch is reported beside a row that did not parse" do
+ before = Security::Price.count
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) do
+ import([ row(2.days.ago, "0"), row(1.day.ago, "20", currency: "NZD") ])
+ end
+
+ assert_equal [
+ { index: 0, message: "price must be greater than 0" },
+ { index: 1, message: "currency must be AUD, the currency of your holdings in this security" }
+ ], error.errors
+ assert_equal before, Security::Price.count
+ end
+
+ test "rejects each malformed row by its index" do
+ error = assert_raises(Security::ManualPriceImport::Invalid) do
+ import([
+ row(1.day.ago, "0"),
+ row(1.day.ago.to_date, "1.23456"),
+ row(Date.current + 1, "5"),
+ { "date" => "06/11/2026", "price" => "5", "currency" => "AUD" },
+ row(2.days.ago, "abc"),
+ row(3.days.ago, "5", currency: "ZZZ"),
+ "not an object",
+ row(4.days.ago, "5"),
+ row(4.days.ago, "6")
+ ])
+ end
+
+ assert_equal [
+ { index: 0, message: "price must be greater than 0" },
+ { index: 1, message: "price must have at most 4 decimal places" },
+ { index: 2, message: "date must not be in the future" },
+ { index: 3, message: "date must be an ISO 8601 date" },
+ { index: 4, message: "price must be a number" },
+ { index: 5, message: "currency must be an ISO 4217 code" },
+ { index: 6, message: "row must be an object with date, price and currency" },
+ { index: 8, message: "date appears more than once in this batch" }
+ ], error.errors
+ end
+
+ test "a currency other than the security's own is rejected" do
+ @security.prices.create!(date: 5.days.ago.to_date, price: 19, currency: "AUD")
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) { import([ row(1.day.ago, "20", currency: "USD") ]) }
+
+ assert_equal [ { index: 0, message: "currency must be AUD, the currency of this security's prices" } ], error.errors
+ end
+
+ test "with no prices yet, the currency comes from the caller's trades before holdings" do
+ @account.entries.create!(
+ date: 3.days.ago.to_date, name: "Buy", amount: 100, currency: "NZD",
+ entryable: Trade.new(security: @security, qty: 5, price: 20, currency: "NZD")
+ )
+
+ assert_equal "NZD", import([ row(1.day.ago, "20", currency: "NZD") ]).currency
+ end
+
+ test "trades in more than one currency leave the currency undecidable" do
+ %w[NZD USD].each do |currency|
+ @account.entries.create!(
+ date: 3.days.ago.to_date, name: "Buy", amount: 100, currency: currency,
+ entryable: Trade.new(security: @security, qty: 5, price: 20, currency: currency)
+ )
+ end
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) { import([ row(1.day.ago, "20", currency: "NZD") ]) }
+
+ assert_equal [ { index: nil, message: "this security's trades are in more than one currency (NZD, USD); none can be chosen for its prices" } ], error.errors
+ end
+
+ test "a security priced in several currencies accepts only those" do
+ @security.prices.create!(date: 5.days.ago.to_date, price: 19, currency: "AUD")
+ @security.prices.create!(date: 5.days.ago.to_date, price: 12, currency: "USD")
+
+ assert_equal "USD", import([ row(1.day.ago, "13", currency: "USD") ]).currency
+ error = assert_raises(Security::ManualPriceImport::Invalid) { import([ row(1.day.ago, "13", currency: "EUR") ]) }
+ assert_equal "currency must be AUD or USD, the currencies of this security's prices", error.errors.first[:message]
+ end
+
+ test "one batch carries one currency" do
+ @security.prices.create!(date: 5.days.ago.to_date, price: 19, currency: "AUD")
+ @security.prices.create!(date: 5.days.ago.to_date, price: 12, currency: "USD")
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) do
+ import([ row(2.days.ago, "13", currency: "USD"), row(1.day.ago, "20", currency: "AUD") ])
+ end
+
+ assert_equal [ { index: 1, message: "every row in one request must use the same currency" } ], error.errors
+ end
+
+ test "an offline security a provider tracks is refused" do
+ [
+ { offline_reason: "health_check_failed" },
+ { offline_reason: "provider_disabled" },
+ { offline_reason: "resolution_pending" },
+ { price_provider: Security.valid_price_providers.first }
+ ].each do |attrs|
+ @security.update_columns({ offline_reason: nil, price_provider: nil }.merge(attrs))
+
+ error = assert_raises(Security::ManualPriceImport::Invalid, attrs.inspect) { import([ row(1.day.ago, "20") ]) }
+
+ assert_equal [ { index: nil, message: "prices can only be imported for a security no provider tracks" } ], error.errors
+ end
+ assert_empty @security.prices
+ end
+
+ test "an online security is refused" do
+ @security.update!(offline: false)
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) { import([ row(1.day.ago, "20") ]) }
+
+ assert_equal [ { index: nil, message: "prices can only be imported for a security no provider tracks" } ], error.errors
+ assert_empty @security.prices
+ end
+
+ test "a cash position's security is refused although it is offline" do
+ cash = Security.cash_for(@account)
+ assert cash.offline?
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) do
+ cash.import_manual_prices!([ row(1.day.ago, "1000", currency: "USD") ], accounts: @accounts)
+ end
+
+ assert_equal [ { index: nil, message: "prices cannot be imported for a cash position" } ], error.errors
+ assert_empty cash.prices
+ end
+
+ test "holdings in more than one currency leave the currency undecidable" do
+ other = @account.family.accounts.create!(name: "USD broker", owner: @account.owner, accountable: Investment.new, balance: 1, currency: "USD")
+ other.holdings.create!(security: @security, date: 3.days.ago.to_date, qty: 1, price: 20, amount: 20, currency: "USD")
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) do
+ @security.import_manual_prices!([ row(1.day.ago, "20") ], accounts: Account.where(id: [ @account.id, other.id ]))
+ end
+
+ assert_equal [ { index: nil, message: "this security's holdings are in more than one currency (AUD, USD); none can be chosen for its prices" } ], error.errors
+ end
+
+ test "a trade with no currency does not count as a second currency" do
+ entries = 2.times.map do |i|
+ @account.entries.create!(
+ date: (3 + i).days.ago.to_date, name: "Buy", amount: 100, currency: "AUD",
+ entryable: Trade.new(security: @security, qty: 5, price: 20, currency: "AUD")
+ )
+ end
+ entries.last.entryable.update_column(:currency, nil)
+
+ assert_equal "AUD", import([ row(1.day.ago, "20") ]).currency
+ end
+
+ # holdings.currency is NOT NULL but trades.currency is not, so only a
+ # trade-backed position with no holding yet can leave nothing to choose.
+ test "a position with no recorded currency is refused with a reason" do
+ @account.holdings.where(security: @security).delete_all
+ entry = @account.entries.create!(
+ date: 3.days.ago.to_date, name: "Buy", amount: 100, currency: "AUD",
+ entryable: Trade.new(security: @security, qty: 5, price: 20, currency: "AUD")
+ )
+ entry.entryable.update_column(:currency, nil)
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) { import([ row(1.day.ago, "20") ]) }
+
+ assert_equal [ { index: nil, message: "no trade or holding of this security records a currency, so none can be chosen for its prices" } ], error.errors
+ assert_empty @security.prices
+ end
+
+ # A resolver assigning a provider while this import waits for the lock: the
+ # eligibility check has to see it, or the closes outlast the provider's own.
+ test "eligibility is checked under the security's lock" do
+ @security.singleton_class.prepend(Module.new do
+ def with_lock(*)
+ Security.where(id: id).update_all(price_provider: "tiingo")
+ super
+ end
+ end)
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) { import([ row(1.day.ago, "20") ]) }
+
+ assert_equal [ { index: nil, message: "prices can only be imported for a security no provider tracks" } ], error.errors
+ assert_empty @security.prices
+ end
+
+ test "only calendar dates are accepted" do
+ error = assert_raises(Security::ManualPriceImport::Invalid) do
+ import([ row(1.day.ago, "5").merge("date" => "2026-001"), row(1.day.ago, "5").merge("date" => "20260101"),
+ row(1.day.ago, "5").merge("date" => "2026-W01-1") ])
+ end
+
+ assert_equal [ 0, 1, 2 ], error.errors.map { |e| e[:index] }
+ assert error.errors.all? { |e| e[:message] == "date must be an ISO 8601 date" }
+ end
+
+ test "an empty batch and one over the limit are refused" do
+ assert_raises(Security::ManualPriceImport::Invalid) { import([]) }
+
+ too_many = (1..(Security::ManualPriceImport::MAX_ROWS + 1)).map { |i| row(Date.current - i, "1") }
+ error = assert_raises(Security::ManualPriceImport::Invalid) { import(too_many) }
+ assert_equal "a request can carry at most #{Security::ManualPriceImport::MAX_ROWS} prices", error.errors.first[:message]
+ end
+
+ test "an imported close is what the holding is valued at, not the trade price" do
+ date = 1.day.ago.to_date
+ @account.entries.create!(
+ date: date, name: "Buy", amount: 200, currency: "USD",
+ entryable: Trade.new(security: @security, qty: 10, price: 20, currency: "USD")
+ )
+ Holding.where(security: @security).delete_all
+
+ before = Holding::PortfolioCache.new(@account).get_price(@security.id, date)
+ import([ row(date, "31", currency: "USD") ])
+ after = Holding::PortfolioCache.new(@account).get_price(@security.id, date)
+
+ assert_equal BigDecimal("20"), before.price
+ assert_equal BigDecimal("31"), after.price
+ end
+
+ test "a provider import that runs later keeps the imported close" do
+ date = 1.day.ago.to_date
+ import([ row(date, "31") ])
+ provider = mock
+ provider.stubs(:fetch_security_prices).returns(provider_success_response([
+ OpenStruct.new(security: @security, date: date, price: 99, currency: "AUD")
+ ]))
+
+ Security::Price::Importer.new(security: @security, security_provider: provider, start_date: date, end_date: date).import_provider_prices
+
+ assert_equal BigDecimal("31"), @security.prices.find_by!(date: date, currency: "AUD").price
+ end
+
+ # Another first import that commits an NZD close while this one waits for
+ # the lock. The currency check has to see it, so it must run under the lock:
+ # checked before, AUD would pass against an empty history and both
+ # currencies would be stored.
+ test "the currency check runs under the security's lock" do
+ @security.singleton_class.prepend(Module.new do
+ def with_lock(*)
+ Security::Price.create!(security: self, date: 5.days.ago.to_date, price: 9, currency: "NZD")
+ super
+ end
+ end)
+
+ error = assert_raises(Security::ManualPriceImport::Invalid) { import([ row(1.day.ago, "20") ]) }
+
+ assert_equal [ { index: 0, message: "currency must be NZD, the currency of this security's prices" } ], error.errors
+ assert_equal %w[NZD], @security.prices.distinct.pluck(:currency)
+ end
+
+ private
+ def import(rows)
+ @security.import_manual_prices!(rows, accounts: @accounts)
+ end
+
+ def row(date, price, currency: "AUD")
+ { "date" => date.to_date.iso8601, "price" => price, "currency" => currency }
+ end
+end