Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Show the ISIN in security search and rank exact ISIN matches first (#5152)

arnaurodondevc8193c8e44ac
diff --git a/app/models/provider/eodhd.rb b/app/models/provider/eodhd.rb
index 4a77fa6b3b..75e65079ce 100644
--- a/app/models/provider/eodhd.rb
+++ b/app/models/provider/eodhd.rb
@@ -175,7 +175,8 @@ class Provider::Eodhd < Provider
logo_url: nil,
exchange_operating_mic: mic,
country_code: country,
- currency: currency
+ currency: currency,
+ isin: security.dig("ISIN").presence&.to_s&.strip&.upcase
)
end
end
diff --git a/app/models/provider/security_concept.rb b/app/models/provider/security_concept.rb
index 37fbd3efe2..65a0ac2c8a 100644
--- a/app/models/provider/security_concept.rb
+++ b/app/models/provider/security_concept.rb
@@ -4,8 +4,11 @@ module Provider::SecurityConcept
# NOTE: This `Security` is a lightweight Data value object used for search results.
# Inside provider classes that `include SecurityConcept`, unqualified `Security`
# resolves to this Data class — NOT to `::Security` (the ActiveRecord model).
- Security = Data.define(:symbol, :name, :logo_url, :exchange_operating_mic, :country_code, :currency) do
- def initialize(symbol:, name:, logo_url:, exchange_operating_mic:, country_code:, currency: nil)
+ #
+ # `isin` is optional: providers whose search results carry an ISIN fill it so the
+ # search dropdown can show it and rank exact ISIN matches first. Others leave it nil.
+ Security = Data.define(:symbol, :name, :logo_url, :exchange_operating_mic, :country_code, :currency, :isin) do
+ def initialize(symbol:, name:, logo_url:, exchange_operating_mic:, country_code:, currency: nil, isin: nil)
super
end
end
diff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rb
index d51c88daa0..5b4e6b9cce 100644
--- a/app/models/provider/yahoo_finance.rb
+++ b/app/models/provider/yahoo_finance.rb
@@ -195,7 +195,10 @@ class Provider::YahooFinance < Provider
def search_securities(symbol, country_code: nil, exchange_operating_mic: nil)
with_provider_response do
- cache_key = "search_#{symbol}_#{country_code}_#{exchange_operating_mic}"
+ # The cached values are Security Data objects. Rails treats an entry that no
+ # longer fits the class (TypeError: struct size differs) as an error, not a
+ # miss, so bump the version here whenever Security's members change.
+ cache_key = "search_v2_#{symbol}_#{country_code}_#{exchange_operating_mic}"
if cached_result = get_cached_result(cache_key)
cached_result
else
diff --git a/app/models/security.rb b/app/models/security.rb
index d82e34d098..5b6d5dd924 100644
--- a/app/models/security.rb
+++ b/app/models/security.rb
@@ -2,7 +2,7 @@ class Security < ApplicationRecord
include Provided, PlanRestrictionTracker
# Transient attribute for search results -- not persisted
- attr_accessor :search_currency
+ attr_accessor :search_currency, :search_isin
# ISO 10383 MIC codes mapped to user-friendly exchange names
# Source: https://www.iso20022.org/market-identifier-codes
@@ -281,7 +281,8 @@ class Security < ApplicationRecord
exchange_operating_mic: exchange_operating_mic,
country_code: country_code,
price_provider: price_provider,
- currency: search_currency
+ currency: search_currency,
+ isin: search_isin
)
end
diff --git a/app/models/security/combobox_option.rb b/app/models/security/combobox_option.rb
index 18a491427b..832b434ad3 100644
--- a/app/models/security/combobox_option.rb
+++ b/app/models/security/combobox_option.rb
@@ -1,7 +1,7 @@
class Security::ComboboxOption
include ActiveModel::Model
- attr_accessor :symbol, :name, :logo_url, :exchange_operating_mic, :country_code, :price_provider, :currency
+ attr_accessor :symbol, :name, :logo_url, :exchange_operating_mic, :country_code, :price_provider, :currency, :isin
def id
"#{symbol}|#{exchange_operating_mic}|#{price_provider}"
diff --git a/app/models/security/provided.rb b/app/models/security/provided.rb
index efe273792d..7fae4ad528 100644
--- a/app/models/security/provided.rb
+++ b/app/models/security/provided.rb
@@ -100,6 +100,7 @@ module Security::Provided
exchange_operating_mic: ps[:exchange_operating_mic],
country_code: ps[:country_code],
search_currency: ps[:currency],
+ search_isin: ps[:isin],
price_provider: provider_key
)
all_results << security
@@ -131,7 +132,8 @@ module Security::Provided
response.data.map do |ps|
{ symbol: ps.symbol, name: ps.name, logo_url: ps.logo_url,
exchange_operating_mic: ps.exchange_operating_mic, country_code: ps.country_code,
- currency: ps.respond_to?(:currency) ? ps.currency : nil }
+ currency: ps.respond_to?(:currency) ? ps.currency : nil,
+ isin: ps.respond_to?(:isin) ? ps.isin : nil }
end
end
rescue => e
@@ -139,8 +141,25 @@ module Security::Provided
nil
end
+ ISIN_FORMAT = /\A[A-Z]{2}[A-Z0-9]{9}\d\z/
+
+ # True when the query is a well-formed ISIN: 2 letters, 9 alphanumerics and a
+ # check digit (letters expand to two digits, then the Luhn check applies).
+ def isin_query?(query)
+ return false unless query.match?(ISIN_FORMAT)
+
+ digits = query.chars.map { |c| c.match?(/\d/) ? c : (c.ord - 55).to_s }.join
+ sum = digits.reverse.chars.each_with_index.sum do |c, i|
+ n = c.to_i
+ n *= 2 if i.odd?
+ n > 9 ? n - 9 : n
+ end
+ (sum % 10).zero?
+ end
+
# Scores and sorts search results so the most relevant matches appear first.
# Scoring criteria (lower = better):
+ # -1: the query is a valid ISIN and the result carries that exact ISIN
# 0: exact ticker match
# 1: ticker starts with query
# 2: name contains query
@@ -149,10 +168,13 @@ module Security::Provided
def rank_search_results(results, symbol, country_code)
query = symbol.upcase
user_country = country_code&.upcase
+ isin_search = isin_query?(query)
results.sort_by do |s|
ticker_up = s.ticker.upcase
- relevance = if ticker_up == query
+ relevance = if isin_search && s.search_isin.present? && s.search_isin.upcase == query
+ -1
+ elsif ticker_up == query
0
elsif ticker_up.start_with?(query)
1
diff --git a/app/views/securities/_combobox_security.turbo_stream.erb b/app/views/securities/_combobox_security.turbo_stream.erb
index 79f8263e08..ffffb31dbb 100644
--- a/app/views/securities/_combobox_security.turbo_stream.erb
+++ b/app/views/securities/_combobox_security.turbo_stream.erb
@@ -9,6 +9,9 @@
</span>
<span class="text-xs text-secondary">
<%= t("securities.combobox.exchange_label", symbol: combobox_security.symbol, exchange: combobox_security.exchange_name) %>
+ <% if combobox_security.isin.present? %>
+ <span class="text-xs text-tertiary">&middot; <%= combobox_security.isin %></span>
+ <% end %>
<% if combobox_security.price_provider.present? %>
<span class="text-xs text-tertiary">&middot; <%= t("securities.providers.#{combobox_security.price_provider}", default: combobox_security.price_provider.humanize) %></span>
<% end %>
diff --git a/test/controllers/securities_controller_test.rb b/test/controllers/securities_controller_test.rb
new file mode 100644
index 0000000000..7b21e19b2e
--- /dev/null
+++ b/test/controllers/securities_controller_test.rb
@@ -0,0 +1,20 @@
+require "test_helper"
+
+class SecuritiesControllerTest < ActionDispatch::IntegrationTest
+ setup { sign_in users(:family_admin) }
+
+ test "index shows the ISIN of a search result when the provider returns one" do
+ with_isin = Security.new(ticker: "SGLD", name: "Invesco Physical Gold", exchange_operating_mic: "XLON",
+ country_code: "GB", price_provider: "eodhd")
+ with_isin.search_isin = "IE00B579F325"
+ without_isin = Security.new(ticker: "PHYM", name: "Another fund", exchange_operating_mic: "XLON",
+ country_code: "GB", price_provider: "yahoo_finance")
+ Security.stubs(:search_provider).returns([ with_isin, without_isin ])
+
+ get securities_url(q: "gold"), as: :turbo_stream
+
+ assert_response :success
+ assert_equal 1, response.body.scan("IE00B579F325").size
+ assert_includes response.body, "Another fund"
+ end
+end
diff --git a/test/models/provider/eodhd_test.rb b/test/models/provider/eodhd_test.rb
index 54d0f655b6..245930c82d 100644
--- a/test/models/provider/eodhd_test.rb
+++ b/test/models/provider/eodhd_test.rb
@@ -35,6 +35,28 @@ class Provider::EodhdTest < ActiveSupport::TestCase
assert_equal "EUR", security.currency
end
+ test "search keeps the ISIN EODHD returns and leaves it nil when absent" do
+ body = [
+ { "Code" => "SGLD", "Name" => "Invesco Physical Gold", "Exchange" => "LSE", "Country" => "UK",
+ "Currency" => "GBP", "ISIN" => "ie00b579f325" },
+ { "Code" => "XYZ", "Name" => "No isin", "Exchange" => "US", "Country" => "USA",
+ "Currency" => "USD", "ISIN" => "" },
+ { "Code" => "ABC", "Name" => "Missing key", "Exchange" => "US", "Country" => "USA", "Currency" => "USD" }
+ ].to_json
+
+ mock_response = mock
+ mock_response.stubs(:body).returns(body)
+ @provider.stubs(:enforce_daily_limit!)
+ @provider.stubs(:throttle_request)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(mock_response)
+
+ result = @provider.search_securities("IE00B579F325")
+
+ assert result.success?
+ assert_equal [ "IE00B579F325", nil, nil ], result.data.map(&:isin)
+ end
+
test "uses mapped MIC when exchange code is in mapping" do
mapped_exchange_body = [
{
diff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rb
index 9c6219ed57..2e23225614 100644
--- a/test/models/provider/yahoo_finance_test.rb
+++ b/test/models/provider/yahoo_finance_test.rb
@@ -509,6 +509,35 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
assert_equal [], response.data
end
+ test "search_securities ignores cached results written with the six-member Security layout" do
+ concept = Provider::SecurityConcept
+ current = concept::Security
+ legacy_members = current.members - [ :isin ]
+
+ # Write a cache entry the way the previous release did: with a Security
+ # that has no isin member, under the key that release used.
+ legacy = Data.define(*legacy_members)
+ concept.send(:remove_const, :Security)
+ concept.const_set(:Security, legacy)
+ begin
+ stale = [ legacy.new(symbol: "STALE", name: "Stale", logo_url: nil, exchange_operating_mic: "XNAS", country_code: "US", currency: nil) ]
+ @cache.write("yahoo_finance_search_ABC__", stale, expires_in: 5.minutes)
+ ensure
+ concept.send(:remove_const, :Security)
+ concept.const_set(:Security, current)
+ end
+
+ mock_response = mock
+ mock_response.stubs(:body).returns({ quotes: [ { symbol: "ABC", longname: "Abc Inc", exchange: "NMS", exchDisp: "NASDAQ" } ] }.to_json)
+ @provider.stubs(:client).returns(mock_client = mock)
+ mock_client.stubs(:get).returns(mock_response)
+
+ response = @provider.search_securities("ABC")
+
+ assert response.success?, "stale entry should not break the search: #{response.error&.message}"
+ assert_equal [ "ABC" ], response.data.map(&:symbol)
+ end
+
test "search_securities returns canonical Colombian identity for Yahoo BVC listings" do
mock_response = mock
mock_response.stubs(:body).returns({
diff --git a/test/models/security/provided_test.rb b/test/models/security/provided_test.rb
index cb74587541..13439bc041 100644
--- a/test/models/security/provided_test.rb
+++ b/test/models/security/provided_test.rb
@@ -387,4 +387,61 @@ class Security::ProvidedTest < ActiveSupport::TestCase
assert_equal "TSLA", ranked[0].ticker
assert_equal "US", ranked[0].country_code, "US Tesla should rank first for US user"
end
+
+ test "ranking: a valid ISIN query ranks results carrying that ISIN first" do
+ other = build_result(ticker: "SGLDX", name: "Other gold fund", country_code: "GB")
+ match = build_result(ticker: "SGLD", name: "Invesco Physical Gold", country_code: "GB", exchange_operating_mic: "XLON")
+ match.search_isin = "IE00B579F325"
+ other_isin = build_result(ticker: "IE00B579F325", name: "Ticker equals query", country_code: "US")
+ other_isin.search_isin = "IE00B4ND3602"
+
+ ranked = rank([ other, other_isin, match ], "ie00b579f325", "US")
+
+ assert_equal "SGLD", ranked.first.ticker
+ end
+
+ test "ranking: an ISIN-shaped query with a bad check digit is not treated as an ISIN" do
+ wrong = build_result(ticker: "AAA", name: "Wrong")
+ wrong.search_isin = "IE00B579F326"
+ exact_ticker = build_result(ticker: "IE00B579F326", name: "Ticker match")
+
+ ranked = rank([ wrong, exact_ticker ], "IE00B579F326")
+
+ assert_equal "IE00B579F326", ranked.first.ticker
+ end
+
+ test "ranking: results without an ISIN are unaffected by an ISIN query" do
+ a = build_result(ticker: "ZZZ", name: "Zed")
+ b = build_result(ticker: "AAA", name: "Aye")
+
+ assert_equal %w[AAA ZZZ], rank([ a, b ], "IE00B579F325").map(&:ticker)
+ end
+
+ test "search_provider carries the provider ISIN through and tolerates providers without one" do
+ with_isin = mock("with_isin")
+ without_isin = mock("without_isin")
+ with_isin.stubs(:class).returns(Provider::Eodhd)
+ without_isin.stubs(:class).returns(Provider::YahooFinance)
+
+ with_isin.expects(:search_securities).with("IE00B579F325").returns(provider_success_response([
+ Provider::SecurityConcept::Security.new(
+ symbol: "SGLD", name: "Invesco Physical Gold", logo_url: nil,
+ exchange_operating_mic: "XLON", country_code: "GB", currency: "GBP", isin: "IE00B579F325"
+ )
+ ]))
+ without_isin.expects(:search_securities).with("IE00B579F325").returns(provider_success_response([
+ Provider::SecurityConcept::Security.new(
+ symbol: "IE00B579F325.SG", name: "Invesco Physical Gold", logo_url: nil,
+ exchange_operating_mic: "XSTU", country_code: "DE"
+ )
+ ]))
+
+ Security.stubs(:providers).returns([ without_isin, with_isin ])
+
+ results = Security.search_provider("IE00B579F325")
+
+ assert_equal [ "SGLD", "IE00B579F325.SG" ], results.map(&:ticker)
+ assert_equal "IE00B579F325", results.first.to_combobox_option.isin
+ assert_nil results.last.to_combobox_option.isin
+ end
end