The personal finance app for everyone (by everyone)
Ruby
feat: add Mansa API provider for NGX (Nigerian Exchange) securities (#3629)
Desmondb883643c677f
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rbindex af71e4d18e..fe73027168 100644--- a/app/controllers/settings/hostings_controller.rb+++ b/app/controllers/settings/hostings_controller.rb@@ -33,6 +33,7 @@ class Settings::HostingsController < ApplicationController@show_tiingo_settings = enabled_securities.include?("tiingo")@show_eodhd_settings = enabled_securities.include?("eodhd")@show_alpha_vantage_settings = enabled_securities.include?("alpha_vantage")+ @show_mansa_settings = enabled_securities.include?("mansa")tinkoff_invest_checked = enabled_securities.include?("tinkoff_invest")tinkoff_invest_configured = ENV["TINKOFF_INVEST_API_KEY"].present? || Setting.tinkoff_invest_api_key.present?@show_tinkoff_invest_settings = tinkoff_invest_checked || enabled_securities.include?("moex_public") || tinkoff_invest_configured@@ -120,6 +121,7 @@ class Settings::HostingsController < ApplicationControllerupdate_encrypted_setting(:eodhd_api_key)update_encrypted_setting(:alpha_vantage_api_key)update_encrypted_setting(:tinkoff_invest_api_key)+ update_encrypted_setting(:mansa_api_key)update_encrypted_setting(:rentcast_api_key)update_encrypted_setting(:realie_api_key)@@ -271,7 +273,7 @@ class Settings::HostingsController < ApplicationController# Strong parameters for the self-hosting settings form.def hosting_paramsreturn ActionController::Parameters.new unless params.key?(:setting)- params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :rentcast_api_key, :realie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_agent_id, securities_providers: [])+ params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :brand_fetch_client_id, :brand_fetch_high_res_logos, :twelve_data_api_key, :tiingo_api_key, :eodhd_api_key, :alpha_vantage_api_key, :tinkoff_invest_api_key, :mansa_api_key, :rentcast_api_key, :realie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_agent_id, securities_providers: [])enddef update_assistant_typediff --git a/app/models/provider/mansa.rb b/app/models/provider/mansa.rbnew file mode 100644index 0000000000..99eec6fadc--- /dev/null+++ b/app/models/provider/mansa.rb@@ -0,0 +1,288 @@+# Mansa API (mansaapi.com) — African stock exchange data, including NGX+# (Nigerian Exchange). Added because none of Sure's existing securities+# providers cover NGX: TwelveData/YahooFinance don't list it, and EODHD's own+# MIC-code map in this codebase (see Provider::Eodhd::MIC_TO_EODHD_EXCHANGE)+# has no XNSA entry despite EODHD's marketing pages listing Nigeria as a+# covered exchange generally — confirmed absent, not just unconfirmed.+#+# Free tier: 100 requests/day, no card required, covers quotes/search/exchange+# metadata. Per-stock historical OHLCV (the /history endpoint) requires a paid+# Pro plan — see #fetch_security_prices below for how that's handled here.+#+# Response shape confirmed live (2026-09-17) against real NGX data:+# GET .../exchanges/NGX/stocks/MTNN ->+# {"success":true,"data":{"ticker":...,"name":...,"price":...,...},+# "meta":{"exchange":"NGX","currency":"NGN",...}}+# GET .../markets/search?q=MTN&exchange=NGX ->+# {"success":true,"data":[{"ticker":...,"name":...,"exchange":"NGX",+# "currency":"NGN",...}]}+# Two things that didn't match the pre-testing guess, worth flagging since a+# future provider written the same way would hit the same trap: the field is+# `name`, not `company_name` — and on the single-quote endpoint specifically,+# `currency` lives under the top-level `meta`, not inside `data` (the search+# endpoint's per-row `data` entries do carry their own `currency` directly).+class Provider::Mansa < Provider+ include SecurityConcept, RateLimitable+ extend SslConfigurable++ Error = Class.new(Provider::Error)+ InvalidSecurityPriceError = Class.new(Error)+ RateLimitError = Class.new(Error)++ # Mansa's docs specify a 100/day cap but don't document a per-minute pacing+ # limit the way TwelveData/EODHD do — this is a conservative default, not a+ # confirmed number, kept low to avoid tripping an undocumented limit.+ MIN_REQUEST_INTERVAL = 1.0++ MAX_REQUESTS_PER_DAY = 100++ # Historical data isn't available on the free tier (see class comment), so+ # there's no meaningful "how far back" answer here the way there is for+ # providers with real EOD history access.+ def max_history_days+ 0+ end++ # Only NGX is confirmed working end-to-end (this is the exchange the fleet+ # actually needs). Mansa's API covers 21 African exchanges total — extend+ # this map once another one is actually verified against a live response,+ # rather than guessing MIC codes for exchanges nobody has tested here.+ MIC_TO_MANSA_EXCHANGE = {+ "XNSA" => "NGX"+ }.freeze++ MANSA_EXCHANGE_TO_MIC = MIC_TO_MANSA_EXCHANGE.invert.freeze++ # The only exchange verified end-to-end (see above). Used to scope any+ # search/quote request that doesn't specify a MIC we recognize — Sure's own+ # trade-form combobox never passes exchange_operating_mic on search at all+ # (see app/views/trades/_form.html.erb), so leaving this unscoped would let+ # Mansa return matches from other African exchanges this adapter has no+ # verified MIC mapping for, which would then persist Mansa's own exchange+ # code (e.g. "JSE") into exchange_operating_mic instead of a real ISO MIC.+ DEFAULT_MANSA_EXCHANGE = "NGX"++ def initialize(api_key)+ @api_key = api_key # pipelock:ignore+ end++ def healthy?+ with_provider_response do+ response = client.get("#{base_url}/api/v1/markets/exchanges/NGX/stocks") do |req|+ req.params["limit"] = 1+ end++ parsed = JSON.parse(response.body)+ parsed["success"] == true+ end+ end++ def usage+ with_provider_response do+ used = Rails.cache.read(daily_cache_key).to_i++ UsageData.new(+ used: used,+ limit: max_requests_per_day,+ utilization: used.to_f / max_requests_per_day * 100,+ plan: "free"+ )+ end+ end++ # ================================+ # Securities+ # ================================++ def search_securities(symbol, country_code: nil, exchange_operating_mic: nil)+ with_provider_response do+ enforce_daily_limit!+ throttle_request++ mansa_exchange = MIC_TO_MANSA_EXCHANGE[exchange_operating_mic]+ # A blank MIC (the real UI's normal case — see DEFAULT_MANSA_EXCHANGE's+ # comment) falls back to NGX. A *present* MIC that isn't XNSA means the+ # caller wants a specific exchange Mansa doesn't cover here — searching+ # NGX anyway would silently return the wrong exchange's results, so+ # return nothing instead of guessing.+ next [] if exchange_operating_mic.present? && mansa_exchange.nil?+ mansa_exchange ||= DEFAULT_MANSA_EXCHANGE++ response = client.get("#{base_url}/api/v1/markets/search") do |req|+ req.params["q"] = symbol+ req.params["exchange"] = mansa_exchange+ req.params["limit"] = 25+ end++ parsed = JSON.parse(response.body)+ check_api_error!(parsed)+ results = parsed.dig("data") || []++ # Skip anything that doesn't map to a verified real MIC rather than+ # falling back to Mansa's own exchange code — better to drop a result+ # than to persist a non-ISO string into exchange_operating_mic. In+ # practice this shouldn't happen since the request above is always+ # explicitly scoped to a single exchange, but it's cheap insurance+ # against Mansa's search ignoring/broadening the exchange filter.+ results.filter_map do |security|+ mic = MANSA_EXCHANGE_TO_MIC[security.dig("exchange")]+ next unless mic++ Security.new(+ symbol: security.dig("ticker"),+ name: security.dig("name"),+ logo_url: nil,+ exchange_operating_mic: mic,+ country_code: nil,+ currency: security.dig("currency")+ )+ end+ end+ end++ def fetch_security_info(symbol:, exchange_operating_mic:)+ with_provider_response do+ quote = fetch_quote!(symbol:, exchange_operating_mic:)++ SecurityInfo.new(+ symbol: symbol,+ name: quote.dig("name"),+ links: nil,+ logo_url: nil,+ description: nil,+ kind: "stock",+ exchange_operating_mic: exchange_operating_mic+ )+ end+ end++ # Only returns a price for `date == Date.current` (or a date range that+ # includes today) — the free tier has no historical endpoint. See the+ # class comment and #fetch_security_prices.+ def fetch_security_price(symbol:, exchange_operating_mic: nil, date:)+ with_provider_response do+ unless date.to_date == Date.current+ raise InvalidSecurityPriceError,+ "Mansa's free tier only exposes the current quote, not a price for #{date} specifically. " \+ "Historical OHLCV requires a paid Mansa plan (see /history endpoint)."+ end++ quote = fetch_quote!(symbol:, exchange_operating_mic:)++ Price.new(+ symbol: symbol,+ date: Date.current,+ price: quote.dig("price"),+ currency: quote.dig("currency"),+ exchange_operating_mic: exchange_operating_mic+ )+ end+ end++ # Best-effort for a date range: if the range includes today, returns+ # today's live quote as a single-element array (better than nothing for a+ # "what's it worth right now" holding sync). A range that's entirely in the+ # past raises clearly rather than silently returning nothing, since that's+ # a real capability gap (Pro-tier /history), not a transient failure.+ def fetch_security_prices(symbol:, exchange_operating_mic: nil, start_date:, end_date:)+ with_provider_response do+ unless (start_date..end_date).cover?(Date.current)+ raise InvalidSecurityPriceError,+ "Mansa's free tier has no historical price endpoint (Pro plan required for /history). " \+ "Requested range #{start_date}..#{end_date} doesn't include today, so nothing can be returned."+ end++ quote = fetch_quote!(symbol:, exchange_operating_mic:)++ [+ Price.new(+ symbol: symbol,+ date: Date.current,+ price: quote.dig("price"),+ currency: quote.dig("currency"),+ exchange_operating_mic: exchange_operating_mic+ )+ ]+ end+ end++ private+ attr_reader :api_key++ def fetch_quote!(symbol:, exchange_operating_mic:)+ enforce_daily_limit!+ throttle_request++ mansa_exchange = MIC_TO_MANSA_EXCHANGE[exchange_operating_mic]+ # Same principle as search_securities: a present-but-unmapped MIC means+ # don't silently fetch an NGX quote and let the caller mislabel it as+ # coming from whatever exchange was actually asked for. Only a blank+ # MIC (no data to go on at all) gets the NGX default.+ if exchange_operating_mic.present? && mansa_exchange.nil?+ raise InvalidSecurityPriceError, "Mansa does not support exchange #{exchange_operating_mic}"+ end+ mansa_exchange ||= DEFAULT_MANSA_EXCHANGE++ response = client.get("#{base_url}/api/v1/markets/exchanges/#{mansa_exchange}/stocks/#{CGI.escape(symbol)}")++ parsed = JSON.parse(response.body)+ check_api_error!(parsed)+ quote = parsed.dig("data")++ raise InvalidSecurityPriceError, "No quote returned for #{symbol} on #{mansa_exchange}" if quote.blank?++ # Currency lives under the top-level `meta`, not inside `data`, on this+ # endpoint specifically (confirmed live — see class comment). Merge it+ # in so callers can keep reading `quote.dig("currency")` uniformly.+ quote.merge("currency" => parsed.dig("meta", "currency"))+ end++ def base_url+ ENV["MANSA_API_URL"] || "https://mansaapi.com"+ end++ def client+ @client ||= Faraday.new(url: base_url, ssl: self.class.faraday_ssl_options) do |faraday|+ faraday.request(:retry, {+ max: 3,+ interval: 1.0,+ interval_randomness: 0.5,+ backoff_factor: 2,+ exceptions: Faraday::Retry::Middleware::DEFAULT_EXCEPTIONS + [ Faraday::ConnectionFailed ]+ })++ faraday.request :json+ faraday.response :raise_error+ faraday.headers["Authorization"] = "Bearer #{api_key}"+ end+ end++ def daily_cache_key+ "mansa:daily:#{Date.current}"+ end++ def enforce_daily_limit!+ new_count = Rails.cache.increment(daily_cache_key, 1, expires_in: 24.hours).to_i++ if new_count > max_requests_per_day+ raise RateLimitError, "Mansa daily rate limit of #{max_requests_per_day} requests exhausted"+ end+ end++ def max_requests_per_day+ ENV.fetch("MANSA_MAX_REQUESTS_PER_DAY", MAX_REQUESTS_PER_DAY).to_i+ end++ # Confirmed live (2026-09-17): error responses nest a hash under "error"+ # ({"code","message","hint","docs"}), not a flat string — e.g.+ # {"success":false,"error":{"code":"NOT_FOUND","message":"Ticker '...' not found on NGX.",...}}+ def check_api_error!(parsed)+ return unless parsed.is_a?(Hash) && parsed["success"] == false++ error = parsed["error"]+ message = error.is_a?(Hash) ? error["message"] : error+ code = error.is_a?(Hash) ? error["code"] : nil++ raise Error, "API error#{" (#{code})" if code}: #{message || "unknown error"}"+ end+enddiff --git a/app/models/provider/registry.rb b/app/models/provider/registry.rbindex b625fc22fd..5c6eecdc72 100644--- a/app/models/provider/registry.rb+++ b/app/models/provider/registry.rb@@ -133,6 +133,14 @@ class Provider::RegistryProvider::AlphaVantage.new(api_key)end+ def mansa+ api_key = ENV["MANSA_API_KEY"].presence || Setting.mansa_api_key # pipelock:ignore++ return nil unless api_key.present?++ Provider::Mansa.new(api_key)+ end+def mfapiProvider::Mfapi.newend@@ -204,7 +212,7 @@ class Provider::Registrywhen :exchange_rates%i[twelve_data yahoo_finance moex_public frankfurter]when :securities- %i[twelve_data yahoo_finance tiingo eodhd alpha_vantage mfapi binance_public moex_public tinkoff_invest]+ %i[twelve_data yahoo_finance tiingo eodhd alpha_vantage mfapi binance_public moex_public tinkoff_invest mansa]when :llm%i[openai anthropic]when :property_valuationsdiff --git a/app/models/setting.rb b/app/models/setting.rbindex 4ecc98e212..edf2dc71a1 100644--- a/app/models/setting.rb+++ b/app/models/setting.rb@@ -78,6 +78,9 @@ class Setting < RailsSettings::Basefield :eodhd_api_key, type: :string, default: ENV["EODHD_API_KEY"]field :alpha_vantage_api_key, type: :string, default: ENV["ALPHA_VANTAGE_API_KEY"]field :tinkoff_invest_api_key, type: :string, default: ENV["TINKOFF_INVEST_API_KEY"]+ # Mansa API (mansaapi.com) — African exchanges, including NGX (Nigeria),+ # which none of the providers above cover. See Provider::Mansa.+ field :mansa_api_key, type: :string, default: ENV["MANSA_API_KEY"]# Property valuation (AVM) provider API keysfield :rentcast_api_key, type: :string, default: ENV["RENTCAST_API_KEY"]@@ -97,6 +100,7 @@ class Setting < RailsSettings::Baseeodhd_api_keyalpha_vantage_api_keytinkoff_invest_api_key+ mansa_api_keyrentcast_api_keyrealie_api_keyopenai_access_tokendiff --git a/app/views/settings/hostings/_mansa_settings.html.erb b/app/views/settings/hostings/_mansa_settings.html.erbnew file mode 100644index 0000000000..99283a13f9--- /dev/null+++ b/app/views/settings/hostings/_mansa_settings.html.erb@@ -0,0 +1,40 @@+<div class="space-y-4">+ <div>+ <h2 class="font-medium mb-1"><%= t(".title") %></h2>+ <% if ENV["MANSA_API_KEY"].present? %>+ <p class="text-sm text-secondary"><%= t(".env_configured_message") %></p>+ <% else %>+ <div class="text-secondary text-sm mb-4">+ <span><%= t(".description") %></span>+ <%= render DS::Disclosure.new(variant: :inline) do |disclosure| %>+ <% disclosure.with_summary_content do %>+ <span class="font-medium text-secondary underline"><%= t(".show_details") %></span>+ <% end %>+ <ol class="text-sm text-secondary mt-2 list-decimal ml-6 space-y-2">+ <li><%= t(".step_1_html") %></li>+ <li><%= t(".step_2") %></li>+ </ol>+ <% end %>+ </div>+ <% end %>+ </div>++ <%= styled_form_with model: Setting.new,+ url: settings_hosting_path,+ method: :patch,+ data: {+ controller: "auto-submit-form",+ "auto-submit-form-trigger-event-value": "blur"+ } do |form| %>+ <% has_key = ENV["MANSA_API_KEY"].present? || Setting.mansa_api_key.present? %>+ <%= form.text_field :mansa_api_key,+ label: t(".label"),+ type: "password",+ placeholder: t(".placeholder"),+ value: has_key ? "********" : "",+ disabled: ENV["MANSA_API_KEY"].present?,+ data: { "auto-submit-form-target": "auto" } %>+ <% end %>++ <%= render DS::Alert.new(message: t(".rate_limit_warning"), variant: :warning) %>+</div>diff --git a/app/views/settings/hostings/_provider_selection.html.erb b/app/views/settings/hostings/_provider_selection.html.erbindex 0c5c4476cc..b1cf9210ec 100644--- a/app/views/settings/hostings/_provider_selection.html.erb+++ b/app/views/settings/hostings/_provider_selection.html.erb@@ -55,6 +55,7 @@["binance_public", t(".providers.binance_public"), t(".binance_public_hint")],["moex_public", t(".providers.moex_public"), t(".moex_public_hint")],["tinkoff_invest", t(".providers.tinkoff_invest"), t(".tinkoff_invest_hint")],+ ["mansa", t(".providers.mansa"), t(".requires_api_key_mansa")],].each do |value, label, hint| %><label class="flex items-center gap-2 cursor-pointer"><input type="checkbox"diff --git a/app/views/settings/hostings/show.html.erb b/app/views/settings/hostings/show.html.erbindex 44970a9afa..e230197b69 100644--- a/app/views/settings/hostings/show.html.erb+++ b/app/views/settings/hostings/show.html.erb@@ -39,6 +39,9 @@<% if @show_tinkoff_invest_settings %><%= render "settings/hostings/tinkoff_invest_settings" %><% end %>+ <% if @show_mansa_settings %>+ <%= render "settings/hostings/mansa_settings" %>+ <% end %></div><% end %><%= settings_section title: t(".property_valuation_providers") do %>diff --git a/config/locales/views/securities/en.yml b/config/locales/views/securities/en.ymlindex 5ff0f5d6d2..e37eb37a57 100644--- a/config/locales/views/securities/en.yml+++ b/config/locales/views/securities/en.yml@@ -13,3 +13,4 @@ en:mfapi: MFAPI.inbinance_public: Binancemoex_public: MOEX+ mansa: Mansadiff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.ymlindex bb65badd36..fb81421752 100644--- a/config/locales/views/settings/hostings/en.yml+++ b/config/locales/views/settings/hostings/en.yml@@ -47,6 +47,7 @@ en:binance_public_hint: free, no API key -- crypto only (BTC, ETH, etc.)moex_public_hint: free, no API key -- Russian stocks, funds & bonds (MOEX), incl. RUB FXtinkoff_invest_hint: requires read-only token -- Russian stocks/funds/bonds prices + brand logos+ requires_api_key_mansa: requires API key, 100 calls/day free tier -- NGX (Nigerian Exchange) onlyproviders:twelve_data: Twelve Datayahoo_finance: Yahoo Finance@@ -58,6 +59,7 @@ en:moex_public: MOEXtinkoff_invest: T-Invest (T-Bank)frankfurter: Frankfurter+ mansa: Mansaassistant_settings:title: AI Assistantdescription: Choose how the chat assistant responds. Builtin uses your configured LLM provider directly. External delegates to a remote AI agent that can call back to Sure's financial tools via MCP.@@ -207,6 +209,16 @@ en:step_2_html: 'Go to your <a href="https://eodhd.com/cp/dashboard" target="_blank" rel="noopener noreferrer" class="underline">Dashboard</a> to find your API token.'step_3: Copy your API token and paste it below.rate_limit_warning: "EODHD free tier is limited to 20 API calls per day. Best used as a supplementary provider for EU ETFs not available from other providers."+ mansa_settings:+ title: Mansa+ description: Enter the API key from Mansa API. Supports NGX (Nigerian Exchange), not covered by any other provider here. Mansa covers other African exchanges too, but only NGX is verified against this integration.+ env_configured_message: Successfully configured through the MANSA_API_KEY environment variable.+ label: API Key+ placeholder: Enter your Mansa API key here+ show_details: "(show details)"+ step_1_html: 'Visit <a href="https://mansaapi.com" target="_blank" rel="noopener noreferrer" class="underline">mansaapi.com</a> and claim your free API key -- no card required.'+ step_2: Copy your API key and paste it below.+ rate_limit_warning: "Mansa's free tier is limited to 100 API calls per day, and only exposes current quotes -- historical prices require a paid plan. Only NGX (Nigerian Exchange) is verified against this integration; other African exchanges Mansa covers are not yet supported here."alpha_vantage_settings:title: Alpha Vantagedescription: Enter the API key from Alpha Vantage. Supports EU ETFs on London Stock Exchange, XETRA, and other exchanges.diff --git a/test/models/provider/mansa_test.rb b/test/models/provider/mansa_test.rbnew file mode 100644index 0000000000..94cf785737--- /dev/null+++ b/test/models/provider/mansa_test.rb@@ -0,0 +1,246 @@+require "test_helper"++class Provider::MansaTest < ActiveSupport::TestCase+ setup do+ @provider = Provider::Mansa.new("test_api_key")+ @provider.stubs(:enforce_daily_limit!)+ @provider.stubs(:throttle_request)+ end++ # Fixture bodies below are copies of real responses captured against the+ # live API (2026-09-17), not guessed — see Provider::Mansa's class comment+ # for why that matters here specifically.++ test "search_securities maps fields from a real NGX response" do+ body = {+ success: true,+ data: [+ {+ ticker: "MTNN",+ name: "MTN Nigeria Communications Plc",+ exchange: "NGX",+ exchange_code: "NIGERIA",+ currency: "NGN",+ sector: "ICT",+ price: 815,+ change: 0,+ change_pct: 0,+ volume: 1696945,+ last_updated: "2026-09-17T16:25:50.197+00:00"+ }+ ],+ meta: { query: "MTN", count: 1, source: "mansa_api" }+ }.to_json++ mock_response = mock+ mock_response.stubs(:body).returns(body)+ @provider.stubs(:client).returns(mock_client = mock)+ mock_client.stubs(:get).returns(mock_response)++ result = @provider.search_securities("MTN", exchange_operating_mic: "XNSA")++ assert result.success?+ security = result.data.first+ assert_equal "MTNN", security.symbol+ # Real field is `name`, not `company_name` — the first draft of this+ # provider guessed `company_name` from the docs alone and got it wrong.+ assert_equal "MTN Nigeria Communications Plc", security.name+ assert_equal "XNSA", security.exchange_operating_mic+ assert_equal "NGN", security.currency+ end++ test "search_securities always scopes to NGX even with no MIC given, matching the real controller call" do+ # Sure's actual trade-form combobox never passes exchange_operating_mic on+ # search (see app/views/trades/_form.html.erb) — this test calls the+ # provider exactly that way, which the original PR's only search test+ # didn't (it passed exchange_operating_mic: "XNSA" explicitly and so+ # never exercised the real controller -> provider path).+ body = {+ success: true,+ data: [+ { ticker: "MTNN", name: "MTN Nigeria Communications Plc", exchange: "NGX", currency: "NGN" }+ ]+ }.to_json++ mock_response = mock+ mock_response.stubs(:body).returns(body)+ fake_request = Struct.new(:params).new({})+ @provider.stubs(:client).returns(mock_client = mock)+ mock_client.expects(:get).yields(fake_request).returns(mock_response)++ result = @provider.search_securities("MTNN")++ assert result.success?+ # The actual bug: without this, an unscoped search could return matches+ # from other African exchanges this adapter has no verified MIC for.+ assert_equal "NGX", fake_request.params["exchange"]+ assert_equal "XNSA", result.data.first.exchange_operating_mic+ end++ test "search_securities returns nothing for an explicit MIC Mansa doesn't cover, rather than guessing NGX" do+ # A blank MIC (no data to go on) falls back to NGX — but an explicit,+ # present MIC we can't map (e.g. a caller checking a NYSE-listed security+ # while Mansa happens to be enabled) must not silently search NGX and+ # return unrelated results.+ @provider.stubs(:client).returns(mock_client = mock)+ mock_client.expects(:get).never++ result = @provider.search_securities("AAPL", exchange_operating_mic: "XNYS")++ assert result.success?+ assert_equal [], result.data+ end++ test "search_securities drops a result on an exchange this adapter can't map to a real MIC" do+ # Defensive: even though the request above always explicitly scopes to a+ # single exchange, this proves a stray result from an unmapped exchange+ # (e.g. Mansa's search broadening the filter) never gets saved with+ # Mansa's own exchange code standing in for a real ISO MIC.+ body = {+ success: true,+ data: [+ { ticker: "SOMETICKER", name: "Some Johannesburg Company", exchange: "JSE", currency: "ZAR" }+ ]+ }.to_json++ mock_response = mock+ mock_response.stubs(:body).returns(body)+ @provider.stubs(:client).returns(mock_client = mock)+ mock_client.stubs(:get).returns(mock_response)++ result = @provider.search_securities("Some Johannesburg Company", exchange_operating_mic: "XNSA")++ assert result.success?+ assert_equal [], result.data+ end++ test "fetch_security_price rejects an explicit MIC Mansa doesn't cover, rather than mislabeling an NGX quote" do+ # The actual bug this guards: without this check, a present-but-unmapped+ # MIC would silently fetch NGX's quote and let the caller stamp it with+ # whatever exchange was actually asked for — a real, wrong security price+ # under someone else's exchange label.+ @provider.stubs(:client).returns(mock_client = mock)+ mock_client.expects(:get).never++ result = @provider.fetch_security_price(symbol: "AAPL", exchange_operating_mic: "XNYS", date: Date.current)++ assert_not result.success?+ assert_instance_of Provider::Mansa::Error, result.error+ assert_match(/does not support exchange XNYS/, result.error.message)+ end++ test "fetch_security_price reads currency from meta, not data" do+ body = {+ success: true,+ data: {+ ticker: "MTNN",+ name: "MTN Nigeria Communications Plc",+ price: 815,+ change: 0,+ change_pct: 0,+ volume: 1696945,+ market_cap: 15914634558074,+ shares_outstanding: 20995560103,+ sector: "ICT",+ logo_url: nil,+ last_updated: "2026-09-17T16:25:50.197+00:00"+ # Note: no "currency" key here on purpose — see meta below.+ },+ meta: {+ exchange: "NGX",+ currency: "NGN",+ price_unit: "major",+ updated_at: "2026-09-17T16:25:50.197+00:00",+ data_freshness: "30_minutes",+ source: "mansa_api"+ }+ }.to_json++ mock_response = mock+ mock_response.stubs(:body).returns(body)+ @provider.stubs(:client).returns(mock_client = mock)+ mock_client.stubs(:get).returns(mock_response)++ result = @provider.fetch_security_price(symbol: "MTNN", exchange_operating_mic: "XNSA", date: Date.current)++ assert result.success?+ price = result.data+ assert_equal 815, price.price+ # This is the actual bug the first draft had: reading `data.currency`+ # (which doesn't exist on this endpoint) instead of `meta.currency`.+ assert_equal "NGN", price.currency+ assert_equal "XNSA", price.exchange_operating_mic+ end++ test "fetch_security_price rejects a non-today date (free tier has no historical endpoint)" do+ result = @provider.fetch_security_price(symbol: "MTNN", exchange_operating_mic: "XNSA", date: 5.days.ago.to_date)++ assert_not result.success?+ # Only RateLimitError survives with_provider_response's default error+ # transformer as its own subclass (see Provider::RateLimitable) — every+ # other raised error, including this one, normalizes to the base Error+ # class with its message preserved. Consistent with every other provider+ # in this codebase, not a Mansa-specific gap.+ assert_instance_of Provider::Mansa::Error, result.error+ assert_match(/free tier only exposes the current quote/, result.error.message)+ end++ test "fetch_security_prices raises clearly for a range that doesn't include today" do+ result = @provider.fetch_security_prices(+ symbol: "MTNN",+ exchange_operating_mic: "XNSA",+ start_date: 10.days.ago.to_date,+ end_date: 5.days.ago.to_date+ )++ assert_not result.success?+ assert_match(/Pro plan required/, result.error.message)+ end++ test "fetch_security_prices returns today's quote as a best-effort single row when range includes today" do+ body = {+ success: true,+ data: { ticker: "MTNN", name: "MTN Nigeria Communications Plc", price: 815 },+ meta: { exchange: "NGX", currency: "NGN" }+ }.to_json++ mock_response = mock+ mock_response.stubs(:body).returns(body)+ @provider.stubs(:client).returns(mock_client = mock)+ mock_client.stubs(:get).returns(mock_response)++ result = @provider.fetch_security_prices(+ symbol: "MTNN",+ exchange_operating_mic: "XNSA",+ start_date: 5.days.ago.to_date,+ end_date: Date.current+ )++ assert result.success?+ assert_equal 1, result.data.length+ assert_equal Date.current, result.data.first.date+ end++ test "check_api_error! extracts the nested error message, not a raw hash dump" do+ body = {+ success: false,+ error: {+ code: "NOT_FOUND",+ message: "Ticker 'NOTAREALTICKER' not found on NGX.",+ hint: "Check the ticker against GET /api/v1/markets/exchanges/NGX/stocks",+ docs: "https://mansaapi.com/docs/markets"+ }+ }.to_json++ error = assert_raises(Provider::Mansa::Error) do+ @provider.send(:check_api_error!, JSON.parse(body))+ end++ # The first draft interpolated the whole error hash into the message+ # (`#{parsed["error"]}` where "error" is itself a Hash) instead of+ # pulling out just the message string.+ assert_match(/Ticker 'NOTAREALTICKER' not found on NGX\./, error.message)+ assert_match(/NOT_FOUND/, error.message)+ assert_no_match(/=>/, error.message) # would appear in a raw Hash#to_s dump+ end+end