Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Add TerraScoutX as a property valuation provider (#3969)

Saqib Khan97f7cd842bfa
diff --git a/app/controllers/settings/hostings_controller.rb b/app/controllers/settings/hostings_controller.rb
index 34057ed1f3..53555d95f2 100644
--- a/app/controllers/settings/hostings_controller.rb
+++ b/app/controllers/settings/hostings_controller.rb
@@ -60,6 +60,7 @@ class Settings::HostingsController < ApplicationController
@rentcast_usage = Provider::Registry.get_provider(:rentcast)&.usage
@realie_usage = Provider::Registry.get_provider(:realie)&.usage
@chimnie_usage = Provider::Registry.get_provider(:chimnie)&.usage
+ @terrascoutx_usage = Provider::Registry.get_provider(:terrascoutx)&.usage
load_external_assistant_models
end
@@ -155,6 +156,7 @@ class Settings::HostingsController < ApplicationController
update_encrypted_setting(:rentcast_api_key)
update_encrypted_setting(:realie_api_key)
update_encrypted_setting(:chimnie_api_key)
+ update_encrypted_setting(:terrascoutx_api_key)
if hosting_params.key?(:syncs_include_pending)
Setting.syncs_include_pending = hosting_params[:syncs_include_pending] == "1"
@@ -366,7 +368,7 @@ class Settings::HostingsController < ApplicationController
# Strong parameters for the self-hosting settings form.
def hosting_params
return ActionController::Parameters.new unless params.key?(:setting)
- params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :demo_family_refresh_enabled, :demo_family_refresh_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, :chimnie_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :ai_health_probe_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :market_data_sync_enabled, :market_data_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])
+ params.require(:setting).permit(:onboarding_state, :require_email_confirmation, :invite_only_default_family_id, :demo_family_refresh_enabled, :demo_family_refresh_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, :chimnie_api_key, :terrascoutx_api_key, :openai_access_token, :openai_uri_base, :openai_model, :openai_json_mode, :anthropic_access_token, :anthropic_base_url, :anthropic_model, :jev_api_key, :jev_endpoint, :jev_model, :llm_provider, :llm_context_window, :llm_max_response_tokens, :llm_max_items_per_call, :openai_request_timeout, :ai_response_timeout, :ai_health_probe_timeout, :exchange_rate_provider, :securities_provider, :syncs_include_pending, :auto_sync_enabled, :auto_sync_time, :market_data_sync_enabled, :market_data_sync_time, :external_assistant_url, :external_assistant_token, :external_assistant_model, securities_providers: [])
end
def load_external_assistant_models
diff --git a/app/models/provider/registry.rb b/app/models/provider/registry.rb
index 48926becc8..f69758d4d6 100644
--- a/app/models/provider/registry.rb
+++ b/app/models/provider/registry.rb
@@ -203,6 +203,14 @@ class Provider::Registry
Provider::Chimnie.new(api_key)
end
+
+ def terrascoutx
+ api_key = ENV["TERRASCOUTX_API_KEY"].presence || Setting.terrascoutx_api_key # pipelock:ignore
+
+ return nil unless api_key.present?
+
+ Provider::Terrascoutx.new(api_key)
+ end
end
def initialize(concept)
@@ -245,7 +253,7 @@ class Provider::Registry
# builds them by name when benchmarking against Jev.
%i[jev]
when :property_valuations
- %i[rentcast realie chimnie]
+ %i[rentcast realie chimnie terrascoutx]
else
%i[plaid_us plaid_eu github openai anthropic]
end
diff --git a/app/models/provider/terrascoutx.rb b/app/models/provider/terrascoutx.rb
new file mode 100644
index 0000000000..3ab23b932b
--- /dev/null
+++ b/app/models/provider/terrascoutx.rb
@@ -0,0 +1,121 @@
+class Provider::Terrascoutx < Provider
+ include PropertyValuationConcept, RateLimitable
+ extend SslConfigurable
+
+ # Subclass so errors caught in this provider are raised as Provider::Terrascoutx::Error
+ Error = Class.new(Provider::Error)
+ RateLimitError = Class.new(Error)
+
+ # Minimum delay between requests to avoid rate limiting (in seconds)
+ MIN_REQUEST_INTERVAL = 1.0
+
+ # Maximum API requests per month (TerraScoutX free tier limit).
+ # Override with TERRASCOUTX_MAX_REQUESTS_PER_MONTH for paid plans.
+ MAX_REQUESTS_PER_MONTH = 2000
+
+ def initialize(api_key)
+ @api_key = api_key # pipelock:ignore
+ end
+
+ # The address search returns full property records, best match first, so
+ # a single request is enough. The value is the county assessor's roll
+ # value (market value, else total appraised), not an automated estimate.
+ def fetch_property_valuation(line1:, locality: nil, region: nil, postal_code: nil)
+ with_provider_response do
+ throttle_request
+ record_monthly_request!
+
+ state = region.to_s.strip.upcase
+ response = client.get("#{base_url}/v1/suggest") do |req|
+ req.params["q"] = [ line1, locality, region, postal_code ].map { |part| part.to_s.strip }.reject(&:empty?).join(", ")
+ req.params["limit"] = 5
+ req.params["state"] = state if state.match?(/\A[A-Z]{2}\z/)
+ end
+
+ records = JSON.parse(response.body)["results"].to_a
+ raise Error.new(I18n.t("providers.terrascoutx.errors.no_property")) if records.empty?
+
+ record = records.find { |candidate| location_match?(candidate, line1: line1, postal_code: postal_code) }
+ raise Error.new(I18n.t("providers.terrascoutx.errors.location_mismatch")) if record.nil?
+
+ valuation = record.values_at("marketValue", "totalAppraised").find { |value| value.to_d.positive? }
+ raise Error.new(I18n.t("providers.terrascoutx.errors.no_valuation")) if valuation.nil?
+
+ PropertyValuation.new(
+ valuation: BigDecimal(valuation.to_s),
+ currency: "USD",
+ property_type: subtype_for_land_use(record["landUse"]),
+ year_built: record["yearBuilt"],
+ area_value: record["livingAreaSqft"],
+ area_unit: "sqft"
+ )
+ end
+ end
+
+ private
+ attr_reader :api_key
+
+ # The search is fuzzy, so a near miss (a neighbouring house number, the
+ # same street in another ZIP) must not be taken as the user's property.
+ # The city isn't compared: county rolls often record the municipality
+ # rather than the mailing city.
+ # Both identifiers must be present and agree. A record that omits its
+ # house number or ZIP cannot be checked, so it is refused.
+ def location_match?(record, line1:, postal_code:)
+ address = record["address"] || {}
+ returned_house, entered_house = house_number(address["street"]), house_number(line1)
+ returned_zip, entered_zip = zip_code(address["zip"]), zip_code(postal_code)
+ returned_house.present? && returned_house == entered_house &&
+ returned_zip.present? && returned_zip == entered_zip
+ end
+
+ def house_number(street)
+ street.to_s[/\A\s*(\d+)/, 1]
+ end
+
+ # Five digits, optionally followed by a ZIP+4 extension.
+ def zip_code(value)
+ value.to_s.strip[/\A(\d{5})(?:-\d{4})?\z/, 1]
+ end
+
+ # Land use is the county's own description, so it is matched on keywords.
+ # Unmatched descriptions leave the subtype unset rather than guessing.
+ def subtype_for_land_use(land_use)
+ case land_use.to_s.downcase
+ when /condo/ then "condominium"
+ when /town.?(house|home)/ then "townhouse"
+ when /single.?family|sfr/ then "single_family_home"
+ when /multi.?family|duplex|triplex|fourplex/ then "multi_family_home"
+ when /apartment/ then "apartment"
+ when /agricultur|farm|ranch/ then "agri_land"
+ when /commercial|retail|office|industrial/ then "commercial"
+ when /vacant|\bland\b|\blots?\b/ then "plot"
+ end
+ end
+
+ def base_url
+ url = ENV["TERRASCOUTX_URL"].presence || "https://api.terrascoutx.com"
+ raise Error.new(I18n.t("providers.terrascoutx.errors.insecure_url")) unless url.start_with?("https://")
+ url
+ end
+
+ def client
+ @client ||= Faraday.new(url: base_url, ssl: self.class.faraday_ssl_options) do |faraday|
+ # Retry transient connection failures so a network blip doesn't burn
+ # one of the monthly budget's requests
+ 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.options.timeout = 10
+ faraday.options.open_timeout = 5
+ faraday.headers["X-Api-Key"] = api_key
+ faraday.headers["Accept"] = "application/json"
+ end
+ end
+end
diff --git a/app/models/setting.rb b/app/models/setting.rb
index 58d4dc11e0..d957be4c8a 100644
--- a/app/models/setting.rb
+++ b/app/models/setting.rb
@@ -117,6 +117,7 @@ class Setting < RailsSettings::Base
field :rentcast_api_key, type: :string, default: ENV["RENTCAST_API_KEY"]
field :realie_api_key, type: :string, default: ENV["REALIE_API_KEY"]
field :chimnie_api_key, type: :string, default: ENV["CHIMNIE_API_KEY"]
+ field :terrascoutx_api_key, type: :string, default: ENV["TERRASCOUTX_API_KEY"]
# Transparent encryption for API key fields. The `field` macro defines the
# raw getter/setter on the class. By prepending this module we intercept
@@ -136,6 +137,7 @@ class Setting < RailsSettings::Base
rentcast_api_key
realie_api_key
chimnie_api_key
+ terrascoutx_api_key
openai_access_token
anthropic_access_token
jev_api_key
diff --git a/app/views/properties/_avm_form.html.erb b/app/views/properties/_avm_form.html.erb
index ec0a5e72d5..ab86d4b707 100644
--- a/app/views/properties/_avm_form.html.erb
+++ b/app/views/properties/_avm_form.html.erb
@@ -11,7 +11,7 @@
<div class="flex flex-col gap-2 min-h-80">
<%= render "properties/form_alert", notice: nil, error: @error_message %>
- <p class="text-sm text-secondary"><%= t("properties.new.avm_description", provider: provider_name) %></p>
+ <p class="text-sm text-secondary"><%= t("properties.new.avm_descriptions.#{provider_key}", provider: provider_name, default: t("properties.new.avm_description", provider: provider_name)) %></p>
<%= hidden_field_tag :avm_provider, provider_key %>
<%= form.hidden_field :accountable_type, value: "Property" %>
diff --git a/app/views/properties/_avm_preview.html.erb b/app/views/properties/_avm_preview.html.erb
index 6580b85a74..bd7d4c3dc7 100644
--- a/app/views/properties/_avm_preview.html.erb
+++ b/app/views/properties/_avm_preview.html.erb
@@ -59,6 +59,11 @@
</dl>
<% end %>
+ <% roll_note = t("properties.new.avm_roll_value_notes.#{provider_key}", provider: provider_name, default: "") %>
+ <% if roll_note.present? %>
+ <p class="text-sm text-secondary"><%= roll_note %></p>
+ <% end %>
+
<% if no_property_record && preview.external_id.blank? %>
<p class="text-sm text-secondary"><%= t("properties.new.avm_preview_no_record", provider: provider_name) %></p>
<% end %>
diff --git a/app/views/settings/hostings/_terrascoutx_settings.html.erb b/app/views/settings/hostings/_terrascoutx_settings.html.erb
new file mode 100644
index 0000000000..94d2c7857f
--- /dev/null
+++ b/app/views/settings/hostings/_terrascoutx_settings.html.erb
@@ -0,0 +1,30 @@
+<div class="space-y-4">
+ <div>
+ <h2 class="font-medium mb-1"><%= t(".title") %></h2>
+ <% if ENV["TERRASCOUTX_API_KEY"].present? %>
+ <p class="text-sm text-secondary"><%= t(".env_configured_message") %></p>
+ <% else %>
+ <p class="text-secondary text-sm mb-4"><%= t(".description") %></p>
+ <% end %>
+ <% if @terrascoutx_usage&.success? %>
+ <p class="text-sm text-secondary"><%= t(".usage", used: @terrascoutx_usage.data.used, limit: @terrascoutx_usage.data.limit) %></p>
+ <% 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["TERRASCOUTX_API_KEY"].present? || Setting.terrascoutx_api_key.present? %>
+ <%= form.text_field :terrascoutx_api_key,
+ label: t(".label"),
+ type: "password",
+ placeholder: t(".placeholder"),
+ value: has_key ? "********" : "",
+ disabled: ENV["TERRASCOUTX_API_KEY"].present?,
+ data: { "auto-submit-form-target": "auto" } %>
+ <% end %>
+</div>
diff --git a/app/views/settings/hostings/show.html.erb b/app/views/settings/hostings/show.html.erb
index 5def17e48b..1f7dc3cf36 100644
--- a/app/views/settings/hostings/show.html.erb
+++ b/app/views/settings/hostings/show.html.erb
@@ -73,6 +73,7 @@
<%= render "settings/hostings/rentcast_settings" %>
<%= render "settings/hostings/realie_settings" %>
<%= render "settings/hostings/chimnie_settings" %>
+ <%= render "settings/hostings/terrascoutx_settings" %>
</div>
<% end %>
<%= settings_section title: t(".sync_settings") do %>
diff --git a/config/locales/models/provider/en.yml b/config/locales/models/provider/en.yml
index cfef811bd3..448f04f61b 100644
--- a/config/locales/models/provider/en.yml
+++ b/config/locales/models/provider/en.yml
@@ -27,3 +27,9 @@ en:
unsupported_property: Chimnie only values residential properties; this UPRN belongs to a commercial or mixed-use property.
unauthorized: Chimnie rejected the API key. Check the key in Settings → Self-Hosting.
insufficient_balance: Your Chimnie account balance is too low for this request.
+ terrascoutx:
+ errors:
+ no_property: TerraScoutX could not find a property matching this address.
+ no_valuation: TerraScoutX did not return a value for this property.
+ location_mismatch: TerraScoutX matched a property with a different house number or ZIP code. Please double-check the address.
+ insecure_url: TERRASCOUTX_URL must use https://.
diff --git a/config/locales/views/properties/en.yml b/config/locales/views/properties/en.yml
index 132b5f1912..23c8dd50be 100644
--- a/config/locales/views/properties/en.yml
+++ b/config/locales/views/properties/en.yml
@@ -26,6 +26,7 @@ en:
rentcast: RentCast
realie: Realie
chimnie: Chimnie
+ terrascoutx: TerraScoutX
new:
title: Enter property manually
next: "Next"
@@ -43,6 +44,10 @@ en:
avm_submit: "Look up property"
avm_preview_title: "Confirm property details"
avm_preview_description: "Here's what %{provider} found. Review the details before adding the property — nothing has been created yet."
+ avm_descriptions:
+ terrascoutx: "Enter a name for the property and its address. %{provider} will look up the property details and the county's assessed value from its latest tax roll. That is not a current market estimate."
+ avm_roll_value_notes:
+ terrascoutx: "%{provider} reports the county's assessed value from its latest tax roll. It is not a current market estimate, so it can differ from what the property would sell for."
avm_preview_no_record: "%{provider} couldn't find a property record at this address, so the value shown is an estimate based on the surrounding area. Double-check the address before continuing."
avm_preview_back: "Back"
avm_preview_uprn: "UPRN"
diff --git a/config/locales/views/settings/hostings/en.yml b/config/locales/views/settings/hostings/en.yml
index 112e3b3276..f00fe3933e 100644
--- a/config/locales/views/settings/hostings/en.yml
+++ b/config/locales/views/settings/hostings/en.yml
@@ -252,6 +252,12 @@ en:
env_configured_message: Successfully configured through the CHIMNIE_API_KEY environment variable.
label: API Key
placeholder: Enter your Chimnie API key here
+ terrascoutx_settings:
+ title: TerraScoutX
+ description: Enter your TerraScoutX API key to look up US property details and values when adding a property. The value is the county assessor's appraised value from the latest tax roll TerraScoutX holds, not an automated market estimate, so it lags the market and can sit well below it in states that cap assessments, such as California. Coverage varies by county. Keys are free and limited to 2,000 API requests per month, shared between property lookups and daily valuation refreshes. If your key allows more, raise the cap with the TERRASCOUTX_MAX_REQUESTS_PER_MONTH environment variable.
+ env_configured_message: Successfully configured through the TERRASCOUTX_API_KEY environment variable.
+ label: API Key
+ placeholder: Enter your TerraScoutX API key here
usage: "%{used} of %{limit} monthly requests used"
tiingo_settings:
title: Tiingo
diff --git a/db/migrate/20261012100000_add_terrascoutx_to_avm_provider_check.rb b/db/migrate/20261012100000_add_terrascoutx_to_avm_provider_check.rb
new file mode 100644
index 0000000000..4c71ecb4de
--- /dev/null
+++ b/db/migrate/20261012100000_add_terrascoutx_to_avm_provider_check.rb
@@ -0,0 +1,22 @@
+class AddTerrascoutxToAvmProviderCheck < ActiveRecord::Migration[8.1]
+ def up
+ remove_check_constraint :properties, name: "properties_avm_provider_check"
+ add_check_constraint :properties,
+ "avm_provider IS NULL OR avm_provider IN ('rentcast', 'realie', 'chimnie', 'terrascoutx')",
+ name: "properties_avm_provider_check"
+ end
+
+ # The restored constraint would reject any property already set to 'terrascoutx', so rollback stops while one exists.
+ # Clear those values first (set avm_provider to NULL; the valuation itself is kept elsewhere). The scan is a full
+ # pass over properties, since avm_provider has no index.
+ def down
+ if select_value("SELECT 1 FROM properties WHERE avm_provider = 'terrascoutx' LIMIT 1")
+ raise ActiveRecord::MigrationError, "properties still have avm_provider = 'terrascoutx'; set them to NULL before rolling back"
+ end
+
+ remove_check_constraint :properties, name: "properties_avm_provider_check"
+ add_check_constraint :properties,
+ "avm_provider IS NULL OR avm_provider IN ('rentcast', 'realie', 'chimnie')",
+ name: "properties_avm_provider_check"
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index e8253560e0..d79998ad64 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -2007,7 +2007,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_16_120000) do
t.datetime "updated_at", null: false
t.integer "year_built"
t.index ["avm_last_synced_on"], name: "index_properties_on_avm_provider_sync", order: "NULLS FIRST", where: "(avm_provider IS NOT NULL)"
- t.check_constraint "avm_provider IS NULL OR (avm_provider::text = ANY (ARRAY['rentcast'::character varying, 'realie'::character varying, 'chimnie'::character varying]::text[]))", name: "properties_avm_provider_check"
+ t.check_constraint "avm_provider IS NULL OR (avm_provider::text = ANY (ARRAY['rentcast'::character varying, 'realie'::character varying, 'chimnie'::character varying, 'terrascoutx'::character varying]::text[]))", name: "properties_avm_provider_check"
end
create_table "provider_request_counts", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
diff --git a/test/controllers/properties_controller_test.rb b/test/controllers/properties_controller_test.rb
index 092827f411..f9571282de 100644
--- a/test/controllers/properties_controller_test.rb
+++ b/test/controllers/properties_controller_test.rb
@@ -324,6 +324,7 @@ class PropertiesControllerTest < ActionDispatch::IntegrationTest
test "new skips method selector when no AVM provider is configured" do
Provider::Registry.stubs(:rentcast).returns(nil)
Provider::Registry.stubs(:realie).returns(nil)
+ Provider::Registry.stubs(:terrascoutx).returns(nil)
get new_property_path(step: "method_select")
diff --git a/test/controllers/settings/hostings_controller_test.rb b/test/controllers/settings/hostings_controller_test.rb
index 32875066d0..af1a93f672 100644
--- a/test/controllers/settings/hostings_controller_test.rb
+++ b/test/controllers/settings/hostings_controller_test.rb
@@ -19,6 +19,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
Provider::Registry.stubs(:get_provider).with(:rentcast).returns(nil)
Provider::Registry.stubs(:get_provider).with(:realie).returns(nil)
Provider::Registry.stubs(:get_provider).with(:chimnie).returns(nil)
+ Provider::Registry.stubs(:get_provider).with(:terrascoutx).returns(nil)
@provider.stubs(:usage).returns(provider_success_response(
OpenStruct.new(
used: 10,
@@ -32,7 +33,7 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
teardown do
# These tests persist global Setting.* values; reset them so state can't
# leak into later (order-dependent) tests.
- %i[anthropic_access_token anthropic_base_url anthropic_model jev_api_key jev_endpoint jev_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout ai_health_probe_timeout external_assistant_url external_assistant_token external_assistant_model external_assistant_agent_id rentcast_api_key realie_api_key chimnie_api_key demo_family_refresh_enabled demo_family_refresh_family_id
+ %i[anthropic_access_token anthropic_base_url anthropic_model jev_api_key jev_endpoint jev_model llm_provider twelve_data_api_key openai_access_token openai_request_timeout ai_response_timeout ai_health_probe_timeout external_assistant_url external_assistant_token external_assistant_model external_assistant_agent_id rentcast_api_key realie_api_key chimnie_api_key terrascoutx_api_key demo_family_refresh_enabled demo_family_refresh_family_id
market_data_sync_enabled market_data_sync_time market_data_sync_timezone].each do |key|
Setting.public_send("#{key}=", nil)
end
@@ -326,6 +327,14 @@ class Settings::HostingsControllerTest < ActionDispatch::IntegrationTest
end
end
+ test "can update terrascoutx api key when self hosting is enabled" do
+ with_self_hosting do
+ patch settings_hosting_url, params: { setting: { terrascoutx_api_key: "terrascoutx-token" } }
+
+ assert_equal "terrascoutx-token", Setting.terrascoutx_api_key
+ end
+ end
+
test "shows Yahoo Finance rate limiting as a warning" do
@provider.stubs(:health_status).returns(:rate_limited)
diff --git a/test/models/provider/terrascoutx_test.rb b/test/models/provider/terrascoutx_test.rb
new file mode 100644
index 0000000000..4d42b5749c
--- /dev/null
+++ b/test/models/provider/terrascoutx_test.rb
@@ -0,0 +1,201 @@
+require "test_helper"
+
+class Provider::TerrascoutxTest < ActiveSupport::TestCase
+ setup do
+ @provider = Provider::Terrascoutx.new("test_api_key")
+ @provider.stubs(:throttle_request)
+ end
+
+ # Recorded from the live API for 1000 Main St, Houston (Harris County
+ # parcel 0011390000002), trimmed to its address, value and building fields.
+ def property_record(overrides = {})
+ {
+ "id" => "hcad-0011390000002",
+ "address" => { "street" => "1000 Main St", "city" => "Houston", "state" => "TX", "zip" => "77002", "county" => "Harris" },
+ "parcelId" => "0011390000002",
+ "landUse" => "Commercial",
+ "landUseCode" => "F1",
+ "livingAreaSqft" => 1_181_384,
+ "yearBuilt" => 2001,
+ "totalAppraised" => 190_756_291,
+ "marketValue" => 190_756_291
+ }.merge(overrides)
+ end
+
+ def suggest_body(*records)
+ { "results" => records }.to_json
+ end
+
+ def fetch_main_st
+ @provider.fetch_property_valuation(line1: "1000 Main St", locality: "Houston", region: "TX", postal_code: "77002")
+ end
+
+ test "fetches valuation and property attributes in a single request" do
+ stub = stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(
+ query: { "q" => "1000 Main St, Houston, TX, 77002", "limit" => "5", "state" => "TX" },
+ headers: { "X-Api-Key" => "test_api_key" }
+ )
+ .to_return(status: 200, body: suggest_body(property_record))
+
+ response = fetch_main_st
+
+ assert response.success?
+ data = response.data
+ assert_equal 190_756_291, data.valuation
+ assert_equal "USD", data.currency
+ assert_equal "commercial", data.property_type
+ assert_equal 2001, data.year_built
+ assert_equal 1_181_384, data.area_value
+ assert_equal "sqft", data.area_unit
+ assert_requested stub
+ end
+
+ test "treats a zero market value as absent and falls back to the total appraised value" do
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1000 Main St, Houston, TX, 77002"))
+ .to_return(status: 200, body: suggest_body(property_record("marketValue" => 0, "totalAppraised" => 180_000_000)))
+
+ response = fetch_main_st
+
+ assert response.success?
+ assert_equal 180_000_000, response.data.valuation
+ end
+
+ test "returns an error when the record carries no usable value" do
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1000 Main St, Houston, TX, 77002"))
+ .to_return(status: 200, body: suggest_body(property_record("marketValue" => nil, "totalAppraised" => 0)))
+
+ response = fetch_main_st
+
+ assert_not response.success?
+ assert_equal I18n.t("providers.terrascoutx.errors.no_valuation"), response.error.message
+ end
+
+ test "picks the candidate matching the entered house number and ZIP" do
+ neighbour = property_record("id" => "hcad-neighbour", "address" => { "street" => "1001 Main St", "zip" => "77002" }, "marketValue" => 5_000_000)
+ other_zip = property_record("id" => "mcad-other", "address" => { "street" => "1000 Main St", "zip" => "77301" }, "marketValue" => 250_000)
+
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1000 Main St, Houston, TX, 77002"))
+ .to_return(status: 200, body: suggest_body(neighbour, other_zip, property_record))
+
+ response = fetch_main_st
+
+ assert response.success?
+ assert_equal 190_756_291, response.data.valuation
+ end
+
+ test "rejects a match with a different house number or ZIP" do
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1000 Main St, Houston, TX, 77002"))
+ .to_return(status: 200, body: suggest_body(property_record("address" => { "street" => "1001 Main St", "zip" => "77002" })))
+
+ response = fetch_main_st
+
+ assert_not response.success?
+ assert_equal I18n.t("providers.terrascoutx.errors.location_mismatch"), response.error.message
+ end
+
+ test "refuses a record that omits its house number or ZIP, since the match cannot be checked" do
+ [
+ { "street" => "Main St", "zip" => "77002" },
+ { "street" => "1000 Main St" }
+ ].each do |address|
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1000 Main St, Houston, TX, 77002"))
+ .to_return(status: 200, body: suggest_body(property_record("address" => address)))
+
+ response = fetch_main_st
+
+ assert_not response.success?, address.inspect
+ assert_equal I18n.t("providers.terrascoutx.errors.location_mismatch"), response.error.message
+ end
+ end
+
+ test "refuses a lookup entered without a ZIP code" do
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1000 Main St, Houston, TX"))
+ .to_return(status: 200, body: suggest_body(property_record))
+
+ response = @provider.fetch_property_valuation(line1: "1000 Main St", locality: "Houston", region: "TX")
+
+ assert_not response.success?
+ assert_equal I18n.t("providers.terrascoutx.errors.location_mismatch"), response.error.message
+ end
+
+ test "accepts a ZIP+4 on the record when the five digits agree" do
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1000 Main St, Houston, TX, 77002"))
+ .to_return(status: 200, body: suggest_body(property_record("address" => { "street" => "1000 Main St", "zip" => "77002-1234" })))
+
+ assert fetch_main_st.success?
+ end
+
+ test "refuses a base URL that is not https, so the API key is never sent in cleartext" do
+ previous = ENV["TERRASCOUTX_URL"]
+ ENV["TERRASCOUTX_URL"] = "http://localhost:4010"
+ response = fetch_main_st
+
+ assert_not response.success?
+ assert_equal I18n.t("providers.terrascoutx.errors.insecure_url"), response.error.message
+ ensure
+ previous ? ENV["TERRASCOUTX_URL"] = previous : ENV.delete("TERRASCOUTX_URL")
+ end
+
+ test "returns a friendly error when no property matches the address" do
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1 Nowhere Ln"))
+ .to_return(status: 200, body: suggest_body)
+
+ response = @provider.fetch_property_valuation(line1: "1 Nowhere Ln")
+
+ assert_not response.success?
+ assert_match(/could not find a property/i, response.error.message)
+ end
+
+ test "maps land use descriptions to property subtypes" do
+ {
+ "Residential Single-Family" => "single_family_home",
+ "Residential Condominium" => "condominium",
+ "Townhome" => "townhouse",
+ "Duplex" => "multi_family_home",
+ "Apartments" => "apartment",
+ "Agricultural" => "agri_land",
+ "Commercial" => "commercial",
+ "Vacant Land" => "plot",
+ "Real Property" => nil
+ }.each do |land_use, expected|
+ actual = @provider.send(:subtype_for_land_use, land_use)
+ if expected.nil?
+ assert_nil actual, "expected #{land_use.inspect} to map to nil"
+ else
+ assert_equal expected, actual, "expected #{land_use.inspect} to map to #{expected.inspect}"
+ end
+ end
+ end
+
+ test "returns a rate limit error when the API reports its monthly limit" do
+ stub_request(:get, "https://api.terrascoutx.com/v1/suggest")
+ .with(query: hash_including("q" => "1000 Main St, Houston, TX, 77002"))
+ .to_return(status: 429, body: { "error" => "monthly_request_limit_exceeded", "limit" => 2000, "used" => 2000, "plan" => "free" }.to_json)
+
+ response = fetch_main_st
+
+ assert_not response.success?
+ assert_instance_of Provider::Terrascoutx::RateLimitError, response.error
+ end
+
+ test "stops issuing requests once the monthly limit is reached" do
+ ProviderRequestCount.create!(provider_key: "terrascoutx", period: ProviderRequestCount.current_period, count: Provider::Terrascoutx::MAX_REQUESTS_PER_MONTH)
+
+ assert_not @provider.requests_remaining?
+
+ response = fetch_main_st
+
+ assert_not response.success?
+ assert_instance_of Provider::Terrascoutx::RateLimitError, response.error
+ assert_not_requested :get, %r{api\.terrascoutx\.com}
+ end
+end
diff --git a/test/system/settings_test.rb b/test/system/settings_test.rb
index 7a28d08dbe..f47b2846f3 100644
--- a/test/system/settings_test.rb
+++ b/test/system/settings_test.rb
@@ -59,6 +59,7 @@ class SettingsTest < ApplicationSystemTestCase
Provider::Registry.stubs(:get_provider).with(:rentcast).returns(nil)
Provider::Registry.stubs(:get_provider).with(:realie).returns(nil)
Provider::Registry.stubs(:get_provider).with(:chimnie).returns(nil)
+ Provider::Registry.stubs(:get_provider).with(:terrascoutx).returns(nil)
Provider::Registry.stubs(:get_provider).with(:github).returns(stub(fetch_latest_release_notes: nil, fetch_release_notes: nil))
open_settings_from_sidebar
assert_selector "li", text: "Self-Hosting"