Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix EODHD Warsaw (XWAR) prices labelled as USD (#3141)

William Wei Ming42836ccaccbb
diff --git a/app/models/provider/eodhd.rb b/app/models/provider/eodhd.rb
index b4dfc57b02..f8d5e51445 100644
--- a/app/models/provider/eodhd.rb
+++ b/app/models/provider/eodhd.rb
@@ -39,6 +39,10 @@ class Provider::Eodhd < Provider
"XKRX" => "KS",
"XBOM" => "BSE",
"XNSE" => "NSE",
+ "XWAR" => "WAR",
+ # Still accept legacy rows / inputs that store the raw EODHD code as MIC.
+ # Persistence always canonicalizes WAR → XWAR via Security::MIC_ALIASES.
+ "WAR" => "WAR",
"EUFUND" => "EUFUND"
}.freeze
@@ -49,7 +53,7 @@ class Provider::Eodhd < Provider
"TSE" => "XTKS", "MI" => "XMIL", "MC" => "XMAD",
"OL" => "XOSL", "HE" => "XHEL", "CO" => "XCSE",
"ST" => "XSTO", "KS" => "XKRX", "BSE" => "XBOM",
- "NSE" => "XNSE"
+ "NSE" => "XNSE", "WAR" => "XWAR"
}.freeze
EODHD_COUNTRY_TO_CODE = {
@@ -58,7 +62,7 @@ class Provider::Eodhd < Provider
"Japan" => "JP", "Australia" => "AU", "Hong Kong" => "HK",
"Italy" => "IT", "Spain" => "ES", "Norway" => "NO",
"Finland" => "FI", "Denmark" => "DK", "Sweden" => "SE",
- "South Korea" => "KR", "India" => "IN"
+ "South Korea" => "KR", "India" => "IN", "Poland" => "PL"
}.freeze
EXCHANGE_CURRENCY = {
@@ -68,6 +72,7 @@ class Provider::Eodhd < Provider
"OL" => "NOK", "HE" => "EUR", "CO" => "DKK",
"ST" => "SEK", "KS" => "KRW", "BSE" => "INR",
"NSE" => "INR",
+ "WAR" => "PLN",
"EUFUND" => "EUR"
}.freeze
@@ -217,10 +222,10 @@ class Provider::Eodhd < Provider
raise InvalidSecurityPriceError, "Unexpected response format from EOD API"
end
- # Prefer cached currency from search results; fall back to hardcoded map
- cache_key = "eodhd:currency:#{symbol.upcase}:#{exchange_operating_mic}"
- eodhd_exchange = MIC_TO_EODHD_EXCHANGE[exchange_operating_mic]
- currency = Rails.cache.read(cache_key) || EXCHANGE_CURRENCY[eodhd_exchange]
+ # Prefer the per-security currency cached from search (handles USD LSE
+ # listings, etc.), then fall back to the exchange default map — including
+ # legacy rows that still store the raw EODHD code as MIC (e.g. "WAR").
+ currency = currency_for(exchange_operating_mic: exchange_operating_mic, symbol: symbol)
parsed.map do |resp|
price = resp.dig("close")
@@ -277,6 +282,22 @@ class Provider::Eodhd < Provider
end
end
+ def currency_for(exchange_operating_mic:, symbol:)
+ # Accept legacy raw EODHD codes (e.g. WAR) and ISO MICs (XWAR).
+ # Use ::Security — bare Security here is Provider::SecurityConcept::Security.
+ eodhd_exchange = MIC_TO_EODHD_EXCHANGE[exchange_operating_mic] ||
+ MIC_TO_EODHD_EXCHANGE[::Security.canonical_exchange_operating_mic(exchange_operating_mic)]
+ symbol_key = symbol.to_s.upcase
+ cache_keys = [
+ "eodhd:currency:#{symbol_key}:#{exchange_operating_mic}",
+ "eodhd:currency:#{symbol_key}:#{::Security.canonical_exchange_operating_mic(exchange_operating_mic)}"
+ ].uniq
+
+ cache_keys.lazy.map { |key| Rails.cache.read(key) }.find(&:present?) ||
+ EXCHANGE_CURRENCY[eodhd_exchange] ||
+ EXCHANGE_CURRENCY[exchange_operating_mic]
+ end
+
# Cache key for tracking daily API usage
def daily_cache_key
"eodhd:daily:#{Date.current}"
diff --git a/app/models/security.rb b/app/models/security.rb
index 6f567f4ab9..981b35dada 100644
--- a/app/models/security.rb
+++ b/app/models/security.rb
@@ -9,6 +9,12 @@ class Security < ApplicationRecord
# Data stored in config/exchanges.yml
EXCHANGES = YAML.safe_load_file(Rails.root.join("config", "exchanges.yml")).freeze
+ # Legacy non-ISO values previously persisted as exchange_operating_mic
+ # (e.g. raw EODHD exchange codes) mapped to their ISO MIC.
+ MIC_ALIASES = {
+ "WAR" => "XWAR"
+ }.freeze
+
KINDS = %w[standard cash].freeze
# Known securities provider keys — derived from the registry so adding a new
@@ -118,6 +124,82 @@ class Security < ApplicationRecord
EXCHANGES.dig(mic.upcase, "name") || mic.upcase
end
+ def self.canonical_exchange_operating_mic(mic)
+ return nil if mic.blank?
+
+ key = mic.to_s.upcase
+ MIC_ALIASES.fetch(key, key)
+ end
+
+ # Values that should match the same venue for DB lookup (canonical + legacy aliases).
+ def self.exchange_operating_mic_lookup_values(mic)
+ return [] if mic.blank?
+
+ canonical = canonical_exchange_operating_mic(mic)
+ aliases = MIC_ALIASES.select { |_legacy, canon| canon == canonical }.keys
+ ([ canonical ] + aliases).uniq
+ end
+
+ # Finds a security by ticker + MIC, treating legacy MIC aliases as the same
+ # venue. When a legacy row is found, upgrades it to the canonical MIC unless
+ # a canonical row already exists (in which case the canonical row wins).
+ #
+ # When +exchange_operating_mic+ is blank:
+ # - match_blank_mic: true → only rows with a blank MIC (find-or-initialize)
+ # - match_blank_mic: false → do not filter by MIC (exact DB match by ticker)
+ def self.find_by_ticker_and_exchange(ticker:, exchange_operating_mic: nil, country_code: nil, match_blank_mic: false)
+ return nil if ticker.blank?
+
+ scope = where("UPPER(ticker) = ?", ticker.to_s.upcase)
+
+ if exchange_operating_mic.present?
+ mics = exchange_operating_mic_lookup_values(exchange_operating_mic)
+ scope = scope.where("UPPER(exchange_operating_mic) IN (?)", mics)
+ elsif match_blank_mic
+ scope = scope.where(exchange_operating_mic: [ nil, "" ])
+ end
+
+ scope = scope.where(country_code: country_code) if country_code.present?
+
+ canonical = canonical_exchange_operating_mic(exchange_operating_mic)
+ security = if canonical.present?
+ scope.order(
+ Arel.sql(
+ sanitize_sql_array([
+ "CASE WHEN UPPER(COALESCE(exchange_operating_mic, '')) = ? THEN 0 ELSE 1 END",
+ canonical
+ ])
+ )
+ ).first
+ else
+ scope.first
+ end
+
+ return nil unless security
+ return security if canonical.blank?
+ return security if security.exchange_operating_mic.to_s.upcase == canonical
+
+ existing_canonical = find_by(ticker: security.ticker, exchange_operating_mic: canonical)
+ return existing_canonical if existing_canonical
+
+ security.update!(exchange_operating_mic: canonical)
+ security
+ end
+
+ def self.find_or_initialize_by_ticker_and_exchange(ticker:, exchange_operating_mic: nil)
+ existing = find_by_ticker_and_exchange(
+ ticker: ticker,
+ exchange_operating_mic: exchange_operating_mic,
+ match_blank_mic: exchange_operating_mic.blank?
+ )
+ return existing if existing
+
+ new(
+ ticker: ticker,
+ exchange_operating_mic: canonical_exchange_operating_mic(exchange_operating_mic)
+ )
+ end
+
def exchange_name
self.class.exchange_name_for(exchange_operating_mic)
end
@@ -159,7 +241,7 @@ class Security < ApplicationRecord
def upcase_symbols
self.ticker = ticker.upcase
- self.exchange_operating_mic = exchange_operating_mic.upcase if exchange_operating_mic.present?
+ self.exchange_operating_mic = self.class.canonical_exchange_operating_mic(exchange_operating_mic) if exchange_operating_mic.present?
end
def should_generate_logo?
diff --git a/app/models/security/resolver.rb b/app/models/security/resolver.rb
index 4d0521b2da..ddd340c08f 100644
--- a/app/models/security/resolver.rb
+++ b/app/models/security/resolver.rb
@@ -1,7 +1,7 @@
class Security::Resolver
def initialize(symbol, exchange_operating_mic: nil, country_code: nil, price_provider: nil)
@symbol = validate_symbol!(symbol)
- @exchange_operating_mic = exchange_operating_mic
+ @exchange_operating_mic = Security.canonical_exchange_operating_mic(exchange_operating_mic)
@country_code = country_code
@price_provider = validated_price_provider(price_provider)
end
@@ -38,9 +38,9 @@ class Security::Resolver
end
def offline_security
- security = Security.find_or_initialize_by(
+ security = Security.find_or_initialize_by_ticker_and_exchange(
ticker: symbol,
- exchange_operating_mic: exchange_operating_mic,
+ exchange_operating_mic: exchange_operating_mic
)
security.assign_attributes(
@@ -54,12 +54,10 @@ class Security::Resolver
end
def exact_match_from_db
- security = Security.find_by(
- {
- ticker: symbol,
- exchange_operating_mic: exchange_operating_mic,
- country_code: country_code.presence
- }.compact
+ security = Security.find_by_ticker_and_exchange(
+ ticker: symbol,
+ exchange_operating_mic: exchange_operating_mic,
+ country_code: country_code.presence
)
return nil unless security
@@ -83,7 +81,10 @@ class Security::Resolver
match = provider_search_result.find do |s|
ticker_matches = s.ticker&.upcase.to_s == symbol.upcase.to_s
- exchange_matches = s.exchange_operating_mic&.upcase.to_s == exchange_operating_mic.upcase.to_s
+ exchange_matches = exchange_operating_mics_equivalent?(
+ s.exchange_operating_mic,
+ exchange_operating_mic
+ )
if country_code && exchange_operating_mic
ticker_matches && exchange_matches && country_matches?(s.country_code)
@@ -114,9 +115,9 @@ class Security::Resolver
sorted_candidates = filtered_candidates.sort_by do |s|
[
s.ticker&.upcase.to_s == symbol.upcase.to_s ? 0 : 1,
- exchange_operating_mic.present? && s.exchange_operating_mic&.upcase.to_s == exchange_operating_mic.upcase.to_s ? 0 : 1,
+ exchange_operating_mic.present? && exchange_operating_mics_equivalent?(s.exchange_operating_mic, exchange_operating_mic) ? 0 : 1,
sorted_country_codes_by_relevance.index(s.country_code&.upcase.to_s) || sorted_country_codes_by_relevance.length,
- sorted_exchange_operating_mics_by_relevance.index(s.exchange_operating_mic&.upcase.to_s) || sorted_exchange_operating_mics_by_relevance.length
+ sorted_exchange_operating_mics_by_relevance.index(Security.canonical_exchange_operating_mic(s.exchange_operating_mic)) || sorted_exchange_operating_mics_by_relevance.length
]
end
@@ -128,9 +129,9 @@ class Security::Resolver
end
def find_or_create_provider_match!(match)
- security = Security.find_or_initialize_by(
+ security = Security.find_or_initialize_by_ticker_and_exchange(
ticker: match.ticker,
- exchange_operating_mic: match.exchange_operating_mic,
+ exchange_operating_mic: match.exchange_operating_mic
)
security.country_code = match.country_code
@@ -172,6 +173,12 @@ class Security::Resolver
candidate_country.upcase == country_code.upcase
end
+ def exchange_operating_mics_equivalent?(left, right)
+ return false if left.blank? || right.blank?
+
+ Security.canonical_exchange_operating_mic(left) == Security.canonical_exchange_operating_mic(right)
+ end
+
def provider_search_result
params = {
exchange_operating_mic: exchange_operating_mic,
diff --git a/app/models/security/warsaw_price_currency_backfill.rb b/app/models/security/warsaw_price_currency_backfill.rb
new file mode 100644
index 0000000000..cac9bb5105
--- /dev/null
+++ b/app/models/security/warsaw_price_currency_backfill.rb
@@ -0,0 +1,148 @@
+# Relabels mis-tagged Warsaw (XWAR / legacy WAR) security_prices from USD → PLN.
+#
+# Before Provider::Eodhd mapped Warsaw, search-cache expiry caused PLN closes to be
+# persisted as USD (#3128). Numeric prices stay the same; only the currency label
+# is corrected. When a PLN row already exists for the same (security, date), the
+# USD duplicate is deleted to satisfy the unique index.
+#
+# Optionally upgrades legacy WAR MICs to XWAR and schedules account syncs so
+# calculated holdings revalue with the corrected FX.
+class Security::WarsawPriceCurrencyBackfill
+ WARSAW_MICS = %w[XWAR WAR].freeze
+ FROM_CURRENCY = "USD"
+ TO_CURRENCY = "PLN"
+
+ Result = Data.define(
+ :securities_scanned,
+ :mics_canonicalized,
+ :prices_relabeled,
+ :prices_deleted,
+ :accounts_queued_for_sync,
+ :dry_run
+ )
+
+ def initialize(dry_run: false, sync_accounts: true)
+ @dry_run = dry_run
+ @sync_accounts = sync_accounts
+ end
+
+ def call
+ securities_scanned = 0
+ mics_canonicalized = 0
+ prices_relabeled = 0
+ prices_deleted = 0
+ touched_security_ids = []
+
+ warsaw_securities.find_each do |security|
+ securities_scanned += 1
+
+ mic_changed = canonicalize_mic!(security)
+ mics_canonicalized += 1 if mic_changed
+
+ relabeled, deleted = fix_prices_for!(security)
+ prices_relabeled += relabeled
+ prices_deleted += deleted
+ if mic_changed || relabeled.positive? || deleted.positive?
+ touched_security_ids << security.id
+ end
+ end
+
+ accounts_queued = enqueue_account_syncs!(touched_security_ids.uniq)
+
+ Result.new(
+ securities_scanned: securities_scanned,
+ mics_canonicalized: mics_canonicalized,
+ prices_relabeled: prices_relabeled,
+ prices_deleted: prices_deleted,
+ accounts_queued_for_sync: accounts_queued,
+ dry_run: dry_run
+ )
+ end
+
+ private
+ attr_reader :dry_run, :sync_accounts
+
+ def warsaw_securities
+ Security.where("UPPER(exchange_operating_mic) IN (?)", WARSAW_MICS)
+ end
+
+ def canonicalize_mic!(security)
+ return false unless security.exchange_operating_mic.to_s.upcase == "WAR"
+
+ existing_canonical = Security
+ .where("UPPER(ticker) = ?", security.ticker.to_s.upcase)
+ .where("UPPER(exchange_operating_mic) = ?", "XWAR")
+ .where.not(id: security.id)
+ .first
+
+ return false if existing_canonical # leave merge to securities:deduplicate
+
+ unless dry_run
+ security.update_columns(exchange_operating_mic: "XWAR", updated_at: Time.current)
+ end
+
+ true
+ end
+
+ def fix_prices_for!(security)
+ pln_dates = security.prices.where(currency: TO_CURRENCY).pluck(:date).to_set
+ usd_prices = security.prices.where(currency: FROM_CURRENCY)
+ usd_rows = usd_prices.pluck(:id, :date)
+
+ to_delete_ids = []
+ to_relabel_ids = []
+ usd_rows.each do |id, date|
+ if pln_dates.include?(date)
+ to_delete_ids << id
+ else
+ to_relabel_ids << id
+ end
+ end
+
+ unless dry_run
+ Security::Price.where(id: to_delete_ids).delete_all if to_delete_ids.any?
+ if to_relabel_ids.any?
+ Security::Price.where(id: to_relabel_ids).update_all(
+ currency: TO_CURRENCY,
+ updated_at: Time.current
+ )
+ end
+ end
+
+ [ to_relabel_ids.size, to_delete_ids.size ]
+ end
+
+ def enqueue_account_syncs!(touched_security_ids)
+ return 0 unless sync_accounts
+
+ security_ids = security_ids_for_account_sync(touched_security_ids)
+ return 0 if security_ids.empty?
+
+ account_ids = Holding.where(security_id: security_ids).distinct.pluck(:account_id)
+ return 0 if account_ids.empty?
+
+ unless dry_run
+ Account.where(id: account_ids).find_each(&:sync_later)
+ end
+
+ account_ids.size
+ end
+
+ # Without a DDL transaction, a failed migration may relabel prices and then
+ # abort before sync. On retry those rows are already PLN and won't look
+ # "touched", so also requeue holdings for Warsaw securities that no longer
+ # have mis-tagged USD prices.
+ def security_ids_for_account_sync(touched_security_ids)
+ usd_prices_for_holding = Security::Price
+ .where(currency: FROM_CURRENCY)
+ .where(Security::Price.arel_table[:security_id].eq(Holding.arel_table[:security_id]))
+
+ corrected_without_usd = Holding
+ .where(security_id: warsaw_securities.select(:id))
+ .where.not(usd_prices_for_holding.arel.exists)
+ .distinct
+ .pluck(:security_id)
+
+ (touched_security_ids + corrected_without_usd).uniq
+ end
+end
diff --git a/db/migrate/20260824130000_backfill_warsaw_security_price_currency.rb b/db/migrate/20260824130000_backfill_warsaw_security_price_currency.rb
new file mode 100644
index 0000000000..5bb46281a2
--- /dev/null
+++ b/db/migrate/20260824130000_backfill_warsaw_security_price_currency.rb
@@ -0,0 +1,28 @@
+# frozen_string_literal: true
+
+class BackfillWarsawSecurityPriceCurrency < ActiveRecord::Migration[7.2]
+ disable_ddl_transaction!
+
+ def up
+ say_with_time "Backfilling Warsaw security_prices USD → PLN (and WAR → XWAR MICs)" do
+ result = Security::WarsawPriceCurrencyBackfill.new(
+ dry_run: false,
+ sync_accounts: !Rails.env.test?
+ ).call
+ say(
+ "scanned=#{result.securities_scanned} " \
+ "mics=#{result.mics_canonicalized} " \
+ "relabeled=#{result.prices_relabeled} " \
+ "deleted_usd_dupes=#{result.prices_deleted} " \
+ "accounts_synced=#{result.accounts_queued_for_sync}",
+ true
+ )
+ result.prices_relabeled + result.prices_deleted + result.mics_canonicalized
+ end
+ end
+
+ def down
+ raise ActiveRecord::IrreversibleMigration,
+ "Cannot distinguish corrected PLN rows from prices that were always PLN"
+ end
+end
diff --git a/lib/tasks/securities.rake b/lib/tasks/securities.rake
index 808df1924d..a0a81b1187 100644
--- a/lib/tasks/securities.rake
+++ b/lib/tasks/securities.rake
@@ -116,4 +116,20 @@ namespace :securities do
puts " Mode: #{dry_run ? 'Dry run (no changes made)' : 'Live run (changes applied)'}"
puts "\nDe-duplication complete!"
end
+
+ desc "Relabel Warsaw (XWAR/WAR) security_prices wrongly stored as USD to PLN. Args: dry_run (default true)"
+ task :backfill_warsaw_price_currency, [ :dry_run ] => :environment do |_t, args|
+ raw_dry = args[:dry_run].presence || ENV["DRY_RUN"].presence
+ dry_run = case raw_dry.to_s.strip.downcase
+ when "0", "false", "no", "n" then false
+ when "1", "true", "yes", "y" then true
+ when "" then true
+ else
+ true
+ end
+
+ puts "Warsaw price currency backfill (dry_run: #{dry_run})..."
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: dry_run, sync_accounts: !dry_run).call
+ puts result.to_h.to_json
+ end
end
diff --git a/test/models/provider/eodhd_test.rb b/test/models/provider/eodhd_test.rb
index bb53ec6fb5..fa965ad712 100644
--- a/test/models/provider/eodhd_test.rb
+++ b/test/models/provider/eodhd_test.rb
@@ -79,4 +79,120 @@ class Provider::EodhdTest < ActiveSupport::TestCase
ticker = @provider.send(:eodhd_symbol, "AAPL", "XNYS")
assert_equal "AAPL.US", ticker
end
+
+ test "maps Warsaw exchange WAR to ISO MIC XWAR with PLN" do
+ warsaw_body = [
+ {
+ "Code" => "KTY",
+ "Name" => "Grupa Kety SA",
+ "Exchange" => "WAR",
+ "Country" => "Poland",
+ "Currency" => "PLN"
+ }
+ ].to_json
+
+ mock_response = mock
+ mock_response.stubs(:body).returns(warsaw_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("KTY")
+
+ assert result.success?
+ security = result.data.first
+ assert_equal "KTY", security.symbol
+ assert_equal "XWAR", security.exchange_operating_mic
+ assert_equal "PL", security.country_code
+ assert_equal "PLN", security.currency
+ end
+
+ test "eodhd_symbol builds Warsaw ticker from XWAR MIC" do
+ assert_equal "KTY.WAR", @provider.send(:eodhd_symbol, "KTY", "XWAR")
+ end
+
+ test "eodhd_symbol builds Warsaw ticker from legacy WAR MIC" do
+ assert_equal "KTY.WAR", @provider.send(:eodhd_symbol, "KTY", "WAR")
+ end
+
+ test "fetch_security_prices uses PLN for XWAR without currency cache" do
+ Rails.cache.clear
+
+ eod_body = [
+ { "date" => "2026-08-21", "close" => 1213.0 },
+ { "date" => "2026-08-22", "close" => 1227.0 }
+ ].to_json
+
+ mock_response = mock
+ mock_response.stubs(:body).returns(eod_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.fetch_security_prices(
+ symbol: "KTY",
+ exchange_operating_mic: "XWAR",
+ start_date: Date.new(2026, 8, 21),
+ end_date: Date.new(2026, 8, 22)
+ )
+
+ assert result.success?
+ assert_equal 2, result.data.length
+ assert result.data.all? { |price| price.currency == "PLN" }
+ assert_equal [ 1213.0, 1227.0 ], result.data.map { |price| price.price.to_f }
+ end
+
+ test "fetch_security_prices uses PLN for legacy WAR MIC without cache" do
+ Rails.cache.clear
+
+ eod_body = [ { "date" => "2026-08-21", "close" => 1213.0 } ].to_json
+
+ mock_response = mock
+ mock_response.stubs(:body).returns(eod_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.fetch_security_prices(
+ symbol: "KTY",
+ exchange_operating_mic: "WAR",
+ start_date: Date.new(2026, 8, 21),
+ end_date: Date.new(2026, 8, 21)
+ )
+
+ assert result.success?
+ assert_equal "PLN", result.data.first.currency
+ end
+
+ test "fetch_security_prices prefers cached per-security currency over exchange default" do
+ # LSE venue default is GBP, but this listing is USD-denominated in search results.
+ # Test env uses null_store, so stub the cache read the provider would see after search.
+ Rails.cache.stubs(:read).with("eodhd:currency:BABA:XLON").returns("USD")
+
+ eod_body = [ { "date" => "2026-08-21", "close" => 85.5 } ].to_json
+
+ mock_response = mock
+ mock_response.stubs(:body).returns(eod_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.fetch_security_prices(
+ symbol: "BABA",
+ exchange_operating_mic: "XLON",
+ start_date: Date.new(2026, 8, 21),
+ end_date: Date.new(2026, 8, 21)
+ )
+
+ assert result.success?
+ assert_equal "USD", result.data.first.currency
+ end
end
diff --git a/test/models/security/resolver_test.rb b/test/models/security/resolver_test.rb
index 791688e091..02f4b342ba 100644
--- a/test/models/security/resolver_test.rb
+++ b/test/models/security/resolver_test.rb
@@ -207,4 +207,73 @@ class Security::ResolverTest < ActiveSupport::TestCase
assert_equal db_security, resolved
assert_nil resolved.reload.price_provider, "Disabled providers should be rejected"
end
+
+ test "canonicalizes legacy WAR MIC to XWAR on resolve and reuses existing row" do
+ legacy = Security.create!(ticker: "KTY", exchange_operating_mic: "XWAR", country_code: "PL")
+ legacy.update_columns(exchange_operating_mic: "WAR")
+
+ Security.expects(:search_provider).never
+
+ resolved = Security::Resolver.new("KTY", exchange_operating_mic: "WAR", country_code: "PL").resolve
+
+ assert_equal legacy.id, resolved.id
+ assert_equal "XWAR", resolved.reload.exchange_operating_mic
+ end
+
+ test "WAR and XWAR resolve to the same security without creating a duplicate" do
+ match = Security.new(ticker: "KTY", exchange_operating_mic: "XWAR", country_code: "PL", price_provider: "eodhd")
+
+ Security.expects(:search_provider)
+ .with("KTY", exchange_operating_mic: "XWAR", country_code: "PL")
+ .returns([ match ])
+
+ Setting.stubs(:enabled_securities_providers).returns([ "eodhd" ])
+
+ assert_difference "Security.count", 1 do
+ resolved = Security::Resolver.new(
+ "KTY",
+ exchange_operating_mic: "WAR",
+ country_code: "PL",
+ price_provider: "eodhd"
+ ).resolve
+
+ assert_equal "XWAR", resolved.exchange_operating_mic
+ end
+
+ Security.expects(:search_provider).never
+
+ assert_no_difference "Security.count" do
+ again = Security::Resolver.new(
+ "KTY",
+ exchange_operating_mic: "XWAR",
+ country_code: "PL",
+ price_provider: "eodhd"
+ ).resolve
+
+ assert_equal "XWAR", again.exchange_operating_mic
+ assert_equal 1, Security.where("UPPER(ticker) = ?", "KTY").count
+ end
+ end
+
+ test "prefers canonical XWAR when both WAR and XWAR rows exist" do
+ canonical = Security.create!(ticker: "KTY", exchange_operating_mic: "XWAR", country_code: "PL")
+ legacy = Security.new(ticker: "KTY", exchange_operating_mic: "WAR", country_code: "PL")
+ legacy.save!(validate: false)
+
+ Security.expects(:search_provider).never
+
+ resolved = Security::Resolver.new("KTY", exchange_operating_mic: "WAR", country_code: "PL").resolve
+
+ assert_equal canonical.id, resolved.id
+ assert_equal "XWAR", resolved.exchange_operating_mic
+ end
+
+ test "persists WAR lookups as canonical XWAR" do
+ Security.expects(:search_provider).returns([])
+
+ resolved = Security::Resolver.new("KTY", exchange_operating_mic: "WAR", country_code: "PL").resolve
+
+ assert resolved.persisted?
+ assert_equal "XWAR", resolved.exchange_operating_mic
+ end
end
diff --git a/test/models/security/warsaw_price_currency_backfill_test.rb b/test/models/security/warsaw_price_currency_backfill_test.rb
new file mode 100644
index 0000000000..c9d391f5e7
--- /dev/null
+++ b/test/models/security/warsaw_price_currency_backfill_test.rb
@@ -0,0 +1,145 @@
+require "test_helper"
+
+class Security::WarsawPriceCurrencyBackfillTest < ActiveSupport::TestCase
+ setup do
+ @security = Security.create!(ticker: "KTY", exchange_operating_mic: "XWAR", country_code: "PL")
+ end
+
+ test "relabels USD Warsaw prices to PLN" do
+ usd = Security::Price.create!(security: @security, date: Date.new(2026, 8, 21), price: 1213, currency: "USD")
+
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: false, sync_accounts: false).call
+
+ assert_equal 1, result.prices_relabeled
+ assert_equal 0, result.prices_deleted
+ assert_equal "PLN", usd.reload.currency
+ end
+
+ test "deletes USD duplicate when PLN already exists for the same date" do
+ Security::Price.create!(security: @security, date: Date.new(2026, 8, 21), price: 1213, currency: "PLN")
+ usd = Security::Price.create!(security: @security, date: Date.new(2026, 8, 21), price: 1213, currency: "USD")
+
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: false, sync_accounts: false).call
+
+ assert_equal 0, result.prices_relabeled
+ assert_equal 1, result.prices_deleted
+ assert_not Security::Price.exists?(usd.id)
+ assert_equal 1, @security.prices.where(date: Date.new(2026, 8, 21), currency: "PLN").count
+ end
+
+ test "canonicalizes legacy WAR MIC to XWAR when no conflict" do
+ legacy = Security.create!(ticker: "PKO", exchange_operating_mic: "XWAR", country_code: "PL")
+ legacy.update_columns(exchange_operating_mic: "WAR")
+ Security::Price.create!(security: legacy, date: Date.new(2026, 8, 21), price: 50, currency: "USD")
+
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: false, sync_accounts: false).call
+
+ assert_operator result.mics_canonicalized, :>=, 1
+ assert_equal "XWAR", legacy.reload.exchange_operating_mic
+ assert_equal "PLN", legacy.prices.first.currency
+ end
+
+ test "dry run does not mutate rows" do
+ usd = Security::Price.create!(security: @security, date: Date.new(2026, 8, 21), price: 1213, currency: "USD")
+
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: true, sync_accounts: false).call
+
+ assert result.dry_run
+ assert_equal 1, result.prices_relabeled
+ assert_equal "USD", usd.reload.currency
+ end
+
+ test "does not touch non-Warsaw securities" do
+ other = Security.create!(ticker: "ZZZZ", exchange_operating_mic: "XNAS", country_code: "US")
+ usd = Security::Price.create!(security: other, date: Date.new(2026, 8, 21), price: 200, currency: "USD")
+
+ Security::WarsawPriceCurrencyBackfill.new(dry_run: false, sync_accounts: false).call
+
+ assert_equal "USD", usd.reload.currency
+ end
+
+ test "queues account syncs for holdings of touched securities" do
+ account = accounts(:investment)
+ Security::Price.create!(security: @security, date: Date.new(2026, 8, 21), price: 1213, currency: "USD")
+ Holding.create!(
+ account: account,
+ security: @security,
+ date: Date.new(2026, 8, 21),
+ qty: 1,
+ price: 1213,
+ amount: 1213,
+ currency: "USD"
+ )
+
+ Account.any_instance.expects(:sync_later).at_least_once
+
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: false, sync_accounts: true).call
+
+ assert_operator result.accounts_queued_for_sync, :>=, 1
+ end
+
+ test "requeues account sync on retry for already corrected Warsaw securities" do
+ account = accounts(:investment)
+ Security::Price.create!(security: @security, date: Date.new(2026, 8, 21), price: 1213, currency: "PLN")
+ Holding.create!(
+ account: account,
+ security: @security,
+ date: Date.new(2026, 8, 21),
+ qty: 1,
+ price: 1213,
+ amount: 1213,
+ currency: "PLN"
+ )
+
+ Account.any_instance.expects(:sync_later).at_least_once
+
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: false, sync_accounts: true).call
+
+ assert_equal 0, result.prices_relabeled
+ assert_operator result.accounts_queued_for_sync, :>=, 1
+ end
+
+ test "requeues account sync on retry when orphaned USD prices have null security_id" do
+ account = accounts(:investment)
+ Security::Price.create!(security: @security, date: Date.new(2026, 8, 21), price: 1213, currency: "PLN")
+ Holding.create!(
+ account: account,
+ security: @security,
+ date: Date.new(2026, 8, 21),
+ qty: 1,
+ price: 1213,
+ amount: 1213,
+ currency: "PLN"
+ )
+
+ orphaned_usd = Security::Price.new(
+ date: Date.new(2026, 8, 20),
+ price: 99,
+ currency: "USD",
+ security_id: nil
+ )
+ orphaned_usd.save!(validate: false)
+
+ Account.any_instance.expects(:sync_later).at_least_once
+
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: false, sync_accounts: true).call
+
+ assert_equal 0, result.prices_relabeled
+ assert_operator result.accounts_queued_for_sync, :>=, 1
+ assert_nil orphaned_usd.reload.security_id
+ end
+
+ test "skips MIC upgrade when both WAR and XWAR securities already exist" do
+ canonical = Security.create!(ticker: "PZU", exchange_operating_mic: "XWAR", country_code: "PL")
+ legacy = Security.new(ticker: "PZU", exchange_operating_mic: "WAR", country_code: "PL")
+ legacy.save!(validate: false)
+ Security::Price.create!(security: legacy, date: Date.new(2026, 8, 21), price: 40, currency: "USD")
+
+ result = Security::WarsawPriceCurrencyBackfill.new(dry_run: false, sync_accounts: false).call
+
+ assert_equal "WAR", legacy.reload.exchange_operating_mic
+ assert_equal "XWAR", canonical.reload.exchange_operating_mic
+ assert_equal "PLN", legacy.prices.first.currency
+ assert_equal 0, result.mics_canonicalized
+ end
+end
diff --git a/test/models/security_test.rb b/test/models/security_test.rb
index 09225eab92..0fe528d3f0 100644
--- a/test/models/security_test.rb
+++ b/test/models/security_test.rb
@@ -39,6 +39,22 @@ class SecurityTest < ActiveSupport::TestCase
assert_equal [ "has already been taken" ], duplicate.errors[:ticker]
end
+ test "canonicalizes WAR to XWAR on save" do
+ security = Security.create!(ticker: "KTY", exchange_operating_mic: "WAR")
+
+ assert_equal "XWAR", security.exchange_operating_mic
+ end
+
+ test "find_by_ticker_and_exchange upgrades legacy WAR and avoids duplicates" do
+ legacy = Security.create!(ticker: "KTY", exchange_operating_mic: "XWAR")
+ legacy.update_columns(exchange_operating_mic: "WAR")
+
+ found = Security.find_by_ticker_and_exchange(ticker: "KTY", exchange_operating_mic: "XWAR")
+
+ assert_equal legacy.id, found.id
+ assert_equal "XWAR", found.reload.exchange_operating_mic
+ end
+
test "cash_for lazily creates a per-account synthetic cash security" do
account = accounts(:investment)